/[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.27 by pam-fi, Fri Mar 16 20:34:08 2007 UTC revision 1.110 by pam-fi, Tue Mar 24 09:15:01 2015 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;    trk_ext_track = 0;
282      tof_track  = 0;    calo_track = 0;
283      candeleteobj = 0;    tof_track = 0;
284  };    orb_track = 0;
285      candeleteobj = 0;
286      pscore = 0;
287      iscore = 0;
288    }
289    ;
290  //--------------------------------------  //--------------------------------------
291  //  //
292  //  //
293  //--------------------------------------  //--------------------------------------
294  /**  /**
295   * Constructor   * Constructor
296   */   */
297  PamTrack::PamTrack(TrkTrack* t, CaloTrkVar* c, ToFTrkVar* o){  PamTrack::PamTrack(TrkTrack* t, CaloTrkVar* c, ToFTrkVar* o, OrbitalInfoTrkVar *r) {
298    
299      trk_track  = 0;    trk_ext_track = 0;
300      calo_track = 0;    trk_track = 0;
301      tof_track  = 0;    calo_track = 0;
302  //     if(t)trk_track  = new TrkTrack(*t);    tof_track = 0;
303  //     if(c)calo_track = new CaloTrkVar(*c);    orb_track = 0;
304  //     if(o)tof_track  = new ToFTrkVar(*o);    //     if(t)trk_track  = new TrkTrack(*t);
305      if(t)trk_track  = t;    //     if(c)calo_track = new CaloTrkVar(*c);
306      if(c)calo_track = c;    //     if(o)tof_track  = new ToFTrkVar(*o);
307      if(o)tof_track  = o;  //   if (t)
308      candeleteobj = 0;  //     trk_track = t;
309    //   if (c)
310    //     calo_track = c;
311    //   if (o)
312    //     tof_track = o;
313    //   if (r)
314    //     orb_track = r;
315    
316    //   candeleteobj = 0;
317    
318    
319      if (t){
320          trk_track = new TrkTrack(*t);
321          trk_ext_track = new ExtTrack(*t);//NB!! ha dimensione 6 invece che 8
322      }
323      if (c)
324        calo_track = new CaloTrkVar(*c);
325      if (o)
326        tof_track = new ToFTrkVar(*o);
327      if (r)
328        orb_track = new OrbitalInfoTrkVar(*r);
329      candeleteobj = 1;
330    
331  };  }
332  PamTrack::PamTrack(const PamTrack& track){  ;
333    /**
334     * Constructor
335     */
336    PamTrack::PamTrack(ExtTrack* t, CaloTrkVar* c, ToFTrkVar* o, OrbitalInfoTrkVar *r) {
337    
338      TrkTrack   *t = track.trk_track;    trk_ext_track = 0;
339      CaloTrkVar *c = track.calo_track;    trk_track = 0;
340      ToFTrkVar  *o = track.tof_track;    calo_track = 0;
341      tof_track = 0;
342      orb_track = 0;
343      //     if(t)trk_track  = new TrkTrack(*t);
344      //     if(c)calo_track = new CaloTrkVar(*c);
345      //     if(o)tof_track  = new ToFTrkVar(*o);
346    //   if (t)
347    //     trk_track = t;
348    //   if (c)
349    //     calo_track = c;
350    //   if (o)
351    //     tof_track = o;
352    //   if (r)
353    //     orb_track = r;
354    
355    //   candeleteobj = 0;
356    
357    
358      if (t){
359    ////      trk_track = new TrkTrack(*t);//in this case TrkTrack object remains null
360          trk_ext_track = new ExtTrack(*t);
361      }
362      if (c)
363        calo_track = new CaloTrkVar(*c);
364      if (o)
365        tof_track = new ToFTrkVar(*o);
366      if (r)
367        orb_track = new OrbitalInfoTrkVar(*r);
368      candeleteobj = 1;
369      pscore = 0;
370      iscore = 0;
371    
372      trk_track  = 0;  }
373      calo_track = 0;  ;
374      tof_track  = 0;  
375      if(t)trk_track  = new TrkTrack(*t);  PamTrack::PamTrack(const PamTrack& track) {
376      if(c)calo_track = new CaloTrkVar(*c);  
377      if(o)tof_track  = new ToFTrkVar(*o);    TrkTrack *t = track.trk_track;
378      candeleteobj = 1;    ExtTrack *e = track.trk_ext_track;
379      CaloTrkVar *c = track.calo_track;
380      ToFTrkVar *o = track.tof_track;
381      OrbitalInfoTrkVar *r = track.orb_track;
382    
383      trk_ext_track = 0;
384      trk_track     = 0;
385      calo_track    = 0;
386      tof_track     = 0;
387      orb_track     = 0;
388      if(e)
389          trk_ext_track = new ExtTrack(*e);
390      if (t)
391        trk_track = new TrkTrack(*t);
392      if (c)
393        calo_track = new CaloTrkVar(*c);
394      if (o)
395        tof_track = new ToFTrkVar(*o);
396      if (r)
397        orb_track = new OrbitalInfoTrkVar(*r);
398    
399      candeleteobj = 1;
400      pscore = 0;
401      iscore = 0;
402    
403    }
404    
405    void PamTrack::Copy( PamTrack& track) const {
406    
407        track.trk_track = trk_track;
408        track.trk_ext_track = trk_ext_track;
409        track.calo_track = calo_track;
410        track.tof_track = tof_track;
411        track.orb_track = orb_track;
412        
413        track.candeleteobj = candeleteobj;
414        track.pscore = pscore;
415        track.iscore = iscore;
416            
417  }  }
 void PamTrack::Clear(){  
418    
419  //    cout << "PamTrack::Clear() "<<candeleteobj<<endl;  
420      if(candeleteobj){  
421          if(trk_track)  trk_track->TrkTrack::Clear();  void PamTrack::Clear(Option_t *option) {
422          if(calo_track) calo_track->CaloTrkVar::Clear();//???  
423          if(tof_track)  tof_track->ToFTrkVar::Clear();//???  //    cout << "PamTrack::Clear( "<<option<<" ) "<<candeleteobj<<endl;
424      }else{    if (candeleteobj) {
425          trk_track  = 0;        
426          calo_track = 0;      if (trk_ext_track)
427          tof_track  = 0;        trk_ext_track->ExtTrack::Clear(option);
428      }      if (trk_track)
429  }        trk_track->TrkTrack::Clear();
430  void PamTrack::Delete(){      if (calo_track)
431  //    cout << "PamTrack::Delete() "<<candeleteobj<<endl;        calo_track->CaloTrkVar::Clear();//???
432      if(candeleteobj){      if (tof_track)
433          if(trk_track)  {        tof_track->ToFTrkVar::Clear();//???
434              trk_track->TrkTrack::Clear();      if (orb_track)
435              delete trk_track;        orb_track->OrbitalInfoTrkVar::Clear();//???
436          }    }
437          if(calo_track){    else {
438              calo_track->CaloTrkVar::Clear();//???      trk_ext_track = 0;
439              delete calo_track;      trk_track = 0;
440          }      calo_track = 0;
441          if(tof_track){      tof_track = 0;
442              tof_track->ToFTrkVar::Clear();//???      orb_track = 0;
443              delete tof_track;    }
444          }    pscore = 0;
445      }else{    iscore = 0;
446          Clear();  
447    }
448    void PamTrack::Delete() {
449      //    cout << "PamTrack::Delete() "<<candeleteobj<<endl;
450      if (candeleteobj) {
451        if (trk_ext_track) {
452    //      trk_ext_track->ExtTrack::Clear("C");//Clear is called for all the array elements
453            trk_ext_track->ExtTrack::Clear("C+C");//Clear is called for all the array elements passing option 'C'
454          delete trk_ext_track;
455        }
456        if (trk_track) {
457          trk_track->TrkTrack::Clear();
458          delete trk_track;
459      }      }
460        if (calo_track) {
461          calo_track->CaloTrkVar::Clear();//???
462          delete calo_track;
463        }
464        if (tof_track) {
465          tof_track->ToFTrkVar::Clear();//???
466          delete tof_track;
467        }
468        if (orb_track) {
469          orb_track->OrbitalInfoTrkVar::Clear();//???
470          delete orb_track;
471        }
472      }
473      else {
474        Clear();
475      }
476  }  }
477    
478    
479    
480    
481  //--------------------------------------  //--------------------------------------
482  //  //
483  //  //
484  //--------------------------------------  //--------------------------------------
485  /**  /**
486   * Constructor   * Default Constructor
487   */   */
488  PamLevel2::PamLevel2(){  PamLevel2::PamLevel2() {
489              Initialize();
490  //     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;  
491    
     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;  
492    
493        /**
494     * Constructor
495     * @param ddir Name of directory where level2 files are stored.
496     * @param list Name of an ascii file containing the list of file names
497     * @param detlist Options to chose what to load.
498     * Possible options are:
499     *       +AUTO --> load all trees/branches in the input files
500     *       +(-)ALL --> inlcude(exclude) all trees/branches
501     *       +(-)TRK1+(-)TRK2+(-)CAL1+(-)CAL2+(-)TOF+(-)TRG+(-)ND+(-)S4+(-)ORB+(-)AC --> inlcude(exclude) trees and branches
502     *       +(-)TRK0 --> include(exclude) tracker level0 tree
503     *       +(-)GP --> include exclude GPAMELA output tree
504     * If no options are specified, the default is assumed. Default is:
505     * +TRK2+CAL2+CAL1+TOF+TRG+ND+AC+S4+ORB
506     */
507    PamLevel2::PamLevel2(TString ddir, TString llist, TString detlist) {
508      Initialize();
509      TList* listf = GetListOfLevel2Files(ddir, llist);
510      if (listf)
511        GetPamTree(listf, detlist);
512      if (listf)
513        GetRunTree(listf);
514      SetMaxShift(-1);
515    }
516    
 //    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;  
517    
518      SELLI = -1;  PamLevel2::PamLevel2(TString ddir, TList *llist, TString detlist) {
519      Initialize();
520      GetPamTree(llist, detlist);
521      GetRunTree(llist);
522      SetMaxShift(-1);
523    }
524    
525    /**
526     * Constructor
527     * @param ddir Name of directory where level2 files are stored.
528     * @param list Name of an ascii file containing the list of file names
529     * Default trees/branches are loaded. Default is:
530     * +TRK2+CAL2+CAL1+TOF+TRG+ND+AC+S4+ORB
531     */
532    PamLevel2::PamLevel2(TString ddir, TString llist) {
533      Initialize();
534      TList* listf = GetListOfLevel2Files(ddir, llist);
535      cout << "GetPamTree: "<<endl;
536      GetPamTree(listf, "");
537      cout << "GetRunTree: "<<endl;
538      GetRunTree(listf);
539      SetMaxShift(-1);
540    }
541    
     tsorted=0;  
     timage=0;  
542    
543  };  void PamLevel2::Initialize() {
544    
545      h0_obj = 0;
546      trk0_obj = 0;
547      calo0_obj = 0;
548    
549      trk2_obj = 0;
550      trk1_obj = 0;
551      trkh_obj = 0;
552      calo1_obj = 0;
553      calo2_obj = 0;
554      tof2_obj = 0;
555      trig_obj = 0;
556      s4_obj = 0;
557      nd_obj = 0;
558      ac_obj = 0;
559      orb2_obj = 0;
560      gp_obj = 0;
561    
562      extAlgFlag=0;
563    
564      trk_ext_obj     = 0;
565      trk_ext_nuc_obj = 0;
566      trk_nuc_obj     = 0;
567      
568      calo_ext_obj     = 0;
569      calo_ext_nuc_obj = 0;
570      calo_nuc_obj     = 0;
571      
572      tof_ext_obj     = 0;
573      tof_ext_nuc_obj = 0;
574      tof_nuc_obj     = 0;
575      
576      orb_ext_obj     = 0;
577      orb_ext_nuc_obj = 0;
578      orb_nuc_obj     = 0;
579    
580      trk2_nuc_obj  = 0;
581      calo2_nuc_obj = 0;
582      tof2_nuc_obj  = 0;
583      orb2_nuc_obj  = 0;
584    
585    
586      run_obj = 0;//new GL_RUN();
587      soft_obj = 0;// Emiliano
588      proc_obj = 0;// Emiliano
589      irun = -1LL;
590      irunt = -1LL;
591      totrunentry = 0LL;
592      totrunentrymax = 0LL;
593      totrunentrymin = 0LL;
594      runfirstentry = 0LL;
595      runlastentry = 0LL;
596      gltsync = 0; // Emiliano
597      fUpdateRunInfo = true; // Emiliano
598      fUseDBinRunInfo = true; // Emiliano
599      fDiscarded = false; //EM
600      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
601      il0entry = 0LL;
602      //  hasL0EE = true;
603    
604      l0_file = NULL;
605      l0_tree = NULL;
606      iroot = -1;
607      dbc = 0;
608    
609      prevshift = 0;
610      yprevshift = 0;
611      maxshift = 10; //EMILIANO now overridden by SetMaxShift(-1) called by constructors
612    
613      run_tree = NULL;
614      run_tree_clone = NULL;
615    
616      proc_tree = NULL;
617      proc_tree_clone = NULL;
618    
619      sel_tree = NULL;
620      sel_tree_clone = NULL;
621    
622      irunentry = -1LL;
623      pam_tree = NULL;
624      for (Int_t i = 0; i < NCLONES; i++)
625        pam_tree_clone[i] = NULL;
626    
627      totdltime[0] = 0LL;
628      totdltime[1] = 0LL;
629      totdltime[2] = 0LL;
630    
631      host = "mysql://localhost/pamelaprod";
632      user = "anonymous";
633      psw = "";
634      const char *pamdbhost = gSystem->Getenv("PAM_DBHOST");
635      const char *pamdbuser = gSystem->Getenv("PAM_DBUSER");
636      const char *pamdbpsw = gSystem->Getenv("PAM_DBPSW");
637      if (!pamdbhost)
638        pamdbhost = "";
639      if (!pamdbuser)
640        pamdbuser = "";
641      if (!pamdbpsw)
642        pamdbpsw = "";
643      if (strcmp(pamdbhost, ""))
644        host = pamdbhost;
645      if (strcmp(pamdbuser, ""))
646        user = pamdbuser;
647      if (strcmp(pamdbpsw, ""))
648        psw = pamdbpsw;
649    
650      customString = "";
651    
652      //    sorted_tracks = 0;//new TRefArray();
653    
654      CAL0 = false;
655      CAL1 = true;
656      CAL2 = true;
657      TRK2 = true;
658      TRK1 = false;
659      TRK0 = false;
660      TRKh = false;
661      TRG = true;
662      TOF = true;
663      TOF0 = false;
664      S4 = true;
665      ND = true;
666      AC = true;
667      ORB = true;
668      PROC = true;
669      GP = false;
670    
671      EXT = false;
672      NUC = false;
673      trkAlg = "STD";//default tracking algorythm
674    
675      RUN = true;
676    
677      SELLI = -1;
678    
679      ISGP = false;
680    
681      DBG = false;
682    
683      tsorted = 0;
684      timage = 0;
685      text = 0 ;
686    
687      tsorted_nuc = 0;
688      timage_nuc = 0;
689      text_nuc = 0 ;
690    
691      howtosort = "+CAL+TOF";
692      //howtosort = "+TOF";
693      sortthr = 100.;
694    
695      issorted = false;
696      lastsorted = -1;
697      issorted_new = false;
698      lastsorted_new = -1;
699    
700    }
701    ;
702  /**  /**
703   * Delete the event (act as Dtor)   * Delete the event (act as Dtor)
704   */   */
705  void PamLevel2::Delete(){  void PamLevel2::Delete() {
           
     if(run_obj)delete run_obj;  
     if(soft_obj)delete soft_obj; //Emiliano  
706    
707  //    cout << "void PamLevel2::Clear()"<<endl;    if (run_obj)
708      if(h0_obj)   delete h0_obj;      delete run_obj;
709      if(trk0_obj) delete trk0_obj;          if (soft_obj)
710      if(trk1_obj) delete trk1_obj;            delete soft_obj; //Emiliano
711      if(trk2_obj) delete trk2_obj;    if (proc_obj)
712      if(trkh_obj) delete trkh_obj;      delete proc_obj; //Emiliano
713      if(calo1_obj)delete calo1_obj;  
714      if(calo2_obj)delete calo2_obj;    //    cout << "void PamLevel2::Clear()"<<endl;
715      if(tof_obj)  delete tof_obj;    if (h0_obj)
716      if(trig_obj) delete trig_obj;      delete h0_obj;
717      if(s4_obj)   delete s4_obj;    if (trk0_obj)
718      if(nd_obj)   delete nd_obj;      delete trk0_obj;
719      if(ac_obj)   delete ac_obj;    if (calo0_obj)
720      if(orb_obj)  delete orb_obj;      delete calo0_obj;
721          if (trk1_obj)
722      if(tsorted){      delete trk1_obj;
723          tsorted->Delete();    if (trk2_obj)
724          delete tsorted;      delete trk2_obj;
725      }    if (trkh_obj)
726      if(timage){      delete trkh_obj;
727          timage->Delete();    if (calo1_obj)
728          delete timage;      delete calo1_obj;
729      }    if (calo2_obj)
730        delete calo2_obj;
731      if (tof2_obj)
732        delete tof2_obj;
733      if (trig_obj)
734        delete trig_obj;
735      if (s4_obj)
736        delete s4_obj;
737      if (nd_obj)
738        delete nd_obj;
739      if (ac_obj)
740        delete ac_obj;
741      if (orb2_obj)
742        delete orb2_obj;
743      if (gp_obj)
744        delete gp_obj;
745    
746      if(trk_nuc_obj)trk_nuc_obj->Delete();
747      if(trk_ext_obj)trk_ext_obj->Delete();
748      if(trk_ext_nuc_obj)trk_ext_nuc_obj->Delete();
749    
750      if(calo_nuc_obj)calo_nuc_obj->Delete();
751      if(calo_ext_obj)calo_ext_obj->Delete();
752      if(calo_ext_nuc_obj)calo_ext_nuc_obj->Delete();
753    
754      if(tof_nuc_obj)tof_nuc_obj->Delete();
755      if(tof_ext_obj)tof_ext_obj->Delete();
756      if(tof_ext_nuc_obj)tof_ext_nuc_obj->Delete();
757    
758      if(orb_nuc_obj)orb_nuc_obj->Delete();
759      if(orb_ext_obj)orb_ext_obj->Delete();
760      if(orb_ext_nuc_obj)orb_ext_nuc_obj->Delete();
761    
762    
763      if(trk2_nuc_obj)trk2_nuc_obj->Delete();;
764      if( calo2_nuc_obj)calo2_nuc_obj->Delete();;
765      if(tof2_nuc_obj)tof2_nuc_obj->Delete();;
766      if(orb2_nuc_obj)orb2_nuc_obj->Delete();;
767      
768    
     if(dbc){  
         dbc->Close();  
         delete dbc;  
     }  
       
     if(l0_file)l0_file->Close();  
     if(pam_tree)pam_tree->Delete();;  
     if(run_tree)run_tree->Delete();;  
     if(sel_tree)sel_tree->Delete();;  
     for(Int_t i=0; i<NCLONES; i++ )if(pam_tree_clone[i])pam_tree_clone[i]->Delete();;  
     if(run_tree_clone)run_tree_clone->Delete();;  
     if(sel_tree_clone)sel_tree_clone->Delete();;  
       
769    
770  };    if (tsorted) {
771        tsorted->Delete();
772        delete tsorted;
773      }
774      if (timage) {
775        timage->Delete();
776        delete timage;
777      }
778      if (text) {
779        text->Delete();
780        delete text;
781      }
782      if (tsorted_nuc) {
783        tsorted_nuc->Delete();
784        delete tsorted_nuc;
785      }
786      if (timage_nuc) {
787        timage_nuc->Delete();
788        delete timage_nuc;
789      }
790      if (text_nuc) {
791        text_nuc->Delete();
792        delete text_nuc;
793      }
794    
795    
796    
797      if (dbc) {
798        dbc->Close();
799        delete dbc;
800        dbc=0;
801      }
802    
803      if (gltsync)
804        delete gltsync;
805    
806      if (l0_file)
807        l0_file->Close();
808      //    if(pam_tree)pam_tree->Delete();;
809    
810      if (pam_tree) {
811        //
812        // 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...
813        //
814        TList *temp = pam_tree->GetListOfFriends();
815        TList *contents = new TList; // create chain friend list
816        contents->SetOwner();
817        TIter next(temp);
818        TChain *questo = 0;
819        while ((questo = (TChain*) next())) {
820          TString name = questo->GetName();
821          contents->Add((TChain*) gROOT->FindObject(name.Data()));// add object to the list
822        };
823        //
824        // deleting the main chain
825        //
826        pam_tree->Delete();
827        //
828        // deleting the friends...
829        //
830        TIter next2(contents);
831        TChain *questa = 0;
832        while ( (questa = (TChain*)next2()) ) {
833          TString name = questa->GetName();
834          questa->Delete();
835          questa = NULL;
836        };
837        //
838      };
839      pam_tree = NULL;
840    
841      if (run_tree)
842        run_tree->Delete();;
843      if (sel_tree)
844        sel_tree->Delete();;
845    
846      // The following lines are commented out since they may generate a double delete error
847      // if the file containing the clone trees is closed. This is because the file owns the
848      // clone trees which are written into it, so it will delete them when it is closed; if
849      // also PamLevel2 will try to delete these trees, a double delete error will be generated
850      // when exiting from analysis program. (Nicola 28/11/2011)
851    
852      /*for (Int_t i = 0; i < NCLONES; i++)
853        if (pam_tree_clone[i])
854          pam_tree_clone[i]->Delete();;
855      if (run_tree_clone)
856        run_tree_clone->Delete();;
857      if (sel_tree_clone)
858        sel_tree_clone->Delete();;*/
859    
860      if (irunoffset)
861        delete[] irunoffset;
862    
863    
864      Initialize();
865    
866    }
867    ;
868    
869  /**  /**
870   * Clear the event (NB! does not deallocate objects)   * Clear the event (NB! does not deallocate objects)
871   */   */
872  void PamLevel2::Clear(){  void PamLevel2::Clear() {
           
 //    cout << "void PamLevel2::Clear()"<<endl;  
873    
874  //    //    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();  
875    
876      if(tsorted){    //
877          tsorted->Delete();    // 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
878      }    // want to load them for each event even if they are the same...
879      if(timage){    //
880          timage->Delete();    //    if(run_obj)delete run_obj;
881      }    //    if(run_obj) run_obj->Clear();  // Emiliano: Do not deallocate run_obj here, it will give segmentation fault! call clear instead
882          //    if(soft_obj) soft_obj->Clear();
883  };  
884      if (h0_obj)
885        h0_obj->Clear();
886      //    if(trk0_obj) trk0_obj->Clear();
887      if (trk1_obj)
888        trk1_obj->Clear();
889      if (trk2_obj)
890        trk2_obj->Clear();
891      if (trkh_obj)
892        trkh_obj->Clear();
893      if (calo0_obj)
894        calo0_obj->Clear();
895      if (calo1_obj)
896        calo1_obj->Clear();
897      if (calo2_obj)
898        calo2_obj->Clear();
899      if (tof2_obj)
900        tof2_obj->Clear();
901      if (trig_obj)
902        trig_obj->Clear();
903      if (s4_obj)
904        s4_obj->Clear();
905      if (nd_obj)
906        nd_obj->Clear();
907      if (ac_obj)
908        ac_obj->Clear();
909      if (orb2_obj)
910        orb2_obj->Clear();
911      if (gp_obj)
912        gp_obj->Clear();
913      if (proc_obj)
914        proc_obj->Clear();
915    
916      //    if(sorted_tracks)sorted_tracks->Clear();
917      //    sorted_tracks.Clear();
918    
919      if(trk_nuc_obj)trk_nuc_obj->Clear();
920      if(trk_ext_obj)trk_ext_obj->Clear();
921      if(trk_ext_nuc_obj)trk_ext_nuc_obj->Clear();
922    
923      if(calo_nuc_obj)calo_nuc_obj->Clear();
924      if(calo_ext_obj)calo_ext_obj->Clear();
925      if(calo_ext_nuc_obj)calo_ext_nuc_obj->Clear();
926    
927      if(tof_nuc_obj)tof_nuc_obj->Clear();
928      if(tof_ext_obj)tof_ext_obj->Clear();
929      if(tof_ext_nuc_obj)tof_ext_nuc_obj->Clear();
930    
931      if(orb_nuc_obj)orb_nuc_obj->Clear();
932      if(orb_ext_obj)orb_ext_obj->Clear();
933      if(orb_ext_nuc_obj)orb_ext_nuc_obj->Clear();
934    
935      if(trk2_nuc_obj)trk2_nuc_obj->Clear();;
936      if( calo2_nuc_obj)calo2_nuc_obj->Clear();;
937      if(tof2_nuc_obj)tof2_nuc_obj->Clear();;
938      if(orb2_nuc_obj)orb2_nuc_obj->Clear();;
939    
940      if (tsorted)tsorted->Delete();
941      if (timage)timage->Delete();
942      if (text) text->Delete();
943    
944      if (tsorted_nuc)tsorted_nuc->Delete();
945      if (timage_nuc)timage_nuc->Delete();
946      if (text_nuc) text_nuc->Delete();
947    }
948    ;
949    
950    void PamLevel2::Reset() {
951      //
952      // First of all clear everything
953      //
954      Clear();
955      //
956      // close and reset chains and pointers
957      //
958      if (pam_tree) {
959        //
960        // 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...
961        //
962        TList *temp = pam_tree->GetListOfFriends();
963        TList *contents = new TList; // create chain friend list
964        contents->SetOwner();
965        TIter next(temp);
966        TChain *questo = 0;
967        while ((questo = (TChain*) next())) {
968          TString name = questo->GetName();
969          contents->Add((TChain*) gROOT->FindObject(name.Data()));// add object to the list
970        };
971        //
972        // deleting the main chain
973        //
974        pam_tree->Delete();
975        //
976        // deleting the friends...
977        //
978        TIter next2(contents);
979        TChain *questa = 0;
980        while ( (questa = (TChain*) next2()) ) {
981          TString name = questa->GetName();
982          questa->Delete();
983          questa = NULL;
984        };
985        //
986      };
987      pam_tree = NULL;
988      //
989      if (run_tree)
990        run_tree->Delete();;
991      run_tree = NULL;
992      if (sel_tree)
993        sel_tree->Delete();;
994      sel_tree = NULL;
995    
996      if (proc_tree)
997        proc_tree->Delete();
998      proc_tree = NULL;
999      //
1000      // Close file
1001      //
1002      if (l0_file)
1003        l0_file->Close("R");
1004      l0_file = NULL;
1005      //
1006      h0_obj = 0;
1007      trk0_obj = 0;
1008      calo0_obj = 0;
1009      //
1010      trk2_obj = 0;
1011      trk1_obj = 0;
1012      trkh_obj = 0;
1013      calo1_obj = 0;
1014      calo2_obj = 0;
1015      tof2_obj = 0;
1016      trig_obj = 0;
1017      s4_obj = 0;
1018      nd_obj = 0;
1019      ac_obj = 0;
1020      orb2_obj = 0;
1021      gp_obj = 0;
1022      proc_obj = 0;
1023    
1024      trk_ext_obj     = 0;
1025      trk_ext_nuc_obj = 0;
1026      trk_nuc_obj     = 0;
1027      
1028      calo_ext_obj     = 0;
1029      calo_ext_nuc_obj = 0;
1030      calo_nuc_obj     = 0;
1031      
1032      tof_ext_obj     = 0;
1033      tof_ext_nuc_obj = 0;
1034      tof_nuc_obj     = 0;
1035      
1036      orb_ext_obj     = 0;
1037      orb_ext_nuc_obj = 0;
1038      orb_nuc_obj     = 0;
1039    
1040      trk2_nuc_obj  = 0;
1041      calo2_nuc_obj = 0;
1042      tof2_nuc_obj  = 0;
1043      orb2_nuc_obj  = 0;
1044    
1045      trk2_nuc_obj  = 0;
1046      calo2_nuc_obj = 0;
1047      tof2_nuc_obj  = 0;
1048      orb2_nuc_obj  = 0;
1049      //
1050      // Reset run pointers
1051      //
1052      run_obj = 0;//new GL_RUN();
1053      soft_obj = 0;// Emiliano
1054      proc_obj = 0;// Emiliano
1055      irun = -1;
1056      irunt = -1;
1057      totrunentry = 0LL;
1058      totrunentrymax = 0LL;
1059      totrunentrymin = 0LL;
1060      runfirstentry = 0ULL;
1061      runlastentry = 0ULL;
1062      prevabstime = 0ULL;
1063      prevpktnum = 0;
1064      abstime = 0ULL;
1065      pktnum = 0;
1066      isFragment = false;
1067      //
1068      totdltime[0] = 0LL;
1069      totdltime[1] = 0LL;
1070      totdltime[2] = 0LL;
1071      //
1072    }
1073    ;
1074    
1075    Bool_t PamLevel2::IsGood(Bool_t strict) {
1076      Bool_t goodev = true;
1077      //
1078      if (calo2_obj && !calo2_obj->IsGood(strict))
1079        goodev = false;
1080      //
1081      if (strict) {
1082        if (trk2_obj && trk2_obj->UnpackError() != 0)
1083          goodev = false;
1084        if (tof2_obj && tof2_obj->unpackError != 0)
1085          goodev = false;
1086        if (trig_obj && trig_obj->unpackError != 0)
1087          goodev = false;
1088        if (s4_obj && s4_obj->unpackError != 0)
1089          goodev = false;
1090        if (nd_obj && nd_obj->unpackError != 0)
1091          goodev = false;
1092        if (ac_obj && (ac_obj->unpackError != 0 || ((ac_obj->status[0] >> 2) & 1) || ((ac_obj->status[1] >> 2) & 1)))
1093          goodev = false;
1094        //  if(orb2_obj)
1095      }
1096      else {
1097        if (nd_obj && nd_obj->unpackError != 0)
1098          goodev = false;
1099        if (ac_obj && (ac_obj->unpackError != 0 || ((ac_obj->status[0] >> 2) & 1) || ((ac_obj->status[1] >> 2) & 1)))
1100          goodev = false;
1101      };
1102      return (goodev);
1103    }
1104    ;
1105    
1106    void PamLevel2::SkipRunInfoUpdate(){
1107      printf("\n\n ******** WARNING ******** \n Skip DB connections, DO NOT USE PamLevel2::GetRunInfo() method! \n\n");
1108      fUpdateRunInfo = false;
1109      this->SetSELLI(2);
1110      printf(" ===============> W A R N I N G <================ \n");
1111      printf(" in case PamLevel2::CreateCloneTrees() will be called \n");
1112      printf(" it will be reverted to PadmeAmidala level2 structure , i.e. NO SELECTIONLIST WILL BE CREATED IN THE NEW LEVEL2 FILE! \n\n");
1113      if ( run_tree_clone ){
1114        printf(" ===============> W A R N I N G <================ \n");
1115        printf(" PamLevel2::SkipRunIndoUpdate or PamLevel2::NoDBconnections() has been called together with PamLevel2::CreateCloneTrees() \n");
1116        printf(" TO AVOID CRASHES call PamLevel2::CreateCloneTrees() after PamLevel2::SkipRunIndoUpdate or PamLevel2::NoDBconnections() \n");    
1117      };
1118    }
1119    
1120    void PamLevel2::SetMaxShift(Int_t sh){
1121      if ( sh >=  0 ){
1122        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");
1123        maxshift = sh;
1124      } else {
1125        ULong64_t nev = GetEntries();
1126        ULong64_t runnev = 0ULL;
1127        for (Int_t r=0; r< run_tree->GetEntries();r++){
1128          run_tree->GetEntry(r);//update runinfo
1129          runnev += GetRunInfo()->NEVENTS;
1130        }
1131        maxshift = (Int_t)(runnev-nev) + 10; // +10 just to be conservative
1132        if ( (runnev-nev) == 0 ) isSync = true;
1133        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);
1134        //    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
1135      }
1136    }
1137    
1138  //--------------------------------------  //--------------------------------------
1139  //  //
1140  //  //
1141  //--------------------------------------  //--------------------------------------
1142  void *PamLevel2::GetPointerTo(const char* c ){  void *PamLevel2::GetPointerTo(const char* c) {
1143    
1144      TString objname = c;    TString objname = c;
1145    
1146      if(!objname.CompareTo("TrkLevel1"))  {    if (!objname.CompareTo("TrkLevel1")) {
1147          if(!trk1_obj){      if (!trk1_obj) {
1148              trk1_obj  = new TrkLevel1();        trk1_obj = new TrkLevel1();
1149              trk1_obj->Set();        trk1_obj->Set();
1150          }      }
1151          return &trk1_obj;      return &trk1_obj;
1152      };    };
1153      if(!objname.CompareTo("TrkLevel2"))  {    if (!objname.CompareTo("TrkLevel2")) {
1154          if(!trk2_obj){        if (!trk2_obj) {
1155              trk2_obj  = new TrkLevel2();        trk2_obj = new TrkLevel2();
1156              trk2_obj->Set();        trk2_obj->Set();
1157          }      }
1158          return &trk2_obj;      return &trk2_obj;
1159      };    };
1160      if(!objname.CompareTo("TrkHough"))   {    if (!objname.CompareTo("TrkHough")) {
1161          if(!trkh_obj)  trkh_obj  = new TrkHough();      if (!trkh_obj) {
1162          return &trkh_obj;        trkh_obj = new TrkHough();
1163      };        trkh_obj->Set();
1164      if(!objname.CompareTo("CaloLevel1")) {      }
1165          if(!calo1_obj) calo1_obj = new CaloLevel1();      return &trkh_obj;
1166          return &calo1_obj;    };
1167      };    if (!objname.CompareTo("CaloLevel1")) {
1168      if(!objname.CompareTo("CaloLevel2")) {      if (!calo1_obj)
1169          if(!calo2_obj){        calo1_obj = new CaloLevel1();
1170              calo2_obj = new CaloLevel2();      return &calo1_obj;
1171              calo2_obj->Set();    };
1172          };    if (!objname.CompareTo("CaloLevel2")) {
1173          return &calo2_obj;      if (!calo2_obj) {
1174      };        calo2_obj = new CaloLevel2();
1175      if(!objname.CompareTo("ToFLevel2"))  {        calo2_obj->Set();
         if(!tof_obj){  
             tof_obj   = new ToFLevel2();  
             tof_obj->Set();  
         }  
         return &tof_obj;  
     };  
     if(!objname.CompareTo("TrigLevel2")) {  
         if(!trig_obj)  trig_obj  = new TrigLevel2();  
         return &trig_obj;  
     };  
     if(!objname.CompareTo("S4Level2"))   {  
         if(!s4_obj)    s4_obj    = new S4Level2();  
         return &s4_obj;  
     };  
     if(!objname.CompareTo("NDLevel2"))   {  
         if(!nd_obj)    nd_obj    = new NDLevel2();  
         return &nd_obj;  
     };  
     if(!objname.CompareTo("AcLevel2"))   {  
         if(!ac_obj)    ac_obj    = new AcLevel2();  
         return &ac_obj;  
     };  
     if(!objname.CompareTo("OrbitalInfo")){  
         if(!orb_obj)   orb_obj   = new OrbitalInfo();  
         return &orb_obj;  
1176      };      };
1177            return &calo2_obj;
1178      if(!objname.CompareTo("RunInfo"))return &run_obj;    };
1179      if (!objname.CompareTo("ToFLevel2")) {
1180        if (!tof2_obj) {
1181          tof2_obj = new ToFLevel2();
1182          tof2_obj->Set();
1183        }
1184        return &tof2_obj;
1185      };
1186      if (!objname.CompareTo("TrigLevel2")) {
1187        if (!trig_obj)
1188          trig_obj = new TrigLevel2();
1189        return &trig_obj;
1190      };
1191      if (!objname.CompareTo("S4Level2")) {
1192        if (!s4_obj)
1193          s4_obj = new S4Level2();
1194        return &s4_obj;
1195      };
1196      if (!objname.CompareTo("NDLevel2")) {
1197        if (!nd_obj)
1198          nd_obj = new NDLevel2();
1199        return &nd_obj;
1200      };
1201      if (!objname.CompareTo("AcLevel2")) {
1202        if (!ac_obj)
1203          ac_obj = new AcLevel2();
1204        return &ac_obj;
1205      };
1206      if (!objname.CompareTo("OrbitalInfo")) {
1207        if (!orb2_obj) {
1208          orb2_obj = new OrbitalInfo();
1209          orb2_obj->Set();
1210        }
1211        return &orb2_obj;
1212      };
1213      //     if(!objname.CompareTo("OrbitalInfo")){
1214      //    if(!orb2_obj)   orb2_obj   = new OrbitalInfo();
1215      //    return &orb2_obj;
1216      //     };
1217      if (!objname.CompareTo("GPamela")) {
1218        if (!gp_obj)
1219          gp_obj = new GPamela();
1220        return &gp_obj;
1221      };
1222    
1223      if(!objname.CompareTo("SoftInfo"))return &soft_obj; // Emiliano    if (!objname.CompareTo("RunInfo"))
1224        return &run_obj;
1225    
1226      return NULL;    if (!objname.CompareTo("SoftInfo"))
1227  };      return &soft_obj; // Emiliano
1228    
1229      if (!objname.CompareTo("ProcInfo")){
1230        if (!proc_obj)
1231          proc_obj = new ProcInfo();    
1232        return &proc_obj; // Emiliano
1233      }
1234    
1235      return NULL;
1236    }
1237    ;
1238  //--------------------------------------  //--------------------------------------
1239  //  //
1240  //  //
1241  //--------------------------------------  //--------------------------------------
1242  /**  /**
1243   * Retrieves the calorimeter track matching the seqno-th tracker stored track.   * Retrieves the calorimeter track matching the seqno-th tracker stored track.
1244   * (If seqno = -1 retrieves the self-trigger calorimeter track)   * (If seqno = -1 retrieves the self-trigger calorimeter track)
1245   */   */
1246   CaloTrkVar *PamLevel2::GetCaloStoredTrack(int seqno){  CaloTrkVar *PamLevel2::GetCaloStoredTrack(int seqno) {
       
      if( !calo2_obj )return 0;  
1247    
1248       if( calo2_obj->CaloLevel2::ntrk()==0 ){    if (!calo2_obj)
1249           cout << "PamLevel2::GetCaloStoredTrack(int) : requested tracker SeqNo "<< seqno <<" but no Calorimeter tracks are stored"<<endl;      return 0;
          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;  
1250    
1251       if( tof_obj->ToFLevel2::ntrk()==0 ){    if (calo2_obj->CaloLevel2::ntrk() == 0) {
1252           cout << "PamLevel2::GetToFStoredTrack(int) : requested tracker SeqNo "<< seqno <<" but no ToF tracks are stored"<<endl;        if( seqno >=0 ){
1253           return NULL;            cout << "PamLevel2::GetCaloStoredTrack(int) : requested tracker SeqNo " << seqno;
1254       };            cout << " but no Calorimeter tracks are stored" << endl;
1255              }
1256       ToFTrkVar *c = 0;        return NULL;
1257       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;  
       
  };  
1258    
1259  //--------------------------------------    CaloTrkVar *c = 0;
1260   //    Int_t it_calo = 0;
  //  
 //--------------------------------------  
 /**  
  * 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;  
1261    
1262       CaloTrkVar *c = 0;    do {
1263       ToFTrkVar  *o = 0;      c = calo2_obj->CaloLevel2::GetCaloTrkVar(it_calo);
1264            it_calo++;
1265       if(CAL2) c = GetCaloStoredTrack(t->GetSeqNo());    } while (c && seqno != c->trkseqno && it_calo < calo2_obj->CaloLevel2::ntrk());
1266       if(TOF) o = GetToFStoredTrack(t->GetSeqNo());  
1267          if (!c || seqno != c->trkseqno) {
1268  //    if(t && c && o)track = new PamTrack(t,c,o);      c = 0;
1269       PamTrack *track = new PamTrack(t,c,o);      if (seqno != -1 && seqno>=0)
1270              cout << "PamLevel2::GetCaloStoredTrack(int) : requested tracker SeqNo " << seqno
1271       return track;            << " does not match Calorimeter stored tracks" << endl;
1272      };
1273   };    return c;
1274    
1275    }
1276    ;
1277  //--------------------------------------  //--------------------------------------
1278  //  //
1279  //  //
1280  //--------------------------------------  //--------------------------------------
1281  /**  /**
1282   * Retrieves the it-th stored track.   * Retrieves the ToF track matching the seqno-th tracker stored track.
1283   * It override TrkLevel2::GetTrack(int it).   * (If seqno = -1 retrieves the tracker-independent tof track)
  * @param itrk Track number, ranging from 0 to GetNTracks().  
1284   */   */
1285    ToFTrkVar *PamLevel2::GetToFStoredTrack(int seqno) {
1286    
1287  PamTrack* PamLevel2::GetStoredTrack(Int_t itrk){    if (!tof2_obj)
1288            return 0;
1289      cout <<"PamLevel2::GetStoredTrack(Int_t itrk) **to-be-updated** "<<endl;  
1290      cout <<"for the moment, better use separately the methods: TrkLevel2::GetStoredTrack(seqno) CaloLevel2::GetCaloTrkVar(Int_t notrack) ToFLevel2::GetToFTrkVar(Int_t notrack)"<<endl;    if (tof2_obj->ToFLevel2::ntrk() == 0) {
1291      cout <<"(if you use it, remember to delete the PamTrack object)"<<endl;      cout << "PamLevel2::GetToFStoredTrack(int) : requested tracker SeqNo " << seqno << " but no ToF tracks are stored"
1292      PamTrack *track = 0;          << endl;
1293            return NULL;
1294      if( itrk >=0 && itrk < trk2_obj->TrkLevel2::ntrk() ){    };
1295            
1296          TrkTrack *t = trk2_obj->TrkLevel2::GetStoredTrack(itrk);    ToFTrkVar *c = 0;
1297          track = GetPamTrackAlong(t);    Int_t it_tof = 0;
1298            
1299              do {
1300        c = tof2_obj->ToFLevel2::GetToFTrkVar(it_tof);
1301        it_tof++;
1302      } while (c && seqno != c->trkseqno && it_tof < tof2_obj->ToFLevel2::ntrk());
1303    
1304      if (!c || seqno != c->trkseqno) {
1305        c = 0;
1306        if (seqno != -1)
1307          cout << "PamLevel2::GetToFStoredTrack(int) : requested tracker SeqNo " << seqno
1308              << " does not match ToF stored tracks" << endl;
1309      };
1310      return c;
1311    
     }else{  
         cout << "PamLevel2::GetStoredTrack(int) : tracker track SeqNo "<< itrk <<" does not exist (GetNTracks() = "<<trk2_obj->TrkLevel2::GetNTracks()<<")"<<endl;  
     };  
       
     return track;  
       
1312  }  }
1313    ;
1314    
1315  //--------------------------------------  //--------------------------------------
1316  //  //
1317  //  //
1318  //--------------------------------------  //--------------------------------------
1319  /**  /**
1320   * Sort physical (tracker) tracks and stores them in the TRefArray (of TrkTrack objects) which pointer is  PamLevel2::sorted_tracks.   * Retrieves the OrbitalInfo track matching the seqno-th tracker stored track.
1321   * @param how String to set the sorting cryterium (es: "CAL" or "TRK+CAL+TOF" ecc...).   * (If seqno = -1 retrieves the tracker-independent tof related 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).  
1322   */   */
1323  void PamLevel2::SortTracks(TString how){  OrbitalInfoTrkVar *PamLevel2::GetOrbitalInfoStoredTrack(int seqno) {
1324    
1325  //    cout <<" PamLevel2::SortTracks(TString how) "<<endl;    if (!orb2_obj)
1326      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();  
1327    
1328  //    cout << "ObjectNumber  "<<ObjectNumber <<endl;    if (orb2_obj->OrbitalInfo::ntrk() == 0) {
1329        //       // TRICK BEGIN
1330  //     if(!sorted_tracks)sorted_tracks = new TRefArray();      //       OrbitalInfoTrkVar  *r = new OrbitalInfoTrkVar(); // TEMPORARY TRICK
1331  //     sorted_tracks->Clear();      //       Int_t nn = 0;
1332  //    sorted_tracks.Clear();      //       TClonesArray &tor = *orb2_obj->OrbitalInfoTrk;
1333        //       for(Int_t nt=0; nt < tof2_obj->ToFLevel2::ntrk(); nt++){
1334        //  //
1335        //  ToFTrkVar *ptt = tof2_obj->ToFLevel2::GetToFTrkVar(nt);
1336        //  if ( ptt->trkseqno != -1  ){
1337        //    //
1338        //    r->trkseqno = ptt->trkseqno;
1339        //    //
1340        //    r->Eij = 0;
1341        //    //
1342        //    r->Sij = 0;
1343        //    //
1344        //    r->pitch = -1000.;
1345        //    //
1346        //    r->cutoff = -1000.;
1347        //    //
1348        //    new(tor[nn]) OrbitalInfoTrkVar(*r);
1349        //    nn++;
1350        //    //
1351        //    r->Clear();
1352        //    //
1353        //  };
1354        //       };
1355        //       delete r;
1356        //       OrbitalInfoTrkVar *c = 0;
1357        //       c = orb2_obj->OrbitalInfo::GetOrbitalInfoTrkVar(0);
1358        //       return c;
1359        //       //TRICK END
1360        cout << "PamLevel2::GetOrbitalInfoStoredTrack(int) : requested tracker SeqNo " << seqno
1361            << " but no OrbitalInfo tracks are stored" << endl;
1362        return NULL;
1363      };
1364    
1365      if(!tsorted)tsorted = new TClonesArray("PamTrack",trk2_obj->GetNTracks());    OrbitalInfoTrkVar *c = 0;
1366      tsorted->Delete();    Int_t it_tof = 0;
     TClonesArray &ttsorted = *tsorted;  
     if(!timage)timage = new TClonesArray("PamTrack",trk2_obj->GetNTracks());  
     timage->Delete();  
     TClonesArray &ttimage = *timage;  
1367    
1368      do {
1369        c = orb2_obj->OrbitalInfo::GetOrbitalInfoTrkVar(it_tof);
1370        it_tof++;
1371      } while (c && seqno != c->trkseqno && it_tof < orb2_obj->OrbitalInfo::ntrk());
1372    
1373      if (!c || seqno != c->trkseqno) {
1374        c = 0;
1375        if (seqno != -1)
1376          cout << "PamLevel2::GetOrbitalInfoStoredTrack(int) : requested tracker SeqNo " << seqno
1377              << " does not match OrbitalInfo stored tracks" << endl;
1378      };
1379      return c;
1380    
1381      // loop over the tracks sorted by the tracker  }
1382      Bool_t use_TRK = how.Contains("TRK", TString::kIgnoreCase);  ;
     Bool_t use_CAL = how.Contains("CAL", TString::kIgnoreCase);  
     Bool_t use_TOF = how.Contains("TOF", TString::kIgnoreCase);  
       
     if( !CAL2 &&  use_CAL) use_CAL = false;  
     if( !TOF &&  use_TOF) use_TOF = false;  
       
     if( !TRK2 ){  
 //      cout << "SortTracks() : without tracker does not work!!! (not yet)" << endl;  
         return;  
     };  
1383    
1384      //   cout << "use_CAL "<<use_CAL<<" use_TOF "<<use_TOF<<" use_TRK "<<use_TRK <<endl;  //--------------------------------------
1385        //
1386      for(Int_t i=0; i < trk2_obj->TrkLevel2::GetNTracks(); i++){  //
1387            //--------------------------------------
1388          TrkTrack   *ts = 0;  // /**
1389          CaloTrkVar *cs = 0;  //  * Give the pamela track associated to a tracker track, retrieving related calorimeter, orbitalinfo and tof track information.
1390          ToFTrkVar  *os = 0;  //  */
1391            // PamTrack* PamLevel2::GetPamTrackAlong(TrkTrack* t) {
1392          // get tracker tracks  
1393          TrkTrack   *tp = trk2_obj->TrkLevel2::GetTrack(i);                    //tracker  //   cout << "PamLevel2::GetPamTrackAlong(TrkTrack* t) **obsolete** " << endl;
1394          CaloTrkVar *cp = GetCaloStoredTrack(tp->GetSeqNo());  //   cout << "(if you use it, remember to delete the PamTrack object)" << endl;
1395          ToFTrkVar  *op = GetToFStoredTrack(tp->GetSeqNo());  
1396    //   CaloTrkVar *c = 0;
1397          TrkTrack   *ti = 0;              //tracker (image)  //   ToFTrkVar *o = 0;
1398          CaloTrkVar *ci = 0;  //   OrbitalInfoTrkVar *r = 0;
1399          ToFTrkVar  *oi = 0;  
1400  //      cout << "trk track n. "<<i << " "<<hex<< tp <<dec<< endl;  //   if (CAL2)
1401          // if track has an image, check image selection  //     c = GetCaloStoredTrack(t->GetSeqNo());
1402          if(tp->HasImage()){  //   if (TOF)
1403                //     o = GetToFStoredTrack(t->GetSeqNo());
1404              ti = trk2_obj->TrkLevel2::GetTrackImage(i);              //tracker (image)  //   if (ORB)
1405              ci = GetCaloStoredTrack(ti->GetSeqNo());  //     r = GetOrbitalInfoStoredTrack(t->GetSeqNo());
             oi = GetToFStoredTrack(ti->GetSeqNo());  
               
 //          cout << "its image "<<i << " "<<hex<< ti <<dec<< endl;  
1406    
1407              //assign starting scores  //   //    if(t && c && o)track = new PamTrack(t,c,o);
1408              Int_t tp_score = 0;  //main track sorted by the tracker  //   PamTrack *track = new PamTrack(t, c, o, r);
             Int_t ti_score = 0;  //image track  
               
             // ------------------------  
             // calorimeter check  
             // ------------------------  
             // check the Y spatial residual on the first calorimeter plane  
             // (cut on calorimeter variables from Emiliano)  
             if( use_CAL && !calo2_obj ){  
                 cout << "void PamLevel2::SortTracks(TString how): how= "<<how<<" but CaloLevel2 not loaded !!!";  
                 return;  
             };  
             if(  
                 use_CAL            &&  
                 calo2_obj->npcfit[1] > 15     &&   //no. of fit planes on Y view  
                 calo2_obj->varcfit[1] < 1000. &&  //fit variance on Y view  
                 cp && ci &&  
                 true){  
1409    
1410                    //   return track;
                 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++;  
1411    
1412  //              cout << "CALO "<<tp_score<<ti_score<<endl;  // }
1413    // ;
1414    //--------------------------------------
1415    //
1416    //
1417    //--------------------------------------
1418    // /**
1419    //  * Retrieves the it-th stored track.
1420    //  * It override TrkLevel2::GetTrack(int it).
1421    //  * @param itrk Track number, ranging from 0 to GetNTracks().
1422    //  */
1423    
1424    // PamTrack* PamLevel2::GetStoredTrack(Int_t itrk) {
1425    
1426    //   cout << "PamLevel2::GetStoredTrack(Int_t itrk) **to-be-updated** " << endl;
1427    //   cout
1428    //       << "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)"
1429    //       << endl;
1430    //   cout << "(if you use it, remember to delete the PamTrack object)" << endl;
1431    //   PamTrack *track = 0;
1432    
1433    //   if (itrk >= 0 && itrk < trk2_obj->TrkLevel2::ntrk()) {
1434    
1435    //     TrkTrack *t = trk2_obj->TrkLevel2::GetStoredTrack(itrk);
1436    //     track = GetPamTrackAlong(t);
1437    
1438    //   }
1439    //   else {
1440    //     cout << "PamLevel2::GetStoredTrack(int) : tracker track SeqNo " << itrk << " does not exist (GetNTracks() = "
1441    //         << trk2_obj->TrkLevel2::GetNTracks() << ")" << endl;
1442    //   };
1443    
1444              };  //   return track;
             // ------------------------  
             // TOF check  
             // ------------------------      
             // check the number of hit pmts along the track  
             // on S12 S21 and S32, where paddles are parallel to Y axis  
             if( use_TOF && !tof_obj ){  
                 cout << "void PamLevel2::SortTracks(TString how): how= "<<how<<" but ToFLevel2 not loaded !!!";  
                 return;  
             };  
             if( use_TOF && op && oi ){  
                   
                 Int_t nphit_p =0;  
                 Int_t nphit_i =0;  
                   
                   
 /*                              cout << "track: npmtadc "<< op->npmtadc << endl;  
                                 cout << "track: npmttdc "<< op->npmttdc << endl;  
                                 cout << "image: npmtadc "<< oi->npmtadc << endl;  
                                 cout << "image: npmttdc "<< oi->npmttdc << endl;*/  
                   
                 for (Int_t ih=0; ih < op->npmtadc; ih++){  
                     Int_t pl = tof_obj->GetPlaneIndex( (op->pmtadc).At(ih) );  
                     if(pl == 1 || pl == 2 || pl == 5)nphit_p++;  
                 };  
                   
                 for (Int_t ih=0; ih < oi->npmtadc; ih++){  
                     Int_t pl = tof_obj->GetPlaneIndex( (oi->pmtadc).At(ih) );  
                     if(pl == 1 || pl == 2 || pl == 5)nphit_i++;  
                 };  
                   
                 if(  
                     use_TOF            &&  
                     (nphit_p+nphit_i) !=0 &&      
                     true){  
                       
                     if( nphit_p >= nphit_i) tp_score++;  
                     else ti_score++;  
                 };  
 //              cout << "TOF "<<tp_score<<ti_score<<endl;  
             };  
             if(tp_score == ti_score) use_TRK = true;  
             // ------------------------  
             // tracker check  
             // ------------------------  
             // chi**2 difference is not always large enough to distinguish among  
             // the real track and its image.  
             // Tracker check will be applied always when calorimeter and tof information is ambiguous.  
             if(use_TRK){  
                 if(      tp->chi2 > 0 && tp->chi2 < ti->chi2 ) tp_score++ ;  
                 else if( ti->chi2 > 0 && ti->chi2 < tp->chi2 ) ti_score++ ;  
 //              cout << "TRK "<<tp_score<<ti_score<<endl;  
             };  
               
             // ------------------------  
             // the winner is....  
             // ------------------------      
             if      (tp_score > ti_score) {  
 //              ts = tp;//the track sorted by the tracker!!  
 //              cs = cp;  
 //              os = op;  
             }else if (tp_score < ti_score) {  
                 ts = ti;//its image!!  
                 cs = ci;  
                 os = oi;  
   
                 ti = tp;//its image!!  
                 ci = cp;  
                 oi = op;  
   
                 tp = ts;//its image!!  
                 cp = cs;  
                 op = os;  
1445    
1446                    // }
1447              }else {  //--------------------------------------
1448  //              ts = tp;  //
1449  //              cs = cp;  
1450  //              os = op;  /**
1451  //                              cout << "Warning - track image ambiguity not solved" << endl;   * Sort physical (tracker) tracks. Left here as backward compatibility method.
1452  //                              cout << ts->GetNtot() << " "<< ts->chi2 << " " << npcfit[1] << " "<< nphit_p << endl;   **/
1453              };  void PamLevel2::SortTracks(TString how) {
1454                  printf(
1455          }else{        " WARNING! obsolete, use SortTracks() and SetSortingMethod(TString) instead! \n Setting sorting method to %s \n",
1456  //          ts = tp;        how.Data());
1457  //          cs = cp;    howtosort = how;
1458  //          os = op;    SortTracks();
1459          };  }
1460            ;
1461  //      cout <<" SortTracks() "<<i<<" -- "<<ts<<endl;  
1462  //      sorted_tracks->Add(ts);//save the track in the sorted array  //
1463  //      sorted_tracks.Add(ts);//save the track in the sorted array  //--------------------------------------
1464  //      sorted_tracks.Add(tp);//save the track in the sorted array  /**
1465  //      cout << "SortTracks:: sorted_tracks->Add(it) "<<i<<" "<<ts<<endl;   * Sort physical (tracker) tracks.
1466  //      cout<<"o "<<tp<<endl;   * @param how String to set the sorting cryterium (es: "CAL" or "TRK+CAL+TOF" ecc...).
1467  //      cout<<"o "<<cp<<endl;   * Sorting cryteria:
1468  //      cout<<"o "<<op<<endl;   * TRK: lower chi**2
1469          new(ttsorted[i]) PamTrack(tp,cp,op);   * CAL: lower Y spatial residual on the first calorimeter plane
1470          new(ttimage[i])  PamTrack(ti,ci,oi);   * TOF: bigger numebr of hit PMTs along the track, on S12 S21 S32 (where paddles are along the Y axis).
1471      };   * S1: (ask Emiliano)
1472     * S2: (ask Emiliano)
1473      if( tsorted->GetEntries() != trk2_obj->GetNTracks() ){   * S3: (ask Emiliano)
1474          cout << "void PamLevel2::SortTracks(TString how): tsorted->GetEntries() "<<tsorted->GetEntries()<<" != trk2_obj->GetNTracks() = "<<trk2_obj->GetNTracks() <<endl;   * GP: more GP hits
1475          tsorted->Delete(); tsorted=0;   * The default sorting cryterium is "TOF+CAL".
1476          timage->Delete(); timage=0;       *
1477      }   * 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).
1478     */
1479      //Restore Object count  void PamLevel2::SortTracks() {
1480      //To save space in the table keeping track of all referenced objects  
1481      //We reset the object count to what it was at the beginning of the event.    //Check if the current event has already been sorted
1482      TProcessID::SetObjectCount(ObjectNumber);    if (issorted && lastsorted == GetReadEntry()) {
1483        return;
1484      }
1485      //Reset the sort flags, just in case something will go wrong...
1486      issorted = false;
1487      lastsorted = -1;
1488    
1489      TString how = howtosort;
1490    
1491      //  cout <<" PamLevel2::SortTracks(TString how) "<<endl;
1492      if (!trk2_obj) {
1493        cout << "void PamLevel2::SortTracks():  TrkLevel2 not loaded !!!";
1494        return;
1495      };
1496      //Save current Object count
1497      Int_t ObjectNumber = TProcessID::GetObjectCount();
1498    
1499      // create TCloneArrays to store tracks and its images
1500    //   if (!tsorted)
1501    //     tsorted = new TClonesArray("PamTrack", trk2_obj->GetNTracks());
1502    //   tsorted->Clear("C+C");//Delete();
1503    //   if (!timage)
1504    //     timage = new TClonesArray("PamTrack", trk2_obj->GetNTracks());
1505    //   timage->Clear("C+C");//Delete();
1506    
1507      if(tsorted)delete tsorted;
1508      if(timage) delete timage;
1509      tsorted = new TClonesArray("PamTrack", trk2_obj->GetNTracks());
1510      timage = new TClonesArray("PamTrack", trk2_obj->GetNTracks());
1511    
1512    
1513      TClonesArray &ttsorted = *tsorted;
1514      TClonesArray &ttimage = *timage;
1515    
1516    
1517    
1518      //--------------------------------------------------
1519      // retrieve sorting method
1520      //--------------------------------------------------
1521      Bool_t use_TRK = how.Contains("TRK", TString::kIgnoreCase);
1522      Bool_t use_CAL = how.Contains("CAL", TString::kIgnoreCase);
1523      Bool_t use_TOF = how.Contains("TOF", TString::kIgnoreCase);
1524      Bool_t use_S1 = how.Contains("S1", TString::kIgnoreCase);
1525      Bool_t use_S2 = how.Contains("S2", TString::kIgnoreCase);
1526      Bool_t use_S3 = how.Contains("S3", TString::kIgnoreCase);
1527      Bool_t use_GP = how.Contains("GP", TString::kIgnoreCase);
1528    
1529      if (use_TOF) {
1530        use_S1 = true;
1531        use_S2 = true;
1532        use_S3 = true;
1533      };
1534      if (!CAL2 && use_CAL)
1535        use_CAL = false;
1536      if (!TOF) {
1537        use_TOF = false;
1538        use_S1 = false;
1539        use_S2 = false;
1540        use_S3 = false;
1541      }
1542      if (!GP) {
1543        use_GP = false;
1544      }
1545    
1546      if (!TRK2) {
1547        cout << "SortTracks() : without tracker does not work!!! (not yet)" << endl;
1548        return;
1549      };
1550    
1551      //   cout << "use_CAL "<<use_CAL<<" use_TOF "<<use_TOF<<" use_TRK "<<use_TRK <<endl;
1552    
1553    
1554      //--------------------------------------------------
1555      // loop over "physical" tracks sorted by the tracker
1556      //--------------------------------------------------
1557      for (Int_t i = 0; i < trk2_obj->TrkLevel2::GetNTracks(); i++) {
1558    
1559        TrkTrack *ts = 0;
1560        CaloTrkVar *cs = 0;
1561        ToFTrkVar *os = 0;
1562        OrbitalInfoTrkVar *rs = 0;
1563    
1564        // get tracker tracks
1565        TrkTrack *tp = trk2_obj->TrkLevel2::GetTrack(i); //tracker
1566        CaloTrkVar *cp = GetCaloStoredTrack(tp->GetSeqNo());
1567        ToFTrkVar *op = GetToFStoredTrack(tp->GetSeqNo());
1568        OrbitalInfoTrkVar *rp = GetOrbitalInfoStoredTrack(tp->GetSeqNo());
1569    
1570        TrkTrack *ti = 0; //tracker (image)
1571        CaloTrkVar *ci = 0;
1572        ToFTrkVar *oi = 0;
1573        OrbitalInfoTrkVar *ri = 0;
1574        //  cout << "trk track n. "<<i << " "<<hex<< tp <<dec<< endl;
1575        // if track has an image, check image selection
1576    
1577        Int_t tp_score = 0; //main track sorted by the tracker
1578        Int_t ti_score = 0; //image track
1579        Int_t totp_score = 0; //main track sorted by the tracker
1580        Int_t toti_score = 0; //image track
1581    
1582        if (tp->HasImage()) {
1583    
1584          ti = trk2_obj->TrkLevel2::GetTrackImage(i); //tracker (image)
1585          ci = GetCaloStoredTrack(ti->GetSeqNo());
1586          oi = GetToFStoredTrack(ti->GetSeqNo());
1587          ri = GetOrbitalInfoStoredTrack(ti->GetSeqNo());
1588    
1589          //            cout << "its image "<<i << " "<<hex<< ti <<dec<< endl;
1590    
1591          //assign starting scores
1592          tp_score = 0; //main track sorted by the tracker
1593          ti_score = 0; //image track
1594    
1595          // -----------------------------------------------------------------------------------------
1596          // *****************************************************************************************
1597          // -----------------------------------------------------------------------------------------
1598          // calorimeter check
1599          // -----------------------------------------------------------------------------------------
1600          if (use_CAL && !calo2_obj) {
1601            cout << "void PamLevel2::SortTracks(): howtosort= " << how << " but CaloLevel2 not loaded !!!";
1602            return;
1603          };
1604          if (use_CAL && !cp && ci) {
1605            ti_score++;
1606            toti_score++;
1607          };
1608          if (use_CAL && cp && !ci) {
1609            tp_score++;
1610            totp_score++;
1611          };
1612          if (use_CAL && cp && ci && true) {
1613    
1614            if (cp->npresh > ci->npresh && true) {
1615              tp_score++;
1616              totp_score++;
1617            };
1618            if (cp->npresh < ci->npresh && true) {
1619              ti_score++;
1620              toti_score++;
1621            };
1622    
1623            //      cout << "CALO "<<tp_score<<ti_score<<endl;
1624    
1625          };
1626          // -----------------------------------------------------------------------------------------
1627          // *****************************************************************************************
1628          // -----------------------------------------------------------------------------------------
1629          // TOF check
1630          // -----------------------------------------------------------------------------------------
1631          // check the number of hit pmts along the track
1632          // on S12 S21 and S32, where paddles are parallel to Y axis
1633          if ((use_TOF || use_S1 || use_S2 || use_S3) && !tof2_obj) {
1634            cout << "void PamLevel2::SortTracks(): howtosort= " << how << " but ToFLevel2 not loaded !!!";
1635            return;
1636          };
1637          //
1638          if ((use_TOF || use_S1 || use_S2 || use_S3) && !op && oi) {
1639            ti_score++;
1640            toti_score++;
1641          };
1642          if ((use_TOF || use_S1 || use_S2 || use_S3) && op && !oi) {
1643            tp_score++;
1644            totp_score++;
1645          };
1646          if ((use_TOF || use_S1 || use_S2 || use_S3) && op && oi) {
1647            //
1648            Float_t sen = 0.;
1649            for (Int_t ih = 0; ih < op->npmtadc; ih++) {
1650              Int_t pl = tof2_obj->GetPlaneIndex((op->pmtadc).At(ih));
1651              if (pl == 2 || pl == 3 || pl == 4 || pl == 5)
1652                sen += (op->dedx).At(ih);
1653            };
1654            for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
1655              Int_t pl = tof2_obj->GetPlaneIndex((oi->pmtadc).At(ih));
1656              if (pl == 2 || pl == 3 || pl == 4 || pl == 5)
1657                sen += (oi->dedx).At(ih);
1658            };
1659            //
1660            if (sen >= sortthr && false) { // temporary disabled NUCLEI special algorithm since the new one should work for every particle (to be checked!)
1661              //printf(" IS A NUCLEUS! en = %f \n",sen);
1662              //
1663              // is a nucleus use a different algorithm
1664              //
1665              Int_t nz = 6;
1666              Float_t zin[6]; // << define TOF z-coordinates
1667              for (Int_t ip = 0; ip < nz; ip++)
1668                zin[ip] = tof2_obj->ToFLevel2::GetZTOF(tof2_obj->ToFLevel2::GetToFPlaneID(ip)); // << read ToF plane z-coordinates
1669              Trajectory *tr = new Trajectory(nz, zin);
1670              //
1671              Int_t nphit_p = 0;
1672              Int_t nphit_i = 0;
1673              Float_t enhit_p = 0.;
1674              Float_t enhit_i = 0.;
1675              //
1676              for (Int_t ih = 0; ih < op->npmtadc; ih++) {
1677                Int_t pl = tof2_obj->GetPlaneIndex((op->pmtadc).At(ih));
1678                if (pl == 1 || pl == 2 || pl == 5) {
1679                  nphit_p++;
1680                  enhit_p += (op->dedx).At(ih);
1681                };
1682              };
1683              //
1684              tp->DoTrack2(tr);
1685              //
1686              if (fabs(tr->y[0] - oi->ytofpos[0]) < 2.) {
1687                for (Int_t ih = 0; ih < op->npmtadc; ih++) {
1688                  Int_t pl = tof2_obj->GetPlaneIndex((op->pmtadc).At(ih));
1689                  if (pl == 0) {
1690                    nphit_p++;
1691                    enhit_p += (op->dedx).At(ih);
1692                  };
1693                };
1694              };
1695              if (fabs(tr->y[3] - oi->ytofpos[1]) < 2.) {
1696                for (Int_t ih = 0; ih < op->npmtadc; ih++) {
1697                  Int_t pl = tof2_obj->GetPlaneIndex((op->pmtadc).At(ih));
1698                  if (pl == 3) {
1699                    nphit_p++;
1700                    enhit_p += (op->dedx).At(ih);
1701                  };
1702                };
1703              };
1704              if (fabs(tr->y[4] - oi->ytofpos[2]) < 2.) {
1705                for (Int_t ih = 0; ih < op->npmtadc; ih++) {
1706                  Int_t pl = tof2_obj->GetPlaneIndex((op->pmtadc).At(ih));
1707                  if (pl == 4) {
1708                    nphit_p++;
1709                    enhit_p += (op->dedx).At(ih);
1710                  };
1711                };
1712              };
1713    
1714              for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
1715                Int_t pl = tof2_obj->GetPlaneIndex((oi->pmtadc).At(ih));
1716                if (pl == 1 || pl == 2 || pl == 5) {
1717                  nphit_i++;
1718                  enhit_i += (op->dedx).At(ih);
1719                };
1720              };
1721              //
1722              ti->DoTrack2(tr);
1723              //
1724              if (fabs(tr->y[0] - oi->ytofpos[0]) < 2.) {
1725                for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
1726                  Int_t pl = tof2_obj->GetPlaneIndex((oi->pmtadc).At(ih));
1727                  if (pl == 0) {
1728                    nphit_i++;
1729                    enhit_i += (op->dedx).At(ih);
1730                  };
1731                };
1732              };
1733              if (fabs(tr->y[3] - oi->ytofpos[1]) < 2.) {
1734                for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
1735                  Int_t pl = tof2_obj->GetPlaneIndex((oi->pmtadc).At(ih));
1736                  if (pl == 3) {
1737                    nphit_i++;
1738                    enhit_i += (op->dedx).At(ih);
1739                  };
1740                };
1741              };
1742              if (fabs(tr->y[4] - oi->ytofpos[2]) < 2.) {
1743                for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
1744                  Int_t pl = tof2_obj->GetPlaneIndex((oi->pmtadc).At(ih));
1745                  if (pl == 4) {
1746                    nphit_i++;
1747                    enhit_i += (op->dedx).At(ih);
1748                  };
1749                };
1750              };
1751    
1752              if ((use_TOF || use_S1 || use_S2 || use_S3) && (nphit_p + nphit_i) != 0 && true) {
1753    
1754                //      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);
1755                //      printf(" score p %i score i %i \n",tp_score,ti_score);
1756                //            if( enhit_p > enhit_i ) tp_score++;
1757                //            if( nphit_p >= nphit_i && enhit_p > enhit_i ) tp_score++;
1758                if (nphit_p > nphit_i)
1759                  tp_score++;
1760                if (nphit_p < nphit_i)
1761                  ti_score++;
1762                if (nphit_p == nphit_i) {
1763                  if (enhit_p > enhit_i)
1764                    tp_score++;
1765                  else
1766                    ti_score++;
1767                };
1768                //      printf(" dopo score p %i score i %i \n",tp_score,ti_score);
1769              };
1770              delete tr;
1771              //
1772            }
1773            else {
1774              // -------------
1775              // NOT a NUCLEUS
1776              // -------------
1777              //printf(" NOT a NUCLEUS! en = %f \n",sen);
1778    
1779              Int_t nphit_p = 0;
1780              Int_t nphit_i = 0;
1781    
1782              /*                            cout << "track: npmtadc "<< op->npmtadc << endl;
1783               cout << "track: npmttdc "<< op->npmttdc << endl;
1784               cout << "image: npmtadc "<< oi->npmtadc << endl;
1785               cout << "image: npmttdc "<< oi->npmttdc << endl;*/
1786    
1787              //      for (Int_t ih=0; ih < op->npmtadc; ih++){
1788              //        Int_t pl = tof2_obj->GetPlaneIndex( (op->pmtadc).At(ih) );
1789              //        if(pl == 1 || pl == 2 || pl == 5)nphit_p++;
1790              //      };
1791    
1792              //      for (Int_t ih=0; ih < oi->npmtadc; ih++){
1793              //        Int_t pl = tof2_obj->GetPlaneIndex( (oi->pmtadc).At(ih) );
1794              //        if(pl == 1 || pl == 2 || pl == 5)nphit_i++;
1795              //      };
1796              // --- modified to count tdc signals (more efficient?)
1797              // --- and to implement check on tdcflag
1798              for (Int_t ih = 0; ih < op->npmttdc; ih++) {
1799                Int_t pl = tof2_obj->GetPlaneIndex((op->pmttdc).At(ih));
1800                //      if( (op->tdcflag).At(ih)==0 && (pl == 1 || pl == 2 || pl == 5) )nphit_p++;
1801                if ((use_S1 && (pl == 0 || pl == 1)) || (use_S2 && (pl == 2 || pl == 3))
1802                    || (use_S3 && (pl == 4 || pl == 5))) {
1803                  if ((op->tdcflag).At(ih) == 0)
1804                    nphit_p++;
1805                };
1806              };
1807    
1808              for (Int_t ih = 0; ih < oi->npmttdc; ih++) {
1809                Int_t pl = tof2_obj->GetPlaneIndex((oi->pmttdc).At(ih));
1810                //      if( (oi->tdcflag).At(ih)==0 && (pl == 1 || pl == 2 || pl == 5) )nphit_i++;
1811                if ((use_S1 && (pl == 0 || pl == 1)) || (use_S2 && (pl == 2 || pl == 3))
1812                    || (use_S3 && (pl == 4 || pl == 5))) {
1813                  if ((oi->tdcflag).At(ih) == 0)
1814                    nphit_i++;
1815                };
1816              };
1817    
1818              if ((nphit_p + nphit_i) != 0 && true) {
1819    
1820                if (nphit_p != nphit_i) {
1821                  totp_score += nphit_p;
1822                  toti_score += nphit_i;
1823                  tp_score += nphit_p;
1824                  ti_score += nphit_i;
1825                };
1826                //      if     ( nphit_p > nphit_i) tp_score+=nphit_p;
1827                //      else if( nphit_p < nphit_i) ti_score+=nphit_i;
1828                //      else ;//niente
1829              };
1830            };
1831            //      cout << "TOF "<<tp_score<<ti_score<<endl;
1832          };
1833    
1834          //      if(tp_score == ti_score) use_TRK = true;
1835    
1836    
1837          // -----------------------------------------------------------------------------------------
1838          // *****************************************************************************************
1839          // -----------------------------------------------------------------------------------------
1840          // tracker check
1841          // -----------------------------------------------------------------------------------------
1842          // chi**2 difference is not always large enough to distinguish among
1843          // the real track and its image.
1844          // Tracker check will be applied always when calorimeter and tof information is ambiguous.
1845          // *** MODIFIED ON AUGUST 2007 ***
1846          if (use_TRK) {
1847            //      if(      tp->chi2 > 0 && tp->chi2 < ti->chi2 ) tp_score++ ;
1848            //      else if( ti->chi2 > 0 && ti->chi2 < tp->chi2 ) ti_score++ ;
1849    
1850            // CHECK 1 : number of points along X
1851            if (tp->GetNX() >= ti->GetNX()) {
1852              tp_score++;
1853              totp_score++;
1854            };
1855            if (tp->GetNX() <= ti->GetNX()) {
1856              ti_score++;
1857              toti_score++;
1858            };
1859            // CHECK 2 : number of points along Y
1860            if (tp->GetNY() >= ti->GetNY()) {
1861              tp_score++;
1862              totp_score++;
1863            };
1864            if (tp->GetNY() <= ti->GetNY()) {
1865              ti_score++;
1866              toti_score++;
1867            };
1868    
1869            //      cout << "TRK "<<tp_score<<ti_score<<endl;
1870          };
1871    
1872          // -----------------------------------------------------------------------------------------
1873          // *****************************************************************************************
1874          // -----------------------------------------------------------------------------------------
1875          // GPamela check
1876          // -----------------------------------------------------------------------------------------
1877    
1878          //---------------------------------------------------
1879          // count the number of GP hits
1880          //---------------------------------------------------
1881          if (use_GP) {
1882            int ngphits_p = 0;
1883            int ngphits_i = 0;
1884            float toll = 0.02; //200 micron
1885            for (int ih = 0; ih < GetGPamela()->Nthspe; ih++) {
1886              int ip = (Int_t) GetGPamela()->Itrpb[ih] - 1;
1887              if (tp && tp->YGood(ip) && fabs(tp->ym[ip] - GetGPamela()->Yavspe[ih]) < toll && true)
1888                ngphits_p++;
1889              if (ti && ti->YGood(ip) && fabs(ti->ym[ip] - GetGPamela()->Yavspe[ih]) < toll && true)
1890                ngphits_i++;
1891            }
1892            if (ngphits_p > ngphits_i && true) {
1893              tp_score++;
1894              totp_score++;
1895            }
1896            if (ngphits_p < ngphits_i && true) {
1897              ti_score++;
1898              toti_score++;
1899            }
1900          }
1901    
1902          // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
1903          // the winner is....
1904          // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
1905          if (tp_score > ti_score) {
1906    
1907          }
1908          else if (tp_score < ti_score) {
1909    
1910            ts = ti;//its image!!
1911            cs = ci;
1912            os = oi;
1913            rs = ri;
1914            Int_t totis = toti_score;
1915    
1916            ti = tp;//its image!!
1917            ci = cp;
1918            oi = op;
1919            ri = rp;
1920    
1921            tp = ts;//its image!!
1922            cp = cs;
1923            op = os;
1924            rp = rs;
1925    
1926            toti_score = totp_score;
1927            totp_score = totis;
1928    
1929          }
1930          else {
1931    
1932            //      cout << "Warning - track image ambiguity not solved" << endl;
1933    
1934          };
1935    
1936        }
1937        else {
1938          totp_score = 1;
1939          toti_score = 0;
1940    
1941          //            ts = tp;
1942          //            cs = cp;
1943          //            os = op;
1944        };
1945    
1946        //  cout <<" SortTracks() "<<i<<" -- "<<ts<<endl;
1947        //  sorted_tracks->Add(ts);//save the track in the sorted array
1948        //  sorted_tracks.Add(ts);//save the track in the sorted array
1949        //  sorted_tracks.Add(tp);//save the track in the sorted array
1950        //  cout << "SortTracks:: sorted_tracks->Add(it) "<<i<<" "<<ts<<endl;
1951        //  cout<<"o "<<tp<<endl;
1952        //  cout<<"o "<<cp<<endl;
1953        //  cout<<"o "<<op<<endl;
1954    
1955        new (ttsorted[i]) PamTrack(tp, cp, op, rp);
1956        new (ttimage[i]) PamTrack(ti, ci, oi, ri);
1957    
1958        ((PamTrack*) (ttsorted[i]))->SetPScore(totp_score);
1959        ((PamTrack*) (ttsorted[i]))->SetIScore(toti_score);
1960        ((PamTrack*) (ttimage[i]))->SetPScore(totp_score);
1961        ((PamTrack*) (ttimage[i]))->SetIScore(toti_score);
1962      };
1963    
1964      if (tsorted->GetEntries() != trk2_obj->GetNTracks()) {
1965        cout << "void PamLevel2::SortTracks(): tsorted->GetEntries() " << tsorted->GetEntries()
1966            << " != trk2_obj->GetNTracks() = " << trk2_obj->GetNTracks() << endl;
1967        tsorted->Delete();
1968        tsorted = 0;
1969        timage->Delete();
1970        timage = 0;
1971      }
1972    
1973      //Restore Object count
1974      //To save space in the table keeping track of all referenced objects
1975      //We reset the object count to what it was at the beginning of the event.
1976      TProcessID::SetObjectCount(ObjectNumber);
1977    
1978      //Everything went fine so the current event can be tagged as sorted
1979      issorted = true;
1980      lastsorted = GetReadEntry();
1981    
1982    }
1983    ;
1984    //
1985    //--------------------------------------
1986    /**
1987     * Sort physical (tracker) tracks.
1988     * @param how String to set the sorting cryterium (es: "CAL" or "TRK+CAL+TOF" ecc...).
1989     * Sorting cryteria:
1990     * TRK: lower chi**2
1991     * CAL: lower Y spatial residual on the first calorimeter plane
1992     * TOF: bigger numebr of hit PMTs along the track, on S12 S21 S32 (where paddles are along the Y axis).
1993     * S1: (ask Emiliano)
1994     * S2: (ask Emiliano)
1995     * S3: (ask Emiliano)
1996     * GP: more GP hits
1997     * The default sorting cryterium is "TOF+CAL".
1998     *
1999     * 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).
2000     *
2001     * New version, with handling of extended tracks and nuclei tracks.
2002     */
2003    void PamLevel2::SortTracksNew() {
2004    
2005      //--------------------------------------------------
2006      //Check if the current event has already been sorted
2007      //--------------------------------------------------
2008      if (issorted_new && lastsorted_new == GetReadEntry()) {
2009          return; //already done for this event
2010      }
2011    
2012    
2013    //  cout << "SORT" << endl;
2014    
2015      //Reset the sort flags, just in case something will go wrong...
2016      issorted_new = false;
2017      lastsorted_new = -1;
2018    
2019      //--------------------------------------------------
2020      // set input variables
2021      //--------------------------------------------------
2022    
2023      TString how = howtosort;
2024      //Save current Object count
2025      Int_t ObjectNumber = TProcessID::GetObjectCount();
2026    
2027    
2028    
2029    
2030      TrkLevel2  * trk2 ;
2031      CaloLevel2 * calo2;
2032      ToFLevel2  * tof2  ;
2033      OrbitalInfo  * orb2 ;
2034      
2035      TClonesArray * trkext ;
2036      TClonesArray * caloext;
2037      TClonesArray * tofext ;
2038      TClonesArray * orbext ;
2039    
2040    
2041    //   cout << "trk2_obj" << trk2_obj<< endl;
2042    //   cout << "trk2_nuc_obj" << trk2_nuc_obj<< endl;
2043    //   cout << " trk_ext_obj "<<trk_ext_obj<< endl;
2044    //   cout << " trk_ext_nuc_obj "<<trk_ext_nuc_obj<< endl;
2045    
2046      //-----------------------------------------------------------
2047      // create/reset TCloneArrays to store tracks and their images
2048      //-----------------------------------------------------------
2049    
2050    //  cout << " PamLevel2::SortTracksNew() --- Clear TClonesArray objects"<<endl;
2051      
2052      // main tracks from standard alg
2053    //   if (!tsorted)
2054    //       tsorted = new TClonesArray("PamTrack", trk2_obj->GetNTracks());
2055    //   tsorted->Clear("C+C");//Delete();
2056    //   // track images from standard alg
2057    //   if (!timage)
2058    //       timage = new TClonesArray("PamTrack", trk2_obj->GetNTracks());
2059    //   timage->Clear("C+C");//Delete();
2060    //   // tracks from extended algorythm
2061    //   if(EXT && !text)
2062    //       text = new TClonesArray("PamTrack",trk_ext_obj->GetEntries());
2063    //   if(text)text->Clear("C+C");//Delete();
2064    
2065      if(tsorted)delete tsorted;
2066      if(timage) delete timage;
2067      if(text)   delete text;
2068      tsorted = new TClonesArray("PamTrack", trk2_obj->GetNTracks());
2069      timage = new TClonesArray("PamTrack", trk2_obj->GetNTracks());
2070      text = new TClonesArray("PamTrack",trk_ext_obj->GetEntries());
2071    
2072      //-----------------------------------------------------------
2073      // create/reset TCloneArrays to store tracks and their images
2074      //-----------------------------------------------------------
2075      if(NUC){
2076    
2077          
2078          if(tsorted_nuc)delete tsorted_nuc;
2079          if(timage_nuc) delete timage_nuc;
2080          if(text_nuc)   delete text_nuc;
2081          tsorted_nuc = new TClonesArray("PamTrack", trk2_nuc_obj->GetNTracks());
2082          timage_nuc = new TClonesArray("PamTrack", trk2_nuc_obj->GetNTracks());
2083          text_nuc = new TClonesArray("PamTrack",trk_ext_nuc_obj->GetEntries());
2084    
2085      // main tracks from standard alg
2086    //       if (!tsorted_nuc)
2087    //        tsorted_nuc = new TClonesArray("PamTrack", trk2_nuc_obj->GetNTracks());
2088    //       tsorted_nuc->Clear("C+C");//Delete();
2089    //       // track images from standard alg
2090    //       if (!timage_nuc)
2091    //        timage_nuc = new TClonesArray("PamTrack", trk2_nuc_obj->GetNTracks());
2092    //       timage_nuc->Clear("C+C");//Delete();
2093    //       // tracks from extended algorythm
2094    //       if(EXT && !text_nuc)
2095    //        text_nuc = new TClonesArray("PamTrack",trk_ext_nuc_obj->GetEntries());
2096    //       if(text_nuc)text_nuc->Clear("C+C");//Delete();
2097    
2098      }
2099      //--------------------------------------------------
2100      // retrieve sorting method
2101      //--------------------------------------------------
2102      Bool_t use_TRK = how.Contains("TRK", TString::kIgnoreCase);
2103      Bool_t use_CAL = how.Contains("CAL", TString::kIgnoreCase);
2104      Bool_t use_TOF = how.Contains("TOF", TString::kIgnoreCase);
2105      Bool_t use_S1 = how.Contains("S1", TString::kIgnoreCase);
2106      Bool_t use_S2 = how.Contains("S2", TString::kIgnoreCase);
2107      Bool_t use_S3 = how.Contains("S3", TString::kIgnoreCase);
2108      Bool_t use_GP = how.Contains("GP", TString::kIgnoreCase);
2109    
2110      if (use_TOF) {
2111        use_S1 = true;
2112        use_S2 = true;
2113        use_S3 = true;
2114      };
2115      if (!CAL2 && use_CAL)
2116        use_CAL = false;
2117      if (!TOF) {
2118        use_TOF = false;
2119        use_S1 = false;
2120        use_S2 = false;
2121        use_S3 = false;
2122      }
2123      if (!GP) {
2124        use_GP = false;
2125      }
2126    
2127      if (!TRK2) {
2128        cout << "SortTracks() : without tracker does not work!!! (not yet)" << endl;
2129        return;
2130      };
2131    
2132    
2133      ///////////////////////////////////////////////////////////////////////////////////
2134      //
2135      //   sort tracks and fill PamTrack arrays
2136      //
2137      ///////////////////////////////////////////////////////////////////////////////////
2138      for(int doit=0; doit<2; doit++){
2139    
2140    //       cout << "doit "<<doit<<endl;
2141    
2142    
2143          if(doit == 0){
2144    
2145              trk2  = trk2_obj;
2146              calo2 = calo2_obj;
2147              tof2  = tof2_obj;
2148              orb2  = orb2_obj;
2149          
2150              trkext = trk_ext_obj;
2151              caloext = calo_ext_obj;
2152              tofext = tof_ext_obj;
2153              orbext = orb_ext_obj;
2154            
2155          
2156          
2157          
2158    
2159          }else if (doit == 1){
2160    
2161              if(!NUC)break;
2162    
2163          
2164              trk2  = trk2_nuc_obj;
2165              calo2 = calo2_nuc_obj;
2166              tof2  = tof2_nuc_obj;
2167              orb2  = orb2_nuc_obj;
2168          
2169              trkext = trk_ext_nuc_obj;
2170              caloext = calo_ext_nuc_obj;
2171              tofext = tof_ext_nuc_obj;
2172              orbext = orb_ext_nuc_obj;
2173          
2174          
2175          
2176    
2177          }
2178    
2179    //       cout << "trk2" << trk2<<endl;
2180    //       cout << "calo2" << calo2<<endl;
2181    //       cout << "tof2" << tof2<<endl;
2182    //       cout << "orb2" << orb2<<endl;
2183    //       cout << "trkext" <<trkext <<endl;
2184    //       cout << "tofext" << tofext<<endl;
2185    //       cout << "caloext" << caloext<<endl;
2186    //       cout << "orbext" << orbext<<endl;
2187    
2188          TClonesArray &ttext    = (doit==0 ? *text : *text_nuc);
2189          TClonesArray &ttimage  = (doit==0 ? *timage : *timage_nuc);
2190          TClonesArray &ttsorted = (doit==0 ? *tsorted : *tsorted_nuc);
2191      
2192    //       cout << "tsorted + timage "<<doit<<endl;
2193    
2194          //--------------------------------------------------
2195          // loop over "physical" tracks sorted by the tracker
2196          //--------------------------------------------------
2197          for (Int_t i = 0; i < trk2->TrkLevel2::GetNTracks(); i++) {
2198    
2199              TrkTrack *ts = 0;
2200              CaloTrkVar *cs = 0;
2201              ToFTrkVar *os = 0;
2202              OrbitalInfoTrkVar *rs = 0;
2203    
2204              // get tracker tracks
2205              TrkTrack *tp = trk2->GetTrack(i); //tracker
2206              CaloTrkVar *cp = calo2->GetCaloStoredTrack(tp->GetSeqNo());
2207              ToFTrkVar *op = tof2->GetToFStoredTrack(tp->GetSeqNo());
2208              OrbitalInfoTrkVar *rp = orb2->GetOrbitalInfoStoredTrack(tp->GetSeqNo());
2209    
2210              TrkTrack *ti = 0; //tracker (image)
2211              CaloTrkVar *ci = 0;
2212              ToFTrkVar *oi = 0;
2213              OrbitalInfoTrkVar *ri = 0;
2214              //    cout << "trk track n. "<<i << " "<<hex<< tp <<dec<< endl;
2215              // if track has an image, check image selection
2216    
2217              Int_t tp_score = 0; //main track sorted by the tracker
2218              Int_t ti_score = 0; //image track
2219              Int_t totp_score = 0; //main track sorted by the tracker
2220              Int_t toti_score = 0; //image track
2221    
2222              if (tp->HasImage()) {
2223    
2224                  ti = trk2->GetTrackImage(i); //tracker (image)
2225                  ci = calo2->GetCaloStoredTrack(ti->GetSeqNo());
2226                  oi = tof2->GetToFStoredTrack(ti->GetSeqNo());
2227                  ri = orb2->GetOrbitalInfoStoredTrack(ti->GetSeqNo());
2228    
2229                  //            cout << "its image "<<i << " "<<hex<< ti <<dec<< endl;
2230    
2231                  //assign starting scores
2232                  tp_score = 0; //main track sorted by the tracker
2233                  ti_score = 0; //image track
2234    
2235                  // -----------------------------------------------------------------------------------------
2236                  // *****************************************************************************************
2237                  // -----------------------------------------------------------------------------------------
2238                  // calorimeter check
2239                  // -----------------------------------------------------------------------------------------
2240                  if (use_CAL && !calo2) {
2241                      cout << "void PamLevel2::SortTracks(): howtosort= " << how << " but CaloLevel2 not loaded !!!";
2242                      return;
2243                  };
2244                  if (use_CAL && !cp && ci) {
2245                      ti_score++;
2246                      toti_score++;
2247                  };
2248                  if (use_CAL && cp && !ci) {
2249                      tp_score++;
2250                      totp_score++;
2251                  };
2252                  if (use_CAL && cp && ci && true) {
2253    
2254                      if (cp->npresh > ci->npresh && true) {
2255                          tp_score++;
2256                          totp_score++;
2257                      };
2258                      if (cp->npresh < ci->npresh && true) {
2259                          ti_score++;
2260                          toti_score++;
2261                      };
2262    
2263                      //    cout << "CALO "<<tp_score<<ti_score<<endl;
2264    
2265                  };
2266                  // -----------------------------------------------------------------------------------------
2267                  // *****************************************************************************************
2268                  // -----------------------------------------------------------------------------------------
2269                  // TOF check
2270                  // -----------------------------------------------------------------------------------------
2271                  // check the number of hit pmts along the track
2272                  // on S12 S21 and S32, where paddles are parallel to Y axis
2273                  if ((use_TOF || use_S1 || use_S2 || use_S3) && !tof2) {
2274                      cout << "void PamLevel2::SortTracks(): howtosort= " << how << " but ToFLevel2 not loaded !!!";
2275                      return;
2276                  };
2277                  //
2278                  if ((use_TOF || use_S1 || use_S2 || use_S3) && !op && oi) {
2279                      ti_score++;
2280                      toti_score++;
2281                  };
2282                  if ((use_TOF || use_S1 || use_S2 || use_S3) && op && !oi) {
2283                      tp_score++;
2284                      totp_score++;
2285                  };
2286                  if ((use_TOF || use_S1 || use_S2 || use_S3) && op && oi) {
2287                      //
2288                      Float_t sen = 0.;
2289                      for (Int_t ih = 0; ih < op->npmtadc; ih++) {
2290                          Int_t pl = tof2->GetPlaneIndex((op->pmtadc).At(ih));
2291                          if (pl == 2 || pl == 3 || pl == 4 || pl == 5)
2292                              sen += (op->dedx).At(ih);
2293                      };
2294                      for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
2295                          Int_t pl = tof2->GetPlaneIndex((oi->pmtadc).At(ih));
2296                          if (pl == 2 || pl == 3 || pl == 4 || pl == 5)
2297                              sen += (oi->dedx).At(ih);
2298                      };
2299                      //
2300                      if (sen >= sortthr && false) { // temporary disabled NUCLEI special algorithm since the new one should work for every particle (to be checked!)
2301                          //printf(" IS A NUCLEUS! en = %f \n",sen);
2302                          //
2303                          // is a nucleus use a different algorithm
2304                          //
2305                          Int_t nz = 6;
2306                          Float_t zin[6]; // << define TOF z-coordinates
2307                          for (Int_t ip = 0; ip < nz; ip++)
2308                              zin[ip] = tof2->GetZTOF(tof2->GetToFPlaneID(ip)); // << read ToF plane z-coordinates
2309                          Trajectory *tr = new Trajectory(nz, zin);
2310                          //
2311                          Int_t nphit_p = 0;
2312                          Int_t nphit_i = 0;
2313                          Float_t enhit_p = 0.;
2314                          Float_t enhit_i = 0.;
2315                          //
2316                          for (Int_t ih = 0; ih < op->npmtadc; ih++) {
2317                              Int_t pl = tof2->GetPlaneIndex((op->pmtadc).At(ih));
2318                              if (pl == 1 || pl == 2 || pl == 5) {
2319                                  nphit_p++;
2320                                  enhit_p += (op->dedx).At(ih);
2321                              };
2322                          };
2323                          //
2324                          tp->DoTrack2(tr);
2325                          //
2326                          if (fabs(tr->y[0] - oi->ytofpos[0]) < 2.) {
2327                              for (Int_t ih = 0; ih < op->npmtadc; ih++) {
2328                                  Int_t pl = tof2->GetPlaneIndex((op->pmtadc).At(ih));
2329                                  if (pl == 0) {
2330                                      nphit_p++;
2331                                      enhit_p += (op->dedx).At(ih);
2332                                  };
2333                              };
2334                          };
2335                          if (fabs(tr->y[3] - oi->ytofpos[1]) < 2.) {
2336                              for (Int_t ih = 0; ih < op->npmtadc; ih++) {
2337                                  Int_t pl = tof2->GetPlaneIndex((op->pmtadc).At(ih));
2338                                  if (pl == 3) {
2339                                      nphit_p++;
2340                                      enhit_p += (op->dedx).At(ih);
2341                                  };
2342                              };
2343                          };
2344                          if (fabs(tr->y[4] - oi->ytofpos[2]) < 2.) {
2345                              for (Int_t ih = 0; ih < op->npmtadc; ih++) {
2346                                  Int_t pl = tof2->GetPlaneIndex((op->pmtadc).At(ih));
2347                                  if (pl == 4) {
2348                                      nphit_p++;
2349                                      enhit_p += (op->dedx).At(ih);
2350                                  };
2351                              };
2352                          };
2353    
2354                          for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
2355                              Int_t pl = tof2->GetPlaneIndex((oi->pmtadc).At(ih));
2356                              if (pl == 1 || pl == 2 || pl == 5) {
2357                                  nphit_i++;
2358                                  enhit_i += (op->dedx).At(ih);
2359                              };
2360                          };
2361                          //
2362                          ti->DoTrack2(tr);
2363                          //
2364                          if (fabs(tr->y[0] - oi->ytofpos[0]) < 2.) {
2365                              for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
2366                                  Int_t pl = tof2->GetPlaneIndex((oi->pmtadc).At(ih));
2367                                  if (pl == 0) {
2368                                      nphit_i++;
2369                                      enhit_i += (op->dedx).At(ih);
2370                                  };
2371                              };
2372                          };
2373                          if (fabs(tr->y[3] - oi->ytofpos[1]) < 2.) {
2374                              for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
2375                                  Int_t pl = tof2->GetPlaneIndex((oi->pmtadc).At(ih));
2376                                  if (pl == 3) {
2377                                      nphit_i++;
2378                                      enhit_i += (op->dedx).At(ih);
2379                                  };
2380                              };
2381                          };
2382                          if (fabs(tr->y[4] - oi->ytofpos[2]) < 2.) {
2383                              for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
2384                                  Int_t pl = tof2->GetPlaneIndex((oi->pmtadc).At(ih));
2385                                  if (pl == 4) {
2386                                      nphit_i++;
2387                                      enhit_i += (op->dedx).At(ih);
2388                                  };
2389                              };
2390                          };
2391    
2392                          if ((use_TOF || use_S1 || use_S2 || use_S3) && (nphit_p + nphit_i) != 0 && true) {
2393    
2394                              //        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);
2395                              //        printf(" score p %i score i %i \n",tp_score,ti_score);
2396                              //              if( enhit_p > enhit_i ) tp_score++;
2397                              //              if( nphit_p >= nphit_i && enhit_p > enhit_i ) tp_score++;
2398                              if (nphit_p > nphit_i)
2399                                  tp_score++;
2400                              if (nphit_p < nphit_i)
2401                                  ti_score++;
2402                              if (nphit_p == nphit_i) {
2403                                  if (enhit_p > enhit_i)
2404                                      tp_score++;
2405                                  else
2406                                      ti_score++;
2407                              };
2408                              //        printf(" dopo score p %i score i %i \n",tp_score,ti_score);
2409                          };
2410                          delete tr;
2411                          //
2412                      }
2413                      else {
2414                          // -------------
2415                          // NOT a NUCLEUS
2416                          // -------------
2417                          //printf(" NOT a NUCLEUS! en = %f \n",sen);
2418    
2419                          Int_t nphit_p = 0;
2420                          Int_t nphit_i = 0;
2421    
2422                          /*                                cout << "track: npmtadc "<< op->npmtadc << endl;
2423                            cout << "track: npmttdc "<< op->npmttdc << endl;
2424                            cout << "image: npmtadc "<< oi->npmtadc << endl;
2425                            cout << "image: npmttdc "<< oi->npmttdc << endl;*/
2426    
2427                          //          for (Int_t ih=0; ih < op->npmtadc; ih++){
2428                          //            Int_t pl = tof2_obj->GetPlaneIndex( (op->pmtadc).At(ih) );
2429                          //            if(pl == 1 || pl == 2 || pl == 5)nphit_p++;
2430                          //          };
2431    
2432                          //          for (Int_t ih=0; ih < oi->npmtadc; ih++){
2433                          //            Int_t pl = tof2_obj->GetPlaneIndex( (oi->pmtadc).At(ih) );
2434                          //            if(pl == 1 || pl == 2 || pl == 5)nphit_i++;
2435                          //          };
2436                          // --- modified to count tdc signals (more efficient?)
2437                          // --- and to implement check on tdcflag
2438                          for (Int_t ih = 0; ih < op->npmttdc; ih++) {
2439                              Int_t pl = tof2->GetPlaneIndex((op->pmttdc).At(ih));
2440                              //        if( (op->tdcflag).At(ih)==0 && (pl == 1 || pl == 2 || pl == 5) )nphit_p++;
2441                              if ((use_S1 && (pl == 0 || pl == 1)) || (use_S2 && (pl == 2 || pl == 3))
2442                                  || (use_S3 && (pl == 4 || pl == 5))) {
2443                                  if ((op->tdcflag).At(ih) == 0)
2444                                      nphit_p++;
2445                              };
2446                          };
2447    
2448                          for (Int_t ih = 0; ih < oi->npmttdc; ih++) {
2449                              Int_t pl = tof2->GetPlaneIndex((oi->pmttdc).At(ih));
2450                              //        if( (oi->tdcflag).At(ih)==0 && (pl == 1 || pl == 2 || pl == 5) )nphit_i++;
2451                              if ((use_S1 && (pl == 0 || pl == 1)) || (use_S2 && (pl == 2 || pl == 3))
2452                                  || (use_S3 && (pl == 4 || pl == 5))) {
2453                                  if ((oi->tdcflag).At(ih) == 0)
2454                                      nphit_i++;
2455                              };
2456                          };
2457    
2458                          if ((nphit_p + nphit_i) != 0 && true) {
2459    
2460                              if (nphit_p != nphit_i) {
2461                                  totp_score += nphit_p;
2462                                  toti_score += nphit_i;
2463                                  tp_score += nphit_p;
2464                                  ti_score += nphit_i;
2465                              };
2466                              //        if     ( nphit_p > nphit_i) tp_score+=nphit_p;
2467                              //        else if( nphit_p < nphit_i) ti_score+=nphit_i;
2468                              //        else ;//niente
2469                          };
2470                      };
2471                      //    cout << "TOF "<<tp_score<<ti_score<<endl;
2472                  };
2473    
2474                  //      if(tp_score == ti_score) use_TRK = true;
2475    
2476    
2477                  // -----------------------------------------------------------------------------------------
2478                  // *****************************************************************************************
2479                  // -----------------------------------------------------------------------------------------
2480                  // tracker check
2481                  // -----------------------------------------------------------------------------------------
2482                  // chi**2 difference is not always large enough to distinguish among
2483                  // the real track and its image.
2484                  // Tracker check will be applied always when calorimeter and tof information is ambiguous.
2485                  // *** MODIFIED ON AUGUST 2007 ***
2486                  if (use_TRK) {
2487                      //    if(      tp->chi2 > 0 && tp->chi2 < ti->chi2 ) tp_score++ ;
2488                      //    else if( ti->chi2 > 0 && ti->chi2 < tp->chi2 ) ti_score++ ;
2489    
2490                      // CHECK 1 : number of points along X
2491                      if (tp->GetNX() >= ti->GetNX()) {
2492                          tp_score++;
2493                          totp_score++;
2494                      };
2495                      if (tp->GetNX() <= ti->GetNX()) {
2496                          ti_score++;
2497                          toti_score++;
2498                      };
2499                      // CHECK 2 : number of points along Y
2500                      if (tp->GetNY() >= ti->GetNY()) {
2501                          tp_score++;
2502                          totp_score++;
2503                      };
2504                      if (tp->GetNY() <= ti->GetNY()) {
2505                          ti_score++;
2506                          toti_score++;
2507                      };
2508    
2509                      //    cout << "TRK "<<tp_score<<ti_score<<endl;
2510                  };
2511    
2512                  // -----------------------------------------------------------------------------------------
2513                  // *****************************************************************************************
2514                  // -----------------------------------------------------------------------------------------
2515                  // GPamela check
2516                  // -----------------------------------------------------------------------------------------
2517    
2518                  //---------------------------------------------------
2519                  // count the number of GP hits
2520                  //---------------------------------------------------
2521                  if (use_GP) {
2522                      int ngphits_p = 0;
2523                      int ngphits_i = 0;
2524                      float toll = 0.02; //200 micron
2525                      for (int ih = 0; ih < GetGPamela()->Nthspe; ih++) {
2526                          int ip = (Int_t) GetGPamela()->Itrpb[ih] - 1;
2527                          if (tp && tp->YGood(ip) && fabs(tp->ym[ip] - GetGPamela()->Yavspe[ih]) < toll && true)
2528                              ngphits_p++;
2529                          if (ti && ti->YGood(ip) && fabs(ti->ym[ip] - GetGPamela()->Yavspe[ih]) < toll && true)
2530                              ngphits_i++;
2531                      }
2532                      if (ngphits_p > ngphits_i && true) {
2533                          tp_score++;
2534                          totp_score++;
2535                      }
2536                      if (ngphits_p < ngphits_i && true) {
2537                          ti_score++;
2538                          toti_score++;
2539                      }
2540                  }
2541    
2542                  // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
2543                  // the winner is....
2544                  // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
2545                  if (tp_score > ti_score) {
2546    
2547                  }
2548                  else if (tp_score < ti_score) {
2549    
2550                      ts = ti;//its image!!
2551                      cs = ci;
2552                      os = oi;
2553                      rs = ri;
2554                      Int_t totis = toti_score;
2555    
2556                      ti = tp;//its image!!
2557                      ci = cp;
2558                      oi = op;
2559                      ri = rp;
2560    
2561                      tp = ts;//its image!!
2562                      cp = cs;
2563                      op = os;
2564                      rp = rs;
2565    
2566                      toti_score = totp_score;
2567                      totp_score = totis;
2568    
2569                  }
2570                  else {
2571    
2572                      //    cout << "Warning - track image ambiguity not solved" << endl;
2573    
2574                  };
2575    
2576              }
2577              else {
2578                  totp_score = 1;
2579                  toti_score = 0;
2580    
2581                  //            ts = tp;
2582                  //            cs = cp;
2583                  //            os = op;
2584              };
2585    
2586              //    cout <<" SortTracks() "<<i<<" -- "<<ts<<endl;
2587              //    sorted_tracks->Add(ts);//save the track in the sorted array
2588              //    sorted_tracks.Add(ts);//save the track in the sorted array
2589              //    sorted_tracks.Add(tp);//save the track in the sorted array
2590              //    cout << "SortTracks:: sorted_tracks->Add(it) "<<i<<" "<<ts<<endl;
2591              //    cout<<"o "<<tp<<endl;
2592              //    cout<<"o "<<cp<<endl;
2593              //    cout<<"o "<<op<<endl;
2594    
2595              new (ttsorted[i]) PamTrack(tp, cp, op, rp);
2596              new (ttimage[i]) PamTrack(ti, ci, oi, ri);
2597    
2598              ((PamTrack*) (ttsorted[i]))->SetPScore(totp_score);
2599              ((PamTrack*) (ttsorted[i]))->SetIScore(toti_score);
2600              ((PamTrack*) (ttimage[i]))->SetPScore(totp_score);
2601              ((PamTrack*) (ttimage[i]))->SetIScore(toti_score);
2602          };
2603    
2604    
2605    
2606    
2607    
2608    //   if (tsorted->GetEntries() != trk2->GetNTracks()) {
2609    //     cout << "void PamLevel2::SortTracks(): tsorted->GetEntries() " << tsorted->GetEntries()
2610    //         << " != trk2->GetNTracks() = " << trk2->GetNTracks() << endl;
2611    //     tsorted->Delete();
2612    //     tsorted = 0;
2613    //     timage->Delete();
2614    //     timage = 0;
2615    //   }
2616    
2617    
2618    //       cout << "text "<<doit<<endl;
2619    
2620    
2621          //--------------------------------------------------
2622          // fill array with extended tracks (this is easy...)
2623          //--------------------------------------------------
2624          if(EXT){
2625              for(int it=0; it<trkext->GetEntries(); it++){
2626                  
2627                  new (ttext[it]) PamTrack((ExtTrack*)(*trkext)[it], (CaloTrkVar*)(*caloext)[it], (ToFTrkVar*)(*tofext)[it], (OrbitalInfoTrkVar*)(*orbext)[it]);
2628                  
2629              }
2630          }
2631          
2632    
2633    
2634      };
2635    
2636    
2637      //Restore Object count
2638      //To save space in the table keeping track of all referenced objects
2639      //We reset the object count to what it was at the beginning of the event.
2640      TProcessID::SetObjectCount(ObjectNumber);
2641    
2642      //Everything went fine so the current event can be tagged as sorted
2643      issorted_new = true;
2644      lastsorted_new = GetReadEntry();
2645    
2646    //   cout << " tsorted "<< tsorted << " "<<(tsorted ? tsorted->GetEntries() : 0)<<endl;
2647    //   cout << " timage  "<< timage  << " "<<(timage  ? timage->GetEntries() : 0)<<endl;
2648    //   cout << " text    "<< text    << " "<<(text    ? text->GetEntries() : 0)<<endl;
2649    
2650    
2651  };  };
2652  //--------------------------------------  //--------------------------------------
2653  //  //
# Line 687  void PamLevel2::SortTracks(TString how){ Line 2657  void PamLevel2::SortTracks(TString how){
2657   * This method overrides TrkLevel2::GetTracks(), where sorting is done by decreasing number of fit points and increasing chi^2.   * This method overrides TrkLevel2::GetTracks(), where sorting is done by decreasing number of fit points and increasing chi^2.
2658   * PamLevel2::GetTracks() keeps the same track order given by TrkLevel2::GetTracks(), but checks image selection by using calorimeter and ToF tracking information.   * PamLevel2::GetTracks() keeps the same track order given by TrkLevel2::GetTracks(), but checks image selection by using calorimeter and ToF tracking information.
2659   */   */
2660    
2661  // TRefArray *PamLevel2::GetTracks(){  // TRefArray *PamLevel2::GetTracks(){
2662    
2663  // //  *-*-*-*-*-*-*-*-*-*-*-*-*  // //  *-*-*-*-*-*-*-*-*-*-*-*-*
# Line 695  void PamLevel2::SortTracks(TString how){ Line 2666  void PamLevel2::SortTracks(TString how){
2666    
2667  // //   return  sorted_tracks;  // //   return  sorted_tracks;
2668  //     return &sorted_tracks;  //     return &sorted_tracks;
2669        
2670  //  };  //  };
 TClonesArray *PamLevel2::GetTracks(){  
2671    
 //  *-*-*-*-*-*-*-*-*-*-*-*-*  
     SortTracks("+CAL+TOF");  
 //  *-*-*-*-*-*-*-*-*-*-*-*-*  
2672    
     return tsorted;  
       
  };  
2673  //--------------------------------------  //--------------------------------------
2674   //  //
2675   //  //
2676  //--------------------------------------  //--------------------------------------
2677    
2678  /**  /**
2679   * Retrieves the it-th Pamela "physical" track.   * Retrieves the it-th Pamela "physical" track.
2680   * It override TrkLevel2::GetTrack(int it).   * It override TrkLevel2::GetTrack(int it).
2681   * @param it Track number, ranging from 0 to GetNTracks().   * @param it Track number, ranging from 0 to GetNTracks().
2682   */   */
2683  PamTrack *PamLevel2::GetTrack(int it){  PamTrack *PamLevel2::GetTrackOld(int it) {
2684    
2685  //    if(!trk2_obj) return 0;    PamTrack *track = NULL;
           
 // //  *-*-*-*-*-*-*-*-*-*-*-*-*  
 //     SortTracks("+CAL+TOF");  
 // //  *-*-*-*-*-*-*-*-*-*-*-*-*  
 // //    if(!sorted_tracks)return 0;  
 //     if(sorted_tracks.IsEmpty())return 0;  
2686    
2687  //     PamTrack *track = 0;    //  *-*-*-*-*-*-*-*-*-*-*-*-*
2688          SortTracks();
2689  //     if( it >=0 && it < trk2_obj->TrkLevel2::GetNTracks() && it<sorted_tracks.GetEntriesFast() ){        //  *-*-*-*-*-*-*-*-*-*-*-*-*
2690  //      TrkTrack   *t = (TrkTrack*)sorted_tracks.At(it);    if (!tsorted)
2691  //      track = GetPamTrackAlong(t);      return track;
2692  //     }else{  //   if (!tsorted->GetEntries())
 //      cout << "PamLevel2::GetTrack(int) : tracker track SeqNo "<< it <<" does not exist (GetNTracks() = "<<trk2_obj->TrkLevel2::GetNTracks()<<")"<<endl;  
 //     };  
       
2693  //     return track;  //     return track;
2694      if (tsorted->GetEntries()==0)
2695        return track;
2696    
2697    
2698      if (
2699          tsorted &&
2700          it >= 0 &&
2701          it < trk2_obj->TrkLevel2::GetNTracks() &&
2702          it < tsorted->GetEntries() &&
2703          true) {
2704          track = (PamTrack*)((*tsorted)[it]);
2705      }
2706      else {
2707        cout << "PamLevel2::GetTrackOld(int) : tracker track SeqNo " << it << " does not exist (GetNTracks() = "
2708            << trk2_obj->TrkLevel2::GetNTracks() << ")" << endl;
2709      };
2710    
2711  //    cout << "PamLevel2::GetTrack(int it) "<<endl;    return track;
2712  //  *-*-*-*-*-*-*-*-*-*-*-*-*  
2713      SortTracks("+CAL+TOF");  };
2714  //  *-*-*-*-*-*-*-*-*-*-*-*-*  
2715      if(!tsorted)return 0;  //PamTrack *PamLevel2::GetTrack(int it) { return GetTrack(it,trkAlg); };
2716      if(!tsorted->GetEntries())return 0;  
2717    /**
2718     * Retrieves the it-th Pamela "physical" track.
2719     * It override TrkLevel2::GetTrack(int it).
2720     * @param it Track number, ranging from 0 to GetNTracks().
2721     * @param alg Algorythm, see SetTrakingAlgorythm(char *alg) for explanation.
2722     */
2723    PamTrack *PamLevel2::GetTrack(int it, const char* alg) {
2724    
2725      PamTrack *track = 0;      TString s(alg);
2726        if(!s.CompareTo("") ||!s.CompareTo("STD") )return GetTrackOld(it); //old algorythm
2727    
2728    
2729        SortTracksNew();
2730        // >> fill tsorted, timage and text
2731    
2732        if ( ( !s.Contains("EXTF", TString::kIgnoreCase) || !EXT )){ //not forced exteded-alg requested (or exteded-data missing)
2733    
2734            if( s.Contains("NUC")){
2735                if(
2736                    tsorted_nuc &&
2737                    it < tsorted_nuc->GetEntries() &&                             //enough tracks found
2738                    it >= 0 &&                                                //valid index
2739                    true) return (PamTrack*)((*tsorted_nuc)[it]);                 //ok return the track
2740            }else{
2741                if(
2742                    tsorted &&
2743                    it < tsorted->GetEntries() &&                             //enough tracks found
2744                    it >= 0 &&                                                //valid index
2745                    true )return (PamTrack*)((*tsorted)[it]);                 //ok return the track
2746            }
2747    
2748        }
2749            
2750      if( it >=0 && it < trk2_obj->TrkLevel2::GetNTracks()){  
2751  //      TrkTrack   *t = (TrkTrack*)sorted_tracks.At(it);      /////////////////////////////////////////////////////////////////////////
2752  //      track = GetPamTrackAlong(t);      /// if requested get track from extended algorythm output
2753          TClonesArray &t = *(tsorted);      /////////////////////////////////////////////////////////////////////////
2754          track = (PamTrack*)t[it];      
2755        if(s.Contains("EXT", TString::kIgnoreCase) && EXT){//if exteded-alg requested
2756                    
2757      }else{          if(s.Contains("NUC")){
2758          cout << "PamLevel2::GetTrack(int) : tracker track SeqNo "<< it <<" does not exist (GetNTracks() = "<<trk2_obj->TrkLevel2::GetNTracks()<<")"<<endl;              if(
2759                    text_nuc &&
2760                    it < text_nuc->GetEntries() &&                             //enough tracks found
2761                    it >= 0 &&                                                //valid index
2762                    true) return (PamTrack*)((*text_nuc)[it]);
2763            }else{
2764                if(
2765                    text &&
2766                    it < text->GetEntries() &&                             //enough tracks found
2767                    it >= 0 &&                                                //valid index
2768                    true) return (PamTrack*)((*text)[it]);
2769            }
2770    
2771      };      };
2772            
     return track;  
2773            
2774  };      cout << "PamTrack *PamLevel2::GetTrack("<<it<<","<<alg<<") -- wrong track number or unrecognised algorithm"<<endl;
2775        
2776        return NULL;
2777    
2778    }
2779    ;
2780    TClonesArray *PamLevel2::GetTracks() {
2781    
2782      //  *-*-*-*-*-*-*-*-*-*-*-*-*
2783      SortTracks();
2784      //  *-*-*-*-*-*-*-*-*-*-*-*-*
2785    
2786      return tsorted;
2787    
2788    }
2789    ;
2790    Int_t  PamLevel2::GetNTracks(const char* alg) {
2791    
2792    
2793    //    cout << " trk_nuc_obj->GetEntries() "<<trk_nuc_obj->GetEntries()<<" trk2_nuc_obj->GetNTracks() "<<trk2_nuc_obj->GetNTracks()<<endl;
2794    
2795        TString s(alg);
2796    
2797        if(!s.CompareTo("") || !s.CompareTo("STD"))return trk2_obj->TrkLevel2::GetNTracks(); //standard algorythm
2798            
2799        if(s.Contains("EXTF", TString::kIgnoreCase) && EXT){
2800            if(s.Contains("NUC", TString::kIgnoreCase) && NUC)return trk_ext_nuc_obj->GetEntries();//ok
2801            return trk_ext_obj->GetEntries();//ok
2802        }
2803        if( s.Contains("EXT", TString::kIgnoreCase) && EXT) {
2804            if(s.Contains("NUC", TString::kIgnoreCase) && NUC)
2805                return (trk2_nuc_obj->TrkLevel2::GetNTracks() ?  trk2_nuc_obj->TrkLevel2::GetNTracks() :  trk_ext_nuc_obj->GetEntries() );  
2806            return (trk2_obj->TrkLevel2::GetNTracks() ?  trk2_obj->TrkLevel2::GetNTracks() :  trk_ext_obj->GetEntries() );
2807        }
2808        if(s.Contains("NUC", TString::kIgnoreCase) && NUC )
2809            return trk2_nuc_obj->TrkLevel2::GetNTracks();
2810        
2811        cout << "Int_t  PamLevel2::GetNTracks("<<alg<<") -- unrecognised algorithm"<<endl;
2812    
2813        return 0;
2814    
2815    }
2816    
2817    
2818  //--------------------------------------  //--------------------------------------
2819  //  //
2820  //  //
2821  //--------------------------------------  //--------------------------------------
2822  /**  /**
2823   * Retrieves (if present) the image of the it-th Pamela "physical" track, sorted by the method PamLevel2::SortTracks().   * Retrieves (if present) the image of the it-th Pamela "physical" track, sorted by the method PamLevel2::SortTracks().
2824     * @param it Track number, ranging from 0 to GetNTracks().
2825     */
2826    PamTrack *PamLevel2::GetTrackImageOld(int it) {
2827    
2828      //  *-*-*-*-*-*-*-*-*-*-*-*-*
2829      SortTracks();
2830      //  *-*-*-*-*-*-*-*-*-*-*-*-*
2831      if (!timage)
2832        return 0;
2833      if (!timage->GetEntries())
2834        return 0;
2835    
2836      PamTrack *image = 0;
2837    
2838      if (it >= 0 && it < trk2_obj->TrkLevel2::GetNTracks()) {
2839        TClonesArray &t = *(tsorted);
2840        PamTrack *temp = (PamTrack*) t[it];
2841        if (temp->GetTrkTrack()->HasImage()) {
2842          TClonesArray & t = *(timage);
2843          image = (PamTrack*) t[it];
2844        }
2845        else {
2846          //            cout <<"PamLevel2::GetTrackImage(int) : Track SeqNo "<<it<<" does not have image"<<endl;
2847        };
2848      }
2849      else {
2850        cout << "PamLevel2::GetTrackImageOld(int) : Tracker track SeqNo " << it << " does not exist (GetNTracks() = "
2851            << trk2_obj->TrkLevel2::GetNTracks() << ")" << endl;
2852      };
2853    
2854      return image;
2855    }
2856    /**
2857     * Retrieves (if present) the image of the it-th Pamela "physical" track, sorted by the method PamLevel2::SortTracks().
2858   * @param it Track number, ranging from 0 to GetNTracks().   * @param it Track number, ranging from 0 to GetNTracks().
2859     * @param alg Algorythm, see SetTrakingAlgorythm(char *alg) for explanation.
2860   */   */
2861  PamTrack *PamLevel2::GetTrackImage(int it){  PamTrack *PamLevel2::GetTrackImage(int it, const char* alg) {
2862    
2863  //     if(!trk2_obj) return 0;      TString s(alg);
2864        if(!s.CompareTo("") || !s.CompareTo("STD"))return GetTrackImageOld(it); //old algorythm
2865    
 // //  *-*-*-*-*-*-*-*-*-*-*-*-*  
 //     SortTracks("+CAL+TOF");  
 // //  *-*-*-*-*-*-*-*-*-*-*-*-*  
 // //    if(!sorted_tracks)return 0;  
 //     if(sorted_tracks.IsEmpty())return 0;  
       
 //     PamTrack *image = 0;  
       
 //     if( it >=0 && it < trk2_obj->TrkLevel2::GetNTracks() ){  
 //      TrkTrack *temp = (TrkTrack*)sorted_tracks.At(it);  
 //      if( temp->HasImage() ){  
 //          TrkTrack   *t = trk2_obj->TrkLevel2::GetStoredTrack(temp->GetImageSeqNo());  
 //          image = GetPamTrackAlong(t);  
 //      }else{  
 //          cout <<"PamLevel2::GetTrackImage(int) : Track SeqNo "<<it<<" does not have image"<<endl;  
 //      };  
 //     }else{  
 //      cout << "PamLevel2::GetTrackImage(int) : Tracker track SeqNo "<< it <<" does not exist (GetNTracks() = "<<trk2_obj->TrkLevel2::GetNTracks()<<")"<<endl;  
 //     };  
       
 //     return image;  
2866    
2867        SortTracksNew();
2868        // >> fill tsorted, timage and text
2869    
2870  //  *-*-*-*-*-*-*-*-*-*-*-*-*      if ( ( !s.Contains("EXTF", TString::kIgnoreCase) || !EXT )){ //not forced exteded-alg requested (or exteded-data missing)
2871      SortTracks("+CAL+TOF");  
2872  //  *-*-*-*-*-*-*-*-*-*-*-*-*          if( s.Contains("NUC")){
2873      if(!timage)return 0;              if(
2874      if(!timage->GetEntries())return 0;                  tsorted_nuc &&
2875                        it < tsorted_nuc->GetEntries() &&                             //enough tracks found
2876      PamTrack *image = 0;                  it >= 0 &&                                                //valid index
2877                        true){
2878      if( it >=0 && it < trk2_obj->TrkLevel2::GetNTracks() ){                  TClonesArray &t = *(tsorted_nuc);
2879          TClonesArray &t = *(tsorted);                  PamTrack *temp = (PamTrack*) t[it];
2880          PamTrack *temp = (PamTrack*)t[it];                  if (temp->GetTrkTrack()->HasImage()) {
2881          if( temp->GetTrkTrack()->HasImage() ){                      return (PamTrack*)((*timage_nuc)[it]);                 //ok return the track
2882              TClonesArray &t = *(timage);                  }else{
2883              image = (PamTrack*)t[it];                      return NULL;
2884                    }
2885                    
2886                }
2887          }else{          }else{
2888  //          cout <<"PamLevel2::GetTrackImage(int) : Track SeqNo "<<it<<" does not have image"<<endl;              if(
2889          };                  tsorted &&
2890      }else{                  it < tsorted->GetEntries() &&                             //enough tracks found
2891          cout << "PamLevel2::GetTrackImage(int) : Tracker track SeqNo "<< it <<" does not exist (GetNTracks() = "<<trk2_obj->TrkLevel2::GetNTracks()<<")"<<endl;                  it >= 0 &&                                                //valid index
2892      };                  true ){
2893                        TClonesArray &t = *(tsorted);
2894      return image;                  PamTrack *temp = (PamTrack*) t[it];
2895                    if (temp->GetTrkTrack()->HasImage()) {              
2896                        return (PamTrack*)((*timage)[it]);                 //ok return the track
2897                    }else{
2898                        return NULL;
2899                    }
2900                }
2901            }
2902    
2903        }
2904    
2905    //    cout << "PamTrack *PamLevel2::GetTrackImage("<<it<<","<<alg<<") -- wrong track number or unrecognised algorithm"<<endl;
2906          
2907        return NULL;
2908    
2909  }  }
2910    ;
2911    
2912  //--------------------------------------  //--------------------------------------
2913  //  //
# Line 828  PamTrack *PamLevel2::GetTrackImage(int i Line 2919  PamTrack *PamLevel2::GetTrackImage(int i
2919   * @param detlist String to select trees to be included   * @param detlist String to select trees to be included
2920   * @return Pointer to a TTree   * @return Pointer to a TTree
2921   */   */
2922  TTree *PamLevel2::GetPamTree(TFile *f, TString detlist ){  TTree *PamLevel2::GetPamTree(TFile *f, TString detlist) {
2923    
2924  //     if( !detlist.IsNull() ) SetWhichTrees(detlist);    if (detlist.Contains("+AUTO", TString::kIgnoreCase)) {
2925  //     else                    GetWhichTrees(f);      cout << "+AUTO" << endl;
2926            GetWhichTrees(f);
2927      cout << "TTree *PamLevel2::GetPamTree(TFile *f, TString detlist ) -- obsolte "<<endl;    };
2928      SetWhichTrees(detlist);
2929    
2930      SetWhichTrees(detlist);    if (pam_tree) {
2931        printf("WARNING: TTree *PamLevel2::GetPamTree(TFile *fl, TString detlist) -- pam_tree already exists!\n ");
2932        return pam_tree;
2933      };
2934      //
2935    
2936      TTree *Trout =0;    cout << "TTree *PamLevel2::GetPamTree(TFile *f, TString detlist ) -- obsolte " << endl;
2937    
2938      TString fname = f->GetName();    //    SetWhichTrees(detlist);
2939      if(!CheckLevel2File(fname))return NULL;  
2940      TTree *Trout = 0;
2941    
2942      TString fname = f->GetName();
2943      if (!CheckLevel2File(fname))
2944        return NULL;
2945    
2946      //    UInt_t *found=0;
2947    
2948      cout << "GetPamTree(TFile*,TString): detector list --> ";
2949      if (TRK1)
2950        cout << "TRK1 ";
2951      if (TRK2)
2952        cout << "TRK2 ";
2953      if (TRKh)
2954        cout << "TRKH ";
2955      if (CAL1)
2956        cout << "CAL1 ";
2957      if (CAL2)
2958        cout << "CAL2 ";
2959      if (TOF)
2960        cout << "TOF ";
2961      if (TRG)
2962        cout << "TRG ";
2963      if (AC)
2964        cout << "AC ";
2965      if (ND)
2966        cout << "ND ";
2967      if (S4)
2968        cout << "S4 ";
2969      if (ORB)
2970        cout << "ORB ";
2971      if (GP)
2972        cout << "GP ";
2973      cout << endl;
2974      if (SELLI && SELLI != 2)
2975        cout << ">>> Found selection-list <<<" << endl; //EMILIANO
2976    
2977      f->cd();
2978    
2979      // Tracker
2980      TTree *T = (TTree*) f->Get("Tracker");
2981      if (T && (TRK2 || TRK1 || TRKh)) {
2982        if (TRK2)
2983          T->SetBranchAddress("TrkLevel2", GetPointerTo("TrkLevel2"));
2984        //  else    T->SetBranchStatus("TrkLevel2",0,found);
2985        if (TRK2)
2986          cout << "Tracker      : set branch address TrkLevel2" << endl;
2987        if (TRK1)
2988          T->SetBranchAddress("TrkLevel1", GetPointerTo("TrkLevel1"));
2989        //  else    T->SetBranchStatus("TrkLevel1",0,found);
2990        if (TRK1)
2991          cout << "Tracker      : set branch address TrkLevel1" << endl;
2992        if (TRKh)
2993          T->SetBranchAddress("TrkHough", GetPointerTo("TrkHough"));
2994        //  else    T->SetBranchStatus("TrkHough",0,found);
2995        if (TRKh)
2996          cout << "Tracker      : set branch address TrkHough" << endl;
2997        if (!Trout)
2998          Trout = T;
2999        else
3000            Trout->AddFriend(T);
3001      }
3002      else {
3003        cout << "Tracker      : missing tree" << endl;
3004      };
3005      // Calorimeter
3006      TTree *C = (TTree*) f->Get("Calorimeter");
3007      if (C && (CAL2 || CAL1)) {
3008        if (CAL2)
3009          C->SetBranchAddress("CaloLevel2", GetPointerTo("CaloLevel2"));
3010        //  else    C->SetBranchStatus("CaloLevel2",0,found);
3011        if (CAL2)
3012          cout << "Calorimeter  : set branch address CaloLevel2" << endl;
3013        if (CAL1)
3014          C->SetBranchAddress("CaloLevel1", GetPointerTo("CaloLevel1"));
3015        //  else    C->SetBranchStatus("CaloLevel1",0,found);
3016        if (CAL1)
3017          cout << "Calorimeter  : set branch address CaloLevel1" << endl;
3018        if (!Trout)
3019          Trout = C;
3020        else
3021          Trout->AddFriend(C);
3022      }
3023      else {
3024        cout << "Calorimeter  : missing tree" << endl;
3025      };
3026    
3027      // ToF
3028      TTree *O = (TTree*) f->Get("ToF");
3029      if (O && TOF) {
3030        O->SetBranchAddress("ToFLevel2", GetPointerTo("ToFLevel2"));
3031        cout << "ToF          : set branch address ToFLevel2" << endl;
3032        if (!Trout)
3033          Trout = O;
3034        else
3035          Trout->AddFriend(O);
3036      }
3037      else {
3038        cout << "ToF         : missing tree" << endl;
3039      };
3040      // Trigger
3041      TTree *R = (TTree*) f->Get("Trigger");
3042      if (R && TRG) {
3043        R->SetBranchAddress("TrigLevel2", GetPointerTo("TrigLevel2"));
3044        cout << "Trigger      : set branch address TrigLevel2" << endl;
3045        if (!Trout)
3046          Trout = R;
3047        else
3048          Trout->AddFriend(R);
3049      }
3050      else {
3051        cout << "Trigger      : missing tree" << endl;
3052      };
3053      // S4
3054      TTree *S = (TTree*) f->Get("S4");
3055      if (S && S4) {
3056        S->SetBranchAddress("S4Level2", GetPointerTo("S4Level2"));
3057        cout << "S4           : set branch address S4Level2" << endl;
3058        if (!Trout)
3059          Trout = S;
3060        else
3061          Trout->AddFriend(S);
3062      }
3063      else {
3064        cout << "S4           : missing tree" << endl;
3065      };
3066      // Neutron Detector
3067      TTree *N = (TTree*) f->Get("NeutronD");
3068      if (N && ND) {
3069        N->SetBranchAddress("NDLevel2", GetPointerTo("NDLevel2"));
3070        cout << "NeutronD     : set branch address NDLevel2" << endl;
3071        if (!Trout)
3072          Trout = N;
3073        else
3074          Trout->AddFriend(N);
3075      }
3076      else {
3077        cout << "NeutronD     : missing tree" << endl;
3078      };
3079      // Anticounters
3080      TTree *A = (TTree*) f->Get("Anticounter");
3081      if (A && AC) {
3082        A->SetBranchAddress("AcLevel2", GetPointerTo("AcLevel2"));
3083        cout << "Anticounter  : set branch address AcLevel2" << endl;
3084        if (!Trout)
3085          Trout = A;
3086        else
3087          Trout->AddFriend(A);
3088      }
3089      else {
3090        cout << "Anticounter  : missing tree" << endl;
3091      };
3092      // Orbital Info
3093      TTree *B = (TTree*) f->Get("OrbitalInfo");
3094      if (B && ORB) {
3095        B->SetBranchAddress("OrbitalInfo", GetPointerTo("OrbitalInfo"));
3096        cout << "OrbitalInfo  : set branch address OrbitalInfo" << endl;
3097        if (!Trout)
3098          Trout = B;
3099        else
3100          Trout->AddFriend(B);
3101      }
3102      else {
3103        cout << "OrbitalInfo  : missing tree" << endl;
3104      };
3105    
3106      // GPamela
3107      TTree *G = (TTree*) f->Get("h20");
3108      if (G && GP) {
3109        if (!gp_obj)
3110          gp_obj = new GPamela();
3111        //      ------------------------------------
3112        //      ATTENZIONE!!!
3113        //      non so per quale arcano motivo,
3114        //      per l'albero di gpamela il branch address lo devo settare
3115        //      DOPO aver fatto friend
3116        //      FGRRRVZZZZUTSALKJMSLKJ!!!
3117        //      ------------------------------------
3118        //  gp_obj->SetBranchAddress(G); //ho dovuto fare in maniera diversa dagli altri
3119        //  cout << "h20          : set branch address GPamela "<<endl;
3120        if (!Trout)
3121          Trout = G;
3122        else
3123          Trout->AddFriend(G);
3124      }
3125      else {
3126        //  cout << "h20          : missing tree"<<endl;
3127      };
3128    
3129      TTree *L = (TTree*) f->Get("SelectionList");
3130      if (L && SELLI == 1) {
3131        cout << " TTree *PamLevel2::GetPamTree(TFile, TString) >>> SelectionList not implemented!!!!" << endl;
3132        sel_tree = 0;
3133      }
3134      else {
3135        cout << "SelectionList  : missing tree" << endl;
3136      };
3137    
3138      cout << endl << " Number of entries: " << Trout->GetEntries() << endl << endl;
3139    
3140      //      ------------------------------------
3141      //      ATTENZIONE!!!
3142      //      non so per quale arcano motivo,
3143      //      per l'albero di gpamela il branch address lo devo settare
3144      //      DOPO aver fatto friend
3145      //      FGRRRVZZZZUTSALKJMSLKJ!!!
3146      //      ------------------------------------
3147      if (G && GP) {
3148        gp_obj->SetBranchAddress(Trout); //ho dovuto fare in maniera diversa dagli altri
3149        cout << "h20          : set branch address GPamela " << endl;
3150      }
3151      else {
3152        cout << "h20          : missing tree" << endl;
3153      };
3154    
3155      pam_tree = (TChain*) Trout;
3156    
3157      return Trout;
3158    
 //    UInt_t *found=0;      
   
     cout<< "GetPamTree(TFile*,TString): detector list --> ";  
     if(TRK1)cout<<"TRK1 ";  
     if(TRK2)cout<<"TRK2 ";  
     if(TRKh)cout<<"TRKH ";  
     if(CAL1)cout<<"CAL1 ";  
     if(CAL2)cout<<"CAL2 ";  
     if(TOF)cout<<"TOF ";  
     if(TRG)cout<<"TRG ";  
     if(AC)cout<<"AC ";  
     if(ND)cout<<"ND ";  
     if(S4)cout<<"S4 ";  
     if(ORB)cout<<"ORB ";  
     cout << endl;  
     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;  
       
     return Trout;  
       
3159  }  }
3160  //--------------------------------------  //--------------------------------------
3161  //  //
# Line 984  TTree *PamLevel2::GetPamTree(TFile *f, T Line 3168  TTree *PamLevel2::GetPamTree(TFile *f, T
3168   * @return Pointer to a TList of TSystemFiles   * @return Pointer to a TList of TSystemFiles
3169   * 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.
3170   */   */
3171  TList*  PamLevel2::GetListOfLevel2Files(TString ddir, TString flisttxt = ""){  TList* PamLevel2::GetListOfLevel2Files(TString ddir, TString flisttxt = "") {
3172            
3173      TString wdir = gSystem->WorkingDirectory();    TString wdir = gSystem->WorkingDirectory();
3174        
3175      if(ddir=="")ddir = wdir;    if (ddir != "") {
3176  //      TSystemDirectory *datadir = new TSystemDirectory(gSystem->BaseName(ddir),ddir);      cout << "Level2 data directory : " << ddir << endl;
3177      cout << "Level2 data directory : "<<  ddir << endl;    }
3178          else {
3179      TList *contents  = new TList; // create output list      cout << "Level2 data directory not given as input: trying to evaluate from list or taking working directory "
3180      contents->SetOwner();          << endl;
3181          };
3182  //    char *fullpath;    TList *contents = new TList; // create output list
3183  //    const char *fullpath;    contents->SetOwner();
3184        
3185      // if no input file list is given:      // --------------------------------------
3186      if ( flisttxt != "" ){    // case 1 : input file/file-list provided
3187              // --------------------------------------
3188  //      if( !gSystem->IsFileInIncludePath(flisttxt,&fullpath) ){            if (flisttxt != "") {
3189  //      if( !(fullpath = gSystem->FindFile("./",flisttxt)) ){  
3190  //          cout <<"File "<<flisttxt<<" not found"<<endl;      // --------------------------------------
3191  //          return 0;      // a list of files given as input
3192  //      }            // --------------------------------------
3193  //      flisttxt = fullpath;      if (!flisttxt.EndsWith(".root")) {
3194    
3195          flisttxt = gSystem->ConcatFileName(gSystem->DirName(flisttxt),gSystem->BaseName(flisttxt));        TString dir = gSystem->DirName(flisttxt);
3196          //            cout << " List directory "<<dir<<endl;
3197          if( !gSystem->ChangeDirectory(ddir) ){        if (dir == "." || dir == "")
3198              cout << "Cannot change directory : "<<ddir<<endl;          flisttxt = gSystem->ConcatFileName(wdir.Data(), gSystem->BaseName(flisttxt));
3199              return 0;        //                flisttxt = gSystem->ConcatFileName(gSystem->DirName(flisttxt),gSystem->BaseName(flisttxt));
3200          }  
3201                  if (!gSystem->ChangeDirectory(ddir)) {
3202          cout <<"Input file list : " << flisttxt <<endl;          cout << "Cannot change directory : " << ddir << endl;
3203          ifstream in;          return 0;
3204          in.open(flisttxt, ios::in); //open input file list        }
3205          if(!in.good()){  
3206              cout <<" ERROR opening the file "<<endl;        cout << "Input file list : " << flisttxt << endl;
3207              gSystem->ChangeDirectory(wdir); // back to the working directory        ifstream in;
3208              return 0;        in.open(flisttxt, ios::in); //open input file list
3209          }              if (!in.good()) {
3210          int line=0;          cout << " TList*  PamLevel2::GetListOfLevel2Files(TString, TString) --> ERROR opening the file " << endl;
3211          while (1) {          gSystem->ChangeDirectory(wdir); // back to the working directory
3212              TString file;          return 0;
3213              in >> file;        }
3214              if (!in.good()) break;        int line = 0;
3215              line++;        // ...........................
3216  //          cout <<"(1) " << file << endl;        // loop over file-list records
3217              if(file.IsNull()){        // ...........................
3218                  cout << "-- list interrupted at line "<<line <<endl;        while (1) {
3219                  break;          TString file;
3220              }          in >> file;
3221              if(file.Contains("#"))file = file(0,file.First("#"));          if (!in.good())
3222  //          cout <<"(2) " << file << endl;            break;
3223  //          if( gSystem->IsFileInIncludePath(file,&fullpath) ){          line++;
3224  //          if( (fullpath = gSystem->FindFile(ddir,file)) ){          cout << "(*) " << file << endl;
3225              if( file.EndsWith(".root") ){          if (file.IsNull()) {
3226                  char *fullpath = gSystem->ConcatFileName(gSystem->DirName(ddir),gSystem->BaseName(file));            cout << "-- list interrupted at line " << line << endl;
3227                  contents->Add(new TSystemFile(fullpath,gSystem->DirName(fullpath)));// add file to the list            break;
3228                  delete fullpath;          }
3229              }          if (file.Contains("#"))
3230  //          }else{            file = file(0, file.First("#"));
3231  //              if(file.Data()!="")cout << "File: "<<file<<" ---> missing "<< endl;          //
3232  //          };          // take only root files
3233          };          //
3234          in.close();          if (file.EndsWith(".root")) {
3235                      TString filedir;
3236      }else{            cout << ddir << endl;
3237                      if ( ddir != "" ) {
3238          cout << "No input file list given."<<endl;              filedir = ddir; // take the input dir
3239          cout << "Check for existing root files."<<endl;            }
3240  //              cout << "Warking directory: "<< gSystem->WorkingDirectory()<< endl;            else {
3241                        gSystem->ChangeDirectory(wdir); // back to the working directory
3242          TSystemDirectory *datadir = new TSystemDirectory(gSystem->BaseName(ddir),ddir);              filedir = gSystem->DirName(file); // this will take the path if exist in the list otherwise it will return automatically the working dir
3243          TList *temp = datadir->GetListOfFiles();            };
3244  //              temp->Print();            filedir.Append("/");
3245  //              cout << "*************************************" << endl;            //          char *fullpath = gSystem->ConcatFileName(gSystem->DirName(filedir), gSystem->BaseName(file));
3246                      char *fullpath = gSystem->ConcatFileName(filedir.Data(), gSystem->BaseName(file));
3247          TIter next(temp);            contents->Add(new TSystemFile(fullpath, gSystem->DirName(fullpath)));// add file to the list
3248          TSystemFile *questo = 0;            cout << fullpath << endl;
3249                      delete fullpath;
3250                    }
3251          while ( (questo = (TSystemFile*) next()) ) {          //          }else{
3252              TString name =  questo-> GetName();          //              if(file.Data()!="")cout << "File: "<<file<<" ---> missing "<< endl;
3253              if( name.EndsWith(".root") ){          //          };
3254  //              const char *fullpath = gSystem->FindFile(ddir,name);        };
3255  //              char *fullpath;        in.close();
3256  //              gSystem->IsFileInIncludePath(name,&fullpath);        // --------------------------------------
3257                  char *fullpath = gSystem->ConcatFileName(gSystem->DirName(ddir),gSystem->BaseName(name));        // a single root file given as input
3258                  contents->Add(new TSystemFile(fullpath,gSystem->DirName(fullpath)));        // --------------------------------------
3259                  delete fullpath;      }
3260              };      else {
3261          }        if (flisttxt.Contains("#"))
3262          delete temp;          flisttxt = flisttxt(0, flisttxt.First("#"));
3263          delete datadir;        char *fullpath = gSystem->ConcatFileName(gSystem->DirName(flisttxt), gSystem->BaseName(flisttxt));
3264                  contents->Add(new TSystemFile(fullpath, gSystem->DirName(fullpath)));// add file to the list
3265      };        delete fullpath;
3266      gSystem->ChangeDirectory(wdir); // back to the working directory      };
3267  //      cout << endl << "Selected files:" << endl;      // ---------------------------------------------------------------------------------
3268  //      contents->Print();      // case 2 : no input file/file-list provided --> read all files insede the directory
3269      cout << contents->GetEntries()<<" files \n";      // ---------------------------------------------------------------------------------
3270  //      cout << endl;    }
3271  //      cout << "Working directory: "<< gSystem->WorkingDirectory()<< endl;    else {
3272      return contents;  
3273  };      cout << "No input file list given." << endl;
3274        cout << "Check for existing root files." << endl;
3275        //          cout << "Warking directory: "<< gSystem->WorkingDirectory()<< endl;
3276        if (ddir == "") {
3277          ddir = wdir;
3278          cout << "Level2 data directory : " << ddir << endl;
3279        };
3280    
3281        TSystemDirectory *datadir = new TSystemDirectory(gSystem->BaseName(ddir), ddir);
3282        TList *temp = datadir->GetListOfFiles();
3283        if (!temp)
3284          return 0;
3285        //          temp->Print();
3286        //          cout << "*************************************" << endl;
3287    
3288        TIter next(temp);
3289        TSystemFile *questo = 0;
3290    
3291        while ((questo = (TSystemFile*) next())) {
3292          TString name = questo-> GetName();
3293          if (name.EndsWith(".root")) {
3294            //              const char *fullpath = gSystem->FindFile(ddir,name);
3295            //              char *fullpath;
3296            //              gSystem->IsFileInIncludePath(name,&fullpath);
3297            char *fullpath = gSystem->ConcatFileName(gSystem->DirName(ddir), gSystem->BaseName(name));
3298            contents->Add(new TSystemFile(fullpath, gSystem->DirName(fullpath)));
3299            delete fullpath;
3300          };
3301        }
3302        delete temp;
3303        delete datadir;
3304    
3305      };
3306      gSystem->ChangeDirectory(wdir); // back to the working directory
3307      //    cout << endl << "Selected files:" << endl;
3308      //    contents->Print();
3309      cout << contents->GetEntries() << " files \n";
3310      //    cout << endl;
3311      //    cout << "Working directory: "<< gSystem->WorkingDirectory()<< endl;
3312      return contents;
3313    }
3314    ;
3315  //--------------------------------------  //--------------------------------------
3316  //  //
3317  //  //
3318  //--------------------------------------  //--------------------------------------
3319  /**  /**
3320   * 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.
3321   * @param fl Pointer to a TList of TSystemFiles   * @param fl Pointer to a TList of TSystemFiles
3322   * @param detlist String to select trees to be included   * @param detlist String to select trees to be included
3323   * @return Pointer to a TChain   * @return Pointer to a TChain
3324   */   */
3325  TChain *PamLevel2::GetPamTree(TList *fl, TString detlist ){  TChain *PamLevel2::GetPamTree(TList *fl, TString detlist) {
3326          //
3327      TChain *Trout =0;    //
3328      //
3329      if (pam_tree) {
3330        printf("WARNING: TChain *PamLevel2::GetPamTree(TList *fl, TString detlist) -- pam_tree already exists!\n ");
3331        return pam_tree;
3332      };
3333      //
3334    
3335  //    if( !detlist.IsNull() )SetWhichTrees(detlist);    TChain *Trout = 0;
3336      SetWhichTrees(detlist);  
3337          // -------------------------------------------
3338      cout<< "GetPamTree(TList*,TString): input detector list --> ";    // set flags to include/exclude trees/branches
3339      if(TRK1)cout<<"TRK1 ";    // -------------------------------------------
3340      if(TRK2)cout<<"TRK2 ";    if (detlist.Contains("+AUTO", TString::kIgnoreCase)) {
3341      if(TRKh)cout<<"TRKH ";      if (fl->GetEntries() > 0) {
3342      if(CAL1)cout<<"CAL1 ";        cout << "+AUTO" << endl;
3343      if(CAL2)cout<<"CAL2 ";        TFile *fprimo = new TFile(fl->At(0)->GetName());
3344      if(TOF)cout<<"TOF ";        GetWhichTrees(fprimo);
3345      if(TRG)cout<<"TRG ";        fprimo->Close();// AAAAARGGGGGHHHHH!!!!!!! non commentare questa riga, altrimenti si incasina il TChain
3346      if(AC)cout<<"AC ";        fprimo->Delete();
3347      if(ND)cout<<"ND ";      }
3348      if(S4)cout<<"S4 ";    };
3349      if(ORB)cout<<"ORB ";    SetWhichTrees(detlist);
3350      cout << endl;  
3351      // -------------------------------------------
3352      TChain *T = 0;          // build chains
3353      TChain *C = 0;    // -------------------------------------------
3354      TChain *O = 0;    TChain *T = 0;
3355      TChain *R = 0;    TChain *C = 0;
3356      TChain *S = 0;    TChain *O = 0;
3357      TChain *N = 0;    TChain *R = 0;
3358      TChain *A = 0;    TChain *S = 0;
3359      TChain *B = 0;    TChain *N = 0;
3360      TChain *A = 0;
3361      TChain *B = 0;
3362      TChain *G = 0;
3363    
3364      TChain *L = 0;
3365      TChain *P = 0;
3366    
3367      if (TRK2 || TRK1 || TRKh)
3368        T = new TChain("Tracker");
3369      if (CAL2 || CAL1)
3370        C = new TChain("Calorimeter");
3371      if (TOF)
3372        O = new TChain("ToF");
3373      if (TRG)
3374        R = new TChain("Trigger");
3375      if (S4)
3376        S = new TChain("S4");
3377      if (ND)
3378        N = new TChain("NeutronD");
3379      if (AC)
3380        A = new TChain("Anticounter");
3381      if (ORB)
3382        B = new TChain("OrbitalInfo");
3383      if (GP)
3384        G = new TChain("h20");
3385      if (PROC)
3386        P = new TChain("ProcessingInfo");
3387      L = new TChain("SelectionList");
3388    
3389      // loop over files and create chains
3390      TIter next(fl);
3391      TSystemFile *questo = 0;
3392      while ((questo = (TSystemFile*) next())) {
3393        TString name = questo->GetName();
3394        cout << "File: " << name << endl;
3395        if (CheckLevel2File(name)) {
3396          if (TRK2 || TRK1 || TRKh)
3397            T->Add(name);
3398          if (CAL1 || CAL2)
3399            C->Add(name);
3400          if (TOF)
3401            O->Add(name);
3402          if (TRG)
3403            R->Add(name);
3404          if (S4)
3405            S->Add(name);
3406          if (ND)
3407            N->Add(name);
3408          if (AC)
3409            A->Add(name);
3410          if (ORB)
3411            B->Add(name);
3412          if (GP)
3413            G->Add(name);
3414          if (P)
3415            P->Add(name);
3416          if (SELLI == 1)
3417            L->Add(name);
3418         };
3419      };
3420    
3421      cout << "done data-tree chains  "<<  T->GetNtrees() <<" \n";
3422      cout << "----------------------------------------------------" << endl;
3423    
3424      // -------------------------------------------
3425      // make friends
3426      // -------------------------------------------
3427    
3428      // Tracker
3429      cout << "Friends: " << endl;
3430      if (T && (TRK2 || TRK1 || TRKh)) {
3431        if (!Trout)
3432          Trout = T;
3433        else
3434          Trout->AddFriend("Tracker");
3435        //  cout << "+Tacker"<<endl;
3436      };
3437      // Calorimeter
3438      if (C && (CAL2 || CAL1)) {
3439        if (!Trout)
3440          Trout = C;
3441        else
3442          Trout->AddFriend("Calorimeter");
3443        //  cout << "+Calorimeter"<<endl;
3444      };
3445      // ToF
3446      if (O && TOF) {
3447        if (!Trout)
3448          Trout = O;
3449        else
3450          Trout->AddFriend("ToF");
3451        //  cout << "+ToF"<<endl;
3452      };
3453      // Trigger
3454      if (R && TRG) {
3455        if (!Trout)
3456          Trout = O;
3457        else
3458          Trout->AddFriend("Trigger");
3459        //  cout << "+Trigger"<<endl;
3460      };
3461      // S4
3462      if (S && S4) {
3463        if (!Trout)
3464          Trout = O;
3465        else
3466          Trout->AddFriend("S4");
3467        //  cout << "+S4"<<endl;
3468      };
3469      // Neutron Detector
3470      if (N && ND) {
3471        if (!Trout)
3472          Trout = O;
3473        else
3474          Trout->AddFriend("NeutronD");
3475        //  cout << "+NeutronD"<<endl;
3476      };
3477      // Anticounters
3478      if (A && AC) {
3479        if (!Trout)
3480          Trout = O;
3481        else
3482          Trout->AddFriend("Anticounter");
3483        //  cout << "+Anticounter"<<endl;
3484      };
3485      // Orbital Info
3486      if (B && ORB) {
3487        if (!Trout)
3488          Trout = O;
3489        else
3490          Trout->AddFriend("OrbitalInfo");
3491        //  cout << "+OrbitalInfo"<<endl;
3492      };
3493      // GPamela
3494      if (G && GP) {
3495        if (!Trout)
3496          Trout = G;
3497        else
3498          Trout->AddFriend("h20");
3499        //  cout << "+h20"<<endl;
3500      };
3501    
3502      //  =====================================
3503      //  SET BRANCH-ADDRESS AFTER CHAIN+FRIEND
3504      //  =====================================
3505      if( Trout->GetNtrees() )SetBranchAddress(Trout);
3506    
3507      //  ------------------------------------
3508      //  finally handle selection trees...
3509      //  (it is not friend of pamela tree)
3510      //  ------------------------------------
3511    
3512      cout << "----------------------------------------------------" << endl;
3513    
3514      // Selection List
3515      if (L && SELLI == 1) {
3516        cout << ">>> Found selection-list <<<" << endl;
3517        //  L->SetBranchAddress("RunEntry",&irun);
3518        L->SetBranchAddress("RunEntry", &irunt);//NEWNEW
3519        cout << "SelectionList: set branch address RunEntry" << endl;
3520        L->SetBranchAddress("EventEntry", &irunentry);
3521        cout << "SelectionList: set branch address EventEntry" << endl;
3522        /*    if ( L->GetBranch("L0EventEntry") ){
3523          hasL0EE = true;
3524          L->SetBranchAddress("L0EventEntry", &il0entry);
3525          cout << "SelectionList: set branch address L0EventEntry" << endl;
3526        } else {
3527          hasL0EE = false; // backward compatibility with old preselected files...
3528          }*/
3529        sel_tree = L;
3530        //          if(!Trout)Trout=O;
3531        //          else Trout->AddFriend("SelectionList");
3532        cout << "+SelectionList" << endl;
3533        cout << "----------------------------------------------------" << endl;
3534      }
3535      else {
3536        //  cout << "SelectionList  : missing tree"<<endl;
3537        if (L)
3538          L->Delete();
3539      };
3540    
3541      //ProcessingInfo EM
3542      if ( P && P->GetEntries() ){
3543        cout << "----------------------------------------------------" << endl;
3544        cout << ">>> Found ProcessingInfo <<<" << endl;
3545        //  L->SetBranchAddress("RunEntry",&irun);
3546        P->SetBranchAddress("ProcInfo", &proc_obj);//NEWNEW
3547        proc_tree = P;
3548      } else {
3549        //    proc_tree = new TChain("ProcessingInfo","Log of data processing");
3550        //    proc_tree->Branch("ProcInfo", "ProcInfo", &proc_obj);
3551        cout << "----------------------------------------------------" << endl;
3552        cout << ">>> ProcessingInfo not found, PROC set to false and continue (not 10RED files?)<<<" << endl;
3553        PROC = false;
3554      }
3555      //  --------------------------------------------
3556      //  return the pamela chain with all the friends
3557      //  --------------------------------------------
3558    
3559      pam_tree = Trout;
3560      return Trout;
3561    }
3562    
3563    //--------------------------------------
3564    //
3565    //
3566    //--------------------------------------
3567    /**
3568     * Set branch addresses for Pamela friend trees
3569     */
3570    void PamLevel2::SetBranchAddress(TTree *t) {
3571    
3572    //   TRK2 = TRK2 & t->GetBranchStatus("TrkLevel2");
3573    //   TRK1 = TRK1 & t->GetBranchStatus("TrkLevel1");
3574    //   TRKh = TRKh & t->GetBranchStatus("TrkHough");
3575    //   CAL2 = CAL2 & t->GetBranchStatus("CaloLevel2");
3576    //   CAL1 = CAL1 & t->GetBranchStatus("CaloLevel1");
3577    //   TOF = TOF & t->GetBranchStatus("ToFLevel2");
3578    //   TRG = TRG & t->GetBranchStatus("TrigLevel2");
3579    //   S4 = S4 & t->GetBranchStatus("S4Level2");
3580    //   ND = ND & t->GetBranchStatus("NDLevel2");
3581    //   AC = AC & t->GetBranchStatus("AcLevel2");
3582    //   ORB = ORB & t->GetBranchStatus("OrbitalInfo");
3583    //   GP = GP & t->GetBranchStatus("h20");
3584    
3585    
3586      // Tracker
3587      if (TRK1) {
3588        t->SetBranchAddress("TrkLevel1", GetPointerTo("TrkLevel2"));
3589        cout << "Tracker      : set branch address TrkLevel1" << endl;
3590      };
3591      if (TRK2) {
3592        t->SetBranchAddress("TrkLevel2", GetPointerTo("TrkLevel1"));
3593        cout << "Tracker      : set branch address TrkLevel2" << endl;
3594        NUC = t->GetBranchStatus("TrackNuclei");
3595        EXT = t->GetBranchStatus("RecoveredTrack") && (NUC ? t->GetBranchStatus("RecoveredTrackNuclei"): true );    
3596      };
3597      if (TRKh) {
3598        t->SetBranchAddress("TrkHough", GetPointerTo("TrkHough"));
3599        cout << "Tracker      : set branch address TrkHough" << endl;
3600      };
3601    
3602      // Calorimeter
3603      if (CAL1) {
3604        t->SetBranchAddress("CaloLevel1", GetPointerTo("CaloLevel1"));
3605        cout << "Calorimeter  : set branch address CaloLevel1" << endl;
3606      };
3607      if (CAL2) {
3608        t->SetBranchAddress("CaloLevel2", GetPointerTo("CaloLevel2"));
3609        cout << "Calorimeter  : set branch address CaloLevel2" << endl;
3610      };
3611    
3612      // ToF
3613      if (TOF) {
3614        t->SetBranchAddress("ToFLevel2", GetPointerTo("ToFLevel2"));
3615        cout << "ToF          : set branch address ToFLevel2" << endl;
3616      };
3617      // Trigger
3618      if (TRG) {
3619        t->SetBranchAddress("TrigLevel2", GetPointerTo("TrigLevel2"));
3620        cout << "Trigger      : set branch address TrigLevel2" << endl;
3621      };
3622      // S4
3623      if (S4) {
3624        t->SetBranchAddress("S4Level2", GetPointerTo("S4Level2"));
3625        cout << "S4           : set branch address S4Level2" << endl;
3626      };
3627      // Neutron Detector
3628      if (ND) {
3629        t->SetBranchAddress("NDLevel2", GetPointerTo("NDLevel2"));
3630        cout << "NeutronD     : set branch address NDLevel2" << endl;
3631      };
3632      // Anticounters
3633      if (AC) {
3634        t->SetBranchAddress("AcLevel2", GetPointerTo("AcLevel2"));
3635        cout << "Anticounter  : set branch address AcLevel2" << endl;
3636      };
3637      // OrbitalInfo
3638      if (ORB) {
3639        t->SetBranchAddress("OrbitalInfo", GetPointerTo("OrbitalInfo"));
3640        cout << "OrbitalInfo  : set branch address OrbitalInfo" << endl;
3641      };
3642      // GPamela
3643      if (GP) {
3644        //  GetPointerTo("GPamela");
3645        if (!gp_obj)
3646          gp_obj = new GPamela();
3647        //  gp_obj->SetBranchAddress(t); //ho dovuto fare in maniera diversa dagli altri
3648        // //       t->SetBranchAddress("GPamela", GetPointerTo("GPamela"));
3649        if (SELLI)
3650          t->SetBranchAddress("GPamela", GetPointerTo("GPamela"));
3651        else
3652          gp_obj->SetBranchAddress(t); //ho dovuto fare in maniera diversa dagli altri
3653    
3654        cout << "h20          : set branch address GPamela " << endl;
3655      };
3656      if(NUC){
3657          
3658          cout << "Found nuclei-track branches" << endl;
3659    
3660          if( !trk_nuc_obj )trk_nuc_obj = new TClonesArray("TrkTrack");
3661          if( !calo_nuc_obj)calo_nuc_obj= new TClonesArray("CaloTrkVar");
3662          if( !tof_nuc_obj)tof_nuc_obj= new TClonesArray("ToFTrkVar");
3663          if( !orb_nuc_obj)orb_nuc_obj= new TClonesArray("OrbitalInfoTrkVar");
3664          if (TRK2)t->                          SetBranchAddress("TrackNuclei",&trk_nuc_obj);
3665          if (CAL2)t->GetFriend("Calorimeter")->SetBranchAddress("TrackNuclei",&calo_nuc_obj);
3666          if (TOF )t->GetFriend("ToF")->        SetBranchAddress("TrackNuclei",&tof_nuc_obj);
3667          if (ORB )t->GetFriend("OrbitalInfo")->SetBranchAddress("TrackNuclei",&orb_nuc_obj);
3668    
3669          ///copy the vector content inside a "fake" object (all aother info are missing)    
3670    
3671          if( !trk2_nuc_obj )trk2_nuc_obj =  new TrkLevel2();
3672          if( !calo2_nuc_obj )calo2_nuc_obj =  new CaloLevel2();
3673          if( !tof2_nuc_obj )tof2_nuc_obj =  new ToFLevel2();
3674          if( !orb2_nuc_obj )orb2_nuc_obj =  new OrbitalInfo();
3675    //       *(trk2_nuc_obj->GetPointerToTrackArray()) = new TClonesArray(*trk_nuc_obj);
3676    //       *(calo2_nuc_obj->GetPointerToTrackArray()) = new TClonesArray(*calo_nuc_obj);
3677    //       *(tof2_nuc_obj->GetPointerToTrackArray()) = new TClonesArray(*tof_nuc_obj);
3678    //       *(orb2_nuc_obj->GetPointerToTrackArray()) = new TClonesArray(*orb_nuc_obj);
3679    
3680          trk2_nuc_obj->SetTrackArray(  trk_nuc_obj  );
3681          calo2_nuc_obj->SetTrackArray( calo_nuc_obj );
3682          tof2_nuc_obj->SetTrackArray(  tof_nuc_obj  );
3683          orb2_nuc_obj->SetTrackArray(  orb_nuc_obj  );
3684    
3685          
3686      }    
3687    
3688      if(EXT){
3689          
3690          cout << "Found extended tracking algorythm branches" << endl;
3691    
3692          if( !trk_ext_obj )trk_ext_obj = new TClonesArray("ExtTrack");
3693          if( !calo_ext_obj)calo_ext_obj= new TClonesArray("CaloTrkVar");
3694          if( !tof_ext_obj)tof_ext_obj= new TClonesArray("ToFTrkVar");
3695          if( !orb_ext_obj)orb_ext_obj= new TClonesArray("OrbitalInfoTrkVar");
3696          
3697          if (TRK2)t->                          SetBranchAddress("RecoveredTrack",&trk_ext_obj);
3698          if (CAL2)t->GetFriend("Calorimeter")->SetBranchAddress("RecoveredTrack",&calo_ext_obj);
3699          if (TOF )t->GetFriend("ToF")->        SetBranchAddress("RecoveredTrack",&tof_ext_obj);
3700          if (ORB )t->GetFriend("OrbitalInfo")->SetBranchAddress("RecoveredTrack",&orb_ext_obj);
3701    
3702        
3703          if(NUC){
3704              if( !trk_ext_nuc_obj )trk_ext_nuc_obj = new TClonesArray("ExtTrack");
3705              if( !calo_ext_nuc_obj)calo_ext_nuc_obj= new TClonesArray("CaloTrkVar");
3706              if( !tof_ext_nuc_obj)tof_ext_nuc_obj= new TClonesArray("ToFTrkVar");
3707              if( !orb_ext_nuc_obj)orb_ext_nuc_obj= new TClonesArray("OrbitalInfoTrkVar");
3708              if (TRK2)t->                          SetBranchAddress("RecoveredTrackNuclei",&trk_ext_nuc_obj);
3709              if (CAL2)t->GetFriend("Calorimeter")->SetBranchAddress("RecoveredTrackNuclei",&calo_ext_nuc_obj);
3710              if (TOF )t->GetFriend("ToF")->        SetBranchAddress("RecoveredTrackNuclei",&tof_ext_nuc_obj);
3711              if (ORB )t->GetFriend("OrbitalInfo")->SetBranchAddress("RecoveredTrackNuclei",&orb_ext_nuc_obj);
3712          }
3713      }    
3714    }
3715    /**
3716     * Set branch addresses for Pamela friend trees
3717     */
3718    void PamLevel2::SetBranchAddress(TChain *t) {
3719    
3720      TChain *L = 0;    //     TRK2    = TRK2 & t->GetBranchStatus("TrkLevel2");
3721          //     TRK1    = TRK1 & t->GetBranchStatus("TrkLevel1");
3722      if(TRK2||TRK1||TRKh) T = new TChain("Tracker");        //     TRKh    = TRKh & t->GetBranchStatus("TrkHough");
3723      if(CAL2||CAL1)       C = new TChain("Calorimeter");    //     CAL1    = CAL1 & t->GetBranchStatus("CaloLevel1");
3724      if(TOF)              O = new TChain("ToF");    //     CAL2    = CAL2 & t->GetBranchStatus("CaloLevel2");
3725      if(TRG)              R = new TChain("Trigger");    //     TOF    = TOF & t->GetBranchStatus("ToFLevel2");
3726      if(S4)               S = new TChain("S4");    //     TRG    = TRG & t->GetBranchStatus("TrigLevel2");
3727      if(ND)               N = new TChain("NeutronD");    //     S4     = S4  & t->GetBranchStatus("S4Level2");
3728      if(AC)               A = new TChain("Anticounter");    //     ND     = ND  & t->GetBranchStatus("NDLevel2");
3729      if(ORB)              B = new TChain("OrbitalInfo");    //     AC     = AC  & t->GetBranchStatus("AcLevel2");
3730      //     ORB    = ORB & t->GetBranchStatus("OrbitalInfo");
3731      //    GP     = GP & t->GetBranchStatus("h20");
3732    
3733      // Tracker
3734      if (TRK2) {
3735        t->SetBranchAddress("TrkLevel2", GetPointerTo("TrkLevel2"));
3736        cout << "Tracker      : set branch address TrkLevel2" << endl;
3737        NUC = t->GetBranchStatus("TrackNuclei");
3738        EXT = t->GetBranchStatus("RecoveredTrack") && (NUC ? t->GetBranchStatus("RecoveredTrackNuclei"): true );
3739      };
3740      if (TRK1) {
3741        t->SetBranchAddress("TrkLevel1", GetPointerTo("TrkLevel1"));
3742        cout << "Tracker      : set branch address TrkLevel1" << endl;
3743      };
3744      if (TRKh) {
3745        t->SetBranchAddress("TrkHough", GetPointerTo("TrkHough"));
3746        cout << "Tracker      : set branch address TrkHough" << endl;
3747      };
3748    
3749       L = new TChain("SelectionList");    // Calorimeter
3750          if (CAL2) {
3751      // loop over files and create chains              t->SetBranchAddress("CaloLevel2", GetPointerTo("CaloLevel2"));
3752      TIter next(fl);      cout << "Calorimeter  : set branch address CaloLevel2" << endl;    
3753      TSystemFile *questo = 0;    };
3754      while ( (questo = (TSystemFile*) next()) ) {    if (CAL1) {
3755          TString name =  questo->GetName();      t->SetBranchAddress("CaloLevel1", GetPointerTo("CaloLevel1"));
3756          cout << "File: "<< name << endl;      cout << "Calorimeter  : set branch address CaloLevel1" << endl;
3757          if( CheckLevel2File(name) ){    };
             if(TRK2||TRK1||TRKh) T->Add(name);  
             if(CAL1||CAL2)       C->Add(name);  
             if(TOF)              O->Add(name);  
             if(TRG)              R->Add(name);  
             if(S4)               S->Add(name);  
             if(ND)               N->Add(name);  
             if(AC)               A->Add(name);  
             if(ORB)              B->Add(name);  
             if(SELLI==1)         L->Add(name);  
         };  
     }  
       
     cout << "done chain \n";  
3758    
3759  //    UInt_t *found=0;    // ToF
3760  // Tracker    if (TOF) {
3761      if(T && (TRK2||TRK1||TRKh)) {      t->SetBranchAddress("ToFLevel2", GetPointerTo("ToFLevel2"));
3762          if(TRK2)T->SetBranchAddress("TrkLevel2", GetPointerTo("TrkLevel2"));      cout << "ToF          : set branch address ToFLevel2" << endl;
3763  //      else    T->SetBranchStatus("TrkLevel2",0,found);    };
3764          if(TRK2)cout << "Tracker      : set branch address TrkLevel2"<<endl;    // Trigger
3765          if(TRK1)T->SetBranchAddress("TrkLevel1", GetPointerTo("TrkLevel1"));    if (TRG) {
3766  //      else    T->SetBranchStatus("TrkLevel1",0,found);      t->SetBranchAddress("TrigLevel2", GetPointerTo("TrigLevel2"));
3767          if(TRK1)cout << "Tracker      : set branch address TrkLevel1"<<endl;      cout << "Trigger      : set branch address TrigLevel2" << endl;
3768          if(TRKh)T->SetBranchAddress("TrkHough", GetPointerTo("TrkHough"));    };
3769  //      else    T->SetBranchStatus("TrkHough",0,found);    // S4
3770          if(TRKh)cout << "Tracker      : set branch address TrkHough"<<endl;    if (S4) {
3771          if(!Trout)Trout=T;      t->SetBranchAddress("S4Level2", GetPointerTo("S4Level2"));
3772          else Trout->AddFriend("Tracker");      cout << "S4           : set branch address S4Level2" << endl;
3773      }else{    };
3774          cout << "Tracker      : missing tree"<<endl;    // Neutron Detector
3775      };    if (ND) {
3776      // Calorimeter      t->SetBranchAddress("NDLevel2", GetPointerTo("NDLevel2"));
3777      if(C && (CAL2||CAL1)) {      cout << "NeutronD     : set branch address NDLevel2" << endl;
3778          if(CAL2)C->SetBranchAddress("CaloLevel2", GetPointerTo("CaloLevel2"));    };
3779  //      else    C->SetBranchStatus("CaloLevel2",0,found);    // Anticounters
3780          if(CAL2)cout << "Calorimeter  : set branch address CaloLevel2"<<endl;    if (AC) {
3781          if(CAL1)C->SetBranchAddress("CaloLevel1", GetPointerTo("CaloLevel1"));      t->SetBranchAddress("AcLevel2", GetPointerTo("AcLevel2"));
3782  //      else    C->SetBranchStatus("CaloLevel1",0,found);      cout << "Anticounter  : set branch address AcLevel2" << endl;
3783          if(CAL1)cout << "Calorimeter  : set branch address CaloLevel1"<<endl;    };
3784          if(!Trout)Trout=C;    // OrbitalInfo
3785          else Trout->AddFriend("Calorimeter");    if (ORB) {
3786      }else{      t->SetBranchAddress("OrbitalInfo", GetPointerTo("OrbitalInfo"));
3787          cout << "Calorimeter  : missing tree"<<endl;      cout << "OrbitalInfo  : set branch address OrbitalInfo" << endl;
3788      };    };
3789      // ToF        // GPamela
3790      if(O && TOF) {    //    cout <<"GP "<<GP<<endl;
3791          O->SetBranchAddress("ToFLevel2", GetPointerTo("ToFLevel2"));    if (GP) {
3792          cout << "ToF          : set branch address ToFLevel2"<<endl;      //  GetPointerTo("GPamela");
3793          if(!Trout)Trout=O;      if (!gp_obj)
3794          else Trout->AddFriend("ToF");        gp_obj = new GPamela();
3795      }else{      if (SELLI)
3796          cout << "ToF         : missing tree"<<endl;        t->SetBranchAddress("GPamela", GetPointerTo("GPamela"));
3797      };      else
3798      // Trigger        gp_obj->SetBranchAddress(t); //ho dovuto fare in maniera diversa dagli altri
3799      if(R && TRG) {      //  gp_obj->SetBranchAddress(t); //ho dovuto fare in maniera diversa dagli altri
3800          R->SetBranchAddress("TrigLevel2", GetPointerTo("TrigLevel2"));      cout << "h20          : set branch address GPamela " << endl;
3801          cout << "Trigger      : set branch address TrigLevel2"<<endl;    };
3802          if(!Trout)Trout=O;    // SelectionList
3803          else Trout->AddFriend("Trigger");    //     if(SELLI==1){
3804      }else{    //    t->SetBranchAddress("RunEntry",&irunt);//NEWNEW
3805          cout << "Trigger      : missing tree"<<endl;    //    cout << "SelectionList: set branch address RunEntry"<<endl;
3806      };    //    t->SetBranchAddress("EventEntry",&irunentry);
3807      // S4    //    cout << "SelectionList: set branch address EventEntry"<<endl;
     if(S && S4) {  
         S->SetBranchAddress("S4Level2", GetPointerTo("S4Level2"));  
         cout << "S4           : set branch address S4Level2"<<endl;  
         if(!Trout)Trout=O;  
         else Trout->AddFriend("S4");  
     }else{  
         cout << "S4           : missing tree"<<endl;  
     };  
     // Neutron Detector  
     if(N && ND) {  
         N->SetBranchAddress("NDLevel2", GetPointerTo("NDLevel2"));  
         cout << "NeutronD     : set branch address NDLevel2"<<endl;  
         if(!Trout)Trout=O;  
         else Trout->AddFriend("NeutronD");  
     }else{  
         cout << "NeutronD     : missing tree"<<endl;  
     };  
     // Anticounters  
     if(A && AC) {  
         A->SetBranchAddress("AcLevel2", GetPointerTo("AcLevel2"));  
         cout << "Anticounter  : set branch address AcLevel2"<<endl;  
         if(!Trout)Trout=O;  
         else Trout->AddFriend("Anticounter");  
     }else{  
         cout << "Anticounter  : missing tree"<<endl;  
     };  
     // Orbital Info  
     if(B && ORB) {  
         B->SetBranchAddress("OrbitalInfo", GetPointerTo("OrbitalInfo"));  
         cout << "OrbitalInfo  : set branch address OrbitalInfo"<<endl;  
         if(!Trout)Trout=O;  
         else Trout->AddFriend("OrbitalInfo");  
     }else{  
         cout << "OrbitalInfo  : missing tree"<<endl;  
     };  
   
     // 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();  
     };  
       
 //    cout<<endl<<" Number of entries: "<<Trout->GetEntries()<<endl<<endl;  
3808    
3809      pam_tree = Trout;    //     }
3810      if(NUC){
3811          
3812          cout << "Found nuclei-track branches" << endl;
3813    
3814      return Trout;        if( !trk_nuc_obj )trk_nuc_obj = new TClonesArray("TrkTrack");
3815  }        if( !calo_nuc_obj)calo_nuc_obj= new TClonesArray("CaloTrkVar");
3816          if( !tof_nuc_obj)tof_nuc_obj= new TClonesArray("ToFTrkVar");
3817          if( !orb_nuc_obj)orb_nuc_obj= new TClonesArray("OrbitalInfoTrkVar");
3818          if (TRK2)t->                          SetBranchAddress("TrackNuclei",&trk_nuc_obj);
3819          if (CAL2)t->GetFriend("Calorimeter")->SetBranchAddress("TrackNuclei",&calo_nuc_obj);
3820          if (TOF )t->GetFriend("ToF")->        SetBranchAddress("TrackNuclei",&tof_nuc_obj);
3821          if (ORB )t->GetFriend("OrbitalInfo")->SetBranchAddress("TrackNuclei",&orb_nuc_obj);
3822          
3823          ///copy the vector content inside a "fake" object (all aother info are missing)    
3824    
3825          if( !trk2_nuc_obj )trk2_nuc_obj =  new TrkLevel2();
3826          if( !calo2_nuc_obj )calo2_nuc_obj =  new CaloLevel2();
3827          if( !tof2_nuc_obj )tof2_nuc_obj =  new ToFLevel2();
3828          if( !orb2_nuc_obj )orb2_nuc_obj =  new OrbitalInfo();
3829    
3830    //       *(trk2_nuc_obj->GetPointerToTrackArray()) = new TClonesArray(*trk_nuc_obj);
3831    //       *(calo2_nuc_obj->GetPointerToTrackArray()) = new TClonesArray(*calo_nuc_obj);
3832    //       *(tof2_nuc_obj->GetPointerToTrackArray()) = new TClonesArray(*tof_nuc_obj);
3833    //       *(orb2_nuc_obj->GetPointerToTrackArray()) = new TClonesArray(*orb_nuc_obj);
3834          trk2_nuc_obj->SetTrackArray(  trk_nuc_obj  );
3835          calo2_nuc_obj->SetTrackArray( calo_nuc_obj );
3836          tof2_nuc_obj->SetTrackArray(  tof_nuc_obj  );
3837          orb2_nuc_obj->SetTrackArray(  orb_nuc_obj  );
3838    
3839      }    
3840      if(EXT){
3841          
3842          cout << "Found extended tracking algorythm branches" << endl;
3843    
3844  //--------------------------------------        t->SetBranchAddress("extAlgFlag",&extAlgFlag);
 //  
 //  
 //--------------------------------------  
 /**  
  * Set branch addresses for Pamela friend trees  
  */  
 void PamLevel2::SetBranchAddress(TTree *t){  
3845    
3846      TRK2    = TRK2 & t->GetBranchStatus("TrkLevel2");        if( !trk_ext_obj )trk_ext_obj = new TClonesArray("ExtTrack");
3847      TRK1    = TRK1 & t->GetBranchStatus("TrkLevel1");        if( !calo_ext_obj)calo_ext_obj= new TClonesArray("CaloTrkVar");
3848      TRKh    = TRKh & t->GetBranchStatus("TrkHough");        if( !tof_ext_obj)tof_ext_obj= new TClonesArray("ToFTrkVar");
3849      CAL2    = CAL2 & t->GetBranchStatus("CaloLevel2");        if( !orb_ext_obj)orb_ext_obj= new TClonesArray("OrbitalInfoTrkVar");
3850      CAL1    = CAL1 & t->GetBranchStatus("CaloLevel1");        
3851      TOF    = TOF & t->GetBranchStatus("ToFLevel2");        if (TRK2)t->                          SetBranchAddress("RecoveredTrack",&trk_ext_obj);
3852      TRG    = TRG & t->GetBranchStatus("TrigLevel2");        if (CAL2)t->GetFriend("Calorimeter")->SetBranchAddress("RecoveredTrack",&calo_ext_obj);
3853      S4     = S4  & t->GetBranchStatus("S4Level2");        if (TOF )t->GetFriend("ToF")->        SetBranchAddress("RecoveredTrack",&tof_ext_obj);
3854      ND     = ND  & t->GetBranchStatus("NDLevel2");        if (ORB )t->GetFriend("OrbitalInfo")->SetBranchAddress("RecoveredTrack",&orb_ext_obj);
3855      AC     = AC  & t->GetBranchStatus("AcLevel2");        
3856      ORB    = ORB & t->GetBranchStatus("OrbitalInfo");        if(NUC){
3857              if( !trk_ext_nuc_obj )trk_ext_nuc_obj = new TClonesArray("ExtTrack");
3858              if( !calo_ext_nuc_obj)calo_ext_nuc_obj= new TClonesArray("CaloTrkVar");
3859      // Tracker            if( !tof_ext_nuc_obj)tof_ext_nuc_obj= new TClonesArray("ToFTrkVar");
3860      if(TRK1) {            if( !orb_ext_nuc_obj)orb_ext_nuc_obj= new TClonesArray("OrbitalInfoTrkVar");
3861          t->SetBranchAddress("TrkLevel1", GetPointerTo("TrkLevel2"));            if (TRK2)t->                          SetBranchAddress("RecoveredTrackNuclei",&trk_ext_nuc_obj);
3862          cout << "Tracker      : set branch address TrkLevel1"<<endl;            if (CAL2)t->GetFriend("Calorimeter")->SetBranchAddress("RecoveredTrackNuclei",&calo_ext_nuc_obj);
3863      };            if (TOF )t->GetFriend("ToF")->        SetBranchAddress("RecoveredTrackNuclei",&tof_ext_nuc_obj);
3864      if(TRK2) {            if (ORB )t->GetFriend("OrbitalInfo")->SetBranchAddress("RecoveredTrackNuclei",&orb_ext_nuc_obj);
3865          t->SetBranchAddress("TrkLevel2", GetPointerTo("TrkLevel1"));        }
3866          cout << "Tracker      : set branch address TrkLevel2"<<endl;    }    
3867      };    
     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;  
     };  
       
3868  }  }
3869    
3870  /**  /**
3871   * Set branch addresses for Pamela friend trees   * Set the tracking algorythm
3872     * @param alg String to choose the track.
3873     * "" --> take the output of the standard tracking algorythm
3874     * "STD" --> take the output of the standard tracking algorythm
3875     * "NUC" --> take the output of the standard tracking algorythm for nuclei cluster selection
3876     * "EXT" --> in case the standard tracking algorythm has not found any track, take the output of the extended one
3877     * "EXTF" --> force the extended tracking algorythm
3878     * "NUCEXT" --> as "EXT", but for nuclei
3879     * "NUCEXTF" --> as "EXTF", but for nuclei
3880   */   */
3881  void PamLevel2::SetBranchAddress(TChain *t){  // void PamLevel2::SetTrackingAlgorythm(const char *alg){
3882    
3883    
3884    //     TString s(alg);
3885    //     if(s.Contains("NUC", TString::kIgnoreCase) && !NUC)
3886    //      cout << "Warning! NUC algorythm requested, but branches are missing"<<endl;
3887    //     if(s.Contains("EXT", TString::kIgnoreCase) && !EXT)
3888    //      cout << "Warning! EXT algorythm requested, but branches are missing"<<endl;;
3889                
3890    //     trkAlg = alg;
3891    
3892    // };
3893    // const char* PamLevel2::GetTrackingAlgorythm(){
3894    
3895    
3896    //     cout<<endl<<" Implemented tracking algorythm: ";
3897    //     cout<<endl<<"  \"\" or \"STD\"  --> take the output of the standard tracking algorythm";
3898    //     cout<<endl<<"  \"NUC\"      --> take the output of the standard tracking algorythm for nuclei cluster selection";
3899    //     cout<<endl<<"  \"EXT\"      --> in case the standard tracking algorythm has not found any track,";
3900    //     cout<<endl<<"                 take the output of the extended one";
3901    //     cout<<endl<<"  \"EXTF\"     --> force the extended tracking algorythm";
3902    //     cout<<endl<<"  \"NUCEXT\"   --> as \"EXT\", but for nuclei ";
3903    //     cout<<endl<<"  \"NUCEXTF\"  --> as \"EXTF\", but for nuclei";
3904    
3905    //     cout<<endl;
3906    //     cout<<" <<Currently set algorythm>> "<<trkAlg<<endl;
3907    //     cout<<endl;
3908    
3909    //     return trkAlg;
3910    // };
3911    
     TRK2    = TRK2 & t->GetBranchStatus("TrkLevel2");  
     TRK1    = TRK1 & t->GetBranchStatus("TrkLevel1");  
     TRKh    = TRKh & t->GetBranchStatus("TrkHough");  
     CAL1    = CAL1 & t->GetBranchStatus("CaloLevel1");  
     CAL2    = CAL2 & t->GetBranchStatus("CaloLevel2");  
     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(TRK2) {  
         t->SetBranchAddress("TrkLevel2", GetPointerTo("TrkLevel2"));  
         cout << "Tracker      : set branch address TrkLevel2"<<endl;  
     };  
     if(TRK1) {  
         t->SetBranchAddress("TrkLevel1", GetPointerTo("TrkLevel1"));  
         cout << "Tracker      : set branch address TrkLevel1"<<endl;  
     };  
      if(TRKh) {  
         t->SetBranchAddress("TrkHough", GetPointerTo("TrkHough"));  
         cout << "Tracker      : set branch address TrkHough"<<endl;  
      };  
       
     // 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;  
     };  
       
 }  
3912    
3913    
3914  //--------------------------------------  //--------------------------------------
# Line 1443  void PamLevel2::SetBranchAddress(TChain Line 3917  void PamLevel2::SetBranchAddress(TChain
3917  //--------------------------------------  //--------------------------------------
3918  /**  /**
3919   * Get the Run tree chain from a list of files.   * Get the Run tree chain from a list of files.
3920   * @param fl Pointer to a TList of TSystemFiles   * @param fl Pointer to a TList of TSystemFiles
3921   * @return Pointer to a TChain   * @return Pointer to a TChain
3922   */   */
3923  TChain *PamLevel2::GetRunTree(TList *fl){  TChain *PamLevel2::GetRunTree(TList *fl) {
3924              //
3925      TChain *R = new TChain("Run");    //
3926          //
3927      // loop over files and create chains            if (run_tree) {
3928      TIter next(fl);      printf("WARNING: TChain *PamLevel2::GetRunTree(TList *fl) -- run_tree already exists!\n ");
3929      TSystemFile *questo = 0;      return run_tree;
3930      while ( (questo = (TSystemFile*) next()) ) {    };
3931          TString name =  questo->GetName();    //
 //              cout << "File: "<< name << endl;  
         if( CheckLevel2File(name) ){  
             R->Add(name);  
         };  
     }  
3932    
3933      if(R->GetNtrees()){  
3934          TChain *R = new TChain("Run");
3935          R->SetBranchAddress("RunInfo", GetPointerTo("RunInfo"));  
3936          cout << "Run         : set branch address RunInfo"<<endl;    // loop over files and create chains
3937          R->SetBranchAddress("SoftInfo", GetPointerTo("SoftInfo")); // Emiliano    TIter next(fl);
3938          cout << "Software    : set branch address SoftInfo"<<endl; // Emiliano    TSystemFile *questo = 0;
3939      }else{    while ((questo = (TSystemFile*) next())) {
3940          delete R;      TString name = questo->GetName();
3941          R=0;      //          cout << "File: "<< name << endl;
3942        if (CheckLevel2File(name)) {
3943          R->Add(name);
3944        };
3945      }
3946    
3947      cout << "done run chain  "<<  R->GetNtrees() <<" \n";
3948    
3949    
3950      if (RUN && R->GetNtrees()) {
3951    
3952        R->SetBranchAddress("RunInfo", GetPointerTo("RunInfo"));
3953        cout << "Run         : set branch address RunInfo" << endl;
3954        R->SetBranchAddress("SoftInfo", GetPointerTo("SoftInfo")); // Emiliano
3955        cout << "Software    : set branch address SoftInfo" << endl; // Emiliano
3956    
3957        irunoffset = new int[R->GetNtrees()];
3958        if (DBG) {
3959          cout << "----------------------------------------------------" << endl;
3960          cout << "irun\t | ";
3961          cout << "tree\t |";
3962          //        cout << "offset\t |";
3963          cout << "RUN\t";
3964          cout << "FRAG\t";
3965          cout << "NEVENTS\t";
3966          cout << "absolute time\t\t\t";
3967          cout << "on-board time";
3968          cout << endl;
3969      }      }
3970        for (Int_t ii = 0; ii < R->GetEntries(); ii++) {
3971          R->GetEntry(ii);
3972          if (DBG) {
3973            cout << ii << "\t | ";
3974            cout << R->GetTreeNumber() << "\t |";
3975            //          cout << R->GetChainOffset()<< "\t |";
3976            cout << GetRunInfo()->ID << "\t";
3977            cout << GetRunInfo()->ID_RUN_FRAG << "\t";
3978            cout << GetRunInfo()->NEVENTS << "\t";
3979            cout << GetRunInfo()->RUNHEADER_TIME << " <---> " << GetRunInfo()->RUNTRAILER_TIME << "\t";
3980            cout << GetRunInfo()->RUNHEADER_OBT << " <---> " << GetRunInfo()->RUNTRAILER_OBT << "\t";
3981            cout << endl;
3982          }
3983          irunoffset[R->GetTreeNumber()] = R->GetChainOffset();
3984        }
3985        cout << "N.run = " << R->GetEntries() << endl;
3986        cout << "----------------------------------------------------" << endl;
3987    
3988      run_tree = R;    }
3989    //   else {
3990    //     delete R;
3991    //     R = 0;
3992    //   }
3993    
3994      run_tree = R;
3995    
3996      return R;
3997    
     return R;  
       
3998  }  }
3999  //--------------------------------------  //--------------------------------------
4000  //  //
# Line 1483  TChain *PamLevel2::GetRunTree(TList *fl) Line 4002  TChain *PamLevel2::GetRunTree(TList *fl)
4002  //--------------------------------------  //--------------------------------------
4003  /**  /**
4004   * Get the Run tree  from a file.   * Get the Run tree  from a file.
4005   * @param f Pointer to a TFile   * @param f Pointer to a TFile
4006   * @return Pointer to a TTree   * @return Pointer to a TTree
4007   */   */
4008  TTree *PamLevel2::GetRunTree(TFile *f){  TTree *PamLevel2::GetRunTree(TFile *f) {
4009      if (run_tree) {
4010        printf("WARNING: TTree *PamLevel2::GetRunTree(TFile *f) -- run_tree already exists!\n ");
4011        return run_tree;
4012      };
4013    
4014      cout << "TTree *PamLevel2::GetRunTree(TFile *f) -- obsolte "<<endl;    cout << "TTree *PamLevel2::GetRunTree(TFile *f) -- obsolte " << endl;
4015    
4016      TTree *T = (TTree*) f->Get("Run");
4017    
4018      if (T) {
4019        T->SetBranchAddress("RunInfo", GetPointerTo("RunInfo"));
4020        cout << "Run         : set branch address RunInfo" << endl;
4021        T->SetBranchAddress("SoftInfo", GetPointerTo("SoftInfo")); // Emiliano
4022        cout << "Software    : set branch address SoftInfo" << endl; // Emiliano
4023    
4024      }
4025    
4026      run_tree = (TChain*) T;
4027    
4028      return T;
4029    
     TTree *R = (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  
     }  
     return R;  
       
4030  }  }
4031  /**  
4032   * Update the runinfo informations (to be used to have Run infos event by event basis)  Bool_t PamLevel2::UpdateRunInfo(Long64_t iev) {
4033   * @param run Pointer to the chain/tree which contains run infos  
4034   * @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");
4035   */  
4036  Bool_t PamLevel2::UpdateRunInfo(TChain *run, ULong64_t iev){    if (!run_tree) {
4037    //      cout << " Bool_t PamLevel2::UpdateRunInfo(ULong64_t iev) -- ERROR -- run tree not loaded" << endl;
4038    // check if we have already called once GetEntry, if not call it      return false;
4039    //    }
4040    if ( run->GetEntries() <= 0 ) return(false);    if (run_tree->GetEntries() <= 0) {
4041    //      cout << " Bool_t PamLevel2::UpdateRunInfo(ULong64_t iev) -- ERROR -- run tree is empty" << endl;
4042          return (false);
4043    Int_t oldrun = irun;    }
4044    // --------------------------------------  
4045    
4046      Int_t oldrun = irun; // store current run index
4047    
4048      // -----------------------------------------------------------------------
4049      // the first time the routine is called, set run search from the beginning
4050      // -----------------------------------------------------------------------
4051    
4052      if (irun < 0) {
4053        irun = 0LL;
4054        irunt = 0LL;
4055        totrunentry = 0LL;
4056        totrunentrymin = 0LL;
4057        totrunentrymax = 0LL;
4058        irunentry = 0LL;
4059        il0entry = 0LL;
4060        prevshift = 0;
4061        yprevshift = 0;
4062        prevabstime = 0;
4063        prevpktnum = 0;
4064        abstime = 0ULL;
4065        pktnum = 0;
4066        isFragment = false;
4067        run_tree->GetEntry(irun);
4068        if (!GetOrbitalInfo())
4069          cout << "** WARNING ** missing OrbitalInfo ---> run info might be not correctly updated " << endl;
4070        if ( fUseDBinRunInfo ){
4071          if (gltsync)
4072            delete gltsync; //Emiliano
4073          if (!dbc || (dbc && !dbc->IsConnected()))
4074            SetDBConnection(); //Emiliano
4075          gltsync = new GL_TIMESYNC(GetRunInfo()->ID_ROOT_L0, "ID", dbc, false); //Emiliano // the "false" means not to use level0 file (not necessary here)
4076          if (dbc){
4077            dbc->Close();// Emiliano
4078            delete dbc;
4079            dbc=0;
4080          }
4081        }
4082      }
4083      // ---------------------------------------------------------------
4084      // retrieve OBT and absolute time of the event
4085      // ---------------------------------------------------------------
4086      Long64_t obt = 0LL; // Emiliano, Long64_t GL_TIMESYNC::DBobt(UInt_t obt) since depending on the situation OBT is lowered or boosted
4087      prevabstime = abstime;
4088      prevpktnum = pktnum;
4089      if (GetOrbitalInfo()) {
4090        abstime = GetOrbitalInfo()->absTime;
4091        if ( fUseDBinRunInfo ) obt = gltsync->DBobt(GetOrbitalInfo()->OBT); // Emiliano
4092        pktnum = GetOrbitalInfo()->pkt_num; // Emiliano
4093      }
4094      else {
4095        abstime = GetRunInfo()->RUNHEADER_TIME;
4096        if ( fUseDBinRunInfo ) obt = gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT); // Emiliano
4097        pktnum = GetRunInfo()->RUNHEADER_PKT; // Emiliano
4098      }
4099    
4100      if (DBG){
4101        printf("0abstime %lld %lld pktnum %d %d obt %lld \n",abstime,prevabstime,pktnum,prevpktnum,obt);
4102        printf("0        rth %d %d nevents %d  \n",GetRunInfo()->RUNHEADER_TIME,GetRunInfo()->RUNTRAILER_TIME,GetRunInfo()->NEVENTS);
4103        printf("0        rto %d %d \n",GetRunInfo()->RUNHEADER_OBT,GetRunInfo()->RUNTRAILER_OBT);
4104        if ( fUseDBinRunInfo ) printf("0        rto2 %lld %lld \n",gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT),gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT));
4105        printf("0        bo irunentry %lld prevshift %lld irun %lld  \n",irunentry,prevshift,irun);
4106        printf("0        min %lld iev %lld max %lld tot %lld \n",totrunentrymin,iev,totrunentrymax,totrunentry);
4107      }
4108    
4109      // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
4110    // if it is a full file (not preselected)    // if it is a full file (not preselected)
4111    // --------------------------------------    // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
4112    if(SELLI==0){    if (SELLI == 0 || SELLI == 2) { // Emiliano
4113        if ( irun < 0 ){  
4114            irun = 0;      // ---------------------------------------------------------------
4115            run->GetEntry(irun);      // increment dead and live-time counters
4116            runfirstentry = 0ULL;      // (only when reading a file not preselected)
4117            runlastentry += (ULong64_t)(this->GetRunInfo()->NEVENTS) - 1ULL;      // ---------------------------------------------------------------
4118            return(true);      if (SELLI == 0) {
4119        };              if (GetTrigLevel2()) {
4120            totdltime[0] += GetTrigLevel2()->dltime[0];
4121        if( !GetOrbitalInfo() ){          totdltime[1] += GetTrigLevel2()->dltime[1];
4122            cout << "Bool_t PamLevel2::UpdateRunInfo(TChain *run, ULong64_t iev) -- ERROR -- missing OrbitalInfo "<<endl;        }
4123            return(false);        totdltime[2]++;
4124        }      }
4125        // modificato il controllo sull'aggiornamento del run, per evitare problemi  
4126        // dovuti agli eventi annidati (NB! NEVENTS conta anche questi!!)      //
4127        while ( GetOrbitalInfo()->absTime > GetRunInfo()->RUNTRAILER_TIME && irun < run->GetEntries() ){      bool a = true;
4128  //      while ( iev > (runfirstentry+(ULong64_t)(this->GetRunInfo()->NEVENTS-1)) && irun < run->GetEntries() ){      bool b = true;
4129            //    printf(" iev %llu %u %llu \n",iev,this->GetRunInfo()->NEVENTS,(ULong64_t)(runfirstentry+(ULong64_t)(this->GetRunInfo()->NEVENTS)));      if ( fUseDBinRunInfo ){
4130            irun++;        a = false;    
4131            run->GetEntry(irun);        b = false;
4132            runfirstentry = runlastentry+1ULL;        if ( obt < gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT) ) a = true;
4133            runlastentry += (ULong64_t)(this->GetRunInfo()->NEVENTS);        if ( obt > gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT) ) b = true;
4134        };      }
4135        if ( iev < totrunentrymin || iev > totrunentrymax // entry is outside run limits
4136             || iev == 0 // or it is the first entry
4137             || (!isSync && (
4138                             (abstime <= GetRunInfo()->RUNHEADER_TIME && a ) // or it is outside obt limits (and abstime limits for security reasons)
4139                             || (abstime >= GetRunInfo()->RUNTRAILER_TIME && b ) ))// or it is outside obt limits (and abstime limits for security reasons)
4140             ){ // check on abstime and obt needed to handle nested+DV_skipped packets
4141                
4142        //        // check for a new run (ma prima il primo!)
4143        if        if (DBG){
4144   ( irun == oldrun || irun >= run->GetEntries() ) return(false);          printf("1abstime %lld %lld pktnum %d %d obt %lld \n",abstime,prevabstime,pktnum,prevpktnum,obt);
4145        //          printf("1        rth %d %d nevents %d  \n",GetRunInfo()->RUNHEADER_TIME,GetRunInfo()->RUNTRAILER_TIME,GetRunInfo()->NEVENTS);
4146        //  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        rto %d %d \n",GetRunInfo()->RUNHEADER_OBT,GetRunInfo()->RUNTRAILER_OBT);
4147        //          if ( fUseDBinRunInfo ) printf("1        rto2 %lld %lld \n",gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT),gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT));
4148        return(true);              printf("1        bo irunentry %lld prevshift %lld irun %lld  \n",irunentry,prevshift,irun);
4149    };          printf("1        min %lld iev %lld max %lld tot %lld \n",totrunentrymin,iev,totrunentrymax,totrunentry);
4150    // ----------------------------------------------------        }
4151          //        printf("1abstime %lld %lld pktnum %d %d obt %lld \n",abstime,prevabstime,pktnum,prevpktnum,obt);
4152          //        printf("1        rth %d %d nevents %d  \n",GetRunInfo()->RUNHEADER_TIME,GetRunInfo()->RUNTRAILER_TIME,GetRunInfo()->NEVENTS);
4153          //        printf("1        rto %d %d \n",GetRunInfo()->RUNHEADER_OBT,GetRunInfo()->RUNTRAILER_OBT);
4154          //        printf("1        rto2 %lld %lld \n",gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT),gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT));
4155          //        printf("1        bo irunentry %lld prevshift %lld irun %lld  \n",irunentry,prevshift,irun);
4156          //        printf("1        min %lld iev %lld max %lld tot %lld \n",totrunentrymin,iev,totrunentrymax,totrunentry);//TOGLITOGLI
4157    
4158          totrunentry = 0LL;
4159          runfirstentry = 0LL;
4160          for (Int_t r=0; r< run_tree->GetEntries();r++){
4161            // -------------------------------------------------------------------
4162            // save the index of the first entry of the run, relative to pam_tree,
4163            // and read a new run
4164            // -------------------------------------------------------------------
4165            run_tree->GetEntry(r);//update runinfo
4166            if ( r > 0 ){
4167              totrunentrymin = totrunentrymax+1;
4168            } else {
4169              totrunentrymin = 0LL;
4170            }
4171            totrunentry += GetRunInfo()->NEVENTS;
4172            totrunentrymax = totrunentry - 1 - prevshift; // prevshift is needed to handle nested+DV_skipped packets
4173            irun = r;        
4174            if ( fUseDBinRunInfo ){
4175              a = false;    
4176              b = false;
4177              if ( obt < gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT) ) a = true;
4178              if ( obt > gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT) ) b = true;
4179            }
4180            if ( (iev >= totrunentrymin && iev <= totrunentrymax) || // entry is inside run limits
4181                 ( !isSync &&
4182                   ( abstime >= GetRunInfo()->RUNHEADER_TIME  && a // or it is inside obt limits (and abstime limits for security reasons)
4183                     && abstime <= GetRunInfo()->RUNTRAILER_TIME && b))  // or it is inside obt limits (and abstime limits for security reasons)
4184                 ){ // check on abstime and obt needed to handle nested+DV_skipped packets
4185              if ( totrunentrymin > iev ){ // there is a shift (nested+DV_skipped packets)
4186                if ( !isSync ){
4187                  if (DBG) printf("PamLevel2::UpdateRunInfo(Long64_t) - unconsistent iev - nevents, probable DBL0-L2 async\n");
4188                  if (DBG) printf("PamLevel2::UpdateRunInfo(Long64_t) - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);
4189                  //              printf("PamLevel2::UpdateRunInfo(Long64_t) - unconsistent iev - nevents, probable DBL0-L2 async\n");
4190                  //              printf("PamLevel2::UpdateRunInfo(Long64_t) - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);//TOGLITOGLI
4191                  prevshift += (totrunentrymin-iev); // add the new shift to total shift
4192                  totrunentrymin -= (totrunentrymin-iev); // shift run position min
4193                  totrunentrymax -= (totrunentrymin-iev); // shift run position max
4194                  if (DBG) printf("PamLevel2::UpdateRunInfo(Long64_t) - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);
4195                  //              printf("PamLevel2::UpdateRunInfo(Long64_t) - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);//TOGLITOGLI
4196                } else {
4197                  printf(" PamLevel2::UpdateRunInfo(Long64_t) ERROR! sync file but unconsistent totrunetrymin %lld and iev %lld!!! \n",totrunentrymin,iev);
4198                  cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
4199                  cout << "\nFor bug reporting instructions, please see for example:\n";
4200                  cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
4201                  cout << "  " << endl;
4202                }
4203              }
4204              runfirstentry = totrunentrymin; // first entry of the run in the level2
4205              
4206    
4207              //
4208              if ( fUseDBinRunInfo ){
4209                if (gltsync)
4210                  delete gltsync; // Emiliano
4211                if (!dbc || (dbc && !dbc->IsConnected()))
4212                  SetDBConnection(); //Emiliano
4213                gltsync = new GL_TIMESYNC(GetRunInfo()->ID_ROOT_L0, "ID", dbc, false); // Emiliano
4214                TrkParams::Set(GetRunInfo(), dbc);
4215                if (dbc){
4216                  dbc->Close(); // Emiliano
4217                  delete dbc;
4218                  dbc=0;
4219                }          
4220                if (gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT) > gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT)) { // Emiliano
4221                  cout << "Bool_t PamLevel2::UpdateRunInfo(Long64_t iev) -- WARNING -- irun " << irun
4222                       << "  has RUNHEADER_OBT>=RUNTRAILER_OBT " << endl;
4223                  cout
4224                    << "                                                            (NB!! in this case some events could be assigned to a wrong run)"
4225                    << endl;
4226                }
4227              }
4228              //
4229              if (DBG) printf(" found \n");
4230              //          printf(" found \n");//TOGLITOGLI
4231              //
4232              break;
4233            }
4234          } // loop over run
4235          
4236          // --------------------------------------
4237          // if there was no need to update the run
4238          // ---> exit with FALSE
4239          // --------------------------------------
4240          if (irun == oldrun){
4241            if (DBG) printf(" no new run \n");
4242            //        printf(" no new run \n");//TOGLITOGLI
4243            return (false);
4244          }      
4245          // --------------------------------------
4246          // ... otherwise
4247          // ---> exit with TRUE
4248          // --------------------------------------
4249    
4250          if (SELLI != 2) {
4251            /// decrement counters since this event belongs to a new run
4252            if (GetTrigLevel2()) {
4253              totdltime[0] -= GetTrigLevel2()->dltime[0];//live-time
4254              totdltime[1] -= GetTrigLevel2()->dltime[1];//dead-time
4255            }
4256            totdltime[2]--; //event counter
4257            if (DBG) {
4258              cout << endl;
4259              cout << "n.events     : " << totdltime[2] << endl;
4260              cout << "RUN LIVE-TIME: " << totdltime[0] * 0.16 << " ms" << endl;
4261              cout << "RUN DEAD-TIME: " << totdltime[1] * 0.01 << " ms" << endl;
4262            }
4263            // add an entry
4264            if (run_tree_clone && totdltime[2] > 0)
4265              if (run_tree_clone->GetBranch("DeadLiveTime")->GetEntries() < run_tree->GetEntries())
4266                run_tree_clone->GetBranch("DeadLiveTime")->Fill();
4267            // reset counters
4268            if ( totdltime[2] > 0 ){
4269              if (GetTrigLevel2()) {
4270                totdltime[0] = GetTrigLevel2()->dltime[0];//live-time
4271                totdltime[1] = 0; //dead-time
4272              }
4273              totdltime[2] = 1; //event counter
4274            }
4275          }
4276    
4277          if (DBG){
4278            cout << endl << " ))))) UPDATE RUN INFO (((((  @iev " << iev << " run " << GetRunInfo()->ID << " irun " << irun
4279                 << endl;        
4280            printf("2abstime %lld %lld pktnum %d %d obt %lld \n",abstime,prevabstime,pktnum,prevpktnum,obt);
4281            printf("2        rth %d %d nevents %d  \n",GetRunInfo()->RUNHEADER_TIME,GetRunInfo()->RUNTRAILER_TIME,GetRunInfo()->NEVENTS);
4282            printf("2        rto %d %d \n",GetRunInfo()->RUNHEADER_OBT,GetRunInfo()->RUNTRAILER_OBT);
4283            if ( fUseDBinRunInfo ) printf("2        rto2 %lld %lld \n",gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT),gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT));
4284            printf("2        bo irunentry %lld prevshift %lld irun %lld  \n",irunentry,prevshift,irun);
4285            printf("2        min %lld iev %lld max %lld tot %lld \n",totrunentrymin,iev,totrunentrymax,totrunentry);
4286          }
4287          //        printf("2abstime %lld %lld pktnum %d %d obt %lld \n",abstime,prevabstime,pktnum,prevpktnum,obt);
4288          //        printf("2        rth %d %d nevents %d  \n",GetRunInfo()->RUNHEADER_TIME,GetRunInfo()->RUNTRAILER_TIME,GetRunInfo()->NEVENTS);
4289          //        printf("2        rto %d %d \n",GetRunInfo()->RUNHEADER_OBT,GetRunInfo()->RUNTRAILER_OBT);
4290          //        printf("2        rto2 %lld %lld \n",gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT),gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT));
4291          //        printf("2        bo irunentry %lld prevshift %lld irun %lld  \n",irunentry,prevshift,irun);
4292          //        printf("2        min %lld iev %lld max %lld tot %lld \n",totrunentrymin,iev,totrunentrymax,totrunentry);//TOGLITOGLI
4293    
4294          return (true);
4295        } // need for run upgrade
4296        if (DBG) printf("return false\n");
4297        return (false);
4298      }// SELLI = 0 SELLI = 2
4299      
4300      // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
4301    // if it is a preselected file (there is SelectionList)    // if it is a preselected file (there is SelectionList)
4302    // NBNB - the event tree MUST be read first    // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
4303    // ----------------------------------------------------    // irun  = run entry relative to the chain
4304    if(SELLI==1){          // irunt = run entry relative to the tree
4305        sel_tree->GetEntry(iev);    if (SELLI == 1) {
4306        if(irun != oldrun){      sel_tree->GetEntry(iev);// read irunt from SelectionList
4307            run->GetEntry(irun);      irun = irunt + irunoffset[sel_tree->GetTreeNumber()];//NEWNEW
4308            return true;      if (irun != oldrun) {
4309          if (irun < run_tree->GetEntries())
4310            run_tree->GetEntry(irun);
4311          // check if the time is ok (with merged files it is not...)
4312          // if not loop over run and look for the proper entry
4313          bool SECONDO_GIRO = false;
4314          //            Long64_t irun_start   = irun;
4315          int offset_start = irunoffset[sel_tree->GetTreeNumber()];
4316          while (((!(abstime >= GetRunInfo()->RUNHEADER_TIME && // check on absolute time (s)
4317              abstime <= GetRunInfo()->RUNTRAILER_TIME)
4318          //                        ||
4319          //                        !(obt >= GetRunInfo()->RUNHEADER_OBT &&         // additional check on OBT (ms)
4320          //                          obt <= GetRunInfo()->RUNTRAILER_OBT)
4321          ) || GetRunInfo()->NEVENTS == 0)
4322          //                && irun < run_tree->GetEntries()
4323          ) {
4324    
4325            if (DBG) {
4326              cout << " (test) ";
4327              cout << " tree " << sel_tree->GetTreeNumber();
4328              cout << " irunt " << irunt;
4329              cout << " offset " << irunoffset[sel_tree->GetTreeNumber()];
4330              cout << " abs " << abstime;
4331              cout << " >> " << GetRunInfo()->RUNHEADER_TIME << " " << GetRunInfo()->RUNTRAILER_TIME;
4332              cout << " obt " << obt;
4333              cout << " >> " << GetRunInfo()->RUNHEADER_OBT << " " << GetRunInfo()->RUNTRAILER_OBT;
4334              cout << " *** JUMP RUN *** irun " << irun;
4335              cout << endl;
4336            }
4337            //              irun++;
4338            irunoffset[sel_tree->GetTreeNumber()]++;
4339            irun = irunt + irunoffset[sel_tree->GetTreeNumber()];//NEWNEW
4340            if (irun == run_tree->GetEntries() && SECONDO_GIRO) {
4341              //            if(irun == irun_start ){
4342              cout << " ...grrrvzzkhhhajsdkj!!!! " << endl;
4343              irunoffset[sel_tree->GetTreeNumber()] = offset_start;
4344              return false;
4345            }
4346            if (irun >= run_tree->GetEntries() || irun < 0) {
4347              cout << "irun = " << irun << " >>  search from the beginning... <<" << endl;
4348              SECONDO_GIRO = true;
4349              irun = 0;
4350              irunoffset[sel_tree->GetTreeNumber()] = -irunt;
4351            }
4352            run_tree->GetEntry(irun);
4353          }
4354    
4355          if (DBG) {
4356            cout << " (test) ";
4357            cout << " tree " << sel_tree->GetTreeNumber();
4358            cout << " irunt " << irunt;
4359            cout << " offset " << irunoffset[sel_tree->GetTreeNumber()];
4360            cout << " abs " << abstime;
4361            cout << " >> " << GetRunInfo()->RUNHEADER_TIME << " " << GetRunInfo()->RUNTRAILER_TIME;
4362            cout << " obt " << obt;
4363            cout << " >> " << GetRunInfo()->RUNHEADER_OBT << " " << GetRunInfo()->RUNTRAILER_OBT;
4364        }        }
4365        return false;        if (DBG)
4366            cout << endl;
4367          if (DBG)
4368            cout << endl << " ))))) UPDATE RUN INFO (((((  @iev " << iev << " run " << GetRunInfo()->ID << " (run-entry "
4369                << irun << ")" << endl;
4370          // ----------------------------------------------------
4371          // update the tracker parameters
4372          // (non ho trovato nessun altro modo sicuro di farlo...)
4373          // ----------------------------------------------------
4374          if ( fUseDBinRunInfo ){
4375            if (!dbc || (dbc && !dbc->IsConnected()))
4376              SetDBConnection();
4377            TrkParams::Set(GetRunInfo(), dbc);
4378            if (dbc){
4379              dbc->Close();
4380              delete dbc;
4381              dbc=0;
4382            }
4383          }
4384          //            cout << endl;
4385          prevshift = 0;
4386          yprevshift = 0;
4387          return true;
4388        }
4389        return false;
4390    }    }
4391    
4392    return false;    return false;
4393    //    //
4394  };  }
4395    
4396  /**  /**
4397   * 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)
4398   * @param run Pointer to the chain/tree which contains run infos   * @param run Pointer to the chain/tree which contains run infos
4399   * @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
4400   */   */
4401  Bool_t PamLevel2::UpdateRunInfo(TTree *run, ULong64_t iev){  Bool_t PamLevel2::UpdateRunInfo(TChain *run, Long64_t iev) {
4402    return(UpdateRunInfo((TChain*)run,iev));    return (UpdateRunInfo(iev));
4403  };  }
4404    
4405    /**
4406     * Update the runinfo informations (to be used to have Run infos event by event basis)
4407     * @param run Pointer to the chain/tree which contains run infos
4408     * @return true if a new run has been read, false if it is still the same run
4409     */
4410    Bool_t PamLevel2::UpdateRunInfo(TTree *run, Long64_t iev) {
4411      return (UpdateRunInfo((TChain*) run, iev));
4412    }
4413    
4414    
4415  //--------------------------------------  //--------------------------------------
4416  //  //
# Line 1580  Bool_t PamLevel2::UpdateRunInfo(TTree *r Line 4418  Bool_t PamLevel2::UpdateRunInfo(TTree *r
4418  //--------------------------------------  //--------------------------------------
4419  /**  /**
4420   * Set which trees shoul be analysed   * Set which trees shoul be analysed
4421   * @param detlist TString containing the sequence of trees required   * @param detlist TString containing the sequence of trees required
4422  */   */
4423  void PamLevel2::SetWhichTrees(TString detlist){  void PamLevel2::SetWhichTrees(TString detlist) {
           
     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;  
     };  
4424    
4425      if( detlist.Contains("CAL0", TString::kIgnoreCase) ){    //    if(detlist.IsNull() || detlist.Contains("+ALL", TString::kIgnoreCase)){
4426          if ( detlist.Contains("-CAL0", TString::kIgnoreCase) )CAL0=false;    if (detlist.Contains("+ALL", TString::kIgnoreCase)) {
         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;  
     };  
4427    
4428      if( detlist.Contains("TRK1", TString::kIgnoreCase) ){      cout << " ======================================================== " << endl;
4429          if ( detlist.Contains("-TRK1", TString::kIgnoreCase) )TRK1=false;      cout << "                       (( WARNING ))                      " << endl;
4430          if ( detlist.Contains("+TRK1", TString::kIgnoreCase) )TRK1=true;      cout << " The meaning of the option +ALL has changed!!             " << endl;
4431      };      cout << " Now it includes really all (level0+level1+level2+gpamela)" << endl;
4432                cout << " and the file is discarded if it does not contain         " << endl;
4433      if( detlist.Contains("TRK2", TString::kIgnoreCase)){      cout << " all trees or  if level0 files are not available!!        " << endl;
4434          if ( detlist.Contains("-TRK2", TString::kIgnoreCase) )TRK2=false;      cout << " ======================================================== " << endl;
         if ( detlist.Contains("+TRK2", TString::kIgnoreCase) )TRK2=true;  
     };  
4435    
4436      if( detlist.Contains("TRKh", TString::kIgnoreCase)){      CAL0 = true;
4437          if ( detlist.Contains("-TRKh", TString::kIgnoreCase) )TRKh=false;      CAL1 = true;
4438          if ( detlist.Contains("+TRKh", TString::kIgnoreCase) )TRKh=true;      CAL2 = true;
4439      };      TRK2 = true;
4440                TRK1 = true;
4441      if( detlist.Contains("+TRK", TString::kIgnoreCase) && !TRK1 && !TRK2 && !TRKh )TRK2=true;      TRKh = true;
4442      if( detlist.Contains("-TRK", TString::kIgnoreCase) && TRK1 && TRK2 && TRKh){      TRK0 = true;
4443          TRK2=false;      TRG = true;
4444          TRK1=false;      TOF = true;
4445          TRKh=false;      TOF0 = true;
4446      }      S4 = true;
4447  //  -------------------------------------------------------------------------      ND = true;
4448            AC = true;
4449      if( detlist.Contains("-TRG", TString::kIgnoreCase) )TRG = false;      ORB = true;
4450      else if( detlist.Contains("+TRG", TString::kIgnoreCase) )TRG = true;      GP = true;
4451          }
4452      if( detlist.Contains("-TOF", TString::kIgnoreCase) )TOF = false;    else if (detlist.Contains("-ALL", TString::kIgnoreCase)) {
4453      else if( detlist.Contains("+TOF", TString::kIgnoreCase) )TOF = true;      CAL0 = false;
4454        CAL1 = false;
4455        CAL2 = false;
4456        TRK2 = false;
4457        TRK1 = false;
4458        TRKh = false;
4459        TRK0 = false;
4460        TRG = false;
4461        TOF = false;
4462        TOF0 = false;
4463        S4 = false;
4464        ND = false;
4465        AC = false;
4466        ORB = false;
4467        GP = false;
4468      };
4469    
4470      if( detlist.Contains("-TOF0", TString::kIgnoreCase) )TOF0 = false;    //  -------------------------------------------------------------------------
4471      else if( detlist.Contains("+TOF0", TString::kIgnoreCase) )TOF0 = true;    if (detlist.Contains("CAL1", TString::kIgnoreCase)) {
4472            if (detlist.Contains("-CAL1", TString::kIgnoreCase))
4473      if( detlist.Contains("-S4",  TString::kIgnoreCase) )S4  = false;        CAL1 = false;
4474      else if( detlist.Contains("+S4",  TString::kIgnoreCase) )S4  = true;      if (detlist.Contains("+CAL1", TString::kIgnoreCase))
4475              CAL1 = true;
4476      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;  
4477    
4478  //     cout<< "Set detector list --> ";    if (detlist.Contains("CAL0", TString::kIgnoreCase)) {
4479  //     if(TRK1)cout<<"TRK1 ";      if (detlist.Contains("-CAL0", TString::kIgnoreCase))
4480  //     if(TRK2)cout<<"TRK2 ";        CAL0 = false;
4481  //     if(TRKh)cout<<"TRKH ";      if (detlist.Contains("+CAL0", TString::kIgnoreCase))
4482  //     if(CAL1)cout<<"CAL1 ";        CAL0 = true;
4483  //     if(CAL2)cout<<"CAL2 ";    };
4484  //     if(TOF)cout<<"TOF ";  
4485  //     if(TRG)cout<<"TRG ";    if (detlist.Contains("CAL2", TString::kIgnoreCase)) {
4486  //     if(AC)cout<<"AC ";      if (detlist.Contains("-CAL2", TString::kIgnoreCase))
4487  //     if(ND)cout<<"ND ";        CAL2 = false;
4488  //     if(S4)cout<<"S4 ";      if (detlist.Contains("+CAL2", TString::kIgnoreCase))
4489  //     if(ORB)cout<<"ORB ";        CAL2 = true;
4490  //     cout << endl;    };
4491        
4492  };    if (detlist.Contains("+CAL", TString::kIgnoreCase) && !CAL1 && !CAL2)
4493        CAL2 = true;
4494      if (detlist.Contains("-CAL", TString::kIgnoreCase) && CAL1 && CAL2) {
4495        CAL2 = false;
4496        CAL1 = false;
4497      }
4498      //  -------------------------------------------------------------------------
4499      if (detlist.Contains("TRK0", TString::kIgnoreCase)) {
4500        if (detlist.Contains("-TRK0", TString::kIgnoreCase))
4501          TRK0 = false;
4502        if (detlist.Contains("+TRK0", TString::kIgnoreCase))
4503          TRK0 = true;
4504      };
4505    
4506      if (detlist.Contains("TRK1", TString::kIgnoreCase)) {
4507        if (detlist.Contains("-TRK1", TString::kIgnoreCase))
4508          TRK1 = false;
4509        if (detlist.Contains("+TRK1", TString::kIgnoreCase))
4510          TRK1 = true;
4511      };
4512    
4513      if (detlist.Contains("TRK2", TString::kIgnoreCase)) {
4514        if (detlist.Contains("-TRK2", TString::kIgnoreCase))
4515          TRK2 = false;
4516        if (detlist.Contains("+TRK2", TString::kIgnoreCase))
4517          TRK2 = true;
4518      };
4519    
4520      if (detlist.Contains("TRKh", TString::kIgnoreCase)) {
4521        if (detlist.Contains("-TRKh", TString::kIgnoreCase))
4522          TRKh = false;
4523        if (detlist.Contains("+TRKh", TString::kIgnoreCase))
4524          TRKh = true;
4525      };
4526    
4527      if (detlist.Contains("+TRK", TString::kIgnoreCase) && !TRK1 && !TRK2 && !TRKh)
4528        TRK2 = true;
4529      if (detlist.Contains("-TRK", TString::kIgnoreCase) && TRK1 && TRK2 && TRKh) {
4530        TRK2 = false;
4531        TRK1 = false;
4532        TRKh = false;
4533      }
4534      //  -------------------------------------------------------------------------
4535    
4536      if (detlist.Contains("-TRG", TString::kIgnoreCase))
4537        TRG = false;
4538      else if (detlist.Contains("+TRG", TString::kIgnoreCase))
4539        TRG = true;
4540    
4541      if (detlist.Contains("-TOF", TString::kIgnoreCase))
4542        TOF = false;
4543      else if (detlist.Contains("+TOF", TString::kIgnoreCase))
4544        TOF = true;
4545    
4546      if (detlist.Contains("-TOF0", TString::kIgnoreCase))
4547        TOF0 = false;
4548      else if (detlist.Contains("+TOF0", TString::kIgnoreCase))
4549        TOF0 = true;
4550    
4551      if (detlist.Contains("-S4", TString::kIgnoreCase))
4552        S4 = false;
4553      else if (detlist.Contains("+S4", TString::kIgnoreCase))
4554        S4 = true;
4555    
4556      if (detlist.Contains("-ND", TString::kIgnoreCase))
4557        ND = false;
4558      else if (detlist.Contains("+ND", TString::kIgnoreCase))
4559        ND = true;
4560    
4561      if (detlist.Contains("-AC", TString::kIgnoreCase))
4562        AC = false;
4563      else if (detlist.Contains("+AC", TString::kIgnoreCase))
4564        AC = true;
4565    
4566      if (detlist.Contains("-ORB", TString::kIgnoreCase))
4567        ORB = false;
4568      else if (detlist.Contains("+ORB", TString::kIgnoreCase))
4569        ORB = true;
4570    
4571      if (detlist.Contains("-GP", TString::kIgnoreCase))
4572        GP = false;
4573      else if (detlist.Contains("+GP", TString::kIgnoreCase))
4574        GP = true;
4575    
4576      cout << "tree/branch list from input --> ";
4577      if (TRK0)
4578        cout << "TRK0 ";
4579      if (TRK1)
4580        cout << "TRK1 ";
4581      if (TRK2)
4582        cout << "TRK2 ";
4583      if (TRKh)
4584        cout << "TRKH ";
4585      if (CAL0)
4586        cout << "CAL0 ";
4587      if (CAL1)
4588        cout << "CAL1 ";
4589      if (CAL2)
4590        cout << "CAL2 ";
4591      if (TOF)
4592        cout << "TOF ";
4593      if (TRG)
4594        cout << "TRG ";
4595      if (AC)
4596        cout << "AC ";
4597      if (ND)
4598        cout << "ND ";
4599      if (S4)
4600        cout << "S4 ";
4601      if (ORB)
4602        cout << "ORB ";
4603      if (GP)
4604        cout << "GP ";
4605      cout << endl;
4606      //     cout<< "Set detector list --> ";
4607      //     if(TRK1)cout<<"TRK1 ";
4608      //     if(TRK2)cout<<"TRK2 ";
4609      //     if(TRKh)cout<<"TRKH ";
4610      //     if(CAL1)cout<<"CAL1 ";
4611      //     if(CAL2)cout<<"CAL2 ";
4612      //     if(TOF0)cout<<"TOF0 ";
4613      //     if(TOF)cout<<"TOF ";
4614      //     if(TRG)cout<<"TRG ";
4615      //     if(AC)cout<<"AC ";
4616      //     if(ND)cout<<"ND ";
4617      //     if(S4)cout<<"S4 ";
4618      //     if(ORB)cout<<"ORB ";
4619      //     cout << endl;
4620    
4621    }
4622    ;
4623    
4624  /**  /**
4625   * Set tree/branch detector flags from the content of a tree   * Set tree/branch detector flags from the content of a tree
4626   */   */
4627  void  PamLevel2::GetWhichTrees(TFile* f){  void PamLevel2::GetWhichTrees(TFile* f) {
       
4628    
4629      //    cout << "void  PamLevel2::GetWhichTrees(TFile* f) --- WARNING!! --- ...potrebbe non funzionare "<<endl;
4630      // -----------
4631      // reset flags
4632      // -----------
4633      CAL1 = false;
4634      CAL2 = false;
4635      TRK2 = false;
4636      TRK1 = false;
4637      TRKh = false;
4638      TRG = false;
4639      TOF = false;
4640      S4 = false;
4641      ND = false;
4642      AC = false;
4643      ORB = false;
4644      GP = false;
4645    
4646      RUN = false;
4647    
4648      //    cout << "Checking file: "<<f->GetName()<<endl;
4649      if (!f || f->IsZombie()) {
4650        cout << "File: " << f->GetName() << " Non valid root file" << endl;
4651        fDiscarded = true;
4652        return;
4653      }
4654    
4655      cout << "void  PamLevel2::GetWhichTrees(TFile* f) --- WARNING!! --- ...potrebbe non funzionare "<<endl;    TList *lk = f->GetListOfKeys();
4656      // -----------    if (!lk)
4657      // reset flags      return;
4658      // -----------    TIter next(lk);
4659      CAL1   = false;        TKey *key = 0;
4660      CAL2   = false;      
4661      TRK2   = false;        Int_t nev = 0;
4662      TRK1   = false;      
4663      TRKh   = false;        while ((key = (TKey*) next())) {
4664      TRG    = false;      
4665      TOF    = false;          if (!strcmp(key->GetName(), "Run"))
4666      S4     = false;            RUN = true;
4667      ND     = false;      
4668      AC     = false;          //=========================================================
4669      ORB    = false;          if (!strcmp(key->GetName(), "Trigger")) {
4670              TRG = true;
4671      RUN    = false;        Int_t nevt = ((TTree*) f->Get("Trigger"))->GetEntries();
4672                  if (nev && nevt != nev) {
4673      cout << "Checking file: "<<f->GetName()<<endl;          cout << "File: " << f->GetName() << " Trigger tree has " << nevt << " events instead of " << nev << endl;
4674      if( !f || f->IsZombie() ){          TRG = false;
4675          cout << "File: "<< f->GetName() <<" Non valid root file"<< endl;        }
4676          return;        else
4677            nev = nevt;
4678      }      }
4679        //=========================================================
4680        if (!strcmp(key->GetName(), "ToF")) {
4681          TOF = true;
4682          Int_t nevt = ((TTree*) f->Get("ToF"))->GetEntries();
4683          if (nev && nevt != nev) {
4684            cout << "File: " << f->GetName() << "     ToF tree has " << nevt << " events instead of " << nev << endl;
4685            TOF = false;
4686          }
4687          else
4688            nev = nevt;
4689        }
4690        //=========================================================
4691        if (!strcmp(key->GetName(), "S4")) {
4692          S4 = true;
4693          Int_t nevt = ((TTree*) f->Get("S4"))->GetEntries();
4694          if (nev && nevt != nev) {
4695            cout << "File: " << f->GetName() << "      S4 tree has " << nevt << " events instead of " << nev << endl;
4696            S4 = false;
4697          }
4698          else
4699            nev = nevt;
4700        }
4701        //=========================================================
4702    
4703      TList *lk = f->GetListOfKeys();      if (!strcmp(key->GetName(), "NeutronD")) {
4704      TIter next(lk);        ND = true;
4705      TKey *key =0;        Int_t nevt = ((TTree*) f->Get("NeutronD"))->GetEntries();
4706          if (nev && nevt != nev) {
4707      Int_t nev = 0;          cout << "File: " << f->GetName() << "NeutronD tree has " << nevt << " events instead of " << nev << endl;
4708            ND = false;
4709      while( (key = (TKey*)next()) ){        }
4710                  else
4711          if( !strcmp(key->GetName(),"Run"        ) )RUN = true;          nev = nevt;
4712        }
4713        //=========================================================
4714        if (!strcmp(key->GetName(), "Anticounter")) {
4715          AC = true;
4716          Int_t nevt = ((TTree*) f->Get("Anticounter"))->GetEntries();
4717          if (nev && nevt != nev) {
4718            cout << "File: " << f->GetName() << " Anticounter tree has " << nevt << " events instead of " << nev << endl;
4719            AC = false;
4720          }
4721          else
4722            nev = nevt;
4723        }
4724        //=========================================================
4725        if (!strcmp(key->GetName(), "OrbitalInfo")) {
4726          ORB = true;
4727          Int_t nevt = ((TTree*) f->Get("OrbitalInfo"))->GetEntries();
4728          if (nev && nevt != nev) {
4729            cout << "File: " << f->GetName() << " OrbitalInfo tree has " << nevt << " events instead of " << nev << endl;
4730            ORB = false;
4731          }
4732          else
4733            nev = nevt;
4734        }
4735        //=========================================================
4736        if (!strcmp(key->GetName(), "Tracker")) {
4737          TTree *T = (TTree*) f->Get("Tracker");
4738          for (Int_t i = 0; i < T->GetListOfBranches()->GetEntries(); i++) {
4739            TString name = T->GetListOfBranches()->At(i)->GetName();
4740            if (!name.CompareTo("TrkLevel1"))
4741              TRK1 = true;
4742            if (!name.CompareTo("TrkLevel2"))
4743              TRK2 = true;
4744            if (!name.CompareTo("TrkHough"))
4745              TRKh = true;
4746          };
4747          Int_t nevt = T->GetEntries();
4748          if (nev && nevt != nev) {
4749            cout << "File: " << f->GetName() << " Tracker tree has " << nevt << " events instead of " << nev << endl;
4750            TRK1 = false;
4751            TRK2 = false;
4752            TRKh = false;
4753          }
4754          else
4755            nev = nevt;
4756          //            T->Delete();
4757        };
4758        //=========================================================
4759        if (!strcmp(key->GetName(), "Calorimeter")) {
4760          TTree *T = (TTree*) f->Get("Calorimeter");
4761          for (Int_t i = 0; i < T->GetListOfBranches()->GetEntries(); i++) {
4762            TString name = T->GetListOfBranches()->At(i)->GetName();
4763            if (!name.CompareTo("CaloLevel1"))
4764              CAL1 = true;
4765            if (!name.CompareTo("CaloLevel2"))
4766              CAL2 = true;
4767          };
4768          Int_t nevt = T->GetEntries();
4769          if (nev && nevt != nev) {
4770            cout << "File: " << f->GetName() << "  Calorimeter tree has " << nevt << " events instead of " << nev << endl;
4771            CAL1 = false;
4772            CAL2 = false;
4773          }
4774          else
4775            nev = nevt;
4776          //            T->Delete();
4777        };
4778        //=========================================================
4779        if (!strcmp(key->GetName(), "h20")) {
4780          GP = true;
4781          Int_t nevt = ((TTree*) f->Get("h20"))->GetEntries();
4782          if (nev && nevt != nev) {
4783            cout << "File: " << f->GetName() << " h20 tree has " << nevt << " events instead of " << nev << endl;
4784            GP = false;
4785          }
4786          else
4787            nev = nevt;
4788        }
4789    
4790          //=========================================================        };
         if( !strcmp(key->GetName(),"Trigger"    ) ){  
             TRG = true;  
             Int_t nevt = ((TTree*)f->Get("Trigger"))->GetEntries();  
             if( nev && nevt!=nev){  
                 cout << "File: "<< f->GetName() <<" Trigger tree has "<<nevt<<" events instead of "<<nev<< endl;  
                 TRG = false;  
             }else nev=nevt;  
         }  
         //=========================================================      
         if( !strcmp(key->GetName(),"ToF"        ) ){  
             TOF = true;  
             Int_t nevt = ((TTree*)f->Get("ToF"))->GetEntries();  
             if( nev && nevt!=nev){  
                 cout << "File: "<< f->GetName() <<"     ToF tree has "<<nevt<<" events instead of "<<nev<< endl;  
                 TOF = false;  
             }else nev=nevt;  
         }  
         //=========================================================    
         if( !strcmp(key->GetName(),"S4"         ) ){  
             S4 = true;  
             Int_t nevt = ((TTree*)f->Get("S4"))->GetEntries();  
             if( nev && nevt!=nev){  
                 cout << "File: "<< f->GetName() <<"      S4 tree has "<<nevt<<" events instead of "<<nev<< endl;  
                 S4 = false;  
             }else nev=nevt;  
         }  
         //=========================================================    
4791    
4792          if( !strcmp(key->GetName(),"NeutronD"   ) ){    //    delete lk;
             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();  
         };        
4793    
4794      };    cout << "tree/branch list from file  --> ";
4795          if (TRK1)
4796      delete lk;      cout << "TRK1 ";
4797      if (TRK2)
4798        cout << "TRK2 ";
4799      if (TRKh)
4800        cout << "TRKH ";
4801      if (CAL1)
4802        cout << "CAL1 ";
4803      if (CAL2)
4804        cout << "CAL2 ";
4805      if (TOF)
4806        cout << "TOF ";
4807      if (TRG)
4808        cout << "TRG ";
4809      if (AC)
4810        cout << "AC ";
4811      if (ND)
4812        cout << "ND ";
4813      if (S4)
4814        cout << "S4 ";
4815      if (ORB)
4816        cout << "ORB ";
4817      if (GP)
4818        cout << "GP ";
4819      cout << endl;
4820    
4821  //     cout<< "Get detector list from input file --> ";    return;
 //     if(TRK1)cout<<"TRK1 ";  
 //     if(TRK2)cout<<"TRK2 ";  
 //     if(TRKh)cout<<"TRKH ";  
 //     if(CAL1)cout<<"CAL1 ";  
 //     if(CAL2)cout<<"CAL2 ";  
 //     if(TOF)cout<<"TOF ";  
 //     if(TRG)cout<<"TRG ";  
 //     if(AC)cout<<"AC ";  
 //     if(ND)cout<<"ND ";  
 //     if(S4)cout<<"S4 ";  
 //     if(ORB)cout<<"ORB ";  
 //     cout << endl;  
         
     return ;  
           
 };  
4822    
4823    }
4824    ;
4825    
4826  //--------------------------------------  //--------------------------------------
4827  //  //
# Line 1867  void  PamLevel2::GetWhichTrees(TFile* f) Line 4832  void  PamLevel2::GetWhichTrees(TFile* f)
4832   * @param name File name   * @param name File name
4833   * @return true if the file is ok.   * @return true if the file is ok.
4834   */   */
4835  Bool_t  PamLevel2::CheckLevel2File(TString name){  Bool_t PamLevel2::CheckLevel2File(TString name) {
4836            
4837      Bool_t CAL1__ok   = false;        Bool_t CAL1__ok = false;
4838      Bool_t CAL2__ok   = false;        Bool_t CAL2__ok = false;
4839      Bool_t TRK2__ok   = false;        Bool_t TRK2__ok = false;
4840      Bool_t TRK1__ok   = false;        Bool_t TRK1__ok = false;
4841      Bool_t TRKh__ok   = false;        Bool_t TRKh__ok = false;
4842      Bool_t TRG__ok    = false;        Bool_t TRG__ok = false;
4843      Bool_t TOF__ok    = false;        Bool_t TOF__ok = false;
4844      Bool_t S4__ok     = false;        Bool_t S4__ok = false;
4845      Bool_t ND__ok     = false;        Bool_t ND__ok = false;
4846      Bool_t AC__ok     = false;        Bool_t AC__ok = false;
4847      Bool_t ORB__ok    = false;        Bool_t ORB__ok = false;
4848          Bool_t GP__ok = false;
4849      Bool_t RUN__ok    = false;  
4850          Bool_t RUN__ok = false;
4851      Bool_t SELLI__ok  = false;  
4852      Bool_t SELLI__ok = false;
4853    
4854      //    cout << "Checking file: "<<name<<endl;
4855      TFile *f = new TFile(name.Data());
4856      if (!f || f->IsZombie()) {
4857        cout << "File: " << f->GetName() << " discarded ---- Non valid root file" << endl;
4858        fDiscarded = true;
4859        return false;
4860      }
4861      //    cout << "Get list of keys: "<<f<<endl;
4862      TList *lk = f->GetListOfKeys();
4863      //    lk->Print();
4864      TIter next(lk);
4865      TKey *key = 0;
4866    
4867      Int_t nev = 0;
4868    
4869      while ((key = (TKey*) next())) {
4870    
4871        //  cout << key->GetName() << endl;
4872        //  cout << key->GetName() << ""<<key->GetClassName()<<endl;
4873        //          cout << " Get tree: " << f->Get(key->GetName())<<endl;
4874        //  nev_previous = nev;
4875        //  cout << " n.entries  "<< nev <<endl;
4876        //  if( key->GetClassName()=="TTree" && nev_previous && nev != nev_previous ){
4877        //      nev = ((TTree*)f->Get(key->GetName()))->GetEntries();
4878        //      cout << "File: "<< f->GetName() <<" discarded ---- "<< key->GetName() << " tree: n.entries does not match "<<nev<<" "<<nev_previous<< endl;
4879        //      return false;
4880        //  };
4881    
4882        //=========================================================
4883        // check if the file
4884    
4885    
4886        if (!strcmp(key->GetName(), "Run"))
4887          RUN__ok = true;
4888    
4889        //=========================================================
4890        if (!strcmp(key->GetName(), "SelectionList")) {
4891          SELLI__ok = true;
4892          if (SELLI == 1) {
4893            Int_t nevt = ((TTree*) f->Get("SelectionList"))->GetEntries();
4894            if (nev && nevt != nev) {
4895              cout << "File: " << f->GetName() << " discarded ---- SelectionList tree has " << nevt
4896                  << " events instead of " << nev << endl;
4897              fDiscarded = true;
4898              return false;
4899            }
4900            nev = nevt;
4901          }
4902        }
4903    
4904        //=========================================================
4905        if (!strcmp(key->GetName(), "Trigger")) {
4906          TRG__ok = true;
4907          if (TRG) {
4908            Int_t nevt = ((TTree*) f->Get("Trigger"))->GetEntries();
4909            if (nev && nevt != nev) {
4910              cout << "File: " << f->GetName() << " discarded ---- Trigger tree has " << nevt << " events instead of "
4911                  << nev << endl;
4912              fDiscarded = true;
4913              return false;
4914            }
4915            nev = nevt;
4916          }
4917        }
4918        //=========================================================
4919        if (!strcmp(key->GetName(), "ToF")) {
4920          TOF__ok = true;
4921          if (TOF) {
4922            Int_t nevt = ((TTree*) f->Get("ToF"))->GetEntries();
4923            if (nev && nevt != nev) {
4924              cout << "File: " << f->GetName() << " discarded ---- ToF tree has " << nevt << " events instead of " << nev
4925                  << endl;
4926              fDiscarded = true;
4927              return false;
4928            }
4929            nev = nevt;
4930          }
4931        }
4932        //=========================================================
4933        if (!strcmp(key->GetName(), "S4")) {
4934          S4__ok = true;
4935          if (S4) {
4936            Int_t nevt = ((TTree*) f->Get("S4"))->GetEntries();
4937            if (nev && nevt != nev) {
4938              cout << "File: " << f->GetName() << " discarded ---- S4 tree has " << nevt << " events instead of " << nev
4939                  << endl;
4940              fDiscarded = true;
4941              return false;
4942            }
4943            nev = nevt;
4944          }
4945        }
4946        //=========================================================
4947    
4948      cout << "Checking file: "<<name<<endl;      if (!strcmp(key->GetName(), "NeutronD")) {
4949      TFile *f = new TFile(name.Data());        ND__ok = true;
4950      if( !f || f->IsZombie() ){        if (ND) {
4951          cout << "File: "<< f->GetName() <<" discarded ---- Non valid root file"<< endl; return false;          Int_t nevt = ((TTree*) f->Get("NeutronD"))->GetEntries();
4952      }          if (nev && nevt != nev) {
4953  //    cout << "Get list of keys: "<<f<<endl;            cout << "File: " << f->GetName() << " discarded ---- NeutronD tree has " << nevt << " events instead of "
4954      TList *lk = f->GetListOfKeys();                << nev << endl;
4955  //    lk->Print();            fDiscarded = true;
4956      TIter next(lk);            return false;
4957      TKey *key =0;          }
4958            nev = nevt;
4959          }
4960        }
4961        //=========================================================
4962        if (!strcmp(key->GetName(), "Anticounter")) {
4963          AC__ok = true;
4964          if (AC) {
4965            Int_t nevt = ((TTree*) f->Get("Anticounter"))->GetEntries();
4966            if (nev && nevt != nev) {
4967              cout << "File: " << f->GetName() << " discarded ---- Anticounter tree has " << nevt << " events instead of "
4968                  << nev << endl;
4969              fDiscarded = true;
4970              return false;
4971            }
4972            nev = nevt;
4973          }
4974        }
4975        //=========================================================
4976        if (!strcmp(key->GetName(), "OrbitalInfo")) {
4977          ORB__ok = true;
4978          if (ORB) {
4979            Int_t nevt = ((TTree*) f->Get("OrbitalInfo"))->GetEntries();
4980            if (nev && nevt != nev) {
4981              cout << "File: " << f->GetName() << " discarded ---- OrbitalInfo tree has " << nevt << " events instead of "
4982                  << nev << endl;
4983              fDiscarded = true;
4984              return false;
4985            }
4986            nev = nevt;
4987          }
4988        }
4989        //=========================================================
4990        if (!strcmp(key->GetName(), "Tracker")) {
4991          TTree *T = (TTree*) f->Get("Tracker");
4992          if (TRK1 || TRK2 || TRKh) {
4993            Int_t nevt = T->GetEntries();
4994            if (nev && nevt != nev) {
4995              cout << "File: " << f->GetName() << " discarded ---- Tracker tree has " << nevt << " events instead of "
4996                  << nev << endl;
4997              fDiscarded = true;
4998              return false;
4999            }
5000            nev = nevt;
5001          }
5002          for (Int_t i = 0; i < T->GetListOfBranches()->GetEntries(); i++) {
5003            TString name = T->GetListOfBranches()->At(i)->GetName();
5004            if (!name.CompareTo("TrkLevel1"))
5005              TRK1__ok = true;
5006            if (!name.CompareTo("TrkLevel2"))
5007              TRK2__ok = true;
5008            if (!name.CompareTo("TrkHough"))
5009              TRKh__ok = true;
5010          };
5011          T->Delete();
5012        };
5013        //=========================================================
5014        if (!strcmp(key->GetName(), "Calorimeter")) {
5015          TTree *T = (TTree*) f->Get("Calorimeter");
5016          if (CAL1 || CAL2) {
5017            Int_t nevt = T->GetEntries();
5018            if (nev && nevt != nev) {
5019              cout << "File: " << f->GetName() << " discarded ---- Calorimeter tree has " << nevt << " events instead of "
5020                  << nev << endl;
5021              fDiscarded = true;
5022              return false;
5023            }
5024            nev = nevt;
5025          }
5026          for (Int_t i = 0; i < T->GetListOfBranches()->GetEntries(); i++) {
5027            TString name = T->GetListOfBranches()->At(i)->GetName();
5028            if (!name.CompareTo("CaloLevel1"))
5029              CAL1__ok = true;
5030            if (!name.CompareTo("CaloLevel2"))
5031              CAL2__ok = true;
5032          };
5033          T->Delete();
5034        };
5035        //=========================================================
5036        if (!strcmp(key->GetName(), "h20")) {
5037          ISGP = true;
5038          GP__ok = true;
5039          if (GP) {
5040            Int_t nevt = ((TTree*) f->Get("h20"))->GetEntries();
5041            if (nev && nevt != nev) {
5042              cout << "File: " << f->GetName() << " discarded ---- h20 tree has " << nevt << " events instead of " << nev
5043                  << endl;
5044              fDiscarded = true;
5045              return false;
5046            }
5047            nev = nevt;
5048          }
5049        }
5050    
5051      Int_t nev = 0;    };
5052    
5053      while( (key = (TKey*)next()) ){    if (SELLI == -1)
5054                SELLI = (Int_t) SELLI__ok;
5055  //      cout << key->GetName() << endl;    if (SELLI == 0 && SELLI__ok) {
5056  //      cout << key->GetName() << ""<<key->GetClassName()<<endl;      cout << "File: " << f->GetName() << " discarded ---- found SelectionList (it is not a full-event file)" << endl;
5057  //              cout << " Get tree: " << f->Get(key->GetName())<<endl;      fDiscarded = true;
5058  //      nev_previous = nev;      return false;
5059  //      cout << " n.entries  "<< nev <<endl;    }
5060  //      if( key->GetClassName()=="TTree" && nev_previous && nev != nev_previous ){    if (SELLI == 1 && !SELLI__ok) {
5061  //          nev = ((TTree*)f->Get(key->GetName()))->GetEntries();      cout << "File: " << f->GetName() << " discarded ---- SelectionList missing" << endl;
5062  //          cout << "File: "<< f->GetName() <<" discarded ---- "<< key->GetName() << " tree: n.entries does not match "<<nev<<" "<<nev_previous<< endl;      fDiscarded = true;
5063  //          return false;      return false;
5064  //      };    }
   
   
         if( !strcmp(key->GetName(),"Run"        ) )RUN__ok = true;        
   
         //=========================================================      
         if( !strcmp(key->GetName(),"SelectionList"    ) ){  
             SELLI__ok = true;  
             if(SELLI==1){  
                 Int_t nevt = ((TTree*)f->Get("SelectionList"))->GetEntries();  
                 if( nev && nevt!=nev){  
                     cout << "File: "<< f->GetName() <<" discarded ---- SelectionList tree has "<<nevt<<" events instead of "<<nev<< endl;  
                     return false;  
                 }  
                 nev=nevt;  
             }  
         }  
5065    
5066          //=========================================================        //    cout << "SELLI "<<SELLI<<endl;
         if( !strcmp(key->GetName(),"Trigger"    ) ){  
             TRG__ok = true;  
             if(TRG){  
                 Int_t nevt = ((TTree*)f->Get("Trigger"))->GetEntries();  
                 if( nev && nevt!=nev){  
                     cout << "File: "<< f->GetName() <<" discarded ---- Trigger tree has "<<nevt<<" events instead of "<<nev<< endl;  
                     return false;  
                 }  
                 nev=nevt;  
             }  
         }  
         //=========================================================      
         if( !strcmp(key->GetName(),"ToF"        ) ){  
             TOF__ok = true;  
             if(TOF){  
                 Int_t nevt = ((TTree*)f->Get("ToF"))->GetEntries();  
                 if( nev && nevt!=nev){  
                     cout << "File: "<< f->GetName() <<" discarded ---- ToF tree has "<<nevt<<" events instead of "<<nev<< endl;  
                     return false;  
                 }  
                 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;  
             }  
         }  
         //=========================================================    
5067    
5068          if( !strcmp(key->GetName(),"NeutronD"   ) ){    //     cout<< "CheckLevel2File(TString): detector list --> ";
5069              ND__ok = true;    //     if(TRK1__ok)cout<<"TRK1 ";
5070              if(ND){    //     if(TRK2__ok)cout<<"TRK2 ";
5071                  Int_t nevt = ((TTree*)f->Get("NeutronD"))->GetEntries();    //     if(TRKh__ok)cout<<"TRKH ";
5072                  if( nev && nevt!=nev){    //     if(CAL1__ok)cout<<"CAL1 ";
5073                      cout << "File: "<< f->GetName() <<" discarded ---- NeutronD tree has "<<nevt<<" events instead of "<<nev<< endl;    //     if(CAL2__ok)cout<<"CAL2 ";
5074                      return false;    //     if(TOF__ok)cout<<"TOF ";
5075                  }    //     if(TRG__ok)cout<<"TRG ";
5076                  nev=nevt;    //     if(AC__ok)cout<<"AC ";
5077              }    //     if(ND__ok)cout<<"ND ";
5078          }          //     if(S4__ok)cout<<"S4 ";
5079          //=========================================================      //     if(ORB__ok)cout<<"ORB ";
5080          if( !strcmp(key->GetName(),"Anticounter") ){    //     cout << endl;
5081              AC__ok = true;  
5082              if(AC){  
5083                  Int_t nevt = ((TTree*)f->Get("Anticounter"))->GetEntries();    if (TRK2 && TRK1__ok)
5084                  if( nev && nevt!=nev){      TRK1 = 1;
5085                      cout << "File: "<< f->GetName() <<" discarded ---- Anticounter tree has "<<nevt<<" events instead of "<<nev<< endl;    // ----------------------------------------------------------------------------
5086                      return false;    // NOTA
5087                  }    // se c'e` il level1, lo devo necessarimente leggere.
5088                  nev=nevt;    // infatti (non ho capito perche`) i cluster vengono letti e allocati in memoria
5089              }    // comunque, ma non vengono disallocati da PamLevel2::Clear()
5090          }    // ----------------------------------------------------------------------------
5091          //=========================================================    
5092          if( !strcmp(key->GetName(),"OrbitalInfo") ){  
5093              ORB__ok = true;    if (!RUN__ok) {
5094              if(ORB){      cout << "File: " << f->GetName() << " *WARNING* ---- Missing RunInfo tree (NB: RUN infos will not be updated)"
5095                  Int_t nevt = ((TTree*)f->Get("OrbitalInfo"))->GetEntries();          << endl;
5096                  if( nev && nevt!=nev){      RUN = false;
5097                      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();  
         };        
5098    
5099      };    if (CAL1 && !CAL1__ok) {
5100        cout << "File: " << f->GetName() << " discarded ---- Missing CaloLevel1 branch" << endl;
5101        fDiscarded = true;
5102        return false;
5103      };
5104      if (CAL2 && !CAL2__ok) {
5105        cout << "File: " << f->GetName() << " discarded ---- Missing CaloLevel2 branch" << endl;
5106        fDiscarded = true;
5107        return false;
5108      };
5109      if (TRK2 && !TRK2__ok) {
5110        cout << "File: " << f->GetName() << " discarded ---- Missing TrkLevel2 branch" << endl;
5111        fDiscarded = true;
5112        return false;
5113      };
5114      if (TRK1 && !TRK1__ok) {
5115        cout << "File: " << f->GetName() << " discarded ---- Missing TrkLevel1 branch" << endl;
5116        fDiscarded = true;
5117        return false;
5118      };
5119      if (TRKh && !TRKh__ok) {
5120        cout << "File: " << f->GetName() << " discarded ---- Missing TrkHough branch" << endl;
5121        fDiscarded = true;
5122        return false;
5123      };
5124      if (ORB && !ORB__ok) {
5125        cout << "File: " << f->GetName() << " discarded ---- Missing ORB tree" << endl;
5126        fDiscarded = true;
5127        return false;
5128      };
5129      if (AC && !AC__ok) {
5130        cout << "File: " << f->GetName() << " discarded ---- Missing AC tree" << endl;
5131        fDiscarded = true;
5132        return false;
5133      };
5134      if (S4 && !S4__ok) {
5135        cout << "File: " << f->GetName() << " discarded ---- Missing S4 tree" << endl;
5136        fDiscarded = true;
5137        return false;
5138      };
5139      if (TOF && !TOF__ok) {
5140        cout << "File: " << f->GetName() << " discarded ---- Missing ToF tree" << endl;
5141        fDiscarded = true;
5142        return false;
5143      };
5144    
5145      if( SELLI==-1 )SELLI = (Int_t)SELLI__ok;    if (ND && !ND__ok) {
5146      if( SELLI==0 && SELLI__ok ){      cout << "File: " << f->GetName() << " discarded ---- Missing ND tree" << endl;
5147          cout << "File: "<< f->GetName() <<" discarded ---- found SelectionList (it is not a full-event file)" << endl;      fDiscarded = true;
5148          return false;        return false;
5149      }    };
5150      if( SELLI==1 && !SELLI__ok ){    if (TRG && !TRG__ok) {
5151          cout << "File: "<< f->GetName() <<" discarded ---- SelectionList missing" << endl;      cout << "File: " << f->GetName() << " discarded ---- Missing Trigger tree" << endl;
5152          return false;      fDiscarded = true;
5153      }      return false;
5154          };
5155  //    cout << "SELLI "<<SELLI<<endl;    if (GP && !GP__ok) {
5156        cout << "File: " << f->GetName() << " discarded ---- Missing h20 tree" << endl;
5157        fDiscarded = true;
5158        return false;
5159      };
5160    
5161  //     cout<< "CheckLevel2File(TString): detector list --> ";    //    lk->Delete();
5162  //     if(TRK1__ok)cout<<"TRK1 ";    //    delete lk;
5163  //     if(TRK2__ok)cout<<"TRK2 ";    f->Close();
5164  //     if(TRKh__ok)cout<<"TRKH ";  
5165  //     if(CAL1__ok)cout<<"CAL1 ";    //     cout<< "CheckLevel2File(TString): detector list --> ";
5166  //     if(CAL2__ok)cout<<"CAL2 ";    //     if(TRK1)cout<<"TRK1 ";
5167  //     if(TOF__ok)cout<<"TOF ";    //     if(TRK2)cout<<"TRK2 ";
5168  //     if(TRG__ok)cout<<"TRG ";    //     if(TRKh)cout<<"TRKH ";
5169  //     if(AC__ok)cout<<"AC ";    //     if(CAL1)cout<<"CAL1 ";
5170  //     if(ND__ok)cout<<"ND ";    //     if(CAL2)cout<<"CAL2 ";
5171  //     if(S4__ok)cout<<"S4 ";    //     if(TOF)cout<<"TOF ";
5172  //     if(ORB__ok)cout<<"ORB ";    //     if(TRG)cout<<"TRG ";
5173  //     cout << endl;    //     if(AC)cout<<"AC ";
5174      //     if(ND)cout<<"ND ";
5175      //     if(S4)cout<<"S4 ";
5176      if(TRK2 && TRK1__ok)TRK1=1;    //     if(ORB)cout<<"ORB ";
5177  // ----------------------------------------------------------------------------    //     if(GP)cout<<"GP ";
5178  // NOTA    //     cout << endl;
 // se c'e` il level1, lo devo necessarimente leggere.  
 // infatti (non ho capito perche`) i cluster vengono letti e allocati in memoria  
 // comunque, ma non vengono disallocati da PamLevel2::Clear()  
 // ----------------------------------------------------------------------------  
   
   
     if(!RUN__ok) {  
         cout << "File: "<< f->GetName() <<" *WARNING* ---- Missing RunInfo tree"<< endl;  
 //      return false;  
     };  
   
     if(CAL1 && !CAL1__ok){  
         cout << "File: "<< f->GetName() <<" discarded ---- Missing CaloLevel1 branch"<< endl;  
         return false;  
     };  
     if(CAL2 && !CAL2__ok){  
         cout << "File: "<< f->GetName() <<" discarded ---- Missing CaloLevel2 branch"<< endl;  
         return false;  
     };  
     if(TRK2 && !TRK2__ok){  
         cout << "File: "<< f->GetName() <<" discarded ---- Missing TrkLevel2 branch"<< endl;  
         return false;  
     };  
     if(TRK1 && !TRK1__ok){  
         cout << "File: "<< f->GetName() <<" discarded ---- Missing TrkLevel1 branch"<< endl;  
         return false;  
     };  
     if(TRKh && !TRKh__ok){  
         cout << "File: "<< f->GetName() <<" discarded ---- Missing TrkHough branch"<< endl;  
         return false;  
     };  
     if(ORB && !ORB__ok){  
         cout << "File: "<< f->GetName() <<" discarded ---- Missing ORB tree"<< endl;  
         return false;  
     };  
     if(AC && !AC__ok){  
         cout << "File: "<< f->GetName() <<" discarded ---- Missing AC tree"<< endl;  
         return false;  
     };  
     if(S4 && !S4__ok){  
         cout << "File: "<< f->GetName() <<" discarded ---- Missing S4 tree"<< endl;  
         return false;  
     };  
     if(TOF && !TOF__ok){  
         cout << "File: "<< f->GetName() <<" discarded ---- Missing ToF tree"<< endl;  
         return false;  
     };  
   
     if(ND && !ND__ok){  
         cout << "File: "<< f->GetName() <<" discarded ---- Missing ND tree"<< endl;  
         return false;  
     };  
     if(TRG && !TRG__ok){  
         cout << "File: "<< f->GetName() <<" discarded ---- Missing Trigger tree"<< endl;  
         return false;  
     };  
       
5179    
5180  //    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;  
           
 };  
5181    
5182    }
5183    ;
5184    
5185  /**  /**
5186   * Create clone-trees   * Create clone-trees
5187   */   */
5188  void PamLevel2::CreateCloneTrees0( TChain *fChain, TFile *ofile ){  void PamLevel2::CreateCloneTrees0(TChain *fChain, TFile *ofile) {
5189    
5190      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;    cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
5191      cout << "Create clones of PAMELA trees "<<endl;    cout << "Create clones of PAMELA trees " << endl;
5192        
5193      Int_t i=0;    Int_t i = 0;
5194      pam_tree_clone[i] = fChain->GetTree()->CloneTree(0);    pam_tree_clone[i] = fChain->GetTree()->CloneTree(0);
5195      TString name =  pam_tree_clone[i]->GetName();    TString name = pam_tree_clone[i]->GetName();
5196      name.Append("_clone");
5197      //    pam_tree_clone[i]->SetName(name.Data());
5198      cout << pam_tree_clone[i]->GetName() << endl;
5199      i++;
5200    
5201      TList *li = fChain->GetListOfFriends();
5202      TIter next(li);
5203      TFriendElement* T_friend = 0;
5204      ofile->cd();
5205      while ((T_friend = (TFriendElement*) next())) {
5206        //  cout<<T_friend->IsA()->GetName()<<" "<<T_friend->GetName()<<hex << T_friend->GetTree() << dec<<endl;
5207        //  cout<<T_friend->GetTree()->GetName()<< endl;
5208        pam_tree_clone[i] = T_friend->GetTree()->CloneTree(0);
5209        pam_tree_clone[i]->SetAutoSave(1000000);
5210        name = pam_tree_clone[i]->GetName();
5211      name.Append("_clone");      name.Append("_clone");
5212  //    pam_tree_clone[i]->SetName(name.Data());      //  pam_tree_clone[i]->SetName(name.Data());
5213      cout << pam_tree_clone[i]->GetName() <<endl;      cout << pam_tree_clone[i]->GetName() << endl;
5214      i++;      i++;
5215      }
5216    
5217      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;  
5218    
5219      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;    cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
5220    
5221  }  }
5222    
5223  /**  /**
5224   * Create clone-trees   * Create clone-trees
5225   */   */
5226  void PamLevel2::CreateCloneTrees(TFile *ofile){  void PamLevel2::CreateCloneTrees(TFile *ofile) {
5227    
5228      ofile->cd();    //  if the pointer is null, create a default file
5229      if (!run_tree)
5230        return;
5231    
5232      if (!ofile) {
5233        cout << "void PamLevel2::CreateCloneTrees(TFile*) -- WARNING -- Creating file: clone-tree.root " << endl;
5234        ofile = new TFile("clone-tree.root", "recreate");
5235      }
5236    
5237      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;    ofile->cd();
     cout << "Create new PAMELA trees "<<endl;  
           
5238    
5239      run_tree_clone = new TTree("Run","PAMELA Level2 data from the GL_RUN table ");    cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
5240      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;  
               
5241    
5242      run_tree_clone = new TTree("Run", "PAMELA Level2 data from the GL_RUN table ");
5243      run_tree_clone->Branch("RunInfo", "GL_RUN", GetPointerTo("RunInfo"));
5244      cout << "Run          : branch RunInfo" << endl;
5245      run_tree_clone->Branch("SoftInfo", "SoftInfo", GetPointerTo("SoftInfo"));
5246      cout << "Run          : branch SoftInfo" << endl;
5247      // ------------------
5248      // replicate run tree
5249      // ------------------
5250      //    cout << "----------------------------------------------------"<<endl;
5251      //    cout << "irun\t | RUN\t NEVENTS\t absolute time"<<endl;
5252      for (Int_t i = 0; i < run_tree->GetEntries(); i++) {
5253        run_tree->GetEntry(i);
5254        //  cout << i<< "\t | "<<GetRunInfo()->ID<<"\t "<<GetRunInfo()->NEVENTS<< "\t "<<GetRunInfo()->RUNHEADER_TIME<<" <---> "<<GetRunInfo()->RUNTRAILER_TIME<<endl;
5255        run_tree_clone->Fill();
5256      }
5257      //
5258      // replicate processinginfo tree
5259      //
5260      if ( PROC ){ // EMEMEM
5261        proc_tree_clone = new TTree("ProcessingInfo","Log of data processing");
5262        proc_tree_clone->Branch("ProcInfo", "ProcInfo", GetPointerTo("ProcInfo"));
5263        cout << "ProcessingInfo: branch ProcessingInfo" << endl;  
5264        // ------------------
5265        // replicate processinginfo tree
5266        // ------------------
5267        //    cout << "----------------------------------------------------"<<endl;
5268        //    cout << "irun\t | RUN\t NEVENTS\t absolute time"<<endl;
5269        for (Int_t i = 0; i < proc_tree->GetEntries(); i++) {
5270          proc_tree->GetEntry(i);
5271          //      cout << i<< "\t | "<<endl;
5272          proc_tree_clone->Fill();
5273        }
5274        if ( SELLI != 2 ){      
5275          proc_obj->runID = 0;
5276          TTimeStamp *dt = new TTimeStamp();
5277          proc_obj->date = dt->AsString();
5278          delete dt;
5279          proc_obj->commandLine = Form("PamelaLevel2 was called: CAL2 %i CAL1 %i CAL0 %i TRK2 %i TRK1 %i TRKh %i TRK0 %i TOF %i TOF0 %i TRG %i \n                                            S4 %i ND %i AC %i ORB %i GP %i EXT %i NUC %i RUN %i ISGP %i SELLI %i \n Custom string   = %s",CAL2,CAL1,CAL0,TRK2,TRK1,TRKh,TRK0,TOF,TOF0,TRG,S4,ND,AC,ORB,GP,EXT,NUC,RUN,ISGP,SELLI,customString.Data());
5280          proc_obj->outputFilename = ofile->GetName();
5281          proc_obj->localDir = gSystem->WorkingDirectory();
5282          proc_obj->uname = gSystem->GetFromPipe("uname -a");
5283          if (!dbc || (dbc && !dbc->IsConnected())) SetDBConnection();
5284          proc_obj->DB = Form("mysql://%s/%s",dbc->GetHost(),dbc->GetDB());
5285          dbc->Close();
5286          proc_tree_clone->Fill();
5287        }
5288        cout << "----------------------------------------------------" << endl;
5289      }
5290      // ------------------------------------
5291      // add branch with dead and live times
5292      // ------------------------------------
5293      if (SELLI != 2) { // EMILIANO
5294        run_tree_clone->Branch("DeadLiveTime", totdltime, "dltime[3]/l");
5295        cout << "Run          : branch DeadLiveTime" << endl;
5296    
5297        sel_tree_clone = new TTree("SelectionList", "List of selected events ");
5298        //    sel_tree_clone->Branch("RunEntry",&irun,"runentry/L");
5299        sel_tree_clone->Branch("RunEntry", &irunt, "runentry/L");//NEWNEW
5300        sel_tree_clone->Branch("EventEntry", &irunentry, "eventry/L");
5301        //    if ( hasL0EE ) sel_tree_clone->Branch("L0EventEntry", &il0entry, "l0eventry/L");
5302      };
5303    
5304      sel_tree_clone = new TTree("SelectionList","List of selected events ");    Int_t i = 0;
5305      sel_tree_clone->Branch("RunEntry",&irun,"runentry/I");    if (TRK1 || TRK2 || TRKh) {
5306      sel_tree_clone->Branch("EventEntry",&irunentry,"eventry/I");      pam_tree_clone[i] = new TTree("Tracker", "PAMELA tracker level2 data ");
5307            if (TRK1) {
5308          pam_tree_clone[i]->Branch("TrkLevel1", "TrkLevel1", GetPointerTo("TrkLevel1"));
5309          pam_tree_clone[i]->BranchRef();
5310          cout << "Tracker      : branch TrkLevel1" << endl;
5311          //            cout << "CreateCloneTrees " << GetTrkLevel1()<<endl;
5312        };
5313        if (TRK2) {
5314          pam_tree_clone[i]->Branch("TrkLevel2", "TrkLevel2", GetPointerTo("TrkLevel2"));
5315          cout << "Tracker      : branch TrkLevel2" << endl;
5316        };
5317        if (TRKh) {
5318          pam_tree_clone[i]->Branch("TrkHough", "TrkHough", GetPointerTo("TrkHough"));
5319          cout << "Tracker      : branch TrkHough" << endl;
5320        };
5321        if(NUC){
5322            pam_tree_clone[i]->Branch("TrackNuclei","TClonesArray",&trk_nuc_obj);
5323            cout << "Tracker      : branch TrackNuclei" << endl;    
5324        }
5325        if(EXT){
5326            pam_tree_clone[i]->Branch("extAlgFlag",&extAlgFlag,"extAlgFlag/I");
5327            pam_tree_clone[i]->Branch("RecoveredTrack","TClonesArray",&trk_ext_obj);
5328            cout << "Tracker      : branch RecoveredTrack" << endl;
5329            if(NUC){
5330                pam_tree_clone[i]->Branch("RecoveredTrackNuclei","TClonesArray",&trk_ext_nuc_obj);
5331                cout << "Tracker      : branch RecoveredTrackNuclei" << endl;                  
5332            }
5333        }
5334    
5335      Int_t i=0;      i++;
5336      if(TRK1||TRK2||TRKh){    }
         pam_tree_clone[i] = new TTree("Tracker","PAMELA tracker level2 data ");  
         if(TRK1) {  
             pam_tree_clone[i]->Branch("TrkLevel1","TrkLevel1", GetPointerTo("TrkLevel1"));  
             pam_tree_clone[i]->BranchRef();  
             cout << "Tracker      : branch TrkLevel1"<<endl;  
             cout << "CreateCloneTrees " << GetTrkLevel1()<<endl;  
         };  
         if(TRK2) {  
             pam_tree_clone[i]->Branch("TrkLevel2", "TrkLevel2",GetPointerTo("TrkLevel2"));  
             cout << "Tracker      : branch TrkLevel2"<<endl;          
         };  
         if(TRKh) {  
             pam_tree_clone[i]->Branch("TrkHough","TrkHough", GetPointerTo("TrkHough"));  
             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++;  
     };  
     cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;  
5337    
5338  }    // Calorimeter
5339      if (CAL1 || CAL2) {
5340        pam_tree_clone[i] = new TTree("Calorimeter", "PAMELA calorimeter level2 data ");
5341        if (CAL1) {
5342          pam_tree_clone[i]->Branch("CaloLevel1", "CaloLevel1", GetPointerTo("CaloLevel1"));
5343          cout << "Calorimeter  : branch CaloLevel1" << endl;
5344        };
5345        if (CAL2) {
5346          pam_tree_clone[i]->Branch("CaloLevel2", "CaloLevel2", GetPointerTo("CaloLevel2"));
5347          cout << "Calorimeter  : branch CaloLevel2" << endl;
5348        };
5349        if(NUC){
5350            pam_tree_clone[i]->Branch("TrackNuclei","TClonesArray",&calo_nuc_obj);
5351            cout << "Calorimeter  : branch TrackNuclei" << endl;    
5352        }
5353        if(EXT){
5354            pam_tree_clone[i]->Branch("RecoveredTrack","TClonesArray",&calo_ext_obj);
5355            cout << "Calorimeter  : branch RecoveredTrack" << endl;
5356            if(NUC){
5357                pam_tree_clone[i]->Branch("RecoveredTrackNuclei","TClonesArray",&calo_ext_nuc_obj);
5358                cout << "Calorimeter  : branch RecoveredTrackNuclei" << endl;                  
5359            }
5360        }
5361        i++;
5362      }
5363    
5364      // ToF
5365      if (TOF) {
5366        pam_tree_clone[i] = new TTree("ToF", "PAMELA ToF level2 data ");
5367        pam_tree_clone[i]->Branch("ToFLevel2", "ToFLevel2", GetPointerTo("ToFLevel2"));
5368        cout << "ToF          : branch ToFLevel2" << endl;
5369        if(NUC){
5370            pam_tree_clone[i]->Branch("TrackNuclei","TClonesArray",&tof_nuc_obj);
5371            cout << "ToF          : branch TrackNuclei" << endl;    
5372        }
5373        if(EXT){
5374            pam_tree_clone[i]->Branch("RecoveredTrack","TClonesArray",&tof_ext_obj);
5375            cout << "ToF          : branch RecoveredTrack" << endl;
5376            if(NUC){
5377                pam_tree_clone[i]->Branch("RecoveredTrackNuclei","TClonesArray",&tof_ext_nuc_obj);
5378                cout << "ToF          : branch RecoveredTrackNuclei" << endl;                  
5379            }
5380        }
5381        i++;
5382      };
5383      // Trigger
5384      if (TRG) {
5385        pam_tree_clone[i] = new TTree("Trigger", "PAMELA trigger level2 data ");
5386        pam_tree_clone[i]->Branch("TrigLevel2", "TrigLevel2", GetPointerTo("TrigLevel2"));
5387        cout << "Trigger      : branch TrigLevel2" << endl;
5388        i++;
5389      };
5390      // S4
5391      if (S4) {
5392        pam_tree_clone[i] = new TTree("S4", "PAMELA S4 level2 data ");
5393        pam_tree_clone[i]->Branch("S4Level2", "S4Level2", GetPointerTo("S4Level2"));
5394        cout << "S4           : branch S4Level2" << endl;
5395        i++;
5396      };
5397      // Neutron Detector
5398      if (ND) {
5399        pam_tree_clone[i] = new TTree("NeutronD", "PAMELA neutron detector level2 data ");
5400        pam_tree_clone[i]->Branch("NDLevel2", "NDLevel2", GetPointerTo("NDLevel2"));
5401        cout << "NeutronD     : branch NDLevel2" << endl;
5402        i++;
5403      };
5404      // Anticounters
5405      if (AC) {
5406        pam_tree_clone[i] = new TTree("Anticounter", "PAMELA anticounter detector level2 data ");
5407        pam_tree_clone[i]->Branch("AcLevel2", "AcLevel2", GetPointerTo("AcLevel2"));
5408        cout << "Anticounter  : branch AcLevel2" << endl;
5409        i++;
5410      };
5411      // OrbitalInfo
5412      if (ORB) {
5413        pam_tree_clone[i] = new TTree("OrbitalInfo", "PAMELA orbital info  ");
5414        pam_tree_clone[i]->Branch("OrbitalInfo", "OrbitalInfo", GetPointerTo("OrbitalInfo"));
5415        cout << "OrbitalInfo  : branch OrbitalInfo" << endl;
5416        if(NUC){
5417            pam_tree_clone[i]->Branch("TrackNuclei","TClonesArray",&orb_nuc_obj);
5418            cout << "OrbitalInfo  : branch TrackNuclei" << endl;    
5419        }
5420        if(EXT){
5421            pam_tree_clone[i]->Branch("RecoveredTrack","TClonesArray",&orb_ext_obj);
5422            cout << "OrbitalInfo  : branch RecoveredTrack" << endl;
5423            if(NUC){
5424                pam_tree_clone[i]->Branch("RecoveredTrackNuclei","TClonesArray",&orb_ext_nuc_obj);
5425                cout << "OrbitalInfo  : branch RecoveredTrackNuclei" << endl;                  
5426            }
5427        }
5428        i++;
5429      };
5430      // GPamela
5431      if (GP) {
5432        pam_tree_clone[i] = new TTree("h20", "GPAMELA info ");
5433        pam_tree_clone[i]->Branch("GPamela", "GPamela", GetPointerTo("GPamela"), 32000, 1);//split
5434        cout << "GPamela  : branch GPamela" << endl;
5435        i++;
5436      };
5437    
5438    
5439      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
5440    
5441    }
5442    
5443  /**  /**
5444   * Fill tree (created with CreateCloneTrees)   * Fill tree (created with CreateCloneTrees)
5445   *   *
5446   */   */
5447  //void PamLevel2::FillNewPamTree(TTree *T){  //void PamLevel2::FillNewPamTree(TTree *T){
5448  void PamLevel2::FillCloneTrees(){  void PamLevel2::FillCloneTrees() {
       
 //    cout << "PamLevel2::FillCloneTrees()" << irunentry << endl;  
5449    
5450      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();      
5451    
5452  }    for (Int_t i = 0; i < NCLONES; i++) {
5453        if (pam_tree_clone[i])
5454          pam_tree_clone[i]->Fill();
5455      }
5456      if (sel_tree_clone)
5457        sel_tree_clone->Fill();
5458    
5459    }
5460    
5461  TTree* PamLevel2::GetCloneTree(TString name){  TTree* PamLevel2::GetCloneTree(TString name) {
5462    
5463      for(Int_t i=0; i<NCLONES; i++){        for (Int_t i = 0; i < NCLONES; i++) {
5464          if(pam_tree_clone[i]){      if (pam_tree_clone[i]) {
5465              TString na = pam_tree_clone[i]->GetName();        TString na = pam_tree_clone[i]->GetName();
5466              if(!name.CompareTo(na))return pam_tree_clone[i];        if (!name.CompareTo(na))
5467          };          return pam_tree_clone[i];
5468      }      };
5469      if(run_tree_clone){    }
5470          TString na = run_tree_clone->GetName();    if (run_tree_clone) {
5471          if(!name.CompareTo(na))return run_tree_clone;      TString na = run_tree_clone->GetName();
5472      }      if (!name.CompareTo(na))
5473      if(sel_tree_clone){        return run_tree_clone;
5474          TString na = sel_tree_clone->GetName();    }
5475          if(!name.CompareTo(na))return sel_tree_clone;    if (sel_tree_clone) {
5476      }      TString na = sel_tree_clone->GetName();
5477      return NULL;      if (!name.CompareTo(na))
5478          return sel_tree_clone;
5479      }
5480      if (proc_tree_clone && PROC) {
5481        TString na = proc_tree_clone->GetName();
5482        if (!name.CompareTo(na))
5483          return proc_tree_clone;
5484      }
5485      return NULL;
5486    
5487  }  }
5488  void PamLevel2::WriteCloneTrees(){  void PamLevel2::WriteCloneTrees() {
5489      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;    cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
5490      cout << "Write clones of PAMELA trees "<<endl;    cout << "Write clones of PAMELA trees " << endl;
5491      cout << run_tree_clone->GetName()<<endl;        cout << run_tree_clone->GetName() << endl;
5492      run_tree_clone->Write();    if (SELLI != 2) {// Emiliano
5493      cout << sel_tree_clone->GetName()<<endl;          if (run_tree_clone->GetBranch("DeadLiveTime")->GetEntries() < run_tree->GetEntries())
5494          run_tree_clone->GetBranch("DeadLiveTime")->Fill();
5495      };
5496      run_tree_clone->Write();
5497      if (SELLI != 2) { //Emiliano
5498        cout << sel_tree_clone->GetName() << endl;
5499      sel_tree_clone->Write();      sel_tree_clone->Write();
5500      for(Int_t i=0; i<NCLONES; i++){        };
5501          if(pam_tree_clone[i]){    for (Int_t i = 0; i < NCLONES; i++) {
5502              cout << pam_tree_clone[i]->GetName()<<endl;      if (pam_tree_clone[i]) {
5503              pam_tree_clone[i]->Write();        cout << pam_tree_clone[i]->GetName() << endl;
5504          };        pam_tree_clone[i]->Write(pam_tree_clone[i]->GetName(),TObject::kOverwrite);
5505      }      };
5506      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;    }
5507      
5508      if ( PROC ){//EMEMEMEM
5509        proc_tree_clone->Write("ProcessingInfo",TObject::kOverwrite);
5510      }
5511      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
5512    
5513  }  }
5514    
5515  /**  /**
5516   * 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.
5517   */   */
5518  Int_t PamLevel2::GetEntry(Int_t iee){  Int_t PamLevel2::GetEntry(Long64_t iee) {
5519        
5520      if(!pam_tree){    if (!pam_tree) {
5521          cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- level2 trees not loeaded"<<endl;      cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- level2 trees not loaded" << endl;
5522          return 0;      return 0;
5523      }    }
5524      if(!run_tree ){  
5525          cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- run tree not loeaded"<<endl;    //
5526          return 0;    // 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...
5527      }    //
5528      //    if(!run_tree ){
5529      Int_t ii=0;    //    cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- run tree not loeaded"<<endl;
5530      //-------------------------------    //    return 0;
5531      ii = iee;    //    }
5532      if( !pam_tree->GetEntry(ii) ) return 0;  
5533      //-------------------------------    //-------------------------------
5534      ii = iee;    if (!pam_tree->GetEntry(iee)) {
5535      Bool_t UPDATED = UpdateRunInfo(run_tree,ii);      cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- error reading pam tree" << endl;
5536      if(SELLI==0)irunentry = iee-runfirstentry;      return 0;
5537      if(UPDATED && run_tree_clone)run_tree_clone->Fill();    }
5538      //
5539      // ... 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.
5540      // 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
5541      // a problem if you don't check the return code of getentry.
5542      //
5543      if (!RUN || !run_tree) {
5544        if (TRK0 || CAL0 || TOF0 || RUN) { //forse cosi` va bene per tornare 1?
5545          cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- run tree not loaded" << endl;
5546          return 0;
5547        }
5548        else {
5549          return 1; //cosi` se non c'e` run esce qua...
5550        }
5551      }
5552    
5553  //    cout << "PamLevel2::GetEntry("<<iee<<") "<<irun<<" "<<runfirstentry<<" "<<irunentry<<endl;    //-------------------------------
5554      //
5555      if ( fUpdateRunInfo ) UpdateRunInfo(iee); // Emiliano
5556      if (SELLI == 0 || SELLI == 2) irunentry = iee - runfirstentry;
5557    
5558      if( TRK0 || CAL0 || TOF0 )GetYodaEntry( );    return 1;
5559    
5560      return 1;  }
5561    
5562    TrkLevel0 *PamLevel2::GetTrkLevel0() {
5563      if (!TRK0)
5564        return NULL;
5565      if (!GetYodaEntry()) {
5566        cout << " Int_t PamLevel2::GetTrkLevel0() -- ERROR -- error reading level0 tree" << endl;
5567        return 0;
5568      }
5569      return trk0_obj;
5570  }  }
5571    ;
5572    CaloLevel0 *PamLevel2::GetCaloLevel0() {
5573      if (!CAL0)
5574        return NULL;
5575      if (!GetYodaEntry()) {
5576        cout << " Int_t PamLevel2::GetCaloLevel0() -- ERROR -- error reading level0 tree" << endl;
5577        return 0;
5578      }
5579      return calo0_obj;
5580    }
5581    ;
5582    
5583  /**  /**
5584   * 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 2385  Int_t PamLevel2::GetEntry(Int_t iee){ Line 5586  Int_t PamLevel2::GetEntry(Int_t iee){
5586   * @return Pointer to the tree   * @return Pointer to the tree
5587   */   */
5588    
5589    TTree* PamLevel2::GetYodaTree() {
5590    
5591  TTree* PamLevel2::GetYodaTree( ){    //    cout << "TTree* PamLevel2::GetYodaTree( )"<<endl;
5592          //===================================
5593  //    cout << "TTree* PamLevel2::GetYodaTree( )"<<endl;    // check if iroot has changed
5594      //===================================    //===================================
5595      // check if iroot has changed    if (irun < 0) {
5596      //===================================      cout << "PamLevel2::GetYodaTree() -- ERROR -- irun = " << irun << endl;
5597      if( irun<0 ){      if (DBG) cout << "In order to use this method you have to first load the RunInfo tree "<<endl;
5598          cout << "PamLevel2::GetYodaTree() -- ERROR "<<endl;      return NULL;
5599          cout << "In order to use this method you have to load the RunInfo tree "<<endl;    }
5600          cout << "with the method TChain* PamLevel2::GetRunTree(TString, TString)"<<endl;    Int_t irootnew = GetRunInfo()->ID_ROOT_L0;
5601  //      cout << " - read the event with PamLevel2::GetEntry(Int_t)"<<endl;    if (DBG){
5602          return NULL;      cout << "iroot    "<<iroot<<endl;
5603      }          cout << "irootnew "<<irootnew<<endl;
5604      Int_t irootnew = run_obj->ID_ROOT_L0;    }
 //     cout << "iroot    "<<iroot<<endl;  
 //     cout << "irootnew "<<irootnew<<endl;  
5605    
5606      //===================================
5607      // load the level0 file
5608      // (if not already loaded)
5609      //===================================
5610      if (iroot != irootnew || !l0_tree) {
5611        iroot = irootnew;
5612      //===================================      //===================================
5613      // load the level0 file      // open the DB connection
5614      // (if not already loaded)      // (if not already opened)
5615      //===================================      //===================================
5616      if( iroot != irootnew || !l0_tree){      if (!dbc || (dbc && !dbc->IsConnected()))
5617          iroot = irootnew;        SetDBConnection();
5618          //===================================      GL_ROOT glroot = GL_ROOT();
5619          // open the DB connection      if (glroot.Query_GL_ROOT(iroot, dbc)) {
5620          // (if not already opened)        cout << "TTree* PamLevel2::GetYodaTree( ) -- ERROR -- level0 file iroot = " << iroot << " does not exists"
5621          //===================================            << endl;
5622          if(!dbc || (dbc && !dbc->IsConnected())){        return NULL;
5623              cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;      };
5624              cout<<"Connecting to DB"<<endl;      TString filename = glroot.PATH + glroot.NAME;
5625              cout<<"HOST "<<host<<endl;      if (l0_file) {
5626              cout<<"USER "<<user<<endl;        l0_file->Close();
5627              cout<<"PSW  "<<psw<<endl;        l0_file->Delete();
5628              dbc = TSQLServer::Connect(host.Data(),user.Data(),psw.Data());      }
5629              if( !dbc )return NULL;      cout << "Opening LEVEL0 file: " << filename << endl;
5630              if( !dbc->IsConnected() )return NULL;          FileStat_t t;
5631  //          cout<<"...done"<<endl;      if (gSystem->GetPathInfo(filename.Data(), t)) {
5632              cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;        cout << " PamLevel2::GetYodaTree() -- ERROR opening file " << endl;
5633          }else{        return NULL;
5634  //          cout<<"DB already connected"<<endl;      }
5635          }      l0_file = new TFile(filename);
5636          GL_ROOT glroot = GL_ROOT();      if (!l0_file)
5637          if( glroot.Query_GL_ROOT(iroot,dbc) ){        return NULL;
5638              cout << "TTree* PamLevel2::GetYodaTree( ) -- ERROR -- level0 file iroot = "<<iroot<< " does not exists"<<endl;      l0_tree = (TTree*) l0_file->Get("Physics");
5639              return NULL;      if (!h0_obj)
5640          };        h0_obj = new EventHeader();
5641          TString filename = glroot.PATH + glroot.NAME;      l0_tree->SetBranchAddress("Header", &h0_obj);
5642          if(l0_file){      yprevshift = 0; // yes, yprevshift is the shift in the level0, prevshift is the shift in the level2
5643              l0_file->Close();      //---------------------------------------------------
5644              l0_file->Delete();      // TRACKER:
5645          }      if (TRK0) {
5646          cout << "Opening LEVEL0 file: "<< filename << endl;        if (!trk0_obj) {
5647          FileStat_t t;          trk0_obj = new TrkLevel0();
5648          if( gSystem->GetPathInfo(filename.Data(),t) ){          trk0_obj->Set();
5649              cout << " PamLevel2::GetYodaTree() -- ERROR opening file "<<endl;        };
5650              return NULL;        l0_tree->SetBranchAddress("Tracker", trk0_obj->GetPointerToTrackerEvent());
5651          }      }
5652          l0_file = new TFile(filename);      //--------------------------------------------------
5653          if( !l0_file )return NULL;      // CALORIMETER:
5654          l0_tree = (TTree*)l0_file->Get("Physics");      if (CAL0) {
5655          if(!h0_obj)h0_obj = new EventHeader();        if (!calo0_obj) {
5656          l0_tree->SetBranchAddress("Header" ,&h0_obj);          calo0_obj = new CaloLevel0();
5657          //---------------------------------------------------          calo0_obj->Set();
5658          // TRACKER:        };
5659          if(TRK0){        l0_tree->SetBranchAddress("Calorimeter", calo0_obj->GetPointerToCalorimeterEvent());
5660              if(!trk0_obj){      }
5661                  trk0_obj = new TrkLevel0();      //---------------------------------------------------
5662                  trk0_obj->Set();      // TOF:
5663              };      if (TOF0) {
5664              l0_tree->SetBranchAddress("Tracker" ,trk0_obj->GetPointerToTrackerEvent());        cout << "PamLevel2::GetYodaTree() --- level0 TOF not implemented " << endl;
         }  
         //---------------------------------------------------  
         // CALORIMETER:  
         if(CAL0){  
             cout << "PamLevel2::GetYodaTree() --- level0 calorimeter not implemented "<<endl;  
         }  
         //---------------------------------------------------  
         // TOF:  
         if(TOF0){  
             cout << "PamLevel2::GetYodaTree() --- level0 TOF not implemented "<<endl;  
         }  
   
     };  
   
     if(!dbc || (dbc && !dbc->IsConnected())){  
         cout << " TTree* PamLevel2::GetYodaTree( ) -- no DB connected... hai fatto qualche cazzata "<<endl;  
5665      }      }
5666    
5667      TrkParams::SetCalib(run_obj,dbc);      dbc->Close(); // EMILIANO, do not leave open connections, open only when needed
5668        delete dbc;
5669        dbc=0;
5670    
5671  //    cout << l0_tree << endl;    };
       
     return l0_tree;  
5672    
5673      if (TRK0) {
5674        if(!dbc || (dbc && !dbc->IsConnected()))SetDBConnection();
5675        TrkParams::SetCalib(run_obj, dbc);
5676        TrkParams::LoadCalib();
5677        if (!TrkParams::CalibIsLoaded()) {
5678          cout << " TTree* PamLevel2::GetYodaTree( ) -- WARNING -- Calibration not loaded" << endl;
5679        };
5680        if(dbc){
5681          dbc->Close(); // EMILIANO, do not leave open connections, open only when needed
5682          delete dbc;
5683          dbc=0;
5684        };
5685      }
5686      return l0_tree;
5687  }  }
5688    
5689  /**  /**
5690   * 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.
5691   */   */
5692  Int_t PamLevel2::GetYodaEntry(){  Int_t PamLevel2::GetYodaEntry() {
5693    
5694  //    cout << "Int_t PamLevel2::GetYodaEntry()"<<endl;    Long64_t iev = this->GetReadEntry();
5695      if(!GetYodaTree())return 0;  
5696          // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
5697      // patch    // if it is a full file (not preselected)
5698      if( (Int_t)irunentry < 0){    // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
5699          cout << "Int_t PamLevel2::GetYodaEntry() -- ATTENZIONE -- irunentry negativo?!?! "<<(Int_t)irunentry<<endl;    //  if (SELLI == 0 || SELLI == 2 || !hasL0EE) {
5700          irunentry=0;  
5701        if (!GetYodaTree()){
5702          printf(" PamLevel2::GetYodaEntry() : ERROR no level0 file loaded!\n");
5703          return 0;
5704        }
5705    
5706        if (irunentry < 0) {
5707          if (DBG) cout << "Int_t PamLevel2::GetYodaEntry() -- ATTENZIONE -- irunentry negativo?!?! "<<(Int_t)irunentry<<endl;
5708          //      cout << "Int_t PamLevel2::GetYodaEntry() -- ATTENZIONE -- irunentry negativo?!?! "<<(Int_t)irunentry<<endl; // TOGLITOGLI
5709          irunentry = 0LL;
5710      }      }
5711      //  ---------------------------------      //  ---------------------------------
5712      //  if file is NOT a preselected file      //  if file is NOT a preselected file
5713      //  ---------------------------------      //  ---------------------------------
5714      UInt_t quellagiusta = irunentry + run_obj->EV_FROM;      Long64_t quellagiusta = irunentry + (Long64_t)(run_obj->EV_FROM); // prevshift already included in irunentry
       
5715    
5716  //     cout << " irun "<< irun << " irunentry "<< irunentry<<" run_obj->EV_FROM "<<run_obj->EV_FROM <<" quella giusta "<<quellagiusta << endl;      if (DBG){
5717  //     cout << " iroot "<<iroot<<" run_obj->ID_ROOT_L0 "<<run_obj->ID_ROOT_L0<<endl;        cout << " irun "<< irun << " irunentry "<< irunentry<<" run_obj->EV_FROM "<<run_obj->EV_FROM <<" quella giusta "<<quellagiusta << endl;
5718  //     cout << " time "<< GetOrbitalInfo()->absTime << endl;        cout << " iroot "<<iroot<<" run_obj->ID_ROOT_L0 "<<run_obj->ID_ROOT_L0<<endl;
5719  //     cout << " trk_calib_used "<<run_obj->TRK_CALIB_USED<< endl;        cout << " time "<< abstime << endl;
5720            }
5721      if( !GetOrbitalInfo() ){  
5722          cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- missing OrbitalInfo "<<endl;      ULong64_t obt = 0;
5723          return 0;      ULong64_t pktn = 0;
5724        if (GetOrbitalInfo()) {
5725          obt = GetOrbitalInfo()->OBT;
5726          pktn = GetOrbitalInfo()->pkt_num;
5727        }
5728    
5729        if (!GetOrbitalInfo() && !ISGP) {
5730          cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- missing OrbitalInfo " << endl;
5731          return 0;
5732        }
5733        if (obt == 0 && pktn == 0 && !ISGP) {
5734          cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- level2 event corrupted ?? " << endl;
5735          return 0;
5736      }      }
5737    
5738      // ---------------------------------------------------------------------      // ---------------------------------------------------------------------
# Line 2523  Int_t PamLevel2::GetYodaEntry(){ Line 5746  Int_t PamLevel2::GetYodaEntry(){
5746      // 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
5747      // is shift forward until when the packets match.      // is shift forward until when the packets match.
5748      // ---------------------------------------------------------------------      // ---------------------------------------------------------------------
5749      Int_t answer = 0;      Long64_t shift = 0LL;
5750      Int_t shift =0;      Long64_t answer = quellagiusta + shift + yprevshift;
5751      do{      Int_t readl0 = 0;
5752          if(shift>0){      readl0 = l0_tree->GetEntry(answer); // prevshift already included in irunentry
5753              cout << " level0 <--> level2 mismatch ( irun "<<irun<<" irunentry "<<irunentry<<" shift "<<shift<<" )"<<endl;  
5754          }      if (DBG){
5755          answer = l0_tree->GetEntry(quellagiusta+shift);        printf(" siamo qui shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);
5756          shift++;      }
         if( !GetEventHeader() ){  
             cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- missing EventHeader "<<endl;  
             return 0;  
         }  
 //      if( (quellagiusta+shift) == l0_tree->GetEntries()+1 )cout << ">>> end of level0 tree <<<"<<endl;  
 //      cout << " GetOrbitalInfo()->OBT "<< GetOrbitalInfo()->OBT << endl;  
 //      cout << " GetEventHeader()->GetPscuHeader()->GetOrbitalTime() "<< GetEventHeader()->GetPscuHeader()->GetOrbitalTime() << endl;  
 //      cout << " GetOrbitalInfo()->pkt_num "<< GetOrbitalInfo()->pkt_num << endl;  
 //      cout << " GetEventHeader()->GetPscuHeader()->GetCounter() "<< GetEventHeader()->GetPscuHeader()->GetCounter() << endl;  
5757    
     }while( ( GetOrbitalInfo()->OBT != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()) || GetOrbitalInfo()->pkt_num != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter())) && (quellagiusta+shift) < GetYodaTree()->GetEntries() );  
5758    
5759  //    cout << "LA ENTRY GIUSTA E`: "<<quellagiusta<<" (spero...)"<<endl;      if (ISGP) {
5760  //    return GetYodaTree()->GetEntry(quellagiusta);        obt = (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()); //BARBATRUCCO
5761              pktn = (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter()); //BARBATRUCCO
5762      return answer;      }
5763    
5764        while ( (obt != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()) || pktn != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter())) && (quellagiusta + (Long64_t) shift) < GetYodaTree()->GetEntries() && shift < maxshift ){
5765          if ( isSync && shift == 0LL ){
5766            printf(" PamLevel2::GetYodaEntry() ERROR! sync file but the level0 entry not found in place!!! \n");
5767            cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
5768            cout << "\nFor bug reporting instructions, please see for example:\n";
5769            cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
5770            cout << "  " << endl;
5771          }
5772          if (shift > 0) {
5773            if (DBG) cout << " PKTNUM  L2 --- " << pktn << " --- L0 --- " << GetEventHeader()->GetPscuHeader()->GetCounter() << endl;
5774            if (DBG)
5775              cout << "         RUN: ID " << GetRunInfo()->ID << " ID_ROOT_L0 " << run_obj->ID_ROOT_L0 << " ID_RUN_FRAG "
5776                   << GetRunInfo()->ID_RUN_FRAG << " EV_FROM " << GetRunInfo()->EV_FROM << endl;
5777            if (DBG)
5778              cout << "         L2 <--> L0 mismatch ( irun " << irun << " irunentry " << irunentry << " shift " << shift
5779                   << " prevshift " << prevshift << " )" << endl;
5780          }
5781          answer = quellagiusta +  shift+ yprevshift;
5782          readl0 = l0_tree->GetEntry(answer);
5783          //      printf(" inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);//TOGLITOGLI
5784    
5785          if (!GetEventHeader()) {
5786            cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- missing EventHeader " << endl;
5787            return 0;
5788          }
5789    
5790          //
5791          if (yprevshift != 0 && (quellagiusta + (Long64_t) shift) == GetYodaTree()->GetEntries()) {
5792            if (DBG) printf(" reset inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);
5793            //        printf(" reset inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);//TOGLITOGLI
5794            yprevshift = 0LL;
5795            shift = -1LL;
5796          };
5797            
5798          shift++;
5799        }
5800                                      
5801    
5802        if ( obt != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()) || pktn != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter()) ){
5803          if ( isSync ){
5804            printf(" PamLevel2::GetYodaEntry() ERROR! sync file but the level0 entry not found AT ALL!!! \n");
5805            cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
5806            cout << "\nFor bug reporting instructions, please see for example:\n";
5807            cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
5808            cout << "  " << endl;
5809          }
5810          cout << "Int_t PamLevel2::GetYodaEntry() -- WARNING -- " << endl;
5811          cout << " Big trouble here, no such event in Level0 data! (NB maxshift set to " << maxshift << " )" << endl;    
5812          cout << " Nested and/or DarthVader skipped packets in fragmented run? checking and trying to fix " <<endl;
5813          // query the DB for runs containing the event, loop over LEVEL0 files which could contain the level0 event and try to find it
5814          // 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
5815          // connect to db
5816          if (!dbc || (dbc && !dbc->IsConnected())) SetDBConnection(); //Emiliano
5817          //
5818          if (GetOrbitalInfo()){
5819            abstime = GetOrbitalInfo()->absTime;
5820          } else {
5821            printf(" PamLevel2::GetYodaEntry() ERROR! no OrbitalInfo, cannot get the absolute time for event \n");
5822            return 0;
5823          }
5824          // query DB looking for runs containing the processed event
5825          TSQLResult *pResult;
5826          TSQLRow *Row = NULL;
5827          TString myquery = Form("select ID,NEVENTS from GL_RUN where RUNHEADER_TIME<=%lld and RUNTRAILER_TIME>=%lld;",abstime,abstime);
5828          if ( DBG ) printf(" query is %s \n",myquery.Data());
5829          //      printf(" query is %s \n",myquery.Data());// TOGLITOGLI
5830          pResult = dbc->Query(myquery.Data());    
5831          if (!pResult->GetRowCount()){
5832            printf(" PamLevel2::GetYodaEntry() ERROR! event is not included in any run!!! \n");
5833            cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
5834            cout << "\nFor bug reporting instructions, please see for example:\n";
5835            cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
5836            cout << "  " << endl;
5837            return 0;
5838          }
5839          if ( pResult->GetRowCount() == 1 ){
5840            if (DBG) printf(" PamLevel2::GetYodaEntry() - WARNING - YodaEntry not found but only one run containing the event, it should not happen \n");
5841            //        printf(" PamLevel2::GetYodaEntry() - WARNING - YodaEntry not found but only one run containing the event, it should not happen \n");//TOGLITOGLI
5842          }
5843          for( Int_t ru=0; ru < pResult->GetRowCount(); ru++){ // loop over runs containing the event
5844            if (Row) delete Row;
5845            Row = pResult->Next();  
5846            if( Row == NULL ) break;
5847            UInt_t idrun = (UInt_t)atoll(Row->GetField(0));
5848            UInt_t nev = (UInt_t)atoll(Row->GetField(1));
5849            if (DBG) printf(" inside loop over runs: ru %i idrun %i nev %i \n",ru,idrun,nev);
5850            //        printf(" inside loop over runs: ru %i idrun %i nev %i \n",ru,idrun,nev);//TOGLITOGLI
5851    
5852            // now look for this run in the level2 file, it must be present! code is taken from updateruninfo of course
5853            Bool_t rfound = false;
5854            totrunentry = 0LL;
5855            runfirstentry = 0LL;
5856            for (Int_t r=0; r< run_tree->GetEntries();r++){
5857              run_tree->GetEntry(r);//update runinfo
5858              if ( r > 0 ){
5859                totrunentrymin = totrunentrymax+1;
5860              } else {
5861                totrunentrymin = 0LL;
5862              }
5863              totrunentry += GetRunInfo()->NEVENTS;
5864              totrunentrymax = totrunentry - 1 - prevshift; // prevshift is needed to handle nested+DV_skipped packets
5865              irun = r;        
5866    
5867              if (idrun == GetRunInfo()->ID){
5868                if ( totrunentrymin > iev ){ // there is a shift (nested+DV_skipped packets)
5869                  if (DBG) printf("PamLevel2::GetYodaEntry - unconsistent iev - nevents, probable DBL0-L2 async\n");
5870                  if (DBG) printf("PamLevel2::GetYodaEntry - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);
5871                  //              printf("PamLevel2::GetYodaEntry - unconsistent iev - nevents, probable DBL0-L2 async\n");
5872                  //              printf("PamLevel2::GetYodaEntry - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);//TOGLITOGLI
5873                  prevshift += (totrunentrymin-iev); // add the new shift to total shift
5874                  totrunentrymin -= (totrunentrymin-iev); // shift run position min
5875                  totrunentrymax -= (totrunentrymin-iev); // shift run position max
5876                  if (DBG) printf("PamLevel2::GetYodaEntry - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);
5877                  //              printf("PamLevel2::GetYodaEntry - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);//TOGLITOGLI
5878                }
5879                runfirstentry = totrunentrymin; // first entry of the run in the level2
5880              
5881    
5882                //
5883                if (gltsync)
5884                  delete gltsync; // Emiliano
5885                if (!dbc || (dbc && !dbc->IsConnected()))
5886                  SetDBConnection(); //Emiliano
5887                gltsync = new GL_TIMESYNC(GetRunInfo()->ID_ROOT_L0, "ID", dbc, false); // Emiliano
5888                if (dbc){
5889                  dbc->Close(); // Emiliano
5890                  delete dbc;
5891                  dbc=0;
5892                }          
5893                if (gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT) > gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT)) { // Emiliano
5894                  cout << "Bool_t PamLevel2::UpdateRunInfo(Long64_t iev) -- WARNING -- irun " << irun
5895                       << "  has RUNHEADER_OBT>=RUNTRAILER_OBT " << endl;
5896                  cout
5897                    << "                                                            (NB!! in this case some events could be assigned to a wrong run)"
5898                    << endl;
5899                }
5900                //
5901                if (DBG) printf(" found \n");
5902                //            printf(" found \n");//TOGLITOGLI
5903                rfound = true;
5904                //
5905                break;
5906              }
5907            } // loop over run
5908            if ( !rfound ){
5909              printf(" PamLevel2::GetYodaEntry() ERROR! run is not present in the level2 file!!! \n");
5910              cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
5911              cout << "\nFor bug reporting instructions, please see for example:\n";
5912              cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
5913              cout << "  " << endl;        
5914              return 0;
5915            }
5916    
5917            // here we got the first run and we can check if it contains the level0 event
5918            if (!GetYodaTree()){
5919              printf(" PamLevel2::GetYodaEntry() : ERROR no level0 file loaded!\n");
5920              return 0;
5921            }      
5922    
5923            // get the current run entry
5924            irunentry = iev - runfirstentry;
5925            if (irunentry < 0) {
5926              if (DBG) cout << "Int_t PamLevel2::GetYodaEntry() -- ATTENZIONE -- irunentry negativo?!?! "<<(Int_t)irunentry<<endl;
5927              //          cout << "Int_t PamLevel2::GetYodaEntry() -- ATTENZIONE -- irunentry negativo?!?! "<<(Int_t)irunentry<<endl; // TOGLITOGLI
5928              irunentry = 0LL;
5929            }
5930            //  ---------------------------------
5931            //  if file is NOT a preselected file
5932            //  ---------------------------------
5933            quellagiusta = irunentry + (Long64_t)(run_obj->EV_FROM); // prevshift already included in irunentry
5934          
5935            if (DBG){
5936              cout << " irun "<< irun << " irunentry "<< irunentry<<" run_obj->EV_FROM "<<run_obj->EV_FROM <<" quella giusta "<<quellagiusta << endl;
5937              cout << " iroot "<<iroot<<" run_obj->ID_ROOT_L0 "<<run_obj->ID_ROOT_L0<<endl;
5938              cout << " time "<< abstime << endl;
5939            }
5940            //        cout << " irun "<< irun << " irunentry "<< irunentry<<" run_obj->EV_FROM "<<run_obj->EV_FROM <<" quella giusta "<<quellagiusta << endl;
5941            //        cout << " iroot "<<iroot<<" run_obj->ID_ROOT_L0 "<<run_obj->ID_ROOT_L0<<endl;
5942            //        cout << " time "<< abstime << endl; // TOGLITOGLI
5943          
5944            shift = 0;
5945            answer = quellagiusta + shift + yprevshift; // prevshift already included in irunentry
5946            readl0 = l0_tree->GetEntry(answer); // prevshift already included in irunentry
5947    
5948            if (DBG){
5949              printf(" siamo qua shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);
5950            }
5951            //        printf(" siamo qua shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);//TOGLITOGLI
5952          
5953            while ( (obt != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()) || pktn != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter())) && (quellagiusta + (Long64_t) shift) < GetYodaTree()->GetEntries() && shift < maxshift ){
5954              if (shift > 0) {
5955                if (DBG) cout << " PKTNUM  L2 --- " << pktn << " --- L0 --- " << GetEventHeader()->GetPscuHeader()->GetCounter() << endl;
5956                if (DBG)
5957                  cout << "         RUN: ID " << GetRunInfo()->ID << " ID_ROOT_L0 " << run_obj->ID_ROOT_L0 << " ID_RUN_FRAG "
5958                       << GetRunInfo()->ID_RUN_FRAG << " EV_FROM " << GetRunInfo()->EV_FROM << endl;
5959                if (DBG)
5960                  cout << "         L2 <--> L0 mismatch ( irun " << irun << " irunentry " << irunentry << " shift " << shift
5961                       << " prevshift " << prevshift << " )" << endl;
5962              }
5963              answer = quellagiusta +  shift+ yprevshift;
5964              readl0 = l0_tree->GetEntry(answer);
5965              //          printf(" inside inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);//TOGLITOGLI
5966            
5967              if (!GetEventHeader()) {
5968                cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- missing EventHeader " << endl;
5969                return 0;
5970              }
5971              //
5972              if (yprevshift != 0 && (quellagiusta + (Long64_t) shift) == GetYodaTree()->GetEntries()) {
5973                if (DBG) printf(" reset inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);
5974                //            printf(" reset inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);//TOGLITOGLI
5975                yprevshift = 0;
5976                shift = -1;
5977              };
5978            
5979              shift++;
5980            }
5981          
5982            if ( obt != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()) || pktn != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter()) ){
5983              //still not the good run... continue with the nex one!
5984              printf("still not the good run... continue with the nex one!\n");
5985            } else {
5986              if (DBG) cout << "LA ENTRY GIUSTA E`: "<<quellagiusta<<" (spero...)"<<endl;
5987              //          cout << "LA ENTRY GIUSTA E`: "<<answer<<" (spero...)"<<endl;//TOGLITOGLI
5988              if (shift > 1) yprevshift = (shift - 1);
5989              if (Row) delete Row;
5990              delete pResult;  
5991              if (dbc){
5992                dbc->Close(); // Emiliano
5993                delete dbc;
5994                dbc=0;
5995              }    
5996              il0entry = answer;
5997              return readl0;
5998            }
5999            // perhaps it is all
6000          }// loop over runs containing the event
6001          if (Row) delete Row;
6002          delete pResult;  
6003          if (dbc){
6004            dbc->Close(); // Emiliano
6005            delete dbc;
6006            dbc=0;
6007          }          
6008          // arriving here it means no run found, cannot be! error!
6009          printf(" PamLevel2::GetYodaEntry() ERROR! run is not present in the level0 files!!! \n");
6010          cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
6011          cout << "\nFor bug reporting instructions, please see for example:\n";
6012          cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
6013          cout << "  " << endl;        
6014          return 0;
6015        } else {
6016          if (DBG) cout << "=> LA ENTRY GIUSTA E`: "<<answer<<" (spero...)"<<endl;
6017          //    cout << "=> LA ENTRY GIUSTA E`: "<<answer<<" (spero...)"<<endl;
6018          //    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()) );
6019          if (shift > 1) yprevshift = (shift - 1);
6020          il0entry = answer;
6021          return readl0;
6022        }
6023    
6024        /*  } // if selli 0 || 2
6025      if ( SELLI == 1 && hasL0EE ){
6026        sel_tree->GetEntry(iev);  
6027        Long64_t answer = il0entry;
6028        Int_t readl0 = 0;
6029        readl0 = l0_tree->GetEntry(answer);
6030        return readl0;
6031        }*/
6032      printf(" PamLevel2::GetYodaEntry() ERROR! \n");
6033      cout << " Entry not found! OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
6034      cout << "\nFor bug reporting instructions, please see for example:\n";
6035      cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
6036      cout << "  " << endl;
6037      return 0;
6038    }
6039    
6040    /**
6041     * \Brief Set DB connection
6042     */
6043    Bool_t PamLevel2::SetDBConnection() {
6044    
6045      //    cout << "PamLevel2::SetDBConnection()" << endl;
6046      if (DBG) {
6047        cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
6048        cout << "Connecting to DB" << endl;
6049        cout << "HOST " << host << endl;
6050        cout << "USER " << user << endl;
6051        cout << "PSW  " << psw << endl;
6052      }
6053      Bool_t notconn = true;
6054      Int_t trials = 0;
6055      while ( notconn && trials < 10 ){
6056        //    gSystem->Sleep(500);
6057        dbc = TSQLServer::Connect(host.Data(), user.Data(), psw.Data());
6058        //dbc->Connect(host.Data(), user.Data(), psw.Data());
6059        if ( dbc ) notconn = false;
6060        if (DBG) printf("<%i> test connection...\n ",trials);
6061        if (!dbc){
6062          if (DBG) printf(" :( failed, no pointer \n");
6063          notconn = true;
6064          //      return false;
6065        };
6066        if (dbc && !dbc->IsConnected()){
6067          if (DBG) printf(" :( failed, no connection \n");
6068          notconn = true;
6069          //      return false;
6070        };
6071        trials++;
6072      };
6073      if ( notconn ) return false;
6074      //
6075      if (DBG) printf("=connected!\n");
6076      stringstream myquery; // EMILIANO
6077      myquery.str(""); // EMILIANO
6078      myquery << "SET time_zone='+0:00'"; // EMILIANO
6079      dbc->Query(myquery.str().c_str()); // EMILIANO
6080      if ( DBG ) printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
6081      return true;
6082    
6083    }
6084    
6085    /**
6086     * \Brief Add a friend to the pamela chain.
6087     * @param cname name of the chain to be added
6088     */
6089    
6090    TChain* PamLevel2::AddFriend(TString cname) {
6091    
6092      if (!GetPamTree()) {
6093        cout << " TChain* PamLevel2::AddFriend(TString cname) --- a pamela tree must be created first" << endl;
6094        return NULL;
6095      }
6096    
6097      TChain *c = new TChain(cname.Data());
6098    
6099      TIter next(GetPamTree()->GetListOfFiles());
6100      Int_t nf = 0;
6101      TChainElement* element = 0;
6102      while ((element = (TChainElement*) next())) {
6103        c->Add(element->GetTitle());
6104        nf++;
6105      }
6106    
6107      GetPamTree()->AddFriend(cname.Data());
6108    
6109      cout << "external chain created and added to pamela friends :" << cname << endl;
6110      cout << "n.files " << nf << endl;
6111    
6112      return c;
6113    
6114    }
6115    
6116    /**
6117     * Returns the current read entry. This method simply returns the result of the call to
6118     * pam_tree->GetReadEntry(), so it is entirely handled by ROOT.
6119     */
6120    Long64_t PamLevel2::GetReadEntry() {
6121      return pam_tree->GetReadEntry();
6122    }
6123    
6124    /**
6125     * Sets the sorting method. If the new method is different from the previous, the issorted
6126     * flag is set to false, forcing a new sort the next time GetTrack is called.
6127     * @see GetTrack
6128     */
6129    void PamLevel2::SetSortingMethod(TString how) {
6130      if (howtosort != how) {
6131        issorted = false;
6132        issorted_new = false;
6133      }
6134      howtosort = how;
6135  }  }

Legend:
Removed from v.1.27  
changed lines
  Added in v.1.110

  ViewVC Help
Powered by ViewVC 1.1.23