// eks: ]C1020571091900154237100
function identifyBarcode(barcode) {
    barcode_elements = {}; // returns the elements in the barcode, which can be accessed as barcode_elements[AI_code]

    var SI = null;
    var modifier = null;
    var debug_str = ""

    // if SI indicator ] is present, we cut it off and parse the SI
    if (barcode[0] == "]") {
        debug_str += "---- SI ----\n";
        SI_str = barcode.substring(0, 3);
        barcode = barcode.substring(3);

        SI = SI_table[SI_str[1]];

        debug_str += "SI: " + SI + "\n";

        // some barcode types have a modifier
        switch (SI) {
            case "Code 39":
                modifier = code39_opt[SI_str[2]];
                debug_str += "Modifier: " + code39_opt[SI_str[2]] + "\n";
                break;
            case "Code 128":
                modifier = code128_opt[SI_str[2]];
                debug_str += "Modifier: " + code128_opt[SI_str[2]] + "\n";
                break;
            case "Telepen":
                modifier = telepen_opt[SI_str[2]];
                debug_str += "Modifier: " + telepen_opt[SI_str[2]] + "\n";
                break;
        }
    }

    // at this point the 3-letter SI is cut off barcode, the variables "SI" and "modifier" should hold the SI-values

    if (!SI) {
        debug_str += "No SI found. Unknown barcode type\n";
        debug_str += "Assuming Code 128\n";
        //barcode_elements['-1'] = barcode; // if no SI was found, we just return the barcode in key = '-1'
    }

    // if there is no SI, we assume Code 128
    if (!SI || SI == "Code 128") {
        var start_index = 0;
        do{
            for (var end_index = start_index; end_index < barcode.length; end_index++) {
                if (gs1_128_table[barcode.substring(start_index, end_index)]) {
                    debug_str += "---- element ----\n";
                    var AI_code = barcode.substring(start_index, end_index); // application identifier value
                    var description = gs1_128_table[AI_code]['description'];
                    var length = gs1_128_table[AI_code]['length'];

                    // if the length is variable (e.g. 1-9), we assume this is the last barcode element (otherwise we cant parse it)
                    if (length.search('-') != -1) { 
                        length = barcode.length - end_index;
                    }

                    var barcode_element = barcode.substring(end_index, end_index + parseInt(length));
                    barcode_elements[AI_code] = barcode_element;
                    debug_str += "Description: " + description + "\nData length: " + length + "\nValue: " + barcode_element + "\n";
                    break;
                }
            }
            start_index = end_index + parseInt(length);
        }while(end_index < barcode.length);
    }

    //alert(debug_str);
    return barcode_elements;

}
