require 'rbtree'

class LexGod
    attr_accessor :bigH, :lexD
    def initialize(newCutOff)
        @Hash_CutOff = newCutOff;
    end

    def build(fileName)
        words = File.open(fileName,"r").readlines;
        @lexD = words.map{|w|breakDown(w.chop)}.flatten.sort;
        File.open("lexArray.rbo", "w+") {|file|
            Marshal.dump(@lexD, file);
        }
        #@lexD = Marshal.load(File.open("lexArray.rbo").read);

        @bigH = RBTree.new();
        assimilate();

        File.open("lexDict.rbo", "w+") { |file|
            Marshal.dump(@bigH, file);
        }
    end

    def assimilate(remWords = @lexD, char = 0, curH = @bigH)
        while (not remWords.empty?)
            exW = remWords.pop();
            puts "Ass: #{exW}";
            newWords = [exW];
            remWords.reject!{ |word|
                result = (word =~ /^#{exW[0..char]}/);
                newWords.push(word) if result;
                result;
            }
            if (newWords.length > @Hash_CutOff)
                curH[exW[char,1]] = RBTree.new();
                assimilate(newWords, char + 1, curH[exW[char,1]]);
            else
                curH[exW[char,1]] = newWords.sort;
            end
        end
    end

    def breakDown(word)
        puts "Bkn: #{word}";
        tokens = Array.new();
        0.upto(word.length - 2) { |slice|
            tokens.push(word[0..slice].reverse +
                "0" + 
                word[slice+1..word.length-1]);
        }
        tokens.push(word.reverse);
        return tokens;
    end
end

puts "Must Enter Hash Cutoff Length..." or exit if ARGV.empty?;

#puts "Building...";
arnold = LexGod.new(ARGV.first.to_i);
arnold.build("dict.txt");

puts "All done";
exit(0);
