#!/usr/bin/env python
import os, sys
import preproc,subprocess

phpast=""
phporacle=""
phpfiles = []

def my_sys(cmd):
	subprocess.Popen(cmd).wait()

def register():
	global phpast,phporacle
	phpast = os.path.join(os.path.abspath(os.curdir), "php-ast")
	phporacle = os.path.join(os.path.abspath(os.curdir), "php-oracle")

def populate_PROJ(dirname):
	global phpfiles
	all = {}
	all = [f for f in os.listdir(dirname) if os.path.isdir(os.path.join(dirname, f)) or os.path.isfile(os.path.join(dirname, f))]
	for f in all:
		if os.path.isdir(dirname + '/' + f):
			populate_PROJ(dirname + '/' + f)
		else:
			if f.find(".php") > -1 or f.find('.inc') > -1:
				if '.study.' not in f and '.php.xml' not in f: 
					phpfiles.append(os.path.join(dirname, f))

def generate_AST():
	for fname in phpfiles:
		preproc.pp_file(fname)
		sname = fname + '.study.php'
		xml_name = sname[:sname.find('.study.php')] + '.xml'
		print "### ", sname
		my_sys("php-ast " + sname + " " + xml_name)
		print ""

def generate_RESULTS():
	for fname in phpfiles:
		sname = fname + '.study.php'
		xml_name = sname[:sname.find('.study.php')] + '.xml'
		res_name = xml_name[:xml_name.find('.xml')] + '.res.txt'
		if os.path.isfile(xml_name):
			my_sys("php-oracle " + xml_name + " " + res_name)

def generate_M1(outfile):
	f = outfile
	for fname in phpfiles:
		sname = fname + '.study.php'
		xml_name = sname[:sname.find('.study.php')] + '.xml'
		res_name = xml_name[:xml_name.find('.xml')] + '.res.txt'
		if os.path.isfile(xml_name):
			my_sys("php-oracle -foo " + xml_name + " " + f)

if __name__ == "__main__":
	phpfiles = []
	register()
	phpfiles = []
	populate_PROJ("./study/cms/kelev")
	print "Total Number of Files = ", len(phpfiles)
	generate_AST()
	#generate_RESULTS()
	generate_M1("kelev.xml")



