var tsvToArray = null;
(function ($) {
    tsvToArray = {
        file: 'cells.txt',
        text: null,
        json: null,

        initLoadText: function (text) {
            this.text = text;
            return this.generateJSON();
        },        
        numberOfTabs: function (text) {
            var count = 0;
            var index = 0;
            while (text.charAt(index++) === "\t") {
                count++;
            }
            return count;
        },
        generateJSON: function () {
            var self = this;
            var text = self.text;
            var lines = text.split(/\r\n|\r|\n/);
            self.generatedArray = [];
            var previousTabPosition = 0;
            var currentContent = null;
            var previousContent = null;
            $.each(lines, function (lineNumber, line) {
                var line = this;
                var content = line.replace(/\t/g, '');
                var tabPosition = self.numberOfTabs(line);
                currentContent = content.length ? content : currentContent;

                if (!self.generatedArray[lineNumber]) {
                    self.generatedArray[lineNumber] = [];
                }

                if (tabPosition > previousTabPosition) {
                    self.generatedArray[lineNumber] = self.autoFillArray(self.generatedArray[lineNumber], lineNumber, previousTabPosition, tabPosition, previousContent, currentContent);
                } else {
                    self.generatedArray[lineNumber].push(content);
                    previousTabPosition = tabPosition;
                    previousContent = content;
                }

            });

            return self.generatedArray;
        },
        autoFillArray: function (array, lineNumber, previousTabPosition, currentTabPosition, previousContent, currentContent) {
            var self = this;
            var currentElementArray = [currentContent];
            var previousLineArray = self.generatedArray[lineNumber - 1];
            var pluckedArray = previousLineArray.slice(0, currentTabPosition);
            var newArray = pluckedArray.concat(currentElementArray);
            return newArray;
        },
        convertArrayToTabContentString: function(array){
            var newLines = [];
            for(var i = 0; i < array.length; i++){
                var lineArray = array[i];
                var lineArrayString = lineArray.join('\t');
                newLines.push(lineArrayString);
            }
            return newLines.join('\n');
        },
        getAutoFilledTabContent: function(text){
            var array = this.initLoadText(text);
            var string = this.convertArrayToTabContentString(array);
            return string;
        },
        init: function () {
            
        }
    };
    tsvToArray.init();
})(jQuery);