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

Legend:
Removed from v.1.2  
changed lines
  Added in v.1.89

  ViewVC Help
Powered by ViewVC 1.1.23