from parser import *
import re
import sys
import symbol
import token
import types

def createAst(filename):
	f = open(filename, "r")
	str = f.read()
	return suite(str)

def escapeElementValue(value):
	value = re.sub("&", "&amp;", value)
	value = re.sub("<", "&lt;", value)
	value = re.sub(">", "&gt;", value)
	return value

def printAst(tuple, output):
	printAst2(tuple, output, 0, 1)

def printAst2(tuple, output, depth, lastline):
	id = tuple[0]
	if not isinstance(tuple[1], types.StringType):
		element_name = symbol.sym_name[id]
		output.write("  " * depth + "<" + element_name + ">\n")
		for item in tuple[1:]:
			lastline = printAst2(item, output, depth + 1, lastline)
		output.write("  " * depth + "</" + element_name + ">\n")
	else:
		element_name = token.tok_name[id]
		output.write("  " * depth + "<" + element_name + " startline=\"" + str(lastline) + "\" endline=\"" + str(tuple[2]) + "\">" + escapeElementValue(tuple[1]) + "</" + element_name + ">\n")
		lastline = tuple[2]
		if element_name == "NEWLINE": lastline += 1
	return lastline

ast = createAst(sys.argv[1])
output = open(sys.argv[2], "w")
printAst(ast2tuple(ast, True), output)
