#!/usr/bin/env python
#
# filterator -- filter and format the output of comparator
#
import sys, comparator

if __name__ == '__main__':
    def report_common(state):
        "Generate a report on common code."
        print "Filter-Program: filterator 1.0"
        print "Hash-Method: MD5"
        if state.merge_program:
            print "Merge-Program:", state.merge_program
        print "Normalization:", state.normalization
        print "Shred-Size: %d" % state.shredsize
        if minsize:
            print "Minimum-Size: %d" % minsize
        print 75 * '-'
        for tree in state.trees:
            rep = tree + ":"
            for (key, value) in state.trees[tree].items():
                rep += " %s=%s," % (key, value)
            sys.stdout.write(rep[:-1] + "\n")
        print 75 * '-'
        state.read_matches()
        for clique in state.cliques:
            (file, start, end, text) = state.extract_text(clique)
            if start == 1 and end == state.files[file]:
                print "%% %s:%d-%d: entire (%d matches)" % \
                      (file, start, end, len(clique))
            else:
                print "%% %s:%d-%d: (%d matches)" % \
                      (file, start, end, len(clique))
            sys.stdout.write(text)
    # Main line begins here
    import getopt
    try:
        (optlist, args) = getopt.getopt(sys.argv[1:], 'd:m:')
    except getopt.GetoptError:
        sys.stderr.write("usage: filterator [-d dir] [-m size]\n")
        sys.exit(2)
    minsize = 5
    dir = None
    linecounts = {}
    for (opt, val) in optlist:
        if opt == '-d':
            dir = val
        elif opt == '-m':
            minsize = int(val)

    try:
        state = comparator.CommonReport(sys.stdin, dir)
        if minsize:
            state.filter_by_size(minsize)
        try:
            report_common(state)
        except (KeyboardInterrupt, IOError):
            pass
    except comparator.ComparatorException, e:
        sys.stderr.write("filterator: " + e.message + "\n")
        sys.exit(1)

# End

