#!/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_a1CFGlines(a1CFGlines, 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

    FAIL_re = re.compile('^projecting failed')
    TAG_re = re.compile('^After attaching unaligned src word:')
    diff_re = re.compile('^different src_sent:')
    all = []

    a1CFGdict = {}
    id_re = re.compile('^Igt_id=(\d+)')

    while len(a1CFGlines) > 0:
    # for i in range(0,len(a1CFGlines)):
        m = id_re.match(a1CFGlines[0])
        if m:
            fail = 0
            # print("found match, "+str(m.group(0)))
            # print("going to loop till i find the start TAG...")
            tstring = ""
            while len(a1CFGlines) > 0:
                t = TAG_re.match(a1CFGlines[0])
                f = FAIL_re.match(a1CFGlines[0])
                a1CFGlines.pop(0)
                if t:
                    break 
                elif f:
                    fail=1
                    break

            # print("found the tag (or ran out of lines)")
            if fail==0:
                while len(a1CFGlines) > 0 \
                    and not diff_re.match(a1CFGlines[0]) \
                    and not a1CFGlines[0] == "\n":
                    # print("adding "+a1CFGlines[0]+" to tstring")
                    tstring += a1CFGlines[0]
                    a1CFGlines.pop(0)

                # print("found a tree: "+tstring)
                clean = tstring.replace('\n','')
                a1CFGdict[m.group(0)] = clean+"\n"
            else: a1CFGdict[m.group(0)] = "None\n"
        else:
            a1CFGlines.pop(0)


    # print("----------------")
    # print str(a1CFGdict)
    # print("----------------")

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

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

if __name__ == '__main__':
    a1CFGfile= 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 parse trees 
    a1CFGlines = open(a1CFGfile).readlines()
    all = parse_a1CFGlines(a1CFGlines, igt_items)

    out = open(igtfile,'w') 
    for i in range(0,len(all)):
        for l in all[i]: 
            out.write(l)
       
        if i+1 != len(all):
            out.write("\n")
