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

Legend:
Removed from v.1.42  
changed lines
  Added in v.1.96

  ViewVC Help
Powered by ViewVC 1.1.23