Function to fill trees and branches after matching events


I’m working on a ROOT stand-alone application to compare events that have been reconstructed in two different ways. The original code performs the event matching in the main{} (the loop over all events is there), and if it succeed then it calls a function that in turn calls another function

FillHisto(const Event& event1,const Event& event2, TFile* tFile) 

that fills the histograms, profiles, etc., defined as e.g.

new TH1D("name","title", nbinsx, xmin, xmax); 

and fill the histogram in this way

((TH1D*) tFile->Get("dAngle"))->Fill(|ang1-ang2|);

Now, because it is not very versatile (think for a second one wants to increment nbinsx, then one has to modify the code, make again, and run again, which can take a lot of time if one has a huge amount of data) I would like to implement a similar function but filling trees with the variables of interest.
As a first attempt, I tried leaving the same structure and replacing histograms with trees

[code] tFile->cd();

new TTree("compTree1","first file Tree");
new TTree("compTree2","second file Tree");    

Int_t Id1, Id2;
Bool_t satEvent1, satEvent2;
Double_t Zen1, Zen2;

((TTree*) tFile->Get("compTree1"))->Branch("Zenith", &Zen1, "Zenith/D");
((TTree*) tFile->Get("compTree1"))->Branch("SD_Id", &Id1, "Event_Id/I");
((TTree*) tFile->Get("compTree1"))->Branch("Saturated", &satEvent1, "Saturation_Status/B");

((TTree*) tFile->Get("compTree2"))->Branch("Zenith", &Zen2, "Zenith/D");
((TTree*) tFile->Get("compTree2"))->Branch("SD_Id", &Id2, "Event_Id/I");
((TTree*) tFile->Get("compTree2"))->Branch("Saturated", &satEvent2, "Saturation_Status/B");

Id1 = event1.GetEventId();
Id2 = event2.GetEventId();   

satEvent1=  event1.IsSaturated();
satEvent2=  event2.IsSaturated();

Zen1 = event1.GetZenith(); // radiants
Zen2 = event2.GetZenith();

((TTree*) tFile->Get("compTree1"))->Fill();
((TTree*) tFile->Get("compTree2"))->Fill();

((TTree*) tFile->Get("compTree1"))->Write(); //"", TObject::kOverwrite);
((TTree*) tFile->Get("compTree2"))->Write(); //"", TObject::kOverwrite);


this doesn’t work. Execution is extremely slow and it crashes after a while.
Has anybody a clear guess/explanation on why this doesn’t work?
I imagine the trees declaration should be outside of the function and Ttree pointers should be given as arguments to the function.
Any hint, comment, remark, is more than welcome [-o<


avoid re-reading the tree each time:[code] TTree *compTree2 = new TTree(“compTree2”,“second file Tree”);

Int_t Id1, Id2;
Bool_t satEvent1, satEvent2;
Double_t Zen1, Zen2;

compTree2->Branch(“Zenith”, &Zen1, “Zenith/D”);[/code]