#!/usr/bin/env python3
#
# purpose: align the output of the nl_parser with an igt file
import sys

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
    igt_items.append(igt_blk)

    return igt_items        
        

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

    # create an array of igt items
    igt_lines = open(igtfile).readlines()
    igt_items = parse_igt(igt_lines)

    # get the parses
    parse_lines = open(parsefile).readlines()

    # check the lengths
    if len(igt_items) != len(parse_lines):
        print("lengths of igt_items and parse vectors differ?\n" +\
              str(len(igt_items))+ " " +
              str(len(parse_lines))+ "\n\n" +
              str(igt_items)+ "\n\n" +
              str(parse_lines)+ "\n\n", file=sys.stderr)
    else: 
        print("alignment of igt with parses looks ok",file=sys.stderr)

    out = open(igtfile,'w') 
    for i in range(0,len(igt_items)):
        for l in igt_items[i]:
            if l.find("\n") == -1:
#               print("appending newline to igt",file=sys.stderr)
                l+="\n"
#           else:
#               print("igt line ends in newline already",file=sys.stderr)
#               print(l,file=sys.stderr)
            out.write(l) 
        out.write(parse_lines[i])
        if i+1 != len(igt_items):
            out.write("\n")
