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

Legend:
Removed from v.1.13  
changed lines
  Added in v.1.99

  ViewVC Help
Powered by ViewVC 1.1.23