#!/usr/bin/env python3

from sys import argv, exit

if len(argv) != 4:
    print("Usage: %s [node ID to path walk from] [input DOT file] [output DOT file]" %argv[0])
    exit(1)
if argv[1] == "0":
    print("This is the root!")
    exit(1)

nextnodes = []
parsednodes = []
removenodes = []

with open(argv[2], 'r') as infile:
    text=infile.read()
infile.close()

splits = text.split(";")
total = len(splits)
nodeinfo=text.split("->")[0][:-2]
numstates=len((nodeinfo.split(";")))-1

curr_node=argv[1]

with open("temp.dot", 'w') as tmpDOT:
    tmpDOT.write(nodeinfo)
    while True:
        for i in range(total):
            if ("->"+curr_node) in splits[i]:
                from_node=(splits[i].split("->")[0].strip('\n'))
                if from_node not in nextnodes:
                    nextnodes.append(from_node)
                tmpDOT.write(splits[i]+";")
        if len(nextnodes)>0:
            nextnodes.sort()
            parsednodes.append(curr_node)
            curr_node=nextnodes.pop()
        else:
            break            
    tmpDOT.write("\n}")
    parsednodes.append('0')
tmpDOT.close()

for i in range(numstates):
    if repr(i) not in parsednodes:
        removenodes.append(i)

count=-1

with open(argv[3], 'w') as outDOT:    
    lines_seen = set()
    for line in open("temp.dot", 'r'):
        if count not in removenodes:
            if line not in lines_seen:
                outDOT.write(line)
                lines_seen.add(line)
        count+=1

outDOT.close()
        


