#!/usr/bin/python
#
# purpose: align the output of the english trees annotated
#          for grammatical function with the igt file

import sys
import re

def parse_igt(igt_lines):
    igt_items = []
    igt_blk = []
    while len(igt_lines) > 0:
#        print("dealing with line: [" + igt_lines[0] + "]")
        if igt_lines[0].strip() == '': 
#            print("discard and new block")
            # create a new igt block
            igt_items.append(igt_blk)
            igt_blk = []
            igt_lines.pop(0)
        else:
#            print("part of igt item")
            igt_blk.append(igt_lines[0])
            igt_lines.pop(0)

    # finish off the last igt block
#    # make sure there's a final newline
#    try:
#        if not "\n" in igt_blk[-1]:
#            igt_blk[-1]+="\n"
#    except:
#        print(str(igt_blk) + " was empty (surprisingly)")
#
    igt_items.append(igt_blk)

    return igt_items        

def parse_b1lines(b1lines, igt_items):
    ## it's a lil crazy in there, the items are in a sort of 
    ## random order, so we have to match by IGT id line

    ## in order to traverse the file less times, we build
    ## a dictionary based on the id as key
    TAG = "############################## Q2: English parse tree \n"
    all = []

    b1dict = {}
    id_re = re.compile('^Igt_id=(\d+)')
    for i in range(0,len(b1lines)):
        m = id_re.match(b1lines[i])
        if m:
            # found an id, get the tree and hash it
            # print(m.group(0))
            while b1lines[i] != TAG:
                i+=1
            b1dict[m.group(0)] = b1lines[i+1] 

#    print str(b1dict)


    toremove = []
    for igti in igt_items:
        if len(igti) < 4:
            toremove.append(igti)
            # print("weird igti (b1res): "+str(igti))
        else:
            id = ''
            m = id_re.match(igti[0])
            if m:
                id = id_re.match(igti[0]).group(0) 
            if b1dict[id]:
                igti.append(b1dict[id])

    for igti in toremove:
        # print('removing '+str(igti)+' from output')
        igt_items.remove(igti)
    return igt_items 

if __name__ == '__main__':
    b1file= sys.argv[1]
    igtfile = sys.argv[2]


    # read into array of igt items
    try:
        igt_lines = open(igtfile).readlines()
    except:
        print igtfile + " failed to open"
    igt_items = parse_igt(igt_lines)

    # get the parses
    b1lines = open(b1file).readlines()
    all = parse_b1lines(b1lines, igt_items)

    out = open(igtfile,'w') 
    for igt in all:
        for l in igt: 
            out.write(l)
        out.write("\n")
