/[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.25 by mocchiut, Thu Mar 15 13:42:36 2007 UTC revision 1.93 by mocchiut, Thu Jan 16 15:36:32 2014 UTC
# Line 1  Line 1 
1  #include <PamLevel2.h>  #include <PamLevel2.h>
2    
3    /////////////////////////////////////////////////////////////////////////////
4    /////////////////////////////////////////////////////////////////////////////
5    /////////////////////////////////////////////////////////////////////////////
6    /////////////////////////////////////////////////////////////////////////////
7    
8    void GPamela::Clear() {
9      Irun = 0;
10      Ievnt = 0;
11      Ipa = 0;
12      X0 = 0.;
13      Y0 = 0.;
14      Z0 = 0.;
15      Theta = 0.;
16      Phi = 0.;
17      P0 = 0.;
18      Nthtof = 0;
19      Nthcat = 0;
20      Nthcas = 0;
21      Nthspe = 0;
22      Nstrpx = 0;
23      Nstrpy = 0;
24      Nthcali = 0;
25      Nthcal = 0;
26      Nthnd = 0;
27      Nthcard = 0;
28    }
29    
30    void GPamela::Delete() {
31    
32      Clear();
33      /* EM all these are in the stack not in the heap, so no need to delete by hand...
34      delete[] Ipltof;
35      delete[] Ipaddle;
36      delete[] Ipartof;
37      delete[] Xintof;
38      delete[] Yintof;
39      delete[] Zintof;
40      delete[] Xouttof;
41      delete[] Youttof;
42      delete[] Zouttof;
43      delete[] Ereltof;
44      delete[] Timetof;
45      delete[] Pathtof;
46      delete[] P0tof;
47      delete[] Iparcat;
48      delete[] Icat;
49      delete[] Xincat;
50      delete[] Yincat;
51      delete[] Zincat;
52      delete[] Xoutcat;
53      delete[] Youtcat;
54      delete[] Zoutcat;
55      delete[] Erelcat;
56      delete[] Timecat;
57      delete[] Pathcat;
58      delete[] P0cat;
59      delete[] Iparcas;
60      delete[] Icas;
61      delete[] Xincas;
62      delete[] Yincas;
63      delete[] Zincas;
64      delete[] Xoutcas;
65      delete[] Youtcas;
66      delete[] Zoutcas;
67      delete[] Erelcas;
68      delete[] Timecas;
69      delete[] Pathcas;
70      delete[] P0cas;
71      delete[] Iparspe;
72      delete[] Itrpb;
73      delete[] Itrsl;
74      delete[] Itspa;
75      delete[] Xinspe;
76      delete[] Yinspe;
77      delete[] Zinspe;
78      delete[] Xoutspe;
79      delete[] Youtspe;
80      delete[] Zoutspe;
81      delete[] Xavspe;
82      delete[] Yavspe;
83      delete[] Zavspe;
84      delete[] Erelspe;
85      delete[] Pathspe;
86      delete[] P0spe;
87      delete[] Nxmult;
88      delete[] Nymult;
89      delete[] Npstripx;
90      delete[] Ntstripx;
91      delete[] Istripx;
92      delete[] Qstripx;
93      delete[] Xstripx;
94      delete[] Npstripy;
95      delete[] Ntstripy;
96      delete[] Istripy;
97      delete[] Qstripy;
98      delete[] Ystripy;
99      delete[] Icaplane;
100      delete[] Icastrip;
101      delete[] Icamod;
102      delete[] Enestrip;
103      delete[] Icapl;
104      delete[] Icasi;
105      delete[] Icast;
106      delete[] Xincal;
107      delete[] Yincal;
108      delete[] Zincal;
109      delete[] Erelcal;
110      delete[] Itubend;
111      delete[] Iparnd;
112      delete[] Xinnd;
113      delete[] Yinnd;
114      delete[] Zinnd;
115      delete[] Xoutnd;
116      delete[] Youtnd;
117      delete[] Zoutnd;
118      delete[] Erelnd;
119      delete[] Timend;
120      delete[] Pathnd;
121      delete[] P0nd;
122      delete[] Iparcard;
123      delete[] Icard;
124      delete[] Xincard;
125      delete[] Yincard;
126      delete[] Zincard;
127      delete[] Xoutcard;
128      delete[] Youtcard;
129      delete[] Zoutcard;
130      delete[] Erelcard;
131      delete[] Timecard;
132      delete[] Pathcard;
133      delete[] P0card;
134      */
135    }
136    
137    
138    void GPamela::SetBranchAddress(TChain* fhBookTree) {
139    
140      //    cout << "fhBookTree "<<fhBookTree << endl;
141      // prepare tree
142      fhBookTree->SetBranchAddress("Irun", &Irun);
143      fhBookTree->SetBranchAddress("Ievnt", &Ievnt);
144      fhBookTree->SetBranchAddress("Ipa", &Ipa);
145      fhBookTree->SetBranchAddress("X0", &X0);
146      fhBookTree->SetBranchAddress("Y0", &Y0);
147      fhBookTree->SetBranchAddress("Z0", &Z0);
148      fhBookTree->SetBranchAddress("Theta", &Theta);
149      fhBookTree->SetBranchAddress("Phi", &Phi);
150      fhBookTree->SetBranchAddress("P0", &P0);
151      fhBookTree->SetBranchAddress("Nthtof", &Nthtof);
152      fhBookTree->SetBranchAddress("Ipltof", Ipltof);
153      fhBookTree->SetBranchAddress("Ipaddle", Ipaddle);
154      fhBookTree->SetBranchAddress("Ipartof", Ipartof);
155      fhBookTree->SetBranchAddress("Xintof", Xintof);
156      fhBookTree->SetBranchAddress("Yintof", Yintof);
157      fhBookTree->SetBranchAddress("Zintof", Zintof);
158      fhBookTree->SetBranchAddress("Xouttof", Xouttof);
159      fhBookTree->SetBranchAddress("Youttof", Youttof);
160      fhBookTree->SetBranchAddress("Zouttof", Zouttof);
161      fhBookTree->SetBranchAddress("Ereltof", Ereltof);
162      fhBookTree->SetBranchAddress("Timetof", Timetof);
163      fhBookTree->SetBranchAddress("Pathtof", Pathtof);
164      fhBookTree->SetBranchAddress("P0tof", P0tof);
165      fhBookTree->SetBranchAddress("Nthcat", &Nthcat);
166      fhBookTree->SetBranchAddress("Iparcat", Iparcat);
167      fhBookTree->SetBranchAddress("Icat", Icat);
168      fhBookTree->SetBranchAddress("Xincat", Xincat);
169      fhBookTree->SetBranchAddress("Yincat", Yincat);
170      fhBookTree->SetBranchAddress("Zincat", Zincat);
171      fhBookTree->SetBranchAddress("Xoutcat", Xoutcat);
172      fhBookTree->SetBranchAddress("Youtcat", Youtcat);
173      fhBookTree->SetBranchAddress("Zoutcat", Zoutcat);
174      fhBookTree->SetBranchAddress("Erelcat", Erelcat);
175      fhBookTree->SetBranchAddress("Timecat", Timecat);
176      fhBookTree->SetBranchAddress("Pathcat", Pathcat);
177      fhBookTree->SetBranchAddress("P0cat", P0cat);
178      fhBookTree->SetBranchAddress("Nthcas", &Nthcas);
179      fhBookTree->SetBranchAddress("Iparcas", Iparcas);
180      fhBookTree->SetBranchAddress("Icas", Icas);
181      fhBookTree->SetBranchAddress("Xincas", Xincas);
182      fhBookTree->SetBranchAddress("Yincas", Yincas);
183      fhBookTree->SetBranchAddress("Zincas", Zincas);
184      fhBookTree->SetBranchAddress("Xoutcas", Xoutcas);
185      fhBookTree->SetBranchAddress("Youtcas", Youtcas);
186      fhBookTree->SetBranchAddress("Zoutcas", Zoutcas);
187      fhBookTree->SetBranchAddress("Erelcas", Erelcas);
188      fhBookTree->SetBranchAddress("Timecas", Timecas);
189      fhBookTree->SetBranchAddress("Pathcas", Pathcas);
190      fhBookTree->SetBranchAddress("P0cas", P0cas);
191      fhBookTree->SetBranchAddress("Nthspe", &Nthspe);
192      fhBookTree->SetBranchAddress("Iparspe", Iparspe);
193      fhBookTree->SetBranchAddress("Itrpb", Itrpb);
194      fhBookTree->SetBranchAddress("Itrsl", Itrsl);
195      fhBookTree->SetBranchAddress("Itspa", Itspa);
196      fhBookTree->SetBranchAddress("Xinspe", Xinspe);
197      fhBookTree->SetBranchAddress("Yinspe", Yinspe);
198      fhBookTree->SetBranchAddress("Zinspe", Zinspe);
199      fhBookTree->SetBranchAddress("Xoutspe", Xoutspe);
200      fhBookTree->SetBranchAddress("Youtspe", Youtspe);
201      fhBookTree->SetBranchAddress("Zoutspe", Zoutspe);
202      fhBookTree->SetBranchAddress("Xavspe", Xavspe);
203      fhBookTree->SetBranchAddress("Yavspe", Yavspe);
204      fhBookTree->SetBranchAddress("Zavspe", Zavspe);
205      fhBookTree->SetBranchAddress("Erelspe", Erelspe);
206      fhBookTree->SetBranchAddress("Pathspe", Pathspe);
207      fhBookTree->SetBranchAddress("P0spe", P0spe);
208      fhBookTree->SetBranchAddress("Nxmult", Nxmult);
209      fhBookTree->SetBranchAddress("Nymult", Nymult);
210      fhBookTree->SetBranchAddress("Nstrpx", &Nstrpx);
211      fhBookTree->SetBranchAddress("Npstripx", Npstripx);
212      fhBookTree->SetBranchAddress("Ntstripx", Ntstripx);
213      fhBookTree->SetBranchAddress("Istripx", Istripx);
214      fhBookTree->SetBranchAddress("Qstripx", Qstripx);
215      fhBookTree->SetBranchAddress("Xstripx", Xstripx);
216      fhBookTree->SetBranchAddress("Nstrpy", &Nstrpy);
217      fhBookTree->SetBranchAddress("Npstripy", Npstripy);
218      fhBookTree->SetBranchAddress("Ntstripy", Ntstripy);
219      fhBookTree->SetBranchAddress("Istripy", Istripy);
220      fhBookTree->SetBranchAddress("Qstripy", Qstripy);
221      fhBookTree->SetBranchAddress("Ystripy", Ystripy);
222      fhBookTree->SetBranchAddress("Nthcali", &Nthcali);
223      fhBookTree->SetBranchAddress("Icaplane", Icaplane);
224      fhBookTree->SetBranchAddress("Icastrip", Icastrip);
225      fhBookTree->SetBranchAddress("Icamod", Icamod);
226      fhBookTree->SetBranchAddress("Enestrip", Enestrip);
227      fhBookTree->SetBranchAddress("Nthcal", &Nthcal);
228      fhBookTree->SetBranchAddress("Icapl", Icapl);
229      fhBookTree->SetBranchAddress("Icasi", Icasi);
230      fhBookTree->SetBranchAddress("Icast", Icast);
231      fhBookTree->SetBranchAddress("Xincal", Xincal);
232      fhBookTree->SetBranchAddress("Yincal", Yincal);
233      fhBookTree->SetBranchAddress("Zincal", Zincal);
234      fhBookTree->SetBranchAddress("Erelcal", Erelcal);
235      fhBookTree->SetBranchAddress("Nthnd", &Nthnd);
236      fhBookTree->SetBranchAddress("Itubend", Itubend);
237      fhBookTree->SetBranchAddress("Iparnd", Iparnd);
238      fhBookTree->SetBranchAddress("Xinnd", Xinnd);
239      fhBookTree->SetBranchAddress("Yinnd", Yinnd);
240      fhBookTree->SetBranchAddress("Zinnd", Zinnd);
241      fhBookTree->SetBranchAddress("Xoutnd", Xoutnd);
242      fhBookTree->SetBranchAddress("Youtnd", Youtnd);
243      fhBookTree->SetBranchAddress("Zoutnd", Zoutnd);
244      fhBookTree->SetBranchAddress("Erelnd", Erelnd);
245      fhBookTree->SetBranchAddress("Timend", Timend);
246      fhBookTree->SetBranchAddress("Pathnd", Pathnd);
247      fhBookTree->SetBranchAddress("P0nd", P0nd);
248      fhBookTree->SetBranchAddress("Nthcard", &Nthcard);
249      fhBookTree->SetBranchAddress("Iparcard", Iparcard);
250      fhBookTree->SetBranchAddress("Icard", Icard);
251      fhBookTree->SetBranchAddress("Xincard", Xincard);
252      fhBookTree->SetBranchAddress("Yincard", Yincard);
253      fhBookTree->SetBranchAddress("Zincard", Zincard);
254      fhBookTree->SetBranchAddress("Xoutcard", Xoutcard);
255      fhBookTree->SetBranchAddress("Youtcard", Youtcard);
256      fhBookTree->SetBranchAddress("Zoutcard", Zoutcard);
257      fhBookTree->SetBranchAddress("Erelcard", Erelcard);
258      fhBookTree->SetBranchAddress("Timecard", Timecard);
259      fhBookTree->SetBranchAddress("Pathcard", Pathcard);
260      fhBookTree->SetBranchAddress("P0card", P0card);
261    
262      //    fhBookTree->SetBranchStatus("*",0);
263    
264    }
265    
266    ClassImp( GPamela);
267    
268    /////////////////////////////////////////////////////////////////////////////
269    /////////////////////////////////////////////////////////////////////////////
270    /////////////////////////////////////////////////////////////////////////////
271    /////////////////////////////////////////////////////////////////////////////
272  //--------------------------------------  //--------------------------------------
273  //  //
274  //  //
275  //--------------------------------------  //--------------------------------------
276  /**  /**
277   * Default constructor   * Default constructor
278   */   */
279  PamTrack::PamTrack(){  PamTrack::PamTrack() {
280      trk_track  = 0;    trk_track = 0;
281      calo_track = 0;    calo_track = 0;
282      tof_track  = 0;    tof_track = 0;
283      candeleteobj = 0;    orb_track = 0;
284  };    candeleteobj = 0;
285      pscore = 0;
286      iscore = 0;
287    }
288    ;
289  //--------------------------------------  //--------------------------------------
290  //  //
291  //  //
292  //--------------------------------------  //--------------------------------------
293  /**  /**
294   * Constructor   * Constructor
295   */   */
296  PamTrack::PamTrack(TrkTrack* t, CaloTrkVar* c, ToFTrkVar* o){  PamTrack::PamTrack(TrkTrack* t, CaloTrkVar* c, ToFTrkVar* o, OrbitalInfoTrkVar *r) {
297    
298      trk_track  = 0;    trk_track = 0;
299      calo_track = 0;    calo_track = 0;
300      tof_track  = 0;    tof_track = 0;
301  //     if(t)trk_track  = new TrkTrack(*t);    orb_track = 0;
302  //     if(c)calo_track = new CaloTrkVar(*c);    //     if(t)trk_track  = new TrkTrack(*t);
303  //     if(o)tof_track  = new ToFTrkVar(*o);    //     if(c)calo_track = new CaloTrkVar(*c);
304      if(t)trk_track  = t;    //     if(o)tof_track  = new ToFTrkVar(*o);
305      if(c)calo_track = c;    if (t)
306      if(o)tof_track  = o;      trk_track = t;
307      candeleteobj = 0;    if (c)
308        calo_track = c;
309  };    if (o)
310  PamTrack::PamTrack(const PamTrack& track){      tof_track = o;
311      if (r)
312      TrkTrack   *t = track.trk_track;      orb_track = r;
313      CaloTrkVar *c = track.calo_track;  
314      ToFTrkVar  *o = track.tof_track;    candeleteobj = 0;
315    
316    }
317    ;
318    PamTrack::PamTrack(const PamTrack& track) {
319    
320      TrkTrack *t = track.trk_track;
321      CaloTrkVar *c = track.calo_track;
322      ToFTrkVar *o = track.tof_track;
323      OrbitalInfoTrkVar *r = track.orb_track;
324    
325      trk_track = 0;
326      calo_track = 0;
327      tof_track = 0;
328      orb_track = 0;
329      if (t)
330        trk_track = new TrkTrack(*t);
331      if (c)
332        calo_track = new CaloTrkVar(*c);
333      if (o)
334        tof_track = new ToFTrkVar(*o);
335      if (r)
336        orb_track = new OrbitalInfoTrkVar(*r);
337      candeleteobj = 1;
338    
     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;  
       
339  }  }
340  void PamTrack::Clear(){  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;
369          calo_track = 0;      }
370          tof_track  = 0;      if (calo_track) {
371      }        calo_track->CaloTrkVar::Clear();//???
372  }        delete calo_track;
 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();  
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;  
397    
     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 = -1;  
     runfirstentry = 0ULL;  
     runlastentry = 0ULL;  
   
     l0_file = NULL;  
     l0_tree = NULL;  
     iroot   = -1;  
     dbc     = 0;  
       
     irun = -1;  
     run_tree = NULL;  
     run_tree_clone = NULL;  
     sel_tree = NULL;  
     sel_tree_clone = NULL;  
       
     irunentry = -1;  
     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(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(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
758          return &calo1_obj;      };
759      };      //
760      if(!objname.CompareTo("CaloLevel2")) {      // deleting the main chain
761          if(!calo2_obj){      //
762              calo2_obj = new CaloLevel2();      pam_tree->Delete();
763              calo2_obj->Set();      //
764          };      // deleting the friends...
765          return &calo2_obj;      //
766      };      TIter next2(contents);
767      if(!objname.CompareTo("ToFLevel2"))  {      TChain *questa = 0;
768          if(!tof_obj){      while ( (questa = (TChain*) next2()) ) {
769              tof_obj   = new ToFLevel2();        TString name = questa->GetName();
770              tof_obj->Set();        questa->Delete();
771          }        questa = NULL;
         return &tof_obj;  
     };  
     if(!objname.CompareTo("TrigLevel2")) {  
         if(!trig_obj)  trig_obj  = new TrigLevel2();  
         return &trig_obj;  
     };  
     if(!objname.CompareTo("S4Level2"))   {  
         if(!s4_obj)    s4_obj    = new S4Level2();  
         return &s4_obj;  
     };  
     if(!objname.CompareTo("NDLevel2"))   {  
         if(!nd_obj)    nd_obj    = new NDLevel2();  
         return &nd_obj;  
     };  
     if(!objname.CompareTo("AcLevel2"))   {  
         if(!ac_obj)    ac_obj    = new AcLevel2();  
         return &ac_obj;  
     };  
     if(!objname.CompareTo("OrbitalInfo")){  
         if(!orb_obj)   orb_obj   = new OrbitalInfo();  
         return &orb_obj;  
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      if(!objname.CompareTo("SoftInfo"))return &soft_obj; // Emiliano  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    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;  
 };  
 //--------------------------------------  
 //  
 //  
 //--------------------------------------  
 /**  
  * Retrieves the calorimeter track matching the seqno-th tracker stored track.  
  * (If seqno = -1 retrieves the self-trigger calorimeter track)  
  */  
  CaloTrkVar *PamLevel2::GetCaloStoredTrack(int seqno){  
       
      if( !calo2_obj )return 0;  
   
      if( calo2_obj->CaloLevel2::ntrk()==0 ){  
          cout << "PamLevel2::GetCaloStoredTrack(int) : requested tracker SeqNo "<< seqno <<" but no Calorimeter tracks are stored"<<endl;  
          return NULL;  
      };  
       
      CaloTrkVar *c = 0;  
      Int_t it_calo=0;  
       
      do{  
          c = calo2_obj->CaloLevel2::GetCaloTrkVar(it_calo);  
          it_calo++;  
      } while( c && seqno != c->trkseqno && it_calo < calo2_obj->CaloLevel2::ntrk());      
       
      if(!c || seqno != c->trkseqno){  
          c = 0;  
          if(seqno!=-1)cout << "PamLevel2::GetCaloStoredTrack(int) : requested tracker SeqNo "<< seqno <<" does not match Calorimeter stored tracks"<<endl;  
      };  
      return c;  
       
  };  
 //--------------------------------------  
  //  
  //  
 //--------------------------------------  
 /**  
   * Retrieves the ToF track matching the seqno-th tracker stored track.  
   * (If seqno = -1 retrieves the tracker-independent tof track)  
  */  
  ToFTrkVar *PamLevel2::GetToFStoredTrack(int seqno){  
           
      if( !tof_obj )return 0;  
   
      if( tof_obj->ToFLevel2::ntrk()==0 ){  
          cout << "PamLevel2::GetToFStoredTrack(int) : requested tracker SeqNo "<< seqno <<" but no ToF tracks are stored"<<endl;  
          return NULL;  
      };  
       
      ToFTrkVar *c = 0;  
      Int_t it_tof=0;  
       
      do{  
          c = tof_obj->ToFLevel2::GetToFTrkVar(it_tof);  
          it_tof++;  
      } while( c && seqno != c->trkseqno && it_tof < tof_obj->ToFLevel2::ntrk());          
       
      if(!c || seqno != c->trkseqno){  
          c = 0;  
          if(seqno!=-1)cout << "PamLevel2::GetToFStoredTrack(int) : requested tracker SeqNo "<< seqno <<" does not match ToF stored tracks"<<endl;  
      };  
      return c;  
       
  };  
   
 //--------------------------------------  
  //  
  //  
 //--------------------------------------  
 /**  
  * Give the pamela track associated to a tracker track, retrieving related calorimeter and tof track information.  
  */  
  PamTrack* PamLevel2::GetPamTrackAlong(TrkTrack* t){  
       
      cout <<"PamLevel2::GetPamTrackAlong(TrkTrack* t) **obsolete** "<<endl;  
      cout <<"(if you use it, remember to delete the PamTrack object)"<<endl;  
   
      CaloTrkVar *c = 0;  
      ToFTrkVar  *o = 0;  
       
      if(CAL2) c = GetCaloStoredTrack(t->GetSeqNo());  
      if(TOF) o = GetToFStoredTrack(t->GetSeqNo());  
       
 //    if(t && c && o)track = new PamTrack(t,c,o);  
      PamTrack *track = new PamTrack(t,c,o);  
       
      return track;  
   
  };  
894  //--------------------------------------  //--------------------------------------
895  //  //
896  //  //
897  //--------------------------------------  //--------------------------------------
898  /**  void *PamLevel2::GetPointerTo(const char* c) {
  * Retrieves the it-th stored track.  
  * It override TrkLevel2::GetTrack(int it).  
  * @param itrk Track number, ranging from 0 to GetNTracks().  
  */  
899    
900  PamTrack* PamLevel2::GetStoredTrack(Int_t itrk){    TString objname = c;
       
     cout <<"PamLevel2::GetStoredTrack(Int_t itrk) **to-be-updated** "<<endl;  
     cout <<"for the moment, better use separately the methods: TrkLevel2::GetStoredTrack(seqno) CaloLevel2::GetCaloTrkVar(Int_t notrack) ToFLevel2::GetToFTrkVar(Int_t notrack)"<<endl;  
     cout <<"(if you use it, remember to delete the PamTrack object)"<<endl;  
     PamTrack *track = 0;  
       
     if( itrk >=0 && itrk < trk2_obj->TrkLevel2::ntrk() ){  
           
         TrkTrack *t = trk2_obj->TrkLevel2::GetStoredTrack(itrk);  
         track = GetPamTrackAlong(t);  
           
           
901    
902      }else{    if (!objname.CompareTo("TrkLevel1")) {
903          cout << "PamLevel2::GetStoredTrack(int) : tracker track SeqNo "<< itrk <<" does not exist (GetNTracks() = "<<trk2_obj->TrkLevel2::GetNTracks()<<")"<<endl;      if (!trk1_obj) {
904          trk1_obj = new TrkLevel1();
905          trk1_obj->Set();
906        }
907        return &trk1_obj;
908      };
909      if (!objname.CompareTo("TrkLevel2")) {
910        if (!trk2_obj) {
911          trk2_obj = new TrkLevel2();
912          trk2_obj->Set();
913        }
914        return &trk2_obj;
915      };
916      if (!objname.CompareTo("TrkHough")) {
917        if (!trkh_obj) {
918          trkh_obj = new TrkHough();
919          trkh_obj->Set();
920        }
921        return &trkh_obj;
922      };
923      if (!objname.CompareTo("CaloLevel1")) {
924        if (!calo1_obj)
925          calo1_obj = new CaloLevel1();
926        return &calo1_obj;
927      };
928      if (!objname.CompareTo("CaloLevel2")) {
929        if (!calo2_obj) {
930          calo2_obj = new CaloLevel2();
931          calo2_obj->Set();
932      };      };
933            return &calo2_obj;
934      return track;    };
935          if (!objname.CompareTo("ToFLevel2")) {
936        if (!tof_obj) {
937          tof_obj = new ToFLevel2();
938          tof_obj->Set();
939        }
940        return &tof_obj;
941      };
942      if (!objname.CompareTo("TrigLevel2")) {
943        if (!trig_obj)
944          trig_obj = new TrigLevel2();
945        return &trig_obj;
946      };
947      if (!objname.CompareTo("S4Level2")) {
948        if (!s4_obj)
949          s4_obj = new S4Level2();
950        return &s4_obj;
951      };
952      if (!objname.CompareTo("NDLevel2")) {
953        if (!nd_obj)
954          nd_obj = new NDLevel2();
955        return &nd_obj;
956      };
957      if (!objname.CompareTo("AcLevel2")) {
958        if (!ac_obj)
959          ac_obj = new AcLevel2();
960        return &ac_obj;
961      };
962      if (!objname.CompareTo("OrbitalInfo")) {
963        if (!orb_obj) {
964          orb_obj = new OrbitalInfo();
965          orb_obj->Set();
966        }
967        return &orb_obj;
968      };
969      //     if(!objname.CompareTo("OrbitalInfo")){
970      //    if(!orb_obj)   orb_obj   = new OrbitalInfo();
971      //    return &orb_obj;
972      //     };
973      if (!objname.CompareTo("GPamela")) {
974        if (!gp_obj)
975          gp_obj = new GPamela();
976        return &gp_obj;
977      };
978    
979      if (!objname.CompareTo("RunInfo"))
980        return &run_obj;
981    
982      if (!objname.CompareTo("SoftInfo"))
983        return &soft_obj; // Emiliano
984    
985      return NULL;
986  }  }
987    ;
988  //--------------------------------------  //--------------------------------------
989  //  //
990  //  //
991  //--------------------------------------  //--------------------------------------
992  /**  /**
993   * Sort physical (tracker) tracks and stores them in the TRefArray (of TrkTrack objects) which pointer is  PamLevel2::sorted_tracks.   * Retrieves the calorimeter track matching the seqno-th tracker stored track.
994   * @param how String to set the sorting cryterium (es: "CAL" or "TRK+CAL+TOF" ecc...).   * (If seqno = -1 retrieves the self-trigger calorimeter 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).  
995   */   */
996  void PamLevel2::SortTracks(TString how){  CaloTrkVar *PamLevel2::GetCaloStoredTrack(int seqno) {
997    
998  //    cout <<" PamLevel2::SortTracks(TString how) "<<endl;    if (!calo2_obj)
999      if( !trk2_obj ){      return 0;
         cout << "void PamLevel2::SortTracks(TString how):  TrkLevel2 not loaded !!!";  
         return;  
     };  
 //    cout << "call SortTracs() "<<endl;  
   //Save current Object count  
     Int_t ObjectNumber = TProcessID::GetObjectCount();  
   
 //    cout << "ObjectNumber  "<<ObjectNumber <<endl;  
   
 //     if(!sorted_tracks)sorted_tracks = new TRefArray();  
 //     sorted_tracks->Clear();  
 //    sorted_tracks.Clear();  
1000    
1001      if(!tsorted)tsorted = new TClonesArray("PamTrack",trk2_obj->GetNTracks());    if (calo2_obj->CaloLevel2::ntrk() == 0) {
1002      tsorted->Delete();      cout << "PamLevel2::GetCaloStoredTrack(int) : requested tracker SeqNo " << seqno
1003      TClonesArray &ttsorted = *tsorted;          << " but no Calorimeter tracks are stored" << endl;
1004      if(!timage)timage = new TClonesArray("PamTrack",trk2_obj->GetNTracks());      return NULL;
1005      timage->Delete();    };
     TClonesArray &ttimage = *timage;  
1006    
1007      CaloTrkVar *c = 0;
1008      Int_t it_calo = 0;
1009    
1010      // loop over the tracks sorted by the tracker    do {
1011      Bool_t use_TRK = how.Contains("TRK", TString::kIgnoreCase);      c = calo2_obj->CaloLevel2::GetCaloTrkVar(it_calo);
1012      Bool_t use_CAL = how.Contains("CAL", TString::kIgnoreCase);      it_calo++;
1013      Bool_t use_TOF = how.Contains("TOF", TString::kIgnoreCase);    } while (c && seqno != c->trkseqno && it_calo < calo2_obj->CaloLevel2::ntrk());
1014        
1015      if( !CAL2 &&  use_CAL) use_CAL = false;    if (!c || seqno != c->trkseqno) {
1016      if( !TOF &&  use_TOF) use_TOF = false;      c = 0;
1017            if (seqno != -1)
1018      if( !TRK2 ){        cout << "PamLevel2::GetCaloStoredTrack(int) : requested tracker SeqNo " << seqno
1019  //      cout << "SortTracks() : without tracker does not work!!! (not yet)" << endl;            << " does not match Calorimeter stored tracks" << endl;
1020          return;    };
1021      };    return c;
1022    
1023      //   cout << "use_CAL "<<use_CAL<<" use_TOF "<<use_TOF<<" use_TRK "<<use_TRK <<endl;  }
1024        ;
     for(Int_t i=0; i < trk2_obj->TrkLevel2::GetNTracks(); i++){  
           
         TrkTrack   *ts = 0;  
         CaloTrkVar *cs = 0;  
         ToFTrkVar  *os = 0;  
           
         // get tracker tracks  
         TrkTrack   *tp = trk2_obj->TrkLevel2::GetTrack(i);                    //tracker  
         CaloTrkVar *cp = GetCaloStoredTrack(tp->GetSeqNo());  
         ToFTrkVar  *op = GetToFStoredTrack(tp->GetSeqNo());  
   
         TrkTrack   *ti = 0;              //tracker (image)  
         CaloTrkVar *ci = 0;  
         ToFTrkVar  *oi = 0;  
 //      cout << "trk track n. "<<i << " "<<hex<< tp <<dec<< endl;  
         // if track has an image, check image selection  
         if(tp->HasImage()){  
               
             ti = trk2_obj->TrkLevel2::GetTrackImage(i);              //tracker (image)  
             ci = GetCaloStoredTrack(ti->GetSeqNo());  
             oi = GetToFStoredTrack(ti->GetSeqNo());  
               
 //          cout << "its image "<<i << " "<<hex<< ti <<dec<< endl;  
   
             //assign starting scores  
             Int_t tp_score = 0;  //main track sorted by the tracker  
             Int_t ti_score = 0;  //image track  
               
             // ------------------------  
             // calorimeter check  
             // ------------------------  
             // check the Y spatial residual on the first calorimeter plane  
             // (cut on calorimeter variables from Emiliano)  
             if( use_CAL && !calo2_obj ){  
                 cout << "void PamLevel2::SortTracks(TString how): how= "<<how<<" but CaloLevel2 not loaded !!!";  
                 return;  
             };  
             if(  
                 use_CAL            &&  
                 calo2_obj->npcfit[1] > 15     &&   //no. of fit planes on Y view  
                 calo2_obj->varcfit[1] < 1000. &&  //fit variance on Y view  
                 true){  
   
                   
                 Float_t resy_p = cp->tbar[0][1] - calo2_obj->cbar[0][1]; if(resy_p < 0)resy_p= - resy_p;  
                 Float_t resy_i = ci->tbar[0][1] - calo2_obj->cbar[0][1]; if(resy_i < 0)resy_i= - resy_i;  
                   
                 if(resy_p <= resy_i) tp_score++;  
                 else                 ti_score++;  
   
 //              cout << "CALO "<<tp_score<<ti_score<<endl;  
   
             };  
             // ------------------------  
             // TOF check  
             // ------------------------      
             // check the number of hit pmts along the track  
             // on S12 S21 and S32, where paddles are parallel to Y axis  
             if( use_TOF && !tof_obj ){  
                 cout << "void PamLevel2::SortTracks(TString how): how= "<<how<<" but ToFLevel2 not loaded !!!";  
                 return;  
             };  
             if( use_TOF ){  
                   
                 Int_t nphit_p =0;  
                 Int_t nphit_i =0;  
                   
                   
 /*                              cout << "track: npmtadc "<< op->npmtadc << endl;  
                                 cout << "track: npmttdc "<< op->npmttdc << endl;  
                                 cout << "image: npmtadc "<< oi->npmtadc << endl;  
                                 cout << "image: npmttdc "<< oi->npmttdc << endl;*/  
                   
                 for (Int_t ih=0; ih < op->npmtadc; ih++){  
                     Int_t pl = tof_obj->GetPlaneIndex( (op->pmtadc).At(ih) );  
                     if(pl == 1 || pl == 2 || pl == 5)nphit_p++;  
                 };  
                   
                 for (Int_t ih=0; ih < oi->npmtadc; ih++){  
                     Int_t pl = tof_obj->GetPlaneIndex( (oi->pmtadc).At(ih) );  
                     if(pl == 1 || pl == 2 || pl == 5)nphit_i++;  
                 };  
                   
                 if(  
                     use_TOF            &&  
                     (nphit_p+nphit_i) !=0 &&      
                     true){  
                       
                     if( nphit_p >= nphit_i) tp_score++;  
                     else ti_score++;  
                 };  
 //              cout << "TOF "<<tp_score<<ti_score<<endl;  
             };  
             if(tp_score == ti_score) use_TRK = true;  
             // ------------------------  
             // tracker check  
             // ------------------------  
             // chi**2 difference is not always large enough to distinguish among  
             // the real track and its image.  
             // Tracker check will be applied always when calorimeter and tof information is ambiguous.  
             if(use_TRK){  
                 if(      tp->chi2 > 0 && tp->chi2 < ti->chi2 ) tp_score++ ;  
                 else if( ti->chi2 > 0 && ti->chi2 < tp->chi2 ) ti_score++ ;  
 //              cout << "TRK "<<tp_score<<ti_score<<endl;  
             };  
               
             // ------------------------  
             // the winner is....  
             // ------------------------      
             if      (tp_score > ti_score) {  
 //              ts = tp;//the track sorted by the tracker!!  
 //              cs = cp;  
 //              os = op;  
             }else if (tp_score < ti_score) {  
                 ts = ti;//its image!!  
                 cs = ci;  
                 os = oi;  
   
                 ti = tp;//its image!!  
                 ci = cp;  
                 oi = op;  
   
                 tp = ts;//its image!!  
                 cp = cs;  
                 op = os;  
   
                   
             }else {  
 //              ts = tp;  
 //              cs = cp;  
 //              os = op;  
 //                              cout << "Warning - track image ambiguity not solved" << endl;  
 //                              cout << ts->GetNtot() << " "<< ts->chi2 << " " << npcfit[1] << " "<< nphit_p << endl;  
             };  
               
         }else{  
 //          ts = tp;  
 //          cs = cp;  
 //          os = op;  
         };  
           
 //      cout <<" SortTracks() "<<i<<" -- "<<ts<<endl;  
 //      sorted_tracks->Add(ts);//save the track in the sorted array  
 //      sorted_tracks.Add(ts);//save the track in the sorted array  
 //      sorted_tracks.Add(tp);//save the track in the sorted array  
 //      cout << "SortTracks:: sorted_tracks->Add(it) "<<i<<" "<<ts<<endl;  
 //      cout<<"o "<<tp<<endl;  
 //      cout<<"o "<<cp<<endl;  
 //      cout<<"o "<<op<<endl;  
         new(ttsorted[i]) PamTrack(tp,cp,op);  
         new(ttimage[i])  PamTrack(ti,ci,oi);  
     };  
   
     if( tsorted->GetEntries() != trk2_obj->GetNTracks() ){  
         cout << "void PamLevel2::SortTracks(TString how): tsorted->GetEntries() "<<tsorted->GetEntries()<<" != trk2_obj->GetNTracks() = "<<trk2_obj->GetNTracks() <<endl;  
         tsorted->Delete(); tsorted=0;  
         timage->Delete(); timage=0;      
     }  
   
     //Restore Object count  
     //To save space in the table keeping track of all referenced objects  
     //We reset the object count to what it was at the beginning of the event.  
     TProcessID::SetObjectCount(ObjectNumber);  
       
 };  
1025  //--------------------------------------  //--------------------------------------
1026  //  //
1027  //  //
1028  //--------------------------------------  //--------------------------------------
1029  /**  /**
1030   * This method overrides TrkLevel2::GetTracks(), where sorting is done by decreasing number of fit points and increasing chi^2.   * Retrieves the ToF track matching the seqno-th tracker stored track.
1031   * PamLevel2::GetTracks() keeps the same track order given by TrkLevel2::GetTracks(), but checks image selection by using calorimeter and ToF tracking information.   * (If seqno = -1 retrieves the tracker-independent tof track)
1032   */   */
1033  // TRefArray *PamLevel2::GetTracks(){  ToFTrkVar *PamLevel2::GetToFStoredTrack(int seqno) {
1034    
1035  // //  *-*-*-*-*-*-*-*-*-*-*-*-*    if (!tof_obj)
1036  //     SortTracks("+CAL+TOF");      return 0;
 // //  *-*-*-*-*-*-*-*-*-*-*-*-*  
1037    
1038  // //   return  sorted_tracks;    if (tof_obj->ToFLevel2::ntrk() == 0) {
1039  //     return &sorted_tracks;      cout << "PamLevel2::GetToFStoredTrack(int) : requested tracker SeqNo " << seqno << " but no ToF tracks are stored"
1040                << endl;
1041  //  };      return NULL;
1042  TClonesArray *PamLevel2::GetTracks(){    };
1043    
1044  //  *-*-*-*-*-*-*-*-*-*-*-*-*    ToFTrkVar *c = 0;
1045      SortTracks("+CAL+TOF");    Int_t it_tof = 0;
1046  //  *-*-*-*-*-*-*-*-*-*-*-*-*  
1047      do {
1048        c = tof_obj->ToFLevel2::GetToFTrkVar(it_tof);
1049        it_tof++;
1050      } while (c && seqno != c->trkseqno && it_tof < tof_obj->ToFLevel2::ntrk());
1051    
1052      if (!c || seqno != c->trkseqno) {
1053        c = 0;
1054        if (seqno != -1)
1055          cout << "PamLevel2::GetToFStoredTrack(int) : requested tracker SeqNo " << seqno
1056              << " does not match ToF stored tracks" << endl;
1057      };
1058      return c;
1059    
1060    }
1061    ;
1062    
     return tsorted;  
       
  };  
1063  //--------------------------------------  //--------------------------------------
1064   //  //
1065   //  //
1066  //--------------------------------------  //--------------------------------------
1067  /**  /**
1068   * Retrieves the it-th Pamela "physical" track.   * Retrieves the OrbitalInfo track matching the seqno-th tracker stored track.
1069   * It override TrkLevel2::GetTrack(int it).   * (If seqno = -1 retrieves the tracker-independent tof related track)
  * @param it Track number, ranging from 0 to GetNTracks().  
1070   */   */
1071  PamTrack *PamLevel2::GetTrack(int it){  OrbitalInfoTrkVar *PamLevel2::GetOrbitalInfoStoredTrack(int seqno) {
1072    
1073  //    if(!trk2_obj) return 0;    if (!orb_obj)
1074                return 0;
 // //  *-*-*-*-*-*-*-*-*-*-*-*-*  
 //     SortTracks("+CAL+TOF");  
 // //  *-*-*-*-*-*-*-*-*-*-*-*-*  
 // //    if(!sorted_tracks)return 0;  
 //     if(sorted_tracks.IsEmpty())return 0;  
1075    
1076  //     PamTrack *track = 0;    if (orb_obj->OrbitalInfo::ntrk() == 0) {
1077            //       // TRICK BEGIN
1078  //     if( it >=0 && it < trk2_obj->TrkLevel2::GetNTracks() && it<sorted_tracks.GetEntriesFast() ){          //       OrbitalInfoTrkVar  *r = new OrbitalInfoTrkVar(); // TEMPORARY TRICK
1079  //      TrkTrack   *t = (TrkTrack*)sorted_tracks.At(it);      //       Int_t nn = 0;
1080  //      track = GetPamTrackAlong(t);      //       TClonesArray &tor = *orb_obj->OrbitalInfoTrk;
1081  //     }else{      //       for(Int_t nt=0; nt < tof_obj->ToFLevel2::ntrk(); nt++){
1082  //      cout << "PamLevel2::GetTrack(int) : tracker track SeqNo "<< it <<" does not exist (GetNTracks() = "<<trk2_obj->TrkLevel2::GetNTracks()<<")"<<endl;      //  //
1083  //     };      //  ToFTrkVar *ptt = tof_obj->ToFLevel2::GetToFTrkVar(nt);
1084            //  if ( ptt->trkseqno != -1  ){
1085  //     return track;      //    //
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  //    cout << "PamLevel2::GetTrack(int it) "<<endl;    OrbitalInfoTrkVar *c = 0;
1114  //  *-*-*-*-*-*-*-*-*-*-*-*-*    Int_t it_tof = 0;
     SortTracks("+CAL+TOF");  
 //  *-*-*-*-*-*-*-*-*-*-*-*-*  
     if(!tsorted)return 0;  
     if(!tsorted->GetEntries())return 0;  
1115    
1116      PamTrack *track = 0;    do {
1117            c = orb_obj->OrbitalInfo::GetOrbitalInfoTrkVar(it_tof);
1118      if( it >=0 && it < trk2_obj->TrkLevel2::GetNTracks()){      it_tof++;
1119  //      TrkTrack   *t = (TrkTrack*)sorted_tracks.At(it);    } while (c && seqno != c->trkseqno && it_tof < orb_obj->OrbitalInfo::ntrk());
1120  //      track = GetPamTrackAlong(t);  
1121          TClonesArray &t = *(tsorted);    if (!c || seqno != c->trkseqno) {
1122          track = (PamTrack*)t[it];      c = 0;
1123                if (seqno != -1)
1124      }else{        cout << "PamLevel2::GetOrbitalInfoStoredTrack(int) : requested tracker SeqNo " << seqno
1125          cout << "PamLevel2::GetTrack(int) : tracker track SeqNo "<< it <<" does not exist (GetNTracks() = "<<trk2_obj->TrkLevel2::GetNTracks()<<")"<<endl;            << " does not match OrbitalInfo stored tracks" << endl;
1126      };    };
1127          return c;
1128      return track;  
1129        }
1130  };  ;
1131    
1132  //--------------------------------------  //--------------------------------------
1133  //  //
1134  //  //
1135  //--------------------------------------  //--------------------------------------
1136  /**  /**
1137   * Retrieves (if present) the image of the it-th Pamela "physical" track, sorted by the method PamLevel2::SortTracks().   * Give the pamela track associated to a tracker track, retrieving related calorimeter, orbitalinfo and tof track information.
  * @param it Track number, ranging from 0 to GetNTracks().  
1138   */   */
1139  PamTrack *PamLevel2::GetTrackImage(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;
1143    
1144  // //  *-*-*-*-*-*-*-*-*-*-*-*-*    CaloTrkVar *c = 0;
1145  //     SortTracks("+CAL+TOF");    ToFTrkVar *o = 0;
1146  // //  *-*-*-*-*-*-*-*-*-*-*-*-*    OrbitalInfoTrkVar *r = 0;
1147  // //    if(!sorted_tracks)return 0;  
1148  //     if(sorted_tracks.IsEmpty())return 0;    if (CAL2)
1149            c = GetCaloStoredTrack(t->GetSeqNo());
1150  //     PamTrack *image = 0;    if (TOF)
1151            o = GetToFStoredTrack(t->GetSeqNo());
1152  //     if( it >=0 && it < trk2_obj->TrkLevel2::GetNTracks() ){    if (ORB)
1153  //      TrkTrack *temp = (TrkTrack*)sorted_tracks.At(it);      r = GetOrbitalInfoStoredTrack(t->GetSeqNo());
 //      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;  
1154    
1155      //    if(t && c && o)track = new PamTrack(t,c,o);
1156      PamTrack *track = new PamTrack(t, c, o, r);
1157    
1158  //  *-*-*-*-*-*-*-*-*-*-*-*-*    return track;
     SortTracks("+CAL+TOF");  
 //  *-*-*-*-*-*-*-*-*-*-*-*-*  
     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;  
 }  
1159    
1160    }
1161    ;
1162  //--------------------------------------  //--------------------------------------
1163  //  //
1164  //  //
1165  //--------------------------------------  //--------------------------------------
1166  /**  /**
1167   * Get the Pamela detector trees in a single file and make them friends.   * Retrieves the it-th stored track.
1168   * @param f TFile pointer   * It override TrkLevel2::GetTrack(int it).
1169   * @param detlist String to select trees to be included   * @param itrk Track number, ranging from 0 to GetNTracks().
  * @return Pointer to a TTree  
1170   */   */
 TTree *PamLevel2::GetPamTree(TFile *f, TString detlist ){  
1171    
1172  //     if( !detlist.IsNull() ) SetWhichTrees(detlist);  PamTrack* PamLevel2::GetStoredTrack(Int_t itrk) {
 //     else                    GetWhichTrees(f);  
       
     cout << "TTree *PamLevel2::GetPamTree(TFile *f, TString detlist ) -- obsolte "<<endl;  
1173    
1174      SetWhichTrees(detlist);    cout << "PamLevel2::GetStoredTrack(Int_t itrk) **to-be-updated** " << endl;
1175      cout
1176          << "for the moment, better use separately the methods: TrkLevel2::GetStoredTrack(seqno) CaloLevel2::GetCaloTrkVar(Int_t notrack) ToFLevel2::GetToFTrkVar(Int_t notrack) OrbitalInfo::GetOrbitalInfoTrkVar(Int_t notrack)"
1177          << endl;
1178      cout << "(if you use it, remember to delete the PamTrack object)" << endl;
1179      PamTrack *track = 0;
1180    
1181      TTree *Trout =0;    if (itrk >= 0 && itrk < trk2_obj->TrkLevel2::ntrk()) {
1182    
1183      TString fname = f->GetName();      TrkTrack *t = trk2_obj->TrkLevel2::GetStoredTrack(itrk);
1184      if(!CheckLevel2File(fname))return NULL;      track = GetPamTrackAlong(t);
1185    
1186  //    UInt_t *found=0;        }
1187      else {
1188      cout<< "GetPamTree(TFile*,TString): detector list --> ";      cout << "PamLevel2::GetStoredTrack(int) : tracker track SeqNo " << itrk << " does not exist (GetNTracks() = "
1189      if(TRK1)cout<<"TRK1 ";          << trk2_obj->TrkLevel2::GetNTracks() << ")" << endl;
1190      if(TRK2)cout<<"TRK2 ";    };
1191      if(TRKh)cout<<"TRKH ";  
1192      if(CAL1)cout<<"CAL1 ";    return track;
     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;  
     if(SELLI)cout<<">>> Found selection-list <<<"<<endl;  
   
     f->cd();  
   
 // Tracker  
     TTree *T = (TTree*)f->Get("Tracker");  
     if(T && (TRK2||TRK1||TRKh)) {  
         if(TRK2)T->SetBranchAddress("TrkLevel2", GetPointerTo("TrkLevel2"));  
 //      else    T->SetBranchStatus("TrkLevel2",0,found);  
         if(TRK2)cout << "Tracker      : set branch address TrkLevel2"<<endl;  
         if(TRK1)T->SetBranchAddress("TrkLevel1", GetPointerTo("TrkLevel1"));  
 //      else    T->SetBranchStatus("TrkLevel1",0,found);  
         if(TRK1)cout << "Tracker      : set branch address TrkLevel1"<<endl;  
         if(TRKh)T->SetBranchAddress("TrkHough", GetPointerTo("TrkHough"));  
 //      else    T->SetBranchStatus("TrkHough",0,found);  
         if(TRKh)cout << "Tracker      : set branch address TrkHough"<<endl;  
         if(!Trout)Trout=T;  
         else Trout->AddFriend(T);  
     }else{  
         cout << "Tracker      : missing tree"<<endl;  
     };  
     // Calorimeter  
     TTree *C = (TTree*)f->Get("Calorimeter");  
     if(C && (CAL2||CAL1)) {  
         if(CAL2)C->SetBranchAddress("CaloLevel2", GetPointerTo("CaloLevel2"));  
 //      else    C->SetBranchStatus("CaloLevel2",0,found);  
         if(CAL2)cout << "Calorimeter  : set branch address CaloLevel2"<<endl;  
         if(CAL1)C->SetBranchAddress("CaloLevel1", GetPointerTo("CaloLevel1"));  
 //      else    C->SetBranchStatus("CaloLevel1",0,found);  
         if(CAL1)cout << "Calorimeter  : set branch address CaloLevel1"<<endl;  
         if(!Trout)Trout=C;  
         else Trout->AddFriend(C);  
     }else{  
         cout << "Calorimeter  : missing tree"<<endl;  
     };  
   
     // ToF      
     TTree *O = (TTree*)f->Get("ToF");  
     if(O && TOF) {  
         O->SetBranchAddress("ToFLevel2", GetPointerTo("ToFLevel2"));  
         cout << "ToF          : set branch address ToFLevel2"<<endl;  
         if(!Trout)Trout=O;  
         else Trout->AddFriend(O);  
     }else{  
         cout << "ToF         : missing tree"<<endl;  
     };  
     // Trigger  
     TTree *R = (TTree*)f->Get("Trigger");  
     if(R && TRG) {  
         R->SetBranchAddress("TrigLevel2", GetPointerTo("TrigLevel2"));  
         cout << "Trigger      : set branch address TrigLevel2"<<endl;  
         if(!Trout)Trout=O;  
         else Trout->AddFriend(R);  
     }else{  
         cout << "Trigger      : missing tree"<<endl;  
     };  
     // S4  
     TTree *S = (TTree*)f->Get("S4");  
     if(S && S4) {  
         S->SetBranchAddress("S4Level2", GetPointerTo("S4Level2"));  
         cout << "S4           : set branch address S4Level2"<<endl;  
         if(!Trout)Trout=O;  
         else Trout->AddFriend(S);  
     }else{  
         cout << "S4           : missing tree"<<endl;  
     };  
     // Neutron Detector  
     TTree *N = (TTree*)f->Get("NeutronD");  
     if(N && ND) {  
         N->SetBranchAddress("NDLevel2", GetPointerTo("NDLevel2"));  
         cout << "NeutronD     : set branch address NDLevel2"<<endl;  
         if(!Trout)Trout=O;  
         else Trout->AddFriend(N);  
     }else{  
         cout << "NeutronD     : missing tree"<<endl;  
     };  
     // Anticounters  
     TTree *A = (TTree*)f->Get("Anticounter");  
     if(A && AC) {  
         A->SetBranchAddress("AcLevel2", GetPointerTo("AcLevel2"));  
         cout << "Anticounter  : set branch address AcLevel2"<<endl;  
         if(!Trout)Trout=O;  
         else Trout->AddFriend(A);  
     }else{  
         cout << "Anticounter  : missing tree"<<endl;  
     };  
     // Orbital Info  
     TTree *B = (TTree*)f->Get("OrbitalInfo");  
     if(B && ORB) {  
         B->SetBranchAddress("OrbitalInfo", GetPointerTo("OrbitalInfo"));  
         cout << "OrbitalInfo  : set branch address OrbitalInfo"<<endl;  
         if(!Trout)Trout=O;  
         else Trout->AddFriend(B);  
     }else{  
         cout << "OrbitalInfo  : missing tree"<<endl;  
     };  
   
     TTree *L = (TTree*)f->Get("SelectionList");  
     if(L && SELLI==1) {  
 //      L->SetBranchAddress("RunEntry",&irun);  
 //      cout << "SelectionList: set branch address RunEntry"<<endl;  
 //      L->SetBranchAddress("EventEntry",&irunentry);  
 //      cout << "SelectionList: set branch address EventEntry"<<endl;  
 //      if(!Trout)Trout=O;  
 //      else Trout->AddFriend("SelectionList");  
         cout << " TTree *PamLevel2::GetPamTree(TFile, TString) >>> SelectionList not implemente!!!!"<<endl;  
         sel_tree = 0;  
     }else{  
         cout << "SelectionList  : missing tree"<<endl;  
     };  
       
     cout<<endl<<" Number of entries: "<<Trout->GetEntries()<<endl<<endl;  
       
     pam_tree = (TChain*)Trout;  
1193    
     return Trout;  
       
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   * Get list of Level2 files.   * 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    //--------------------------------------
1853    /**
1854     * Get the Pamela detector trees in a single file and make them friends.
1855     * @param f TFile pointer
1856     * @param detlist String to select trees to be included
1857     * @return Pointer to a TTree
1858     */
1859    TTree *PamLevel2::GetPamTree(TFile *f, TString detlist) {
1860    
1861      if (detlist.Contains("+AUTO", TString::kIgnoreCase)) {
1862        cout << "+AUTO" << endl;
1863        GetWhichTrees(f);
1864      };
1865      SetWhichTrees(detlist);
1866    
1867      if (pam_tree) {
1868        printf("WARNING: TTree *PamLevel2::GetPamTree(TFile *fl, TString detlist) -- pam_tree already exists!\n ");
1869        return pam_tree;
1870      };
1871      //
1872    
1873      cout << "TTree *PamLevel2::GetPamTree(TFile *f, TString detlist ) -- obsolte " << endl;
1874    
1875      //    SetWhichTrees(detlist);
1876    
1877      TTree *Trout = 0;
1878    
1879      TString fname = f->GetName();
1880      if (!CheckLevel2File(fname))
1881        return NULL;
1882    
1883      //    UInt_t *found=0;
1884    
1885      cout << "GetPamTree(TFile*,TString): detector list --> ";
1886      if (TRK1)
1887        cout << "TRK1 ";
1888      if (TRK2)
1889        cout << "TRK2 ";
1890      if (TRKh)
1891        cout << "TRKH ";
1892      if (CAL1)
1893        cout << "CAL1 ";
1894      if (CAL2)
1895        cout << "CAL2 ";
1896      if (TOF)
1897        cout << "TOF ";
1898      if (TRG)
1899        cout << "TRG ";
1900      if (AC)
1901        cout << "AC ";
1902      if (ND)
1903        cout << "ND ";
1904      if (S4)
1905        cout << "S4 ";
1906      if (ORB)
1907        cout << "ORB ";
1908      if (GP)
1909        cout << "GP ";
1910      cout << endl;
1911      if (SELLI && SELLI != 2)
1912        cout << ">>> Found selection-list <<<" << endl; //EMILIANO
1913    
1914      f->cd();
1915    
1916      // Tracker
1917      TTree *T = (TTree*) f->Get("Tracker");
1918      if (T && (TRK2 || TRK1 || TRKh)) {
1919        if (TRK2)
1920          T->SetBranchAddress("TrkLevel2", GetPointerTo("TrkLevel2"));
1921        //  else    T->SetBranchStatus("TrkLevel2",0,found);
1922        if (TRK2)
1923          cout << "Tracker      : set branch address TrkLevel2" << endl;
1924        if (TRK1)
1925          T->SetBranchAddress("TrkLevel1", GetPointerTo("TrkLevel1"));
1926        //  else    T->SetBranchStatus("TrkLevel1",0,found);
1927        if (TRK1)
1928          cout << "Tracker      : set branch address TrkLevel1" << endl;
1929        if (TRKh)
1930          T->SetBranchAddress("TrkHough", GetPointerTo("TrkHough"));
1931        //  else    T->SetBranchStatus("TrkHough",0,found);
1932        if (TRKh)
1933          cout << "Tracker      : set branch address TrkHough" << endl;
1934        if (!Trout)
1935          Trout = T;
1936        else
1937          Trout->AddFriend(T);
1938      }
1939      else {
1940        cout << "Tracker      : missing tree" << endl;
1941      };
1942      // Calorimeter
1943      TTree *C = (TTree*) f->Get("Calorimeter");
1944      if (C && (CAL2 || CAL1)) {
1945        if (CAL2)
1946          C->SetBranchAddress("CaloLevel2", GetPointerTo("CaloLevel2"));
1947        //  else    C->SetBranchStatus("CaloLevel2",0,found);
1948        if (CAL2)
1949          cout << "Calorimeter  : set branch address CaloLevel2" << endl;
1950        if (CAL1)
1951          C->SetBranchAddress("CaloLevel1", GetPointerTo("CaloLevel1"));
1952        //  else    C->SetBranchStatus("CaloLevel1",0,found);
1953        if (CAL1)
1954          cout << "Calorimeter  : set branch address CaloLevel1" << endl;
1955        if (!Trout)
1956          Trout = C;
1957        else
1958          Trout->AddFriend(C);
1959      }
1960      else {
1961        cout << "Calorimeter  : missing tree" << endl;
1962      };
1963    
1964      // ToF
1965      TTree *O = (TTree*) f->Get("ToF");
1966      if (O && TOF) {
1967        O->SetBranchAddress("ToFLevel2", GetPointerTo("ToFLevel2"));
1968        cout << "ToF          : set branch address ToFLevel2" << endl;
1969        if (!Trout)
1970          Trout = O;
1971        else
1972          Trout->AddFriend(O);
1973      }
1974      else {
1975        cout << "ToF         : missing tree" << endl;
1976      };
1977      // Trigger
1978      TTree *R = (TTree*) f->Get("Trigger");
1979      if (R && TRG) {
1980        R->SetBranchAddress("TrigLevel2", GetPointerTo("TrigLevel2"));
1981        cout << "Trigger      : set branch address TrigLevel2" << endl;
1982        if (!Trout)
1983          Trout = R;
1984        else
1985          Trout->AddFriend(R);
1986      }
1987      else {
1988        cout << "Trigger      : missing tree" << endl;
1989      };
1990      // S4
1991      TTree *S = (TTree*) f->Get("S4");
1992      if (S && S4) {
1993        S->SetBranchAddress("S4Level2", GetPointerTo("S4Level2"));
1994        cout << "S4           : set branch address S4Level2" << endl;
1995        if (!Trout)
1996          Trout = S;
1997        else
1998          Trout->AddFriend(S);
1999      }
2000      else {
2001        cout << "S4           : missing tree" << endl;
2002      };
2003      // Neutron Detector
2004      TTree *N = (TTree*) f->Get("NeutronD");
2005      if (N && ND) {
2006        N->SetBranchAddress("NDLevel2", GetPointerTo("NDLevel2"));
2007        cout << "NeutronD     : set branch address NDLevel2" << endl;
2008        if (!Trout)
2009          Trout = N;
2010        else
2011          Trout->AddFriend(N);
2012      }
2013      else {
2014        cout << "NeutronD     : missing tree" << endl;
2015      };
2016      // Anticounters
2017      TTree *A = (TTree*) f->Get("Anticounter");
2018      if (A && AC) {
2019        A->SetBranchAddress("AcLevel2", GetPointerTo("AcLevel2"));
2020        cout << "Anticounter  : set branch address AcLevel2" << endl;
2021        if (!Trout)
2022          Trout = A;
2023        else
2024          Trout->AddFriend(A);
2025      }
2026      else {
2027        cout << "Anticounter  : missing tree" << endl;
2028      };
2029      // Orbital Info
2030      TTree *B = (TTree*) f->Get("OrbitalInfo");
2031      if (B && ORB) {
2032        B->SetBranchAddress("OrbitalInfo", GetPointerTo("OrbitalInfo"));
2033        cout << "OrbitalInfo  : set branch address OrbitalInfo" << endl;
2034        if (!Trout)
2035          Trout = B;
2036        else
2037          Trout->AddFriend(B);
2038      }
2039      else {
2040        cout << "OrbitalInfo  : missing tree" << endl;
2041      };
2042    
2043      // GPamela
2044      TTree *G = (TTree*) f->Get("h20");
2045      if (G && GP) {
2046        if (!gp_obj)
2047          gp_obj = new GPamela();
2048        //      ------------------------------------
2049        //      ATTENZIONE!!!
2050        //      non so per quale arcano motivo,
2051        //      per l'albero di gpamela il branch address lo devo settare
2052        //      DOPO aver fatto friend
2053        //      FGRRRVZZZZUTSALKJMSLKJ!!!
2054        //      ------------------------------------
2055        //  gp_obj->SetBranchAddress(G); //ho dovuto fare in maniera diversa dagli altri
2056        //  cout << "h20          : set branch address GPamela "<<endl;
2057        if (!Trout)
2058          Trout = G;
2059        else
2060          Trout->AddFriend(G);
2061      }
2062      else {
2063        //  cout << "h20          : missing tree"<<endl;
2064      };
2065    
2066      TTree *L = (TTree*) f->Get("SelectionList");
2067      if (L && SELLI == 1) {
2068        cout << " TTree *PamLevel2::GetPamTree(TFile, TString) >>> SelectionList not implemented!!!!" << endl;
2069        sel_tree = 0;
2070      }
2071      else {
2072        cout << "SelectionList  : missing tree" << endl;
2073      };
2074    
2075      cout << endl << " Number of entries: " << Trout->GetEntries() << endl << endl;
2076    
2077      //      ------------------------------------
2078      //      ATTENZIONE!!!
2079      //      non so per quale arcano motivo,
2080      //      per l'albero di gpamela il branch address lo devo settare
2081      //      DOPO aver fatto friend
2082      //      FGRRRVZZZZUTSALKJMSLKJ!!!
2083      //      ------------------------------------
2084      if (G && GP) {
2085        gp_obj->SetBranchAddress(Trout); //ho dovuto fare in maniera diversa dagli altri
2086        cout << "h20          : set branch address GPamela " << endl;
2087      }
2088      else {
2089        cout << "h20          : missing tree" << endl;
2090      };
2091    
2092      pam_tree = (TChain*) Trout;
2093    
2094      return Trout;
2095    
2096    }
2097    //--------------------------------------
2098    //
2099    //
2100    //--------------------------------------
2101    /**
2102     * Get list of Level2 files.
2103   * @param ddir Level2 data directory.   * @param ddir Level2 data directory.
2104   * @param flisttxt Name of txt file containing file list.   * @param flisttxt Name of txt file containing file list.
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 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    
2132        if ( !flisttxt.EndsWith(".root") ){        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 1283  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 1449  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      run_tree = R;    }
2742      else {
2743        delete R;
2744        R = 0;
2745      }
2746    
2747      run_tree = R;
2748    
2749      return R;
2750    
     return R;  
       
2751  }  }
2752  //--------------------------------------  //--------------------------------------
2753  //  //
# Line 1489  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, ULong64_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->GetEntries() <= 0 ) return(false);    if (run_tree->GetEntries() <= 0) {
2794    //      cout << " Bool_t PamLevel2::UpdateRunInfo(ULong64_t iev) -- ERROR -- run tree is empty" << endl;
2795          return (false);
2796    Int_t oldrun = irun;    }
2797    // --------------------------------------  
2798    
2799      Int_t oldrun = irun; // store current run index
2800    
2801      // -----------------------------------------------------------------------
2802      // the first time the routine is called, set run search from the beginning
2803      // -----------------------------------------------------------------------
2804    
2805      if (irun < 0) {
2806        irun = 0LL;
2807        irunt = 0LL;
2808        totrunentry = 0LL;
2809        totrunentrymin = 0LL;
2810        totrunentrymax = 0LL;
2811        irunentry = 0LL;
2812        il0entry = 0LL;
2813        prevshift = 0;
2814        yprevshift = 0;
2815        prevabstime = 0;
2816        prevpktnum = 0;
2817        abstime = 0ULL;
2818        pktnum = 0;
2819        isFragment = false;
2820        run_tree->GetEntry(irun);
2821        if (!GetOrbitalInfo())
2822          cout << "** WARNING ** missing OrbitalInfo ---> run info might be not correctly updated " << endl;
2823        if (gltsync)
2824          delete gltsync; //Emiliano
2825        if (!dbc || (dbc && !dbc->IsConnected()))
2826          SetDBConnection(); //Emiliano
2827        gltsync = new GL_TIMESYNC(GetRunInfo()->ID_ROOT_L0, "ID", dbc, false); //Emiliano // the "false" means not to use level0 file (not necessary here)
2828        if (dbc){
2829          dbc->Close();// Emiliano
2830          delete dbc;
2831          dbc=0;
2832        };
2833      };
2834      // ---------------------------------------------------------------
2835      // retrieve OBT and absolute time of the event
2836      // ---------------------------------------------------------------
2837      Long64_t obt = 0LL; // Emiliano, Long64_t GL_TIMESYNC::DBobt(UInt_t obt) since depending on the situation OBT is lowered or boosted
2838      prevabstime = abstime;
2839      prevpktnum = pktnum;
2840      if (GetOrbitalInfo()) {
2841        abstime = GetOrbitalInfo()->absTime;
2842        obt = gltsync->DBobt(GetOrbitalInfo()->OBT); // Emiliano
2843        pktnum = GetOrbitalInfo()->pkt_num; // Emiliano
2844      }
2845      else {
2846        abstime = GetRunInfo()->RUNHEADER_TIME;
2847        obt = gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT); // Emiliano
2848        pktnum = GetRunInfo()->RUNHEADER_PKT; // Emiliano
2849      }
2850    
2851      if (DBG){
2852        printf("0abstime %lld %lld pktnum %d %d obt %lld \n",abstime,prevabstime,pktnum,prevpktnum,obt);
2853        printf("0        rth %d %d nevents %d  \n",GetRunInfo()->RUNHEADER_TIME,GetRunInfo()->RUNTRAILER_TIME,GetRunInfo()->NEVENTS);
2854        printf("0        rto %d %d \n",GetRunInfo()->RUNHEADER_OBT,GetRunInfo()->RUNTRAILER_OBT);
2855        printf("0        rto2 %lld %lld \n",gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT),gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT));
2856        printf("0        bo irunentry %lld prevshift %lld irun %lld  \n",irunentry,prevshift,irun);
2857        printf("0        min %lld iev %lld max %lld tot %lld \n",totrunentrymin,iev,totrunentrymax,totrunentry);
2858      }
2859    
2860      // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
2861    // if it is a full file (not preselected)    // if it is a full file (not preselected)
2862    // --------------------------------------    // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
2863    if(SELLI==0){    if (SELLI == 0 || SELLI == 2) { // Emiliano
2864        if ( irun < 0 ){  
2865            irun = 0;      // ---------------------------------------------------------------
2866            run->GetEntry(0);      // increment dead and live-time counters
2867            runfirstentry = 0ULL;      // (only when reading a file not preselected)
2868            runlastentry += (ULong64_t)(this->GetRunInfo()->NEVENTS) - 1ULL;      // ---------------------------------------------------------------
2869        };            if (SELLI == 0) {
2870          if (GetTrigLevel2()) {
2871        if( !GetOrbitalInfo() ){          totdltime[0] += GetTrigLevel2()->dltime[0];
2872            cout << "Bool_t PamLevel2::UpdateRunInfo(TChain *run, ULong64_t iev) -- ERROR -- missing OrbitalInfo "<<endl;          totdltime[1] += GetTrigLevel2()->dltime[1];
2873            return(false);        }
2874        }        totdltime[2]++;
2875        // modificato il controllo sull'aggiornamento del run, per evitare problemi      }
2876        // dovuti agli eventi annidati (NB! NEVENTS conta anche questi!!)  
2877        while ( GetOrbitalInfo()->absTime > GetRunInfo()->RUNTRAILER_TIME && irun < run->GetEntries() ){      //
2878  //      while ( iev > (runfirstentry+(ULong64_t)(this->GetRunInfo()->NEVENTS-1)) && irun < run->GetEntries() ){      if ( iev < totrunentrymin || iev > totrunentrymax // entry is outside run limits
2879            //    printf(" iev %llu %u %llu \n",iev,this->GetRunInfo()->NEVENTS,(ULong64_t)(runfirstentry+(ULong64_t)(this->GetRunInfo()->NEVENTS)));           || iev == 0 // or it is the first entry
2880            irun++;           || (!isSync && (
2881            run->GetEntry(irun);                           (abstime <= GetRunInfo()->RUNHEADER_TIME && obt < gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT) ) // or it is outside obt limits (and abstime limits for security reasons)
2882            runfirstentry = runlastentry+1ULL;                           || (abstime >= GetRunInfo()->RUNTRAILER_TIME && obt > gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT) ) ))// or it is outside obt limits (and abstime limits for security reasons)
2883            runlastentry += (ULong64_t)(this->GetRunInfo()->NEVENTS);           ){ // check on abstime and obt needed to handle nested+DV_skipped packets
       };  
2884                
2885        //        // check for a new run (ma prima il primo!)
2886        if ( irun == oldrun || irun >= run->GetEntries() ) return(false);        if (DBG){
2887        //          printf("1abstime %lld %lld pktnum %d %d obt %lld \n",abstime,prevabstime,pktnum,prevpktnum,obt);
2888        //  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        rth %d %d nevents %d  \n",GetRunInfo()->RUNHEADER_TIME,GetRunInfo()->RUNTRAILER_TIME,GetRunInfo()->NEVENTS);
2889        //          printf("1        rto %d %d \n",GetRunInfo()->RUNHEADER_OBT,GetRunInfo()->RUNTRAILER_OBT);
2890        return(true);              printf("1        rto2 %lld %lld \n",gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT),gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT));
2891    };          printf("1        bo irunentry %lld prevshift %lld irun %lld  \n",irunentry,prevshift,irun);
2892    // ----------------------------------------------------          printf("1        min %lld iev %lld max %lld tot %lld \n",totrunentrymin,iev,totrunentrymax,totrunentry);
2893          }
2894          //        printf("1abstime %lld %lld pktnum %d %d obt %lld \n",abstime,prevabstime,pktnum,prevpktnum,obt);
2895          //        printf("1        rth %d %d nevents %d  \n",GetRunInfo()->RUNHEADER_TIME,GetRunInfo()->RUNTRAILER_TIME,GetRunInfo()->NEVENTS);
2896          //        printf("1        rto %d %d \n",GetRunInfo()->RUNHEADER_OBT,GetRunInfo()->RUNTRAILER_OBT);
2897          //        printf("1        rto2 %lld %lld \n",gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT),gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT));
2898          //        printf("1        bo irunentry %lld prevshift %lld irun %lld  \n",irunentry,prevshift,irun);
2899          //        printf("1        min %lld iev %lld max %lld tot %lld \n",totrunentrymin,iev,totrunentrymax,totrunentry);//TOGLITOGLI
2900    
2901          totrunentry = 0LL;
2902          runfirstentry = 0LL;
2903          for (Int_t r=0; r< run_tree->GetEntries();r++){
2904            // -------------------------------------------------------------------
2905            // save the index of the first entry of the run, relative to pam_tree,
2906            // and read a new run
2907            // -------------------------------------------------------------------
2908            run_tree->GetEntry(r);//update runinfo
2909            if ( r > 0 ){
2910              totrunentrymin = totrunentrymax+1;
2911            } else {
2912              totrunentrymin = 0LL;
2913            }
2914            totrunentry += GetRunInfo()->NEVENTS;
2915            totrunentrymax = totrunentry - 1 - prevshift; // prevshift is needed to handle nested+DV_skipped packets
2916            irun = r;        
2917    
2918            if ( (iev >= totrunentrymin && iev <= totrunentrymax) || // entry is inside run limits
2919                 ( !isSync &&
2920                   ( abstime >= GetRunInfo()->RUNHEADER_TIME  && obt >= gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT) // or it is inside obt limits (and abstime limits for security reasons)
2921                     && abstime <= GetRunInfo()->RUNTRAILER_TIME && obt <= gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT)))  // or it is inside obt limits (and abstime limits for security reasons)
2922                 ){ // check on abstime and obt needed to handle nested+DV_skipped packets
2923              if ( totrunentrymin > iev ){ // there is a shift (nested+DV_skipped packets)
2924                if ( !isSync ){
2925                  if (DBG) printf("PamLevel2::UpdateRunInfo(Long64_t) - unconsistent iev - nevents, probable DBL0-L2 async\n");
2926                  if (DBG) printf("PamLevel2::UpdateRunInfo(Long64_t) - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);
2927                  //              printf("PamLevel2::UpdateRunInfo(Long64_t) - unconsistent iev - nevents, probable DBL0-L2 async\n");
2928                  //              printf("PamLevel2::UpdateRunInfo(Long64_t) - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);//TOGLITOGLI
2929                  prevshift += (totrunentrymin-iev); // add the new shift to total shift
2930                  totrunentrymin -= (totrunentrymin-iev); // shift run position min
2931                  totrunentrymax -= (totrunentrymin-iev); // shift run position max
2932                  if (DBG) printf("PamLevel2::UpdateRunInfo(Long64_t) - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);
2933                  //              printf("PamLevel2::UpdateRunInfo(Long64_t) - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);//TOGLITOGLI
2934                } else {
2935                  printf(" PamLevel2::UpdateRunInfo(Long64_t) ERROR! sync file but unconsistent totrunetrymin %lld and iev %lld!!! \n",totrunentrymin,iev);
2936                  cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
2937                  cout << "\nFor bug reporting instructions, please see for example:\n";
2938                  cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
2939                  cout << "  " << endl;
2940                }
2941              }
2942              runfirstentry = totrunentrymin; // first entry of the run in the level2
2943              
2944    
2945              //
2946              if (gltsync)
2947                delete gltsync; // Emiliano
2948              if (!dbc || (dbc && !dbc->IsConnected()))
2949                SetDBConnection(); //Emiliano
2950              gltsync = new GL_TIMESYNC(GetRunInfo()->ID_ROOT_L0, "ID", dbc, false); // Emiliano
2951              TrkParams::Set(GetRunInfo(), dbc);
2952              if (dbc){
2953                dbc->Close(); // Emiliano
2954                delete dbc;
2955                dbc=0;
2956              }          
2957              if (gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT) > gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT)) { // Emiliano
2958                cout << "Bool_t PamLevel2::UpdateRunInfo(Long64_t iev) -- WARNING -- irun " << irun
2959                     << "  has RUNHEADER_OBT>=RUNTRAILER_OBT " << endl;
2960                cout
2961                  << "                                                            (NB!! in this case some events could be assigned to a wrong run)"
2962                  << endl;
2963              }
2964              //
2965              if (DBG) printf(" found \n");
2966              //          printf(" found \n");//TOGLITOGLI
2967              //
2968              break;
2969            }
2970          } // loop over run
2971          
2972          // --------------------------------------
2973          // if there was no need to update the run
2974          // ---> exit with FALSE
2975          // --------------------------------------
2976          if (irun == oldrun){
2977            if (DBG) printf(" no new run \n");
2978            //        printf(" no new run \n");//TOGLITOGLI
2979            return (false);
2980          }      
2981          // --------------------------------------
2982          // ... otherwise
2983          // ---> exit with TRUE
2984          // --------------------------------------
2985    
2986          if (SELLI != 2) {
2987            /// decrement counters since this event belongs to a new run
2988            if (GetTrigLevel2()) {
2989              totdltime[0] -= GetTrigLevel2()->dltime[0];//live-time
2990              totdltime[1] -= GetTrigLevel2()->dltime[1];//dead-time
2991            }
2992            totdltime[2]--; //event counter
2993            if (DBG) {
2994              cout << endl;
2995              cout << "n.events     : " << totdltime[2] << endl;
2996              cout << "RUN LIVE-TIME: " << totdltime[0] * 0.16 << " ms" << endl;
2997              cout << "RUN DEAD-TIME: " << totdltime[1] * 0.01 << " ms" << endl;
2998            }
2999            // add an entry
3000            if (run_tree_clone && totdltime[2] > 0)
3001              if (run_tree_clone->GetBranch("DeadLiveTime")->GetEntries() < run_tree->GetEntries())
3002                run_tree_clone->GetBranch("DeadLiveTime")->Fill();
3003            // reset counters
3004            if ( totdltime[2] > 0 ){
3005              if (GetTrigLevel2()) {
3006                totdltime[0] = GetTrigLevel2()->dltime[0];//live-time
3007                totdltime[1] = 0; //dead-time
3008              }
3009              totdltime[2] = 1; //event counter
3010            }
3011          }
3012    
3013          if (DBG){
3014            cout << endl << " ))))) UPDATE RUN INFO (((((  @iev " << iev << " run " << GetRunInfo()->ID << " irun " << irun
3015                 << endl;        
3016            printf("2abstime %lld %lld pktnum %d %d obt %lld \n",abstime,prevabstime,pktnum,prevpktnum,obt);
3017            printf("2        rth %d %d nevents %d  \n",GetRunInfo()->RUNHEADER_TIME,GetRunInfo()->RUNTRAILER_TIME,GetRunInfo()->NEVENTS);
3018            printf("2        rto %d %d \n",GetRunInfo()->RUNHEADER_OBT,GetRunInfo()->RUNTRAILER_OBT);
3019            printf("2        rto2 %lld %lld \n",gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT),gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT));
3020            printf("2        bo irunentry %lld prevshift %lld irun %lld  \n",irunentry,prevshift,irun);
3021            printf("2        min %lld iev %lld max %lld tot %lld \n",totrunentrymin,iev,totrunentrymax,totrunentry);
3022          }
3023          //        printf("2abstime %lld %lld pktnum %d %d obt %lld \n",abstime,prevabstime,pktnum,prevpktnum,obt);
3024          //        printf("2        rth %d %d nevents %d  \n",GetRunInfo()->RUNHEADER_TIME,GetRunInfo()->RUNTRAILER_TIME,GetRunInfo()->NEVENTS);
3025          //        printf("2        rto %d %d \n",GetRunInfo()->RUNHEADER_OBT,GetRunInfo()->RUNTRAILER_OBT);
3026          //        printf("2        rto2 %lld %lld \n",gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT),gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT));
3027          //        printf("2        bo irunentry %lld prevshift %lld irun %lld  \n",irunentry,prevshift,irun);
3028          //        printf("2        min %lld iev %lld max %lld tot %lld \n",totrunentrymin,iev,totrunentrymax,totrunentry);//TOGLITOGLI
3029    
3030          return (true);
3031        } // need for run upgrade
3032        if (DBG) printf("return false\n");
3033        return (false);
3034      }// SELLI = 0 SELLI = 2
3035      
3036      // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
3037    // if it is a preselected file (there is SelectionList)    // if it is a preselected file (there is SelectionList)
3038    // NBNB - the event tree MUST be read first    // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
3039    // ----------------------------------------------------    // irun  = run entry relative to the chain
3040    if(SELLI==1){          // irunt = run entry relative to the tree
3041        sel_tree->GetEntry(iev);    if (SELLI == 1) {
3042        if(irun != oldrun){      sel_tree->GetEntry(iev);// read irunt from SelectionList
3043            run->GetEntry(irun);      irun = irunt + irunoffset[sel_tree->GetTreeNumber()];//NEWNEW
3044            return true;      if (irun != oldrun) {
3045          if (irun < run_tree->GetEntries())
3046            run_tree->GetEntry(irun);
3047          // check if the time is ok (with merged files it is not...)
3048          // if not loop over run and look for the proper entry
3049          bool SECONDO_GIRO = false;
3050          //            Long64_t irun_start   = irun;
3051          int offset_start = irunoffset[sel_tree->GetTreeNumber()];
3052          while (((!(abstime >= GetRunInfo()->RUNHEADER_TIME && // check on absolute time (s)
3053              abstime <= GetRunInfo()->RUNTRAILER_TIME)
3054          //                        ||
3055          //                        !(obt >= GetRunInfo()->RUNHEADER_OBT &&         // additional check on OBT (ms)
3056          //                          obt <= GetRunInfo()->RUNTRAILER_OBT)
3057          ) || GetRunInfo()->NEVENTS == 0)
3058          //                && irun < run_tree->GetEntries()
3059          ) {
3060    
3061            if (DBG) {
3062              cout << " (test) ";
3063              cout << " tree " << sel_tree->GetTreeNumber();
3064              cout << " irunt " << irunt;
3065              cout << " offset " << irunoffset[sel_tree->GetTreeNumber()];
3066              cout << " abs " << abstime;
3067              cout << " >> " << GetRunInfo()->RUNHEADER_TIME << " " << GetRunInfo()->RUNTRAILER_TIME;
3068              cout << " obt " << obt;
3069              cout << " >> " << GetRunInfo()->RUNHEADER_OBT << " " << GetRunInfo()->RUNTRAILER_OBT;
3070              cout << " *** JUMP RUN *** irun " << irun;
3071              cout << endl;
3072            }
3073            //              irun++;
3074            irunoffset[sel_tree->GetTreeNumber()]++;
3075            irun = irunt + irunoffset[sel_tree->GetTreeNumber()];//NEWNEW
3076            if (irun == run_tree->GetEntries() && SECONDO_GIRO) {
3077              //            if(irun == irun_start ){
3078              cout << " ...grrrvzzkhhhajsdkj!!!! " << endl;
3079              irunoffset[sel_tree->GetTreeNumber()] = offset_start;
3080              return false;
3081            }
3082            if (irun >= run_tree->GetEntries() || irun < 0) {
3083              cout << "irun = " << irun << " >>  search from the beginning... <<" << endl;
3084              SECONDO_GIRO = true;
3085              irun = 0;
3086              irunoffset[sel_tree->GetTreeNumber()] = -irunt;
3087            }
3088            run_tree->GetEntry(irun);
3089        }        }
3090        return false;  
3091          if (DBG) {
3092            cout << " (test) ";
3093            cout << " tree " << sel_tree->GetTreeNumber();
3094            cout << " irunt " << irunt;
3095            cout << " offset " << irunoffset[sel_tree->GetTreeNumber()];
3096            cout << " abs " << abstime;
3097            cout << " >> " << GetRunInfo()->RUNHEADER_TIME << " " << GetRunInfo()->RUNTRAILER_TIME;
3098            cout << " obt " << obt;
3099            cout << " >> " << GetRunInfo()->RUNHEADER_OBT << " " << GetRunInfo()->RUNTRAILER_OBT;
3100          }
3101          if (DBG)
3102            cout << endl;
3103          if (DBG)
3104            cout << endl << " ))))) UPDATE RUN INFO (((((  @iev " << iev << " run " << GetRunInfo()->ID << " (run-entry "
3105                << irun << ")" << endl;
3106          // ----------------------------------------------------
3107          // update the tracker parameters
3108          // (non ho trovato nessun altro modo sicuro di farlo...)
3109          // ----------------------------------------------------
3110          if (!dbc || (dbc && !dbc->IsConnected()))
3111            SetDBConnection();
3112          TrkParams::Set(GetRunInfo(), dbc);
3113          if (dbc){
3114            dbc->Close();
3115            delete dbc;
3116            dbc=0;
3117          };
3118          //            cout << endl;
3119          prevshift = 0;
3120          yprevshift = 0;
3121          return true;
3122        }
3123        return false;
3124    }    }
3125    
3126    return false;    return false;
3127    //    //
3128  };  }
3129    
3130  /**  /**
3131   * 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)
3132   * @param run Pointer to the chain/tree which contains run infos   * @param run Pointer to the chain/tree which contains run infos
3133   * @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
3134   */   */
3135  Bool_t PamLevel2::UpdateRunInfo(TTree *run, ULong64_t iev){  Bool_t PamLevel2::UpdateRunInfo(TChain *run, Long64_t iev) {
3136    return(UpdateRunInfo((TChain*)run,iev));    return (UpdateRunInfo(iev));
3137  };  }
3138    
3139    /**
3140     * Update the runinfo informations (to be used to have Run infos event by event basis)
3141     * @param run Pointer to the chain/tree which contains run infos
3142     * @return true if a new run has been read, false if it is still the same run
3143     */
3144    Bool_t PamLevel2::UpdateRunInfo(TTree *run, Long64_t iev) {
3145      return (UpdateRunInfo((TChain*) run, iev));
3146    }
3147    
3148    
3149    //--------------------------------------
3150    //
3151    //
3152    //--------------------------------------
3153    /**
3154     * Set which trees shoul be analysed
3155     * @param detlist TString containing the sequence of trees required
3156     */
3157    void PamLevel2::SetWhichTrees(TString detlist) {
3158    
3159      //    if(detlist.IsNull() || detlist.Contains("+ALL", TString::kIgnoreCase)){
3160      if (detlist.Contains("+ALL", TString::kIgnoreCase)) {
3161    
3162        cout << " ======================================================== " << endl;
3163        cout << "                       (( WARNING ))                      " << endl;
3164        cout << " The meaning of the option +ALL has changed!!             " << endl;
3165        cout << " Now it includes really all (level0+level1+level2+gpamela)" << endl;
3166        cout << " and the file is discarded if it does not contain         " << endl;
3167        cout << " all trees or  if level0 files are not available!!        " << endl;
3168        cout << " ======================================================== " << endl;
3169    
3170        CAL0 = true;
3171        CAL1 = true;
3172        CAL2 = true;
3173        TRK2 = true;
3174        TRK1 = true;
3175        TRKh = true;
3176        TRK0 = true;
3177        TRG = true;
3178        TOF = true;
3179        TOF0 = true;
3180        S4 = true;
3181        ND = true;
3182        AC = true;
3183        ORB = true;
3184        GP = true;
3185      }
3186      else if (detlist.Contains("-ALL", TString::kIgnoreCase)) {
3187        CAL0 = false;
3188        CAL1 = false;
3189        CAL2 = false;
3190        TRK2 = false;
3191        TRK1 = false;
3192        TRKh = false;
3193        TRK0 = false;
3194        TRG = false;
3195        TOF = false;
3196        TOF0 = false;
3197        S4 = false;
3198        ND = false;
3199        AC = false;
3200        ORB = false;
3201        GP = false;
3202      };
3203    
3204      //  -------------------------------------------------------------------------
3205      if (detlist.Contains("CAL1", TString::kIgnoreCase)) {
3206        if (detlist.Contains("-CAL1", TString::kIgnoreCase))
3207          CAL1 = false;
3208        if (detlist.Contains("+CAL1", TString::kIgnoreCase))
3209          CAL1 = true;
3210      };
3211    
3212      if (detlist.Contains("CAL0", TString::kIgnoreCase)) {
3213        if (detlist.Contains("-CAL0", TString::kIgnoreCase))
3214          CAL0 = false;
3215        if (detlist.Contains("+CAL0", TString::kIgnoreCase))
3216          CAL0 = true;
3217      };
3218    
3219      if (detlist.Contains("CAL2", TString::kIgnoreCase)) {
3220        if (detlist.Contains("-CAL2", TString::kIgnoreCase))
3221          CAL2 = false;
3222        if (detlist.Contains("+CAL2", TString::kIgnoreCase))
3223          CAL2 = true;
3224      };
3225    
3226      if (detlist.Contains("+CAL", TString::kIgnoreCase) && !CAL1 && !CAL2)
3227        CAL2 = true;
3228      if (detlist.Contains("-CAL", TString::kIgnoreCase) && CAL1 && CAL2) {
3229        CAL2 = false;
3230        CAL1 = false;
3231      }
3232      //  -------------------------------------------------------------------------
3233      if (detlist.Contains("TRK0", TString::kIgnoreCase)) {
3234        if (detlist.Contains("-TRK0", TString::kIgnoreCase))
3235          TRK0 = false;
3236        if (detlist.Contains("+TRK0", TString::kIgnoreCase))
3237          TRK0 = true;
3238      };
3239    
3240      if (detlist.Contains("TRK1", TString::kIgnoreCase)) {
3241        if (detlist.Contains("-TRK1", TString::kIgnoreCase))
3242          TRK1 = false;
3243        if (detlist.Contains("+TRK1", TString::kIgnoreCase))
3244          TRK1 = true;
3245      };
3246    
3247      if (detlist.Contains("TRK2", TString::kIgnoreCase)) {
3248        if (detlist.Contains("-TRK2", TString::kIgnoreCase))
3249          TRK2 = false;
3250        if (detlist.Contains("+TRK2", TString::kIgnoreCase))
3251          TRK2 = true;
3252      };
3253    
3254      if (detlist.Contains("TRKh", TString::kIgnoreCase)) {
3255        if (detlist.Contains("-TRKh", TString::kIgnoreCase))
3256          TRKh = false;
3257        if (detlist.Contains("+TRKh", TString::kIgnoreCase))
3258          TRKh = true;
3259      };
3260    
3261      if (detlist.Contains("+TRK", TString::kIgnoreCase) && !TRK1 && !TRK2 && !TRKh)
3262        TRK2 = true;
3263      if (detlist.Contains("-TRK", TString::kIgnoreCase) && TRK1 && TRK2 && TRKh) {
3264        TRK2 = false;
3265        TRK1 = false;
3266        TRKh = false;
3267      }
3268      //  -------------------------------------------------------------------------
3269    
3270  //--------------------------------------    if (detlist.Contains("-TRG", TString::kIgnoreCase))
3271  //      TRG = false;
3272  //    else if (detlist.Contains("+TRG", TString::kIgnoreCase))
3273  //--------------------------------------      TRG = true;
3274  /**  
3275   * Set which trees shoul be analysed    if (detlist.Contains("-TOF", TString::kIgnoreCase))
3276   * @param detlist TString containing the sequence of trees required      TOF = false;
3277  */    else if (detlist.Contains("+TOF", TString::kIgnoreCase))
3278  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;  
3279    
3280      if( detlist.Contains("-TOF0", TString::kIgnoreCase) )TOF0 = false;    if (detlist.Contains("-TOF0", TString::kIgnoreCase))
3281      else if( detlist.Contains("+TOF0", TString::kIgnoreCase) )TOF0 = true;      TOF0 = false;
3282          else if (detlist.Contains("+TOF0", TString::kIgnoreCase))
3283      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;  
3284    
3285  //     cout<< "Set detector list --> ";    if (detlist.Contains("-S4", TString::kIgnoreCase))
3286  //     if(TRK1)cout<<"TRK1 ";      S4 = false;
3287  //     if(TRK2)cout<<"TRK2 ";    else if (detlist.Contains("+S4", TString::kIgnoreCase))
3288  //     if(TRKh)cout<<"TRKH ";      S4 = true;
3289  //     if(CAL1)cout<<"CAL1 ";  
3290  //     if(CAL2)cout<<"CAL2 ";    if (detlist.Contains("-ND", TString::kIgnoreCase))
3291  //     if(TOF)cout<<"TOF ";      ND = false;
3292  //     if(TRG)cout<<"TRG ";    else if (detlist.Contains("+ND", TString::kIgnoreCase))
3293  //     if(AC)cout<<"AC ";      ND = true;
3294  //     if(ND)cout<<"ND ";  
3295  //     if(S4)cout<<"S4 ";    if (detlist.Contains("-AC", TString::kIgnoreCase))
3296  //     if(ORB)cout<<"ORB ";      AC = false;
3297  //     cout << endl;    else if (detlist.Contains("+AC", TString::kIgnoreCase))
3298            AC = true;
3299  };  
3300      if (detlist.Contains("-ORB", TString::kIgnoreCase))
3301        ORB = false;
3302      else if (detlist.Contains("+ORB", TString::kIgnoreCase))
3303        ORB = true;
3304    
3305      if (detlist.Contains("-GP", TString::kIgnoreCase))
3306        GP = false;
3307      else if (detlist.Contains("+GP", TString::kIgnoreCase))
3308        GP = true;
3309    
3310      cout << "tree/branch list from input --> ";
3311      if (TRK0)
3312        cout << "TRK0 ";
3313      if (TRK1)
3314        cout << "TRK1 ";
3315      if (TRK2)
3316        cout << "TRK2 ";
3317      if (TRKh)
3318        cout << "TRKH ";
3319      if (CAL0)
3320        cout << "CAL0 ";
3321      if (CAL1)
3322        cout << "CAL1 ";
3323      if (CAL2)
3324        cout << "CAL2 ";
3325      if (TOF)
3326        cout << "TOF ";
3327      if (TRG)
3328        cout << "TRG ";
3329      if (AC)
3330        cout << "AC ";
3331      if (ND)
3332        cout << "ND ";
3333      if (S4)
3334        cout << "S4 ";
3335      if (ORB)
3336        cout << "ORB ";
3337      if (GP)
3338        cout << "GP ";
3339      cout << endl;
3340      //     cout<< "Set detector list --> ";
3341      //     if(TRK1)cout<<"TRK1 ";
3342      //     if(TRK2)cout<<"TRK2 ";
3343      //     if(TRKh)cout<<"TRKH ";
3344      //     if(CAL1)cout<<"CAL1 ";
3345      //     if(CAL2)cout<<"CAL2 ";
3346      //     if(TOF0)cout<<"TOF0 ";
3347      //     if(TOF)cout<<"TOF ";
3348      //     if(TRG)cout<<"TRG ";
3349      //     if(AC)cout<<"AC ";
3350      //     if(ND)cout<<"ND ";
3351      //     if(S4)cout<<"S4 ";
3352      //     if(ORB)cout<<"ORB ";
3353      //     cout << endl;
3354    
3355    }
3356    ;
3357    
3358  /**  /**
3359   * Set tree/branch detector flags from the content of a tree   * Set tree/branch detector flags from the content of a tree
3360   */   */
3361  void  PamLevel2::GetWhichTrees(TFile* f){  void PamLevel2::GetWhichTrees(TFile* f) {
       
3362    
3363      //    cout << "void  PamLevel2::GetWhichTrees(TFile* f) --- WARNING!! --- ...potrebbe non funzionare "<<endl;
3364      // -----------
3365      // reset flags
3366      // -----------
3367      CAL1 = false;
3368      CAL2 = false;
3369      TRK2 = false;
3370      TRK1 = false;
3371      TRKh = false;
3372      TRG = false;
3373      TOF = false;
3374      S4 = false;
3375      ND = false;
3376      AC = false;
3377      ORB = false;
3378      GP = false;
3379    
3380      RUN = false;
3381    
3382      //    cout << "Checking file: "<<f->GetName()<<endl;
3383      if (!f || f->IsZombie()) {
3384        cout << "File: " << f->GetName() << " Non valid root file" << endl;
3385        return;
3386      }
3387    
3388      cout << "void  PamLevel2::GetWhichTrees(TFile* f) --- WARNING!! --- ...potrebbe non funzionare "<<endl;    TList *lk = f->GetListOfKeys();
3389      // -----------    if (!lk)
3390      // reset flags      return;
3391      // -----------    TIter next(lk);
3392      CAL1   = false;        TKey *key = 0;
3393      CAL2   = false;      
3394      TRK2   = false;        Int_t nev = 0;
3395      TRK1   = false;      
3396      TRKh   = false;        while ((key = (TKey*) next())) {
3397      TRG    = false;      
3398      TOF    = false;          if (!strcmp(key->GetName(), "Run"))
3399      S4     = false;            RUN = true;
3400      ND     = false;      
3401      AC     = false;          //=========================================================
3402      ORB    = false;          if (!strcmp(key->GetName(), "Trigger")) {
3403              TRG = true;
3404      RUN    = false;        Int_t nevt = ((TTree*) f->Get("Trigger"))->GetEntries();
3405                  if (nev && nevt != nev) {
3406      cout << "Checking file: "<<f->GetName()<<endl;          cout << "File: " << f->GetName() << " Trigger tree has " << nevt << " events instead of " << nev << endl;
3407      if( !f || f->IsZombie() ){          TRG = false;
3408          cout << "File: "<< f->GetName() <<" Non valid root file"<< endl;        }
3409          return;        else
3410      }          nev = nevt;
3411        }
3412      TList *lk = f->GetListOfKeys();      //=========================================================
3413      TIter next(lk);      if (!strcmp(key->GetName(), "ToF")) {
3414      TKey *key =0;        TOF = true;
3415          Int_t nevt = ((TTree*) f->Get("ToF"))->GetEntries();
3416      Int_t nev = 0;        if (nev && nevt != nev) {
3417            cout << "File: " << f->GetName() << "     ToF tree has " << nevt << " events instead of " << nev << endl;
3418      while( (key = (TKey*)next()) ){          TOF = false;
3419                  }
3420          if( !strcmp(key->GetName(),"Run"        ) )RUN = true;        else
3421            nev = nevt;
3422          //=========================================================          }
3423          if( !strcmp(key->GetName(),"Trigger"    ) ){      //=========================================================
3424              TRG = true;      if (!strcmp(key->GetName(), "S4")) {
3425              Int_t nevt = ((TTree*)f->Get("Trigger"))->GetEntries();        S4 = true;
3426              if( nev && nevt!=nev){        Int_t nevt = ((TTree*) f->Get("S4"))->GetEntries();
3427                  cout << "File: "<< f->GetName() <<" Trigger tree has "<<nevt<<" events instead of "<<nev<< endl;        if (nev && nevt != nev) {
3428                  TRG = false;          cout << "File: " << f->GetName() << "      S4 tree has " << nevt << " events instead of " << nev << endl;
3429              }else nev=nevt;          S4 = false;
3430          }        }
3431          //=========================================================            else
3432          if( !strcmp(key->GetName(),"ToF"        ) ){          nev = nevt;
3433              TOF = true;      }
3434              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();  
         };        
3435    
3436      };      if (!strcmp(key->GetName(), "NeutronD")) {
3437              ND = true;
3438      delete lk;        Int_t nevt = ((TTree*) f->Get("NeutronD"))->GetEntries();
3439          if (nev && nevt != nev) {
3440            cout << "File: " << f->GetName() << "NeutronD tree has " << nevt << " events instead of " << nev << endl;
3441            ND = false;
3442          }
3443          else
3444            nev = nevt;
3445        }
3446        //=========================================================
3447        if (!strcmp(key->GetName(), "Anticounter")) {
3448          AC = true;
3449          Int_t nevt = ((TTree*) f->Get("Anticounter"))->GetEntries();
3450          if (nev && nevt != nev) {
3451            cout << "File: " << f->GetName() << " Anticounter tree has " << nevt << " events instead of " << nev << endl;
3452            AC = false;
3453          }
3454          else
3455            nev = nevt;
3456        }
3457        //=========================================================
3458        if (!strcmp(key->GetName(), "OrbitalInfo")) {
3459          ORB = true;
3460          Int_t nevt = ((TTree*) f->Get("OrbitalInfo"))->GetEntries();
3461          if (nev && nevt != nev) {
3462            cout << "File: " << f->GetName() << " OrbitalInfo tree has " << nevt << " events instead of " << nev << endl;
3463            ORB = false;
3464          }
3465          else
3466            nev = nevt;
3467        }
3468        //=========================================================
3469        if (!strcmp(key->GetName(), "Tracker")) {
3470          TTree *T = (TTree*) f->Get("Tracker");
3471          for (Int_t i = 0; i < T->GetListOfBranches()->GetEntries(); i++) {
3472            TString name = T->GetListOfBranches()->At(i)->GetName();
3473            if (!name.CompareTo("TrkLevel1"))
3474              TRK1 = true;
3475            if (!name.CompareTo("TrkLevel2"))
3476              TRK2 = true;
3477            if (!name.CompareTo("TrkHough"))
3478              TRKh = true;
3479          };
3480          Int_t nevt = T->GetEntries();
3481          if (nev && nevt != nev) {
3482            cout << "File: " << f->GetName() << " Tracker tree has " << nevt << " events instead of " << nev << endl;
3483            TRK1 = false;
3484            TRK2 = false;
3485            TRKh = false;
3486          }
3487          else
3488            nev = nevt;
3489          //            T->Delete();
3490        };
3491        //=========================================================
3492        if (!strcmp(key->GetName(), "Calorimeter")) {
3493          TTree *T = (TTree*) f->Get("Calorimeter");
3494          for (Int_t i = 0; i < T->GetListOfBranches()->GetEntries(); i++) {
3495            TString name = T->GetListOfBranches()->At(i)->GetName();
3496            if (!name.CompareTo("CaloLevel1"))
3497              CAL1 = true;
3498            if (!name.CompareTo("CaloLevel2"))
3499              CAL2 = true;
3500          };
3501          Int_t nevt = T->GetEntries();
3502          if (nev && nevt != nev) {
3503            cout << "File: " << f->GetName() << "  Calorimeter tree has " << nevt << " events instead of " << nev << endl;
3504            CAL1 = false;
3505            CAL2 = false;
3506          }
3507          else
3508            nev = nevt;
3509          //            T->Delete();
3510        };
3511        //=========================================================
3512        if (!strcmp(key->GetName(), "h20")) {
3513          GP = true;
3514          Int_t nevt = ((TTree*) f->Get("h20"))->GetEntries();
3515          if (nev && nevt != nev) {
3516            cout << "File: " << f->GetName() << " h20 tree has " << nevt << " events instead of " << nev << endl;
3517            GP = false;
3518          }
3519          else
3520            nev = nevt;
3521        }
3522    
3523      };
3524    
3525  //     cout<< "Get detector list from input file --> ";    //    delete lk;
 //     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 ;  
           
 };  
3526    
3527      cout << "tree/branch list from file  --> ";
3528      if (TRK1)
3529        cout << "TRK1 ";
3530      if (TRK2)
3531        cout << "TRK2 ";
3532      if (TRKh)
3533        cout << "TRKH ";
3534      if (CAL1)
3535        cout << "CAL1 ";
3536      if (CAL2)
3537        cout << "CAL2 ";
3538      if (TOF)
3539        cout << "TOF ";
3540      if (TRG)
3541        cout << "TRG ";
3542      if (AC)
3543        cout << "AC ";
3544      if (ND)
3545        cout << "ND ";
3546      if (S4)
3547        cout << "S4 ";
3548      if (ORB)
3549        cout << "ORB ";
3550      if (GP)
3551        cout << "GP ";
3552      cout << endl;
3553    
3554      return;
3555    
3556    }
3557    ;
3558    
3559  //--------------------------------------  //--------------------------------------
3560  //  //
# Line 1874  void  PamLevel2::GetWhichTrees(TFile* f) Line 3565  void  PamLevel2::GetWhichTrees(TFile* f)
3565   * @param name File name   * @param name File name
3566   * @return true if the file is ok.   * @return true if the file is ok.
3567   */   */
3568  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;  
3569    
3570      cout << "Checking file: "<<name<<endl;    Bool_t CAL1__ok = false;
3571      TFile *f = new TFile(name.Data());    Bool_t CAL2__ok = false;
3572      if( !f || f->IsZombie() ){    Bool_t TRK2__ok = false;
3573          cout << "File: "<< f->GetName() <<" discarded ---- Non valid root file"<< endl; return false;    Bool_t TRK1__ok = false;
3574      }    Bool_t TRKh__ok = false;
3575  //    cout << "Get list of keys: "<<f<<endl;    Bool_t TRG__ok = false;
3576      TList *lk = f->GetListOfKeys();    Bool_t TOF__ok = false;
3577  //    lk->Print();    Bool_t S4__ok = false;
3578      TIter next(lk);    Bool_t ND__ok = false;
3579      TKey *key =0;    Bool_t AC__ok = false;
3580      Bool_t ORB__ok = false;
3581      Int_t nev = 0;    Bool_t GP__ok = false;
3582    
3583      while( (key = (TKey*)next()) ){    Bool_t RUN__ok = false;
3584            
3585  //      cout << key->GetName() << endl;    Bool_t SELLI__ok = false;
3586  //      cout << key->GetName() << ""<<key->GetClassName()<<endl;  
3587  //              cout << " Get tree: " << f->Get(key->GetName())<<endl;    //    cout << "Checking file: "<<name<<endl;
3588  //      nev_previous = nev;    TFile *f = new TFile(name.Data());
3589  //      cout << " n.entries  "<< nev <<endl;    if (!f || f->IsZombie()) {
3590  //      if( key->GetClassName()=="TTree" && nev_previous && nev != nev_previous ){      cout << "File: " << f->GetName() << " discarded ---- Non valid root file" << endl;
3591  //          nev = ((TTree*)f->Get(key->GetName()))->GetEntries();      return false;
3592  //          cout << "File: "<< f->GetName() <<" discarded ---- "<< key->GetName() << " tree: n.entries does not match "<<nev<<" "<<nev_previous<< endl;    }
3593  //          return false;    //    cout << "Get list of keys: "<<f<<endl;
3594  //      };    TList *lk = f->GetListOfKeys();
3595      //    lk->Print();
3596      TIter next(lk);
3597          if( !strcmp(key->GetName(),"Run"        ) )RUN__ok = true;          TKey *key = 0;
3598    
3599          //=========================================================        Int_t nev = 0;
3600          if( !strcmp(key->GetName(),"SelectionList"    ) ){  
3601              SELLI__ok = true;    while ((key = (TKey*) next())) {
3602              if(SELLI==1){  
3603                  Int_t nevt = ((TTree*)f->Get("SelectionList"))->GetEntries();      //  cout << key->GetName() << endl;
3604                  if( nev && nevt!=nev){      //  cout << key->GetName() << ""<<key->GetClassName()<<endl;
3605                      cout << "File: "<< f->GetName() <<" discarded ---- SelectionList tree has "<<nevt<<" events instead of "<<nev<< endl;      //          cout << " Get tree: " << f->Get(key->GetName())<<endl;
3606                      return false;      //  nev_previous = nev;
3607                  }      //  cout << " n.entries  "<< nev <<endl;
3608                  nev=nevt;      //  if( key->GetClassName()=="TTree" && nev_previous && nev != nev_previous ){
3609              }      //      nev = ((TTree*)f->Get(key->GetName()))->GetEntries();
3610          }      //      cout << "File: "<< f->GetName() <<" discarded ---- "<< key->GetName() << " tree: n.entries does not match "<<nev<<" "<<nev_previous<< endl;
3611        //      return false;
3612          //=========================================================          //  };
3613          if( !strcmp(key->GetName(),"Trigger"    ) ){  
3614              TRG__ok = true;      //=========================================================
3615              if(TRG){      // check if the file
3616                  Int_t nevt = ((TTree*)f->Get("Trigger"))->GetEntries();  
3617                  if( nev && nevt!=nev){  
3618                      cout << "File: "<< f->GetName() <<" discarded ---- Trigger tree has "<<nevt<<" events instead of "<<nev<< endl;      if (!strcmp(key->GetName(), "Run"))
3619                      return false;        RUN__ok = true;
3620                  }  
3621                  nev=nevt;      //=========================================================
3622              }      if (!strcmp(key->GetName(), "SelectionList")) {
3623          }        SELLI__ok = true;
3624          //=========================================================            if (SELLI == 1) {
3625          if( !strcmp(key->GetName(),"ToF"        ) ){          Int_t nevt = ((TTree*) f->Get("SelectionList"))->GetEntries();
3626              TOF__ok = true;          if (nev && nevt != nev) {
3627              if(TOF){            cout << "File: " << f->GetName() << " discarded ---- SelectionList tree has " << nevt
3628                  Int_t nevt = ((TTree*)f->Get("ToF"))->GetEntries();                << " events instead of " << nev << endl;
3629                  if( nev && nevt!=nev){            return false;
3630                      cout << "File: "<< f->GetName() <<" discarded ---- ToF tree has "<<nevt<<" events instead of "<<nev<< endl;          }
3631                      return false;          nev = nevt;
3632                  }        }
                 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;  
3633      }      }
       
 //    cout << "SELLI "<<SELLI<<endl;  
3634    
3635  //     cout<< "CheckLevel2File(TString): detector list --> ";      //=========================================================
3636  //     if(TRK1__ok)cout<<"TRK1 ";      if (!strcmp(key->GetName(), "Trigger")) {
3637  //     if(TRK2__ok)cout<<"TRK2 ";        TRG__ok = true;
3638  //     if(TRKh__ok)cout<<"TRKH ";        if (TRG) {
3639  //     if(CAL1__ok)cout<<"CAL1 ";          Int_t nevt = ((TTree*) f->Get("Trigger"))->GetEntries();
3640  //     if(CAL2__ok)cout<<"CAL2 ";          if (nev && nevt != nev) {
3641  //     if(TOF__ok)cout<<"TOF ";            cout << "File: " << f->GetName() << " discarded ---- Trigger tree has " << nevt << " events instead of "
3642  //     if(TRG__ok)cout<<"TRG ";                << nev << endl;
3643  //     if(AC__ok)cout<<"AC ";            return false;
3644  //     if(ND__ok)cout<<"ND ";          }
3645  //     if(S4__ok)cout<<"S4 ";          nev = nevt;
3646  //     if(ORB__ok)cout<<"ORB ";        }
3647  //     cout << endl;      }
3648        //=========================================================
3649        if (!strcmp(key->GetName(), "ToF")) {
3650      if(TRK2 && TRK1__ok)TRK1=1;        TOF__ok = true;
3651  // ----------------------------------------------------------------------------        if (TOF) {
3652  // NOTA          Int_t nevt = ((TTree*) f->Get("ToF"))->GetEntries();
3653  // se c'e` il level1, lo devo necessarimente leggere.          if (nev && nevt != nev) {
3654  // 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
3655  // comunque, ma non vengono disallocati da PamLevel2::Clear()                << endl;
3656  // ----------------------------------------------------------------------------            return false;
3657            }
3658            nev = nevt;
3659      if(!RUN__ok) {        }
3660          cout << "File: "<< f->GetName() <<" *WARNING* ---- Missing RunInfo tree"<< endl;      }
3661  //      return false;      //=========================================================
3662      };      if (!strcmp(key->GetName(), "S4")) {
3663          S4__ok = true;
3664      if(CAL1 && !CAL1__ok){        if (S4) {
3665          cout << "File: "<< f->GetName() <<" discarded ---- Missing CaloLevel1 branch"<< endl;          Int_t nevt = ((TTree*) f->Get("S4"))->GetEntries();
3666          return false;          if (nev && nevt != nev) {
3667      };            cout << "File: " << f->GetName() << " discarded ---- S4 tree has " << nevt << " events instead of " << nev
3668      if(CAL2 && !CAL2__ok){                << endl;
3669          cout << "File: "<< f->GetName() <<" discarded ---- Missing CaloLevel2 branch"<< endl;            return false;
3670          return false;          }
3671      };          nev = nevt;
3672      if(TRK2 && !TRK2__ok){        }
3673          cout << "File: "<< f->GetName() <<" discarded ---- Missing TrkLevel2 branch"<< endl;      }
3674          return false;      //=========================================================
3675      };  
3676      if(TRK1 && !TRK1__ok){      if (!strcmp(key->GetName(), "NeutronD")) {
3677          cout << "File: "<< f->GetName() <<" discarded ---- Missing TrkLevel1 branch"<< endl;        ND__ok = true;
3678          return false;        if (ND) {
3679      };          Int_t nevt = ((TTree*) f->Get("NeutronD"))->GetEntries();
3680      if(TRKh && !TRKh__ok){          if (nev && nevt != nev) {
3681          cout << "File: "<< f->GetName() <<" discarded ---- Missing TrkHough branch"<< endl;            cout << "File: " << f->GetName() << " discarded ---- NeutronD tree has " << nevt << " events instead of "
3682          return false;                << nev << endl;
3683      };            return false;
3684      if(ORB && !ORB__ok){          }
3685          cout << "File: "<< f->GetName() <<" discarded ---- Missing ORB tree"<< endl;          nev = nevt;
3686          return false;        }
3687      };      }
3688      if(AC && !AC__ok){      //=========================================================
3689          cout << "File: "<< f->GetName() <<" discarded ---- Missing AC tree"<< endl;      if (!strcmp(key->GetName(), "Anticounter")) {
3690          return false;        AC__ok = true;
3691      };        if (AC) {
3692      if(S4 && !S4__ok){          Int_t nevt = ((TTree*) f->Get("Anticounter"))->GetEntries();
3693          cout << "File: "<< f->GetName() <<" discarded ---- Missing S4 tree"<< endl;          if (nev && nevt != nev) {
3694          return false;            cout << "File: " << f->GetName() << " discarded ---- Anticounter tree has " << nevt << " events instead of "
3695      };                << nev << endl;
3696      if(TOF && !TOF__ok){            return false;
3697          cout << "File: "<< f->GetName() <<" discarded ---- Missing ToF tree"<< endl;          }
3698          return false;          nev = nevt;
3699      };        }
3700        }
3701      if(ND && !ND__ok){      //=========================================================
3702          cout << "File: "<< f->GetName() <<" discarded ---- Missing ND tree"<< endl;      if (!strcmp(key->GetName(), "OrbitalInfo")) {
3703          return false;        ORB__ok = true;
3704      };        if (ORB) {
3705      if(TRG && !TRG__ok){          Int_t nevt = ((TTree*) f->Get("OrbitalInfo"))->GetEntries();
3706          cout << "File: "<< f->GetName() <<" discarded ---- Missing Trigger tree"<< endl;          if (nev && nevt != nev) {
3707          return false;            cout << "File: " << f->GetName() << " discarded ---- OrbitalInfo tree has " << nevt << " events instead of "
3708                  << nev << endl;
3709              return false;
3710            }
3711            nev = nevt;
3712          }
3713        }
3714        //=========================================================
3715        if (!strcmp(key->GetName(), "Tracker")) {
3716          TTree *T = (TTree*) f->Get("Tracker");
3717          if (TRK1 || TRK2 || TRKh) {
3718            Int_t nevt = T->GetEntries();
3719            if (nev && nevt != nev) {
3720              cout << "File: " << f->GetName() << " discarded ---- Tracker tree has " << nevt << " events instead of "
3721                  << nev << endl;
3722              return false;
3723            }
3724            nev = nevt;
3725          }
3726          for (Int_t i = 0; i < T->GetListOfBranches()->GetEntries(); i++) {
3727            TString name = T->GetListOfBranches()->At(i)->GetName();
3728            if (!name.CompareTo("TrkLevel1"))
3729              TRK1__ok = true;
3730            if (!name.CompareTo("TrkLevel2"))
3731              TRK2__ok = true;
3732            if (!name.CompareTo("TrkHough"))
3733              TRKh__ok = true;
3734          };
3735          T->Delete();
3736      };      };
3737            //=========================================================
3738        if (!strcmp(key->GetName(), "Calorimeter")) {
3739          TTree *T = (TTree*) f->Get("Calorimeter");
3740          if (CAL1 || CAL2) {
3741            Int_t nevt = T->GetEntries();
3742            if (nev && nevt != nev) {
3743              cout << "File: " << f->GetName() << " discarded ---- Calorimeter tree has " << nevt << " events instead of "
3744                  << nev << endl;
3745              return false;
3746            }
3747            nev = nevt;
3748          }
3749          for (Int_t i = 0; i < T->GetListOfBranches()->GetEntries(); i++) {
3750            TString name = T->GetListOfBranches()->At(i)->GetName();
3751            if (!name.CompareTo("CaloLevel1"))
3752              CAL1__ok = true;
3753            if (!name.CompareTo("CaloLevel2"))
3754              CAL2__ok = true;
3755          };
3756          T->Delete();
3757        };
3758        //=========================================================
3759        if (!strcmp(key->GetName(), "h20")) {
3760          ISGP = true;
3761          GP__ok = true;
3762          if (GP) {
3763            Int_t nevt = ((TTree*) f->Get("h20"))->GetEntries();
3764            if (nev && nevt != nev) {
3765              cout << "File: " << f->GetName() << " discarded ---- h20 tree has " << nevt << " events instead of " << nev
3766                  << endl;
3767              return false;
3768            }
3769            nev = nevt;
3770          }
3771        }
3772    
3773      };
3774    
3775      if (SELLI == -1)
3776        SELLI = (Int_t) SELLI__ok;
3777      if (SELLI == 0 && SELLI__ok) {
3778        cout << "File: " << f->GetName() << " discarded ---- found SelectionList (it is not a full-event file)" << endl;
3779        return false;
3780      }
3781      if (SELLI == 1 && !SELLI__ok) {
3782        cout << "File: " << f->GetName() << " discarded ---- SelectionList missing" << endl;
3783        return false;
3784      }
3785    
3786      //    cout << "SELLI "<<SELLI<<endl;
3787    
3788      //     cout<< "CheckLevel2File(TString): detector list --> ";
3789      //     if(TRK1__ok)cout<<"TRK1 ";
3790      //     if(TRK2__ok)cout<<"TRK2 ";
3791      //     if(TRKh__ok)cout<<"TRKH ";
3792      //     if(CAL1__ok)cout<<"CAL1 ";
3793      //     if(CAL2__ok)cout<<"CAL2 ";
3794      //     if(TOF__ok)cout<<"TOF ";
3795      //     if(TRG__ok)cout<<"TRG ";
3796      //     if(AC__ok)cout<<"AC ";
3797      //     if(ND__ok)cout<<"ND ";
3798      //     if(S4__ok)cout<<"S4 ";
3799      //     if(ORB__ok)cout<<"ORB ";
3800      //     cout << endl;
3801    
3802    
3803      if (TRK2 && TRK1__ok)
3804        TRK1 = 1;
3805      // ----------------------------------------------------------------------------
3806      // NOTA
3807      // se c'e` il level1, lo devo necessarimente leggere.
3808      // infatti (non ho capito perche`) i cluster vengono letti e allocati in memoria
3809      // comunque, ma non vengono disallocati da PamLevel2::Clear()
3810      // ----------------------------------------------------------------------------
3811    
3812    
3813      if (!RUN__ok) {
3814        cout << "File: " << f->GetName() << " *WARNING* ---- Missing RunInfo tree (NB: RUN infos will not be updated)"
3815            << endl;
3816        RUN = false;
3817      };
3818    
3819      if (CAL1 && !CAL1__ok) {
3820        cout << "File: " << f->GetName() << " discarded ---- Missing CaloLevel1 branch" << endl;
3821        return false;
3822      };
3823      if (CAL2 && !CAL2__ok) {
3824        cout << "File: " << f->GetName() << " discarded ---- Missing CaloLevel2 branch" << endl;
3825        return false;
3826      };
3827      if (TRK2 && !TRK2__ok) {
3828        cout << "File: " << f->GetName() << " discarded ---- Missing TrkLevel2 branch" << endl;
3829        return false;
3830      };
3831      if (TRK1 && !TRK1__ok) {
3832        cout << "File: " << f->GetName() << " discarded ---- Missing TrkLevel1 branch" << endl;
3833        return false;
3834      };
3835      if (TRKh && !TRKh__ok) {
3836        cout << "File: " << f->GetName() << " discarded ---- Missing TrkHough branch" << endl;
3837        return false;
3838      };
3839      if (ORB && !ORB__ok) {
3840        cout << "File: " << f->GetName() << " discarded ---- Missing ORB tree" << endl;
3841        return false;
3842      };
3843      if (AC && !AC__ok) {
3844        cout << "File: " << f->GetName() << " discarded ---- Missing AC tree" << endl;
3845        return false;
3846      };
3847      if (S4 && !S4__ok) {
3848        cout << "File: " << f->GetName() << " discarded ---- Missing S4 tree" << endl;
3849        return false;
3850      };
3851      if (TOF && !TOF__ok) {
3852        cout << "File: " << f->GetName() << " discarded ---- Missing ToF tree" << endl;
3853        return false;
3854      };
3855    
3856      if (ND && !ND__ok) {
3857        cout << "File: " << f->GetName() << " discarded ---- Missing ND tree" << endl;
3858        return false;
3859      };
3860      if (TRG && !TRG__ok) {
3861        cout << "File: " << f->GetName() << " discarded ---- Missing Trigger tree" << endl;
3862        return false;
3863      };
3864      if (GP && !GP__ok) {
3865        cout << "File: " << f->GetName() << " discarded ---- Missing h20 tree" << endl;
3866        return false;
3867      };
3868    
3869      //    lk->Delete();
3870      //    delete lk;
3871      f->Close();
3872    
3873      //     cout<< "CheckLevel2File(TString): detector list --> ";
3874      //     if(TRK1)cout<<"TRK1 ";
3875      //     if(TRK2)cout<<"TRK2 ";
3876      //     if(TRKh)cout<<"TRKH ";
3877      //     if(CAL1)cout<<"CAL1 ";
3878      //     if(CAL2)cout<<"CAL2 ";
3879      //     if(TOF)cout<<"TOF ";
3880      //     if(TRG)cout<<"TRG ";
3881      //     if(AC)cout<<"AC ";
3882      //     if(ND)cout<<"ND ";
3883      //     if(S4)cout<<"S4 ";
3884      //     if(ORB)cout<<"ORB ";
3885      //     if(GP)cout<<"GP ";
3886      //     cout << endl;
3887    
3888  //    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;  
           
 };  
3889    
3890    }
3891    ;
3892    
3893  /**  /**
3894   * Create clone-trees   * Create clone-trees
3895   */   */
3896  void PamLevel2::CreateCloneTrees0( TChain *fChain, TFile *ofile ){  void PamLevel2::CreateCloneTrees0(TChain *fChain, TFile *ofile) {
3897    
3898      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;    cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
3899      cout << "Create clones of PAMELA trees "<<endl;    cout << "Create clones of PAMELA trees " << endl;
3900        
3901      Int_t i=0;    Int_t i = 0;
3902      pam_tree_clone[i] = fChain->GetTree()->CloneTree(0);    pam_tree_clone[i] = fChain->GetTree()->CloneTree(0);
3903      TString name =  pam_tree_clone[i]->GetName();    TString name = pam_tree_clone[i]->GetName();
3904      name.Append("_clone");
3905      //    pam_tree_clone[i]->SetName(name.Data());
3906      cout << pam_tree_clone[i]->GetName() << endl;
3907      i++;
3908    
3909      TList *li = fChain->GetListOfFriends();
3910      TIter next(li);
3911      TFriendElement* T_friend = 0;
3912      ofile->cd();
3913      while ((T_friend = (TFriendElement*) next())) {
3914        //  cout<<T_friend->IsA()->GetName()<<" "<<T_friend->GetName()<<hex << T_friend->GetTree() << dec<<endl;
3915        //  cout<<T_friend->GetTree()->GetName()<< endl;
3916        pam_tree_clone[i] = T_friend->GetTree()->CloneTree(0);
3917        pam_tree_clone[i]->SetAutoSave(1000000);
3918        name = pam_tree_clone[i]->GetName();
3919      name.Append("_clone");      name.Append("_clone");
3920  //    pam_tree_clone[i]->SetName(name.Data());      //  pam_tree_clone[i]->SetName(name.Data());
3921      cout << pam_tree_clone[i]->GetName() <<endl;      cout << pam_tree_clone[i]->GetName() << endl;
3922      i++;      i++;
3923      }
3924    
3925      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;  
3926    
3927      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;    cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
3928    
3929  }  }
3930    
3931  /**  /**
3932   * Create clone-trees   * Create clone-trees
3933   */   */
3934  void PamLevel2::CreateCloneTrees(TFile *ofile){  void PamLevel2::CreateCloneTrees(TFile *ofile) {
3935    
3936      ofile->cd();    //  if the pointer is null, create a default file
3937      if (!run_tree)
3938        return;
3939    
3940      if (!ofile) {
3941        cout << "void PamLevel2::CreateCloneTrees(TFile*) -- WARNING -- Creating file: clone-tree.root " << endl;
3942        ofile = new TFile("clone-tree.root", "recreate");
3943      }
3944    
3945      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;    ofile->cd();
     cout << "Create new PAMELA trees "<<endl;  
           
3946    
3947      run_tree_clone = new TTree("Run","PAMELA Level2 data from the GL_RUN table ");    cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
3948      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;  
               
3949    
3950      run_tree_clone = new TTree("Run", "PAMELA Level2 data from the GL_RUN table ");
3951      run_tree_clone->Branch("RunInfo", "GL_RUN", GetPointerTo("RunInfo"));
3952      cout << "Run          : branch RunInfo" << endl;
3953      run_tree_clone->Branch("SoftInfo", "SoftInfo", GetPointerTo("SoftInfo"));
3954      cout << "Run          : branch SoftInfo" << endl;
3955      // ------------------
3956      // replicate run tree
3957      // ------------------
3958      //    cout << "----------------------------------------------------"<<endl;
3959      //    cout << "irun\t | RUN\t NEVENTS\t absolute time"<<endl;
3960      for (Int_t i = 0; i < run_tree->GetEntries(); i++) {
3961        run_tree->GetEntry(i);
3962        //  cout << i<< "\t | "<<GetRunInfo()->ID<<"\t "<<GetRunInfo()->NEVENTS<< "\t "<<GetRunInfo()->RUNHEADER_TIME<<" <---> "<<GetRunInfo()->RUNTRAILER_TIME<<endl;
3963        run_tree_clone->Fill();
3964      }
3965      cout << "----------------------------------------------------" << endl;
3966    
3967      sel_tree_clone = new TTree("SelectionList","List of selected events ");    // ------------------------------------
3968      sel_tree_clone->Branch("RunEntry",&irun,"runentry/I");    // add branch with dead and live times
3969      sel_tree_clone->Branch("EventEntry",&irunentry,"eventry/I");    // ------------------------------------
3970          if (SELLI != 2) { // EMILIANO
3971        run_tree_clone->Branch("DeadLiveTime", totdltime, "dltime[3]/l");
3972        cout << "Run          : branch DeadLiveTime" << endl;
3973    
3974        sel_tree_clone = new TTree("SelectionList", "List of selected events ");
3975        //    sel_tree_clone->Branch("RunEntry",&irun,"runentry/L");
3976        sel_tree_clone->Branch("RunEntry", &irunt, "runentry/L");//NEWNEW
3977        sel_tree_clone->Branch("EventEntry", &irunentry, "eventry/L");
3978        //    if ( hasL0EE ) sel_tree_clone->Branch("L0EventEntry", &il0entry, "l0eventry/L");
3979      };
3980    
3981      Int_t i=0;    Int_t i = 0;
3982      if(TRK1||TRK2||TRKh){    if (TRK1 || TRK2 || TRKh) {
3983          pam_tree_clone[i] = new TTree("Tracker","PAMELA tracker level2 data ");      pam_tree_clone[i] = new TTree("Tracker", "PAMELA tracker level2 data ");
3984          if(TRK1) {      if (TRK1) {
3985              pam_tree_clone[i]->Branch("TrkLevel1","TrkLevel1", GetPointerTo("TrkLevel1"));        pam_tree_clone[i]->Branch("TrkLevel1", "TrkLevel1", GetPointerTo("TrkLevel1"));
3986              pam_tree_clone[i]->BranchRef();        pam_tree_clone[i]->BranchRef();
3987              cout << "Tracker      : branch TrkLevel1"<<endl;        cout << "Tracker      : branch TrkLevel1" << endl;
3988              cout << "CreateCloneTrees " << GetTrkLevel1()<<endl;        //            cout << "CreateCloneTrees " << GetTrkLevel1()<<endl;
3989          };      };
3990          if(TRK2) {      if (TRK2) {
3991              pam_tree_clone[i]->Branch("TrkLevel2", "TrkLevel2",GetPointerTo("TrkLevel2"));        pam_tree_clone[i]->Branch("TrkLevel2", "TrkLevel2", GetPointerTo("TrkLevel2"));
3992              cout << "Tracker      : branch TrkLevel2"<<endl;                cout << "Tracker      : branch TrkLevel2" << endl;
3993          };      };
3994          if(TRKh) {      if (TRKh) {
3995              pam_tree_clone[i]->Branch("TrkHough","TrkHough", GetPointerTo("TrkHough"));        pam_tree_clone[i]->Branch("TrkHough", "TrkHough", GetPointerTo("TrkHough"));
3996              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++;  
3997      };      };
3998      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;      i++;
3999      }
4000    
4001  }    // Calorimeter
4002      if (CAL1 || CAL2) {
4003        pam_tree_clone[i] = new TTree("Calorimeter", "PAMELA calorimeter level2 data ");
4004        if (CAL1) {
4005          pam_tree_clone[i]->Branch("CaloLevel1", "CaloLevel1", GetPointerTo("CaloLevel1"));
4006          cout << "Calorimeter  : branch CaloLevel1" << endl;
4007        };
4008        if (CAL2) {
4009          pam_tree_clone[i]->Branch("CaloLevel2", "CaloLevel2", GetPointerTo("CaloLevel2"));
4010          cout << "Calorimeter  : branch CaloLevel2" << endl;
4011        };
4012        i++;
4013      }
4014    
4015      // ToF
4016      if (TOF) {
4017        pam_tree_clone[i] = new TTree("ToF", "PAMELA ToF level2 data ");
4018        pam_tree_clone[i]->Branch("ToFLevel2", "ToFLevel2", GetPointerTo("ToFLevel2"));
4019        cout << "ToF          : branch ToFLevel2" << endl;
4020        i++;
4021      };
4022      // Trigger
4023      if (TRG) {
4024        pam_tree_clone[i] = new TTree("Trigger", "PAMELA trigger level2 data ");
4025        pam_tree_clone[i]->Branch("TrigLevel2", "TrigLevel2", GetPointerTo("TrigLevel2"));
4026        cout << "Trigger      : branch TrigLevel2" << endl;
4027        i++;
4028      };
4029      // S4
4030      if (S4) {
4031        pam_tree_clone[i] = new TTree("S4", "PAMELA S4 level2 data ");
4032        pam_tree_clone[i]->Branch("S4Level2", "S4Level2", GetPointerTo("S4Level2"));
4033        cout << "S4           : branch S4Level2" << endl;
4034        i++;
4035      };
4036      // Neutron Detector
4037      if (ND) {
4038        pam_tree_clone[i] = new TTree("NeutronD", "PAMELA neutron detector level2 data ");
4039        pam_tree_clone[i]->Branch("NDLevel2", "NDLevel2", GetPointerTo("NDLevel2"));
4040        cout << "NeutronD     : branch NDLevel2" << endl;
4041        i++;
4042      };
4043      // Anticounters
4044      if (AC) {
4045        pam_tree_clone[i] = new TTree("Anticounter", "PAMELA anticounter detector level2 data ");
4046        pam_tree_clone[i]->Branch("AcLevel2", "AcLevel2", GetPointerTo("AcLevel2"));
4047        cout << "Anticounter  : branch AcLevel2" << endl;
4048        i++;
4049      };
4050      // OrbitalInfo
4051      if (ORB) {
4052        pam_tree_clone[i] = new TTree("OrbitalInfo", "PAMELA orbital info  ");
4053        pam_tree_clone[i]->Branch("OrbitalInfo", "OrbitalInfo", GetPointerTo("OrbitalInfo"));
4054        cout << "OrbitalInfo  : branch OrbitalInfo" << endl;
4055        i++;
4056      };
4057      // GPamela
4058      if (GP) {
4059        pam_tree_clone[i] = new TTree("h20", "GPAMELA info ");
4060        pam_tree_clone[i]->Branch("GPamela", "GPamela", GetPointerTo("GPamela"), 32000, 1);//split
4061        cout << "GPamela  : branch GPamela" << endl;
4062        i++;
4063      };
4064      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
4065    
4066    }
4067    
4068  /**  /**
4069   * Fill tree (created with CreateCloneTrees)   * Fill tree (created with CreateCloneTrees)
4070   *   *
4071   */   */
4072  //void PamLevel2::FillNewPamTree(TTree *T){  //void PamLevel2::FillNewPamTree(TTree *T){
4073  void PamLevel2::FillCloneTrees(){  void PamLevel2::FillCloneTrees() {
       
 //    cout << "PamLevel2::FillCloneTrees()" << irunentry << endl;  
4074    
4075      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();      
4076    
4077  }    for (Int_t i = 0; i < NCLONES; i++) {
4078        if (pam_tree_clone[i])
4079          pam_tree_clone[i]->Fill();
4080      }
4081      if (sel_tree_clone)
4082        sel_tree_clone->Fill();
4083    
4084    }
4085    
4086  TTree* PamLevel2::GetCloneTree(TString name){  TTree* PamLevel2::GetCloneTree(TString name) {
4087    
4088      for(Int_t i=0; i<NCLONES; i++){        for (Int_t i = 0; i < NCLONES; i++) {
4089          if(pam_tree_clone[i]){      if (pam_tree_clone[i]) {
4090              TString na = pam_tree_clone[i]->GetName();        TString na = pam_tree_clone[i]->GetName();
4091              if(!name.CompareTo(na))return pam_tree_clone[i];        if (!name.CompareTo(na))
4092          };          return pam_tree_clone[i];
4093      }      };
4094      if(run_tree_clone){    }
4095          TString na = run_tree_clone->GetName();    if (run_tree_clone) {
4096          if(!name.CompareTo(na))return run_tree_clone;      TString na = run_tree_clone->GetName();
4097      }      if (!name.CompareTo(na))
4098      if(sel_tree_clone){        return run_tree_clone;
4099          TString na = sel_tree_clone->GetName();    }
4100          if(!name.CompareTo(na))return sel_tree_clone;    if (sel_tree_clone) {
4101      }      TString na = sel_tree_clone->GetName();
4102      return NULL;      if (!name.CompareTo(na))
4103          return sel_tree_clone;
4104      }
4105      return NULL;
4106    
4107  }  }
4108  void PamLevel2::WriteCloneTrees(){  void PamLevel2::WriteCloneTrees() {
4109      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;    cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
4110      cout << "Write clones of PAMELA trees "<<endl;    cout << "Write clones of PAMELA trees " << endl;
4111      cout << run_tree_clone->GetName()<<endl;        cout << run_tree_clone->GetName() << endl;
4112      run_tree_clone->Write();    if (SELLI != 2) {// Emiliano
4113      cout << sel_tree_clone->GetName()<<endl;          if (run_tree_clone->GetBranch("DeadLiveTime")->GetEntries() < run_tree->GetEntries())
4114          run_tree_clone->GetBranch("DeadLiveTime")->Fill();
4115      };
4116      run_tree_clone->Write();
4117      if (SELLI != 2) { //Emiliano
4118        cout << sel_tree_clone->GetName() << endl;
4119      sel_tree_clone->Write();      sel_tree_clone->Write();
4120      for(Int_t i=0; i<NCLONES; i++){        };
4121          if(pam_tree_clone[i]){    for (Int_t i = 0; i < NCLONES; i++) {
4122              cout << pam_tree_clone[i]->GetName()<<endl;      if (pam_tree_clone[i]) {
4123              pam_tree_clone[i]->Write();        cout << pam_tree_clone[i]->GetName() << endl;
4124          };        pam_tree_clone[i]->Write();
4125      }      };
4126      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;    }
4127      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
4128    
4129  }  }
4130    
4131  /**  /**
4132   * 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.
4133   */   */
4134  Int_t PamLevel2::GetEntry(Int_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;  
     }  
4135    
4136      Int_t ii=0;    if (!pam_tree) {
4137      //-------------------------------      cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- level2 trees not loaded" << endl;
4138      ii = iee;      return 0;
4139      if( !pam_tree->GetEntry(ii) ) return 0;    }
     //-------------------------------  
4140    
4141      if(!run_tree ){    //
4142          cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- run tree not loaded"<<endl;    // 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...
4143          return 0;    //
4144      //    if(!run_tree ){
4145      //    cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- run tree not loeaded"<<endl;
4146      //    return 0;
4147      //    }
4148    
4149      //-------------------------------
4150      if (!pam_tree->GetEntry(iee)) {
4151        cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- error reading pam tree" << endl;
4152        return 0;
4153      }
4154      //
4155      // ... 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.
4156      // 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
4157      // a problem if you don't check the return code of getentry.
4158      //
4159      if (!RUN || !run_tree) {
4160        if (TRK0 || CAL0 || TOF0 || RUN) { //forse cosi` va bene per tornare 1?
4161          cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- run tree not loaded" << endl;
4162          return 0;
4163      }      }
4164        else {
4165          return 1; //cosi` se non c'e` run esce qua...
4166        }
4167      }
4168    
4169      ii = iee;    //-------------------------------
4170      Bool_t UPDATED = UpdateRunInfo(run_tree,ii);    //
4171      if(SELLI==0)irunentry = iee-runfirstentry;    if ( fUpdateRunInfo ) UpdateRunInfo(iee); // Emiliano
4172      if(UPDATED && run_tree_clone)run_tree_clone->Fill();    if (SELLI == 0 || SELLI == 2) irunentry = iee - runfirstentry;
   
 //    cout << "PamLevel2::GetEntry("<<iee<<") "<<irun<<" "<<runfirstentry<<" "<<irunentry<<endl;  
4173    
4174      if( TRK0 || CAL0 || TOF0 )GetYodaEntry( );    return 1;
4175    
4176      return 1;  }
4177    
4178    TrkLevel0 *PamLevel2::GetTrkLevel0() {
4179      if (!TRK0)
4180        return NULL;
4181      if (!GetYodaEntry()) {
4182        cout << " Int_t PamLevel2::GetTrkLevel0() -- ERROR -- error reading level0 tree" << endl;
4183        return 0;
4184      }
4185      return trk0_obj;
4186    }
4187    ;
4188    CaloLevel0 *PamLevel2::GetCaloLevel0() {
4189      if (!CAL0)
4190        return NULL;
4191      if (!GetYodaEntry()) {
4192        cout << " Int_t PamLevel2::GetCaloLevel0() -- ERROR -- error reading level0 tree" << endl;
4193        return 0;
4194      }
4195      return calo0_obj;
4196  }  }
4197    ;
4198    
4199  /**  /**
4200   * 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 2394  Int_t PamLevel2::GetEntry(Int_t iee){ Line 4202  Int_t PamLevel2::GetEntry(Int_t iee){
4202   * @return Pointer to the tree   * @return Pointer to the tree
4203   */   */
4204    
4205    TTree* PamLevel2::GetYodaTree() {
4206    
4207  TTree* PamLevel2::GetYodaTree( ){    //    cout << "TTree* PamLevel2::GetYodaTree( )"<<endl;
4208          //===================================
4209  //    cout << "TTree* PamLevel2::GetYodaTree( )"<<endl;    // check if iroot has changed
4210      //===================================    //===================================
4211      // check if iroot has changed    if (irun < 0) {
4212      //===================================      cout << "PamLevel2::GetYodaTree() -- ERROR -- irun = " << irun << endl;
4213      if( irun<0 ){      if (DBG) cout << "In order to use this method you have to first load the RunInfo tree "<<endl;
4214          cout << "PamLevel2::GetYodaTree() -- ERROR "<<endl;      return NULL;
4215          cout << "In order to use this method you have to load the RunInfo tree "<<endl;    }
4216          cout << "with the method TChain* PamLevel2::GetRunTree(TString, TString)"<<endl;    Int_t irootnew = GetRunInfo()->ID_ROOT_L0;
4217  //      cout << " - read the event with PamLevel2::GetEntry(Int_t)"<<endl;    if (DBG){
4218          return NULL;      cout << "iroot    "<<iroot<<endl;
4219      }          cout << "irootnew "<<irootnew<<endl;
4220      Int_t irootnew = run_obj->ID_ROOT_L0;    }
 //     cout << "iroot    "<<iroot<<endl;  
 //     cout << "irootnew "<<irootnew<<endl;  
4221    
4222      //===================================
4223      // load the level0 file
4224      // (if not already loaded)
4225      //===================================
4226      if (iroot != irootnew || !l0_tree) {
4227        iroot = irootnew;
4228      //===================================      //===================================
4229      // load the level0 file      // open the DB connection
4230      // (if not already loaded)      // (if not already opened)
4231      //===================================      //===================================
4232      if( iroot != irootnew || !l0_tree){      if (!dbc || (dbc && !dbc->IsConnected()))
4233          iroot = irootnew;        SetDBConnection();
4234          //===================================      GL_ROOT glroot = GL_ROOT();
4235          // open the DB connection      if (glroot.Query_GL_ROOT(iroot, dbc)) {
4236          // (if not already opened)        cout << "TTree* PamLevel2::GetYodaTree( ) -- ERROR -- level0 file iroot = " << iroot << " does not exists"
4237          //===================================            << endl;
4238          if(!dbc || (dbc && !dbc->IsConnected())){        return NULL;
4239              cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;      };
4240              cout<<"Connecting to DB"<<endl;      TString filename = glroot.PATH + glroot.NAME;
4241              cout<<"HOST "<<host<<endl;      if (l0_file) {
4242              cout<<"USER "<<user<<endl;        l0_file->Close();
4243              cout<<"PSW  "<<psw<<endl;        l0_file->Delete();
4244              dbc = TSQLServer::Connect(host.Data(),user.Data(),psw.Data());      }
4245              if( !dbc )return NULL;      cout << "Opening LEVEL0 file: " << filename << endl;
4246              if( !dbc->IsConnected() )return NULL;          FileStat_t t;
4247  //          cout<<"...done"<<endl;      if (gSystem->GetPathInfo(filename.Data(), t)) {
4248              cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;        cout << " PamLevel2::GetYodaTree() -- ERROR opening file " << endl;
4249          }else{        return NULL;
4250  //          cout<<"DB already connected"<<endl;      }
4251          }      l0_file = new TFile(filename);
4252          GL_ROOT glroot = GL_ROOT();      if (!l0_file)
4253          if( glroot.Query_GL_ROOT(iroot,dbc) ){        return NULL;
4254              cout << "TTree* PamLevel2::GetYodaTree( ) -- ERROR -- level0 file iroot = "<<iroot<< " does not exists"<<endl;      l0_tree = (TTree*) l0_file->Get("Physics");
4255              return NULL;      if (!h0_obj)
4256          };        h0_obj = new EventHeader();
4257          TString filename = glroot.PATH + glroot.NAME;      l0_tree->SetBranchAddress("Header", &h0_obj);
4258          if(l0_file){      yprevshift = 0; // yes, yprevshift is the shift in the level0, prevshift is the shift in the level2
4259              l0_file->Close();      //---------------------------------------------------
4260              l0_file->Delete();      // TRACKER:
4261          }      if (TRK0) {
4262          cout << "Opening LEVEL0 file: "<< filename << endl;        if (!trk0_obj) {
4263          FileStat_t t;          trk0_obj = new TrkLevel0();
4264          if( gSystem->GetPathInfo(filename.Data(),t) ){          trk0_obj->Set();
4265              cout << " PamLevel2::GetYodaTree() -- ERROR opening file "<<endl;        };
4266              return NULL;        l0_tree->SetBranchAddress("Tracker", trk0_obj->GetPointerToTrackerEvent());
4267          }      }
4268          l0_file = new TFile(filename);      //--------------------------------------------------
4269          if( !l0_file )return NULL;      // CALORIMETER:
4270          l0_tree = (TTree*)l0_file->Get("Physics");      if (CAL0) {
4271          if(!h0_obj)h0_obj = new EventHeader();        if (!calo0_obj) {
4272          l0_tree->SetBranchAddress("Header" ,&h0_obj);          calo0_obj = new CaloLevel0();
4273          //---------------------------------------------------          calo0_obj->Set();
4274          // TRACKER:        };
4275          if(TRK0){        l0_tree->SetBranchAddress("Calorimeter", calo0_obj->GetPointerToCalorimeterEvent());
4276              if(!trk0_obj){      }
4277                  trk0_obj = new TrkLevel0();      //---------------------------------------------------
4278                  trk0_obj->Set();      // TOF:
4279              };      if (TOF0) {
4280              l0_tree->SetBranchAddress("Tracker" ,trk0_obj->GetPointerToTrackerEvent());        cout << "PamLevel2::GetYodaTree() --- level0 TOF not implemented " << endl;
4281              TrkParams::SetCalib(run_obj,dbc);      }
         }  
         //---------------------------------------------------  
         // CALORIMETER:  
         if(CAL0){  
             cout << "PamLevel2::GetYodaTree() --- level0 calorimeter not implemented "<<endl;  
         }  
         //---------------------------------------------------  
         // TOF:  
         if(TOF0){  
             cout << "PamLevel2::GetYodaTree() --- level0 TOF not implemented "<<endl;  
         }  
4282    
4283      };      dbc->Close(); // EMILIANO, do not leave open connections, open only when needed
4284        delete dbc;
4285        dbc=0;
4286    
4287  //    cout << l0_tree << endl;    };
       
     return l0_tree;  
4288    
4289      if (TRK0) {
4290        if(!dbc || (dbc && !dbc->IsConnected()))SetDBConnection();
4291        TrkParams::SetCalib(run_obj, dbc);
4292        TrkParams::LoadCalib();
4293        if (!TrkParams::CalibIsLoaded()) {
4294          cout << " TTree* PamLevel2::GetYodaTree( ) -- WARNING -- Calibration not loaded" << endl;
4295        };
4296        if(dbc){
4297          dbc->Close(); // EMILIANO, do not leave open connections, open only when needed
4298          delete dbc;
4299          dbc=0;
4300        };
4301      }
4302      return l0_tree;
4303  }  }
4304    
4305  /**  /**
4306   * 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.
4307   */   */
4308  Int_t PamLevel2::GetYodaEntry(){  Int_t PamLevel2::GetYodaEntry() {
4309    
4310  //    cout << "Int_t PamLevel2::GetYodaEntry()"<<endl;    Long64_t iev = this->GetReadEntry();
4311      if(!GetYodaTree())return 0;  
4312          // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
4313      // if it is a full file (not preselected)
4314      // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
4315      //  if (SELLI == 0 || SELLI == 2 || !hasL0EE) {
4316    
4317        if (!GetYodaTree()){
4318          printf(" PamLevel2::GetYodaEntry() : ERROR no level0 file loaded!\n");
4319          return 0;
4320        }
4321    
4322        if (irunentry < 0) {
4323          if (DBG) cout << "Int_t PamLevel2::GetYodaEntry() -- ATTENZIONE -- irunentry negativo?!?! "<<(Int_t)irunentry<<endl;
4324          //      cout << "Int_t PamLevel2::GetYodaEntry() -- ATTENZIONE -- irunentry negativo?!?! "<<(Int_t)irunentry<<endl; // TOGLITOGLI
4325          irunentry = 0LL;
4326        }
4327      //  ---------------------------------      //  ---------------------------------
4328      //  if file is NOT a preselected file      //  if file is NOT a preselected file
4329      //  ---------------------------------      //  ---------------------------------
4330      Int_t quellagiusta = irunentry + run_obj->EV_FROM;      Long64_t quellagiusta = irunentry + (Long64_t)(run_obj->EV_FROM); // prevshift already included in irunentry
4331    
4332        if (DBG){
4333          cout << " irun "<< irun << " irunentry "<< irunentry<<" run_obj->EV_FROM "<<run_obj->EV_FROM <<" quella giusta "<<quellagiusta << endl;
4334          cout << " iroot "<<iroot<<" run_obj->ID_ROOT_L0 "<<run_obj->ID_ROOT_L0<<endl;
4335          cout << " time "<< abstime << endl;
4336        }
4337    
4338      if( !GetOrbitalInfo() ){      ULong64_t obt = 0;
4339          cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- missing OrbitalInfo "<<endl;      ULong64_t pktn = 0;
4340          return 0;      if (GetOrbitalInfo()) {
4341          obt = GetOrbitalInfo()->OBT;
4342          pktn = GetOrbitalInfo()->pkt_num;
4343        }
4344    
4345        if (!GetOrbitalInfo() && !ISGP) {
4346          cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- missing OrbitalInfo " << endl;
4347          return 0;
4348        }
4349        if (obt == 0 && pktn == 0 && !ISGP) {
4350          cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- level2 event corrupted ?? " << endl;
4351          return 0;
4352      }      }
4353    
4354      // ---------------------------------------------------------------------      // ---------------------------------------------------------------------
# Line 2515  Int_t PamLevel2::GetYodaEntry(){ Line 4362  Int_t PamLevel2::GetYodaEntry(){
4362      // 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
4363      // is shift forward until when the packets match.      // is shift forward until when the packets match.
4364      // ---------------------------------------------------------------------      // ---------------------------------------------------------------------
4365      Int_t answer = 0;      Long64_t shift = 0LL;
4366      Int_t shift =0;      Long64_t answer = quellagiusta + shift + yprevshift;
4367      do{      Int_t readl0 = 0;
4368  //      if(shift>0){      readl0 = l0_tree->GetEntry(answer); // prevshift already included in irunentry
 //          cout << " level0 <--> level2 mismatch ( irun "<<irun<<" irunentry "<<irunentry<<" shift "<<shift<<" )"<<endl;  
 //      }  
         answer = GetYodaTree()->GetEntry(quellagiusta+shift);  
         shift++;  
         if( !GetEventHeader() ){  
             cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- missing EventHeader "<<endl;  
             return 0;  
         }  
 //      if( (quellagiusta+shift) == GetYodaTree()->GetEntries()+1 )cout << ">>> end of level0 tree <<<"<<endl;  
     }while( ( (UInt_t)(GetOrbitalInfo()->OBT) != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()) || GetOrbitalInfo()->pkt_num != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter())) && (quellagiusta+shift) < (UInt_t)(GetYodaTree()->GetEntries()) );  
4369    
4370  //    cout << "LA ENTRY GIUSTA E`: "<<quellagiusta<<" (spero...)"<<endl;      if (DBG){
4371  //    return GetYodaTree()->GetEntry(quellagiusta);        printf(" siamo qui shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);
4372            }
4373      return answer;  
4374    
4375        if (ISGP) {
4376          obt = (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()); //BARBATRUCCO
4377          pktn = (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter()); //BARBATRUCCO
4378        }
4379    
4380        while ( (obt != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()) || pktn != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter())) && (quellagiusta + (Long64_t) shift) < GetYodaTree()->GetEntries() && shift < maxshift ){
4381          if ( isSync && shift == 0LL ){
4382            printf(" PamLevel2::GetYodaEntry() ERROR! sync file but the level0 entry not found in place!!! \n");
4383            cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
4384            cout << "\nFor bug reporting instructions, please see for example:\n";
4385            cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
4386            cout << "  " << endl;
4387          }
4388          if (shift > 0) {
4389            if (DBG) cout << " PKTNUM  L2 --- " << pktn << " --- L0 --- " << GetEventHeader()->GetPscuHeader()->GetCounter() << endl;
4390            if (DBG)
4391              cout << "         RUN: ID " << GetRunInfo()->ID << " ID_ROOT_L0 " << run_obj->ID_ROOT_L0 << " ID_RUN_FRAG "
4392                   << GetRunInfo()->ID_RUN_FRAG << " EV_FROM " << GetRunInfo()->EV_FROM << endl;
4393            if (DBG)
4394              cout << "         L2 <--> L0 mismatch ( irun " << irun << " irunentry " << irunentry << " shift " << shift
4395                   << " prevshift " << prevshift << " )" << endl;
4396          }
4397          answer = quellagiusta +  shift+ yprevshift;
4398          readl0 = l0_tree->GetEntry(answer);
4399          //      printf(" inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);//TOGLITOGLI
4400    
4401          if (!GetEventHeader()) {
4402            cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- missing EventHeader " << endl;
4403            return 0;
4404          }
4405    
4406          //
4407          if (yprevshift != 0 && (quellagiusta + (Long64_t) shift) == GetYodaTree()->GetEntries()) {
4408            if (DBG) printf(" reset inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);
4409            //        printf(" reset inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);//TOGLITOGLI
4410            yprevshift = 0LL;
4411            shift = -1LL;
4412          };
4413            
4414          shift++;
4415        }
4416                                      
4417    
4418        if ( obt != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()) || pktn != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter()) ){
4419          if ( isSync ){
4420            printf(" PamLevel2::GetYodaEntry() ERROR! sync file but the level0 entry not found AT ALL!!! \n");
4421            cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
4422            cout << "\nFor bug reporting instructions, please see for example:\n";
4423            cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
4424            cout << "  " << endl;
4425          }
4426          cout << "Int_t PamLevel2::GetYodaEntry() -- WARNING -- " << endl;
4427          cout << " Big trouble here, no such event in Level0 data! (NB maxshift set to " << maxshift << " )" << endl;    
4428          cout << " Nested and/or DarthVader skipped packets in fragmented run? checking and trying to fix " <<endl;
4429          // query the DB for runs containing the event, loop over LEVEL0 files which could contain the level0 event and try to find it
4430          // 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
4431          // connect to db
4432          if (!dbc || (dbc && !dbc->IsConnected())) SetDBConnection(); //Emiliano
4433          //
4434          if (GetOrbitalInfo()){
4435            abstime = GetOrbitalInfo()->absTime;
4436          } else {
4437            printf(" PamLevel2::GetYodaEntry() ERROR! no OrbitalInfo, cannot get the absolute time for event \n");
4438            return 0;
4439          }
4440          // query DB looking for runs containing the processed event
4441          TSQLResult *pResult;
4442          TSQLRow *Row = NULL;
4443          TString myquery = Form("select ID,NEVENTS from GL_RUN where RUNHEADER_TIME<=%lld and RUNTRAILER_TIME>=%lld;",abstime,abstime);
4444          if ( DBG ) printf(" query is %s \n",myquery.Data());
4445          //      printf(" query is %s \n",myquery.Data());// TOGLITOGLI
4446          pResult = dbc->Query(myquery.Data());    
4447          if (!pResult->GetRowCount()){
4448            printf(" PamLevel2::GetYodaEntry() ERROR! event is not included in any run!!! \n");
4449            cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
4450            cout << "\nFor bug reporting instructions, please see for example:\n";
4451            cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
4452            cout << "  " << endl;
4453            return 0;
4454          }
4455          if ( pResult->GetRowCount() == 1 ){
4456            if (DBG) printf(" PamLevel2::GetYodaEntry() - WARNING - YodaEntry not found but only one run containing the event, it should not happen \n");
4457            //        printf(" PamLevel2::GetYodaEntry() - WARNING - YodaEntry not found but only one run containing the event, it should not happen \n");//TOGLITOGLI
4458          }
4459          for( Int_t ru=0; ru < pResult->GetRowCount(); ru++){ // loop over runs containing the event
4460            if (Row) delete Row;
4461            Row = pResult->Next();  
4462            if( Row == NULL ) break;
4463            UInt_t idrun = (UInt_t)atoll(Row->GetField(0));
4464            UInt_t nev = (UInt_t)atoll(Row->GetField(1));
4465            if (DBG) printf(" inside loop over runs: ru %i idrun %i nev %i \n",ru,idrun,nev);
4466            //        printf(" inside loop over runs: ru %i idrun %i nev %i \n",ru,idrun,nev);//TOGLITOGLI
4467    
4468            // now look for this run in the level2 file, it must be present! code is taken from updateruninfo of course
4469            Bool_t rfound = false;
4470            totrunentry = 0LL;
4471            runfirstentry = 0LL;
4472            for (Int_t r=0; r< run_tree->GetEntries();r++){
4473              run_tree->GetEntry(r);//update runinfo
4474              if ( r > 0 ){
4475                totrunentrymin = totrunentrymax+1;
4476              } else {
4477                totrunentrymin = 0LL;
4478              }
4479              totrunentry += GetRunInfo()->NEVENTS;
4480              totrunentrymax = totrunentry - 1 - prevshift; // prevshift is needed to handle nested+DV_skipped packets
4481              irun = r;        
4482    
4483              if (idrun == GetRunInfo()->ID){
4484                if ( totrunentrymin > iev ){ // there is a shift (nested+DV_skipped packets)
4485                  if (DBG) printf("PamLevel2::GetYodaEntry - unconsistent iev - nevents, probable DBL0-L2 async\n");
4486                  if (DBG) printf("PamLevel2::GetYodaEntry - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);
4487                  //              printf("PamLevel2::GetYodaEntry - unconsistent iev - nevents, probable DBL0-L2 async\n");
4488                  //              printf("PamLevel2::GetYodaEntry - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);//TOGLITOGLI
4489                  prevshift += (totrunentrymin-iev); // add the new shift to total shift
4490                  totrunentrymin -= (totrunentrymin-iev); // shift run position min
4491                  totrunentrymax -= (totrunentrymin-iev); // shift run position max
4492                  if (DBG) printf("PamLevel2::GetYodaEntry - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);
4493                  //              printf("PamLevel2::GetYodaEntry - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);//TOGLITOGLI
4494                }
4495                runfirstentry = totrunentrymin; // first entry of the run in the level2
4496              
4497    
4498                //
4499                if (gltsync)
4500                  delete gltsync; // Emiliano
4501                if (!dbc || (dbc && !dbc->IsConnected()))
4502                  SetDBConnection(); //Emiliano
4503                gltsync = new GL_TIMESYNC(GetRunInfo()->ID_ROOT_L0, "ID", dbc, false); // Emiliano
4504                if (dbc){
4505                  dbc->Close(); // Emiliano
4506                  delete dbc;
4507                  dbc=0;
4508                }          
4509                if (gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT) > gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT)) { // Emiliano
4510                  cout << "Bool_t PamLevel2::UpdateRunInfo(Long64_t iev) -- WARNING -- irun " << irun
4511                       << "  has RUNHEADER_OBT>=RUNTRAILER_OBT " << endl;
4512                  cout
4513                    << "                                                            (NB!! in this case some events could be assigned to a wrong run)"
4514                    << endl;
4515                }
4516                //
4517                if (DBG) printf(" found \n");
4518                //            printf(" found \n");//TOGLITOGLI
4519                rfound = true;
4520                //
4521                break;
4522              }
4523            } // loop over run
4524            if ( !rfound ){
4525              printf(" PamLevel2::GetYodaEntry() ERROR! run is not present in the level2 file!!! \n");
4526              cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
4527              cout << "\nFor bug reporting instructions, please see for example:\n";
4528              cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
4529              cout << "  " << endl;        
4530              return 0;
4531            }
4532    
4533            // here we got the first run and we can check if it contains the level0 event
4534            if (!GetYodaTree()){
4535              printf(" PamLevel2::GetYodaEntry() : ERROR no level0 file loaded!\n");
4536              return 0;
4537            }      
4538    
4539            // get the current run entry
4540            irunentry = iev - runfirstentry;
4541            if (irunentry < 0) {
4542              if (DBG) cout << "Int_t PamLevel2::GetYodaEntry() -- ATTENZIONE -- irunentry negativo?!?! "<<(Int_t)irunentry<<endl;
4543              //          cout << "Int_t PamLevel2::GetYodaEntry() -- ATTENZIONE -- irunentry negativo?!?! "<<(Int_t)irunentry<<endl; // TOGLITOGLI
4544              irunentry = 0LL;
4545            }
4546            //  ---------------------------------
4547            //  if file is NOT a preselected file
4548            //  ---------------------------------
4549            quellagiusta = irunentry + (Long64_t)(run_obj->EV_FROM); // prevshift already included in irunentry
4550          
4551            if (DBG){
4552              cout << " irun "<< irun << " irunentry "<< irunentry<<" run_obj->EV_FROM "<<run_obj->EV_FROM <<" quella giusta "<<quellagiusta << endl;
4553              cout << " iroot "<<iroot<<" run_obj->ID_ROOT_L0 "<<run_obj->ID_ROOT_L0<<endl;
4554              cout << " time "<< abstime << endl;
4555            }
4556            //        cout << " irun "<< irun << " irunentry "<< irunentry<<" run_obj->EV_FROM "<<run_obj->EV_FROM <<" quella giusta "<<quellagiusta << endl;
4557            //        cout << " iroot "<<iroot<<" run_obj->ID_ROOT_L0 "<<run_obj->ID_ROOT_L0<<endl;
4558            //        cout << " time "<< abstime << endl; // TOGLITOGLI
4559          
4560            shift = 0;
4561            answer = quellagiusta + shift + yprevshift; // prevshift already included in irunentry
4562            readl0 = l0_tree->GetEntry(answer); // prevshift already included in irunentry
4563    
4564            if (DBG){
4565              printf(" siamo qua shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);
4566            }
4567            //        printf(" siamo qua shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);//TOGLITOGLI
4568          
4569            while ( (obt != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()) || pktn != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter())) && (quellagiusta + (Long64_t) shift) < GetYodaTree()->GetEntries() && shift < maxshift ){
4570              if (shift > 0) {
4571                if (DBG) cout << " PKTNUM  L2 --- " << pktn << " --- L0 --- " << GetEventHeader()->GetPscuHeader()->GetCounter() << endl;
4572                if (DBG)
4573                  cout << "         RUN: ID " << GetRunInfo()->ID << " ID_ROOT_L0 " << run_obj->ID_ROOT_L0 << " ID_RUN_FRAG "
4574                       << GetRunInfo()->ID_RUN_FRAG << " EV_FROM " << GetRunInfo()->EV_FROM << endl;
4575                if (DBG)
4576                  cout << "         L2 <--> L0 mismatch ( irun " << irun << " irunentry " << irunentry << " shift " << shift
4577                       << " prevshift " << prevshift << " )" << endl;
4578              }
4579              answer = quellagiusta +  shift+ yprevshift;
4580              readl0 = l0_tree->GetEntry(answer);
4581              //          printf(" inside inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);//TOGLITOGLI
4582            
4583              if (!GetEventHeader()) {
4584                cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- missing EventHeader " << endl;
4585                return 0;
4586              }
4587              //
4588              if (yprevshift != 0 && (quellagiusta + (Long64_t) shift) == GetYodaTree()->GetEntries()) {
4589                if (DBG) printf(" reset inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);
4590                //            printf(" reset inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);//TOGLITOGLI
4591                yprevshift = 0;
4592                shift = -1;
4593              };
4594            
4595              shift++;
4596            }
4597          
4598            if ( obt != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()) || pktn != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter()) ){
4599              //still not the good run... continue with the nex one!
4600              printf("still not the good run... continue with the nex one!\n");
4601            } else {
4602              if (DBG) cout << "LA ENTRY GIUSTA E`: "<<quellagiusta<<" (spero...)"<<endl;
4603              //          cout << "LA ENTRY GIUSTA E`: "<<answer<<" (spero...)"<<endl;//TOGLITOGLI
4604              if (shift > 1) yprevshift = (shift - 1);
4605              if (Row) delete Row;
4606              delete pResult;  
4607              if (dbc){
4608                dbc->Close(); // Emiliano
4609                delete dbc;
4610                dbc=0;
4611              }    
4612              il0entry = answer;
4613              return readl0;
4614            }
4615            // perhaps it is all
4616          }// loop over runs containing the event
4617          if (Row) delete Row;
4618          delete pResult;  
4619          if (dbc){
4620            dbc->Close(); // Emiliano
4621            delete dbc;
4622            dbc=0;
4623          }          
4624          // arriving here it means no run found, cannot be! error!
4625          printf(" PamLevel2::GetYodaEntry() ERROR! run is not present in the level0 files!!! \n");
4626          cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
4627          cout << "\nFor bug reporting instructions, please see for example:\n";
4628          cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
4629          cout << "  " << endl;        
4630          return 0;
4631        } else {
4632          if (DBG) cout << "=> LA ENTRY GIUSTA E`: "<<answer<<" (spero...)"<<endl;
4633          //    cout << "=> LA ENTRY GIUSTA E`: "<<answer<<" (spero...)"<<endl;
4634          //    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()) );
4635          if (shift > 1) yprevshift = (shift - 1);
4636          il0entry = answer;
4637          return readl0;
4638        }
4639    
4640        /*  } // if selli 0 || 2
4641      if ( SELLI == 1 && hasL0EE ){
4642        sel_tree->GetEntry(iev);  
4643        Long64_t answer = il0entry;
4644        Int_t readl0 = 0;
4645        readl0 = l0_tree->GetEntry(answer);
4646        return readl0;
4647        }*/
4648      printf(" PamLevel2::GetYodaEntry() ERROR! \n");
4649      cout << " Entry not found! OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
4650      cout << "\nFor bug reporting instructions, please see for example:\n";
4651      cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
4652      cout << "  " << endl;
4653      return 0;
4654    }
4655    
4656    /**
4657     * \Brief Set DB connection
4658     */
4659    Bool_t PamLevel2::SetDBConnection() {
4660    
4661      //    cout << "PamLevel2::SetDBConnection()" << endl;
4662      if (DBG) {
4663        cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
4664        cout << "Connecting to DB" << endl;
4665        cout << "HOST " << host << endl;
4666        cout << "USER " << user << endl;
4667        cout << "PSW  " << psw << endl;
4668      }
4669      Bool_t notconn = true;
4670      Int_t trials = 0;
4671      while ( notconn && trials < 10 ){
4672        //    gSystem->Sleep(500);
4673        dbc = TSQLServer::Connect(host.Data(), user.Data(), psw.Data());
4674        //dbc->Connect(host.Data(), user.Data(), psw.Data());
4675        if ( dbc ) notconn = false;
4676        if (DBG) printf("<%i> test connection...\n ",trials);
4677        if (!dbc){
4678          if (DBG) printf(" :( failed, no pointer \n");
4679          notconn = true;
4680          //      return false;
4681        };
4682        if (dbc && !dbc->IsConnected()){
4683          if (DBG) printf(" :( failed, no connection \n");
4684          notconn = true;
4685          //      return false;
4686        };
4687        trials++;
4688      };
4689      if ( notconn ) return false;
4690      //
4691      if (DBG) printf("=connected!\n");
4692      stringstream myquery; // EMILIANO
4693      myquery.str(""); // EMILIANO
4694      myquery << "SET time_zone='+0:00'"; // EMILIANO
4695      dbc->Query(myquery.str().c_str()); // EMILIANO
4696      if ( DBG ) printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
4697      return true;
4698    
4699    }
4700    
4701    /**
4702     * \Brief Add a friend to the pamela chain.
4703     * @param cname name of the chain to be added
4704     */
4705    
4706    TChain* PamLevel2::AddFriend(TString cname) {
4707    
4708      if (!GetPamTree()) {
4709        cout << " TChain* PamLevel2::AddFriend(TString cname) --- a pamela tree must be created first" << endl;
4710        return NULL;
4711      }
4712    
4713      TChain *c = new TChain(cname.Data());
4714    
4715      TIter next(GetPamTree()->GetListOfFiles());
4716      Int_t nf = 0;
4717      TChainElement* element = 0;
4718      while ((element = (TChainElement*) next())) {
4719        c->Add(element->GetTitle());
4720        nf++;
4721      }
4722    
4723      GetPamTree()->AddFriend(cname.Data());
4724    
4725      cout << "external chain created and added to pamela friends :" << cname << endl;
4726      cout << "n.files " << nf << endl;
4727    
4728      return c;
4729    
4730    }
4731    
4732    /**
4733     * Returns the current read entry. This method simply returns the result of the call to
4734     * pam_tree->GetReadEntry(), so it is entirely handled by ROOT.
4735     */
4736    Long64_t PamLevel2::GetReadEntry() {
4737      return pam_tree->GetReadEntry();
4738    }
4739    
4740    /**
4741     * Sets the sorting method. If the new method is different from the previous, the issorted
4742     * flag is set to false, forcing a new sort the next time GetTrack is called.
4743     * @see GetTrack
4744     */
4745    void PamLevel2::SetSortingMethod(TString how) {
4746      if (howtosort != how) {
4747        issorted = false;
4748      }
4749      howtosort = how;
4750  }  }

Legend:
Removed from v.1.25  
changed lines
  Added in v.1.93

  ViewVC Help
Powered by ViewVC 1.1.23