/[PAMELA software]/PamelaLevel2/src/PamLevel2.cpp
ViewVC logotype

Diff of /PamelaLevel2/src/PamLevel2.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.7 by pam-fi, Fri Oct 27 11:33:19 2006 UTC revision 1.91 by mocchiut, Thu Dec 15 08:54:12 2011 UTC
# Line 1  Line 1 
1  #include <PamLevel2.h>  #include <PamLevel2.h>
2    
3    /////////////////////////////////////////////////////////////////////////////
4    /////////////////////////////////////////////////////////////////////////////
5    /////////////////////////////////////////////////////////////////////////////
6    /////////////////////////////////////////////////////////////////////////////
7    
8    void GPamela::Clear() {
9      Irun = 0;
10      Ievnt = 0;
11      Ipa = 0;
12      X0 = 0.;
13      Y0 = 0.;
14      Z0 = 0.;
15      Theta = 0.;
16      Phi = 0.;
17      P0 = 0.;
18      Nthtof = 0;
19      Nthcat = 0;
20      Nthcas = 0;
21      Nthspe = 0;
22      Nstrpx = 0;
23      Nstrpy = 0;
24      Nthcali = 0;
25      Nthcal = 0;
26      Nthnd = 0;
27      Nthcard = 0;
28    }
29    
30    void GPamela::Delete() {
31    
32      Clear();
33    
34      delete[] Ipltof;
35      delete[] Ipaddle;
36      delete[] Ipartof;
37      delete[] Xintof;
38      delete[] Yintof;
39      delete[] Zintof;
40      delete[] Xouttof;
41      delete[] Youttof;
42      delete[] Zouttof;
43      delete[] Ereltof;
44      delete[] Timetof;
45      delete[] Pathtof;
46      delete[] P0tof;
47      delete[] Iparcat;
48      delete[] Icat;
49      delete[] Xincat;
50      delete[] Yincat;
51      delete[] Zincat;
52      delete[] Xoutcat;
53      delete[] Youtcat;
54      delete[] Zoutcat;
55      delete[] Erelcat;
56      delete[] Timecat;
57      delete[] Pathcat;
58      delete[] P0cat;
59      delete[] Iparcas;
60      delete[] Icas;
61      delete[] Xincas;
62      delete[] Yincas;
63      delete[] Zincas;
64      delete[] Xoutcas;
65      delete[] Youtcas;
66      delete[] Zoutcas;
67      delete[] Erelcas;
68      delete[] Timecas;
69      delete[] Pathcas;
70      delete[] P0cas;
71      delete[] Iparspe;
72      delete[] Itrpb;
73      delete[] Itrsl;
74      delete[] Itspa;
75      delete[] Xinspe;
76      delete[] Yinspe;
77      delete[] Zinspe;
78      delete[] Xoutspe;
79      delete[] Youtspe;
80      delete[] Zoutspe;
81      delete[] Xavspe;
82      delete[] Yavspe;
83      delete[] Zavspe;
84      delete[] Erelspe;
85      delete[] Pathspe;
86      delete[] P0spe;
87      delete[] Nxmult;
88      delete[] Nymult;
89      delete[] Npstripx;
90      delete[] Ntstripx;
91      delete[] Istripx;
92      delete[] Qstripx;
93      delete[] Xstripx;
94      delete[] Npstripy;
95      delete[] Ntstripy;
96      delete[] Istripy;
97      delete[] Qstripy;
98      delete[] Ystripy;
99      delete[] Icaplane;
100      delete[] Icastrip;
101      delete[] Icamod;
102      delete[] Enestrip;
103      delete[] Icapl;
104      delete[] Icasi;
105      delete[] Icast;
106      delete[] Xincal;
107      delete[] Yincal;
108      delete[] Zincal;
109      delete[] Erelcal;
110      delete[] Itubend;
111      delete[] Iparnd;
112      delete[] Xinnd;
113      delete[] Yinnd;
114      delete[] Zinnd;
115      delete[] Xoutnd;
116      delete[] Youtnd;
117      delete[] Zoutnd;
118      delete[] Erelnd;
119      delete[] Timend;
120      delete[] Pathnd;
121      delete[] P0nd;
122      delete[] Iparcard;
123      delete[] Icard;
124      delete[] Xincard;
125      delete[] Yincard;
126      delete[] Zincard;
127      delete[] Xoutcard;
128      delete[] Youtcard;
129      delete[] Zoutcard;
130      delete[] Erelcard;
131      delete[] Timecard;
132      delete[] Pathcard;
133      delete[] P0card;
134    
135    }
136    ;
137    
138    void GPamela::SetBranchAddress(TChain* fhBookTree) {
139    
140      //    cout << "fhBookTree "<<fhBookTree << endl;
141      // prepare tree
142      fhBookTree->SetBranchAddress("Irun", &Irun);
143      fhBookTree->SetBranchAddress("Ievnt", &Ievnt);
144      fhBookTree->SetBranchAddress("Ipa", &Ipa);
145      fhBookTree->SetBranchAddress("X0", &X0);
146      fhBookTree->SetBranchAddress("Y0", &Y0);
147      fhBookTree->SetBranchAddress("Z0", &Z0);
148      fhBookTree->SetBranchAddress("Theta", &Theta);
149      fhBookTree->SetBranchAddress("Phi", &Phi);
150      fhBookTree->SetBranchAddress("P0", &P0);
151      fhBookTree->SetBranchAddress("Nthtof", &Nthtof);
152      fhBookTree->SetBranchAddress("Ipltof", Ipltof);
153      fhBookTree->SetBranchAddress("Ipaddle", Ipaddle);
154      fhBookTree->SetBranchAddress("Ipartof", Ipartof);
155      fhBookTree->SetBranchAddress("Xintof", Xintof);
156      fhBookTree->SetBranchAddress("Yintof", Yintof);
157      fhBookTree->SetBranchAddress("Zintof", Zintof);
158      fhBookTree->SetBranchAddress("Xouttof", Xouttof);
159      fhBookTree->SetBranchAddress("Youttof", Youttof);
160      fhBookTree->SetBranchAddress("Zouttof", Zouttof);
161      fhBookTree->SetBranchAddress("Ereltof", Ereltof);
162      fhBookTree->SetBranchAddress("Timetof", Timetof);
163      fhBookTree->SetBranchAddress("Pathtof", Pathtof);
164      fhBookTree->SetBranchAddress("P0tof", P0tof);
165      fhBookTree->SetBranchAddress("Nthcat", &Nthcat);
166      fhBookTree->SetBranchAddress("Iparcat", Iparcat);
167      fhBookTree->SetBranchAddress("Icat", Icat);
168      fhBookTree->SetBranchAddress("Xincat", Xincat);
169      fhBookTree->SetBranchAddress("Yincat", Yincat);
170      fhBookTree->SetBranchAddress("Zincat", Zincat);
171      fhBookTree->SetBranchAddress("Xoutcat", Xoutcat);
172      fhBookTree->SetBranchAddress("Youtcat", Youtcat);
173      fhBookTree->SetBranchAddress("Zoutcat", Zoutcat);
174      fhBookTree->SetBranchAddress("Erelcat", Erelcat);
175      fhBookTree->SetBranchAddress("Timecat", Timecat);
176      fhBookTree->SetBranchAddress("Pathcat", Pathcat);
177      fhBookTree->SetBranchAddress("P0cat", P0cat);
178      fhBookTree->SetBranchAddress("Nthcas", &Nthcas);
179      fhBookTree->SetBranchAddress("Iparcas", Iparcas);
180      fhBookTree->SetBranchAddress("Icas", Icas);
181      fhBookTree->SetBranchAddress("Xincas", Xincas);
182      fhBookTree->SetBranchAddress("Yincas", Yincas);
183      fhBookTree->SetBranchAddress("Zincas", Zincas);
184      fhBookTree->SetBranchAddress("Xoutcas", Xoutcas);
185      fhBookTree->SetBranchAddress("Youtcas", Youtcas);
186      fhBookTree->SetBranchAddress("Zoutcas", Zoutcas);
187      fhBookTree->SetBranchAddress("Erelcas", Erelcas);
188      fhBookTree->SetBranchAddress("Timecas", Timecas);
189      fhBookTree->SetBranchAddress("Pathcas", Pathcas);
190      fhBookTree->SetBranchAddress("P0cas", P0cas);
191      fhBookTree->SetBranchAddress("Nthspe", &Nthspe);
192      fhBookTree->SetBranchAddress("Iparspe", Iparspe);
193      fhBookTree->SetBranchAddress("Itrpb", Itrpb);
194      fhBookTree->SetBranchAddress("Itrsl", Itrsl);
195      fhBookTree->SetBranchAddress("Itspa", Itspa);
196      fhBookTree->SetBranchAddress("Xinspe", Xinspe);
197      fhBookTree->SetBranchAddress("Yinspe", Yinspe);
198      fhBookTree->SetBranchAddress("Zinspe", Zinspe);
199      fhBookTree->SetBranchAddress("Xoutspe", Xoutspe);
200      fhBookTree->SetBranchAddress("Youtspe", Youtspe);
201      fhBookTree->SetBranchAddress("Zoutspe", Zoutspe);
202      fhBookTree->SetBranchAddress("Xavspe", Xavspe);
203      fhBookTree->SetBranchAddress("Yavspe", Yavspe);
204      fhBookTree->SetBranchAddress("Zavspe", Zavspe);
205      fhBookTree->SetBranchAddress("Erelspe", Erelspe);
206      fhBookTree->SetBranchAddress("Pathspe", Pathspe);
207      fhBookTree->SetBranchAddress("P0spe", P0spe);
208      fhBookTree->SetBranchAddress("Nxmult", Nxmult);
209      fhBookTree->SetBranchAddress("Nymult", Nymult);
210      fhBookTree->SetBranchAddress("Nstrpx", &Nstrpx);
211      fhBookTree->SetBranchAddress("Npstripx", Npstripx);
212      fhBookTree->SetBranchAddress("Ntstripx", Ntstripx);
213      fhBookTree->SetBranchAddress("Istripx", Istripx);
214      fhBookTree->SetBranchAddress("Qstripx", Qstripx);
215      fhBookTree->SetBranchAddress("Xstripx", Xstripx);
216      fhBookTree->SetBranchAddress("Nstrpy", &Nstrpy);
217      fhBookTree->SetBranchAddress("Npstripy", Npstripy);
218      fhBookTree->SetBranchAddress("Ntstripy", Ntstripy);
219      fhBookTree->SetBranchAddress("Istripy", Istripy);
220      fhBookTree->SetBranchAddress("Qstripy", Qstripy);
221      fhBookTree->SetBranchAddress("Ystripy", Ystripy);
222      fhBookTree->SetBranchAddress("Nthcali", &Nthcali);
223      fhBookTree->SetBranchAddress("Icaplane", Icaplane);
224      fhBookTree->SetBranchAddress("Icastrip", Icastrip);
225      fhBookTree->SetBranchAddress("Icamod", Icamod);
226      fhBookTree->SetBranchAddress("Enestrip", Enestrip);
227      fhBookTree->SetBranchAddress("Nthcal", &Nthcal);
228      fhBookTree->SetBranchAddress("Icapl", Icapl);
229      fhBookTree->SetBranchAddress("Icasi", Icasi);
230      fhBookTree->SetBranchAddress("Icast", Icast);
231      fhBookTree->SetBranchAddress("Xincal", Xincal);
232      fhBookTree->SetBranchAddress("Yincal", Yincal);
233      fhBookTree->SetBranchAddress("Zincal", Zincal);
234      fhBookTree->SetBranchAddress("Erelcal", Erelcal);
235      fhBookTree->SetBranchAddress("Nthnd", &Nthnd);
236      fhBookTree->SetBranchAddress("Itubend", Itubend);
237      fhBookTree->SetBranchAddress("Iparnd", Iparnd);
238      fhBookTree->SetBranchAddress("Xinnd", Xinnd);
239      fhBookTree->SetBranchAddress("Yinnd", Yinnd);
240      fhBookTree->SetBranchAddress("Zinnd", Zinnd);
241      fhBookTree->SetBranchAddress("Xoutnd", Xoutnd);
242      fhBookTree->SetBranchAddress("Youtnd", Youtnd);
243      fhBookTree->SetBranchAddress("Zoutnd", Zoutnd);
244      fhBookTree->SetBranchAddress("Erelnd", Erelnd);
245      fhBookTree->SetBranchAddress("Timend", Timend);
246      fhBookTree->SetBranchAddress("Pathnd", Pathnd);
247      fhBookTree->SetBranchAddress("P0nd", P0nd);
248      fhBookTree->SetBranchAddress("Nthcard", &Nthcard);
249      fhBookTree->SetBranchAddress("Iparcard", Iparcard);
250      fhBookTree->SetBranchAddress("Icard", Icard);
251      fhBookTree->SetBranchAddress("Xincard", Xincard);
252      fhBookTree->SetBranchAddress("Yincard", Yincard);
253      fhBookTree->SetBranchAddress("Zincard", Zincard);
254      fhBookTree->SetBranchAddress("Xoutcard", Xoutcard);
255      fhBookTree->SetBranchAddress("Youtcard", Youtcard);
256      fhBookTree->SetBranchAddress("Zoutcard", Zoutcard);
257      fhBookTree->SetBranchAddress("Erelcard", Erelcard);
258      fhBookTree->SetBranchAddress("Timecard", Timecard);
259      fhBookTree->SetBranchAddress("Pathcard", Pathcard);
260      fhBookTree->SetBranchAddress("P0card", P0card);
261    
262      //    fhBookTree->SetBranchStatus("*",0);
263    
264    }
265    
266    ClassImp( GPamela);
267    
268    /////////////////////////////////////////////////////////////////////////////
269    /////////////////////////////////////////////////////////////////////////////
270    /////////////////////////////////////////////////////////////////////////////
271    /////////////////////////////////////////////////////////////////////////////
272  //--------------------------------------  //--------------------------------------
273  //  //
274  //  //
275  //--------------------------------------  //--------------------------------------
276  /**  /**
277   * Default constructor   * Default constructor
278   */   */
279  PamTrack::PamTrack(){  PamTrack::PamTrack() {
280      trk_track  = this->TrkTrack::GetTrkTrack();    trk_track = 0;
281      calo_track = this->CaloTrkVar::GetCaloTrkVar();    calo_track = 0;
282      tof_track  = this->ToFTrkVar::GetToFTrkVar();    tof_track = 0;
283  };    orb_track = 0;
284      candeleteobj = 0;
285      pscore = 0;
286      iscore = 0;
287    }
288    ;
289  //--------------------------------------  //--------------------------------------
290  //  //
291  //  //
292  //--------------------------------------  //--------------------------------------
293  /**  /**
294   * Constructor   * Constructor
295   */   */
296  PamTrack::PamTrack(TrkTrack* t, CaloTrkVar* c, ToFTrkVar* o){  PamTrack::PamTrack(TrkTrack* t, CaloTrkVar* c, ToFTrkVar* o, OrbitalInfoTrkVar *r) {
     trk_track  = this->TrkTrack::GetTrkTrack();  
     calo_track = this->CaloTrkVar::GetCaloTrkVar();  
     tof_track  = this->ToFTrkVar::GetToFTrkVar();  
     if(t) *trk_track  = *t;  
     if(c) *calo_track = *c;  
     if(o) *tof_track  = *o;      
 };  
297    
298      trk_track = 0;
299      calo_track = 0;
300      tof_track = 0;
301      orb_track = 0;
302      //     if(t)trk_track  = new TrkTrack(*t);
303      //     if(c)calo_track = new CaloTrkVar(*c);
304      //     if(o)tof_track  = new ToFTrkVar(*o);
305      if (t)
306        trk_track = t;
307      if (c)
308        calo_track = c;
309      if (o)
310        tof_track = o;
311      if (r)
312        orb_track = r;
313    
314      candeleteobj = 0;
315    
316    }
317    ;
318    PamTrack::PamTrack(const PamTrack& track) {
319    
320      TrkTrack *t = track.trk_track;
321      CaloTrkVar *c = track.calo_track;
322      ToFTrkVar *o = track.tof_track;
323      OrbitalInfoTrkVar *r = track.orb_track;
324    
325      trk_track = 0;
326      calo_track = 0;
327      tof_track = 0;
328      orb_track = 0;
329      if (t)
330        trk_track = new TrkTrack(*t);
331      if (c)
332        calo_track = new CaloTrkVar(*c);
333      if (o)
334        tof_track = new ToFTrkVar(*o);
335      if (r)
336        orb_track = new OrbitalInfoTrkVar(*r);
337      candeleteobj = 1;
338    
339    }
340    void PamTrack::Clear() {
341    
342      //    cout << "PamTrack::Clear() "<<candeleteobj<<endl;
343      if (candeleteobj) {
344        if (trk_track)
345          trk_track->TrkTrack::Clear();
346        if (calo_track)
347          calo_track->CaloTrkVar::Clear();//???
348        if (tof_track)
349          tof_track->ToFTrkVar::Clear();//???
350        if (orb_track)
351          orb_track->OrbitalInfoTrkVar::Clear();//???
352      }
353      else {
354        trk_track = 0;
355        calo_track = 0;
356        tof_track = 0;
357        orb_track = 0;
358      }
359      pscore = 0;
360      iscore = 0;
361    
362    }
363    void PamTrack::Delete() {
364      //    cout << "PamTrack::Delete() "<<candeleteobj<<endl;
365      if (candeleteobj) {
366        if (trk_track) {
367          trk_track->TrkTrack::Clear();
368          delete trk_track;
369        }
370        if (calo_track) {
371          calo_track->CaloTrkVar::Clear();//???
372          delete calo_track;
373        }
374        if (tof_track) {
375          tof_track->ToFTrkVar::Clear();//???
376          delete tof_track;
377        }
378        if (orb_track) {
379          orb_track->OrbitalInfoTrkVar::Clear();//???
380          delete orb_track;
381        }
382      }
383      else {
384        Clear();
385      }
386    }
387  //--------------------------------------  //--------------------------------------
388  //  //
389  //  //
390  //--------------------------------------  //--------------------------------------
391  /**  /**
392   * Constructor   * Default Constructor
393   */   */
394  PamLevel2::PamLevel2(){  PamLevel2::PamLevel2() {
395              Initialize();
396      trk_l1_obj  = this->TrkLevel1::GetTrkLevel1();        }
397      trk_obj     = this->TrkLevel2::GetTrkLevel2();  
     calo_obj    = this->CaloLevel2::GetCaloLevel2();  
     tof_obj     = this->ToFLevel2::GetToFLevel2();  
     trig_obj    = this->TrigLevel2::GetTrigLevel2();  
     s4_obj      = this->S4Level2::GetS4Level2();  
     nd_obj      = this->NDLevel2::GetNDLevel2();  
     ac_obj      = this->AcLevel2::GetAcLevel2();  
     orb_obj     = this->OrbitalInfo::GetOrbitalInfo();  
398    
     run_obj     = new GL_RUN();  
       
     sorted_tracks = new TRefArray();  
       
     CAL = true;  
     TRK = true;  
     TRG = true;  
     TOF = true;  
     S4  = true;  
     ND  = true;  
     AC  = true;  
     ORB = true;  
       
     TRK_L1 = false;  
       
     Tout  = NULL;  
 };  
399  /**  /**
400   * Destructor   * Constructor
401     * @param ddir Name of directory where level2 files are stored.
402     * @param list Name of an ascii file containing the list of file names
403     * @param detlist Options to chose what to load.
404     * Possible options are:
405     *       +AUTO --> load all trees/branches in the input files
406     *       +(-)ALL --> inlcude(exclude) all trees/branches
407     *       +(-)TRK1+(-)TRK2+(-)CAL1+(-)CAL2+(-)TOF+(-)TRG+(-)ND+(-)S4+(-)ORB+(-)AC --> inlcude(exclude) trees and branches
408     *       +(-)TRK0 --> include(exclude) tracker level0 tree
409     *       +(-)GP --> include exclude GPAMELA output tree
410     * If no options are specified, the default is assumed. Default is:
411     * +TRK2+CAL2+CAL1+TOF+TRG+ND+AC+S4+ORB
412   */   */
413  PamLevel2::~PamLevel2(){  PamLevel2::PamLevel2(TString ddir, TString llist, TString detlist) {
414                      Initialize();
415      TrkLevel1::Clear();    TList* listf = GetListOfLevel2Files(ddir, llist);
416          if (listf)
417      TrkLevel2::Clear();      GetPamTree(listf, detlist);
418      CaloLevel2::Clear();    if (listf)
419      ToFLevel2::Clear();      GetRunTree(listf);
420      TrigLevel2::Clear();    this->SetMaxShift(-1);
421      S4Level2::Clear();  }
     NDLevel2::Clear();  
     AcLevel2::Clear();  
     OrbitalInfo::Clear();  
       
     delete run_obj;  
       
 //      delete sorted_tracks;  
     sorted_tracks->Delete(); // clean the reference array  
           
     if(Tout)Tout->Delete(); // delete loaded tree from memory  
           
 };  
 /**  
  * Clear the event  
  */  
 void PamLevel2::Clear(){  
           
     TrkLevel1::Clear();  
           
     TrkLevel2::Clear();  
     CaloLevel2::Clear();  
     ToFLevel2::Clear();  
     TrigLevel2::Clear();  
     S4Level2::Clear();  
     NDLevel2::Clear();  
     AcLevel2::Clear();  
     OrbitalInfo::Clear();  
       
     sorted_tracks->Delete(); // clean the reference array  
       
 };  
422    
423    
424  //--------------------------------------  PamLevel2::PamLevel2(TString ddir, TList *llist, TString detlist) {
425  //    Initialize();
426  //    GetPamTree(llist, detlist);
427  //--------------------------------------    GetRunTree(llist);
428      this->SetMaxShift(-1);
429    }
430    
431  /**  /**
432   * Retrieves the calorimeter track matching the seqno-th tracker stored track.   * Constructor
433   * (If seqno = -1 retrieves the self-trigger calorimeter track)   * @param ddir Name of directory where level2 files are stored.
434     * @param list Name of an ascii file containing the list of file names
435     * Default trees/branches are loaded. Default is:
436     * +TRK2+CAL2+CAL1+TOF+TRG+ND+AC+S4+ORB
437   */   */
438   CaloTrkVar *PamLevel2::GetCaloStoredTrack(int seqno){  PamLevel2::PamLevel2(TString ddir, TString llist) {
439              Initialize();
440       if( CaloLevel2::ntrk()==0 ){    TList* listf = GetListOfLevel2Files(ddir, llist);
441           cout << "PamLevel2::GetCaloStoredTrack(int) : requested tracker SeqNo "<< seqno <<" but no Calorimeter tracks are stored"<<endl;    GetPamTree(listf, "");
442           return NULL;    GetRunTree(listf);
443       };    this->SetMaxShift(-1);
444        }
445       CaloTrkVar *c = 0;  
446       Int_t it_calo=0;  
447        void PamLevel2::Initialize() {
448       do{  
449           c = CaloLevel2::GetCaloTrkVar(it_calo);    h0_obj = 0;
450           it_calo++;    trk0_obj = 0;
451       } while( c && seqno != c->trkseqno && it_calo < CaloLevel2::ntrk());          calo0_obj = 0;
452        
453       if(!c || seqno != c->trkseqno){    trk2_obj = 0;
454           c = 0;    trk1_obj = 0;
455           if(seqno!=-1)cout << "PamLevel2::GetCaloStoredTrack(int) : requested tracker SeqNo "<< seqno <<" does not match Calorimeter stored tracks"<<endl;    trkh_obj = 0;
456       };    calo1_obj = 0;
457       return c;    calo2_obj = 0;
458          tof_obj = 0;
459   };    trig_obj = 0;
460  //--------------------------------------    s4_obj = 0;
461   //    nd_obj = 0;
462   //    ac_obj = 0;
463  //--------------------------------------    orb_obj = 0;
464  /**    gp_obj = 0;
465    * Retrieves the ToF track matching the seqno-th tracker stored track.  
466    * (If seqno = -1 retrieves the tracker-independent tof track)    run_obj = 0;//new GL_RUN();
467   */    soft_obj = 0;// Emiliano
468   ToFTrkVar *PamLevel2::GetToFStoredTrack(int seqno){    irun = -1LL;
469              irunt = -1LL;
470       if( ToFLevel2::ntrk()==0 ){    totrunentry = 0LL;
471           cout << "PamLevel2::GetToFStoredTrack(int) : requested tracker SeqNo "<< seqno <<" but no ToF tracks are stored"<<endl;    totrunentrymax = 0LL;
472           return NULL;    totrunentrymin = 0LL;
473       };    runfirstentry = 0LL;
474          runlastentry = 0LL;
475       ToFTrkVar *c = 0;    gltsync = 0; // Emiliano
476       Int_t it_tof=0;    fUpdateRunInfo = true; // Emiliano
477          isSync = false; // by default assume that the level2 file(s) is(are) not sinchronized between L0/DB and L2, that is we miss some packets in L2 due to nested/DV-skipped events
478       do{    il0entry = 0LL;
479           c = ToFLevel2::GetToFTrkVar(it_tof);    //  hasL0EE = true;
480           it_tof++;  
481       } while( c && seqno != c->trkseqno && it_tof < ToFLevel2::ntrk());    l0_file = NULL;
482          l0_tree = NULL;
483       if(!c || seqno != c->trkseqno){    iroot = -1;
484           c = 0;    dbc = 0;
485           if(seqno!=-1)cout << "PamLevel2::GetToFStoredTrack(int) : requested tracker SeqNo "<< seqno <<" does not match ToF stored tracks"<<endl;  
486       };    prevshift = 0;
487       return c;    yprevshift = 0;
488          maxshift = 10; //EMILIANO now overridden by SetMaxShift(-1) called by constructors
489   };  
490      run_tree = NULL;
491  //--------------------------------------    run_tree_clone = NULL;
492   //    sel_tree = NULL;
493   //    sel_tree_clone = NULL;
494  //--------------------------------------  
495  /**    irunentry = -1LL;
496   * Give the pamela track associated to a tracker track, retrieving related calorimeter and tof track information.    pam_tree = NULL;
497   */    for (Int_t i = 0; i < NCLONES; i++)
498   PamTrack* PamLevel2::GetPamTrackAlong(TrkTrack* t){      pam_tree_clone[i] = NULL;
499            
500       CaloTrkVar *c = 0;    totdltime[0] = 0LL;
501       ToFTrkVar  *o = 0;    totdltime[1] = 0LL;
502          totdltime[2] = 0LL;
503       if(CAL) c = GetCaloStoredTrack(t->GetSeqNo());  
504       if(TOF) o = GetToFStoredTrack(t->GetSeqNo());    host = "mysql://localhost/pamelaprod";
505          user = "anonymous";
506  //    if(t && c && o)track = new PamTrack(t,c,o);    psw = "";
507       PamTrack *track = new PamTrack(t,c,o);    const char *pamdbhost = gSystem->Getenv("PAM_DBHOST");
508          const char *pamdbuser = gSystem->Getenv("PAM_DBUSER");
509       return track;    const char *pamdbpsw = gSystem->Getenv("PAM_DBPSW");
510      if (!pamdbhost)
511   };      pamdbhost = "";
512  //--------------------------------------    if (!pamdbuser)
513  //      pamdbuser = "";
514  //    if (!pamdbpsw)
515  //--------------------------------------      pamdbpsw = "";
516      if (strcmp(pamdbhost, ""))
517        host = pamdbhost;
518      if (strcmp(pamdbuser, ""))
519        user = pamdbuser;
520      if (strcmp(pamdbpsw, ""))
521        psw = pamdbpsw;
522    
523      //    sorted_tracks = 0;//new TRefArray();
524    
525      CAL0 = false;
526      CAL1 = true;
527      CAL2 = true;
528      TRK2 = true;
529      TRK1 = false;
530      TRK0 = false;
531      TRKh = false;
532      TRG = true;
533      TOF = true;
534      TOF0 = false;
535      S4 = true;
536      ND = true;
537      AC = true;
538      ORB = true;
539      GP = false;
540    
541      RUN = true;
542    
543      SELLI = -1;
544    
545      ISGP = false;
546    
547      DBG = false;
548    
549      tsorted = 0;
550      timage = 0;
551    
552      howtosort = "+CAL+TOF";
553      //howtosort = "+TOF";
554      sortthr = 100.;
555    
556      issorted = false;
557      lastsorted = -1;
558    
559    }
560    ;
561  /**  /**
562   * Retrieves the it-th stored track.   * Delete the event (act as Dtor)
  * It override TrkLevel2::GetTrack(int it).  
  * @param itrk Track number, ranging from 0 to GetNTracks().  
563   */   */
564    void PamLevel2::Delete() {
565    
566  PamTrack* PamLevel2::GetStoredTrack(Int_t itrk){    if (run_obj)
567            delete run_obj;
568      PamTrack *track = 0;    if (soft_obj)
569            delete soft_obj; //Emiliano
570      if( itrk >=0 && itrk < TrkLevel2::ntrk() ){  
571              //    cout << "void PamLevel2::Clear()"<<endl;
572          TrkTrack *t = TrkLevel2::GetStoredTrack(itrk);    if (h0_obj)
573          track = GetPamTrackAlong(t);      delete h0_obj;
574              if (trk0_obj)
575      }else{      delete trk0_obj;
576          cout << "PamLevel2::GetStoredTrack(int) : tracker track SeqNo "<< itrk <<" does not exist (GetNTracks() = "<<TrkLevel2::GetNTracks()<<")"<<endl;    if (calo0_obj)
577        delete calo0_obj;
578      if (trk1_obj)
579        delete trk1_obj;
580      if (trk2_obj)
581        delete trk2_obj;
582      if (trkh_obj)
583        delete trkh_obj;
584      if (calo1_obj)
585        delete calo1_obj;
586      if (calo2_obj)
587        delete calo2_obj;
588      if (tof_obj)
589        delete tof_obj;
590      if (trig_obj)
591        delete trig_obj;
592      if (s4_obj)
593        delete s4_obj;
594      if (nd_obj)
595        delete nd_obj;
596      if (ac_obj)
597        delete ac_obj;
598      if (orb_obj)
599        delete orb_obj;
600      if (gp_obj)
601        delete gp_obj;
602    
603      if (tsorted) {
604        tsorted->Delete();
605        delete tsorted;
606      }
607      if (timage) {
608        timage->Delete();
609        delete timage;
610      }
611    
612      if (dbc) {
613        dbc->Close();
614        delete dbc;
615        dbc=0;
616      }
617    
618      if (gltsync)
619        delete gltsync;
620    
621      if (l0_file)
622        l0_file->Close();
623      //    if(pam_tree)pam_tree->Delete();;
624    
625      if (pam_tree) {
626        //
627        // we have first to find which chains we have to delete, then delete the main chain and only after delete the friend chains. Any other order causes a segfault...
628        //
629        TList *temp = pam_tree->GetListOfFriends();
630        TList *contents = new TList; // create chain friend list
631        contents->SetOwner();
632        TIter next(temp);
633        TChain *questo = 0;
634        while ((questo = (TChain*) next())) {
635          TString name = questo->GetName();
636          contents->Add((TChain*) gROOT->FindObject(name.Data()));// add object to the list
637      };      };
638            //
639      return track;      // deleting the main chain
640            //
641        pam_tree->Delete();
642        //
643        // deleting the friends...
644        //
645        TIter next2(contents);
646        TChain *questa = 0;
647        while ( (questa = (TChain*)next2()) ) {
648          TString name = questa->GetName();
649          questa->Delete();
650          questa = NULL;
651        };
652        //
653      };
654      pam_tree = NULL;
655    
656      if (run_tree)
657        run_tree->Delete();;
658      if (sel_tree)
659        sel_tree->Delete();;
660    
661      // The following lines are commented out since they may generate a double delete error
662      // if the file containing the clone trees is closed. This is because the file owns the
663      // clone trees which are written into it, so it will delete them when it is closed; if
664      // also PamLevel2 will try to delete these trees, a double delete error will be generated
665      // when exiting from analysis program. (Nicola 28/11/2011)
666    
667      /*for (Int_t i = 0; i < NCLONES; i++)
668        if (pam_tree_clone[i])
669          pam_tree_clone[i]->Delete();;
670      if (run_tree_clone)
671        run_tree_clone->Delete();;
672      if (sel_tree_clone)
673        sel_tree_clone->Delete();;*/
674    
675      if (irunoffset)
676        delete[] irunoffset;
677    
678  }  }
679  //--------------------------------------  ;
680  //  
 //  
 //--------------------------------------  
681  /**  /**
682   * Sort physical (tracker) tracks and stores them in the TRefArray (of TrkTrack objects) which pointer is  PamLevel2::sorted_tracks.   * Clear the event (NB! does not deallocate objects)
  * @param how String to set the sorting cryterium (es: "CAL" or "TRK+CAL+TOF" ecc...).  
  * Sorting cryteria:  
  * TRK: lower chi**2  
  * CAL: lower Y spatial residual on the first calorimeter plane  
  * TOF: bigger numebr of hit PMTs along the track, on S12 S21 S32 (where paddles are along the Y axis).  
  * The default sorting cryterium is "TOF+CAL".  
  *  
  * The total number of physical tracks is always given by GetNTracks() and the it-th physical track can be retrieved by means of the methods GetTrack(int it) and GetTrack(int it, TString how).  
683   */   */
684  void PamLevel2::SortTracks(TString how){  void PamLevel2::Clear() {
685    
686    //Save current Object count    //    cout << "void PamLevel2::Clear()"<<endl;
687      Int_t ObjectNumber = TProcessID::GetObjectCount();  
688          //
689      sorted_tracks->Delete(); //temporaneo???    // This method is called once for every entry but RunInfo and SoftInfo do not change until the next run so we cannot clear them here unless we don't
690              // want to load them for each event even if they are the same...
691      // loop over the tracks sorted by the tracker    //
692      Bool_t use_TRK = how.Contains("TRK", TString::kIgnoreCase);    //    if(run_obj)delete run_obj;
693      Bool_t use_CAL = how.Contains("CAL", TString::kIgnoreCase);    //    if(run_obj) run_obj->Clear();  // Emiliano: Do not deallocate run_obj here, it will give segmentation fault! call clear instead
694      Bool_t use_TOF = how.Contains("TOF", TString::kIgnoreCase);    //    if(soft_obj) soft_obj->Clear();
695        
696      if( !CAL &&  use_CAL) use_CAL = false;    if (h0_obj)
697      if( !TOF &&  use_TOF) use_TOF = false;      h0_obj->Clear();
698          //    if(trk0_obj) trk0_obj->Clear();
699      if( !TRK ){    if (trk1_obj)
700          cout << "SortTracks() : without tracker does not work!!! (not yet)" << endl;      trk1_obj->Clear();
701          return;    if (trk2_obj)
702        trk2_obj->Clear();
703      if (trkh_obj)
704        trkh_obj->Clear();
705      if (calo0_obj)
706        calo0_obj->Clear();
707      if (calo1_obj)
708        calo1_obj->Clear();
709      if (calo2_obj)
710        calo2_obj->Clear();
711      if (tof_obj)
712        tof_obj->Clear();
713      if (trig_obj)
714        trig_obj->Clear();
715      if (s4_obj)
716        s4_obj->Clear();
717      if (nd_obj)
718        nd_obj->Clear();
719      if (ac_obj)
720        ac_obj->Clear();
721      if (orb_obj)
722        orb_obj->Clear();
723      if (gp_obj)
724        gp_obj->Clear();
725    
726      //    if(sorted_tracks)sorted_tracks->Clear();
727      //    sorted_tracks.Clear();
728    
729      if (tsorted) {
730        tsorted->Delete();
731      }
732      if (timage) {
733        timage->Delete();
734      }
735    }
736    ;
737    
738    void PamLevel2::Reset() {
739      //
740      // First of all clear everything
741      //
742      Clear();
743      //
744      // close and reset chains and pointers
745      //
746      if (pam_tree) {
747        //
748        // we have first to find which chains we have to delete, then delete the main chain and only after delete the friend chains. Any other order causes a segfault...
749        //
750        TList *temp = pam_tree->GetListOfFriends();
751        TList *contents = new TList; // create chain friend list
752        contents->SetOwner();
753        TIter next(temp);
754        TChain *questo = 0;
755        while ((questo = (TChain*) next())) {
756          TString name = questo->GetName();
757          contents->Add((TChain*) gROOT->FindObject(name.Data()));// add object to the list
758      };      };
759            //
760      for(Int_t i=0; i < TrkLevel2::GetNTracks(); i++){      // deleting the main chain
761                //
762          TrkTrack *ts = 0;      pam_tree->Delete();
763                //
764          // get tracker tracks      // deleting the friends...
765          TrkTrack   *tp = TrkLevel2::GetTrack(i);                    //tracker      //
766  //              CaloTrkVar *cp = GetCaloStoredTrack(tp->GetSeqNo());      TIter next2(contents);
767  //              ToFTrkVar  *op = GetToFStoredTrack(tp->GetSeqNo());      TChain *questa = 0;
768          CaloTrkVar *cp = 0;      while ( (questa = (TChain*) next2()) ) {
769          ToFTrkVar  *op = 0;        TString name = questa->GetName();
770                  questa->Delete();
771          // if track has an image, check image selection        questa = NULL;
772          if(tp->HasImage()){      };
773                    //
774              TrkTrack   *ti = TrkLevel2::GetTrackImage(i);              //tracker (image)    };
775  //                      CaloTrkVar *ci = GetCaloStoredTrack(ti->GetSeqNo());    pam_tree = NULL;
776  //                      ToFTrkVar  *oi = GetToFStoredTrack(ti->GetSeqNo());    //
777              CaloTrkVar *ci = 0;    if (run_tree)
778              ToFTrkVar  *oi = 0;      run_tree->Delete();;
779                  run_tree = NULL;
780              //assign starting scores    if (sel_tree)
781              Int_t tp_score = 0;  //main track sorted by the tracker      sel_tree->Delete();;
782              Int_t ti_score = 0;  //image track    sel_tree = NULL;
783                  //
784              // ------------------------    // Close file
785              // calorimeter check    //
786              // ------------------------    if (l0_file)
787              // check the Y spatial residual on the first calorimeter plane      l0_file->Close("R");
788              // (cut on calorimeter variables from Emiliano)    l0_file = NULL;
789              if(    //
790                  use_CAL            &&    h0_obj = 0;
791                  npcfit[1] > 15     &&   //no. of fit planes on Y view    trk0_obj = 0;
792                  varcfit[1] < 1000. &&  //fit variance on Y view    calo0_obj = 0;
793                  true){    //
794                      trk2_obj = 0;
795                  cp = GetCaloStoredTrack(tp->GetSeqNo());    trk1_obj = 0;
796                  ci = GetCaloStoredTrack(ti->GetSeqNo());    trkh_obj = 0;
797                      calo1_obj = 0;
798                  Float_t resy_p = cp->tbar[0][1] - cbar[0][1]; if(resy_p < 0)resy_p= - resy_p;    calo2_obj = 0;
799                  Float_t resy_i = ci->tbar[0][1] - cbar[0][1]; if(resy_i < 0)resy_i= - resy_i;    tof_obj = 0;
800                      trig_obj = 0;
801                  if(resy_p <= resy_i) tp_score++;    s4_obj = 0;
802                  else                 ti_score++;    nd_obj = 0;
803              };    ac_obj = 0;
804              // ------------------------    orb_obj = 0;
805              // TOF check    gp_obj = 0;
806              // ------------------------        //
807              // check the number of hit pmts along the track    // Reset run pointers
808              // on S12 S21 and S32, where paddles are parallel to Y axis    //
809              if( use_TOF ){    run_obj = 0;//new GL_RUN();
810                      soft_obj = 0;// Emiliano
811                  Int_t nphit_p =0;    irun = -1;
812                  Int_t nphit_i =0;    irunt = -1;
813                      totrunentry = 0LL;
814                  op = GetToFStoredTrack(tp->GetSeqNo());    totrunentrymax = 0LL;
815                  oi = GetToFStoredTrack(ti->GetSeqNo());    totrunentrymin = 0LL;
816                      runfirstentry = 0ULL;
817  /*                              cout << "track: npmtadc "<< op->npmtadc << endl;    runlastentry = 0ULL;
818                                  cout << "track: npmttdc "<< op->npmttdc << endl;    prevabstime = 0ULL;
819                                  cout << "image: npmtadc "<< oi->npmtadc << endl;    prevpktnum = 0;
820                                  cout << "image: npmttdc "<< oi->npmttdc << endl;*/    abstime = 0ULL;
821                      pktnum = 0;
822                  for (Int_t ih=0; ih < op->npmtadc; ih++){    isFragment = false;
823                      Int_t pl = GetPlaneIndex( (op->pmtadc).At(ih) );    //
824                      if(pl == 1 || pl == 2 || pl == 5)nphit_p++;    totdltime[0] = 0LL;
825                  };    totdltime[1] = 0LL;
826                      totdltime[2] = 0LL;
827                  for (Int_t ih=0; ih < oi->npmtadc; ih++){    //
828                      Int_t pl = GetPlaneIndex( (oi->pmtadc).At(ih) );  }
829                      if(pl == 1 || pl == 2 || pl == 5)nphit_i++;  ;
830                  };  
831                    Bool_t PamLevel2::IsGood(Bool_t strict) {
832                  if(    Bool_t goodev = true;
833                      use_TOF            &&    //
834                      (nphit_p+nphit_i) !=0 &&        if (calo2_obj && !calo2_obj->IsGood(strict))
835                      true){      goodev = false;
836                          //
837                      if( nphit_p >= nphit_i) tp_score++;    if (strict) {
838                      else ti_score++;      if (trk2_obj && trk2_obj->UnpackError() != 0)
839                  };        goodev = false;
840              };      if (tof_obj && tof_obj->unpackError != 0)
841              if(tp_score == ti_score) use_TRK = true;        goodev = false;
842              // ------------------------      if (trig_obj && trig_obj->unpackError != 0)
843              // tracker check        goodev = false;
844              // ------------------------      if (s4_obj && s4_obj->unpackError != 0)
845              // chi**2 difference is not always large enough to distinguish among        goodev = false;
846              // the real track and its image.      if (nd_obj && nd_obj->unpackError != 0)
847              // Tracker check will be applied always when calorimeter and tof information is ambiguous.        goodev = false;
848              if(use_TRK){      if (ac_obj && (ac_obj->unpackError != 0 || ((ac_obj->status[0] >> 2) & 1) || ((ac_obj->status[1] >> 2) & 1)))
849                  if(      tp->chi2 > 0 && tp->chi2 < ti->chi2 ) tp_score++ ;        goodev = false;
850                  else if( ti->chi2 > 0 && ti->chi2 < tp->chi2 ) ti_score++ ;      //  if(orb_obj)
851              };    }
852                  else {
853              // ------------------------      if (nd_obj && nd_obj->unpackError != 0)
854              // the winner is....        goodev = false;
855              // ------------------------          if (ac_obj && (ac_obj->unpackError != 0 || ((ac_obj->status[0] >> 2) & 1) || ((ac_obj->status[1] >> 2) & 1)))
856              if      (tp_score > ti_score) ts = tp;//the track sorted by the tracker!!        goodev = false;
857              else if (tp_score < ti_score) ts = ti;//its image!!    };
858              else {    return (goodev);
859                  ts = tp;  }
860  //                              cout << "Warning - track image ambiguity not solved" << endl;  ;
861  //                              cout << ts->GetNtot() << " "<< ts->chi2 << " " << npcfit[1] << " "<< nphit_p << endl;  
862              };  void PamLevel2::SkipRunInfoUpdate(){
863                  printf("\n\n ******** WARNING ******** \n Skip DB connections, DO NOT USE PamLevel2::GetRunInfo() method! \n\n");
864          }else{    fUpdateRunInfo = false;
865              ts = tp;    this->SetSELLI(2);
866          };    printf(" ===============> W A R N I N G <================ \n");
867              printf(" in case PamLevel2::CreateCloneTrees() will be called \n");
868  //              cout <<" SortTracks() "<<i<<" -- "<<ts<<endl;    printf(" it will be reverted to PadmeAmidala level2 structure , i.e. NO SELECTIONLIST WILL BE CREATED IN THE NEW LEVEL2 FILE! \n\n");
869          sorted_tracks->Add(ts);//save the track in the sorted array    if ( run_tree_clone ){
870  //              cout << "SortTracks:: sorted_tracks->Add(it) "<<i<<" "<<ts<<endl;      printf(" ===============> W A R N I N G <================ \n");
871                printf(" PamLevel2::SkipRunIndoUpdate or PamLevel2::NoDBconnections() has been called together with PamLevel2::CreateCloneTrees() \n");
872      };      printf(" TO AVOID CRASHES call PamLevel2::CreateCloneTrees() after PamLevel2::SkipRunIndoUpdate or PamLevel2::NoDBconnections() \n");    
873      //Restore Object count    };
874      //To save space in the table keeping track of all referenced objects  }
875      //we assume that our events do not address each other. We reset the  
876      //object count to what it was at the beginning of the event.  void PamLevel2::SetMaxShift(Int_t sh){
877      TProcessID::SetObjectCount(ObjectNumber);    if ( sh >=  0 ){
878            printf("PamLevel2::SetMaxShift(Int_t) --WARNING-- the default is optimized by checking the level2 file\n it is strongly suggested to let PamLevel2 choose the max shift!\n");
879  };      maxshift = sh;
880      } else {
881        ULong64_t nev = this->GetEntries();
882        ULong64_t runnev = 0ULL;
883        for (Int_t r=0; r< run_tree->GetEntries();r++){
884          run_tree->GetEntry(r);//update runinfo
885          runnev += GetRunInfo()->NEVENTS;
886        }
887        maxshift = (Int_t)(runnev-nev) + 10; // +10 just to be conservative
888        if ( (runnev-nev) == 0 ) isSync = true;
889        if (DBG) printf("PamLevel2::SetMaxShift(Int_t_) - sh negative %i - nev is %lld runnnev is %lld so maxshift set to %i \n",sh,nev,runnev,maxshift);
890        //    printf("PamLevel2::SetMaxShift(Int_t_) - sh negative %i - nev is %lld runnnev is %lld so maxshift set to %i \n",sh,nev,runnev,maxshift); // TOGLITOGLI
891      }
892    }
893    
894  //--------------------------------------  //--------------------------------------
895  //  //
896  //  //
897  //--------------------------------------  //--------------------------------------
898  /**  void *PamLevel2::GetPointerTo(const char* c) {
  * This method overrides TrkLevel2::GetTracks(), where sorting is done by decreasing number of fit points and increasing chi^2.  
  * PamLevel2::GetTracks() keeps the same track order given by TrkLevel2::GetTracks(), but checks image selection by using calorimeter and ToF tracking information.  
  */  
  TRefArray *PamLevel2::GetTracks(){  
          //  
 //      SortTracks("+CAL+TOF");  
          SortTracks("+CAL+TRK");//TEMP!!!!!!!!!!!!!  
         //  
         return sorted_tracks;  
  };  
 //--------------------------------------  
  //  
  //  
 //--------------------------------------  
 /**  
  * Retrieves the it-th Pamela "physical" track.  
  * It override TrkLevel2::GetTrack(int it).  
  * @param it Track number, ranging from 0 to GetNTracks().  
  */  
 PamTrack *PamLevel2::GetTrack(int it){  
           
 //  *-*-*-*-*-*-*  
 //      SortTracks("+CAL+TOF");  
     SortTracks("+CAL+TRK");//TEMP!!!!!!!!!!!!!  
 //  *-*-*-*-*-*-*  
899    
900      PamTrack *track = 0;    TString objname = c;
901        
902      if( it >=0 && it < TrkLevel2::GetNTracks() && it<sorted_tracks->GetEntriesFast() ){    if (!objname.CompareTo("TrkLevel1")) {
903          TrkTrack   *t = (TrkTrack*)sorted_tracks->At(it);      if (!trk1_obj) {
904          track = GetPamTrackAlong(t);        trk1_obj = new TrkLevel1();
905      }else{        trk1_obj->Set();
906          cout << "PamLevel2::GetTrack(int) : tracker track SeqNo "<< it <<" does not exist (GetNTracks() = "<<TrkLevel2::GetNTracks()<<")"<<endl;      }
907        return &trk1_obj;
908      };
909      if (!objname.CompareTo("TrkLevel2")) {
910        if (!trk2_obj) {
911          trk2_obj = new TrkLevel2();
912          trk2_obj->Set();
913        }
914        return &trk2_obj;
915      };
916      if (!objname.CompareTo("TrkHough")) {
917        if (!trkh_obj) {
918          trkh_obj = new TrkHough();
919          trkh_obj->Set();
920        }
921        return &trkh_obj;
922      };
923      if (!objname.CompareTo("CaloLevel1")) {
924        if (!calo1_obj)
925          calo1_obj = new CaloLevel1();
926        return &calo1_obj;
927      };
928      if (!objname.CompareTo("CaloLevel2")) {
929        if (!calo2_obj) {
930          calo2_obj = new CaloLevel2();
931          calo2_obj->Set();
932      };      };
933            return &calo2_obj;
934      return track;    };
935          if (!objname.CompareTo("ToFLevel2")) {
936  };      if (!tof_obj) {
937          tof_obj = new ToFLevel2();
938          tof_obj->Set();
939        }
940        return &tof_obj;
941      };
942      if (!objname.CompareTo("TrigLevel2")) {
943        if (!trig_obj)
944          trig_obj = new TrigLevel2();
945        return &trig_obj;
946      };
947      if (!objname.CompareTo("S4Level2")) {
948        if (!s4_obj)
949          s4_obj = new S4Level2();
950        return &s4_obj;
951      };
952      if (!objname.CompareTo("NDLevel2")) {
953        if (!nd_obj)
954          nd_obj = new NDLevel2();
955        return &nd_obj;
956      };
957      if (!objname.CompareTo("AcLevel2")) {
958        if (!ac_obj)
959          ac_obj = new AcLevel2();
960        return &ac_obj;
961      };
962      if (!objname.CompareTo("OrbitalInfo")) {
963        if (!orb_obj) {
964          orb_obj = new OrbitalInfo();
965          orb_obj->Set();
966        }
967        return &orb_obj;
968      };
969      //     if(!objname.CompareTo("OrbitalInfo")){
970      //    if(!orb_obj)   orb_obj   = new OrbitalInfo();
971      //    return &orb_obj;
972      //     };
973      if (!objname.CompareTo("GPamela")) {
974        if (!gp_obj)
975          gp_obj = new GPamela();
976        return &gp_obj;
977      };
978    
979      if (!objname.CompareTo("RunInfo"))
980        return &run_obj;
981    
982      if (!objname.CompareTo("SoftInfo"))
983        return &soft_obj; // Emiliano
984    
985      return NULL;
986    }
987    ;
988  //--------------------------------------  //--------------------------------------
989  //  //
990  //  //
991  //--------------------------------------  //--------------------------------------
992  /**  /**
993   * Retrieves (if present) the image of the it-th Pamela "physical" track, sorted by the method PamLevel2::SortTracks().   * Retrieves the calorimeter track matching the seqno-th tracker stored track.
994   * @param it Track number, ranging from 0 to GetNTracks().   * (If seqno = -1 retrieves the self-trigger calorimeter track)
995   */   */
996  PamTrack *PamLevel2::GetTrackImage(int it){  CaloTrkVar *PamLevel2::GetCaloStoredTrack(int seqno) {
997    
998  //      SortTracks("+CAL+TOF");    if (!calo2_obj)
999          SortTracks("+CAL+TRK");//TEMP!!!!!!!!!!!!!      return 0;
           
         PamTrack *image = 0;  
   
         if( it >=0 && it < TrkLevel2::GetNTracks() ){  
                 TrkTrack *temp = (TrkTrack*)sorted_tracks->At(it);  
                 if( temp->HasImage() ){  
                         TrkTrack   *t = TrkLevel2::GetStoredTrack(temp->GetImageSeqNo());  
                         image = GetPamTrackAlong(t);  
                 }else{  
                         cout <<"PamLevel2::GetTrackImage(int) : Track SeqNo "<<it<<" does not have image"<<endl;  
                 };  
         }else{  
                 cout << "PamLevel2::GetTrackImage(int) : Tracker track SeqNo "<< it <<" does not exist (GetNTracks() = "<<TrkLevel2::GetNTracks()<<")"<<endl;  
         };  
       
         return image;  
 }  
1000    
1001      if (calo2_obj->CaloLevel2::ntrk() == 0) {
1002        cout << "PamLevel2::GetCaloStoredTrack(int) : requested tracker SeqNo " << seqno
1003            << " but no Calorimeter tracks are stored" << endl;
1004        return NULL;
1005      };
1006    
1007      CaloTrkVar *c = 0;
1008      Int_t it_calo = 0;
1009    
1010      do {
1011        c = calo2_obj->CaloLevel2::GetCaloTrkVar(it_calo);
1012        it_calo++;
1013      } while (c && seqno != c->trkseqno && it_calo < calo2_obj->CaloLevel2::ntrk());
1014    
1015      if (!c || seqno != c->trkseqno) {
1016        c = 0;
1017        if (seqno != -1)
1018          cout << "PamLevel2::GetCaloStoredTrack(int) : requested tracker SeqNo " << seqno
1019              << " does not match Calorimeter stored tracks" << endl;
1020      };
1021      return c;
1022    
1023    }
1024    ;
1025  //--------------------------------------  //--------------------------------------
1026  //  //
1027  //  //
1028  //--------------------------------------  //--------------------------------------
1029  /**  /**
1030   * Get the Pamela detector trees in a single file and make them friends.   * Retrieves the ToF track matching the seqno-th tracker stored track.
1031   * @param f TFile pointer   * (If seqno = -1 retrieves the tracker-independent tof track)
  * @param detlist String to select trees to be included  
  * @return Pointer to a TTree  
1032   */   */
1033  TTree *PamLevel2::GetPamTree(TFile *f, TString detlist="+ALL"){  ToFTrkVar *PamLevel2::GetToFStoredTrack(int seqno) {
1034    
1035      if (!tof_obj)
1036        return 0;
1037    
1038      if (tof_obj->ToFLevel2::ntrk() == 0) {
1039        cout << "PamLevel2::GetToFStoredTrack(int) : requested tracker SeqNo " << seqno << " but no ToF tracks are stored"
1040            << endl;
1041        return NULL;
1042      };
1043    
1044      ToFTrkVar *c = 0;
1045      Int_t it_tof = 0;
1046    
1047      do {
1048        c = tof_obj->ToFLevel2::GetToFTrkVar(it_tof);
1049        it_tof++;
1050      } while (c && seqno != c->trkseqno && it_tof < tof_obj->ToFLevel2::ntrk());
1051    
1052      if (!c || seqno != c->trkseqno) {
1053        c = 0;
1054        if (seqno != -1)
1055          cout << "PamLevel2::GetToFStoredTrack(int) : requested tracker SeqNo " << seqno
1056              << " does not match ToF stored tracks" << endl;
1057      };
1058      return c;
1059    
 //      cout << "WARNING!!! -- obsolete method -- \n";  
 //      cout << "better use TChain *PamLevel2::GetPamTree(TList*, TString) \n";  
           
     TTree *Trout =0;  
       
     SetWhichTrees(detlist);  
 // Tracker  
     TTree *T = (TTree*)f->Get("Tracker");  
     if(T && TRK) {  
         if(TRK_L1){  
             T->SetBranchAddress("TrkLevel1", GetPointerToTrk(1));  
             cout << "Tracker      : set branch address TrkLevel1"<<endl;  
         };  
         T->SetBranchAddress("TrkLevel2", GetPointerToTrk(2));  
         cout << "Tracker      : set branch address TrkLevel2"<<endl;  
         Trout=T;  
     }else{  
         cout << "Tracker      : missing tree"<<endl;  
     };  
     // Calorimeter  
     TTree *C = (TTree*)f->Get("Calorimeter");  
     if(C && CAL) {  
         C->SetBranchAddress("CaloLevel2", GetPointerToCalo());  
         cout << "Calorimeter  : set branch address CaloLevel2"<<endl;  
         if(!Trout)Trout=C;  
         else Trout->AddFriend(C);  
     }else{  
         cout << "Calorimeter  : missing tree"<<endl;  
     };  
     // ToF      
     TTree *O = (TTree*)f->Get("ToF");  
     if(O && TOF) {  
         O->SetBranchAddress("ToFLevel2", GetPointerToToF());  
         cout << "ToF          : set branch address ToFLevel2"<<endl;  
         if(!Trout)Trout=O;  
         else Trout->AddFriend(O);  
     }else{  
         cout << "ToF         : missing tree"<<endl;  
     };  
     // Trigger  
     TTree *R = (TTree*)f->Get("Trigger");  
     if(R && TRG) {  
         R->SetBranchAddress("TrigLevel2", GetPointerToTrig());  
         cout << "Trigger      : set branch address TrigLevel2"<<endl;  
         if(!Trout)Trout=O;  
         else Trout->AddFriend(R);  
     }else{  
         cout << "Trigger      : missing tree"<<endl;  
     };  
     // S4  
     TTree *S = (TTree*)f->Get("S4");  
     if(S && S4) {  
         S->SetBranchAddress("S4Level2", GetPointerToS4());  
         cout << "S4           : set branch address S4Level2"<<endl;  
         if(!Trout)Trout=O;  
         else Trout->AddFriend(S);  
     }else{  
         cout << "S4           : missing tree"<<endl;  
     };  
     // Neutron Detector  
     TTree *N = (TTree*)f->Get("NeutronD");  
     if(N && ND) {  
         N->SetBranchAddress("NDLevel2", GetPointerToND());  
         cout << "NeutronD     : set branch address NDLevel2"<<endl;  
         if(!Trout)Trout=O;  
         else Trout->AddFriend(N);  
     }else{  
         cout << "NeutronD     : missing tree"<<endl;  
     };  
     // Anticounters  
     TTree *A = (TTree*)f->Get("Anticounter");  
     if(A && AC) {  
         A->SetBranchAddress("AcLevel2", GetPointerToAc());  
         cout << "Anticounter  : set branch address AcLevel2"<<endl;  
         if(!Trout)Trout=O;  
         else Trout->AddFriend(A);  
     }else{  
         cout << "Anticounter  : missing tree"<<endl;  
     };  
     // Orbital Info  
         TTree *B = (TTree*)f->Get("OrbitalInfo");  
         if(B && ORB) {  
                 B->SetBranchAddress("OrbitalInfo", GetPointerToOrb());  
                 cout << "OrbitalInfo  : set branch address OrbitalInfo"<<endl;  
                 if(!Trout)Trout=O;  
                 else Trout->AddFriend(B);  
         }else{  
                 cout << "OrbitalInfo  : missing tree"<<endl;  
         };  
       
         cout<<endl<<" Number of entries: "<<Trout->GetEntries()<<endl<<endl;  
           
         return Trout;  
       
1060  }  }
1061    ;
1062    
1063  //--------------------------------------  //--------------------------------------
1064  //  //
1065  //  //
1066  //--------------------------------------  //--------------------------------------
1067  /**  /**
1068   * Get list of Level2 files.   * Retrieves the OrbitalInfo track matching the seqno-th tracker stored track.
1069   * @param ddir Level2 data directory.   * (If seqno = -1 retrieves the tracker-independent tof related track)
  * @param flisttxt Name of txt file containing file list.  
  * @return Pointer to a TList of TSystemFiles  
  * If no input file list is given , all the Level2 files inside the directory are processed.  
1070   */   */
1071  TList*  PamLevel2::GetListOfLevel2Files(TString ddir, TString flisttxt = ""){  OrbitalInfoTrkVar *PamLevel2::GetOrbitalInfoStoredTrack(int seqno) {
1072            
1073      TString wdir = gSystem->WorkingDirectory();    if (!orb_obj)
1074            return 0;
1075      if(ddir=="")ddir = wdir;  
1076  //      TSystemDirectory *datadir = new TSystemDirectory(gSystem->BaseName(ddir),ddir);    if (orb_obj->OrbitalInfo::ntrk() == 0) {
1077      cout << "Level2 data directory : "<<  ddir << endl;      //       // TRICK BEGIN
1078            //       OrbitalInfoTrkVar  *r = new OrbitalInfoTrkVar(); // TEMPORARY TRICK
1079      TList *contents  = new TList; // create output list      //       Int_t nn = 0;
1080      contents->SetOwner();      //       TClonesArray &tor = *orb_obj->OrbitalInfoTrk;
1081            //       for(Int_t nt=0; nt < tof_obj->ToFLevel2::ntrk(); nt++){
1082      char *fullpath;      //  //
1083            //  ToFTrkVar *ptt = tof_obj->ToFLevel2::GetToFTrkVar(nt);
1084      // if no input file list is given:        //  if ( ptt->trkseqno != -1  ){
1085      if ( flisttxt != "" ){      //    //
1086                //    r->trkseqno = ptt->trkseqno;
1087          if( !gSystem->IsFileInIncludePath(flisttxt,&fullpath) )return 0;      //    //
1088                //    r->Eij = 0;
1089  //              flisttxt = gSystem->ConcatFileName(gSystem->DirName(flisttxt),gSystem->BaseName(flisttxt));      //    //
1090          flisttxt = fullpath;      //    r->Sij = 0;
1091                //    //
1092          if( !gSystem->ChangeDirectory(ddir) )return 0;      //    r->pitch = -1000.;
1093                //    //
1094          cout <<"Input file list : " << flisttxt <<endl;      //    r->cutoff = -1000.;
1095          ifstream in;      //    //
1096          in.open(flisttxt, ios::in); //open input file list      //    new(tor[nn]) OrbitalInfoTrkVar(*r);
1097          while (1) {      //    nn++;
1098              TString file;      //    //
1099              in >> file;      //    r->Clear();
1100              if (!in.good()) break;      //    //
1101              if( gSystem->IsFileInIncludePath(file,&fullpath) ){      //  };
1102  //                              contents->Add(new TSystemDirectory(fullpath,ddir)); // add file to the list      //       };
1103  //                              contents->Add(new TSystemFile(fullpath,ddir)); // add file to the list      //       delete r;
1104                  contents->Add(new TSystemFile(fullpath,gSystem->DirName(fullpath)));// add file to the list      //       OrbitalInfoTrkVar *c = 0;
1105              }else{      //       c = orb_obj->OrbitalInfo::GetOrbitalInfoTrkVar(0);
1106                  cout << "warning! --- File "<<file<<" does not exists"<< endl;      //       return c;
1107              };      //       //TRICK END
1108          };      cout << "PamLevel2::GetOrbitalInfoStoredTrack(int) : requested tracker SeqNo " << seqno
1109          in.close();          << " but no OrbitalInfo tracks are stored" << endl;
1110                return NULL;
1111      }else{    };
1112            
1113          cout << "No input file list given."<<endl;    OrbitalInfoTrkVar *c = 0;
1114          cout << "Check for existing root files."<<endl;    Int_t it_tof = 0;
1115  //              cout << "Warking directory: "<< gSystem->WorkingDirectory()<< endl;  
1116              do {
1117          TSystemDirectory *datadir = new TSystemDirectory(gSystem->BaseName(ddir),ddir);      c = orb_obj->OrbitalInfo::GetOrbitalInfoTrkVar(it_tof);
1118          TList *temp = datadir->GetListOfFiles();      it_tof++;
1119  //              temp->Print();    } while (c && seqno != c->trkseqno && it_tof < orb_obj->OrbitalInfo::ntrk());
1120  //              cout << "*************************************" << endl;  
1121              if (!c || seqno != c->trkseqno) {
1122          TIter next(temp);      c = 0;
1123          TSystemFile *questo = 0;      if (seqno != -1)
1124                  cout << "PamLevel2::GetOrbitalInfoStoredTrack(int) : requested tracker SeqNo " << seqno
1125                      << " does not match OrbitalInfo stored tracks" << endl;
1126          while ( (questo = (TSystemFile*) next()) ) {    };
1127              TString name =  questo-> GetName();    return c;
1128              if( name.EndsWith(".root") ){  
1129                  char *fullpath;  }
1130                  gSystem->IsFileInIncludePath(name,&fullpath);  ;
1131                  contents->Add(new TSystemFile(fullpath,gSystem->DirName(fullpath)));  
             };  
         }  
         delete temp;  
         delete datadir;  
           
     };  
     gSystem->ChangeDirectory(wdir); // back to the working directory  
 //      cout << endl << "Selected files:" << endl;  
 //      contents->Print();  
     cout << contents->GetEntries()<<" files selected\n";  
 //      cout << endl;  
 //      cout << "Working directory: "<< gSystem->WorkingDirectory()<< endl;  
     return contents;  
 };  
1132  //--------------------------------------  //--------------------------------------
1133  //  //
1134  //  //
1135  //--------------------------------------  //--------------------------------------
1136  /**  /**
1137   * Get the Pamela detector chains from a list of files and make them friends.   * Give the pamela track associated to a tracker track, retrieving related calorimeter, orbitalinfo and tof track information.
  * @param fl Pointer to a TList of TSystemFiles  
  * @param detlist String to select trees to be included  
  * @return Pointer to a TChain  
1138   */   */
1139  TChain *PamLevel2::GetPamTree(TList *fl, TString detlist="+ALL"){  PamTrack* PamLevel2::GetPamTrackAlong(TrkTrack* t) {
1140    
1141  //      TChain *Tout=0;    cout << "PamLevel2::GetPamTrackAlong(TrkTrack* t) **obsolete** " << endl;
1142      if(Tout)Tout->Delete();    cout << "(if you use it, remember to delete the PamTrack object)" << endl;
1143      Tout = NULL;  
1144          CaloTrkVar *c = 0;
1145      SetWhichTrees(detlist);    ToFTrkVar *o = 0;
1146          OrbitalInfoTrkVar *r = 0;
1147      TChain *T = 0;        
1148      TChain *C = 0;    if (CAL2)
1149      TChain *O = 0;      c = GetCaloStoredTrack(t->GetSeqNo());
1150      TChain *R = 0;    if (TOF)
1151      TChain *S = 0;      o = GetToFStoredTrack(t->GetSeqNo());
1152      TChain *N = 0;    if (ORB)
1153      TChain *A = 0;      r = GetOrbitalInfoStoredTrack(t->GetSeqNo());
1154      TChain *B = 0;  
1155          //    if(t && c && o)track = new PamTrack(t,c,o);
1156      if(TRK) T = new TChain("Tracker");      PamTrack *track = new PamTrack(t, c, o, r);
1157      if(CAL) C = new TChain("Calorimeter");  
1158      if(TOF) O = new TChain("ToF");    return track;
     if(TRG) R = new TChain("Trigger");  
     if(S4)  S = new TChain("S4");  
     if(ND)  N = new TChain("NeutronD");  
     if(AC)  A = new TChain("Anticounter");  
     if(ORB) B = new TChain("OrbitalInfo");  
       
     // loop over files and create chains          
     TIter next(fl);  
     TSystemFile *questo = 0;  
     while ( (questo = (TSystemFile*) next()) ) {  
         TString name =  questo->GetName();  
 //              cout << "File: "<< name << endl;  
         if( CheckLevel2File(name) ){  
             if(TRK) T->Add(name);  
             if(CAL) C->Add(name);  
             if(TOF) O->Add(name);  
             if(TRG) R->Add(name);  
             if(S4)  S->Add(name);  
             if(ND)  N->Add(name);  
             if(AC)  A->Add(name);  
             if(ORB) B->Add(name);  
         };  
     }  
       
     cout << "done chain \n";  
1159    
     // Tracker  
     if(TRK) if(!Tout)Tout=T;  
     // Calorimeter  
     if(CAL) {            
         if(!Tout)Tout=C;  
         else Tout->AddFriend("Calorimeter");  
     };  
     // ToF      
     if(TOF) {  
         if(!Tout)Tout=O;  
         else Tout->AddFriend("ToF");  
     };  
     // Trigger  
     if(TRG) {  
         if(!Tout)Tout=O;  
         else Tout->AddFriend("Trigger");  
     };  
     // S4  
     if(S4) {  
         if(!Tout)Tout=O;  
         else Tout->AddFriend("S4");  
     };  
     // Neutron Detector  
     if(ND) {  
         if(!Tout)Tout=O;  
         else Tout->AddFriend("NeutronD");  
     };  
     // Anticounters  
     if(AC) {  
         if(!Tout)Tout=O;  
         else Tout->AddFriend("Anticounter");  
     };  
     // OrbitalInfo  
     if(ORB) {  
         if(!Tout)Tout=O;  
         else Tout->AddFriend("OrbitalInfo");  
     };  
       
 //    cout<<endl<<" Number of entries: "<<Tout->GetEntries()<<endl<<endl;  
       
     if( Tout->GetEntries() )PamLevel2::SetBranchAddress();  
       
     return Tout;  
1160  }  }
1161    ;
1162  //--------------------------------------  //--------------------------------------
1163  //  //
1164  //  //
1165  //--------------------------------------  //--------------------------------------
1166  /**  /**
1167   * Set branch addresses for Pamela friend trees   * Retrieves the it-th stored track.
1168     * It override TrkLevel2::GetTrack(int it).
1169     * @param itrk Track number, ranging from 0 to GetNTracks().
1170   */   */
 void PamLevel2::SetBranchAddress(){  
     // Tracker  
     if(TRK) {  
         if(TRK_L1){  
             Tout->SetBranchAddress("TrkLevel1", GetPointerToTrk(1));  
             cout << "Tracker      : set branch address TrkLevel1"<<endl;  
         };  
         Tout->SetBranchAddress("TrkLevel2", GetPointerToTrk(2));  
         cout << "Tracker      : set branch address TrkLevel2"<<endl;  
     };  
       
     // Calorimeter  
     if(CAL) {  
         Tout->SetBranchAddress("CaloLevel2", GetPointerToCalo());  
         cout << "Calorimeter  : set branch address CaloLevel2"<<endl;  
     };  
       
     // ToF      
     if(TOF) {  
         Tout->SetBranchAddress("ToFLevel2", GetPointerToToF());  
         cout << "ToF          : set branch address ToFLevel2"<<endl;  
     };  
     // Trigger  
     if(TRG) {  
         Tout->SetBranchAddress("TrigLevel2", GetPointerToTrig());  
         cout << "Trigger      : set branch address TrigLevel2"<<endl;  
     };  
     // S4  
     if(S4) {  
         Tout->SetBranchAddress("S4Level2", GetPointerToS4());  
         cout << "S4           : set branch address S4Level2"<<endl;  
     };  
     // Neutron Detector  
     if(ND) {  
         Tout->SetBranchAddress("NDLevel2", GetPointerToND());  
         cout << "NeutronD     : set branch address NDLevel2"<<endl;  
     };  
     // Anticounters  
     if(AC) {  
         Tout->SetBranchAddress("AcLevel2", GetPointerToAc());  
         cout << "Anticounter  : set branch address AcLevel2"<<endl;  
     };  
     // OrbitalInfo  
     if(ORB) {  
         Tout->SetBranchAddress("OrbitalInfo", GetPointerToOrb());  
         cout << "OrbitalInfo  : set branch address OrbitalInfo"<<endl;  
     };  
       
 }  
1171    
1172    PamTrack* PamLevel2::GetStoredTrack(Int_t itrk) {
1173    
1174      cout << "PamLevel2::GetStoredTrack(Int_t itrk) **to-be-updated** " << endl;
1175      cout
1176          << "for the moment, better use separately the methods: TrkLevel2::GetStoredTrack(seqno) CaloLevel2::GetCaloTrkVar(Int_t notrack) ToFLevel2::GetToFTrkVar(Int_t notrack) OrbitalInfo::GetOrbitalInfoTrkVar(Int_t notrack)"
1177          << endl;
1178      cout << "(if you use it, remember to delete the PamTrack object)" << endl;
1179      PamTrack *track = 0;
1180    
1181      if (itrk >= 0 && itrk < trk2_obj->TrkLevel2::ntrk()) {
1182    
1183        TrkTrack *t = trk2_obj->TrkLevel2::GetStoredTrack(itrk);
1184        track = GetPamTrackAlong(t);
1185    
1186      }
1187      else {
1188        cout << "PamLevel2::GetStoredTrack(int) : tracker track SeqNo " << itrk << " does not exist (GetNTracks() = "
1189            << trk2_obj->TrkLevel2::GetNTracks() << ")" << endl;
1190      };
1191    
1192      return track;
1193    
1194    }
1195  //--------------------------------------  //--------------------------------------
1196  //  //
1197  //  
 //--------------------------------------  
 void *PamLevel2::GetPointerTo(const char* c ){  
 //      cout << "objname "<< objname << endl;  
     TString objname = c;  
     if(!objname.CompareTo("TrkLevel1"))return &trk_l1_obj;  
     if(!objname.CompareTo("TrkLevel2"))return &trk_obj;  
       
     return NULL;  
 };  
 //--------------------------------------  
 //  
 //  
 //--------------------------------------  
1198  /**  /**
1199   * Get the Run tree chain from a list of files.   * Sort physical (tracker) tracks. Left here as backward compatibility method.
1200   * @param fl Pointer to a TList of TSystemFiles   **/
1201   * @return Pointer to a TChain  void PamLevel2::SortTracks(TString how) {
1202   */    printf(
1203  TChain *PamLevel2::GetRunTree(TList *fl){        " WARNING! obsolete, use SortTracks() and SetSortingMethod(TString) instead! \n Setting sorting method to %s \n",
1204                  how.Data());
1205      TChain *R = new TChain("Run");    howtosort = how;
1206          SortTracks();
     // loop over files and create chains          
     TIter next(fl);  
     TSystemFile *questo = 0;  
     while ( (questo = (TSystemFile*) next()) ) {  
         TString name =  questo->GetName();  
 //              cout << "File: "<< name << endl;  
         if( CheckLevel2File(name) ){  
             R->Add(name);  
         };  
     }  
       
     R->SetBranchAddress("RunInfo", GetPointerToRun());  
     cout << "Run         : set branch address RunInfo"<<endl;  
       
     return R;  
       
1207  }  }
1208  //--------------------------------------  ;
1209  //  
1210  //  //
1211  //--------------------------------------  //--------------------------------------
1212  /**  /**
1213   * Get the Run tree  from a file.   * Sort physical (tracker) tracks.
1214   * @param f Pointer to a TFile   * @param how String to set the sorting cryterium (es: "CAL" or "TRK+CAL+TOF" ecc...).
1215   * @return Pointer to a TTree   * Sorting cryteria:
1216     * TRK: lower chi**2
1217     * CAL: lower Y spatial residual on the first calorimeter plane
1218     * TOF: bigger numebr of hit PMTs along the track, on S12 S21 S32 (where paddles are along the Y axis).
1219     * S1: (ask Emiliano)
1220     * S2: (ask Emiliano)
1221     * S3: (ask Emiliano)
1222     * GP: more GP hits
1223     * The default sorting cryterium is "TOF+CAL".
1224     *
1225     * The total number of physical tracks is always given by GetNTracks() and the it-th physical track can be retrieved by means of the methods GetTrack(int it) and GetTrack(int it, TString how).
1226     */
1227    void PamLevel2::SortTracks() {
1228    
1229      //Check if the current event has already been sorted
1230      if (issorted && lastsorted == GetReadEntry()) {
1231        return;
1232      }
1233      //Reset the sort flags, just in case something will go wrong...
1234      issorted = false;
1235      lastsorted = -1;
1236    
1237      TString how = howtosort;
1238    
1239      //  cout <<" PamLevel2::SortTracks(TString how) "<<endl;
1240      if (!trk2_obj) {
1241        cout << "void PamLevel2::SortTracks():  TrkLevel2 not loaded !!!";
1242        return;
1243      };
1244      //Save current Object count
1245      Int_t ObjectNumber = TProcessID::GetObjectCount();
1246    
1247      // create TCloneArrays to store tracks and its images
1248      if (!tsorted)
1249        tsorted = new TClonesArray("PamTrack", trk2_obj->GetNTracks());
1250      tsorted->Delete();
1251      TClonesArray &ttsorted = *tsorted;
1252    
1253      if (!timage)
1254        timage = new TClonesArray("PamTrack", trk2_obj->GetNTracks());
1255      timage->Delete();
1256      TClonesArray &ttimage = *timage;
1257    
1258      //--------------------------------------------------
1259      // retrieve sorting method
1260      //--------------------------------------------------
1261      Bool_t use_TRK = how.Contains("TRK", TString::kIgnoreCase);
1262      Bool_t use_CAL = how.Contains("CAL", TString::kIgnoreCase);
1263      Bool_t use_TOF = how.Contains("TOF", TString::kIgnoreCase);
1264      Bool_t use_S1 = how.Contains("S1", TString::kIgnoreCase);
1265      Bool_t use_S2 = how.Contains("S2", TString::kIgnoreCase);
1266      Bool_t use_S3 = how.Contains("S3", TString::kIgnoreCase);
1267      Bool_t use_GP = how.Contains("GP", TString::kIgnoreCase);
1268    
1269      if (use_TOF) {
1270        use_S1 = true;
1271        use_S2 = true;
1272        use_S3 = true;
1273      };
1274      if (!CAL2 && use_CAL)
1275        use_CAL = false;
1276      if (!TOF) {
1277        use_TOF = false;
1278        use_S1 = false;
1279        use_S2 = false;
1280        use_S3 = false;
1281      }
1282      if (!GP) {
1283        use_GP = false;
1284      }
1285    
1286      if (!TRK2) {
1287        cout << "SortTracks() : without tracker does not work!!! (not yet)" << endl;
1288        return;
1289      };
1290    
1291      //   cout << "use_CAL "<<use_CAL<<" use_TOF "<<use_TOF<<" use_TRK "<<use_TRK <<endl;
1292    
1293    
1294      //--------------------------------------------------
1295      // loop over "physical" tracks sorted by the tracker
1296      //--------------------------------------------------
1297      for (Int_t i = 0; i < trk2_obj->TrkLevel2::GetNTracks(); i++) {
1298    
1299        TrkTrack *ts = 0;
1300        CaloTrkVar *cs = 0;
1301        ToFTrkVar *os = 0;
1302        OrbitalInfoTrkVar *rs = 0;
1303    
1304        // get tracker tracks
1305        TrkTrack *tp = trk2_obj->TrkLevel2::GetTrack(i); //tracker
1306        CaloTrkVar *cp = GetCaloStoredTrack(tp->GetSeqNo());
1307        ToFTrkVar *op = GetToFStoredTrack(tp->GetSeqNo());
1308        OrbitalInfoTrkVar *rp = GetOrbitalInfoStoredTrack(tp->GetSeqNo());
1309    
1310        TrkTrack *ti = 0; //tracker (image)
1311        CaloTrkVar *ci = 0;
1312        ToFTrkVar *oi = 0;
1313        OrbitalInfoTrkVar *ri = 0;
1314        //  cout << "trk track n. "<<i << " "<<hex<< tp <<dec<< endl;
1315        // if track has an image, check image selection
1316    
1317        Int_t tp_score = 0; //main track sorted by the tracker
1318        Int_t ti_score = 0; //image track
1319        Int_t totp_score = 0; //main track sorted by the tracker
1320        Int_t toti_score = 0; //image track
1321    
1322        if (tp->HasImage()) {
1323    
1324          ti = trk2_obj->TrkLevel2::GetTrackImage(i); //tracker (image)
1325          ci = GetCaloStoredTrack(ti->GetSeqNo());
1326          oi = GetToFStoredTrack(ti->GetSeqNo());
1327          ri = GetOrbitalInfoStoredTrack(ti->GetSeqNo());
1328    
1329          //            cout << "its image "<<i << " "<<hex<< ti <<dec<< endl;
1330    
1331          //assign starting scores
1332          tp_score = 0; //main track sorted by the tracker
1333          ti_score = 0; //image track
1334    
1335          // -----------------------------------------------------------------------------------------
1336          // *****************************************************************************************
1337          // -----------------------------------------------------------------------------------------
1338          // calorimeter check
1339          // -----------------------------------------------------------------------------------------
1340          if (use_CAL && !calo2_obj) {
1341            cout << "void PamLevel2::SortTracks(): howtosort= " << how << " but CaloLevel2 not loaded !!!";
1342            return;
1343          };
1344          if (use_CAL && !cp && ci) {
1345            ti_score++;
1346            toti_score++;
1347          };
1348          if (use_CAL && cp && !ci) {
1349            tp_score++;
1350            totp_score++;
1351          };
1352          if (use_CAL && cp && ci && true) {
1353    
1354            if (cp->npresh > ci->npresh && true) {
1355              tp_score++;
1356              totp_score++;
1357            };
1358            if (cp->npresh < ci->npresh && true) {
1359              ti_score++;
1360              toti_score++;
1361            };
1362    
1363            //      cout << "CALO "<<tp_score<<ti_score<<endl;
1364    
1365          };
1366          // -----------------------------------------------------------------------------------------
1367          // *****************************************************************************************
1368          // -----------------------------------------------------------------------------------------
1369          // TOF check
1370          // -----------------------------------------------------------------------------------------
1371          // check the number of hit pmts along the track
1372          // on S12 S21 and S32, where paddles are parallel to Y axis
1373          if ((use_TOF || use_S1 || use_S2 || use_S3) && !tof_obj) {
1374            cout << "void PamLevel2::SortTracks(): howtosort= " << how << " but ToFLevel2 not loaded !!!";
1375            return;
1376          };
1377          //
1378          if ((use_TOF || use_S1 || use_S2 || use_S3) && !op && oi) {
1379            ti_score++;
1380            toti_score++;
1381          };
1382          if ((use_TOF || use_S1 || use_S2 || use_S3) && op && !oi) {
1383            tp_score++;
1384            totp_score++;
1385          };
1386          if ((use_TOF || use_S1 || use_S2 || use_S3) && op && oi) {
1387            //
1388            Float_t sen = 0.;
1389            for (Int_t ih = 0; ih < op->npmtadc; ih++) {
1390              Int_t pl = tof_obj->GetPlaneIndex((op->pmtadc).At(ih));
1391              if (pl == 2 || pl == 3 || pl == 4 || pl == 5)
1392                sen += (op->dedx).At(ih);
1393            };
1394            for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
1395              Int_t pl = tof_obj->GetPlaneIndex((oi->pmtadc).At(ih));
1396              if (pl == 2 || pl == 3 || pl == 4 || pl == 5)
1397                sen += (oi->dedx).At(ih);
1398            };
1399            //
1400            if (sen >= sortthr && false) { // temporary disabled NUCLEI special algorithm since the new one should work for every particle (to be checked!)
1401              //printf(" IS A NUCLEUS! en = %f \n",sen);
1402              //
1403              // is a nucleus use a different algorithm
1404              //
1405              Int_t nz = 6;
1406              Float_t zin[6]; // << define TOF z-coordinates
1407              for (Int_t ip = 0; ip < nz; ip++)
1408                zin[ip] = tof_obj->ToFLevel2::GetZTOF(tof_obj->ToFLevel2::GetToFPlaneID(ip)); // << read ToF plane z-coordinates
1409              Trajectory *tr = new Trajectory(nz, zin);
1410              //
1411              Int_t nphit_p = 0;
1412              Int_t nphit_i = 0;
1413              Float_t enhit_p = 0.;
1414              Float_t enhit_i = 0.;
1415              //
1416              for (Int_t ih = 0; ih < op->npmtadc; ih++) {
1417                Int_t pl = tof_obj->GetPlaneIndex((op->pmtadc).At(ih));
1418                if (pl == 1 || pl == 2 || pl == 5) {
1419                  nphit_p++;
1420                  enhit_p += (op->dedx).At(ih);
1421                };
1422              };
1423              //
1424              tp->DoTrack2(tr);
1425              //
1426              if (fabs(tr->y[0] - oi->ytofpos[0]) < 2.) {
1427                for (Int_t ih = 0; ih < op->npmtadc; ih++) {
1428                  Int_t pl = tof_obj->GetPlaneIndex((op->pmtadc).At(ih));
1429                  if (pl == 0) {
1430                    nphit_p++;
1431                    enhit_p += (op->dedx).At(ih);
1432                  };
1433                };
1434              };
1435              if (fabs(tr->y[3] - oi->ytofpos[1]) < 2.) {
1436                for (Int_t ih = 0; ih < op->npmtadc; ih++) {
1437                  Int_t pl = tof_obj->GetPlaneIndex((op->pmtadc).At(ih));
1438                  if (pl == 3) {
1439                    nphit_p++;
1440                    enhit_p += (op->dedx).At(ih);
1441                  };
1442                };
1443              };
1444              if (fabs(tr->y[4] - oi->ytofpos[2]) < 2.) {
1445                for (Int_t ih = 0; ih < op->npmtadc; ih++) {
1446                  Int_t pl = tof_obj->GetPlaneIndex((op->pmtadc).At(ih));
1447                  if (pl == 4) {
1448                    nphit_p++;
1449                    enhit_p += (op->dedx).At(ih);
1450                  };
1451                };
1452              };
1453    
1454              for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
1455                Int_t pl = tof_obj->GetPlaneIndex((oi->pmtadc).At(ih));
1456                if (pl == 1 || pl == 2 || pl == 5) {
1457                  nphit_i++;
1458                  enhit_i += (op->dedx).At(ih);
1459                };
1460              };
1461              //
1462              ti->DoTrack2(tr);
1463              //
1464              if (fabs(tr->y[0] - oi->ytofpos[0]) < 2.) {
1465                for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
1466                  Int_t pl = tof_obj->GetPlaneIndex((oi->pmtadc).At(ih));
1467                  if (pl == 0) {
1468                    nphit_i++;
1469                    enhit_i += (op->dedx).At(ih);
1470                  };
1471                };
1472              };
1473              if (fabs(tr->y[3] - oi->ytofpos[1]) < 2.) {
1474                for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
1475                  Int_t pl = tof_obj->GetPlaneIndex((oi->pmtadc).At(ih));
1476                  if (pl == 3) {
1477                    nphit_i++;
1478                    enhit_i += (op->dedx).At(ih);
1479                  };
1480                };
1481              };
1482              if (fabs(tr->y[4] - oi->ytofpos[2]) < 2.) {
1483                for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
1484                  Int_t pl = tof_obj->GetPlaneIndex((oi->pmtadc).At(ih));
1485                  if (pl == 4) {
1486                    nphit_i++;
1487                    enhit_i += (op->dedx).At(ih);
1488                  };
1489                };
1490              };
1491    
1492              if ((use_TOF || use_S1 || use_S2 || use_S3) && (nphit_p + nphit_i) != 0 && true) {
1493    
1494                //      printf(" seqno %i nphit_p %i nphit_i %i enhit_p %f enhit_i %f \n",trk2_obj->TrkLevel2::GetSeqNo(i),nphit_p,nphit_i,enhit_p,enhit_i);
1495                //      printf(" score p %i score i %i \n",tp_score,ti_score);
1496                //            if( enhit_p > enhit_i ) tp_score++;
1497                //            if( nphit_p >= nphit_i && enhit_p > enhit_i ) tp_score++;
1498                if (nphit_p > nphit_i)
1499                  tp_score++;
1500                if (nphit_p < nphit_i)
1501                  ti_score++;
1502                if (nphit_p == nphit_i) {
1503                  if (enhit_p > enhit_i)
1504                    tp_score++;
1505                  else
1506                    ti_score++;
1507                };
1508                //      printf(" dopo score p %i score i %i \n",tp_score,ti_score);
1509              };
1510              delete tr;
1511              //
1512            }
1513            else {
1514              // -------------
1515              // NOT a NUCLEUS
1516              // -------------
1517              //printf(" NOT a NUCLEUS! en = %f \n",sen);
1518    
1519              Int_t nphit_p = 0;
1520              Int_t nphit_i = 0;
1521    
1522              /*                            cout << "track: npmtadc "<< op->npmtadc << endl;
1523               cout << "track: npmttdc "<< op->npmttdc << endl;
1524               cout << "image: npmtadc "<< oi->npmtadc << endl;
1525               cout << "image: npmttdc "<< oi->npmttdc << endl;*/
1526    
1527              //      for (Int_t ih=0; ih < op->npmtadc; ih++){
1528              //        Int_t pl = tof_obj->GetPlaneIndex( (op->pmtadc).At(ih) );
1529              //        if(pl == 1 || pl == 2 || pl == 5)nphit_p++;
1530              //      };
1531    
1532              //      for (Int_t ih=0; ih < oi->npmtadc; ih++){
1533              //        Int_t pl = tof_obj->GetPlaneIndex( (oi->pmtadc).At(ih) );
1534              //        if(pl == 1 || pl == 2 || pl == 5)nphit_i++;
1535              //      };
1536              // --- modified to count tdc signals (more efficient?)
1537              // --- and to implement check on tdcflag
1538              for (Int_t ih = 0; ih < op->npmttdc; ih++) {
1539                Int_t pl = tof_obj->GetPlaneIndex((op->pmttdc).At(ih));
1540                //      if( (op->tdcflag).At(ih)==0 && (pl == 1 || pl == 2 || pl == 5) )nphit_p++;
1541                if ((use_S1 && (pl == 0 || pl == 1)) || (use_S2 && (pl == 2 || pl == 3))
1542                    || (use_S3 && (pl == 4 || pl == 5))) {
1543                  if ((op->tdcflag).At(ih) == 0)
1544                    nphit_p++;
1545                };
1546              };
1547    
1548              for (Int_t ih = 0; ih < oi->npmttdc; ih++) {
1549                Int_t pl = tof_obj->GetPlaneIndex((oi->pmttdc).At(ih));
1550                //      if( (oi->tdcflag).At(ih)==0 && (pl == 1 || pl == 2 || pl == 5) )nphit_i++;
1551                if ((use_S1 && (pl == 0 || pl == 1)) || (use_S2 && (pl == 2 || pl == 3))
1552                    || (use_S3 && (pl == 4 || pl == 5))) {
1553                  if ((oi->tdcflag).At(ih) == 0)
1554                    nphit_i++;
1555                };
1556              };
1557    
1558              if ((nphit_p + nphit_i) != 0 && true) {
1559    
1560                if (nphit_p != nphit_i) {
1561                  totp_score += nphit_p;
1562                  toti_score += nphit_i;
1563                  tp_score += nphit_p;
1564                  ti_score += nphit_i;
1565                };
1566                //      if     ( nphit_p > nphit_i) tp_score+=nphit_p;
1567                //      else if( nphit_p < nphit_i) ti_score+=nphit_i;
1568                //      else ;//niente
1569              };
1570            };
1571            //      cout << "TOF "<<tp_score<<ti_score<<endl;
1572          };
1573    
1574          //      if(tp_score == ti_score) use_TRK = true;
1575    
1576    
1577          // -----------------------------------------------------------------------------------------
1578          // *****************************************************************************************
1579          // -----------------------------------------------------------------------------------------
1580          // tracker check
1581          // -----------------------------------------------------------------------------------------
1582          // chi**2 difference is not always large enough to distinguish among
1583          // the real track and its image.
1584          // Tracker check will be applied always when calorimeter and tof information is ambiguous.
1585          // *** MODIFIED ON AUGUST 2007 ***
1586          if (use_TRK) {
1587            //      if(      tp->chi2 > 0 && tp->chi2 < ti->chi2 ) tp_score++ ;
1588            //      else if( ti->chi2 > 0 && ti->chi2 < tp->chi2 ) ti_score++ ;
1589    
1590            // CHECK 1 : number of points along X
1591            if (tp->GetNX() >= ti->GetNX()) {
1592              tp_score++;
1593              totp_score++;
1594            };
1595            if (tp->GetNX() <= ti->GetNX()) {
1596              ti_score++;
1597              toti_score++;
1598            };
1599            // CHECK 2 : number of points along Y
1600            if (tp->GetNY() >= ti->GetNY()) {
1601              tp_score++;
1602              totp_score++;
1603            };
1604            if (tp->GetNY() <= ti->GetNY()) {
1605              ti_score++;
1606              toti_score++;
1607            };
1608    
1609            //      cout << "TRK "<<tp_score<<ti_score<<endl;
1610          };
1611    
1612          // -----------------------------------------------------------------------------------------
1613          // *****************************************************************************************
1614          // -----------------------------------------------------------------------------------------
1615          // GPamela check
1616          // -----------------------------------------------------------------------------------------
1617    
1618          //---------------------------------------------------
1619          // count the number of GP hits
1620          //---------------------------------------------------
1621          if (use_GP) {
1622            int ngphits_p = 0;
1623            int ngphits_i = 0;
1624            float toll = 0.02; //200 micron
1625            for (int ih = 0; ih < GetGPamela()->Nthspe; ih++) {
1626              int ip = (Int_t) GetGPamela()->Itrpb[ih] - 1;
1627              if (tp && tp->YGood(ip) && fabs(tp->ym[ip] - GetGPamela()->Yavspe[ih]) < toll && true)
1628                ngphits_p++;
1629              if (ti && ti->YGood(ip) && fabs(ti->ym[ip] - GetGPamela()->Yavspe[ih]) < toll && true)
1630                ngphits_i++;
1631            }
1632            if (ngphits_p > ngphits_i && true) {
1633              tp_score++;
1634              totp_score++;
1635            }
1636            if (ngphits_p < ngphits_i && true) {
1637              ti_score++;
1638              toti_score++;
1639            }
1640          }
1641    
1642          // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
1643          // the winner is....
1644          // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
1645          if (tp_score > ti_score) {
1646    
1647          }
1648          else if (tp_score < ti_score) {
1649    
1650            ts = ti;//its image!!
1651            cs = ci;
1652            os = oi;
1653            rs = ri;
1654            Int_t totis = toti_score;
1655    
1656            ti = tp;//its image!!
1657            ci = cp;
1658            oi = op;
1659            ri = rp;
1660    
1661            tp = ts;//its image!!
1662            cp = cs;
1663            op = os;
1664            rp = rs;
1665    
1666            toti_score = totp_score;
1667            totp_score = totis;
1668    
1669          }
1670          else {
1671    
1672            //      cout << "Warning - track image ambiguity not solved" << endl;
1673    
1674          };
1675    
1676        }
1677        else {
1678          totp_score = 1;
1679          toti_score = 0;
1680    
1681          //            ts = tp;
1682          //            cs = cp;
1683          //            os = op;
1684        };
1685    
1686        //  cout <<" SortTracks() "<<i<<" -- "<<ts<<endl;
1687        //  sorted_tracks->Add(ts);//save the track in the sorted array
1688        //  sorted_tracks.Add(ts);//save the track in the sorted array
1689        //  sorted_tracks.Add(tp);//save the track in the sorted array
1690        //  cout << "SortTracks:: sorted_tracks->Add(it) "<<i<<" "<<ts<<endl;
1691        //  cout<<"o "<<tp<<endl;
1692        //  cout<<"o "<<cp<<endl;
1693        //  cout<<"o "<<op<<endl;
1694    
1695        new (ttsorted[i]) PamTrack(tp, cp, op, rp);
1696        new (ttimage[i]) PamTrack(ti, ci, oi, ri);
1697    
1698        ((PamTrack*) (ttsorted[i]))->SetPScore(totp_score);
1699        ((PamTrack*) (ttsorted[i]))->SetIScore(toti_score);
1700        ((PamTrack*) (ttimage[i]))->SetPScore(totp_score);
1701        ((PamTrack*) (ttimage[i]))->SetIScore(toti_score);
1702      };
1703    
1704      if (tsorted->GetEntries() != trk2_obj->GetNTracks()) {
1705        cout << "void PamLevel2::SortTracks(): tsorted->GetEntries() " << tsorted->GetEntries()
1706            << " != trk2_obj->GetNTracks() = " << trk2_obj->GetNTracks() << endl;
1707        tsorted->Delete();
1708        tsorted = 0;
1709        timage->Delete();
1710        timage = 0;
1711      }
1712    
1713      //Restore Object count
1714      //To save space in the table keeping track of all referenced objects
1715      //We reset the object count to what it was at the beginning of the event.
1716      TProcessID::SetObjectCount(ObjectNumber);
1717    
1718      //Everything went fine so the current event can be tagged as sorted
1719      issorted = true;
1720      lastsorted = GetReadEntry();
1721    
1722    }
1723    ;
1724    //--------------------------------------
1725    //
1726    //
1727    //--------------------------------------
1728    /**
1729     * This method overrides TrkLevel2::GetTracks(), where sorting is done by decreasing number of fit points and increasing chi^2.
1730     * PamLevel2::GetTracks() keeps the same track order given by TrkLevel2::GetTracks(), but checks image selection by using calorimeter and ToF tracking information.
1731     */
1732    // TRefArray *PamLevel2::GetTracks(){
1733    
1734    // //  *-*-*-*-*-*-*-*-*-*-*-*-*
1735    //     SortTracks("+CAL+TOF");
1736    // //  *-*-*-*-*-*-*-*-*-*-*-*-*
1737    
1738    // //   return  sorted_tracks;
1739    //     return &sorted_tracks;
1740    
1741    //  };
1742    TClonesArray *PamLevel2::GetTracks() {
1743    
1744      //  *-*-*-*-*-*-*-*-*-*-*-*-*
1745      SortTracks();
1746      //  *-*-*-*-*-*-*-*-*-*-*-*-*
1747    
1748      return tsorted;
1749    
1750    }
1751    ;
1752    //--------------------------------------
1753    //
1754    //
1755    //--------------------------------------
1756    /**
1757     * Retrieves the it-th Pamela "physical" track.
1758     * It override TrkLevel2::GetTrack(int it).
1759     * @param it Track number, ranging from 0 to GetNTracks().
1760     */
1761    PamTrack *PamLevel2::GetTrack(int it) {
1762    
1763      //    if(!trk2_obj) return 0;
1764    
1765      // //  *-*-*-*+-*-*-*-*-*-*-*-*-*
1766      //     SortTracks("+CAL+TOF");
1767      // //  *-*-*-*-*-*-*-*-*-*-*-*-*
1768      // //    if(!sorted_tracks)return 0;
1769      //     if(sorted_tracks.IsEmpty())return 0;
1770    
1771      //     PamTrack *track = 0;
1772    
1773      //     if( it >=0 && it < trk2_obj->TrkLevel2::GetNTracks() && it<sorted_tracks.GetEntriesFast() ){
1774      //    TrkTrack   *t = (TrkTrack*)sorted_tracks.At(it);
1775      //    track = GetPamTrackAlong(t);
1776      //     }else{
1777      //    cout << "PamLevel2::GetTrack(int) : tracker track SeqNo "<< it <<" does not exist (GetNTracks() = "<<trk2_obj->TrkLevel2::GetNTracks()<<")"<<endl;
1778      //     };
1779    
1780      //     return track;
1781    
1782      //    cout << "PamLevel2::GetTrack(int it) "<<endl;
1783      //  *-*-*-*-*-*-*-*-*-*-*-*-*
1784      SortTracks();
1785      //  *-*-*-*-*-*-*-*-*-*-*-*-*
1786      if (!tsorted)
1787        return 0;
1788      if (!tsorted->GetEntries())
1789        return 0;
1790    
1791      PamTrack *track = 0;
1792    
1793      if (it >= 0 && it < trk2_obj->TrkLevel2::GetNTracks()) {
1794        //  TrkTrack   *t = (TrkTrack*)sorted_tracks.At(it);
1795        //  track = GetPamTrackAlong(t);
1796        //TClonesArray &t = *(tsorted);
1797        //track = (PamTrack*)t[it];
1798        track = (PamTrack*)((*tsorted)[it]);
1799      }
1800      else {
1801        cout << "PamLevel2::GetTrack(int) : tracker track SeqNo " << it << " does not exist (GetNTracks() = "
1802            << trk2_obj->TrkLevel2::GetNTracks() << ")" << endl;
1803      };
1804    
1805      return track;
1806    
1807    }
1808    ;
1809    
1810    //--------------------------------------
1811    //
1812    //
1813    //--------------------------------------
1814    /**
1815     * Retrieves (if present) the image of the it-th Pamela "physical" track, sorted by the method PamLevel2::SortTracks().
1816     * @param it Track number, ranging from 0 to GetNTracks().
1817     */
1818    PamTrack *PamLevel2::GetTrackImage(int it) {
1819    
1820      //  *-*-*-*-*-*-*-*-*-*-*-*-*
1821      SortTracks();
1822      //  *-*-*-*-*-*-*-*-*-*-*-*-*
1823      if (!timage)
1824        return 0;
1825      if (!timage->GetEntries())
1826        return 0;
1827    
1828      PamTrack *image = 0;
1829    
1830      if (it >= 0 && it < trk2_obj->TrkLevel2::GetNTracks()) {
1831        TClonesArray &t = *(tsorted);
1832        PamTrack *temp = (PamTrack*) t[it];
1833        if (temp->GetTrkTrack()->HasImage()) {
1834          TClonesArray & t = *(timage);
1835          image = (PamTrack*) t[it];
1836        }
1837        else {
1838          //            cout <<"PamLevel2::GetTrackImage(int) : Track SeqNo "<<it<<" does not have image"<<endl;
1839        };
1840      }
1841      else {
1842        cout << "PamLevel2::GetTrackImage(int) : Tracker track SeqNo " << it << " does not exist (GetNTracks() = "
1843            << trk2_obj->TrkLevel2::GetNTracks() << ")" << endl;
1844      };
1845    
1846      return image;
1847    }
1848    
1849    //--------------------------------------
1850    //
1851    //
1852    //--------------------------------------
1853    /**
1854     * Get the Pamela detector trees in a single file and make them friends.
1855     * @param f TFile pointer
1856     * @param detlist String to select trees to be included
1857     * @return Pointer to a TTree
1858     */
1859    TTree *PamLevel2::GetPamTree(TFile *f, TString detlist) {
1860    
1861      if (detlist.Contains("+AUTO", TString::kIgnoreCase)) {
1862        cout << "+AUTO" << endl;
1863        GetWhichTrees(f);
1864      };
1865      SetWhichTrees(detlist);
1866    
1867      if (pam_tree) {
1868        printf("WARNING: TTree *PamLevel2::GetPamTree(TFile *fl, TString detlist) -- pam_tree already exists!\n ");
1869        return pam_tree;
1870      };
1871      //
1872    
1873      cout << "TTree *PamLevel2::GetPamTree(TFile *f, TString detlist ) -- obsolte " << endl;
1874    
1875      //    SetWhichTrees(detlist);
1876    
1877      TTree *Trout = 0;
1878    
1879      TString fname = f->GetName();
1880      if (!CheckLevel2File(fname))
1881        return NULL;
1882    
1883      //    UInt_t *found=0;
1884    
1885      cout << "GetPamTree(TFile*,TString): detector list --> ";
1886      if (TRK1)
1887        cout << "TRK1 ";
1888      if (TRK2)
1889        cout << "TRK2 ";
1890      if (TRKh)
1891        cout << "TRKH ";
1892      if (CAL1)
1893        cout << "CAL1 ";
1894      if (CAL2)
1895        cout << "CAL2 ";
1896      if (TOF)
1897        cout << "TOF ";
1898      if (TRG)
1899        cout << "TRG ";
1900      if (AC)
1901        cout << "AC ";
1902      if (ND)
1903        cout << "ND ";
1904      if (S4)
1905        cout << "S4 ";
1906      if (ORB)
1907        cout << "ORB ";
1908      if (GP)
1909        cout << "GP ";
1910      cout << endl;
1911      if (SELLI && SELLI != 2)
1912        cout << ">>> Found selection-list <<<" << endl; //EMILIANO
1913    
1914      f->cd();
1915    
1916      // Tracker
1917      TTree *T = (TTree*) f->Get("Tracker");
1918      if (T && (TRK2 || TRK1 || TRKh)) {
1919        if (TRK2)
1920          T->SetBranchAddress("TrkLevel2", GetPointerTo("TrkLevel2"));
1921        //  else    T->SetBranchStatus("TrkLevel2",0,found);
1922        if (TRK2)
1923          cout << "Tracker      : set branch address TrkLevel2" << endl;
1924        if (TRK1)
1925          T->SetBranchAddress("TrkLevel1", GetPointerTo("TrkLevel1"));
1926        //  else    T->SetBranchStatus("TrkLevel1",0,found);
1927        if (TRK1)
1928          cout << "Tracker      : set branch address TrkLevel1" << endl;
1929        if (TRKh)
1930          T->SetBranchAddress("TrkHough", GetPointerTo("TrkHough"));
1931        //  else    T->SetBranchStatus("TrkHough",0,found);
1932        if (TRKh)
1933          cout << "Tracker      : set branch address TrkHough" << endl;
1934        if (!Trout)
1935          Trout = T;
1936        else
1937          Trout->AddFriend(T);
1938      }
1939      else {
1940        cout << "Tracker      : missing tree" << endl;
1941      };
1942      // Calorimeter
1943      TTree *C = (TTree*) f->Get("Calorimeter");
1944      if (C && (CAL2 || CAL1)) {
1945        if (CAL2)
1946          C->SetBranchAddress("CaloLevel2", GetPointerTo("CaloLevel2"));
1947        //  else    C->SetBranchStatus("CaloLevel2",0,found);
1948        if (CAL2)
1949          cout << "Calorimeter  : set branch address CaloLevel2" << endl;
1950        if (CAL1)
1951          C->SetBranchAddress("CaloLevel1", GetPointerTo("CaloLevel1"));
1952        //  else    C->SetBranchStatus("CaloLevel1",0,found);
1953        if (CAL1)
1954          cout << "Calorimeter  : set branch address CaloLevel1" << endl;
1955        if (!Trout)
1956          Trout = C;
1957        else
1958          Trout->AddFriend(C);
1959      }
1960      else {
1961        cout << "Calorimeter  : missing tree" << endl;
1962      };
1963    
1964      // ToF
1965      TTree *O = (TTree*) f->Get("ToF");
1966      if (O && TOF) {
1967        O->SetBranchAddress("ToFLevel2", GetPointerTo("ToFLevel2"));
1968        cout << "ToF          : set branch address ToFLevel2" << endl;
1969        if (!Trout)
1970          Trout = O;
1971        else
1972          Trout->AddFriend(O);
1973      }
1974      else {
1975        cout << "ToF         : missing tree" << endl;
1976      };
1977      // Trigger
1978      TTree *R = (TTree*) f->Get("Trigger");
1979      if (R && TRG) {
1980        R->SetBranchAddress("TrigLevel2", GetPointerTo("TrigLevel2"));
1981        cout << "Trigger      : set branch address TrigLevel2" << endl;
1982        if (!Trout)
1983          Trout = R;
1984        else
1985          Trout->AddFriend(R);
1986      }
1987      else {
1988        cout << "Trigger      : missing tree" << endl;
1989      };
1990      // S4
1991      TTree *S = (TTree*) f->Get("S4");
1992      if (S && S4) {
1993        S->SetBranchAddress("S4Level2", GetPointerTo("S4Level2"));
1994        cout << "S4           : set branch address S4Level2" << endl;
1995        if (!Trout)
1996          Trout = S;
1997        else
1998          Trout->AddFriend(S);
1999      }
2000      else {
2001        cout << "S4           : missing tree" << endl;
2002      };
2003      // Neutron Detector
2004      TTree *N = (TTree*) f->Get("NeutronD");
2005      if (N && ND) {
2006        N->SetBranchAddress("NDLevel2", GetPointerTo("NDLevel2"));
2007        cout << "NeutronD     : set branch address NDLevel2" << endl;
2008        if (!Trout)
2009          Trout = N;
2010        else
2011          Trout->AddFriend(N);
2012      }
2013      else {
2014        cout << "NeutronD     : missing tree" << endl;
2015      };
2016      // Anticounters
2017      TTree *A = (TTree*) f->Get("Anticounter");
2018      if (A && AC) {
2019        A->SetBranchAddress("AcLevel2", GetPointerTo("AcLevel2"));
2020        cout << "Anticounter  : set branch address AcLevel2" << endl;
2021        if (!Trout)
2022          Trout = A;
2023        else
2024          Trout->AddFriend(A);
2025      }
2026      else {
2027        cout << "Anticounter  : missing tree" << endl;
2028      };
2029      // Orbital Info
2030      TTree *B = (TTree*) f->Get("OrbitalInfo");
2031      if (B && ORB) {
2032        B->SetBranchAddress("OrbitalInfo", GetPointerTo("OrbitalInfo"));
2033        cout << "OrbitalInfo  : set branch address OrbitalInfo" << endl;
2034        if (!Trout)
2035          Trout = B;
2036        else
2037          Trout->AddFriend(B);
2038      }
2039      else {
2040        cout << "OrbitalInfo  : missing tree" << endl;
2041      };
2042    
2043      // GPamela
2044      TTree *G = (TTree*) f->Get("h20");
2045      if (G && GP) {
2046        if (!gp_obj)
2047          gp_obj = new GPamela();
2048        //      ------------------------------------
2049        //      ATTENZIONE!!!
2050        //      non so per quale arcano motivo,
2051        //      per l'albero di gpamela il branch address lo devo settare
2052        //      DOPO aver fatto friend
2053        //      FGRRRVZZZZUTSALKJMSLKJ!!!
2054        //      ------------------------------------
2055        //  gp_obj->SetBranchAddress(G); //ho dovuto fare in maniera diversa dagli altri
2056        //  cout << "h20          : set branch address GPamela "<<endl;
2057        if (!Trout)
2058          Trout = G;
2059        else
2060          Trout->AddFriend(G);
2061      }
2062      else {
2063        //  cout << "h20          : missing tree"<<endl;
2064      };
2065    
2066      TTree *L = (TTree*) f->Get("SelectionList");
2067      if (L && SELLI == 1) {
2068        cout << " TTree *PamLevel2::GetPamTree(TFile, TString) >>> SelectionList not implemented!!!!" << endl;
2069        sel_tree = 0;
2070      }
2071      else {
2072        cout << "SelectionList  : missing tree" << endl;
2073      };
2074    
2075      cout << endl << " Number of entries: " << Trout->GetEntries() << endl << endl;
2076    
2077      //      ------------------------------------
2078      //      ATTENZIONE!!!
2079      //      non so per quale arcano motivo,
2080      //      per l'albero di gpamela il branch address lo devo settare
2081      //      DOPO aver fatto friend
2082      //      FGRRRVZZZZUTSALKJMSLKJ!!!
2083      //      ------------------------------------
2084      if (G && GP) {
2085        gp_obj->SetBranchAddress(Trout); //ho dovuto fare in maniera diversa dagli altri
2086        cout << "h20          : set branch address GPamela " << endl;
2087      }
2088      else {
2089        cout << "h20          : missing tree" << endl;
2090      };
2091    
2092      pam_tree = (TChain*) Trout;
2093    
2094      return Trout;
2095    
2096    }
2097    //--------------------------------------
2098    //
2099    //
2100    //--------------------------------------
2101    /**
2102     * Get list of Level2 files.
2103     * @param ddir Level2 data directory.
2104     * @param flisttxt Name of txt file containing file list.
2105     * @return Pointer to a TList of TSystemFiles
2106     * If no input file list is given , all the Level2 files inside the directory are processed.
2107     */
2108    TList* PamLevel2::GetListOfLevel2Files(TString ddir, TString flisttxt = "") {
2109    
2110      TString wdir = gSystem->WorkingDirectory();
2111    
2112      if (ddir != "") {
2113        cout << "Level2 data directory : " << ddir << endl;
2114      }
2115      else {
2116        cout << "Level2 data directory not given as input: trying to evaluate from list or taking working directory "
2117            << endl;
2118      };
2119      TList *contents = new TList; // create output list
2120      contents->SetOwner();
2121    
2122      // --------------------------------------
2123      // case 1 : input file/file-list provided
2124      // --------------------------------------
2125      if (flisttxt != "") {
2126    
2127        // --------------------------------------
2128        // a list of files given as input
2129        // --------------------------------------
2130        if (!flisttxt.EndsWith(".root")) {
2131    
2132          TString dir = gSystem->DirName(flisttxt);
2133          //            cout << " List directory "<<dir<<endl;
2134          if (dir == "." || dir == "")
2135            flisttxt = gSystem->ConcatFileName(wdir.Data(), gSystem->BaseName(flisttxt));
2136          //                flisttxt = gSystem->ConcatFileName(gSystem->DirName(flisttxt),gSystem->BaseName(flisttxt));
2137    
2138          if (!gSystem->ChangeDirectory(ddir)) {
2139            cout << "Cannot change directory : " << ddir << endl;
2140            return 0;
2141          }
2142    
2143          cout << "Input file list : " << flisttxt << endl;
2144          ifstream in;
2145          in.open(flisttxt, ios::in); //open input file list
2146          if (!in.good()) {
2147            cout << " TList*  PamLevel2::GetListOfLevel2Files(TString, TString) --> ERROR opening the file " << endl;
2148            gSystem->ChangeDirectory(wdir); // back to the working directory
2149            return 0;
2150          }
2151          int line = 0;
2152          // ...........................
2153          // loop over file-list records
2154          // ...........................
2155          while (1) {
2156            TString file;
2157            in >> file;
2158            if (!in.good())
2159              break;
2160            line++;
2161            cout << "(*) " << file << endl;
2162            if (file.IsNull()) {
2163              cout << "-- list interrupted at line " << line << endl;
2164              break;
2165            }
2166            if (file.Contains("#"))
2167              file = file(0, file.First("#"));
2168            //
2169            // take only root files
2170            //
2171            if (file.EndsWith(".root")) {
2172              TString filedir;
2173              cout << ddir << endl;
2174              if ( ddir != "" ) {
2175                filedir = ddir; // take the input dir
2176              }
2177              else {
2178                gSystem->ChangeDirectory(wdir); // back to the working directory
2179                filedir = gSystem->DirName(file); // this will take the path if exist in the list otherwise it will return automatically the working dir
2180              };
2181              filedir.Append("/");
2182              //          char *fullpath = gSystem->ConcatFileName(gSystem->DirName(filedir), gSystem->BaseName(file));
2183              char *fullpath = gSystem->ConcatFileName(filedir.Data(), gSystem->BaseName(file));
2184              contents->Add(new TSystemFile(fullpath, gSystem->DirName(fullpath)));// add file to the list
2185              cout << fullpath << endl;
2186              delete fullpath;
2187            }
2188            //          }else{
2189            //              if(file.Data()!="")cout << "File: "<<file<<" ---> missing "<< endl;
2190            //          };
2191          };
2192          in.close();
2193          // --------------------------------------
2194          // a single root file given as input
2195          // --------------------------------------
2196        }
2197        else {
2198          if (flisttxt.Contains("#"))
2199            flisttxt = flisttxt(0, flisttxt.First("#"));
2200          char *fullpath = gSystem->ConcatFileName(gSystem->DirName(flisttxt), gSystem->BaseName(flisttxt));
2201          contents->Add(new TSystemFile(fullpath, gSystem->DirName(fullpath)));// add file to the list
2202          delete fullpath;
2203        };
2204        // ---------------------------------------------------------------------------------
2205        // case 2 : no input file/file-list provided --> read all files insede the directory
2206        // ---------------------------------------------------------------------------------
2207      }
2208      else {
2209    
2210        cout << "No input file list given." << endl;
2211        cout << "Check for existing root files." << endl;
2212        //          cout << "Warking directory: "<< gSystem->WorkingDirectory()<< endl;
2213        if (ddir == "") {
2214          ddir = wdir;
2215          cout << "Level2 data directory : " << ddir << endl;
2216        };
2217    
2218        TSystemDirectory *datadir = new TSystemDirectory(gSystem->BaseName(ddir), ddir);
2219        TList *temp = datadir->GetListOfFiles();
2220        if (!temp)
2221          return 0;
2222        //          temp->Print();
2223        //          cout << "*************************************" << endl;
2224    
2225        TIter next(temp);
2226        TSystemFile *questo = 0;
2227    
2228        while ((questo = (TSystemFile*) next())) {
2229          TString name = questo-> GetName();
2230          if (name.EndsWith(".root")) {
2231            //              const char *fullpath = gSystem->FindFile(ddir,name);
2232            //              char *fullpath;
2233            //              gSystem->IsFileInIncludePath(name,&fullpath);
2234            char *fullpath = gSystem->ConcatFileName(gSystem->DirName(ddir), gSystem->BaseName(name));
2235            contents->Add(new TSystemFile(fullpath, gSystem->DirName(fullpath)));
2236            delete fullpath;
2237          };
2238        }
2239        delete temp;
2240        delete datadir;
2241    
2242      };
2243      gSystem->ChangeDirectory(wdir); // back to the working directory
2244      //    cout << endl << "Selected files:" << endl;
2245      //    contents->Print();
2246      cout << contents->GetEntries() << " files \n";
2247      //    cout << endl;
2248      //    cout << "Working directory: "<< gSystem->WorkingDirectory()<< endl;
2249      return contents;
2250    }
2251    ;
2252    //--------------------------------------
2253    //
2254    //
2255    //--------------------------------------
2256    /**
2257     * Get the Pamela detector chains from a list of files and make them friends.
2258     * @param fl Pointer to a TList of TSystemFiles
2259     * @param detlist String to select trees to be included
2260     * @return Pointer to a TChain
2261     */
2262    TChain *PamLevel2::GetPamTree(TList *fl, TString detlist) {
2263      //
2264      //
2265      //
2266      if (pam_tree) {
2267        printf("WARNING: TChain *PamLevel2::GetPamTree(TList *fl, TString detlist) -- pam_tree already exists!\n ");
2268        return pam_tree;
2269      };
2270      //
2271    
2272      TChain *Trout = 0;
2273    
2274      // -------------------------------------------
2275      // set flags to include/exclude trees/branches
2276      // -------------------------------------------
2277      if (detlist.Contains("+AUTO", TString::kIgnoreCase)) {
2278        if (fl->GetEntries() > 0) {
2279          cout << "+AUTO" << endl;
2280          TFile *fprimo = new TFile(fl->At(0)->GetName());
2281          GetWhichTrees(fprimo);
2282          fprimo->Close();// AAAAARGGGGGHHHHH!!!!!!! non commentare questa riga, altrimenti si incasina il TChain
2283          fprimo->Delete();
2284        }
2285      };
2286      SetWhichTrees(detlist);
2287    
2288      // -------------------------------------------
2289      // build chains
2290      // -------------------------------------------
2291      TChain *T = 0;
2292      TChain *C = 0;
2293      TChain *O = 0;
2294      TChain *R = 0;
2295      TChain *S = 0;
2296      TChain *N = 0;
2297      TChain *A = 0;
2298      TChain *B = 0;
2299      TChain *G = 0;
2300    
2301      TChain *L = 0;
2302    
2303      if (TRK2 || TRK1 || TRKh)
2304        T = new TChain("Tracker");
2305      if (CAL2 || CAL1)
2306        C = new TChain("Calorimeter");
2307      if (TOF)
2308        O = new TChain("ToF");
2309      if (TRG)
2310        R = new TChain("Trigger");
2311      if (S4)
2312        S = new TChain("S4");
2313      if (ND)
2314        N = new TChain("NeutronD");
2315      if (AC)
2316        A = new TChain("Anticounter");
2317      if (ORB)
2318        B = new TChain("OrbitalInfo");
2319      if (GP)
2320        G = new TChain("h20");
2321      L = new TChain("SelectionList");
2322    
2323      // loop over files and create chains
2324      TIter next(fl);
2325      TSystemFile *questo = 0;
2326      while ((questo = (TSystemFile*) next())) {
2327        TString name = questo->GetName();
2328        cout << "File: " << name << endl;
2329        if (CheckLevel2File(name)) {
2330          if (TRK2 || TRK1 || TRKh)
2331            T->Add(name);
2332          if (CAL1 || CAL2)
2333            C->Add(name);
2334          if (TOF)
2335            O->Add(name);
2336          if (TRG)
2337            R->Add(name);
2338          if (S4)
2339            S->Add(name);
2340          if (ND)
2341            N->Add(name);
2342          if (AC)
2343            A->Add(name);
2344          if (ORB)
2345            B->Add(name);
2346          if (GP)
2347            G->Add(name);
2348          if (SELLI == 1)
2349            L->Add(name);
2350        };
2351      };
2352    
2353      cout << "done chains\n";
2354      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
2355    
2356      // -------------------------------------------
2357      // make friends
2358      // -------------------------------------------
2359    
2360      // Tracker
2361      cout << "Friends: " << endl;
2362      if (T && (TRK2 || TRK1 || TRKh)) {
2363        if (!Trout)
2364          Trout = T;
2365        else
2366          Trout->AddFriend("Tracker");
2367        //  cout << "+Tacker"<<endl;
2368      };
2369      // Calorimeter
2370      if (C && (CAL2 || CAL1)) {
2371        if (!Trout)
2372          Trout = C;
2373        else
2374          Trout->AddFriend("Calorimeter");
2375        //  cout << "+Calorimeter"<<endl;
2376      };
2377      // ToF
2378      if (O && TOF) {
2379        if (!Trout)
2380          Trout = O;
2381        else
2382          Trout->AddFriend("ToF");
2383        //  cout << "+ToF"<<endl;
2384      };
2385      // Trigger
2386      if (R && TRG) {
2387        if (!Trout)
2388          Trout = O;
2389        else
2390          Trout->AddFriend("Trigger");
2391        //  cout << "+Trigger"<<endl;
2392      };
2393      // S4
2394      if (S && S4) {
2395        if (!Trout)
2396          Trout = O;
2397        else
2398          Trout->AddFriend("S4");
2399        //  cout << "+S4"<<endl;
2400      };
2401      // Neutron Detector
2402      if (N && ND) {
2403        if (!Trout)
2404          Trout = O;
2405        else
2406          Trout->AddFriend("NeutronD");
2407        //  cout << "+NeutronD"<<endl;
2408      };
2409      // Anticounters
2410      if (A && AC) {
2411        if (!Trout)
2412          Trout = O;
2413        else
2414          Trout->AddFriend("Anticounter");
2415        //  cout << "+Anticounter"<<endl;
2416      };
2417      // Orbital Info
2418      if (B && ORB) {
2419        if (!Trout)
2420          Trout = O;
2421        else
2422          Trout->AddFriend("OrbitalInfo");
2423        //  cout << "+OrbitalInfo"<<endl;
2424      };
2425      // GPamela
2426      if (G && GP) {
2427        if (!Trout)
2428          Trout = G;
2429        else
2430          Trout->AddFriend("h20");
2431        //  cout << "+h20"<<endl;
2432      };
2433    
2434      //  =====================================
2435      //  SET BRANCH-ADDRESS AFTER CHAIN+FRIEND
2436      //  =====================================
2437      SetBranchAddress(Trout);
2438    
2439      //  ------------------------------------
2440      //  finally handle selection trees...
2441      //  (it is not friend of pamela tree)
2442      //  ------------------------------------
2443    
2444      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
2445    
2446      // Selection List
2447      if (L && SELLI == 1) {
2448        cout << ">>> Found selection-list <<<" << endl;
2449        //  L->SetBranchAddress("RunEntry",&irun);
2450        L->SetBranchAddress("RunEntry", &irunt);//NEWNEW
2451        cout << "SelectionList: set branch address RunEntry" << endl;
2452        L->SetBranchAddress("EventEntry", &irunentry);
2453        cout << "SelectionList: set branch address EventEntry" << endl;
2454        /*    if ( L->GetBranch("L0EventEntry") ){
2455          hasL0EE = true;
2456          L->SetBranchAddress("L0EventEntry", &il0entry);
2457          cout << "SelectionList: set branch address L0EventEntry" << endl;
2458        } else {
2459          hasL0EE = false; // backward compatibility with old preselected files...
2460          }*/
2461        sel_tree = L;
2462        //          if(!Trout)Trout=O;
2463        //          else Trout->AddFriend("SelectionList");
2464        cout << "+SelectionList" << endl;
2465        cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
2466      }
2467      else {
2468        //  cout << "SelectionList  : missing tree"<<endl;
2469        if (L)
2470          L->Delete();
2471      };
2472    
2473      //  --------------------------------------------
2474      //  return the pamela chain with all the friends
2475      //  --------------------------------------------
2476    
2477      pam_tree = Trout;
2478    
2479      return Trout;
2480    }
2481    
2482    //--------------------------------------
2483    //
2484    //
2485    //--------------------------------------
2486    /**
2487     * Set branch addresses for Pamela friend trees
2488     */
2489    void PamLevel2::SetBranchAddress(TTree *t) {
2490    
2491      TRK2 = TRK2 & t->GetBranchStatus("TrkLevel2");
2492      TRK1 = TRK1 & t->GetBranchStatus("TrkLevel1");
2493      TRKh = TRKh & t->GetBranchStatus("TrkHough");
2494      CAL2 = CAL2 & t->GetBranchStatus("CaloLevel2");
2495      CAL1 = CAL1 & t->GetBranchStatus("CaloLevel1");
2496      TOF = TOF & t->GetBranchStatus("ToFLevel2");
2497      TRG = TRG & t->GetBranchStatus("TrigLevel2");
2498      S4 = S4 & t->GetBranchStatus("S4Level2");
2499      ND = ND & t->GetBranchStatus("NDLevel2");
2500      AC = AC & t->GetBranchStatus("AcLevel2");
2501      ORB = ORB & t->GetBranchStatus("OrbitalInfo");
2502      GP = GP & t->GetBranchStatus("h20");
2503    
2504      // Tracker
2505      if (TRK1) {
2506        t->SetBranchAddress("TrkLevel1", GetPointerTo("TrkLevel2"));
2507        cout << "Tracker      : set branch address TrkLevel1" << endl;
2508      };
2509      if (TRK2) {
2510        t->SetBranchAddress("TrkLevel2", GetPointerTo("TrkLevel1"));
2511        cout << "Tracker      : set branch address TrkLevel2" << endl;
2512      };
2513      if (TRKh) {
2514        t->SetBranchAddress("TrkHough", GetPointerTo("TrkHough"));
2515        cout << "Tracker      : set branch address TrkHough" << endl;
2516      };
2517    
2518      // Calorimeter
2519      if (CAL1) {
2520        t->SetBranchAddress("CaloLevel1", GetPointerTo("CaloLevel1"));
2521        cout << "Calorimeter  : set branch address CaloLevel1" << endl;
2522      };
2523      if (CAL2) {
2524        t->SetBranchAddress("CaloLevel2", GetPointerTo("CaloLevel2"));
2525        cout << "Calorimeter  : set branch address CaloLevel2" << endl;
2526      };
2527    
2528      // ToF
2529      if (TOF) {
2530        t->SetBranchAddress("ToFLevel2", GetPointerTo("ToFLevel2"));
2531        cout << "ToF          : set branch address ToFLevel2" << endl;
2532      };
2533      // Trigger
2534      if (TRG) {
2535        t->SetBranchAddress("TrigLevel2", GetPointerTo("TrigLevel2"));
2536        cout << "Trigger      : set branch address TrigLevel2" << endl;
2537      };
2538      // S4
2539      if (S4) {
2540        t->SetBranchAddress("S4Level2", GetPointerTo("S4Level2"));
2541        cout << "S4           : set branch address S4Level2" << endl;
2542      };
2543      // Neutron Detector
2544      if (ND) {
2545        t->SetBranchAddress("NDLevel2", GetPointerTo("NDLevel2"));
2546        cout << "NeutronD     : set branch address NDLevel2" << endl;
2547      };
2548      // Anticounters
2549      if (AC) {
2550        t->SetBranchAddress("AcLevel2", GetPointerTo("AcLevel2"));
2551        cout << "Anticounter  : set branch address AcLevel2" << endl;
2552      };
2553      // OrbitalInfo
2554      if (ORB) {
2555        t->SetBranchAddress("OrbitalInfo", GetPointerTo("OrbitalInfo"));
2556        cout << "OrbitalInfo  : set branch address OrbitalInfo" << endl;
2557      };
2558      // GPamela
2559      if (GP) {
2560        //  GetPointerTo("GPamela");
2561        if (!gp_obj)
2562          gp_obj = new GPamela();
2563        //  gp_obj->SetBranchAddress(t); //ho dovuto fare in maniera diversa dagli altri
2564        // //       t->SetBranchAddress("GPamela", GetPointerTo("GPamela"));
2565        if (SELLI)
2566          t->SetBranchAddress("GPamela", GetPointerTo("GPamela"));
2567        else
2568          gp_obj->SetBranchAddress(t); //ho dovuto fare in maniera diversa dagli altri
2569    
2570        cout << "h20          : set branch address GPamela " << endl;
2571      };
2572    
2573    }
2574    /**
2575     * Set branch addresses for Pamela friend trees
2576     */
2577    void PamLevel2::SetBranchAddress(TChain *t) {
2578    
2579      //     TRK2    = TRK2 & t->GetBranchStatus("TrkLevel2");
2580      //     TRK1    = TRK1 & t->GetBranchStatus("TrkLevel1");
2581      //     TRKh    = TRKh & t->GetBranchStatus("TrkHough");
2582      //     CAL1    = CAL1 & t->GetBranchStatus("CaloLevel1");
2583      //     CAL2    = CAL2 & t->GetBranchStatus("CaloLevel2");
2584      //     TOF    = TOF & t->GetBranchStatus("ToFLevel2");
2585      //     TRG    = TRG & t->GetBranchStatus("TrigLevel2");
2586      //     S4     = S4  & t->GetBranchStatus("S4Level2");
2587      //     ND     = ND  & t->GetBranchStatus("NDLevel2");
2588      //     AC     = AC  & t->GetBranchStatus("AcLevel2");
2589      //     ORB    = ORB & t->GetBranchStatus("OrbitalInfo");
2590      //    GP     = GP & t->GetBranchStatus("h20");
2591    
2592      // Tracker
2593      if (TRK2) {
2594        t->SetBranchAddress("TrkLevel2", GetPointerTo("TrkLevel2"));
2595        cout << "Tracker      : set branch address TrkLevel2" << endl;
2596      };
2597      if (TRK1) {
2598        t->SetBranchAddress("TrkLevel1", GetPointerTo("TrkLevel1"));
2599        cout << "Tracker      : set branch address TrkLevel1" << endl;
2600      };
2601      if (TRKh) {
2602        t->SetBranchAddress("TrkHough", GetPointerTo("TrkHough"));
2603        cout << "Tracker      : set branch address TrkHough" << endl;
2604      };
2605    
2606      // Calorimeter
2607      if (CAL2) {
2608        t->SetBranchAddress("CaloLevel2", GetPointerTo("CaloLevel2"));
2609        cout << "Calorimeter  : set branch address CaloLevel2" << endl;
2610      };
2611      if (CAL1) {
2612        t->SetBranchAddress("CaloLevel1", GetPointerTo("CaloLevel1"));
2613        cout << "Calorimeter  : set branch address CaloLevel1" << endl;
2614      };
2615    
2616      // ToF
2617      if (TOF) {
2618        t->SetBranchAddress("ToFLevel2", GetPointerTo("ToFLevel2"));
2619        cout << "ToF          : set branch address ToFLevel2" << endl;
2620      };
2621      // Trigger
2622      if (TRG) {
2623        t->SetBranchAddress("TrigLevel2", GetPointerTo("TrigLevel2"));
2624        cout << "Trigger      : set branch address TrigLevel2" << endl;
2625      };
2626      // S4
2627      if (S4) {
2628        t->SetBranchAddress("S4Level2", GetPointerTo("S4Level2"));
2629        cout << "S4           : set branch address S4Level2" << endl;
2630      };
2631      // Neutron Detector
2632      if (ND) {
2633        t->SetBranchAddress("NDLevel2", GetPointerTo("NDLevel2"));
2634        cout << "NeutronD     : set branch address NDLevel2" << endl;
2635      };
2636      // Anticounters
2637      if (AC) {
2638        t->SetBranchAddress("AcLevel2", GetPointerTo("AcLevel2"));
2639        cout << "Anticounter  : set branch address AcLevel2" << endl;
2640      };
2641      // OrbitalInfo
2642      if (ORB) {
2643        t->SetBranchAddress("OrbitalInfo", GetPointerTo("OrbitalInfo"));
2644        cout << "OrbitalInfo  : set branch address OrbitalInfo" << endl;
2645      };
2646      // GPamela
2647      //    cout <<"GP "<<GP<<endl;
2648      if (GP) {
2649        //  GetPointerTo("GPamela");
2650        if (!gp_obj)
2651          gp_obj = new GPamela();
2652        if (SELLI)
2653          t->SetBranchAddress("GPamela", GetPointerTo("GPamela"));
2654        else
2655          gp_obj->SetBranchAddress(t); //ho dovuto fare in maniera diversa dagli altri
2656        //  gp_obj->SetBranchAddress(t); //ho dovuto fare in maniera diversa dagli altri
2657        cout << "h20          : set branch address GPamela " << endl;
2658      };
2659      // SelectionList
2660      //     if(SELLI==1){
2661      //    t->SetBranchAddress("RunEntry",&irunt);//NEWNEW
2662      //    cout << "SelectionList: set branch address RunEntry"<<endl;
2663      //    t->SetBranchAddress("EventEntry",&irunentry);
2664      //    cout << "SelectionList: set branch address EventEntry"<<endl;
2665    
2666      //     }
2667    
2668    }
2669    
2670    //--------------------------------------
2671    //
2672    //
2673    //--------------------------------------
2674    /**
2675     * Get the Run tree chain from a list of files.
2676     * @param fl Pointer to a TList of TSystemFiles
2677     * @return Pointer to a TChain
2678     */
2679    TChain *PamLevel2::GetRunTree(TList *fl) {
2680      //
2681      //
2682      //
2683      if (run_tree) {
2684        printf("WARNING: TChain *PamLevel2::GetRunTree(TList *fl) -- run_tree already exists!\n ");
2685        return run_tree;
2686      };
2687      //
2688    
2689    
2690      TChain *R = new TChain("Run");
2691    
2692      // loop over files and create chains
2693      TIter next(fl);
2694      TSystemFile *questo = 0;
2695      while ((questo = (TSystemFile*) next())) {
2696        TString name = questo->GetName();
2697        //          cout << "File: "<< name << endl;
2698        if (CheckLevel2File(name)) {
2699          R->Add(name);
2700        };
2701      }
2702    
2703      if (RUN && R->GetNtrees()) {
2704    
2705        R->SetBranchAddress("RunInfo", GetPointerTo("RunInfo"));
2706        cout << "Run         : set branch address RunInfo" << endl;
2707        R->SetBranchAddress("SoftInfo", GetPointerTo("SoftInfo")); // Emiliano
2708        cout << "Software    : set branch address SoftInfo" << endl; // Emiliano
2709    
2710        irunoffset = new int[R->GetNtrees()];
2711        if (DBG) {
2712          cout << "----------------------------------------------------" << endl;
2713          cout << "irun\t | ";
2714          cout << "tree\t |";
2715          //        cout << "offset\t |";
2716          cout << "RUN\t";
2717          cout << "FRAG\t";
2718          cout << "NEVENTS\t";
2719          cout << "absolute time\t\t\t";
2720          cout << "on-board time";
2721          cout << endl;
2722        }
2723        for (Int_t ii = 0; ii < R->GetEntries(); ii++) {
2724          R->GetEntry(ii);
2725          if (DBG) {
2726            cout << ii << "\t | ";
2727            cout << R->GetTreeNumber() << "\t |";
2728            //          cout << R->GetChainOffset()<< "\t |";
2729            cout << GetRunInfo()->ID << "\t";
2730            cout << GetRunInfo()->ID_RUN_FRAG << "\t";
2731            cout << GetRunInfo()->NEVENTS << "\t";
2732            cout << GetRunInfo()->RUNHEADER_TIME << " <---> " << GetRunInfo()->RUNTRAILER_TIME << "\t";
2733            cout << GetRunInfo()->RUNHEADER_OBT << " <---> " << GetRunInfo()->RUNTRAILER_OBT << "\t";
2734            cout << endl;
2735          }
2736          irunoffset[R->GetTreeNumber()] = R->GetChainOffset();
2737        }
2738        cout << "N.run = " << R->GetEntries() << endl;
2739        cout << "----------------------------------------------------" << endl;
2740    
2741      }
2742      else {
2743        delete R;
2744        R = 0;
2745      }
2746    
2747      run_tree = R;
2748    
2749      return R;
2750    
2751    }
2752    //--------------------------------------
2753    //
2754    //
2755    //--------------------------------------
2756    /**
2757     * Get the Run tree  from a file.
2758     * @param f Pointer to a TFile
2759     * @return Pointer to a TTree
2760     */
2761    TTree *PamLevel2::GetRunTree(TFile *f) {
2762      if (run_tree) {
2763        printf("WARNING: TTree *PamLevel2::GetRunTree(TFile *f) -- run_tree already exists!\n ");
2764        return run_tree;
2765      };
2766    
2767      cout << "TTree *PamLevel2::GetRunTree(TFile *f) -- obsolte " << endl;
2768    
2769      TTree *T = (TTree*) f->Get("Run");
2770    
2771      if (T) {
2772        T->SetBranchAddress("RunInfo", GetPointerTo("RunInfo"));
2773        cout << "Run         : set branch address RunInfo" << endl;
2774        T->SetBranchAddress("SoftInfo", GetPointerTo("SoftInfo")); // Emiliano
2775        cout << "Software    : set branch address SoftInfo" << endl; // Emiliano
2776    
2777      }
2778    
2779      run_tree = (TChain*) T;
2780    
2781      return T;
2782    
2783    }
2784    
2785    Bool_t PamLevel2::UpdateRunInfo(Long64_t iev) {
2786    
2787      if (DBG) printf("PamLevel2::UpdateRunInfo(Long64_t) - inside\n");
2788    
2789      if (!run_tree) {
2790        cout << " Bool_t PamLevel2::UpdateRunInfo(ULong64_t iev) -- ERROR -- run tree not loaded" << endl;
2791        return false;
2792      }
2793      if (run_tree->GetEntries() <= 0) {
2794        cout << " Bool_t PamLevel2::UpdateRunInfo(ULong64_t iev) -- ERROR -- run tree is empty" << endl;
2795        return (false);
2796      }
2797    
2798    
2799      Int_t oldrun = irun; // store current run index
2800    
2801      // -----------------------------------------------------------------------
2802      // the first time the routine is called, set run search from the beginning
2803      // -----------------------------------------------------------------------
2804    
2805      if (irun < 0) {
2806        irun = 0LL;
2807        irunt = 0LL;
2808        totrunentry = 0LL;
2809        totrunentrymin = 0LL;
2810        totrunentrymax = 0LL;
2811        irunentry = 0LL;
2812        il0entry = 0LL;
2813        prevshift = 0;
2814        yprevshift = 0;
2815        prevabstime = 0;
2816        prevpktnum = 0;
2817        abstime = 0ULL;
2818        pktnum = 0;
2819        isFragment = false;
2820        run_tree->GetEntry(irun);
2821        if (!GetOrbitalInfo())
2822          cout << "** WARNING ** missing OrbitalInfo ---> run info might be not correctly updated " << endl;
2823        if (gltsync)
2824          delete gltsync; //Emiliano
2825        if (!dbc || (dbc && !dbc->IsConnected()))
2826          SetDBConnection(); //Emiliano
2827        gltsync = new GL_TIMESYNC(GetRunInfo()->ID_ROOT_L0, "ID", dbc, false); //Emiliano // the "false" means not to use level0 file (not necessary here)
2828        if (dbc){
2829          dbc->Close();// Emiliano
2830          delete dbc;
2831          dbc=0;
2832        };
2833      };
2834      // ---------------------------------------------------------------
2835      // retrieve OBT and absolute time of the event
2836      // ---------------------------------------------------------------
2837      Long64_t obt = 0LL; // Emiliano, Long64_t GL_TIMESYNC::DBobt(UInt_t obt) since depending on the situation OBT is lowered or boosted
2838      prevabstime = abstime;
2839      prevpktnum = pktnum;
2840      if (GetOrbitalInfo()) {
2841        abstime = GetOrbitalInfo()->absTime;
2842        obt = gltsync->DBobt(GetOrbitalInfo()->OBT); // Emiliano
2843        pktnum = GetOrbitalInfo()->pkt_num; // Emiliano
2844      }
2845      else {
2846        abstime = GetRunInfo()->RUNHEADER_TIME;
2847        obt = gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT); // Emiliano
2848        pktnum = GetRunInfo()->RUNHEADER_PKT; // Emiliano
2849      }
2850    
2851      if (DBG){
2852        printf("0abstime %lld %lld pktnum %d %d obt %lld \n",abstime,prevabstime,pktnum,prevpktnum,obt);
2853        printf("0        rth %d %d nevents %d  \n",GetRunInfo()->RUNHEADER_TIME,GetRunInfo()->RUNTRAILER_TIME,GetRunInfo()->NEVENTS);
2854        printf("0        rto %d %d \n",GetRunInfo()->RUNHEADER_OBT,GetRunInfo()->RUNTRAILER_OBT);
2855        printf("0        rto2 %lld %lld \n",gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT),gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT));
2856        printf("0        bo irunentry %lld prevshift %lld irun %lld  \n",irunentry,prevshift,irun);
2857        printf("0        min %lld iev %lld max %lld tot %lld \n",totrunentrymin,iev,totrunentrymax,totrunentry);
2858      }
2859    
2860      // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
2861      // if it is a full file (not preselected)
2862      // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
2863      if (SELLI == 0 || SELLI == 2) { // Emiliano
2864    
2865        // ---------------------------------------------------------------
2866        // increment dead and live-time counters
2867        // (only when reading a file not preselected)
2868        // ---------------------------------------------------------------
2869        if (SELLI == 0) {
2870          if (GetTrigLevel2()) {
2871            totdltime[0] += GetTrigLevel2()->dltime[0];
2872            totdltime[1] += GetTrigLevel2()->dltime[1];
2873          }
2874          totdltime[2]++;
2875        }
2876    
2877        //
2878        if ( iev < totrunentrymin || iev > totrunentrymax // entry is outside run limits
2879             || iev == 0 // or it is the first entry
2880             || (!isSync && (
2881                             (abstime <= GetRunInfo()->RUNHEADER_TIME && obt < gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT) ) // or it is outside obt limits (and abstime limits for security reasons)
2882                             || (abstime >= GetRunInfo()->RUNTRAILER_TIME && obt > gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT) ) ))// or it is outside obt limits (and abstime limits for security reasons)
2883             ){ // check on abstime and obt needed to handle nested+DV_skipped packets
2884          
2885          // check for a new run (ma prima il primo!)
2886          if (DBG){
2887            printf("1abstime %lld %lld pktnum %d %d obt %lld \n",abstime,prevabstime,pktnum,prevpktnum,obt);
2888            printf("1        rth %d %d nevents %d  \n",GetRunInfo()->RUNHEADER_TIME,GetRunInfo()->RUNTRAILER_TIME,GetRunInfo()->NEVENTS);
2889            printf("1        rto %d %d \n",GetRunInfo()->RUNHEADER_OBT,GetRunInfo()->RUNTRAILER_OBT);
2890            printf("1        rto2 %lld %lld \n",gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT),gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT));
2891            printf("1        bo irunentry %lld prevshift %lld irun %lld  \n",irunentry,prevshift,irun);
2892            printf("1        min %lld iev %lld max %lld tot %lld \n",totrunentrymin,iev,totrunentrymax,totrunentry);
2893          }
2894          //        printf("1abstime %lld %lld pktnum %d %d obt %lld \n",abstime,prevabstime,pktnum,prevpktnum,obt);
2895          //        printf("1        rth %d %d nevents %d  \n",GetRunInfo()->RUNHEADER_TIME,GetRunInfo()->RUNTRAILER_TIME,GetRunInfo()->NEVENTS);
2896          //        printf("1        rto %d %d \n",GetRunInfo()->RUNHEADER_OBT,GetRunInfo()->RUNTRAILER_OBT);
2897          //        printf("1        rto2 %lld %lld \n",gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT),gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT));
2898          //        printf("1        bo irunentry %lld prevshift %lld irun %lld  \n",irunentry,prevshift,irun);
2899          //        printf("1        min %lld iev %lld max %lld tot %lld \n",totrunentrymin,iev,totrunentrymax,totrunentry);//TOGLITOGLI
2900    
2901          totrunentry = 0LL;
2902          runfirstentry = 0LL;
2903          for (Int_t r=0; r< run_tree->GetEntries();r++){
2904            // -------------------------------------------------------------------
2905            // save the index of the first entry of the run, relative to pam_tree,
2906            // and read a new run
2907            // -------------------------------------------------------------------
2908            run_tree->GetEntry(r);//update runinfo
2909            if ( r > 0 ){
2910              totrunentrymin = totrunentrymax+1;
2911            } else {
2912              totrunentrymin = 0LL;
2913            }
2914            totrunentry += GetRunInfo()->NEVENTS;
2915            totrunentrymax = totrunentry - 1 - prevshift; // prevshift is needed to handle nested+DV_skipped packets
2916            irun = r;        
2917    
2918            if ( (iev >= totrunentrymin && iev <= totrunentrymax) || // entry is inside run limits
2919                 ( !isSync &&
2920                   ( abstime >= GetRunInfo()->RUNHEADER_TIME  && obt >= gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT) // or it is inside obt limits (and abstime limits for security reasons)
2921                     && abstime <= GetRunInfo()->RUNTRAILER_TIME && obt <= gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT)))  // or it is inside obt limits (and abstime limits for security reasons)
2922                 ){ // check on abstime and obt needed to handle nested+DV_skipped packets
2923              if ( totrunentrymin > iev ){ // there is a shift (nested+DV_skipped packets)
2924                if ( !isSync ){
2925                  if (DBG) printf("PamLevel2::UpdateRunInfo(Long64_t) - unconsistent iev - nevents, probable DBL0-L2 async\n");
2926                  if (DBG) printf("PamLevel2::UpdateRunInfo(Long64_t) - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);
2927                  //              printf("PamLevel2::UpdateRunInfo(Long64_t) - unconsistent iev - nevents, probable DBL0-L2 async\n");
2928                  //              printf("PamLevel2::UpdateRunInfo(Long64_t) - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);//TOGLITOGLI
2929                  prevshift += (totrunentrymin-iev); // add the new shift to total shift
2930                  totrunentrymin -= (totrunentrymin-iev); // shift run position min
2931                  totrunentrymax -= (totrunentrymin-iev); // shift run position max
2932                  if (DBG) printf("PamLevel2::UpdateRunInfo(Long64_t) - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);
2933                  //              printf("PamLevel2::UpdateRunInfo(Long64_t) - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);//TOGLITOGLI
2934                } else {
2935                  printf(" PamLevel2::UpdateRunInfo(Long64_t) ERROR! sync file but unconsistent totrunetrymin %lld and iev %lld!!! \n",totrunentrymin,iev);
2936                  cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
2937                  cout << "\nFor bug reporting instructions, please see for example:\n";
2938                  cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
2939                  cout << "  " << endl;
2940                }
2941              }
2942              runfirstentry = totrunentrymin; // first entry of the run in the level2
2943              
2944    
2945              //
2946              if (gltsync)
2947                delete gltsync; // Emiliano
2948              if (!dbc || (dbc && !dbc->IsConnected()))
2949                SetDBConnection(); //Emiliano
2950              gltsync = new GL_TIMESYNC(GetRunInfo()->ID_ROOT_L0, "ID", dbc, false); // Emiliano
2951              if (dbc){
2952                dbc->Close(); // Emiliano
2953                delete dbc;
2954                dbc=0;
2955              }          
2956              if (gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT) > gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT)) { // Emiliano
2957                cout << "Bool_t PamLevel2::UpdateRunInfo(Long64_t iev) -- WARNING -- irun " << irun
2958                     << "  has RUNHEADER_OBT>=RUNTRAILER_OBT " << endl;
2959                cout
2960                  << "                                                            (NB!! in this case some events could be assigned to a wrong run)"
2961                  << endl;
2962              }
2963              //
2964              if (DBG) printf(" found \n");
2965              //          printf(" found \n");//TOGLITOGLI
2966              //
2967              break;
2968            }
2969          } // loop over run
2970          
2971          // --------------------------------------
2972          // if there was no need to update the run
2973          // ---> exit with FALSE
2974          // --------------------------------------
2975          if (irun == oldrun){
2976            if (DBG) printf(" no new run \n");
2977            //        printf(" no new run \n");//TOGLITOGLI
2978            return (false);
2979          }      
2980          // --------------------------------------
2981          // ... otherwise
2982          // ---> exit with TRUE
2983          // --------------------------------------
2984    
2985          if (SELLI != 2) {
2986            /// decrement counters since this event belongs to a new run
2987            if (GetTrigLevel2()) {
2988              totdltime[0] -= GetTrigLevel2()->dltime[0];//live-time
2989              totdltime[1] -= GetTrigLevel2()->dltime[1];//dead-time
2990            }
2991            totdltime[2]--; //event counter
2992            if (DBG) {
2993              cout << endl;
2994              cout << "n.events     : " << totdltime[2] << endl;
2995              cout << "RUN LIVE-TIME: " << totdltime[0] * 0.16 << " ms" << endl;
2996              cout << "RUN DEAD-TIME: " << totdltime[1] * 0.01 << " ms" << endl;
2997            }
2998            // add an entry
2999            if (run_tree_clone && totdltime[2] > 0)
3000              if (run_tree_clone->GetBranch("DeadLiveTime")->GetEntries() < run_tree->GetEntries())
3001                run_tree_clone->GetBranch("DeadLiveTime")->Fill();
3002            // reset counters
3003            if ( totdltime[2] > 0 ){
3004              if (GetTrigLevel2()) {
3005                totdltime[0] = GetTrigLevel2()->dltime[0];//live-time
3006                totdltime[1] = 0; //dead-time
3007              }
3008              totdltime[2] = 1; //event counter
3009            }
3010          }
3011    
3012          if (DBG){
3013            cout << endl << " ))))) UPDATE RUN INFO (((((  @iev " << iev << " run " << GetRunInfo()->ID << " irun " << irun
3014                 << endl;        
3015            printf("2abstime %lld %lld pktnum %d %d obt %lld \n",abstime,prevabstime,pktnum,prevpktnum,obt);
3016            printf("2        rth %d %d nevents %d  \n",GetRunInfo()->RUNHEADER_TIME,GetRunInfo()->RUNTRAILER_TIME,GetRunInfo()->NEVENTS);
3017            printf("2        rto %d %d \n",GetRunInfo()->RUNHEADER_OBT,GetRunInfo()->RUNTRAILER_OBT);
3018            printf("2        rto2 %lld %lld \n",gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT),gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT));
3019            printf("2        bo irunentry %lld prevshift %lld irun %lld  \n",irunentry,prevshift,irun);
3020            printf("2        min %lld iev %lld max %lld tot %lld \n",totrunentrymin,iev,totrunentrymax,totrunentry);
3021          }
3022          //        printf("2abstime %lld %lld pktnum %d %d obt %lld \n",abstime,prevabstime,pktnum,prevpktnum,obt);
3023          //        printf("2        rth %d %d nevents %d  \n",GetRunInfo()->RUNHEADER_TIME,GetRunInfo()->RUNTRAILER_TIME,GetRunInfo()->NEVENTS);
3024          //        printf("2        rto %d %d \n",GetRunInfo()->RUNHEADER_OBT,GetRunInfo()->RUNTRAILER_OBT);
3025          //        printf("2        rto2 %lld %lld \n",gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT),gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT));
3026          //        printf("2        bo irunentry %lld prevshift %lld irun %lld  \n",irunentry,prevshift,irun);
3027          //        printf("2        min %lld iev %lld max %lld tot %lld \n",totrunentrymin,iev,totrunentrymax,totrunentry);//TOGLITOGLI
3028    
3029          return (true);
3030        } // need for run upgrade
3031        if (DBG) printf("return false\n");
3032        return (false);
3033      }// SELLI = 0 SELLI = 2
3034      
3035      // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
3036      // if it is a preselected file (there is SelectionList)
3037      // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
3038      // irun  = run entry relative to the chain
3039      // irunt = run entry relative to the tree
3040      if (SELLI == 1) {
3041        sel_tree->GetEntry(iev);// read irunt from SelectionList
3042        irun = irunt + irunoffset[sel_tree->GetTreeNumber()];//NEWNEW
3043        if (irun != oldrun) {
3044          if (irun < run_tree->GetEntries())
3045            run_tree->GetEntry(irun);
3046          // check if the time is ok (with merged files it is not...)
3047          // if not loop over run and look for the proper entry
3048          bool SECONDO_GIRO = false;
3049          //            Long64_t irun_start   = irun;
3050          int offset_start = irunoffset[sel_tree->GetTreeNumber()];
3051          while (((!(abstime >= GetRunInfo()->RUNHEADER_TIME && // check on absolute time (s)
3052              abstime <= GetRunInfo()->RUNTRAILER_TIME)
3053          //                        ||
3054          //                        !(obt >= GetRunInfo()->RUNHEADER_OBT &&         // additional check on OBT (ms)
3055          //                          obt <= GetRunInfo()->RUNTRAILER_OBT)
3056          ) || GetRunInfo()->NEVENTS == 0)
3057          //                && irun < run_tree->GetEntries()
3058          ) {
3059    
3060            if (DBG) {
3061              cout << " (test) ";
3062              cout << " tree " << sel_tree->GetTreeNumber();
3063              cout << " irunt " << irunt;
3064              cout << " offset " << irunoffset[sel_tree->GetTreeNumber()];
3065              cout << " abs " << abstime;
3066              cout << " >> " << GetRunInfo()->RUNHEADER_TIME << " " << GetRunInfo()->RUNTRAILER_TIME;
3067              cout << " obt " << obt;
3068              cout << " >> " << GetRunInfo()->RUNHEADER_OBT << " " << GetRunInfo()->RUNTRAILER_OBT;
3069              cout << " *** JUMP RUN *** irun " << irun;
3070              cout << endl;
3071            }
3072            //              irun++;
3073            irunoffset[sel_tree->GetTreeNumber()]++;
3074            irun = irunt + irunoffset[sel_tree->GetTreeNumber()];//NEWNEW
3075            if (irun == run_tree->GetEntries() && SECONDO_GIRO) {
3076              //            if(irun == irun_start ){
3077              cout << " ...grrrvzzkhhhajsdkj!!!! " << endl;
3078              irunoffset[sel_tree->GetTreeNumber()] = offset_start;
3079              return false;
3080            }
3081            if (irun >= run_tree->GetEntries() || irun < 0) {
3082              cout << "irun = " << irun << " >>  search from the beginning... <<" << endl;
3083              SECONDO_GIRO = true;
3084              irun = 0;
3085              irunoffset[sel_tree->GetTreeNumber()] = -irunt;
3086            }
3087            run_tree->GetEntry(irun);
3088          }
3089    
3090          if (DBG) {
3091            cout << " (test) ";
3092            cout << " tree " << sel_tree->GetTreeNumber();
3093            cout << " irunt " << irunt;
3094            cout << " offset " << irunoffset[sel_tree->GetTreeNumber()];
3095            cout << " abs " << abstime;
3096            cout << " >> " << GetRunInfo()->RUNHEADER_TIME << " " << GetRunInfo()->RUNTRAILER_TIME;
3097            cout << " obt " << obt;
3098            cout << " >> " << GetRunInfo()->RUNHEADER_OBT << " " << GetRunInfo()->RUNTRAILER_OBT;
3099          }
3100          if (DBG)
3101            cout << endl;
3102          if (DBG)
3103            cout << endl << " ))))) UPDATE RUN INFO (((((  @iev " << iev << " run " << GetRunInfo()->ID << " (run-entry "
3104                << irun << ")" << endl;
3105          // ----------------------------------------------------
3106          // update the tracker parameters
3107          // (non ho trovato nessun altro modo sicuro di farlo...)
3108          // ----------------------------------------------------
3109          if (!dbc || (dbc && !dbc->IsConnected()))
3110            SetDBConnection();
3111          TrkParams::Set(GetRunInfo(), dbc);
3112          if (dbc){
3113            dbc->Close();
3114            delete dbc;
3115            dbc=0;
3116          };
3117          //            cout << endl;
3118          prevshift = 0;
3119          yprevshift = 0;
3120          return true;
3121        }
3122        return false;
3123      }
3124    
3125      return false;
3126      //
3127    }
3128    
3129    /**
3130     * Update the runinfo informations (to be used to have Run infos event by event basis)
3131     * @param run Pointer to the chain/tree which contains run infos
3132     * @return true if a new run has been read, false if it is still the same run
3133     */
3134    Bool_t PamLevel2::UpdateRunInfo(TChain *run, Long64_t iev) {
3135      return (UpdateRunInfo(iev));
3136    }
3137    
3138    /**
3139     * Update the runinfo informations (to be used to have Run infos event by event basis)
3140     * @param run Pointer to the chain/tree which contains run infos
3141     * @return true if a new run has been read, false if it is still the same run
3142   */   */
3143  TTree *PamLevel2::GetRunTree(TFile *f){  Bool_t PamLevel2::UpdateRunInfo(TTree *run, Long64_t iev) {
3144      return (UpdateRunInfo((TChain*) run, iev));
3145    }
3146    
3147    
     TTree *R = (TTree*)f->Get("Run");  
       
     R->SetBranchAddress("RunInfo", GetPointerToRun());  
     cout << "Run         : set branch address RunInfo"<<endl;  
       
     return R;  
       
 }  
3148  //--------------------------------------  //--------------------------------------
3149  //  //
3150  //  //
3151  //--------------------------------------  //--------------------------------------
3152  /**  /**
3153   * Set which trees should be analysed   * Set which trees shoul be analysed
3154   * @param detlist TString containing the sequence of trees required   * @param detlist TString containing the sequence of trees required
3155  */   */
3156  void PamLevel2::SetWhichTrees(TString detlist){  void PamLevel2::SetWhichTrees(TString detlist) {
3157            
3158      if(detlist.Contains("+ALL", TString::kIgnoreCase)){    //    if(detlist.IsNull() || detlist.Contains("+ALL", TString::kIgnoreCase)){
3159          CAL = true;    if (detlist.Contains("+ALL", TString::kIgnoreCase)) {
3160          TRK = true;  
3161          TRK_L1 = false;      cout << " ======================================================== " << endl;
3162          TRG = true;      cout << "                       (( WARNING ))                      " << endl;
3163          TOF = true;      cout << " The meaning of the option +ALL has changed!!             " << endl;
3164          S4  = true;      cout << " Now it includes really all (level0+level1+level2+gpamela)" << endl;
3165          ND  = true;      cout << " and the file is discarded if it does not contain         " << endl;
3166          AC  = true;      cout << " all trees or  if level0 files are not available!!        " << endl;
3167          ORB = true;      cout << " ======================================================== " << endl;
3168      }else if( detlist.Contains("-ALL", TString::kIgnoreCase) ){  
3169          CAL = false;      CAL0 = true;
3170          TRK = false;      CAL1 = true;
3171          TRK_L1 = false;      CAL2 = true;
3172          TRG = false;      TRK2 = true;
3173          TOF = false;      TRK1 = true;
3174          S4  = false;      TRKh = true;
3175          ND  = false;      TRK0 = true;
3176          AC  = false;      TRG = true;
3177          ORB = false;      TOF = true;
3178        TOF0 = true;
3179        S4 = true;
3180        ND = true;
3181        AC = true;
3182        ORB = true;
3183        GP = true;
3184      }
3185      else if (detlist.Contains("-ALL", TString::kIgnoreCase)) {
3186        CAL0 = false;
3187        CAL1 = false;
3188        CAL2 = false;
3189        TRK2 = false;
3190        TRK1 = false;
3191        TRKh = false;
3192        TRK0 = false;
3193        TRG = false;
3194        TOF = false;
3195        TOF0 = false;
3196        S4 = false;
3197        ND = false;
3198        AC = false;
3199        ORB = false;
3200        GP = false;
3201      };
3202    
3203      //  -------------------------------------------------------------------------
3204      if (detlist.Contains("CAL1", TString::kIgnoreCase)) {
3205        if (detlist.Contains("-CAL1", TString::kIgnoreCase))
3206          CAL1 = false;
3207        if (detlist.Contains("+CAL1", TString::kIgnoreCase))
3208          CAL1 = true;
3209      };
3210    
3211      if (detlist.Contains("CAL0", TString::kIgnoreCase)) {
3212        if (detlist.Contains("-CAL0", TString::kIgnoreCase))
3213          CAL0 = false;
3214        if (detlist.Contains("+CAL0", TString::kIgnoreCase))
3215          CAL0 = true;
3216      };
3217    
3218      if (detlist.Contains("CAL2", TString::kIgnoreCase)) {
3219        if (detlist.Contains("-CAL2", TString::kIgnoreCase))
3220          CAL2 = false;
3221        if (detlist.Contains("+CAL2", TString::kIgnoreCase))
3222          CAL2 = true;
3223      };
3224    
3225      if (detlist.Contains("+CAL", TString::kIgnoreCase) && !CAL1 && !CAL2)
3226        CAL2 = true;
3227      if (detlist.Contains("-CAL", TString::kIgnoreCase) && CAL1 && CAL2) {
3228        CAL2 = false;
3229        CAL1 = false;
3230      }
3231      //  -------------------------------------------------------------------------
3232      if (detlist.Contains("TRK0", TString::kIgnoreCase)) {
3233        if (detlist.Contains("-TRK0", TString::kIgnoreCase))
3234          TRK0 = false;
3235        if (detlist.Contains("+TRK0", TString::kIgnoreCase))
3236          TRK0 = true;
3237      };
3238    
3239      if (detlist.Contains("TRK1", TString::kIgnoreCase)) {
3240        if (detlist.Contains("-TRK1", TString::kIgnoreCase))
3241          TRK1 = false;
3242        if (detlist.Contains("+TRK1", TString::kIgnoreCase))
3243          TRK1 = true;
3244      };
3245    
3246      if (detlist.Contains("TRK2", TString::kIgnoreCase)) {
3247        if (detlist.Contains("-TRK2", TString::kIgnoreCase))
3248          TRK2 = false;
3249        if (detlist.Contains("+TRK2", TString::kIgnoreCase))
3250          TRK2 = true;
3251      };
3252    
3253      if (detlist.Contains("TRKh", TString::kIgnoreCase)) {
3254        if (detlist.Contains("-TRKh", TString::kIgnoreCase))
3255          TRKh = false;
3256        if (detlist.Contains("+TRKh", TString::kIgnoreCase))
3257          TRKh = true;
3258      };
3259    
3260      if (detlist.Contains("+TRK", TString::kIgnoreCase) && !TRK1 && !TRK2 && !TRKh)
3261        TRK2 = true;
3262      if (detlist.Contains("-TRK", TString::kIgnoreCase) && TRK1 && TRK2 && TRKh) {
3263        TRK2 = false;
3264        TRK1 = false;
3265        TRKh = false;
3266      }
3267      //  -------------------------------------------------------------------------
3268    
3269      if (detlist.Contains("-TRG", TString::kIgnoreCase))
3270        TRG = false;
3271      else if (detlist.Contains("+TRG", TString::kIgnoreCase))
3272        TRG = true;
3273    
3274      if (detlist.Contains("-TOF", TString::kIgnoreCase))
3275        TOF = false;
3276      else if (detlist.Contains("+TOF", TString::kIgnoreCase))
3277        TOF = true;
3278    
3279      if (detlist.Contains("-TOF0", TString::kIgnoreCase))
3280        TOF0 = false;
3281      else if (detlist.Contains("+TOF0", TString::kIgnoreCase))
3282        TOF0 = true;
3283    
3284      if (detlist.Contains("-S4", TString::kIgnoreCase))
3285        S4 = false;
3286      else if (detlist.Contains("+S4", TString::kIgnoreCase))
3287        S4 = true;
3288    
3289      if (detlist.Contains("-ND", TString::kIgnoreCase))
3290        ND = false;
3291      else if (detlist.Contains("+ND", TString::kIgnoreCase))
3292        ND = true;
3293    
3294      if (detlist.Contains("-AC", TString::kIgnoreCase))
3295        AC = false;
3296      else if (detlist.Contains("+AC", TString::kIgnoreCase))
3297        AC = true;
3298    
3299      if (detlist.Contains("-ORB", TString::kIgnoreCase))
3300        ORB = false;
3301      else if (detlist.Contains("+ORB", TString::kIgnoreCase))
3302        ORB = true;
3303    
3304      if (detlist.Contains("-GP", TString::kIgnoreCase))
3305        GP = false;
3306      else if (detlist.Contains("+GP", TString::kIgnoreCase))
3307        GP = true;
3308    
3309      cout << "tree/branch list from input --> ";
3310      if (TRK0)
3311        cout << "TRK0 ";
3312      if (TRK1)
3313        cout << "TRK1 ";
3314      if (TRK2)
3315        cout << "TRK2 ";
3316      if (TRKh)
3317        cout << "TRKH ";
3318      if (CAL0)
3319        cout << "CAL0 ";
3320      if (CAL1)
3321        cout << "CAL1 ";
3322      if (CAL2)
3323        cout << "CAL2 ";
3324      if (TOF)
3325        cout << "TOF ";
3326      if (TRG)
3327        cout << "TRG ";
3328      if (AC)
3329        cout << "AC ";
3330      if (ND)
3331        cout << "ND ";
3332      if (S4)
3333        cout << "S4 ";
3334      if (ORB)
3335        cout << "ORB ";
3336      if (GP)
3337        cout << "GP ";
3338      cout << endl;
3339      //     cout<< "Set detector list --> ";
3340      //     if(TRK1)cout<<"TRK1 ";
3341      //     if(TRK2)cout<<"TRK2 ";
3342      //     if(TRKh)cout<<"TRKH ";
3343      //     if(CAL1)cout<<"CAL1 ";
3344      //     if(CAL2)cout<<"CAL2 ";
3345      //     if(TOF0)cout<<"TOF0 ";
3346      //     if(TOF)cout<<"TOF ";
3347      //     if(TRG)cout<<"TRG ";
3348      //     if(AC)cout<<"AC ";
3349      //     if(ND)cout<<"ND ";
3350      //     if(S4)cout<<"S4 ";
3351      //     if(ORB)cout<<"ORB ";
3352      //     cout << endl;
3353    
3354    }
3355    ;
3356    
3357    /**
3358     * Set tree/branch detector flags from the content of a tree
3359     */
3360    void PamLevel2::GetWhichTrees(TFile* f) {
3361    
3362      //    cout << "void  PamLevel2::GetWhichTrees(TFile* f) --- WARNING!! --- ...potrebbe non funzionare "<<endl;
3363      // -----------
3364      // reset flags
3365      // -----------
3366      CAL1 = false;
3367      CAL2 = false;
3368      TRK2 = false;
3369      TRK1 = false;
3370      TRKh = false;
3371      TRG = false;
3372      TOF = false;
3373      S4 = false;
3374      ND = false;
3375      AC = false;
3376      ORB = false;
3377      GP = false;
3378    
3379      RUN = false;
3380    
3381      //    cout << "Checking file: "<<f->GetName()<<endl;
3382      if (!f || f->IsZombie()) {
3383        cout << "File: " << f->GetName() << " Non valid root file" << endl;
3384        return;
3385      }
3386    
3387      TList *lk = f->GetListOfKeys();
3388      if (!lk)
3389        return;
3390      TIter next(lk);
3391      TKey *key = 0;
3392    
3393      Int_t nev = 0;
3394    
3395      while ((key = (TKey*) next())) {
3396    
3397        if (!strcmp(key->GetName(), "Run"))
3398          RUN = true;
3399    
3400        //=========================================================
3401        if (!strcmp(key->GetName(), "Trigger")) {
3402          TRG = true;
3403          Int_t nevt = ((TTree*) f->Get("Trigger"))->GetEntries();
3404          if (nev && nevt != nev) {
3405            cout << "File: " << f->GetName() << " Trigger tree has " << nevt << " events instead of " << nev << endl;
3406            TRG = false;
3407          }
3408          else
3409            nev = nevt;
3410        }
3411        //=========================================================
3412        if (!strcmp(key->GetName(), "ToF")) {
3413          TOF = true;
3414          Int_t nevt = ((TTree*) f->Get("ToF"))->GetEntries();
3415          if (nev && nevt != nev) {
3416            cout << "File: " << f->GetName() << "     ToF tree has " << nevt << " events instead of " << nev << endl;
3417            TOF = false;
3418          }
3419          else
3420            nev = nevt;
3421        }
3422        //=========================================================
3423        if (!strcmp(key->GetName(), "S4")) {
3424          S4 = true;
3425          Int_t nevt = ((TTree*) f->Get("S4"))->GetEntries();
3426          if (nev && nevt != nev) {
3427            cout << "File: " << f->GetName() << "      S4 tree has " << nevt << " events instead of " << nev << endl;
3428            S4 = false;
3429          }
3430          else
3431            nev = nevt;
3432        }
3433        //=========================================================
3434    
3435        if (!strcmp(key->GetName(), "NeutronD")) {
3436          ND = true;
3437          Int_t nevt = ((TTree*) f->Get("NeutronD"))->GetEntries();
3438          if (nev && nevt != nev) {
3439            cout << "File: " << f->GetName() << "NeutronD tree has " << nevt << " events instead of " << nev << endl;
3440            ND = false;
3441          }
3442          else
3443            nev = nevt;
3444        }
3445        //=========================================================
3446        if (!strcmp(key->GetName(), "Anticounter")) {
3447          AC = true;
3448          Int_t nevt = ((TTree*) f->Get("Anticounter"))->GetEntries();
3449          if (nev && nevt != nev) {
3450            cout << "File: " << f->GetName() << " Anticounter tree has " << nevt << " events instead of " << nev << endl;
3451            AC = false;
3452          }
3453          else
3454            nev = nevt;
3455        }
3456        //=========================================================
3457        if (!strcmp(key->GetName(), "OrbitalInfo")) {
3458          ORB = true;
3459          Int_t nevt = ((TTree*) f->Get("OrbitalInfo"))->GetEntries();
3460          if (nev && nevt != nev) {
3461            cout << "File: " << f->GetName() << " OrbitalInfo tree has " << nevt << " events instead of " << nev << endl;
3462            ORB = false;
3463          }
3464          else
3465            nev = nevt;
3466        }
3467        //=========================================================
3468        if (!strcmp(key->GetName(), "Tracker")) {
3469          TTree *T = (TTree*) f->Get("Tracker");
3470          for (Int_t i = 0; i < T->GetListOfBranches()->GetEntries(); i++) {
3471            TString name = T->GetListOfBranches()->At(i)->GetName();
3472            if (!name.CompareTo("TrkLevel1"))
3473              TRK1 = true;
3474            if (!name.CompareTo("TrkLevel2"))
3475              TRK2 = true;
3476            if (!name.CompareTo("TrkHough"))
3477              TRKh = true;
3478          };
3479          Int_t nevt = T->GetEntries();
3480          if (nev && nevt != nev) {
3481            cout << "File: " << f->GetName() << " Tracker tree has " << nevt << " events instead of " << nev << endl;
3482            TRK1 = false;
3483            TRK2 = false;
3484            TRKh = false;
3485          }
3486          else
3487            nev = nevt;
3488          //            T->Delete();
3489      };      };
3490            //=========================================================
3491      if( detlist.Contains("-CAL", TString::kIgnoreCase) )CAL = false;      if (!strcmp(key->GetName(), "Calorimeter")) {
3492      else if( detlist.Contains("+CAL", TString::kIgnoreCase) )CAL = true;        TTree *T = (TTree*) f->Get("Calorimeter");
3493              for (Int_t i = 0; i < T->GetListOfBranches()->GetEntries(); i++) {
3494      if( detlist.Contains("-TRK", TString::kIgnoreCase) )TRK = false;          TString name = T->GetListOfBranches()->At(i)->GetName();
3495      else if( detlist.Contains("+TRK", TString::kIgnoreCase) )TRK = true;          if (!name.CompareTo("CaloLevel1"))
3496                  CAL1 = true;
3497      if( detlist.Contains("-TRK1", TString::kIgnoreCase) )TRK_L1 = false;          if (!name.CompareTo("CaloLevel2"))
3498      else if( detlist.Contains("+TRK1", TString::kIgnoreCase) )TRK_L1 = true;            CAL2 = true;
3499              };
3500      if( detlist.Contains("-TRG", TString::kIgnoreCase) )TRG = false;        Int_t nevt = T->GetEntries();
3501      else if( detlist.Contains("+TRG", TString::kIgnoreCase) )TRG = true;        if (nev && nevt != nev) {
3502                cout << "File: " << f->GetName() << "  Calorimeter tree has " << nevt << " events instead of " << nev << endl;
3503      if( detlist.Contains("-TOF", TString::kIgnoreCase) )TOF = false;          CAL1 = false;
3504      else if( detlist.Contains("+TOF", TString::kIgnoreCase) )TOF = true;          CAL2 = false;
3505              }
3506      if( detlist.Contains("-S4",  TString::kIgnoreCase) )S4  = false;        else
3507      else if( detlist.Contains("+S4",  TString::kIgnoreCase) )S4  = true;          nev = nevt;
3508              //            T->Delete();
3509      if( detlist.Contains("-ND",  TString::kIgnoreCase) )ND  = false;      };
3510      else if( detlist.Contains("+ND",  TString::kIgnoreCase) )ND  = true;      //=========================================================
3511            if (!strcmp(key->GetName(), "h20")) {
3512      if( detlist.Contains("-AC",  TString::kIgnoreCase) )AC  = false;        GP = true;
3513      else if( detlist.Contains("+AC",  TString::kIgnoreCase) )AC  = true;        Int_t nevt = ((TTree*) f->Get("h20"))->GetEntries();
3514              if (nev && nevt != nev) {
3515      if( detlist.Contains("-ORB", TString::kIgnoreCase) )ORB = false;          cout << "File: " << f->GetName() << " h20 tree has " << nevt << " events instead of " << nev << endl;
3516      else if( detlist.Contains("+ORB", TString::kIgnoreCase) )ORB = true;          GP = false;
3517              }
3518  };        else
3519            nev = nevt;
3520        }
3521    
3522      };
3523    
3524      //    delete lk;
3525    
3526      cout << "tree/branch list from file  --> ";
3527      if (TRK1)
3528        cout << "TRK1 ";
3529      if (TRK2)
3530        cout << "TRK2 ";
3531      if (TRKh)
3532        cout << "TRKH ";
3533      if (CAL1)
3534        cout << "CAL1 ";
3535      if (CAL2)
3536        cout << "CAL2 ";
3537      if (TOF)
3538        cout << "TOF ";
3539      if (TRG)
3540        cout << "TRG ";
3541      if (AC)
3542        cout << "AC ";
3543      if (ND)
3544        cout << "ND ";
3545      if (S4)
3546        cout << "S4 ";
3547      if (ORB)
3548        cout << "ORB ";
3549      if (GP)
3550        cout << "GP ";
3551      cout << endl;
3552    
3553      return;
3554    
3555    }
3556    ;
3557    
3558  //--------------------------------------  //--------------------------------------
3559  //  //
3560  //  //
# Line 926  void PamLevel2::SetWhichTrees(TString de Line 3564  void PamLevel2::SetWhichTrees(TString de
3564   * @param name File name   * @param name File name
3565   * @return true if the file is ok.   * @return true if the file is ok.
3566   */   */
3567  Bool_t  PamLevel2::CheckLevel2File(TString name){  Bool_t PamLevel2::CheckLevel2File(TString name) {
3568            
3569      Bool_t CAL__ok    = false;        Bool_t CAL1__ok = false;
3570      Bool_t TRK__ok    = false;        Bool_t CAL2__ok = false;
3571      Bool_t TRK_L1__ok = false;        Bool_t TRK2__ok = false;
3572      Bool_t TRG__ok    = false;        Bool_t TRK1__ok = false;
3573      Bool_t TOF__ok    = false;        Bool_t TRKh__ok = false;
3574      Bool_t S4__ok     = false;        Bool_t TRG__ok = false;
3575      Bool_t ND__ok     = false;        Bool_t TOF__ok = false;
3576      Bool_t AC__ok     = false;        Bool_t S4__ok = false;
3577      Bool_t ORB__ok    = false;        Bool_t ND__ok = false;
3578          Bool_t AC__ok = false;
3579      Bool_t RUN__ok    = false;    Bool_t ORB__ok = false;
3580          Bool_t GP__ok = false;
3581  //    cout << "Checking file: "<<name<<endl;  
3582      TFile *f = new TFile(name.Data());    Bool_t RUN__ok = false;
3583      if( !f || f->IsZombie() ){  
3584          cout << "File: "<< f->GetName() <<" discarded ---- Non valid root file"<< endl; return false;    Bool_t SELLI__ok = false;
3585      }  
3586  //    cout << "Get list of keys: "<<f<<endl;    //    cout << "Checking file: "<<name<<endl;
3587      TList *lk = f->GetListOfKeys();    TFile *f = new TFile(name.Data());
3588      lk->Print();    if (!f || f->IsZombie()) {
3589      TIter next(lk);      cout << "File: " << f->GetName() << " discarded ---- Non valid root file" << endl;
3590      TKey *key =0;      return false;
3591      Int_t nev =0;    }
3592      Int_t nev_previous =0;    //    cout << "Get list of keys: "<<f<<endl;
3593      while( (key = (TKey*)next()) ){    TList *lk = f->GetListOfKeys();
3594              //    lk->Print();
3595  //      cout << key->GetName() << endl;    TIter next(lk);
3596  //      cout << " Get tree: " << f->Get(key->GetName())<<endl;    TKey *key = 0;
3597  //      nev_previous = nev;  
3598  //      cout << " n.entries  "<< nev <<endl;    Int_t nev = 0;
3599  //      if( key->GetClassName()=="TTree" && nev_previous && nev != nev_previous ){  
3600  //          nev = ((TTree*)f->Get(key->GetName()))->GetEntries();    while ((key = (TKey*) next())) {
3601  //          cout << "File: "<< f->GetName() <<" discarded ---- "<< key->GetName() << " tree: n.entries does not match "<<nev<<" "<<nev_previous<< endl;  
3602  //          return false;      //  cout << key->GetName() << endl;
3603  //      };      //  cout << key->GetName() << ""<<key->GetClassName()<<endl;
3604        //          cout << " Get tree: " << f->Get(key->GetName())<<endl;
3605          if( !strcmp(key->GetName(),"Calorimeter") )CAL__ok = true;      //  nev_previous = nev;
3606          if( !strcmp(key->GetName(),"Trigger"    ) )TRG__ok = true;      //  cout << " n.entries  "<< nev <<endl;
3607          if( !strcmp(key->GetName(),"ToF"        ) )TOF__ok = true;      //  if( key->GetClassName()=="TTree" && nev_previous && nev != nev_previous ){
3608          if( !strcmp(key->GetName(),"S4"         ) )S4__ok = true;      //      nev = ((TTree*)f->Get(key->GetName()))->GetEntries();
3609          if( !strcmp(key->GetName(),"NeutronD"   ) )ND__ok = true;      //      cout << "File: "<< f->GetName() <<" discarded ---- "<< key->GetName() << " tree: n.entries does not match "<<nev<<" "<<nev_previous<< endl;
3610          if( !strcmp(key->GetName(),"Anticounter") )AC__ok = true;      //      return false;
3611          if( !strcmp(key->GetName(),"OrbitalInfo") )ORB__ok = true;      //  };
3612          if( !strcmp(key->GetName(),"Run"        ) )RUN__ok = true;        
3613          if( !strcmp(key->GetName(),"Tracker"    ) ){      //=========================================================
3614              TRK__ok = true;      // check if the file
3615              TTree *T = (TTree*)f->Get("Tracker");  
3616              for(Int_t i=0; i<T->GetListOfBranches()->GetEntries(); i++){  
3617                  TString name = T->GetListOfBranches()->At(i)->GetName();      if (!strcmp(key->GetName(), "Run"))
3618                  if( !name.CompareTo("TrkLevel1") )TRK_L1__ok=true;        RUN__ok = true;
3619              };  
3620          };      //=========================================================
3621                if (!strcmp(key->GetName(), "SelectionList")) {
3622          SELLI__ok = true;
3623          if (SELLI == 1) {
3624            Int_t nevt = ((TTree*) f->Get("SelectionList"))->GetEntries();
3625            if (nev && nevt != nev) {
3626              cout << "File: " << f->GetName() << " discarded ---- SelectionList tree has " << nevt
3627                  << " events instead of " << nev << endl;
3628              return false;
3629            }
3630            nev = nevt;
3631          }
3632        }
3633    
3634        //=========================================================
3635        if (!strcmp(key->GetName(), "Trigger")) {
3636          TRG__ok = true;
3637          if (TRG) {
3638            Int_t nevt = ((TTree*) f->Get("Trigger"))->GetEntries();
3639            if (nev && nevt != nev) {
3640              cout << "File: " << f->GetName() << " discarded ---- Trigger tree has " << nevt << " events instead of "
3641                  << nev << endl;
3642              return false;
3643            }
3644            nev = nevt;
3645          }
3646        }
3647        //=========================================================
3648        if (!strcmp(key->GetName(), "ToF")) {
3649          TOF__ok = true;
3650          if (TOF) {
3651            Int_t nevt = ((TTree*) f->Get("ToF"))->GetEntries();
3652            if (nev && nevt != nev) {
3653              cout << "File: " << f->GetName() << " discarded ---- ToF tree has " << nevt << " events instead of " << nev
3654                  << endl;
3655              return false;
3656            }
3657            nev = nevt;
3658          }
3659        }
3660        //=========================================================
3661        if (!strcmp(key->GetName(), "S4")) {
3662          S4__ok = true;
3663          if (S4) {
3664            Int_t nevt = ((TTree*) f->Get("S4"))->GetEntries();
3665            if (nev && nevt != nev) {
3666              cout << "File: " << f->GetName() << " discarded ---- S4 tree has " << nevt << " events instead of " << nev
3667                  << endl;
3668              return false;
3669            }
3670            nev = nevt;
3671          }
3672        }
3673        //=========================================================
3674    
3675        if (!strcmp(key->GetName(), "NeutronD")) {
3676          ND__ok = true;
3677          if (ND) {
3678            Int_t nevt = ((TTree*) f->Get("NeutronD"))->GetEntries();
3679            if (nev && nevt != nev) {
3680              cout << "File: " << f->GetName() << " discarded ---- NeutronD tree has " << nevt << " events instead of "
3681                  << nev << endl;
3682              return false;
3683            }
3684            nev = nevt;
3685          }
3686        }
3687        //=========================================================
3688        if (!strcmp(key->GetName(), "Anticounter")) {
3689          AC__ok = true;
3690          if (AC) {
3691            Int_t nevt = ((TTree*) f->Get("Anticounter"))->GetEntries();
3692            if (nev && nevt != nev) {
3693              cout << "File: " << f->GetName() << " discarded ---- Anticounter tree has " << nevt << " events instead of "
3694                  << nev << endl;
3695              return false;
3696            }
3697            nev = nevt;
3698          }
3699        }
3700        //=========================================================
3701        if (!strcmp(key->GetName(), "OrbitalInfo")) {
3702          ORB__ok = true;
3703          if (ORB) {
3704            Int_t nevt = ((TTree*) f->Get("OrbitalInfo"))->GetEntries();
3705            if (nev && nevt != nev) {
3706              cout << "File: " << f->GetName() << " discarded ---- OrbitalInfo tree has " << nevt << " events instead of "
3707                  << nev << endl;
3708              return false;
3709            }
3710            nev = nevt;
3711          }
3712        }
3713        //=========================================================
3714        if (!strcmp(key->GetName(), "Tracker")) {
3715          TTree *T = (TTree*) f->Get("Tracker");
3716          if (TRK1 || TRK2 || TRKh) {
3717            Int_t nevt = T->GetEntries();
3718            if (nev && nevt != nev) {
3719              cout << "File: " << f->GetName() << " discarded ---- Tracker tree has " << nevt << " events instead of "
3720                  << nev << endl;
3721              return false;
3722            }
3723            nev = nevt;
3724          }
3725          for (Int_t i = 0; i < T->GetListOfBranches()->GetEntries(); i++) {
3726            TString name = T->GetListOfBranches()->At(i)->GetName();
3727            if (!name.CompareTo("TrkLevel1"))
3728              TRK1__ok = true;
3729            if (!name.CompareTo("TrkLevel2"))
3730              TRK2__ok = true;
3731            if (!name.CompareTo("TrkHough"))
3732              TRKh__ok = true;
3733          };
3734          T->Delete();
3735      };      };
3736            //=========================================================
3737      lk->Delete();      if (!strcmp(key->GetName(), "Calorimeter")) {
3738      f->Close();        TTree *T = (TTree*) f->Get("Calorimeter");
3739              if (CAL1 || CAL2) {
3740      Bool_t FLAG = true;          Int_t nevt = T->GetEntries();
3741      if(!RUN__ok) {          if (nev && nevt != nev) {
3742          cout << "File: "<< f->GetName() <<" discarded ---- Missing RunInfo tree"<< endl; return false;            cout << "File: " << f->GetName() << " discarded ---- Calorimeter tree has " << nevt << " events instead of "
3743  //      FLAG = false;                << nev << endl;
3744      };            return false;
3745      if(CAL && !CAL__ok){          }
3746          cout << "File: "<< f->GetName() <<" discarded ---- Missing Calorimeter tree"<< endl; return false;          nev = nevt;
3747  //      FLAG = false;        }
3748      };        for (Int_t i = 0; i < T->GetListOfBranches()->GetEntries(); i++) {
3749      if(TRK && !TRK__ok){          TString name = T->GetListOfBranches()->At(i)->GetName();
3750          cout << "File: "<< f->GetName() <<" discarded ---- Missing Tracker tree"<< endl; return false;          if (!name.CompareTo("CaloLevel1"))
3751  //      FLAG = false;            CAL1__ok = true;
3752      };          if (!name.CompareTo("CaloLevel2"))
3753      if(TRK_L1 && !TRK_L1__ok){            CAL2__ok = true;
3754          cout << "File: "<< f->GetName() <<" discarded ---- Missing Tracker Level1 Branch"<< endl; return false;        };
3755  //      FLAG = false;        T->Delete();
3756      };      };
3757      if(TRG && !TRG__ok){      //=========================================================
3758          cout << "File: "<< f->GetName() <<" discarded ---- Missing Trigger tree"<< endl; return false;      if (!strcmp(key->GetName(), "h20")) {
3759  //      FLAG = false;        ISGP = true;
3760      };        GP__ok = true;
3761      if(TOF && !TOF__ok){        if (GP) {
3762          cout << "File: "<< f->GetName() <<" discarded ---- Missing ToF tree"<< endl; return false;          Int_t nevt = ((TTree*) f->Get("h20"))->GetEntries();
3763  //      FLAG = false;          if (nev && nevt != nev) {
3764      };            cout << "File: " << f->GetName() << " discarded ---- h20 tree has " << nevt << " events instead of " << nev
3765      if(S4 && !S4__ok){                << endl;
3766          cout << "File: "<< f->GetName() <<" discarded ---- Missing S4 tree"<< endl; return false;            return false;
3767  //      FLAG = false;          }
3768      };          nev = nevt;
3769      if(ND && !ND__ok){        }
3770          cout << "File: "<< f->GetName() <<" discarded ---- Missing ND tree"<< endl; return false;      }
3771  //      FLAG = false;  
3772      };    };
3773      if(AC && !AC__ok){  
3774          cout << "File: "<< f->GetName() <<" discarded ---- Missing AC tree"<< endl; return false;    if (SELLI == -1)
3775  //      FLAG = false;      SELLI = (Int_t) SELLI__ok;
3776      };    if (SELLI == 0 && SELLI__ok) {
3777      if(ORB && !ORB__ok){      cout << "File: " << f->GetName() << " discarded ---- found SelectionList (it is not a full-event file)" << endl;
3778          cout << "File: "<< f->GetName() <<" discarded ---- Missing ORB tree"<< endl; return false;      return false;
3779  //      FLAG = false;    }
3780      if (SELLI == 1 && !SELLI__ok) {
3781        cout << "File: " << f->GetName() << " discarded ---- SelectionList missing" << endl;
3782        return false;
3783      }
3784    
3785      //    cout << "SELLI "<<SELLI<<endl;
3786    
3787      //     cout<< "CheckLevel2File(TString): detector list --> ";
3788      //     if(TRK1__ok)cout<<"TRK1 ";
3789      //     if(TRK2__ok)cout<<"TRK2 ";
3790      //     if(TRKh__ok)cout<<"TRKH ";
3791      //     if(CAL1__ok)cout<<"CAL1 ";
3792      //     if(CAL2__ok)cout<<"CAL2 ";
3793      //     if(TOF__ok)cout<<"TOF ";
3794      //     if(TRG__ok)cout<<"TRG ";
3795      //     if(AC__ok)cout<<"AC ";
3796      //     if(ND__ok)cout<<"ND ";
3797      //     if(S4__ok)cout<<"S4 ";
3798      //     if(ORB__ok)cout<<"ORB ";
3799      //     cout << endl;
3800    
3801    
3802      if (TRK2 && TRK1__ok)
3803        TRK1 = 1;
3804      // ----------------------------------------------------------------------------
3805      // NOTA
3806      // se c'e` il level1, lo devo necessarimente leggere.
3807      // infatti (non ho capito perche`) i cluster vengono letti e allocati in memoria
3808      // comunque, ma non vengono disallocati da PamLevel2::Clear()
3809      // ----------------------------------------------------------------------------
3810    
3811    
3812      if (!RUN__ok) {
3813        cout << "File: " << f->GetName() << " *WARNING* ---- Missing RunInfo tree (NB: RUN infos will not be updated)"
3814            << endl;
3815        RUN = false;
3816      };
3817    
3818      if (CAL1 && !CAL1__ok) {
3819        cout << "File: " << f->GetName() << " discarded ---- Missing CaloLevel1 branch" << endl;
3820        return false;
3821      };
3822      if (CAL2 && !CAL2__ok) {
3823        cout << "File: " << f->GetName() << " discarded ---- Missing CaloLevel2 branch" << endl;
3824        return false;
3825      };
3826      if (TRK2 && !TRK2__ok) {
3827        cout << "File: " << f->GetName() << " discarded ---- Missing TrkLevel2 branch" << endl;
3828        return false;
3829      };
3830      if (TRK1 && !TRK1__ok) {
3831        cout << "File: " << f->GetName() << " discarded ---- Missing TrkLevel1 branch" << endl;
3832        return false;
3833      };
3834      if (TRKh && !TRKh__ok) {
3835        cout << "File: " << f->GetName() << " discarded ---- Missing TrkHough branch" << endl;
3836        return false;
3837      };
3838      if (ORB && !ORB__ok) {
3839        cout << "File: " << f->GetName() << " discarded ---- Missing ORB tree" << endl;
3840        return false;
3841      };
3842      if (AC && !AC__ok) {
3843        cout << "File: " << f->GetName() << " discarded ---- Missing AC tree" << endl;
3844        return false;
3845      };
3846      if (S4 && !S4__ok) {
3847        cout << "File: " << f->GetName() << " discarded ---- Missing S4 tree" << endl;
3848        return false;
3849      };
3850      if (TOF && !TOF__ok) {
3851        cout << "File: " << f->GetName() << " discarded ---- Missing ToF tree" << endl;
3852        return false;
3853      };
3854    
3855      if (ND && !ND__ok) {
3856        cout << "File: " << f->GetName() << " discarded ---- Missing ND tree" << endl;
3857        return false;
3858      };
3859      if (TRG && !TRG__ok) {
3860        cout << "File: " << f->GetName() << " discarded ---- Missing Trigger tree" << endl;
3861        return false;
3862      };
3863      if (GP && !GP__ok) {
3864        cout << "File: " << f->GetName() << " discarded ---- Missing h20 tree" << endl;
3865        return false;
3866      };
3867    
3868      //    lk->Delete();
3869      //    delete lk;
3870      f->Close();
3871    
3872      //     cout<< "CheckLevel2File(TString): detector list --> ";
3873      //     if(TRK1)cout<<"TRK1 ";
3874      //     if(TRK2)cout<<"TRK2 ";
3875      //     if(TRKh)cout<<"TRKH ";
3876      //     if(CAL1)cout<<"CAL1 ";
3877      //     if(CAL2)cout<<"CAL2 ";
3878      //     if(TOF)cout<<"TOF ";
3879      //     if(TRG)cout<<"TRG ";
3880      //     if(AC)cout<<"AC ";
3881      //     if(ND)cout<<"ND ";
3882      //     if(S4)cout<<"S4 ";
3883      //     if(ORB)cout<<"ORB ";
3884      //     if(GP)cout<<"GP ";
3885      //     cout << endl;
3886    
3887      return true;
3888    
3889    }
3890    ;
3891    
3892    /**
3893     * Create clone-trees
3894     */
3895    void PamLevel2::CreateCloneTrees0(TChain *fChain, TFile *ofile) {
3896    
3897      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
3898      cout << "Create clones of PAMELA trees " << endl;
3899    
3900      Int_t i = 0;
3901      pam_tree_clone[i] = fChain->GetTree()->CloneTree(0);
3902      TString name = pam_tree_clone[i]->GetName();
3903      name.Append("_clone");
3904      //    pam_tree_clone[i]->SetName(name.Data());
3905      cout << pam_tree_clone[i]->GetName() << endl;
3906      i++;
3907    
3908      TList *li = fChain->GetListOfFriends();
3909      TIter next(li);
3910      TFriendElement* T_friend = 0;
3911      ofile->cd();
3912      while ((T_friend = (TFriendElement*) next())) {
3913        //  cout<<T_friend->IsA()->GetName()<<" "<<T_friend->GetName()<<hex << T_friend->GetTree() << dec<<endl;
3914        //  cout<<T_friend->GetTree()->GetName()<< endl;
3915        pam_tree_clone[i] = T_friend->GetTree()->CloneTree(0);
3916        pam_tree_clone[i]->SetAutoSave(1000000);
3917        name = pam_tree_clone[i]->GetName();
3918        name.Append("_clone");
3919        //  pam_tree_clone[i]->SetName(name.Data());
3920        cout << pam_tree_clone[i]->GetName() << endl;
3921        i++;
3922      }
3923    
3924      delete li;
3925    
3926      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
3927    
3928    }
3929    
3930    /**
3931     * Create clone-trees
3932     */
3933    void PamLevel2::CreateCloneTrees(TFile *ofile) {
3934    
3935      //  if the pointer is null, create a default file
3936      if (!run_tree)
3937        return;
3938    
3939      if (!ofile) {
3940        cout << "void PamLevel2::CreateCloneTrees(TFile*) -- WARNING -- Creating file: clone-tree.root " << endl;
3941        ofile = new TFile("clone-tree.root", "recreate");
3942      }
3943    
3944      ofile->cd();
3945    
3946      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
3947      cout << "Create new PAMELA trees " << endl;
3948    
3949      run_tree_clone = new TTree("Run", "PAMELA Level2 data from the GL_RUN table ");
3950      run_tree_clone->Branch("RunInfo", "GL_RUN", GetPointerTo("RunInfo"));
3951      cout << "Run          : branch RunInfo" << endl;
3952      run_tree_clone->Branch("SoftInfo", "SoftInfo", GetPointerTo("SoftInfo"));
3953      cout << "Run          : branch SoftInfo" << endl;
3954      // ------------------
3955      // replicate run tree
3956      // ------------------
3957      //    cout << "----------------------------------------------------"<<endl;
3958      //    cout << "irun\t | RUN\t NEVENTS\t absolute time"<<endl;
3959      for (Int_t i = 0; i < run_tree->GetEntries(); i++) {
3960        run_tree->GetEntry(i);
3961        //  cout << i<< "\t | "<<GetRunInfo()->ID<<"\t "<<GetRunInfo()->NEVENTS<< "\t "<<GetRunInfo()->RUNHEADER_TIME<<" <---> "<<GetRunInfo()->RUNTRAILER_TIME<<endl;
3962        run_tree_clone->Fill();
3963      }
3964      cout << "----------------------------------------------------" << endl;
3965    
3966      // ------------------------------------
3967      // add branch with dead and live times
3968      // ------------------------------------
3969      if (SELLI != 2) { // EMILIANO
3970        run_tree_clone->Branch("DeadLiveTime", totdltime, "dltime[3]/l");
3971        cout << "Run          : branch DeadLiveTime" << endl;
3972    
3973        sel_tree_clone = new TTree("SelectionList", "List of selected events ");
3974        //    sel_tree_clone->Branch("RunEntry",&irun,"runentry/L");
3975        sel_tree_clone->Branch("RunEntry", &irunt, "runentry/L");//NEWNEW
3976        sel_tree_clone->Branch("EventEntry", &irunentry, "eventry/L");
3977        //    if ( hasL0EE ) sel_tree_clone->Branch("L0EventEntry", &il0entry, "l0eventry/L");
3978      };
3979    
3980      Int_t i = 0;
3981      if (TRK1 || TRK2 || TRKh) {
3982        pam_tree_clone[i] = new TTree("Tracker", "PAMELA tracker level2 data ");
3983        if (TRK1) {
3984          pam_tree_clone[i]->Branch("TrkLevel1", "TrkLevel1", GetPointerTo("TrkLevel1"));
3985          pam_tree_clone[i]->BranchRef();
3986          cout << "Tracker      : branch TrkLevel1" << endl;
3987          //            cout << "CreateCloneTrees " << GetTrkLevel1()<<endl;
3988        };
3989        if (TRK2) {
3990          pam_tree_clone[i]->Branch("TrkLevel2", "TrkLevel2", GetPointerTo("TrkLevel2"));
3991          cout << "Tracker      : branch TrkLevel2" << endl;
3992        };
3993        if (TRKh) {
3994          pam_tree_clone[i]->Branch("TrkHough", "TrkHough", GetPointerTo("TrkHough"));
3995          cout << "Tracker      : branch TrkHough" << endl;
3996        };
3997        i++;
3998      }
3999    
4000      // Calorimeter
4001      if (CAL1 || CAL2) {
4002        pam_tree_clone[i] = new TTree("Calorimeter", "PAMELA calorimeter level2 data ");
4003        if (CAL1) {
4004          pam_tree_clone[i]->Branch("CaloLevel1", "CaloLevel1", GetPointerTo("CaloLevel1"));
4005          cout << "Calorimeter  : branch CaloLevel1" << endl;
4006        };
4007        if (CAL2) {
4008          pam_tree_clone[i]->Branch("CaloLevel2", "CaloLevel2", GetPointerTo("CaloLevel2"));
4009          cout << "Calorimeter  : branch CaloLevel2" << endl;
4010        };
4011        i++;
4012      }
4013    
4014      // ToF
4015      if (TOF) {
4016        pam_tree_clone[i] = new TTree("ToF", "PAMELA ToF level2 data ");
4017        pam_tree_clone[i]->Branch("ToFLevel2", "ToFLevel2", GetPointerTo("ToFLevel2"));
4018        cout << "ToF          : branch ToFLevel2" << endl;
4019        i++;
4020      };
4021      // Trigger
4022      if (TRG) {
4023        pam_tree_clone[i] = new TTree("Trigger", "PAMELA trigger level2 data ");
4024        pam_tree_clone[i]->Branch("TrigLevel2", "TrigLevel2", GetPointerTo("TrigLevel2"));
4025        cout << "Trigger      : branch TrigLevel2" << endl;
4026        i++;
4027      };
4028      // S4
4029      if (S4) {
4030        pam_tree_clone[i] = new TTree("S4", "PAMELA S4 level2 data ");
4031        pam_tree_clone[i]->Branch("S4Level2", "S4Level2", GetPointerTo("S4Level2"));
4032        cout << "S4           : branch S4Level2" << endl;
4033        i++;
4034      };
4035      // Neutron Detector
4036      if (ND) {
4037        pam_tree_clone[i] = new TTree("NeutronD", "PAMELA neutron detector level2 data ");
4038        pam_tree_clone[i]->Branch("NDLevel2", "NDLevel2", GetPointerTo("NDLevel2"));
4039        cout << "NeutronD     : branch NDLevel2" << endl;
4040        i++;
4041      };
4042      // Anticounters
4043      if (AC) {
4044        pam_tree_clone[i] = new TTree("Anticounter", "PAMELA anticounter detector level2 data ");
4045        pam_tree_clone[i]->Branch("AcLevel2", "AcLevel2", GetPointerTo("AcLevel2"));
4046        cout << "Anticounter  : branch AcLevel2" << endl;
4047        i++;
4048      };
4049      // OrbitalInfo
4050      if (ORB) {
4051        pam_tree_clone[i] = new TTree("OrbitalInfo", "PAMELA orbital info  ");
4052        pam_tree_clone[i]->Branch("OrbitalInfo", "OrbitalInfo", GetPointerTo("OrbitalInfo"));
4053        cout << "OrbitalInfo  : branch OrbitalInfo" << endl;
4054        i++;
4055      };
4056      // GPamela
4057      if (GP) {
4058        pam_tree_clone[i] = new TTree("h20", "GPAMELA info ");
4059        pam_tree_clone[i]->Branch("GPamela", "GPamela", GetPointerTo("GPamela"), 32000, 1);//split
4060        cout << "GPamela  : branch GPamela" << endl;
4061        i++;
4062      };
4063      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
4064    
4065    }
4066    
4067    /**
4068     * Fill tree (created with CreateCloneTrees)
4069     *
4070     */
4071    //void PamLevel2::FillNewPamTree(TTree *T){
4072    void PamLevel2::FillCloneTrees() {
4073    
4074      //    cout << "PamLevel2::FillCloneTrees()" << irunentry << endl;
4075    
4076      for (Int_t i = 0; i < NCLONES; i++) {
4077        if (pam_tree_clone[i])
4078          pam_tree_clone[i]->Fill();
4079      }
4080      if (sel_tree_clone)
4081        sel_tree_clone->Fill();
4082    
4083    }
4084    
4085    TTree* PamLevel2::GetCloneTree(TString name) {
4086    
4087      for (Int_t i = 0; i < NCLONES; i++) {
4088        if (pam_tree_clone[i]) {
4089          TString na = pam_tree_clone[i]->GetName();
4090          if (!name.CompareTo(na))
4091            return pam_tree_clone[i];
4092        };
4093      }
4094      if (run_tree_clone) {
4095        TString na = run_tree_clone->GetName();
4096        if (!name.CompareTo(na))
4097          return run_tree_clone;
4098      }
4099      if (sel_tree_clone) {
4100        TString na = sel_tree_clone->GetName();
4101        if (!name.CompareTo(na))
4102          return sel_tree_clone;
4103      }
4104      return NULL;
4105    
4106    }
4107    void PamLevel2::WriteCloneTrees() {
4108      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
4109      cout << "Write clones of PAMELA trees " << endl;
4110      cout << run_tree_clone->GetName() << endl;
4111      if (SELLI != 2) {// Emiliano
4112        if (run_tree_clone->GetBranch("DeadLiveTime")->GetEntries() < run_tree->GetEntries())
4113          run_tree_clone->GetBranch("DeadLiveTime")->Fill();
4114      };
4115      run_tree_clone->Write();
4116      if (SELLI != 2) { //Emiliano
4117        cout << sel_tree_clone->GetName() << endl;
4118        sel_tree_clone->Write();
4119      };
4120      for (Int_t i = 0; i < NCLONES; i++) {
4121        if (pam_tree_clone[i]) {
4122          cout << pam_tree_clone[i]->GetName() << endl;
4123          pam_tree_clone[i]->Write();
4124        };
4125      }
4126      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
4127    
4128    }
4129    
4130    /**
4131     * Method to get level2-trees entry, the corresponding run entry and (if required) the level0 entry.
4132     */
4133    Int_t PamLevel2::GetEntry(Long64_t iee) {
4134    
4135      if (!pam_tree) {
4136        cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- level2 trees not loaded" << endl;
4137        return 0;
4138      }
4139    
4140      //
4141      // This is a sort of bug: if you don't have the run tree you don't want to exit here you want to have loaded the event anyway...
4142      //
4143      //    if(!run_tree ){
4144      //    cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- run tree not loeaded"<<endl;
4145      //    return 0;
4146      //    }
4147    
4148      //-------------------------------
4149      if (!pam_tree->GetEntry(iee)) {
4150        cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- error reading pam tree" << endl;
4151        return 0;
4152      }
4153      //
4154      // ... that's way I put it here. Notice that nothing change in the code (is backward compatible) since in any case you return with 0.
4155      // in theory one would like to return 1 if run is not loaded but now I don't have the will to add that 2 lines of code and it is not
4156      // a problem if you don't check the return code of getentry.
4157      //
4158      if (!RUN || !run_tree) {
4159        if (TRK0 || CAL0 || TOF0 || RUN) { //forse cosi` va bene per tornare 1?
4160          cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- run tree not loaded" << endl;
4161          return 0;
4162        }
4163        else {
4164          return 1; //cosi` se non c'e` run esce qua...
4165        }
4166      }
4167    
4168      //-------------------------------
4169      //
4170      if ( fUpdateRunInfo ) UpdateRunInfo(iee); // Emiliano
4171      if (SELLI == 0 || SELLI == 2) irunentry = iee - runfirstentry;
4172    
4173      return 1;
4174    
4175    }
4176    
4177    TrkLevel0 *PamLevel2::GetTrkLevel0() {
4178      if (!TRK0)
4179        return NULL;
4180      if (!GetYodaEntry()) {
4181        cout << " Int_t PamLevel2::GetTrkLevel0() -- ERROR -- error reading level0 tree" << endl;
4182        return 0;
4183      }
4184      return trk0_obj;
4185    }
4186    ;
4187    CaloLevel0 *PamLevel2::GetCaloLevel0() {
4188      if (!CAL0)
4189        return NULL;
4190      if (!GetYodaEntry()) {
4191        cout << " Int_t PamLevel2::GetCaloLevel0() -- ERROR -- error reading level0 tree" << endl;
4192        return 0;
4193      }
4194      return calo0_obj;
4195    }
4196    ;
4197    
4198    /**
4199     * Method to retrieve the level0 tree (YODA tree) that contains the current event.
4200     * Given the run ID (...), if needed it query the DB and load the proper file.
4201     * @return Pointer to the tree
4202     */
4203    
4204    TTree* PamLevel2::GetYodaTree() {
4205    
4206      //    cout << "TTree* PamLevel2::GetYodaTree( )"<<endl;
4207      //===================================
4208      // check if iroot has changed
4209      //===================================
4210      if (irun < 0) {
4211        cout << "PamLevel2::GetYodaTree() -- ERROR -- irun = " << irun << endl;
4212        if (DBG) cout << "In order to use this method you have to first load the RunInfo tree "<<endl;
4213        return NULL;
4214      }
4215      Int_t irootnew = GetRunInfo()->ID_ROOT_L0;
4216      if (DBG){
4217        cout << "iroot    "<<iroot<<endl;
4218        cout << "irootnew "<<irootnew<<endl;
4219      }
4220    
4221      //===================================
4222      // load the level0 file
4223      // (if not already loaded)
4224      //===================================
4225      if (iroot != irootnew || !l0_tree) {
4226        iroot = irootnew;
4227        //===================================
4228        // open the DB connection
4229        // (if not already opened)
4230        //===================================
4231        if (!dbc || (dbc && !dbc->IsConnected()))
4232          SetDBConnection();
4233        GL_ROOT glroot = GL_ROOT();
4234        if (glroot.Query_GL_ROOT(iroot, dbc)) {
4235          cout << "TTree* PamLevel2::GetYodaTree( ) -- ERROR -- level0 file iroot = " << iroot << " does not exists"
4236              << endl;
4237          return NULL;
4238        };
4239        TString filename = glroot.PATH + glroot.NAME;
4240        if (l0_file) {
4241          l0_file->Close();
4242          l0_file->Delete();
4243        }
4244        cout << "Opening LEVEL0 file: " << filename << endl;
4245        FileStat_t t;
4246        if (gSystem->GetPathInfo(filename.Data(), t)) {
4247          cout << " PamLevel2::GetYodaTree() -- ERROR opening file " << endl;
4248          return NULL;
4249        }
4250        l0_file = new TFile(filename);
4251        if (!l0_file)
4252          return NULL;
4253        l0_tree = (TTree*) l0_file->Get("Physics");
4254        if (!h0_obj)
4255          h0_obj = new EventHeader();
4256        l0_tree->SetBranchAddress("Header", &h0_obj);
4257        yprevshift = 0; // yes, yprevshift is the shift in the level0, prevshift is the shift in the level2
4258        //---------------------------------------------------
4259        // TRACKER:
4260        if (TRK0) {
4261          if (!trk0_obj) {
4262            trk0_obj = new TrkLevel0();
4263            trk0_obj->Set();
4264          };
4265          l0_tree->SetBranchAddress("Tracker", trk0_obj->GetPointerToTrackerEvent());
4266        }
4267        //--------------------------------------------------
4268        // CALORIMETER:
4269        if (CAL0) {
4270          if (!calo0_obj) {
4271            calo0_obj = new CaloLevel0();
4272            calo0_obj->Set();
4273          };
4274          l0_tree->SetBranchAddress("Calorimeter", calo0_obj->GetPointerToCalorimeterEvent());
4275        }
4276        //---------------------------------------------------
4277        // TOF:
4278        if (TOF0) {
4279          cout << "PamLevel2::GetYodaTree() --- level0 TOF not implemented " << endl;
4280        }
4281    
4282        dbc->Close(); // EMILIANO, do not leave open connections, open only when needed
4283        delete dbc;
4284        dbc=0;
4285    
4286      };
4287    
4288      if (TRK0) {
4289        if(!dbc || (dbc && !dbc->IsConnected()))SetDBConnection();
4290        TrkParams::SetCalib(run_obj, dbc);
4291        TrkParams::LoadCalib();
4292        if (!TrkParams::CalibIsLoaded()) {
4293          cout << " TTree* PamLevel2::GetYodaTree( ) -- WARNING -- Calibration not loaded" << endl;
4294      };      };
4295        if(dbc){
4296          dbc->Close(); // EMILIANO, do not leave open connections, open only when needed
4297          delete dbc;
4298          dbc=0;
4299        };
4300      }
4301      return l0_tree;
4302    }
4303    
4304    /**
4305     * Method to retrieve the level0 tree (YODA tree) that contains the current event.
4306     */
4307    Int_t PamLevel2::GetYodaEntry() {
4308    
4309      Long64_t iev = this->GetReadEntry();
4310    
4311      // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
4312      // if it is a full file (not preselected)
4313      // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
4314      //  if (SELLI == 0 || SELLI == 2 || !hasL0EE) {
4315    
4316        if (!GetYodaTree()){
4317          printf(" PamLevel2::GetYodaEntry() : ERROR no level0 file loaded!\n");
4318          return 0;
4319        }
4320    
4321        if (irunentry < 0) {
4322          if (DBG) cout << "Int_t PamLevel2::GetYodaEntry() -- ATTENZIONE -- irunentry negativo?!?! "<<(Int_t)irunentry<<endl;
4323          //      cout << "Int_t PamLevel2::GetYodaEntry() -- ATTENZIONE -- irunentry negativo?!?! "<<(Int_t)irunentry<<endl; // TOGLITOGLI
4324          irunentry = 0LL;
4325        }
4326        //  ---------------------------------
4327        //  if file is NOT a preselected file
4328        //  ---------------------------------
4329        Long64_t quellagiusta = irunentry + (Long64_t)(run_obj->EV_FROM); // prevshift already included in irunentry
4330    
4331        if (DBG){
4332          cout << " irun "<< irun << " irunentry "<< irunentry<<" run_obj->EV_FROM "<<run_obj->EV_FROM <<" quella giusta "<<quellagiusta << endl;
4333          cout << " iroot "<<iroot<<" run_obj->ID_ROOT_L0 "<<run_obj->ID_ROOT_L0<<endl;
4334          cout << " time "<< abstime << endl;
4335        }
4336    
4337        ULong64_t obt = 0;
4338        ULong64_t pktn = 0;
4339        if (GetOrbitalInfo()) {
4340          obt = GetOrbitalInfo()->OBT;
4341          pktn = GetOrbitalInfo()->pkt_num;
4342        }
4343    
4344        if (!GetOrbitalInfo() && !ISGP) {
4345          cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- missing OrbitalInfo " << endl;
4346          return 0;
4347        }
4348        if (obt == 0 && pktn == 0 && !ISGP) {
4349          cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- level2 event corrupted ?? " << endl;
4350          return 0;
4351        }
4352    
4353        // ---------------------------------------------------------------------
4354        // ATTENTION!!!
4355        // If data are not pre-processed with cleaner, the level0 tree may contain
4356        // spurious nested physics packets.
4357        // The GL_RUN variables EV_FROM, EV_TO and NEVENTS counts also these entries
4358        // while level2 tree DOES NOT!!
4359        // This means that "quellagiusta" in these cases is not correct.
4360        // In order to retrieve the correct level0 event, I implemented a check
4361        // of the OBT and pkt-number. In case of mismatch, the level0 entry number
4362        // is shift forward until when the packets match.
4363        // ---------------------------------------------------------------------
4364        Long64_t shift = 0LL;
4365        Long64_t answer = quellagiusta + shift + yprevshift;
4366        Int_t readl0 = 0;
4367        readl0 = l0_tree->GetEntry(answer); // prevshift already included in irunentry
4368    
4369        if (DBG){
4370          printf(" siamo qui shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);
4371        }
4372    
4373    
4374        if (ISGP) {
4375          obt = (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()); //BARBATRUCCO
4376          pktn = (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter()); //BARBATRUCCO
4377        }
4378    
4379        while ( (obt != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()) || pktn != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter())) && (quellagiusta + (Long64_t) shift) < GetYodaTree()->GetEntries() && shift < maxshift ){
4380          if ( isSync && shift == 0LL ){
4381            printf(" PamLevel2::GetYodaEntry() ERROR! sync file but the level0 entry not found in place!!! \n");
4382            cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
4383            cout << "\nFor bug reporting instructions, please see for example:\n";
4384            cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
4385            cout << "  " << endl;
4386          }
4387          if (shift > 0) {
4388            cout << " PKTNUM  L2 --- " << pktn << " --- L0 --- " << GetEventHeader()->GetPscuHeader()->GetCounter() << endl;
4389            if (DBG)
4390              cout << "         RUN: ID " << GetRunInfo()->ID << " ID_ROOT_L0 " << run_obj->ID_ROOT_L0 << " ID_RUN_FRAG "
4391                   << GetRunInfo()->ID_RUN_FRAG << " EV_FROM " << GetRunInfo()->EV_FROM << endl;
4392            if (DBG)
4393              cout << "         L2 <--> L0 mismatch ( irun " << irun << " irunentry " << irunentry << " shift " << shift
4394                   << " prevshift " << prevshift << " )" << endl;
4395          }
4396          answer = quellagiusta +  shift+ yprevshift;
4397          readl0 = l0_tree->GetEntry(answer);
4398          //      printf(" inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);//TOGLITOGLI
4399    
4400          if (!GetEventHeader()) {
4401            cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- missing EventHeader " << endl;
4402            return 0;
4403          }
4404    
4405          //
4406          if (yprevshift != 0 && (quellagiusta + (Long64_t) shift) == GetYodaTree()->GetEntries()) {
4407            if (DBG) printf(" reset inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);
4408            //        printf(" reset inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);//TOGLITOGLI
4409            yprevshift = 0LL;
4410            shift = -1LL;
4411          };
4412            
4413      return FLAG;        shift++;
4414                }
4415  };                                    
4416    
4417        if ( obt != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()) || pktn != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter()) ){
4418          if ( isSync ){
4419            printf(" PamLevel2::GetYodaEntry() ERROR! sync file but the level0 entry not found AT ALL!!! \n");
4420            cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
4421            cout << "\nFor bug reporting instructions, please see for example:\n";
4422            cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
4423            cout << "  " << endl;
4424          }
4425          cout << "Int_t PamLevel2::GetYodaEntry() -- WARNING -- " << endl;
4426          cout << " Big trouble here, no such event in Level0 data! (NB maxshift set to " << maxshift << " )" << endl;    
4427          cout << " Nested and/or DarthVader skipped packets in fragmented run? checking and trying to fix " <<endl;
4428          // query the DB for runs containing the event, loop over LEVEL0 files which could contain the level0 event and try to find it
4429          // ma nel mezzo del cammin per ogni run che pesco devo vedere la posizione relativa di iev rispetto al runheader nel livello2 per andare a cercare nel posto giusto
4430          // connect to db
4431          if (!dbc || (dbc && !dbc->IsConnected())) SetDBConnection(); //Emiliano
4432          //
4433          if (GetOrbitalInfo()){
4434            abstime = GetOrbitalInfo()->absTime;
4435          } else {
4436            printf(" PamLevel2::GetYodaEntry() ERROR! no OrbitalInfo, cannot get the absolute time for event \n");
4437            return 0;
4438          }
4439          // query DB looking for runs containing the processed event
4440          TSQLResult *pResult;
4441          TSQLRow *Row = NULL;
4442          TString myquery = Form("select ID,NEVENTS from GL_RUN where RUNHEADER_TIME<=%lld and RUNTRAILER_TIME>=%lld;",abstime,abstime);
4443          if ( DBG ) printf(" query is %s \n",myquery.Data());
4444          //      printf(" query is %s \n",myquery.Data());// TOGLITOGLI
4445          pResult = dbc->Query(myquery.Data());    
4446          if (!pResult->GetRowCount()){
4447            printf(" PamLevel2::GetYodaEntry() ERROR! event is not included in any run!!! \n");
4448            cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
4449            cout << "\nFor bug reporting instructions, please see for example:\n";
4450            cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
4451            cout << "  " << endl;
4452            return 0;
4453          }
4454          if ( pResult->GetRowCount() == 1 ){
4455            if (DBG) printf(" PamLevel2::GetYodaEntry() - WARNING - YodaEntry not found but only one run containing the event, it should not happen \n");
4456            //        printf(" PamLevel2::GetYodaEntry() - WARNING - YodaEntry not found but only one run containing the event, it should not happen \n");//TOGLITOGLI
4457          }
4458          for( Int_t ru=0; ru < pResult->GetRowCount(); ru++){ // loop over runs containing the event
4459            if (Row) delete Row;
4460            Row = pResult->Next();  
4461            if( Row == NULL ) break;
4462            UInt_t idrun = (UInt_t)atoll(Row->GetField(0));
4463            UInt_t nev = (UInt_t)atoll(Row->GetField(1));
4464            if (DBG) printf(" inside loop over runs: ru %i idrun %i nev %i \n",ru,idrun,nev);
4465            //        printf(" inside loop over runs: ru %i idrun %i nev %i \n",ru,idrun,nev);//TOGLITOGLI
4466    
4467            // now look for this run in the level2 file, it must be present! code is taken from updateruninfo of course
4468            Bool_t rfound = false;
4469            totrunentry = 0LL;
4470            runfirstentry = 0LL;
4471            for (Int_t r=0; r< run_tree->GetEntries();r++){
4472              run_tree->GetEntry(r);//update runinfo
4473              if ( r > 0 ){
4474                totrunentrymin = totrunentrymax+1;
4475              } else {
4476                totrunentrymin = 0LL;
4477              }
4478              totrunentry += GetRunInfo()->NEVENTS;
4479              totrunentrymax = totrunentry - 1 - prevshift; // prevshift is needed to handle nested+DV_skipped packets
4480              irun = r;        
4481    
4482              if (idrun == GetRunInfo()->ID){
4483                if ( totrunentrymin > iev ){ // there is a shift (nested+DV_skipped packets)
4484                  if (DBG) printf("PamLevel2::GetYodaEntry - unconsistent iev - nevents, probable DBL0-L2 async\n");
4485                  if (DBG) printf("PamLevel2::GetYodaEntry - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);
4486                  //              printf("PamLevel2::GetYodaEntry - unconsistent iev - nevents, probable DBL0-L2 async\n");
4487                  //              printf("PamLevel2::GetYodaEntry - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);//TOGLITOGLI
4488                  prevshift += (totrunentrymin-iev); // add the new shift to total shift
4489                  totrunentrymin -= (totrunentrymin-iev); // shift run position min
4490                  totrunentrymax -= (totrunentrymin-iev); // shift run position max
4491                  if (DBG) printf("PamLevel2::GetYodaEntry - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);
4492                  //              printf("PamLevel2::GetYodaEntry - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);//TOGLITOGLI
4493                }
4494                runfirstentry = totrunentrymin; // first entry of the run in the level2
4495              
4496    
4497                //
4498                if (gltsync)
4499                  delete gltsync; // Emiliano
4500                if (!dbc || (dbc && !dbc->IsConnected()))
4501                  SetDBConnection(); //Emiliano
4502                gltsync = new GL_TIMESYNC(GetRunInfo()->ID_ROOT_L0, "ID", dbc, false); // Emiliano
4503                if (dbc){
4504                  dbc->Close(); // Emiliano
4505                  delete dbc;
4506                  dbc=0;
4507                }          
4508                if (gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT) > gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT)) { // Emiliano
4509                  cout << "Bool_t PamLevel2::UpdateRunInfo(Long64_t iev) -- WARNING -- irun " << irun
4510                       << "  has RUNHEADER_OBT>=RUNTRAILER_OBT " << endl;
4511                  cout
4512                    << "                                                            (NB!! in this case some events could be assigned to a wrong run)"
4513                    << endl;
4514                }
4515                //
4516                if (DBG) printf(" found \n");
4517                //            printf(" found \n");//TOGLITOGLI
4518                rfound = true;
4519                //
4520                break;
4521              }
4522            } // loop over run
4523            if ( !rfound ){
4524              printf(" PamLevel2::GetYodaEntry() ERROR! run is not present in the level2 file!!! \n");
4525              cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
4526              cout << "\nFor bug reporting instructions, please see for example:\n";
4527              cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
4528              cout << "  " << endl;        
4529              return 0;
4530            }
4531    
4532            // here we got the first run and we can check if it contains the level0 event
4533            if (!GetYodaTree()){
4534              printf(" PamLevel2::GetYodaEntry() : ERROR no level0 file loaded!\n");
4535              return 0;
4536            }      
4537    
4538            // get the current run entry
4539            irunentry = iev - runfirstentry;
4540            if (irunentry < 0) {
4541              if (DBG) cout << "Int_t PamLevel2::GetYodaEntry() -- ATTENZIONE -- irunentry negativo?!?! "<<(Int_t)irunentry<<endl;
4542              //          cout << "Int_t PamLevel2::GetYodaEntry() -- ATTENZIONE -- irunentry negativo?!?! "<<(Int_t)irunentry<<endl; // TOGLITOGLI
4543              irunentry = 0LL;
4544            }
4545            //  ---------------------------------
4546            //  if file is NOT a preselected file
4547            //  ---------------------------------
4548            quellagiusta = irunentry + (Long64_t)(run_obj->EV_FROM); // prevshift already included in irunentry
4549          
4550            if (DBG){
4551              cout << " irun "<< irun << " irunentry "<< irunentry<<" run_obj->EV_FROM "<<run_obj->EV_FROM <<" quella giusta "<<quellagiusta << endl;
4552              cout << " iroot "<<iroot<<" run_obj->ID_ROOT_L0 "<<run_obj->ID_ROOT_L0<<endl;
4553              cout << " time "<< abstime << endl;
4554            }
4555            //        cout << " irun "<< irun << " irunentry "<< irunentry<<" run_obj->EV_FROM "<<run_obj->EV_FROM <<" quella giusta "<<quellagiusta << endl;
4556            //        cout << " iroot "<<iroot<<" run_obj->ID_ROOT_L0 "<<run_obj->ID_ROOT_L0<<endl;
4557            //        cout << " time "<< abstime << endl; // TOGLITOGLI
4558          
4559            shift = 0;
4560            answer = quellagiusta + shift + yprevshift; // prevshift already included in irunentry
4561            readl0 = l0_tree->GetEntry(answer); // prevshift already included in irunentry
4562    
4563            if (DBG){
4564              printf(" siamo qua shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);
4565            }
4566            //        printf(" siamo qua shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);//TOGLITOGLI
4567          
4568            while ( (obt != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()) || pktn != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter())) && (quellagiusta + (Long64_t) shift) < GetYodaTree()->GetEntries() && shift < maxshift ){
4569              if (shift > 0) {
4570                cout << " PKTNUM  L2 --- " << pktn << " --- L0 --- " << GetEventHeader()->GetPscuHeader()->GetCounter() << endl;
4571                if (DBG)
4572                  cout << "         RUN: ID " << GetRunInfo()->ID << " ID_ROOT_L0 " << run_obj->ID_ROOT_L0 << " ID_RUN_FRAG "
4573                       << GetRunInfo()->ID_RUN_FRAG << " EV_FROM " << GetRunInfo()->EV_FROM << endl;
4574                if (DBG)
4575                  cout << "         L2 <--> L0 mismatch ( irun " << irun << " irunentry " << irunentry << " shift " << shift
4576                       << " prevshift " << prevshift << " )" << endl;
4577              }
4578              answer = quellagiusta +  shift+ yprevshift;
4579              readl0 = l0_tree->GetEntry(answer);
4580              //          printf(" inside inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);//TOGLITOGLI
4581            
4582              if (!GetEventHeader()) {
4583                cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- missing EventHeader " << endl;
4584                return 0;
4585              }
4586              //
4587              if (yprevshift != 0 && (quellagiusta + (Long64_t) shift) == GetYodaTree()->GetEntries()) {
4588                if (DBG) printf(" reset inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);
4589                //            printf(" reset inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);//TOGLITOGLI
4590                yprevshift = 0;
4591                shift = -1;
4592              };
4593            
4594              shift++;
4595            }
4596          
4597            if ( obt != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()) || pktn != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter()) ){
4598              //still not the good run... continue with the nex one!
4599              printf("still not the good run... continue with the nex one!\n");
4600            } else {
4601              if (DBG) cout << "LA ENTRY GIUSTA E`: "<<quellagiusta<<" (spero...)"<<endl;
4602              //          cout << "LA ENTRY GIUSTA E`: "<<answer<<" (spero...)"<<endl;//TOGLITOGLI
4603              if (shift > 1) yprevshift = (shift - 1);
4604              if (Row) delete Row;
4605              delete pResult;  
4606              if (dbc){
4607                dbc->Close(); // Emiliano
4608                delete dbc;
4609                dbc=0;
4610              }    
4611              il0entry = answer;
4612              return readl0;
4613            }
4614            // perhaps it is all
4615          }// loop over runs containing the event
4616          if (Row) delete Row;
4617          delete pResult;  
4618          if (dbc){
4619            dbc->Close(); // Emiliano
4620            delete dbc;
4621            dbc=0;
4622          }          
4623          // arriving here it means no run found, cannot be! error!
4624          printf(" PamLevel2::GetYodaEntry() ERROR! run is not present in the level0 files!!! \n");
4625          cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
4626          cout << "\nFor bug reporting instructions, please see for example:\n";
4627          cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
4628          cout << "  " << endl;        
4629          return 0;
4630        } else {
4631          if (DBG) cout << "=> LA ENTRY GIUSTA E`: "<<answer<<" (spero...)"<<endl;
4632          //    cout << "=> LA ENTRY GIUSTA E`: "<<answer<<" (spero...)"<<endl;
4633          //    printf("obt %lld (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()) %i  pktn %lld (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter() %i \n",obt,(UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()), pktn, (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter()) );
4634          if (shift > 1) yprevshift = (shift - 1);
4635          il0entry = answer;
4636          return readl0;
4637        }
4638    
4639        /*  } // if selli 0 || 2
4640      if ( SELLI == 1 && hasL0EE ){
4641        sel_tree->GetEntry(iev);  
4642        Long64_t answer = il0entry;
4643        Int_t readl0 = 0;
4644        readl0 = l0_tree->GetEntry(answer);
4645        return readl0;
4646        }*/
4647      printf(" PamLevel2::GetYodaEntry() ERROR! \n");
4648      cout << " Entry not found! OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
4649      cout << "\nFor bug reporting instructions, please see for example:\n";
4650      cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
4651      cout << "  " << endl;
4652      return 0;
4653    }
4654    
4655    /**
4656     * \Brief Set DB connection
4657     */
4658    Bool_t PamLevel2::SetDBConnection() {
4659    
4660      //    cout << "PamLevel2::SetDBConnection()" << endl;
4661      if (DBG) {
4662        cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
4663        cout << "Connecting to DB" << endl;
4664        cout << "HOST " << host << endl;
4665        cout << "USER " << user << endl;
4666        cout << "PSW  " << psw << endl;
4667      }
4668      Bool_t notconn = true;
4669      Int_t trials = 0;
4670      while ( notconn && trials < 10 ){
4671        //    gSystem->Sleep(500);
4672        dbc = TSQLServer::Connect(host.Data(), user.Data(), psw.Data());
4673        //dbc->Connect(host.Data(), user.Data(), psw.Data());
4674        if ( dbc ) notconn = false;
4675        if (DBG) printf("<%i> test connection...\n ",trials);
4676        if (!dbc){
4677          if (DBG) printf(" :( failed, no pointer \n");
4678          notconn = true;
4679          //      return false;
4680        };
4681        if (dbc && !dbc->IsConnected()){
4682          if (DBG) printf(" :( failed, no connection \n");
4683          notconn = true;
4684          //      return false;
4685        };
4686        trials++;
4687      };
4688      if ( notconn ) return false;
4689      //
4690      if (DBG) printf("=connected!\n");
4691      stringstream myquery; // EMILIANO
4692      myquery.str(""); // EMILIANO
4693      myquery << "SET time_zone='+0:00'"; // EMILIANO
4694      dbc->Query(myquery.str().c_str()); // EMILIANO
4695      if ( DBG ) printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
4696      return true;
4697    
4698    }
4699    
4700    /**
4701     * \Brief Add a friend to the pamela chain.
4702     * @param cname name of the chain to be added
4703     */
4704    
4705    TChain* PamLevel2::AddFriend(TString cname) {
4706    
4707      if (!GetPamTree()) {
4708        cout << " TChain* PamLevel2::AddFriend(TString cname) --- a pamela tree must be created first" << endl;
4709        return NULL;
4710      }
4711    
4712      TChain *c = new TChain(cname.Data());
4713    
4714      TIter next(GetPamTree()->GetListOfFiles());
4715      Int_t nf = 0;
4716      TChainElement* element = 0;
4717      while ((element = (TChainElement*) next())) {
4718        c->Add(element->GetTitle());
4719        nf++;
4720      }
4721    
4722      GetPamTree()->AddFriend(cname.Data());
4723    
4724      cout << "external chain created and added to pamela friends :" << cname << endl;
4725      cout << "n.files " << nf << endl;
4726    
4727      return c;
4728    
4729    }
4730    
4731    /**
4732     * Returns the current read entry. This method simply returns the result of the call to
4733     * pam_tree->GetReadEntry(), so it is entirely handled by ROOT.
4734     */
4735    Long64_t PamLevel2::GetReadEntry() {
4736      return pam_tree->GetReadEntry();
4737    }
4738    
4739    /**
4740     * Sets the sorting method. If the new method is different from the previous, the issorted
4741     * flag is set to false, forcing a new sort the next time GetTrack is called.
4742     * @see GetTrack
4743     */
4744    void PamLevel2::SetSortingMethod(TString how) {
4745      if (howtosort != how) {
4746        issorted = false;
4747      }
4748      howtosort = how;
4749    }

Legend:
Removed from v.1.7  
changed lines
  Added in v.1.91

  ViewVC Help
Powered by ViewVC 1.1.23