import sys, os
from preproc import pp_file
import popen2
projName = "project"

def my_sys(cmd):
	r, w, e = popen2.popen3(cmd)
	b1 = e.readlines()
	b2 = r.readlines()
	r.close()
	e.close()
	w.close()
	return (b1,b2)

def generate_AST(fname):
	xml_name = None
	if 'preproc' in fname:
		xml_name = fname[:fname.rfind('.preproc.php')] + '.xml'
	else:
		xml_name = fname[:fname.rfind('.php')] + '.xml'
	my_sys("php-ast.exe " + fname + " " + xml_name)
	return xml_name

def proceed(fname):
	pname = pp_file(fname) #> fname.php -> fname.preproc.php
	xname = generate_AST(pname)
	# generate the study output on the file
	(stderrlist , stdoutlist) = my_sys("php-oracle.exe --out:file " + xname + " " + projName )
	#for e in stderrlist:
	#	print "%s \t\t->\t\t %s" % (fname,e)
	my_sys("rm -f " + xname)
	my_sys("rm -f " + pname)
	"""
		tname = xname[:xname.rfind('.xml')] + ".txt"
		out = open(tname, 'w')
		for e in stdoutlist:
			out.write(e)
		out.write('\n<[[stderr]]>\n')
		for e in stderrlist:
			out.write(e)
		out.close()
	"""

def hasGoodExt(name):
	return '.php' in name or '.inc' in name

def scandir(directory):
	names = os.listdir(directory)
	for name in names:
		srcname = os.path.join(directory, name)
		try:
			if os.path.isdir(srcname):
				scandir(srcname)
			elif os.path.isfile(srcname) and hasGoodExt(srcname):
				proceed(srcname)
		except (IOError, os.error), why:
			continue

def main(fname):
	global projName
	projName = fname + ".xml"
	if os.path.isfile(fname):
		proceed(fname)
	elif os.path.isdir(fname):
		scandir(fname)

if __name__ == "__main__":
	main(sys.argv[1])