#!/usr/bin/env python
from lxml import etree
import sys, os


def norm_spaces(s):
	return ' '.join(s.split())

def indentation(i):
	r = ""
	for a in range(0,i):
		r += "\t"
	return r

def generate_SOURCE(xmlName):
	print xmlName
	xsl_tree = etree.parse('./xslt/toWrite.xsl')
	transform = etree.XSLT(xsl_tree)
	doc = etree.parse(xmlName)
	result = str(transform(doc))
	r = result.split("\n")
	formated = []
	indent = 1
	string = ""
	chars = "{}"
	for l in r:
		if len(l) == 0 or l == "\n":
			string += " "
		elif l in chars:
			string += l
			if l == "}": indent -= 1
			formated.append((indent,string))
			if l == "{": indent += 1
			string = ""
		else:
			string += l
			if l == ';' and 'for' not in string:
				formated.append((indent,string))
				string = ""
			
	out = open(xmlName[:xmlName.rfind('.xml')] + '.php', 'w')
	out.write("<?php\n")
	for i,f in formated:
		out.write(indentation(i) + norm_spaces(f) + "\n")
	out.write("\n?>")
	out.close()

if __name__ == '__main__':
	generate_SOURCE(sys.argv[1])
