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

Legend:
Removed from v.1.28  
changed lines
  Added in v.1.100

  ViewVC Help
Powered by ViewVC 1.1.23