#!/usr/bin/python

# find all macros.C
# run with default params
# execute save to file in the same root session

import os
import sys
import fnmatch

def find_files(rootdir='.', pattern='*'):
	return [os.path.join(rootdir, filename)
			for rootdir, dirnames, filenames in os.walk(rootdir)
			for filename in filenames
			if fnmatch.fnmatch(filename, pattern)]

def contains(fn, tx):
	with open(fn, 'r') as f:
		for l in f.readlines():
			if tx in l:
				return True
	return False

def make_macro(m, lm):
	mname    = os.path.dirname(os.path.abspath(m))+'/run_{}'.format(os.path.basename(m))
	thispath = os.path.dirname(os.path.abspath(__file__))
	xmacro 	 = os.path.dirname(os.path.abspath(m))+'/{}'.format(os.path.basename(m))
	macro_inc = os.path.abspath(os.path.dirname(__file__)) + '/../pPb/results/macros/util'
	contents = '''
		{
		// WARNING: THIS FILE IS GENERATED by saveToFileAll.py
		TString wdir = gSystem->WorkingDirectory();
		gSystem->ChangeDirectory("XWDIRX");
		TString mpath = TString::Format("%s%s", gROOT->GetMacroPath(), "XMACRO_INC_PATHX");
		gROOT->SetMacroPath(mpath.Data());		
		gROOT->LoadMacro("XSAVEMACROX");
		gROOT->LoadMacro("XMACROX");
		XMACROFUNCTIONX();
		gSystem->ChangeDirectory(wdir.Data());
		save_to_file();
		}
		'''
	if 'PlotL2K_Pt_PtJE.C' in m:
		contents = '''
			{
			// WARNING: THIS FILE IS GENERATED by saveToFileAll.py
			TString wdir = gSystem->WorkingDirectory();
			gSystem->ChangeDirectory("XWDIRX");
			TString mpath = TString::Format("%s%s", gROOT->GetMacroPath(), "XMACRO_INC_PATHX");
			gROOT->SetMacroPath(mpath.Data());		
			gROOT->LoadMacro("XSAVEMACROX");
			gROOT->LoadMacro("XMACROX");
			XMACROFUNCTIONX(0);
			gSystem->ChangeDirectory(wdir.Data());
			save_to_file();
			}
			'''		
	contents = contents.replace('XMACRO_INC_PATHX', macro_inc)
	contents = contents.replace('XWDIRX', os.path.dirname(os.path.abspath(m)))
	contents = contents.replace('XSAVEMACROX', '{}/save_to_file.C'.format(thispath))
	contents = contents.replace('XMACROX', xmacro)
	contents = contents.replace('XMACROFUNCTIONX', os.path.basename(xmacro).strip('.C'))
	with open(mname, 'w') as f:
		print >> f, contents
	print '[i] macro written:',mname
	lm.append(mname)

	if 'PlotL2K_Pt_PtJE.C' in m:
		contents = contents.replace('(0);', '(2);')
		mname = mname.replace('.C', '_2.C')
		with open(mname, 'w') as f:
			print >> f, contents
		print '[i] macro written:',mname
		lm.append(mname)

def main():
	macros = find_files('../', '*.C')
	dirs = []
	for m in macros:
		if not contains(m, 'ConvHistogramToGraphError'):
			continue
		d = os.path.dirname(m)
		if d not in dirs:
			dirs.append(d)

	run_macros = []
	for d in dirs:
		if 'results' not in d:
			continue
		macrosd = find_files(d, '*.C')
		print d
		for m in macrosd:
			if not contains(m, 'ConvHistogramToGraphError'):
				continue
			make_macro(m, run_macros)

	with open('run_macros.sh', 'w') as f:
		print >> f, 'mkdir -p ./pp'
		print >> f, 'mkdir -p ./pPb'
		for m in run_macros:
			if '/pp/' in m:
				print >> f,'cd ./pp'
			if '/pPb/' in m:
				print >> f,'cd ./pPb'
			print >> f,'root -l -b -q',m
			print >> f,'cd -'

if __name__ == '__main__':
	main()
