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

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

  ViewVC Help
Powered by ViewVC 1.1.23