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

Legend:
Removed from v.1.16  
changed lines
  Added in v.1.94

  ViewVC Help
Powered by ViewVC 1.1.23