import sys, os, gc
import ROOT as r

def splitFile(filename, maxevents):
        origfile = r.TFile(filename,"read")
        geofile = filename.replace("ship","geofile_full")
	bigtree = origfile.Get("cbmsim")
	ntot = bigtree.GetEntriesFast()
	print ntot
	residualentries = ntot
	i = 0
        listOfFiles = []
	while residualentries>maxevents:
                tempfilename = filename.replace(".root","_%s.root"%i)
		tempfile = r.TFile(tempfilename,"recreate")
		tempfile.cd()
		print i*maxevents, min(maxevents,residualentries)
		temptree = bigtree.CopyTree("","",min(maxevents,residualentries), i*maxevents)
		residualentries-=maxevents
		temptree.Write("",r.TObject.kOverwrite)
		tempfile.Write("",r.TObject.kOverwrite)
		tempfile.Close()
		print "created file %s with %s entries"%(tempfilename,min(maxevents,residualentries))
                os.system("cp %s %s"%(geofile, geofile.replace(".root","_%s.root"%i)))
                listOfFiles.append(tempfilename)
		i+=1
	origfile.Close()
        gc.collect()
        return listOfFiles

def performReco(listOfFiles):
        for smallfile in listOfFiles:
		gc.collect()
		print "\tStarting reconstruction of %s"%smallfile
		os.system("python ShipReco.py -f %s"%smallfile)
		gc.collect()
	gc.collect()

def haddReco(listOfFiles):
	listOfReco = [filename.replace(".root","_rec.root") for filename in listOfFiles]
	target = "ship-Cosmics-all.root"
	os.system("hadd %s %s"%(target, " ".join(listOfreco) ))


