/***
This is part of jsdifflib v1.0. <http://snowtide.com/jsdifflib>

Copyright (c) 2007, Snowtide Informatics Systems, Inc.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

   * Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
   * Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the
     distribution.
   * Neither the name of the Snowtide Informatics Systems nor the names
     of its contributors may be used to endorse or promote products
     derived from this software without specific prior written
     permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***/
/* Author: Chas Emerick <cemerick@snowtide.com> */
"use strict";
var whitespace = {
    " ": true,
    "\t": true,
    "\n": true,
    "\f": true,
    "\r": true
},
difflib = {
    defaultJunkFunction: function (c) {
        return c in whitespace;
    },

    stripLinebreaks: function (str) {
        return str.replace(/^[\n\r]*|[\n\r]*$/g, "");
    },

    stringAsLines: function (str) {
        var i, lfpos = str.indexOf("\n"),
        crpos = str.indexOf("\r"),
        linebreak = ((lfpos > -1 && crpos > -1) || crpos < 0) ? "\n": "\r",
        lines = str.split(linebreak);
        for (i = 0; i < lines.length; i += 1) {
            lines[i] = difflib.stripLinebreaks(lines[i]);
        }
        return lines;
    },

    // iteration-based reduce implementation
    reduce: function (func, list, initial) {
        var value, idx;
        if (initial !== null) {
            value = initial;
            idx = 0;
        } else if (list) {
            value = list[0];
            idx = 1;
        } else {
            return null;
        }

        for (; idx < list.length; idx += 1) {
            value = func(value, list[idx]);
        }

        return value;
    },

    // comparison function for sorting lists of numeric tuples
    ntuplecomp: function (a, b) {
        var i, mlen = Math.max(a.length, b.length);
        for (i = 0; i < mlen; i += 1) {
            if (a[i] < b[i]) {
                return - 1;
            }
            if (a[i] > b[i]) {
                return 1;
            }
        }

        return a.length === b.length ? 0 : (a.length < b.length ? -1 : 1);
    },

    calculate_ratio: function (matches, length) {
        return length ? 2.0 * matches / length: 1.0;
    },

    // returns a function that returns true if a key passed to the returned function
    // is in the dict (js object) provided to this function; replaces being able to
    // carry around dict.has_key in python...
    isindict: function (dict) {
        return function (key) {
            return key in dict;
        };
    },

    // replacement for python's dict.get function -- need easy default values
    dictget: function (dict, key, defaultValue) {
        return key in dict ? dict[key] : defaultValue;
    },

    SequenceMatcher: function (a, b, isjunk) {
        this.set_seqs = function (a, b) {
            this.set_seq1(a);
            this.set_seq2(b);
        };
        this.set_seq1 = function (a) {
            if (a === this.a) {
                return;
            }
            this.a = a;
            this.opcodes = null;
            this.matching_blocks = this.opcodes;
        };
        this.set_seq2 = function (b) {
            if (b === this.b) {
                return;
            }
            this.b = b;
            this.fullbcount = null;
            this.opcodes = this.fullbcount;
            this.matching_blocks = this.opcodes;
            this.chain_b();
        };

        this.chain_b = function () {
            var i, elt, indices, b = this.b,
            n = b.length,
            b2j = this.b2j = {},
            populardict = {},
            isjunk = this.isjunk,
            junkdict = {};
            for (i = 0; i < b.length; i += 1) {
                elt = b[i];
                if (elt in b2j) {
                    indices = b2j[elt];
                    if (n >= 200 && indices.length * 100 > n) {
                        populardict[elt] = 1;
                        delete b2j[elt];
                    } else {
                        indices.push(i);
                    }
                } else {
                    b2j[elt] = [i];
                }
            }

            for (elt in populardict) {
                if (populardict.hasOwnProperty(elt)) {
                    delete b2j[elt];
                }
            }

            if (isjunk) {
                for (elt in populardict) {
                    if (isjunk(elt)) {
                        junkdict[elt] = 1;
                        delete populardict[elt];
                    }
                }
                for (elt in b2j) {
                    if (isjunk(elt)) {
                        junkdict[elt] = 1;
                        delete b2j[elt];
                    }
                }
            }

            this.isbjunk = difflib.isindict(junkdict);
            this.isbpopular = difflib.isindict(populardict);
        };

        this.find_longest_match = function (alo, ahi, blo, bhi) {
            var i, newj2len, jdict, jkey, k, a = this.a,
            b = this.b,
            b2j = this.b2j,
            isbjunk = this.isbjunk,
            besti = alo,
            bestj = blo,
            bestsize = 0,
            j = null,
            j2len = {},
            nothing = [];
            for (i = alo; i < ahi; i += 1) {
                newj2len = {};
                jdict = difflib.dictget(b2j, a[i], nothing);
                for (jkey in jdict) {
                    if (jdict.hasOwnProperty(jkey)) {
                        j = jdict[jkey];
                        if (j >= blo) {
                            if (j >= bhi) {
                                break;
                            }
                            k = difflib.dictget(j2len, j - 1, 0) + 1;
                            newj2len[j] = k;
                            if (k > bestsize) {
                                besti = i - k + 1;
                                bestj = j - k + 1;
                                bestsize = k;
                            }
                        }
                    }
                }
                j2len = newj2len;
            }

            while (besti > alo && bestj > blo && !isbjunk(b[bestj - 1]) && a[besti - 1] === b[bestj - 1]) {
                besti -= 1;
                bestj -= 1;
                bestsize += 1;
            }

            while (besti + bestsize < ahi && bestj + bestsize < bhi && !isbjunk(b[bestj + bestsize]) && a[besti + bestsize] === b[bestj + bestsize]) {
                bestsize += 1;
            }

            while (besti > alo && bestj > blo && isbjunk(b[bestj - 1]) && a[besti - 1] === b[bestj - 1]) {
                besti -= 1;
                bestj -= 1;
                bestsize += 1;
            }

            while (besti + bestsize < ahi && bestj + bestsize < bhi && isbjunk(b[bestj + bestsize]) && a[besti + bestsize] === b[bestj + bestsize]) {
                bestsize += 1;
            }

            return [besti, bestj, bestsize];
        };

        this.get_matching_blocks = function () {
            if (this.matching_blocks !== null) {
                return this.matching_blocks;
            }
            var idx, alo, ahi, blo, bhi, qi, i, j, k, x, i2, j2, k2, la = this.a.length,
            lb = this.b.length,
            queue = [ [0, la, 0, lb]],
            matching_blocks = [],
            block = 0,
            k1 = block,
            j1 = k1,
            i1 = j1,
            non_adjacent = [];

            while (queue.length) {
                qi = queue.pop();
                alo = qi[0];
                ahi = qi[1];
                blo = qi[2];
                bhi = qi[3];
                x = this.find_longest_match(alo, ahi, blo, bhi);
                i = x[0];
                j = x[1];
                k = x[2];

                if (k) {
                    matching_blocks.push(x);
                    if (alo < i && blo < j) {
                        queue.push([alo, i, blo, j]);
                    }
                    if (i + k < ahi && j + k < bhi) {
                        queue.push([i + k, ahi, j + k, bhi]);
                    }
                }
            }

            matching_blocks.sort(difflib.ntuplecomp);
            for (idx in matching_blocks) {
                if (matching_blocks.hasOwnProperty(idx)) {
                    block = matching_blocks[idx];
                    i2 = block[0];
                    j2 = block[1];
                    k2 = block[2];
                    if (i1 + k1 === i2 && j1 + k1 === j2) {
                        k1 += k2;
                    } else {
                        if (k1) {
                            non_adjacent.push([i1, j1, k1]);
                        }
                        i1 = i2;
                        j1 = j2;
                        k1 = k2;
                    }
                }
            }

            if (k1) {
                non_adjacent.push([i1, j1, k1]);
            }
            non_adjacent.push([la, lb, 0]);
            this.matching_blocks = non_adjacent;
            return this.matching_blocks;
        };

        this.get_opcodes = function () {
            if (this.opcodes !== null) {
                return this.opcodes;
            }
            var idx, block, ai, bj, size, tag, blocks = this.get_matching_blocks(),
            i = 0,
            j = 0,
            answer = [];
            this.opcodes = answer;
            for (idx in blocks) {
                if (blocks.hasOwnProperty(idx)) {
                    block = blocks[idx];
                    ai = block[0];
                    bj = block[1];
                    size = block[2];
                    tag = '';
                    if (i < ai && j < bj) {
                        tag = 'replace';
                    } else if (i < ai) {
                        tag = 'delete';
                    } else if (j < bj) {
                        tag = 'insert';
                    }
                    if (tag) {
                        answer.push([tag, i, ai, j, bj]);
                    }
                    i = ai + size;
                    j = bj + size;

                    if (size) {
                        answer.push(['equal', ai, i, bj, j]);
                    }
                }
            }

            return answer;
        };

        // this is a generator function in the python lib, which of course is not supported in javascript
        // the reimplementation builds up the grouped opcodes into a list in their entirety and returns that.
        this.get_grouped_opcodes = function (n) {
            var idx, nn, code, tag, i1, i2, j1, j2, groups = [],
            codes = this.get_opcodes();
            if (!n) {
                n = 3;
            }
            if (!codes) {
                codes = [ ["equal", 0, 1, 0, 1]];
            }
            if (codes[0] [0] === 'equal') {
                code = codes[0];
                tag = code[0];
                i1 = code[1];
                i2 = code[2];
                j1 = code[3];
                j2 = code[4];
                codes[0] = [tag, Math.max(i1, i2 - n), i2, Math.max(j1, j2 - n), j2];
            }
            if (codes[codes.length - 1] [0] === 'equal') {
                code = codes[codes.length - 1];
                tag = code[0];
                i1 = code[1];
                i2 = code[2];
                j1 = code[3];
                j2 = code[4];
                codes[codes.length - 1] = [tag, i1, Math.min(i2, i1 + n), j1, Math.min(j2, j1 + n)];
            }

            nn = n + n;
            for (idx in codes) {
                if (codes.hasOwnProperty(idx)) {
                    code = codes[idx];
                    tag = code[0];
                    i1 = code[1];
                    i2 = code[2];
                    j1 = code[3];
                    j2 = code[4];
                    if (tag === 'equal' && i2 - i1 > nn) {
                        groups.push([tag, i1, Math.min(i2, i1 + n), j1, Math.min(j2, j1 + n)]);
                        i1 = Math.max(i1, i2 - n);
                        j1 = Math.max(j1, j2 - n);
                    }

                    groups.push([tag, i1, i2, j1, j2]);
                }
            }

            if (groups && groups[groups.length - 1] [0] === 'equal') {
                groups.pop();
            }
            return groups;
        };

        this.ratio = function () {
            var m = difflib.reduce(
            function (sum, triple) {
                return sum + triple[triple.length - 1];
            },
            this.get_matching_blocks(), 0);
            return difflib.calculate_ratio(m, this.a.length + this.b.length);
        };

        this.quick_ratio = function () {
            var i, elt, fullbcount, avail = {},
            availhas = difflib.isindict(avail),
            numb = 0,
            matchex = numb;
            if (this.fullbcount === null) {
                fullbcount = {};
                this.fullbcount = fullbcount;
                for (i = 0; i < this.b.length; i += 1) {
                    elt = this.b[i];
                    fullbcount[elt] = difflib.dictget(fullbcount, elt, 0) + 1;
                }
            }
            fullbcount = this.fullbcount;
            for (i = 0; i < this.a.length; i += 1) {
                elt = this.a[i];
                if (availhas(elt)) {
                    numb = avail[elt];
                } else {
                    numb = difflib.dictget(fullbcount, elt, 0);
                }
                avail[elt] = numb - 1;
                if (numb > 0) {
                    matchex += 1;
                }
            }
            return difflib.calculate_ratio(matchex, this.a.length + this.b.length);
        };
        this.real_quick_ratio = function () {
            var la = this.a.length,
            lb = this.b.length;
            return difflib.calculate_ratio(Math.min(la, lb), la + lb);
        };

        this.isjunk = isjunk ? isjunk: difflib.defaultJunkFunction;
        this.b = null;
        this.a = this.b;
        this.set_seqs(a, b);
    }
};