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

Legend:
Removed from v.1.1.1.1  
changed lines
  Added in v.1.82

  ViewVC Help
Powered by ViewVC 1.1.23