/[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.40 by pam-fi, Fri May 25 13:38:51 2007 UTC revision 1.101 by mocchiut, Fri Oct 17 16:04:42 2014 UTC
# Line 1  Line 1 
1  #include <PamLevel2.h>  #include <PamLevel2.h>
2    
3    /////////////////////////////////////////////////////////////////////////////
4    /////////////////////////////////////////////////////////////////////////////
5    /////////////////////////////////////////////////////////////////////////////
6    /////////////////////////////////////////////////////////////////////////////
7    
8    void GPamela::Clear() {
9      Irun = 0;
10      Ievnt = 0;
11      Ipa = 0;
12      X0 = 0.;
13      Y0 = 0.;
14      Z0 = 0.;
15      Theta = 0.;
16      Phi = 0.;
17      P0 = 0.;
18      Nthtof = 0;
19      Nthcat = 0;
20      Nthcas = 0;
21      Nthspe = 0;
22      Nstrpx = 0;
23      Nstrpy = 0;
24      Nthcali = 0;
25      Nthcal = 0;
26      Nthnd = 0;
27      Nthcard = 0;
28    }
29    
30    void GPamela::Delete() {
31    
32      Clear();
33      /* EM all these are in the stack not in the heap, so no need to delete by hand...
34      delete[] Ipltof;
35      delete[] Ipaddle;
36      delete[] Ipartof;
37      delete[] Xintof;
38      delete[] Yintof;
39      delete[] Zintof;
40      delete[] Xouttof;
41      delete[] Youttof;
42      delete[] Zouttof;
43      delete[] Ereltof;
44      delete[] Timetof;
45      delete[] Pathtof;
46      delete[] P0tof;
47      delete[] Iparcat;
48      delete[] Icat;
49      delete[] Xincat;
50      delete[] Yincat;
51      delete[] Zincat;
52      delete[] Xoutcat;
53      delete[] Youtcat;
54      delete[] Zoutcat;
55      delete[] Erelcat;
56      delete[] Timecat;
57      delete[] Pathcat;
58      delete[] P0cat;
59      delete[] Iparcas;
60      delete[] Icas;
61      delete[] Xincas;
62      delete[] Yincas;
63      delete[] Zincas;
64      delete[] Xoutcas;
65      delete[] Youtcas;
66      delete[] Zoutcas;
67      delete[] Erelcas;
68      delete[] Timecas;
69      delete[] Pathcas;
70      delete[] P0cas;
71      delete[] Iparspe;
72      delete[] Itrpb;
73      delete[] Itrsl;
74      delete[] Itspa;
75      delete[] Xinspe;
76      delete[] Yinspe;
77      delete[] Zinspe;
78      delete[] Xoutspe;
79      delete[] Youtspe;
80      delete[] Zoutspe;
81      delete[] Xavspe;
82      delete[] Yavspe;
83      delete[] Zavspe;
84      delete[] Erelspe;
85      delete[] Pathspe;
86      delete[] P0spe;
87      delete[] Nxmult;
88      delete[] Nymult;
89      delete[] Npstripx;
90      delete[] Ntstripx;
91      delete[] Istripx;
92      delete[] Qstripx;
93      delete[] Xstripx;
94      delete[] Npstripy;
95      delete[] Ntstripy;
96      delete[] Istripy;
97      delete[] Qstripy;
98      delete[] Ystripy;
99      delete[] Icaplane;
100      delete[] Icastrip;
101      delete[] Icamod;
102      delete[] Enestrip;
103      delete[] Icapl;
104      delete[] Icasi;
105      delete[] Icast;
106      delete[] Xincal;
107      delete[] Yincal;
108      delete[] Zincal;
109      delete[] Erelcal;
110      delete[] Itubend;
111      delete[] Iparnd;
112      delete[] Xinnd;
113      delete[] Yinnd;
114      delete[] Zinnd;
115      delete[] Xoutnd;
116      delete[] Youtnd;
117      delete[] Zoutnd;
118      delete[] Erelnd;
119      delete[] Timend;
120      delete[] Pathnd;
121      delete[] P0nd;
122      delete[] Iparcard;
123      delete[] Icard;
124      delete[] Xincard;
125      delete[] Yincard;
126      delete[] Zincard;
127      delete[] Xoutcard;
128      delete[] Youtcard;
129      delete[] Zoutcard;
130      delete[] Erelcard;
131      delete[] Timecard;
132      delete[] Pathcard;
133      delete[] P0card;
134      */
135    }
136    
137    
138    void GPamela::SetBranchAddress(TChain* fhBookTree) {
139    
140      //    cout << "fhBookTree "<<fhBookTree << endl;
141      // prepare tree
142      fhBookTree->SetBranchAddress("Irun", &Irun);
143      fhBookTree->SetBranchAddress("Ievnt", &Ievnt);
144      fhBookTree->SetBranchAddress("Ipa", &Ipa);
145      fhBookTree->SetBranchAddress("X0", &X0);
146      fhBookTree->SetBranchAddress("Y0", &Y0);
147      fhBookTree->SetBranchAddress("Z0", &Z0);
148      fhBookTree->SetBranchAddress("Theta", &Theta);
149      fhBookTree->SetBranchAddress("Phi", &Phi);
150      fhBookTree->SetBranchAddress("P0", &P0);
151      fhBookTree->SetBranchAddress("Nthtof", &Nthtof);
152      fhBookTree->SetBranchAddress("Ipltof", Ipltof);
153      fhBookTree->SetBranchAddress("Ipaddle", Ipaddle);
154      fhBookTree->SetBranchAddress("Ipartof", Ipartof);
155      fhBookTree->SetBranchAddress("Xintof", Xintof);
156      fhBookTree->SetBranchAddress("Yintof", Yintof);
157      fhBookTree->SetBranchAddress("Zintof", Zintof);
158      fhBookTree->SetBranchAddress("Xouttof", Xouttof);
159      fhBookTree->SetBranchAddress("Youttof", Youttof);
160      fhBookTree->SetBranchAddress("Zouttof", Zouttof);
161      fhBookTree->SetBranchAddress("Ereltof", Ereltof);
162      fhBookTree->SetBranchAddress("Timetof", Timetof);
163      fhBookTree->SetBranchAddress("Pathtof", Pathtof);
164      fhBookTree->SetBranchAddress("P0tof", P0tof);
165      fhBookTree->SetBranchAddress("Nthcat", &Nthcat);
166      fhBookTree->SetBranchAddress("Iparcat", Iparcat);
167      fhBookTree->SetBranchAddress("Icat", Icat);
168      fhBookTree->SetBranchAddress("Xincat", Xincat);
169      fhBookTree->SetBranchAddress("Yincat", Yincat);
170      fhBookTree->SetBranchAddress("Zincat", Zincat);
171      fhBookTree->SetBranchAddress("Xoutcat", Xoutcat);
172      fhBookTree->SetBranchAddress("Youtcat", Youtcat);
173      fhBookTree->SetBranchAddress("Zoutcat", Zoutcat);
174      fhBookTree->SetBranchAddress("Erelcat", Erelcat);
175      fhBookTree->SetBranchAddress("Timecat", Timecat);
176      fhBookTree->SetBranchAddress("Pathcat", Pathcat);
177      fhBookTree->SetBranchAddress("P0cat", P0cat);
178      fhBookTree->SetBranchAddress("Nthcas", &Nthcas);
179      fhBookTree->SetBranchAddress("Iparcas", Iparcas);
180      fhBookTree->SetBranchAddress("Icas", Icas);
181      fhBookTree->SetBranchAddress("Xincas", Xincas);
182      fhBookTree->SetBranchAddress("Yincas", Yincas);
183      fhBookTree->SetBranchAddress("Zincas", Zincas);
184      fhBookTree->SetBranchAddress("Xoutcas", Xoutcas);
185      fhBookTree->SetBranchAddress("Youtcas", Youtcas);
186      fhBookTree->SetBranchAddress("Zoutcas", Zoutcas);
187      fhBookTree->SetBranchAddress("Erelcas", Erelcas);
188      fhBookTree->SetBranchAddress("Timecas", Timecas);
189      fhBookTree->SetBranchAddress("Pathcas", Pathcas);
190      fhBookTree->SetBranchAddress("P0cas", P0cas);
191      fhBookTree->SetBranchAddress("Nthspe", &Nthspe);
192      fhBookTree->SetBranchAddress("Iparspe", Iparspe);
193      fhBookTree->SetBranchAddress("Itrpb", Itrpb);
194      fhBookTree->SetBranchAddress("Itrsl", Itrsl);
195      fhBookTree->SetBranchAddress("Itspa", Itspa);
196      fhBookTree->SetBranchAddress("Xinspe", Xinspe);
197      fhBookTree->SetBranchAddress("Yinspe", Yinspe);
198      fhBookTree->SetBranchAddress("Zinspe", Zinspe);
199      fhBookTree->SetBranchAddress("Xoutspe", Xoutspe);
200      fhBookTree->SetBranchAddress("Youtspe", Youtspe);
201      fhBookTree->SetBranchAddress("Zoutspe", Zoutspe);
202      fhBookTree->SetBranchAddress("Xavspe", Xavspe);
203      fhBookTree->SetBranchAddress("Yavspe", Yavspe);
204      fhBookTree->SetBranchAddress("Zavspe", Zavspe);
205      fhBookTree->SetBranchAddress("Erelspe", Erelspe);
206      fhBookTree->SetBranchAddress("Pathspe", Pathspe);
207      fhBookTree->SetBranchAddress("P0spe", P0spe);
208      fhBookTree->SetBranchAddress("Nxmult", Nxmult);
209      fhBookTree->SetBranchAddress("Nymult", Nymult);
210      fhBookTree->SetBranchAddress("Nstrpx", &Nstrpx);
211      fhBookTree->SetBranchAddress("Npstripx", Npstripx);
212      fhBookTree->SetBranchAddress("Ntstripx", Ntstripx);
213      fhBookTree->SetBranchAddress("Istripx", Istripx);
214      fhBookTree->SetBranchAddress("Qstripx", Qstripx);
215      fhBookTree->SetBranchAddress("Xstripx", Xstripx);
216      fhBookTree->SetBranchAddress("Nstrpy", &Nstrpy);
217      fhBookTree->SetBranchAddress("Npstripy", Npstripy);
218      fhBookTree->SetBranchAddress("Ntstripy", Ntstripy);
219      fhBookTree->SetBranchAddress("Istripy", Istripy);
220      fhBookTree->SetBranchAddress("Qstripy", Qstripy);
221      fhBookTree->SetBranchAddress("Ystripy", Ystripy);
222      fhBookTree->SetBranchAddress("Nthcali", &Nthcali);
223      fhBookTree->SetBranchAddress("Icaplane", Icaplane);
224      fhBookTree->SetBranchAddress("Icastrip", Icastrip);
225      fhBookTree->SetBranchAddress("Icamod", Icamod);
226      fhBookTree->SetBranchAddress("Enestrip", Enestrip);
227      fhBookTree->SetBranchAddress("Nthcal", &Nthcal);
228      fhBookTree->SetBranchAddress("Icapl", Icapl);
229      fhBookTree->SetBranchAddress("Icasi", Icasi);
230      fhBookTree->SetBranchAddress("Icast", Icast);
231      fhBookTree->SetBranchAddress("Xincal", Xincal);
232      fhBookTree->SetBranchAddress("Yincal", Yincal);
233      fhBookTree->SetBranchAddress("Zincal", Zincal);
234      fhBookTree->SetBranchAddress("Erelcal", Erelcal);
235      fhBookTree->SetBranchAddress("Nthnd", &Nthnd);
236      fhBookTree->SetBranchAddress("Itubend", Itubend);
237      fhBookTree->SetBranchAddress("Iparnd", Iparnd);
238      fhBookTree->SetBranchAddress("Xinnd", Xinnd);
239      fhBookTree->SetBranchAddress("Yinnd", Yinnd);
240      fhBookTree->SetBranchAddress("Zinnd", Zinnd);
241      fhBookTree->SetBranchAddress("Xoutnd", Xoutnd);
242      fhBookTree->SetBranchAddress("Youtnd", Youtnd);
243      fhBookTree->SetBranchAddress("Zoutnd", Zoutnd);
244      fhBookTree->SetBranchAddress("Erelnd", Erelnd);
245      fhBookTree->SetBranchAddress("Timend", Timend);
246      fhBookTree->SetBranchAddress("Pathnd", Pathnd);
247      fhBookTree->SetBranchAddress("P0nd", P0nd);
248      fhBookTree->SetBranchAddress("Nthcard", &Nthcard);
249      fhBookTree->SetBranchAddress("Iparcard", Iparcard);
250      fhBookTree->SetBranchAddress("Icard", Icard);
251      fhBookTree->SetBranchAddress("Xincard", Xincard);
252      fhBookTree->SetBranchAddress("Yincard", Yincard);
253      fhBookTree->SetBranchAddress("Zincard", Zincard);
254      fhBookTree->SetBranchAddress("Xoutcard", Xoutcard);
255      fhBookTree->SetBranchAddress("Youtcard", Youtcard);
256      fhBookTree->SetBranchAddress("Zoutcard", Zoutcard);
257      fhBookTree->SetBranchAddress("Erelcard", Erelcard);
258      fhBookTree->SetBranchAddress("Timecard", Timecard);
259      fhBookTree->SetBranchAddress("Pathcard", Pathcard);
260      fhBookTree->SetBranchAddress("P0card", P0card);
261    
262      //    fhBookTree->SetBranchStatus("*",0);
263    
264    }
265    
266    ClassImp( GPamela);
267    
268    /////////////////////////////////////////////////////////////////////////////
269    /////////////////////////////////////////////////////////////////////////////
270    /////////////////////////////////////////////////////////////////////////////
271    /////////////////////////////////////////////////////////////////////////////
272  //--------------------------------------  //--------------------------------------
273  //  //
274  //  //
275  //--------------------------------------  //--------------------------------------
276  /**  /**
277   * Default constructor   * Default constructor
278   */   */
279  PamTrack::PamTrack(){  PamTrack::PamTrack() {
280      trk_track  = 0;    trk_track = 0;
281      calo_track = 0;    trk_ext_track = 0;
282      tof_track  = 0;    calo_track = 0;
283      candeleteobj = 0;    tof_track = 0;
284  };    orb_track = 0;
285      candeleteobj = 0;
286      pscore = 0;
287      iscore = 0;
288    }
289    ;
290  //--------------------------------------  //--------------------------------------
291  //  //
292  //  //
293  //--------------------------------------  //--------------------------------------
294  /**  /**
295   * Constructor   * Constructor
296   */   */
297  PamTrack::PamTrack(TrkTrack* t, CaloTrkVar* c, ToFTrkVar* o){  PamTrack::PamTrack(TrkTrack* t, CaloTrkVar* c, ToFTrkVar* o, OrbitalInfoTrkVar *r) {
298    
299      trk_track  = 0;    trk_ext_track = 0;
300      calo_track = 0;    trk_track = 0;
301      tof_track  = 0;    calo_track = 0;
302  //     if(t)trk_track  = new TrkTrack(*t);    tof_track = 0;
303  //     if(c)calo_track = new CaloTrkVar(*c);    orb_track = 0;
304  //     if(o)tof_track  = new ToFTrkVar(*o);    //     if(t)trk_track  = new TrkTrack(*t);
305      if(t)trk_track  = t;    //     if(c)calo_track = new CaloTrkVar(*c);
306      if(c)calo_track = c;    //     if(o)tof_track  = new ToFTrkVar(*o);
307      if(o)tof_track  = o;  //   if (t)
308      candeleteobj = 0;  //     trk_track = t;
309    //   if (c)
310    //     calo_track = c;
311    //   if (o)
312    //     tof_track = o;
313    //   if (r)
314    //     orb_track = r;
315    
316    //   candeleteobj = 0;
317    
318    
319      if (t){
320          trk_track = new TrkTrack(*t);
321          trk_ext_track = new ExtTrack(*t);//NB!! ha dimensione 6 invece che 8
322      }
323      if (c)
324        calo_track = new CaloTrkVar(*c);
325      if (o)
326        tof_track = new ToFTrkVar(*o);
327      if (r)
328        orb_track = new OrbitalInfoTrkVar(*r);
329      candeleteobj = 1;
330    
331  };  }
332  PamTrack::PamTrack(const PamTrack& track){  ;
333    /**
334     * Constructor
335     */
336    PamTrack::PamTrack(ExtTrack* t, CaloTrkVar* c, ToFTrkVar* o, OrbitalInfoTrkVar *r) {
337    
338      trk_ext_track = 0;
339      trk_track = 0;
340      calo_track = 0;
341      tof_track = 0;
342      orb_track = 0;
343      //     if(t)trk_track  = new TrkTrack(*t);
344      //     if(c)calo_track = new CaloTrkVar(*c);
345      //     if(o)tof_track  = new ToFTrkVar(*o);
346    //   if (t)
347    //     trk_track = t;
348    //   if (c)
349    //     calo_track = c;
350    //   if (o)
351    //     tof_track = o;
352    //   if (r)
353    //     orb_track = r;
354    
355    //   candeleteobj = 0;
356    
357    
358      if (t){
359    ////      trk_track = new TrkTrack(*t);//in this case TrkTrack object remains null
360          trk_ext_track = new ExtTrack(*t);
361      }
362      if (c)
363        calo_track = new CaloTrkVar(*c);
364      if (o)
365        tof_track = new ToFTrkVar(*o);
366      if (r)
367        orb_track = new OrbitalInfoTrkVar(*r);
368      candeleteobj = 1;
369      pscore = 0;
370      iscore = 0;
371    
372      TrkTrack   *t = track.trk_track;  }
373      CaloTrkVar *c = track.calo_track;  ;
374      ToFTrkVar  *o = track.tof_track;  PamTrack::PamTrack(const PamTrack& track) {
375    
376      TrkTrack *t = track.trk_track;
377      ExtTrack *e = track.trk_ext_track;
378      CaloTrkVar *c = track.calo_track;
379      ToFTrkVar *o = track.tof_track;
380      OrbitalInfoTrkVar *r = track.orb_track;
381    
382      trk_ext_track = 0;
383      trk_track     = 0;
384      calo_track    = 0;
385      tof_track     = 0;
386      orb_track     = 0;
387      if(e)
388          trk_ext_track = new ExtTrack(*e);
389      if (t)
390        trk_track = new TrkTrack(*t);
391      if (c)
392        calo_track = new CaloTrkVar(*c);
393      if (o)
394        tof_track = new ToFTrkVar(*o);
395      if (r)
396        orb_track = new OrbitalInfoTrkVar(*r);
397    
398      candeleteobj = 1;
399      pscore = 0;
400      iscore = 0;
401    
     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;  
       
402  }  }
403  void PamTrack::Clear(){  void PamTrack::Clear(Option_t *option) {
404    
405  //    cout << "PamTrack::Clear() "<<candeleteobj<<endl;  //    cout << "PamTrack::Clear( "<<option<<" ) "<<candeleteobj<<endl;
406      if(candeleteobj){    if (candeleteobj) {
407          if(trk_track)  trk_track->TrkTrack::Clear();        
408          if(calo_track) calo_track->CaloTrkVar::Clear();//???      if (trk_ext_track)
409          if(tof_track)  tof_track->ToFTrkVar::Clear();//???        trk_ext_track->ExtTrack::Clear(option);
410      }else{      if (trk_track)
411          trk_track  = 0;        trk_track->TrkTrack::Clear();
412          calo_track = 0;      if (calo_track)
413          tof_track  = 0;        calo_track->CaloTrkVar::Clear();//???
414      }      if (tof_track)
415  }        tof_track->ToFTrkVar::Clear();//???
416  void PamTrack::Delete(){      if (orb_track)
417  //    cout << "PamTrack::Delete() "<<candeleteobj<<endl;        orb_track->OrbitalInfoTrkVar::Clear();//???
418      if(candeleteobj){    }
419          if(trk_track)  {    else {
420              trk_track->TrkTrack::Clear();      trk_ext_track = 0;
421              delete trk_track;      trk_track = 0;
422          }      calo_track = 0;
423          if(calo_track){      tof_track = 0;
424              calo_track->CaloTrkVar::Clear();//???      orb_track = 0;
425              delete calo_track;    }
426          }    pscore = 0;
427          if(tof_track){    iscore = 0;
428              tof_track->ToFTrkVar::Clear();//???  
429              delete tof_track;  }
430          }  void PamTrack::Delete() {
431      }else{    //    cout << "PamTrack::Delete() "<<candeleteobj<<endl;
432          Clear();    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   * Default Constructor   * Default Constructor
468   */   */
469  PamLevel2::PamLevel2(){  PamLevel2::PamLevel2() {
470    Initialize();    Initialize();
471  };  }
472    
473    
474  /**  /**
475   * Constructor with given dir, list and detectors   * 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 list,TString detlist){  PamLevel2::PamLevel2(TString ddir, TString llist, TString detlist) {
489    Initialize();    Initialize();
490    GetPamTree(GetListOfLevel2Files(ddir,list),detlist);    TList* listf = GetListOfLevel2Files(ddir, llist);
491    GetRunTree(GetListOfLevel2Files(ddir,list));    if (listf)
492  };      GetPamTree(listf, detlist);
493      if (listf)
494        GetRunTree(listf);
495      SetMaxShift(-1);
496    }
497    
498    
499    PamLevel2::PamLevel2(TString ddir, TList *llist, TString detlist) {
500      Initialize();
501      GetPamTree(llist, detlist);
502      GetRunTree(llist);
503      SetMaxShift(-1);
504    }
505    
506  /**  /**
507   * Constructor with given dir and list   * 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 list){  PamLevel2::PamLevel2(TString ddir, TString llist) {
514    Initialize();    Initialize();
515    GetPamTree(GetListOfLevel2Files(ddir,list),"");    TList* listf = GetListOfLevel2Files(ddir, llist);
516    GetRunTree(GetListOfLevel2Files(ddir,list));    cout << "GetPamTree: "<<endl;
517  };    GetPamTree(listf, "");
518      cout << "GetRunTree: "<<endl;
519      GetRunTree(listf);
520      SetMaxShift(-1);
521    }
522    
523    
524  void PamLevel2::Initialize(){  void PamLevel2::Initialize() {
           
 //     trk2_obj  = TrkLevel2::GetTrkLevel2();  
 //     trk1_obj  = TrkLevel1::GetTrkLevel1();  
 //     trkh_obj  = TrkHough::GetTrkHough();  
 //     calo1_obj = CaloLevel1::GetCaloLevel1();  
 //     calo2_obj = CaloLevel2::GetCaloLevel2();  
 //     tof_obj   = ToFLevel2::GetToFLevel2();  
 //     trig_obj  = TrigLevel2::GetTrigLevel2();  
 //     s4_obj    = S4Level2::GetS4Level2();  
 //     nd_obj    = NDLevel2::GetNDLevel2();  
 //     ac_obj    = AcLevel2::GetAcLevel2();  
 //     orb_obj   = OrbitalInfo::GetOrbitalInfo();  
       
     h0_obj    = 0;  
     trk0_obj  = 0;  
     calo0_obj  = 0;  
   
     trk2_obj  = 0;  
     trk1_obj  = 0;  
     trkh_obj  = 0;  
     calo1_obj = 0;  
     calo2_obj = 0;  
     tof_obj   = 0;  
     trig_obj  = 0;  
     s4_obj    = 0;  
     nd_obj    = 0;  
     ac_obj    = 0;  
     orb_obj   = 0;  
   
     run_obj   = 0;//new GL_RUN();  
     soft_obj   = 0;// Emiliano  
     irun = -1LL;  
     runfirstentry = 0LL;  
     runlastentry = 0LL;  
   
     l0_file = NULL;  
     l0_tree = NULL;  
     iroot   = -1;  
     dbc     = 0;  
525    
526      prevshift = 0;    h0_obj = 0;
527          trk0_obj = 0;
528      run_tree = NULL;    calo0_obj = 0;
529      run_tree_clone = NULL;  
530      sel_tree = NULL;    trk2_obj = 0;
531      sel_tree_clone = NULL;    trk1_obj = 0;
532          trkh_obj = 0;
533      irunentry = -1LL;    calo1_obj = 0;
534      pam_tree = NULL;    calo2_obj = 0;
535      for(Int_t i=0; i<NCLONES; i++ )pam_tree_clone[i]=NULL;    tof2_obj = 0;
536      trig_obj = 0;
537      host = "mysql://localhost/pamelaprod";    s4_obj = 0;
538      user = "anonymous";    nd_obj = 0;
539      psw = "";    ac_obj = 0;
540      const char *pamdbhost=gSystem->Getenv("PAM_DBHOST");    orb2_obj = 0;
541      const char *pamdbuser=gSystem->Getenv("PAM_DBUSER");    gp_obj = 0;
542      const char *pamdbpsw=gSystem->Getenv("PAM_DBPSW");  
543      if ( !pamdbhost ) pamdbhost = "";    extAlgFlag=0;
544      if ( !pamdbuser ) pamdbuser = "";  
545      if ( !pamdbpsw ) pamdbpsw = "";    trk_ext_obj     = 0;
546      if ( strcmp(pamdbhost,"") ) host = pamdbhost;    trk_ext_nuc_obj = 0;
547      if ( strcmp(pamdbuser,"") ) user = pamdbuser;    trk_nuc_obj     = 0;
548      if ( strcmp(pamdbpsw,"") ) psw = pamdbpsw;    
549      calo_ext_obj     = 0;
550      calo_ext_nuc_obj = 0;
551      calo_nuc_obj     = 0;
552      
553      tof_ext_obj     = 0;
554      tof_ext_nuc_obj = 0;
555      tof_nuc_obj     = 0;
556      
557      orb_ext_obj     = 0;
558      orb_ext_nuc_obj = 0;
559      orb_nuc_obj     = 0;
560    
561      trk2_nuc_obj  = 0;
562      calo2_nuc_obj = 0;
563      tof2_nuc_obj  = 0;
564      orb2_nuc_obj  = 0;
565    
566    
567      run_obj = 0;//new GL_RUN();
568      soft_obj = 0;// Emiliano
569      proc_obj = 0;// Emiliano
570      irun = -1LL;
571      irunt = -1LL;
572      totrunentry = 0LL;
573      totrunentrymax = 0LL;
574      totrunentrymin = 0LL;
575      runfirstentry = 0LL;
576      runlastentry = 0LL;
577      gltsync = 0; // Emiliano
578      fUpdateRunInfo = true; // Emiliano
579      fUseDBinRunInfo = true; // Emiliano
580      fDiscarded = false; //EM
581      isSync = false; // by default assume that the level2 file(s) is(are) not sinchronized between L0/DB and L2, that is we miss some packets in L2 due to nested/DV-skipped events
582      il0entry = 0LL;
583      //  hasL0EE = true;
584    
585          l0_file = NULL;
586      l0_tree = NULL;
587      iroot = -1;
588      dbc = 0;
589    
590      prevshift = 0;
591      yprevshift = 0;
592      maxshift = 10; //EMILIANO now overridden by SetMaxShift(-1) called by constructors
593    
594  //    sorted_tracks = 0;//new TRefArray();    run_tree = NULL;
595          run_tree_clone = NULL;
     CAL0 = false;  
     CAL1 = true;  
     CAL2 = true;  
     TRK2 = true;  
     TRK1 = false;  
     TRKh = false;  
     TRKh = false;  
     TRG  = true;  
     TOF  = true;  
     TOF0 = false;  
     S4   = true;  
     ND   = true;  
     AC   = true;  
     ORB  = true;  
       
     RUN  = true;  
596    
597      SELLI = -1;    proc_tree = NULL;
598      proc_tree_clone = NULL;
599    
600      tsorted=0;    sel_tree = NULL;
601      timage=0;    sel_tree_clone = NULL;
       
     howtosort = "+CAL+TOF";  
     //howtosort = "+TOF";  
     sortthr = 100.;  
602    
603  };    irunentry = -1LL;
604      pam_tree = NULL;
605      for (Int_t i = 0; i < NCLONES; i++)
606        pam_tree_clone[i] = NULL;
607    
608      totdltime[0] = 0LL;
609      totdltime[1] = 0LL;
610      totdltime[2] = 0LL;
611    
612      host = "mysql://localhost/pamelaprod";
613      user = "anonymous";
614      psw = "";
615      const char *pamdbhost = gSystem->Getenv("PAM_DBHOST");
616      const char *pamdbuser = gSystem->Getenv("PAM_DBUSER");
617      const char *pamdbpsw = gSystem->Getenv("PAM_DBPSW");
618      if (!pamdbhost)
619        pamdbhost = "";
620      if (!pamdbuser)
621        pamdbuser = "";
622      if (!pamdbpsw)
623        pamdbpsw = "";
624      if (strcmp(pamdbhost, ""))
625        host = pamdbhost;
626      if (strcmp(pamdbuser, ""))
627        user = pamdbuser;
628      if (strcmp(pamdbpsw, ""))
629        psw = pamdbpsw;
630    
631      //    sorted_tracks = 0;//new TRefArray();
632    
633      CAL0 = false;
634      CAL1 = true;
635      CAL2 = true;
636      TRK2 = true;
637      TRK1 = false;
638      TRK0 = false;
639      TRKh = false;
640      TRG = true;
641      TOF = true;
642      TOF0 = false;
643      S4 = true;
644      ND = true;
645      AC = true;
646      ORB = true;
647      PROC = true;
648      GP = false;
649    
650      EXT = false;
651      NUC = false;
652      trkAlg = "STD";//default tracking algorythm
653    
654      RUN = true;
655    
656      SELLI = -1;
657    
658      ISGP = false;
659    
660      DBG = false;
661    
662      tsorted = 0;
663      timage = 0;
664      text = 0 ;
665    
666      tsorted_nuc = 0;
667      timage_nuc = 0;
668      text_nuc = 0 ;
669    
670      howtosort = "+CAL+TOF";
671      //howtosort = "+TOF";
672      sortthr = 100.;
673    
674      issorted = false;
675      lastsorted = -1;
676      issorted_new = false;
677      lastsorted_new = -1;
678    
679    }
680    ;
681  /**  /**
682   * Delete the event (act as Dtor)   * Delete the event (act as Dtor)
683   */   */
684  void PamLevel2::Delete(){  void PamLevel2::Delete() {
685            
686      if(run_obj)delete run_obj;    if (run_obj)
687      if(soft_obj)delete soft_obj; //Emiliano      delete run_obj;
688      if (soft_obj)
689        delete soft_obj; //Emiliano
690      if (proc_obj)
691        delete proc_obj; //Emiliano
692    
693      //    cout << "void PamLevel2::Clear()"<<endl;
694      if (h0_obj)
695        delete h0_obj;
696      if (trk0_obj)
697        delete trk0_obj;
698      if (calo0_obj)
699        delete calo0_obj;
700      if (trk1_obj)
701        delete trk1_obj;
702      if (trk2_obj)
703        delete trk2_obj;
704      if (trkh_obj)
705        delete trkh_obj;
706      if (calo1_obj)
707        delete calo1_obj;
708      if (calo2_obj)
709        delete calo2_obj;
710      if (tof2_obj)
711        delete tof2_obj;
712      if (trig_obj)
713        delete trig_obj;
714      if (s4_obj)
715        delete s4_obj;
716      if (nd_obj)
717        delete nd_obj;
718      if (ac_obj)
719        delete ac_obj;
720      if (orb2_obj)
721        delete orb2_obj;
722      if (gp_obj)
723        delete gp_obj;
724    
725      if(trk_nuc_obj)trk_nuc_obj->Delete();
726      if(trk_ext_obj)trk_ext_obj->Delete();
727      if(trk_ext_nuc_obj)trk_ext_nuc_obj->Delete();
728    
729      if(calo_nuc_obj)calo_nuc_obj->Delete();
730      if(calo_ext_obj)calo_ext_obj->Delete();
731      if(calo_ext_nuc_obj)calo_ext_nuc_obj->Delete();
732    
733      if(tof_nuc_obj)tof_nuc_obj->Delete();
734      if(tof_ext_obj)tof_ext_obj->Delete();
735      if(tof_ext_nuc_obj)tof_ext_nuc_obj->Delete();
736    
737      if(orb_nuc_obj)orb_nuc_obj->Delete();
738      if(orb_ext_obj)orb_ext_obj->Delete();
739      if(orb_ext_nuc_obj)orb_ext_nuc_obj->Delete();
740    
741    
742      if(trk2_nuc_obj)trk2_nuc_obj->Delete();;
743      if( calo2_nuc_obj)calo2_nuc_obj->Delete();;
744      if(tof2_nuc_obj)tof2_nuc_obj->Delete();;
745      if(orb2_nuc_obj)orb2_nuc_obj->Delete();;
746      
747    
748    
749      if (tsorted) {
750        tsorted->Delete();
751        delete tsorted;
752      }
753      if (timage) {
754        timage->Delete();
755        delete timage;
756      }
757      if (text) {
758        text->Delete();
759        delete text;
760      }
761      if (tsorted_nuc) {
762        tsorted_nuc->Delete();
763        delete tsorted_nuc;
764      }
765      if (timage_nuc) {
766        timage_nuc->Delete();
767        delete timage_nuc;
768      }
769      if (text_nuc) {
770        text_nuc->Delete();
771        delete text_nuc;
772      }
773    
 //    cout << "void PamLevel2::Clear()"<<endl;  
     if(h0_obj)   delete h0_obj;  
     if(trk0_obj) delete trk0_obj;        
     if(calo0_obj) delete calo0_obj;      
     if(trk1_obj) delete trk1_obj;        
     if(trk2_obj) delete trk2_obj;  
     if(trkh_obj) delete trkh_obj;  
     if(calo1_obj)delete calo1_obj;  
     if(calo2_obj)delete calo2_obj;  
     if(tof_obj)  delete tof_obj;  
     if(trig_obj) delete trig_obj;  
     if(s4_obj)   delete s4_obj;  
     if(nd_obj)   delete nd_obj;  
     if(ac_obj)   delete ac_obj;  
     if(orb_obj)  delete orb_obj;  
       
     if(tsorted){  
         tsorted->Delete();  
         delete tsorted;  
     }  
     if(timage){  
         timage->Delete();  
         delete timage;  
     }  
774    
     if(dbc){  
         dbc->Close();  
         delete dbc;  
     }  
       
     if(l0_file)l0_file->Close();  
     //    if(pam_tree)pam_tree->Delete();;  
775    
776    if ( pam_tree ){    if (dbc) {
777        dbc->Close();
778        delete dbc;
779        dbc=0;
780      }
781    
782      if (gltsync)
783        delete gltsync;
784    
785      if (l0_file)
786        l0_file->Close();
787      //    if(pam_tree)pam_tree->Delete();;
788    
789      if (pam_tree) {
790      //      //
791      // we have first to find which chains we have to delete, then delete the main chain and only after delete the friend chains. Any other order causes a segfault...      // we have first to find which chains we have to delete, then delete the main chain and only after delete the friend chains. Any other order causes a segfault...
792      //      //
793      TList *temp = pam_tree->GetListOfFriends();      TList *temp = pam_tree->GetListOfFriends();
794      TList *contents  = new TList; // create chain friend list      TList *contents = new TList; // create chain friend list
795      contents->SetOwner();      contents->SetOwner();
796      TIter next(temp);      TIter next(temp);
797      TChain *questo = 0;      TChain *questo = 0;
798      while ( (questo = (TChain*) next()) ){      while ((questo = (TChain*) next())) {
799        TString name =  questo->GetName();        TString name = questo->GetName();
800        contents->Add((TChain*)gROOT->FindObject(name.Data()));// add object to the list        contents->Add((TChain*) gROOT->FindObject(name.Data()));// add object to the list
801      };      };
802      //      //
803      // deleting the main chain      // deleting the main chain
# Line 269  void PamLevel2::Delete(){ Line 808  void PamLevel2::Delete(){
808      //      //
809      TIter next2(contents);      TIter next2(contents);
810      TChain *questa = 0;      TChain *questa = 0;
811      while ( questa = (TChain*)next2() ){      while ( (questa = (TChain*)next2()) ) {
812        TString name =  questa->GetName();        TString name = questa->GetName();
813        questa->Delete();              questa->Delete();
814        questa=NULL;        questa = NULL;
815      };      };
816      //      //
817    };    };
818    pam_tree = NULL;    pam_tree = NULL;
819    
820      if(run_tree)run_tree->Delete();;    if (run_tree)
821      if(sel_tree)sel_tree->Delete();;      run_tree->Delete();;
822      for(Int_t i=0; i<NCLONES; i++ )if(pam_tree_clone[i])pam_tree_clone[i]->Delete();;    if (sel_tree)
823      if(run_tree_clone)run_tree_clone->Delete();;      sel_tree->Delete();;
824      if(sel_tree_clone)sel_tree_clone->Delete();;  
825          // The following lines are commented out since they may generate a double delete error
826      // if the file containing the clone trees is closed. This is because the file owns the
827      // clone trees which are written into it, so it will delete them when it is closed; if
828      // also PamLevel2 will try to delete these trees, a double delete error will be generated
829      // when exiting from analysis program. (Nicola 28/11/2011)
830    
831      /*for (Int_t i = 0; i < NCLONES; i++)
832        if (pam_tree_clone[i])
833          pam_tree_clone[i]->Delete();;
834      if (run_tree_clone)
835        run_tree_clone->Delete();;
836      if (sel_tree_clone)
837        sel_tree_clone->Delete();;*/
838    
839  };    if (irunoffset)
840        delete[] irunoffset;
841    
842    
843      Initialize();
844    
845    }
846    ;
847    
848  /**  /**
849   * Clear the event (NB! does not deallocate objects)   * Clear the event (NB! does not deallocate objects)
850   */   */
851  void PamLevel2::Clear(){  void PamLevel2::Clear() {
           
 //    cout << "void PamLevel2::Clear()"<<endl;  
852    
853  //    //    cout << "void PamLevel2::Clear()"<<endl;
 // This method is called once for every entry but RunInfo and SoftInfo do not change until the next run so we cannot clear them here unless we don't  
 // want to load them for each event even if they are the same...  
 //  
 //    if(run_obj)delete run_obj;  
 //    if(run_obj) run_obj->Clear();  // Emiliano: Do not deallocate run_obj here, it will give segmentation fault! call clear instead  
 //    if(soft_obj) soft_obj->Clear();  
   
     if(h0_obj)   h0_obj->Clear();        
 //    if(trk0_obj) trk0_obj->Clear();    
     if(trk1_obj) trk1_obj->Clear();      
     if(trk2_obj) trk2_obj->Clear();  
     if(trkh_obj) trkh_obj->Clear();  
     if(calo0_obj) calo0_obj->Clear();    
     if(calo1_obj)calo1_obj->Clear();  
     if(calo2_obj)calo2_obj->Clear();  
     if(tof_obj)  tof_obj->Clear();  
     if(trig_obj) trig_obj->Clear();  
     if(s4_obj)   s4_obj->Clear();  
     if(nd_obj)   nd_obj->Clear();  
     if(ac_obj)   ac_obj->Clear();  
     if(orb_obj)  orb_obj->Clear();  
       
 //    if(sorted_tracks)sorted_tracks->Clear();  
 //    sorted_tracks.Clear();  
854    
855      if(tsorted){    //
856          tsorted->Delete();    // This method is called once for every entry but RunInfo and SoftInfo do not change until the next run so we cannot clear them here unless we don't
857      }    // want to load them for each event even if they are the same...
858      if(timage){    //
859          timage->Delete();    //    if(run_obj)delete run_obj;
860      }    //    if(run_obj) run_obj->Clear();  // Emiliano: Do not deallocate run_obj here, it will give segmentation fault! call clear instead
861  };    //    if(soft_obj) soft_obj->Clear();
862    
863      if (h0_obj)
864        h0_obj->Clear();
865      //    if(trk0_obj) trk0_obj->Clear();
866      if (trk1_obj)
867        trk1_obj->Clear();
868      if (trk2_obj)
869        trk2_obj->Clear();
870      if (trkh_obj)
871        trkh_obj->Clear();
872      if (calo0_obj)
873        calo0_obj->Clear();
874      if (calo1_obj)
875        calo1_obj->Clear();
876      if (calo2_obj)
877        calo2_obj->Clear();
878      if (tof2_obj)
879        tof2_obj->Clear();
880      if (trig_obj)
881        trig_obj->Clear();
882      if (s4_obj)
883        s4_obj->Clear();
884      if (nd_obj)
885        nd_obj->Clear();
886      if (ac_obj)
887        ac_obj->Clear();
888      if (orb2_obj)
889        orb2_obj->Clear();
890      if (gp_obj)
891        gp_obj->Clear();
892      if (proc_obj)
893        proc_obj->Clear();
894    
895      //    if(sorted_tracks)sorted_tracks->Clear();
896      //    sorted_tracks.Clear();
897    
898      if(trk_nuc_obj)trk_nuc_obj->Clear();
899      if(trk_ext_obj)trk_ext_obj->Clear();
900      if(trk_ext_nuc_obj)trk_ext_nuc_obj->Clear();
901    
902      if(calo_nuc_obj)calo_nuc_obj->Clear();
903      if(calo_ext_obj)calo_ext_obj->Clear();
904      if(calo_ext_nuc_obj)calo_ext_nuc_obj->Clear();
905    
906      if(tof_nuc_obj)tof_nuc_obj->Clear();
907      if(tof_ext_obj)tof_ext_obj->Clear();
908      if(tof_ext_nuc_obj)tof_ext_nuc_obj->Clear();
909    
910      if(orb_nuc_obj)orb_nuc_obj->Clear();
911      if(orb_ext_obj)orb_ext_obj->Clear();
912      if(orb_ext_nuc_obj)orb_ext_nuc_obj->Clear();
913    
914      if(trk2_nuc_obj)trk2_nuc_obj->Clear();;
915      if( calo2_nuc_obj)calo2_nuc_obj->Clear();;
916      if(tof2_nuc_obj)tof2_nuc_obj->Clear();;
917      if(orb2_nuc_obj)orb2_nuc_obj->Clear();;
918    
919      if (tsorted)tsorted->Delete();
920      if (timage)timage->Delete();
921      if (text) text->Delete();
922    
923      if (tsorted_nuc)tsorted_nuc->Delete();
924      if (timage_nuc)timage_nuc->Delete();
925      if (text_nuc) text_nuc->Delete();
926    }
927    ;
928    
929  void PamLevel2::Reset(){  void PamLevel2::Reset() {
930    //    //
931    // First of all clear everything    // First of all clear everything
932    //    //
933    Clear();    Clear();
934    //    //
935    // close and reset chains and pointers    // close and reset chains and pointers
936    //        //
937    if ( pam_tree ){    if (pam_tree) {
938      //      //
939      // we have first to find which chains we have to delete, then delete the main chain and only after delete the friend chains. Any other order causes a segfault...      // we have first to find which chains we have to delete, then delete the main chain and only after delete the friend chains. Any other order causes a segfault...
940      //      //
941      TList *temp = pam_tree->GetListOfFriends();      TList *temp = pam_tree->GetListOfFriends();
942      TList *contents  = new TList; // create chain friend list      TList *contents = new TList; // create chain friend list
943      contents->SetOwner();      contents->SetOwner();
944      TIter next(temp);      TIter next(temp);
945      TChain *questo = 0;      TChain *questo = 0;
946      while ( (questo = (TChain*) next()) ){      while ((questo = (TChain*) next())) {
947        TString name =  questo->GetName();        TString name = questo->GetName();
948        contents->Add((TChain*)gROOT->FindObject(name.Data()));// add object to the list        contents->Add((TChain*) gROOT->FindObject(name.Data()));// add object to the list
949      };      };
950      //      //
951      // deleting the main chain      // deleting the main chain
# Line 358  void PamLevel2::Reset(){ Line 956  void PamLevel2::Reset(){
956      //      //
957      TIter next2(contents);      TIter next2(contents);
958      TChain *questa = 0;      TChain *questa = 0;
959      while ( questa = (TChain*)next2() ){      while ( (questa = (TChain*) next2()) ) {
960        TString name =  questa->GetName();        TString name = questa->GetName();
961        questa->Delete();              questa->Delete();
962        questa=NULL;        questa = NULL;
963      };      };
964      //      //
965    };    };
966    pam_tree = NULL;    pam_tree = NULL;
967    //    //
968    if(run_tree)run_tree->Delete();;    if (run_tree)
969        run_tree->Delete();;
970    run_tree = NULL;    run_tree = NULL;
971    if(sel_tree)sel_tree->Delete();;    if (sel_tree)
972        sel_tree->Delete();;
973    sel_tree = NULL;    sel_tree = NULL;
974    //    //
975    // Close file    // Close file
976    //    //
977    if(l0_file)l0_file->Close("R");    if (l0_file)
978        l0_file->Close("R");
979    l0_file = NULL;    l0_file = NULL;
980    //    //
981    h0_obj    = 0;    h0_obj = 0;
982    trk0_obj  = 0;    trk0_obj = 0;
983    calo0_obj  = 0;    calo0_obj = 0;
984    //    //
985    trk2_obj  = 0;    trk2_obj = 0;
986    trk1_obj  = 0;    trk1_obj = 0;
987    trkh_obj  = 0;    trkh_obj = 0;
988    calo1_obj = 0;    calo1_obj = 0;
989    calo2_obj = 0;    calo2_obj = 0;
990    tof_obj   = 0;    tof2_obj = 0;
991    trig_obj  = 0;    trig_obj = 0;
992    s4_obj    = 0;    s4_obj = 0;
993    nd_obj    = 0;    nd_obj = 0;
994    ac_obj    = 0;    ac_obj = 0;
995    orb_obj   = 0;    orb2_obj = 0;
996      gp_obj = 0;
997      proc_obj = 0;
998    
999      trk_ext_obj     = 0;
1000      trk_ext_nuc_obj = 0;
1001      trk_nuc_obj     = 0;
1002      
1003      calo_ext_obj     = 0;
1004      calo_ext_nuc_obj = 0;
1005      calo_nuc_obj     = 0;
1006      
1007      tof_ext_obj     = 0;
1008      tof_ext_nuc_obj = 0;
1009      tof_nuc_obj     = 0;
1010      
1011      orb_ext_obj     = 0;
1012      orb_ext_nuc_obj = 0;
1013      orb_nuc_obj     = 0;
1014    
1015      trk2_nuc_obj  = 0;
1016      calo2_nuc_obj = 0;
1017      tof2_nuc_obj  = 0;
1018      orb2_nuc_obj  = 0;
1019    
1020      trk2_nuc_obj  = 0;
1021      calo2_nuc_obj = 0;
1022      tof2_nuc_obj  = 0;
1023      orb2_nuc_obj  = 0;
1024    //    //
1025    // Reset run pointers    // Reset run pointers
1026    //    //
1027    run_obj   = 0;//new GL_RUN();    run_obj = 0;//new GL_RUN();
1028    soft_obj   = 0;// Emiliano    soft_obj = 0;// Emiliano
1029      proc_obj = 0;// Emiliano
1030    irun = -1;    irun = -1;
1031      irunt = -1;
1032      totrunentry = 0LL;
1033      totrunentrymax = 0LL;
1034      totrunentrymin = 0LL;
1035    runfirstentry = 0ULL;    runfirstentry = 0ULL;
1036    runlastentry = 0ULL;        runlastentry = 0ULL;
1037      prevabstime = 0ULL;
1038      prevpktnum = 0;
1039      abstime = 0ULL;
1040      pktnum = 0;
1041      isFragment = false;
1042    //    //
1043  };    totdltime[0] = 0LL;
1044      totdltime[1] = 0LL;
1045      totdltime[2] = 0LL;
1046      //
1047    }
1048    ;
1049    
1050  Bool_t PamLevel2::IsGood(){  Bool_t PamLevel2::IsGood(Bool_t strict) {
1051    Bool_t goodev=true;    Bool_t goodev = true;
1052    //  if(trk2_obj && trk2_obj->UnpackError() != 0 ) goodev = false;    //
1053    if(calo2_obj && calo2_obj->good != 1) goodev = false;    if (calo2_obj && !calo2_obj->IsGood(strict))
1054    if(tof_obj && tof_obj->unpackError != 0) goodev = false;        goodev = false;
1055    if(trig_obj && trig_obj->unpackError != 0) goodev = false;    //
1056    if(s4_obj && s4_obj->unpackError != 0) goodev = false;      if (strict) {
1057    if(nd_obj && nd_obj->unpackError != 0) goodev = false;        if (trk2_obj && trk2_obj->UnpackError() != 0)
1058    if(ac_obj && ac_obj->unpackError != 255) goodev = false;          goodev = false;
1059      //  if(orb_obj)        if (tof2_obj && tof2_obj->unpackError != 0)
1060    return goodev;        goodev = false;
1061  };      if (trig_obj && trig_obj->unpackError != 0)
1062          goodev = false;
1063        if (s4_obj && s4_obj->unpackError != 0)
1064          goodev = false;
1065        if (nd_obj && nd_obj->unpackError != 0)
1066          goodev = false;
1067        if (ac_obj && (ac_obj->unpackError != 0 || ((ac_obj->status[0] >> 2) & 1) || ((ac_obj->status[1] >> 2) & 1)))
1068          goodev = false;
1069        //  if(orb2_obj)
1070      }
1071      else {
1072        if (nd_obj && nd_obj->unpackError != 0)
1073          goodev = false;
1074        if (ac_obj && (ac_obj->unpackError != 0 || ((ac_obj->status[0] >> 2) & 1) || ((ac_obj->status[1] >> 2) & 1)))
1075          goodev = false;
1076      };
1077      return (goodev);
1078    }
1079    ;
1080    
1081    void PamLevel2::SkipRunInfoUpdate(){
1082      printf("\n\n ******** WARNING ******** \n Skip DB connections, DO NOT USE PamLevel2::GetRunInfo() method! \n\n");
1083      fUpdateRunInfo = false;
1084      this->SetSELLI(2);
1085      printf(" ===============> W A R N I N G <================ \n");
1086      printf(" in case PamLevel2::CreateCloneTrees() will be called \n");
1087      printf(" it will be reverted to PadmeAmidala level2 structure , i.e. NO SELECTIONLIST WILL BE CREATED IN THE NEW LEVEL2 FILE! \n\n");
1088      if ( run_tree_clone ){
1089        printf(" ===============> W A R N I N G <================ \n");
1090        printf(" PamLevel2::SkipRunIndoUpdate or PamLevel2::NoDBconnections() has been called together with PamLevel2::CreateCloneTrees() \n");
1091        printf(" TO AVOID CRASHES call PamLevel2::CreateCloneTrees() after PamLevel2::SkipRunIndoUpdate or PamLevel2::NoDBconnections() \n");    
1092      };
1093    }
1094    
1095    void PamLevel2::SetMaxShift(Int_t sh){
1096      if ( sh >=  0 ){
1097        printf("PamLevel2::SetMaxShift(Int_t) --WARNING-- the default is optimized by checking the level2 file\n it is strongly suggested to let PamLevel2 choose the max shift!\n");
1098        maxshift = sh;
1099      } else {
1100        ULong64_t nev = GetEntries();
1101        ULong64_t runnev = 0ULL;
1102        for (Int_t r=0; r< run_tree->GetEntries();r++){
1103          run_tree->GetEntry(r);//update runinfo
1104          runnev += GetRunInfo()->NEVENTS;
1105        }
1106        maxshift = (Int_t)(runnev-nev) + 10; // +10 just to be conservative
1107        if ( (runnev-nev) == 0 ) isSync = true;
1108        if (DBG) printf("PamLevel2::SetMaxShift(Int_t_) - sh negative %i - nev is %lld runnnev is %lld so maxshift set to %i \n",sh,nev,runnev,maxshift);
1109        //    printf("PamLevel2::SetMaxShift(Int_t_) - sh negative %i - nev is %lld runnnev is %lld so maxshift set to %i \n",sh,nev,runnev,maxshift); // TOGLITOGLI
1110      }
1111    }
1112    
1113  //--------------------------------------  //--------------------------------------
1114  //  //
1115  //  //
1116  //--------------------------------------  //--------------------------------------
1117  void *PamLevel2::GetPointerTo(const char* c ){  void *PamLevel2::GetPointerTo(const char* c) {
1118    
1119      TString objname = c;    TString objname = c;
1120    
1121      if(!objname.CompareTo("TrkLevel1"))  {    if (!objname.CompareTo("TrkLevel1")) {
1122          if(!trk1_obj){      if (!trk1_obj) {
1123              trk1_obj  = new TrkLevel1();        trk1_obj = new TrkLevel1();
1124              trk1_obj->Set();        trk1_obj->Set();
1125          }      }
1126          return &trk1_obj;      return &trk1_obj;
1127      };    };
1128      if(!objname.CompareTo("TrkLevel2"))  {    if (!objname.CompareTo("TrkLevel2")) {
1129          if(!trk2_obj){        if (!trk2_obj) {
1130              trk2_obj  = new TrkLevel2();        trk2_obj = new TrkLevel2();
1131              trk2_obj->Set();        trk2_obj->Set();
1132          }      }
1133          return &trk2_obj;      return &trk2_obj;
1134      };    };
1135      if(!objname.CompareTo("TrkHough"))   {    if (!objname.CompareTo("TrkHough")) {
1136          if(!trkh_obj)  trkh_obj  = new TrkHough();      if (!trkh_obj) {
1137          return &trkh_obj;        trkh_obj = new TrkHough();
1138      };        trkh_obj->Set();
1139      if(!objname.CompareTo("CaloLevel1")) {      }
1140          if(!calo1_obj) calo1_obj = new CaloLevel1();      return &trkh_obj;
1141          return &calo1_obj;    };
1142      };    if (!objname.CompareTo("CaloLevel1")) {
1143      if(!objname.CompareTo("CaloLevel2")) {      if (!calo1_obj)
1144          if(!calo2_obj){        calo1_obj = new CaloLevel1();
1145              calo2_obj = new CaloLevel2();      return &calo1_obj;
1146              calo2_obj->Set();    };
1147          };    if (!objname.CompareTo("CaloLevel2")) {
1148          return &calo2_obj;      if (!calo2_obj) {
1149      };        calo2_obj = new CaloLevel2();
1150      if(!objname.CompareTo("ToFLevel2"))  {        calo2_obj->Set();
         if(!tof_obj){  
             tof_obj   = new ToFLevel2();  
             tof_obj->Set();  
         }  
         return &tof_obj;  
     };  
     if(!objname.CompareTo("TrigLevel2")) {  
         if(!trig_obj)  trig_obj  = new TrigLevel2();  
         return &trig_obj;  
     };  
     if(!objname.CompareTo("S4Level2"))   {  
         if(!s4_obj)    s4_obj    = new S4Level2();  
         return &s4_obj;  
     };  
     if(!objname.CompareTo("NDLevel2"))   {  
         if(!nd_obj)    nd_obj    = new NDLevel2();  
         return &nd_obj;  
     };  
     if(!objname.CompareTo("AcLevel2"))   {  
         if(!ac_obj)    ac_obj    = new AcLevel2();  
         return &ac_obj;  
     };  
     if(!objname.CompareTo("OrbitalInfo")){  
         if(!orb_obj)   orb_obj   = new OrbitalInfo();  
         return &orb_obj;  
1151      };      };
1152            return &calo2_obj;
1153      if(!objname.CompareTo("RunInfo"))return &run_obj;    };
1154      if (!objname.CompareTo("ToFLevel2")) {
1155        if (!tof2_obj) {
1156          tof2_obj = new ToFLevel2();
1157          tof2_obj->Set();
1158        }
1159        return &tof2_obj;
1160      };
1161      if (!objname.CompareTo("TrigLevel2")) {
1162        if (!trig_obj)
1163          trig_obj = new TrigLevel2();
1164        return &trig_obj;
1165      };
1166      if (!objname.CompareTo("S4Level2")) {
1167        if (!s4_obj)
1168          s4_obj = new S4Level2();
1169        return &s4_obj;
1170      };
1171      if (!objname.CompareTo("NDLevel2")) {
1172        if (!nd_obj)
1173          nd_obj = new NDLevel2();
1174        return &nd_obj;
1175      };
1176      if (!objname.CompareTo("AcLevel2")) {
1177        if (!ac_obj)
1178          ac_obj = new AcLevel2();
1179        return &ac_obj;
1180      };
1181      if (!objname.CompareTo("OrbitalInfo")) {
1182        if (!orb2_obj) {
1183          orb2_obj = new OrbitalInfo();
1184          orb2_obj->Set();
1185        }
1186        return &orb2_obj;
1187      };
1188      //     if(!objname.CompareTo("OrbitalInfo")){
1189      //    if(!orb2_obj)   orb2_obj   = new OrbitalInfo();
1190      //    return &orb2_obj;
1191      //     };
1192      if (!objname.CompareTo("GPamela")) {
1193        if (!gp_obj)
1194          gp_obj = new GPamela();
1195        return &gp_obj;
1196      };
1197    
1198      if(!objname.CompareTo("SoftInfo"))return &soft_obj; // Emiliano    if (!objname.CompareTo("RunInfo"))
1199        return &run_obj;
1200    
1201      return NULL;    if (!objname.CompareTo("SoftInfo"))
1202  };      return &soft_obj; // Emiliano
1203    
1204      if (!objname.CompareTo("ProcInfo")){
1205        if (!proc_obj)
1206          proc_obj = new ProcInfo();    
1207        return &proc_obj; // Emiliano
1208      }
1209    
1210      return NULL;
1211    }
1212    ;
1213  //--------------------------------------  //--------------------------------------
1214  //  //
1215  //  //
1216  //--------------------------------------  //--------------------------------------
1217  /**  /**
1218   * Retrieves the calorimeter track matching the seqno-th tracker stored track.   * Retrieves the calorimeter track matching the seqno-th tracker stored track.
1219   * (If seqno = -1 retrieves the self-trigger calorimeter track)   * (If seqno = -1 retrieves the self-trigger calorimeter track)
1220   */   */
1221   CaloTrkVar *PamLevel2::GetCaloStoredTrack(int seqno){  CaloTrkVar *PamLevel2::GetCaloStoredTrack(int seqno) {
       
      if( !calo2_obj )return 0;  
1222    
1223       if( calo2_obj->CaloLevel2::ntrk()==0 ){    if (!calo2_obj)
1224           cout << "PamLevel2::GetCaloStoredTrack(int) : requested tracker SeqNo "<< seqno <<" but no Calorimeter tracks are stored"<<endl;      return 0;
1225           return NULL;  
1226       };    if (calo2_obj->CaloLevel2::ntrk() == 0) {
1227            cout << "PamLevel2::GetCaloStoredTrack(int) : requested tracker SeqNo " << seqno
1228       CaloTrkVar *c = 0;          << " but no Calorimeter tracks are stored" << endl;
1229       Int_t it_calo=0;      return NULL;
1230          };
1231       do{  
1232           c = calo2_obj->CaloLevel2::GetCaloTrkVar(it_calo);    CaloTrkVar *c = 0;
1233           it_calo++;    Int_t it_calo = 0;
1234       } while( c && seqno != c->trkseqno && it_calo < calo2_obj->CaloLevel2::ntrk());      
1235          do {
1236       if(!c || seqno != c->trkseqno){      c = calo2_obj->CaloLevel2::GetCaloTrkVar(it_calo);
1237           c = 0;      it_calo++;
1238           if(seqno!=-1)cout << "PamLevel2::GetCaloStoredTrack(int) : requested tracker SeqNo "<< seqno <<" does not match Calorimeter stored tracks"<<endl;    } while (c && seqno != c->trkseqno && it_calo < calo2_obj->CaloLevel2::ntrk());
1239       };  
1240       return c;    if (!c || seqno != c->trkseqno) {
1241            c = 0;
1242   };      if (seqno != -1)
1243          cout << "PamLevel2::GetCaloStoredTrack(int) : requested tracker SeqNo " << seqno
1244              << " does not match Calorimeter stored tracks" << endl;
1245      };
1246      return c;
1247    
1248    }
1249    ;
1250  //--------------------------------------  //--------------------------------------
1251   //  //
1252   //  //
1253  //--------------------------------------  //--------------------------------------
1254  /**  /**
1255    * Retrieves the ToF track matching the seqno-th tracker stored track.   * Retrieves the ToF track matching the seqno-th tracker stored track.
1256    * (If seqno = -1 retrieves the tracker-independent tof track)   * (If seqno = -1 retrieves the tracker-independent tof track)
1257   */   */
1258   ToFTrkVar *PamLevel2::GetToFStoredTrack(int seqno){  ToFTrkVar *PamLevel2::GetToFStoredTrack(int seqno) {
           
      if( !tof_obj )return 0;  
1259    
1260       if( tof_obj->ToFLevel2::ntrk()==0 ){    if (!tof2_obj)
1261           cout << "PamLevel2::GetToFStoredTrack(int) : requested tracker SeqNo "<< seqno <<" but no ToF tracks are stored"<<endl;      return 0;
1262           return NULL;  
1263       };    if (tof2_obj->ToFLevel2::ntrk() == 0) {
1264            cout << "PamLevel2::GetToFStoredTrack(int) : requested tracker SeqNo " << seqno << " but no ToF tracks are stored"
1265       ToFTrkVar *c = 0;          << endl;
1266       Int_t it_tof=0;      return NULL;
1267          };
1268       do{  
1269           c = tof_obj->ToFLevel2::GetToFTrkVar(it_tof);    ToFTrkVar *c = 0;
1270           it_tof++;    Int_t it_tof = 0;
1271       } while( c && seqno != c->trkseqno && it_tof < tof_obj->ToFLevel2::ntrk());          
1272          do {
1273       if(!c || seqno != c->trkseqno){      c = tof2_obj->ToFLevel2::GetToFTrkVar(it_tof);
1274           c = 0;      it_tof++;
1275           if(seqno!=-1)cout << "PamLevel2::GetToFStoredTrack(int) : requested tracker SeqNo "<< seqno <<" does not match ToF stored tracks"<<endl;    } while (c && seqno != c->trkseqno && it_tof < tof2_obj->ToFLevel2::ntrk());
1276       };  
1277       return c;    if (!c || seqno != c->trkseqno) {
1278            c = 0;
1279   };      if (seqno != -1)
1280          cout << "PamLevel2::GetToFStoredTrack(int) : requested tracker SeqNo " << seqno
1281              << " does not match ToF stored tracks" << endl;
1282      };
1283      return c;
1284    
1285    }
1286    ;
1287    
1288  //--------------------------------------  //--------------------------------------
1289   //  //
1290   //  //
1291  //--------------------------------------  //--------------------------------------
1292  /**  /**
1293   * Give the pamela track associated to a tracker track, retrieving related calorimeter and tof track information.   * Retrieves the OrbitalInfo track matching the seqno-th tracker stored track.
1294     * (If seqno = -1 retrieves the tracker-independent tof related track)
1295   */   */
1296   PamTrack* PamLevel2::GetPamTrackAlong(TrkTrack* t){  OrbitalInfoTrkVar *PamLevel2::GetOrbitalInfoStoredTrack(int seqno) {
1297        
1298       cout <<"PamLevel2::GetPamTrackAlong(TrkTrack* t) **obsolete** "<<endl;    if (!orb2_obj)
1299       cout <<"(if you use it, remember to delete the PamTrack object)"<<endl;      return 0;
1300    
1301      if (orb2_obj->OrbitalInfo::ntrk() == 0) {
1302        //       // TRICK BEGIN
1303        //       OrbitalInfoTrkVar  *r = new OrbitalInfoTrkVar(); // TEMPORARY TRICK
1304        //       Int_t nn = 0;
1305        //       TClonesArray &tor = *orb2_obj->OrbitalInfoTrk;
1306        //       for(Int_t nt=0; nt < tof2_obj->ToFLevel2::ntrk(); nt++){
1307        //  //
1308        //  ToFTrkVar *ptt = tof2_obj->ToFLevel2::GetToFTrkVar(nt);
1309        //  if ( ptt->trkseqno != -1  ){
1310        //    //
1311        //    r->trkseqno = ptt->trkseqno;
1312        //    //
1313        //    r->Eij = 0;
1314        //    //
1315        //    r->Sij = 0;
1316        //    //
1317        //    r->pitch = -1000.;
1318        //    //
1319        //    r->cutoff = -1000.;
1320        //    //
1321        //    new(tor[nn]) OrbitalInfoTrkVar(*r);
1322        //    nn++;
1323        //    //
1324        //    r->Clear();
1325        //    //
1326        //  };
1327        //       };
1328        //       delete r;
1329        //       OrbitalInfoTrkVar *c = 0;
1330        //       c = orb2_obj->OrbitalInfo::GetOrbitalInfoTrkVar(0);
1331        //       return c;
1332        //       //TRICK END
1333        cout << "PamLevel2::GetOrbitalInfoStoredTrack(int) : requested tracker SeqNo " << seqno
1334            << " but no OrbitalInfo tracks are stored" << endl;
1335        return NULL;
1336      };
1337    
1338      OrbitalInfoTrkVar *c = 0;
1339      Int_t it_tof = 0;
1340    
1341      do {
1342        c = orb2_obj->OrbitalInfo::GetOrbitalInfoTrkVar(it_tof);
1343        it_tof++;
1344      } while (c && seqno != c->trkseqno && it_tof < orb2_obj->OrbitalInfo::ntrk());
1345    
1346      if (!c || seqno != c->trkseqno) {
1347        c = 0;
1348        if (seqno != -1)
1349          cout << "PamLevel2::GetOrbitalInfoStoredTrack(int) : requested tracker SeqNo " << seqno
1350              << " does not match OrbitalInfo stored tracks" << endl;
1351      };
1352      return c;
1353    
1354    }
1355    ;
1356    
      CaloTrkVar *c = 0;  
      ToFTrkVar  *o = 0;  
       
      if(CAL2) c = GetCaloStoredTrack(t->GetSeqNo());  
      if(TOF) o = GetToFStoredTrack(t->GetSeqNo());  
       
 //    if(t && c && o)track = new PamTrack(t,c,o);  
      PamTrack *track = new PamTrack(t,c,o);  
       
      return track;  
   
  };  
1357  //--------------------------------------  //--------------------------------------
1358  //  //
1359  //  //
1360  //--------------------------------------  //--------------------------------------
1361  /**  /**
1362   * Retrieves the it-th stored track.   * Give the pamela track associated to a tracker track, retrieving related calorimeter, orbitalinfo and tof track information.
  * It override TrkLevel2::GetTrack(int it).  
  * @param itrk Track number, ranging from 0 to GetNTracks().  
1363   */   */
1364    PamTrack* PamLevel2::GetPamTrackAlong(TrkTrack* t) {
1365    
1366  PamTrack* PamLevel2::GetStoredTrack(Int_t itrk){    cout << "PamLevel2::GetPamTrackAlong(TrkTrack* t) **obsolete** " << endl;
1367          cout << "(if you use it, remember to delete the PamTrack object)" << endl;
1368      cout <<"PamLevel2::GetStoredTrack(Int_t itrk) **to-be-updated** "<<endl;  
1369      cout <<"for the moment, better use separately the methods: TrkLevel2::GetStoredTrack(seqno) CaloLevel2::GetCaloTrkVar(Int_t notrack) ToFLevel2::GetToFTrkVar(Int_t notrack)"<<endl;    CaloTrkVar *c = 0;
1370      cout <<"(if you use it, remember to delete the PamTrack object)"<<endl;    ToFTrkVar *o = 0;
1371      PamTrack *track = 0;    OrbitalInfoTrkVar *r = 0;
1372        
1373      if( itrk >=0 && itrk < trk2_obj->TrkLevel2::ntrk() ){    if (CAL2)
1374                c = GetCaloStoredTrack(t->GetSeqNo());
1375          TrkTrack *t = trk2_obj->TrkLevel2::GetStoredTrack(itrk);    if (TOF)
1376          track = GetPamTrackAlong(t);      o = GetToFStoredTrack(t->GetSeqNo());
1377              if (ORB)
1378                r = GetOrbitalInfoStoredTrack(t->GetSeqNo());
1379    
1380      //    if(t && c && o)track = new PamTrack(t,c,o);
1381      PamTrack *track = new PamTrack(t, c, o, r);
1382    
1383      return track;
1384    
     }else{  
         cout << "PamLevel2::GetStoredTrack(int) : tracker track SeqNo "<< itrk <<" does not exist (GetNTracks() = "<<trk2_obj->TrkLevel2::GetNTracks()<<")"<<endl;  
     };  
       
     return track;  
       
1385  }  }
1386    ;
1387  //--------------------------------------  //--------------------------------------
1388  //  //
   
 /**  
  * Sort physical (tracker) tracks and stores them in the TRefArray (of TrkTrack objects) which pointer is  PamLevel2::sorted_tracks. Left here as backward compatibility method.  
  **/  
 void PamLevel2::SortTracks(TString how){  
   printf(" WARNING! obsolete, use SortTracks() and SetSortingMethod(TString) instead! \n Setting sorting method to %s \n",how.Data());  
   howtosort = how;    
   SortTracks();  
 };  
   
1389  //  //
1390  //--------------------------------------  //--------------------------------------
1391  /**  /**
1392   * Sort physical (tracker) tracks and stores them in the TRefArray (of TrkTrack objects) which pointer is  PamLevel2::sorted_tracks.   * Retrieves the it-th stored track.
1393   * @param how String to set the sorting cryterium (es: "CAL" or "TRK+CAL+TOF" ecc...).   * It override TrkLevel2::GetTrack(int it).
1394   * Sorting cryteria:   * @param itrk Track number, ranging from 0 to GetNTracks().
  * TRK: lower chi**2  
  * CAL: lower Y spatial residual on the first calorimeter plane  
  * TOF: bigger numebr of hit PMTs along the track, on S12 S21 S32 (where paddles are along the Y axis).  
  * The default sorting cryterium is "TOF+CAL".  
  *  
  * The total number of physical tracks is always given by GetNTracks() and the it-th physical track can be retrieved by means of the methods GetTrack(int it) and GetTrack(int it, TString how).  
1395   */   */
 void PamLevel2::SortTracks(){  
   TString how = howtosort;  
1396    
1397    //    cout <<" PamLevel2::SortTracks(TString how) "<<endl;  PamTrack* PamLevel2::GetStoredTrack(Int_t itrk) {
1398    if( !trk2_obj ){  
1399      cout << "void PamLevel2::SortTracks():  TrkLevel2 not loaded !!!";    cout << "PamLevel2::GetStoredTrack(Int_t itrk) **to-be-updated** " << endl;
1400      cout
1401          << "for the moment, better use separately the methods: TrkLevel2::GetStoredTrack(seqno) CaloLevel2::GetCaloTrkVar(Int_t notrack) ToFLevel2::GetToFTrkVar(Int_t notrack) OrbitalInfo::GetOrbitalInfoTrkVar(Int_t notrack)"
1402          << endl;
1403      cout << "(if you use it, remember to delete the PamTrack object)" << endl;
1404      PamTrack *track = 0;
1405    
1406      if (itrk >= 0 && itrk < trk2_obj->TrkLevel2::ntrk()) {
1407    
1408        TrkTrack *t = trk2_obj->TrkLevel2::GetStoredTrack(itrk);
1409        track = GetPamTrackAlong(t);
1410    
1411      }
1412      else {
1413        cout << "PamLevel2::GetStoredTrack(int) : tracker track SeqNo " << itrk << " does not exist (GetNTracks() = "
1414            << trk2_obj->TrkLevel2::GetNTracks() << ")" << endl;
1415      };
1416    
1417      return track;
1418    
1419    }
1420    //--------------------------------------
1421    //
1422    
1423    /**
1424     * Sort physical (tracker) tracks. Left here as backward compatibility method.
1425     **/
1426    void PamLevel2::SortTracks(TString how) {
1427      printf(
1428          " WARNING! obsolete, use SortTracks() and SetSortingMethod(TString) instead! \n Setting sorting method to %s \n",
1429          how.Data());
1430      howtosort = how;
1431      SortTracks();
1432    }
1433    ;
1434    
1435    //
1436    //--------------------------------------
1437    /**
1438     * Sort physical (tracker) tracks.
1439     * @param how String to set the sorting cryterium (es: "CAL" or "TRK+CAL+TOF" ecc...).
1440     * Sorting cryteria:
1441     * TRK: lower chi**2
1442     * CAL: lower Y spatial residual on the first calorimeter plane
1443     * TOF: bigger numebr of hit PMTs along the track, on S12 S21 S32 (where paddles are along the Y axis).
1444     * S1: (ask Emiliano)
1445     * S2: (ask Emiliano)
1446     * S3: (ask Emiliano)
1447     * GP: more GP hits
1448     * The default sorting cryterium is "TOF+CAL".
1449     *
1450     * The total number of physical tracks is always given by GetNTracks() and the it-th physical track can be retrieved by means of the methods GetTrack(int it) and GetTrack(int it, TString how).
1451     */
1452    void PamLevel2::SortTracks() {
1453    
1454      //Check if the current event has already been sorted
1455      if (issorted && lastsorted == GetReadEntry()) {
1456        return;
1457      }
1458      //Reset the sort flags, just in case something will go wrong...
1459      issorted = false;
1460      lastsorted = -1;
1461    
1462      TString how = howtosort;
1463    
1464      //  cout <<" PamLevel2::SortTracks(TString how) "<<endl;
1465      if (!trk2_obj) {
1466        cout << "void PamLevel2::SortTracks():  TrkLevel2 not loaded !!!";
1467      return;      return;
1468    };    };
   //    cout << "call SortTracs() "<<endl;  
1469    //Save current Object count    //Save current Object count
1470    Int_t ObjectNumber = TProcessID::GetObjectCount();    Int_t ObjectNumber = TProcessID::GetObjectCount();
1471    
1472    //    cout << "ObjectNumber  "<<ObjectNumber <<endl;    // create TCloneArrays to store tracks and its images
1473      if (!tsorted)
1474    //     if(!sorted_tracks)sorted_tracks = new TRefArray();      tsorted = new TClonesArray("PamTrack", trk2_obj->GetNTracks());
1475    //     sorted_tracks->Clear();    tsorted->Clear("C+C");//Delete();
   //    sorted_tracks.Clear();  
   
   if(!tsorted)tsorted = new TClonesArray("PamTrack",trk2_obj->GetNTracks());  
   tsorted->Delete();  
1476    TClonesArray &ttsorted = *tsorted;    TClonesArray &ttsorted = *tsorted;
1477    if(!timage)timage = new TClonesArray("PamTrack",trk2_obj->GetNTracks());  
1478    timage->Delete();    if (!timage)
1479        timage = new TClonesArray("PamTrack", trk2_obj->GetNTracks());
1480      timage->Clear("C+C");//Delete();
1481    TClonesArray &ttimage = *timage;    TClonesArray &ttimage = *timage;
1482    
1483    
1484    // loop over the tracks sorted by the tracker  
1485      //--------------------------------------------------
1486      // retrieve sorting method
1487      //--------------------------------------------------
1488    Bool_t use_TRK = how.Contains("TRK", TString::kIgnoreCase);    Bool_t use_TRK = how.Contains("TRK", TString::kIgnoreCase);
1489    Bool_t use_CAL = how.Contains("CAL", TString::kIgnoreCase);    Bool_t use_CAL = how.Contains("CAL", TString::kIgnoreCase);
1490    Bool_t use_TOF = how.Contains("TOF", TString::kIgnoreCase);    Bool_t use_TOF = how.Contains("TOF", TString::kIgnoreCase);
1491          Bool_t use_S1 = how.Contains("S1", TString::kIgnoreCase);
1492    if( !CAL2 &&  use_CAL) use_CAL = false;    Bool_t use_S2 = how.Contains("S2", TString::kIgnoreCase);
1493    if( !TOF &&  use_TOF) use_TOF = false;    Bool_t use_S3 = how.Contains("S3", TString::kIgnoreCase);
1494          Bool_t use_GP = how.Contains("GP", TString::kIgnoreCase);
1495    if( !TRK2 ){  
1496      //  cout << "SortTracks() : without tracker does not work!!! (not yet)" << endl;    if (use_TOF) {
1497        use_S1 = true;
1498        use_S2 = true;
1499        use_S3 = true;
1500      };
1501      if (!CAL2 && use_CAL)
1502        use_CAL = false;
1503      if (!TOF) {
1504        use_TOF = false;
1505        use_S1 = false;
1506        use_S2 = false;
1507        use_S3 = false;
1508      }
1509      if (!GP) {
1510        use_GP = false;
1511      }
1512    
1513      if (!TRK2) {
1514        cout << "SortTracks() : without tracker does not work!!! (not yet)" << endl;
1515      return;      return;
1516    };    };
1517    
1518    //   cout << "use_CAL "<<use_CAL<<" use_TOF "<<use_TOF<<" use_TRK "<<use_TRK <<endl;    //   cout << "use_CAL "<<use_CAL<<" use_TOF "<<use_TOF<<" use_TRK "<<use_TRK <<endl;
1519        
1520    for(Int_t i=0; i < trk2_obj->TrkLevel2::GetNTracks(); i++){  
1521              //--------------------------------------------------
1522      TrkTrack   *ts = 0;    // loop over "physical" tracks sorted by the tracker
1523      //--------------------------------------------------
1524      for (Int_t i = 0; i < trk2_obj->TrkLevel2::GetNTracks(); i++) {
1525    
1526        TrkTrack *ts = 0;
1527      CaloTrkVar *cs = 0;      CaloTrkVar *cs = 0;
1528      ToFTrkVar  *os = 0;      ToFTrkVar *os = 0;
1529                OrbitalInfoTrkVar *rs = 0;
1530    
1531      // get tracker tracks      // get tracker tracks
1532      TrkTrack   *tp = trk2_obj->TrkLevel2::GetTrack(i);                    //tracker      TrkTrack *tp = trk2_obj->TrkLevel2::GetTrack(i); //tracker
1533      CaloTrkVar *cp = GetCaloStoredTrack(tp->GetSeqNo());      CaloTrkVar *cp = GetCaloStoredTrack(tp->GetSeqNo());
1534      ToFTrkVar  *op = GetToFStoredTrack(tp->GetSeqNo());      ToFTrkVar *op = GetToFStoredTrack(tp->GetSeqNo());
1535        OrbitalInfoTrkVar *rp = GetOrbitalInfoStoredTrack(tp->GetSeqNo());
1536    
1537      TrkTrack   *ti = 0;              //tracker (image)      TrkTrack *ti = 0; //tracker (image)
1538      CaloTrkVar *ci = 0;      CaloTrkVar *ci = 0;
1539      ToFTrkVar  *oi = 0;      ToFTrkVar *oi = 0;
1540        OrbitalInfoTrkVar *ri = 0;
1541      //  cout << "trk track n. "<<i << " "<<hex<< tp <<dec<< endl;      //  cout << "trk track n. "<<i << " "<<hex<< tp <<dec<< endl;
1542      // if track has an image, check image selection      // if track has an image, check image selection
1543      if(tp->HasImage()){  
1544                    Int_t tp_score = 0; //main track sorted by the tracker
1545        ti = trk2_obj->TrkLevel2::GetTrackImage(i);              //tracker (image)      Int_t ti_score = 0; //image track
1546        Int_t totp_score = 0; //main track sorted by the tracker
1547        Int_t toti_score = 0; //image track
1548    
1549        if (tp->HasImage()) {
1550    
1551          ti = trk2_obj->TrkLevel2::GetTrackImage(i); //tracker (image)
1552        ci = GetCaloStoredTrack(ti->GetSeqNo());        ci = GetCaloStoredTrack(ti->GetSeqNo());
1553        oi = GetToFStoredTrack(ti->GetSeqNo());        oi = GetToFStoredTrack(ti->GetSeqNo());
1554                      ri = GetOrbitalInfoStoredTrack(ti->GetSeqNo());
1555    
1556        //            cout << "its image "<<i << " "<<hex<< ti <<dec<< endl;        //            cout << "its image "<<i << " "<<hex<< ti <<dec<< endl;
1557    
1558        //assign starting scores        //assign starting scores
1559        Int_t tp_score = 0;  //main track sorted by the tracker        tp_score = 0; //main track sorted by the tracker
1560        Int_t ti_score = 0;  //image track        ti_score = 0; //image track
1561                
1562        // ------------------------        // -----------------------------------------------------------------------------------------
1563          // *****************************************************************************************
1564          // -----------------------------------------------------------------------------------------
1565        // calorimeter check        // calorimeter check
1566        // ------------------------        // -----------------------------------------------------------------------------------------
1567        // check the Y spatial residual on the first calorimeter plane        if (use_CAL && !calo2_obj) {
1568        // (cut on calorimeter variables from Emiliano)          cout << "void PamLevel2::SortTracks(): howtosort= " << how << " but CaloLevel2 not loaded !!!";
1569        if( use_CAL && !calo2_obj ){          return;
1570          cout << "void PamLevel2::SortTracks(): howtosort= "<<how<<" but CaloLevel2 not loaded !!!";        };
1571          return;        if (use_CAL && !cp && ci) {
1572            ti_score++;
1573            toti_score++;
1574          };
1575          if (use_CAL && cp && !ci) {
1576            tp_score++;
1577            totp_score++;
1578        };        };
1579        if(        if (use_CAL && cp && ci && true) {
          use_CAL            &&  
          calo2_obj->npcfit[1] > 5     &&   //no. of fit planes on Y view  
          calo2_obj->varcfit[1] < 1000. &&  //fit variance on Y view  
          cp && ci &&  
          true){  
1580    
1581                            if (cp->npresh > ci->npresh && true) {
1582          Float_t resy_p = cp->tbar[0][1] - calo2_obj->cbar[0][1]; if(resy_p < 0)resy_p= - resy_p;            tp_score++;
1583          Float_t resy_i = ci->tbar[0][1] - calo2_obj->cbar[0][1]; if(resy_i < 0)resy_i= - resy_i;            totp_score++;
1584                            };
1585          if(resy_p <= resy_i) tp_score++;          if (cp->npresh < ci->npresh && true) {
1586          else                 ti_score++;            ti_score++;
1587                      toti_score++;
1588          //      cout << "CALO "<<tp_score<<ti_score<<endl;          };
1589    
1590            //      cout << "CALO "<<tp_score<<ti_score<<endl;
1591    
1592        };        };
1593        // ------------------------        // -----------------------------------------------------------------------------------------
1594          // *****************************************************************************************
1595          // -----------------------------------------------------------------------------------------
1596        // TOF check        // TOF check
1597        // ------------------------                  // -----------------------------------------------------------------------------------------
1598        // check the number of hit pmts along the track        // check the number of hit pmts along the track
1599        // on S12 S21 and S32, where paddles are parallel to Y axis        // on S12 S21 and S32, where paddles are parallel to Y axis
1600        if( use_TOF && !tof_obj ){        if ((use_TOF || use_S1 || use_S2 || use_S3) && !tof2_obj) {
1601          cout << "void PamLevel2::SortTracks(): howtosort= "<<how<<" but ToFLevel2 not loaded !!!";          cout << "void PamLevel2::SortTracks(): howtosort= " << how << " but ToFLevel2 not loaded !!!";
1602          return;          return;
1603          };
1604          //
1605          if ((use_TOF || use_S1 || use_S2 || use_S3) && !op && oi) {
1606            ti_score++;
1607            toti_score++;
1608          };
1609          if ((use_TOF || use_S1 || use_S2 || use_S3) && op && !oi) {
1610            tp_score++;
1611            totp_score++;
1612          };
1613          if ((use_TOF || use_S1 || use_S2 || use_S3) && op && oi) {
1614            //
1615            Float_t sen = 0.;
1616            for (Int_t ih = 0; ih < op->npmtadc; ih++) {
1617              Int_t pl = tof2_obj->GetPlaneIndex((op->pmtadc).At(ih));
1618              if (pl == 2 || pl == 3 || pl == 4 || pl == 5)
1619                sen += (op->dedx).At(ih);
1620            };
1621            for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
1622              Int_t pl = tof2_obj->GetPlaneIndex((oi->pmtadc).At(ih));
1623              if (pl == 2 || pl == 3 || pl == 4 || pl == 5)
1624                sen += (oi->dedx).At(ih);
1625            };
1626            //
1627            if (sen >= sortthr && false) { // temporary disabled NUCLEI special algorithm since the new one should work for every particle (to be checked!)
1628              //printf(" IS A NUCLEUS! en = %f \n",sen);
1629              //
1630              // is a nucleus use a different algorithm
1631              //
1632              Int_t nz = 6;
1633              Float_t zin[6]; // << define TOF z-coordinates
1634              for (Int_t ip = 0; ip < nz; ip++)
1635                zin[ip] = tof2_obj->ToFLevel2::GetZTOF(tof2_obj->ToFLevel2::GetToFPlaneID(ip)); // << read ToF plane z-coordinates
1636              Trajectory *tr = new Trajectory(nz, zin);
1637              //
1638              Int_t nphit_p = 0;
1639              Int_t nphit_i = 0;
1640              Float_t enhit_p = 0.;
1641              Float_t enhit_i = 0.;
1642              //
1643              for (Int_t ih = 0; ih < op->npmtadc; ih++) {
1644                Int_t pl = tof2_obj->GetPlaneIndex((op->pmtadc).At(ih));
1645                if (pl == 1 || pl == 2 || pl == 5) {
1646                  nphit_p++;
1647                  enhit_p += (op->dedx).At(ih);
1648                };
1649              };
1650              //
1651              tp->DoTrack2(tr);
1652              //
1653              if (fabs(tr->y[0] - oi->ytofpos[0]) < 2.) {
1654                for (Int_t ih = 0; ih < op->npmtadc; ih++) {
1655                  Int_t pl = tof2_obj->GetPlaneIndex((op->pmtadc).At(ih));
1656                  if (pl == 0) {
1657                    nphit_p++;
1658                    enhit_p += (op->dedx).At(ih);
1659                  };
1660                };
1661              };
1662              if (fabs(tr->y[3] - oi->ytofpos[1]) < 2.) {
1663                for (Int_t ih = 0; ih < op->npmtadc; ih++) {
1664                  Int_t pl = tof2_obj->GetPlaneIndex((op->pmtadc).At(ih));
1665                  if (pl == 3) {
1666                    nphit_p++;
1667                    enhit_p += (op->dedx).At(ih);
1668                  };
1669                };
1670              };
1671              if (fabs(tr->y[4] - oi->ytofpos[2]) < 2.) {
1672                for (Int_t ih = 0; ih < op->npmtadc; ih++) {
1673                  Int_t pl = tof2_obj->GetPlaneIndex((op->pmtadc).At(ih));
1674                  if (pl == 4) {
1675                    nphit_p++;
1676                    enhit_p += (op->dedx).At(ih);
1677                  };
1678                };
1679              };
1680    
1681              for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
1682                Int_t pl = tof2_obj->GetPlaneIndex((oi->pmtadc).At(ih));
1683                if (pl == 1 || pl == 2 || pl == 5) {
1684                  nphit_i++;
1685                  enhit_i += (op->dedx).At(ih);
1686                };
1687              };
1688              //
1689              ti->DoTrack2(tr);
1690              //
1691              if (fabs(tr->y[0] - oi->ytofpos[0]) < 2.) {
1692                for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
1693                  Int_t pl = tof2_obj->GetPlaneIndex((oi->pmtadc).At(ih));
1694                  if (pl == 0) {
1695                    nphit_i++;
1696                    enhit_i += (op->dedx).At(ih);
1697                  };
1698                };
1699              };
1700              if (fabs(tr->y[3] - oi->ytofpos[1]) < 2.) {
1701                for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
1702                  Int_t pl = tof2_obj->GetPlaneIndex((oi->pmtadc).At(ih));
1703                  if (pl == 3) {
1704                    nphit_i++;
1705                    enhit_i += (op->dedx).At(ih);
1706                  };
1707                };
1708              };
1709              if (fabs(tr->y[4] - oi->ytofpos[2]) < 2.) {
1710                for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
1711                  Int_t pl = tof2_obj->GetPlaneIndex((oi->pmtadc).At(ih));
1712                  if (pl == 4) {
1713                    nphit_i++;
1714                    enhit_i += (op->dedx).At(ih);
1715                  };
1716                };
1717              };
1718    
1719              if ((use_TOF || use_S1 || use_S2 || use_S3) && (nphit_p + nphit_i) != 0 && true) {
1720    
1721                //      printf(" seqno %i nphit_p %i nphit_i %i enhit_p %f enhit_i %f \n",trk2_obj->TrkLevel2::GetSeqNo(i),nphit_p,nphit_i,enhit_p,enhit_i);
1722                //      printf(" score p %i score i %i \n",tp_score,ti_score);
1723                //            if( enhit_p > enhit_i ) tp_score++;
1724                //            if( nphit_p >= nphit_i && enhit_p > enhit_i ) tp_score++;
1725                if (nphit_p > nphit_i)
1726                  tp_score++;
1727                if (nphit_p < nphit_i)
1728                  ti_score++;
1729                if (nphit_p == nphit_i) {
1730                  if (enhit_p > enhit_i)
1731                    tp_score++;
1732                  else
1733                    ti_score++;
1734                };
1735                //      printf(" dopo score p %i score i %i \n",tp_score,ti_score);
1736              };
1737              delete tr;
1738              //
1739            }
1740            else {
1741              // -------------
1742              // NOT a NUCLEUS
1743              // -------------
1744              //printf(" NOT a NUCLEUS! en = %f \n",sen);
1745    
1746              Int_t nphit_p = 0;
1747              Int_t nphit_i = 0;
1748    
1749              /*                            cout << "track: npmtadc "<< op->npmtadc << endl;
1750               cout << "track: npmttdc "<< op->npmttdc << endl;
1751               cout << "image: npmtadc "<< oi->npmtadc << endl;
1752               cout << "image: npmttdc "<< oi->npmttdc << endl;*/
1753    
1754              //      for (Int_t ih=0; ih < op->npmtadc; ih++){
1755              //        Int_t pl = tof2_obj->GetPlaneIndex( (op->pmtadc).At(ih) );
1756              //        if(pl == 1 || pl == 2 || pl == 5)nphit_p++;
1757              //      };
1758    
1759              //      for (Int_t ih=0; ih < oi->npmtadc; ih++){
1760              //        Int_t pl = tof2_obj->GetPlaneIndex( (oi->pmtadc).At(ih) );
1761              //        if(pl == 1 || pl == 2 || pl == 5)nphit_i++;
1762              //      };
1763              // --- modified to count tdc signals (more efficient?)
1764              // --- and to implement check on tdcflag
1765              for (Int_t ih = 0; ih < op->npmttdc; ih++) {
1766                Int_t pl = tof2_obj->GetPlaneIndex((op->pmttdc).At(ih));
1767                //      if( (op->tdcflag).At(ih)==0 && (pl == 1 || pl == 2 || pl == 5) )nphit_p++;
1768                if ((use_S1 && (pl == 0 || pl == 1)) || (use_S2 && (pl == 2 || pl == 3))
1769                    || (use_S3 && (pl == 4 || pl == 5))) {
1770                  if ((op->tdcflag).At(ih) == 0)
1771                    nphit_p++;
1772                };
1773              };
1774    
1775              for (Int_t ih = 0; ih < oi->npmttdc; ih++) {
1776                Int_t pl = tof2_obj->GetPlaneIndex((oi->pmttdc).At(ih));
1777                //      if( (oi->tdcflag).At(ih)==0 && (pl == 1 || pl == 2 || pl == 5) )nphit_i++;
1778                if ((use_S1 && (pl == 0 || pl == 1)) || (use_S2 && (pl == 2 || pl == 3))
1779                    || (use_S3 && (pl == 4 || pl == 5))) {
1780                  if ((oi->tdcflag).At(ih) == 0)
1781                    nphit_i++;
1782                };
1783              };
1784    
1785              if ((nphit_p + nphit_i) != 0 && true) {
1786    
1787                if (nphit_p != nphit_i) {
1788                  totp_score += nphit_p;
1789                  toti_score += nphit_i;
1790                  tp_score += nphit_p;
1791                  ti_score += nphit_i;
1792                };
1793                //      if     ( nphit_p > nphit_i) tp_score+=nphit_p;
1794                //      else if( nphit_p < nphit_i) ti_score+=nphit_i;
1795                //      else ;//niente
1796              };
1797            };
1798            //      cout << "TOF "<<tp_score<<ti_score<<endl;
1799        };        };
       if( use_TOF && op && oi ){  
                   
         //  
         Float_t sen = 0.;  
         for (Int_t ih=0; ih < op->npmtadc; ih++){  
           Int_t pl = tof_obj->GetPlaneIndex( (op->pmtadc).At(ih) );  
           if ( pl == 2 || pl == 3 || pl == 4 || pl == 5 ) sen += (op->dedx).At(ih);  
         };  
         for (Int_t ih=0; ih < oi->npmtadc; ih++){  
           Int_t pl = tof_obj->GetPlaneIndex( (oi->pmtadc).At(ih) );  
           if ( pl == 2 || pl == 3 || pl == 4 || pl == 5 ) sen += (oi->dedx).At(ih);  
         };  
         //  
         if (  sen >= sortthr ){  
           //printf(" IS A NUCLEUS! en = %f \n",sen);  
           //  
           // is a nucleus use a different algorithm  
           //  
           Int_t nz = 6; Float_t zin[6];                                          // << define TOF z-coordinates  
           for(Int_t ip=0; ip<nz; ip++)  
             zin[ip] = tof_obj->ToFLevel2::GetZTOF(tof_obj->ToFLevel2::GetToFPlaneID(ip));     // << read ToF plane z-coordinates  
           Trajectory *tr = new Trajectory(nz,zin);  
           //  
           Int_t nphit_p =0;  
           Int_t nphit_i =0;  
           Float_t enhit_p = 0.;  
           Float_t enhit_i = 0.;  
           //  
           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++;  
               enhit_p += (op->dedx).At(ih);  
             };  
           };  
           //  
           tp->DoTrack2(tr);  
           //  
           if ( fabs(tr->y[0]-oi->ytofpos[0]) < 2. ){  
             for (Int_t ih=0; ih < op->npmtadc; ih++){  
               Int_t pl = tof_obj->GetPlaneIndex( (op->pmtadc).At(ih) );  
               if(pl == 0){  
                 nphit_p++;  
                 enhit_p += (op->dedx).At(ih);  
               };  
             };  
           };  
           if ( fabs(tr->y[3]-oi->ytofpos[1]) < 2. ){  
             for (Int_t ih=0; ih < op->npmtadc; ih++){  
               Int_t pl = tof_obj->GetPlaneIndex( (op->pmtadc).At(ih) );  
               if(pl == 3){  
                 nphit_p++;  
                 enhit_p += (op->dedx).At(ih);  
               };  
             };  
           };  
           if ( fabs(tr->y[4]-oi->ytofpos[2]) < 2. ){  
             for (Int_t ih=0; ih < op->npmtadc; ih++){  
               Int_t pl = tof_obj->GetPlaneIndex( (op->pmtadc).At(ih) );  
               if(pl == 4){  
                 nphit_p++;  
                 enhit_p += (op->dedx).At(ih);  
               };  
             };  
           };  
1800    
1801            for (Int_t ih=0; ih < oi->npmtadc; ih++){        //      if(tp_score == ti_score) use_TRK = true;
             Int_t pl = tof_obj->GetPlaneIndex( (oi->pmtadc).At(ih) );  
             if(pl == 1 || pl == 2 || pl == 5){  
               nphit_i++;          
               enhit_i += (op->dedx).At(ih);  
             };  
           };  
           //  
           ti->DoTrack2(tr);  
           //  
           if ( fabs(tr->y[0]-oi->ytofpos[0]) < 2. ){  
             for (Int_t ih=0; ih < oi->npmtadc; ih++){  
               Int_t pl = tof_obj->GetPlaneIndex( (oi->pmtadc).At(ih) );  
               if(pl == 0){  
                 nphit_i++;  
                 enhit_i += (op->dedx).At(ih);  
               };  
             };  
           };  
           if ( fabs(tr->y[3]-oi->ytofpos[1]) < 2. ){  
             for (Int_t ih=0; ih < oi->npmtadc; ih++){  
               Int_t pl = tof_obj->GetPlaneIndex( (oi->pmtadc).At(ih) );  
               if(pl == 3){  
                 nphit_i++;  
                 enhit_i += (op->dedx).At(ih);  
               };  
             };  
           };  
           if ( fabs(tr->y[4]-oi->ytofpos[2]) < 2. ){  
             for (Int_t ih=0; ih < oi->npmtadc; ih++){  
               Int_t pl = tof_obj->GetPlaneIndex( (oi->pmtadc).At(ih) );  
               if(pl == 4){  
                 nphit_i++;  
                 enhit_i += (op->dedx).At(ih);  
               };  
             };  
           };              
1802    
                   
           if(  
              use_TOF            &&  
              (nphit_p+nphit_i) !=0 &&    
              true){  
                       
             //      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);  
             //      printf(" score p %i score i %i \n",tp_score,ti_score);  
             //            if( enhit_p > enhit_i ) tp_score++;  
             //            if( nphit_p >= nphit_i && enhit_p > enhit_i ) tp_score++;  
             if ( nphit_p > nphit_i ) tp_score++;  
             if ( nphit_p < nphit_i ) ti_score++;  
             if ( nphit_p == nphit_i ){  
               if ( enhit_p > enhit_i ) tp_score++;  
               else ti_score++;  
             };  
             //      printf(" dopo score p %i score i %i \n",tp_score,ti_score);  
           };  
           delete tr;  
           //  
         } else {  
           //  
           // NOT a NUCLEUS  
           //  
           //printf(" NOT a NUCLEUS! en = %f \n",sen);  
1803    
1804            Int_t nphit_p =0;        // -----------------------------------------------------------------------------------------
1805            Int_t nphit_i =0;        // *****************************************************************************************
1806                          // -----------------------------------------------------------------------------------------
                   
           /*                            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;  
       // ------------------------  
1807        // tracker check        // tracker check
1808        // ------------------------        // -----------------------------------------------------------------------------------------
1809        // chi**2 difference is not always large enough to distinguish among        // chi**2 difference is not always large enough to distinguish among
1810        // the real track and its image.        // the real track and its image.
1811        // Tracker check will be applied always when calorimeter and tof information is ambiguous.        // Tracker check will be applied always when calorimeter and tof information is ambiguous.
1812        if(use_TRK){        // *** MODIFIED ON AUGUST 2007 ***
1813          if(      tp->chi2 > 0 && tp->chi2 < ti->chi2 ) tp_score++ ;        if (use_TRK) {
1814          else if( ti->chi2 > 0 && ti->chi2 < tp->chi2 ) ti_score++ ;          //      if(      tp->chi2 > 0 && tp->chi2 < ti->chi2 ) tp_score++ ;
1815          //      cout << "TRK "<<tp_score<<ti_score<<endl;          //      else if( ti->chi2 > 0 && ti->chi2 < tp->chi2 ) ti_score++ ;
1816    
1817            // CHECK 1 : number of points along X
1818            if (tp->GetNX() >= ti->GetNX()) {
1819              tp_score++;
1820              totp_score++;
1821            };
1822            if (tp->GetNX() <= ti->GetNX()) {
1823              ti_score++;
1824              toti_score++;
1825            };
1826            // CHECK 2 : number of points along Y
1827            if (tp->GetNY() >= ti->GetNY()) {
1828              tp_score++;
1829              totp_score++;
1830            };
1831            if (tp->GetNY() <= ti->GetNY()) {
1832              ti_score++;
1833              toti_score++;
1834            };
1835    
1836            //      cout << "TRK "<<tp_score<<ti_score<<endl;
1837        };        };
1838                
1839        // ------------------------        // -----------------------------------------------------------------------------------------
1840          // *****************************************************************************************
1841          // -----------------------------------------------------------------------------------------
1842          // GPamela check
1843          // -----------------------------------------------------------------------------------------
1844    
1845          //---------------------------------------------------
1846          // count the number of GP hits
1847          //---------------------------------------------------
1848          if (use_GP) {
1849            int ngphits_p = 0;
1850            int ngphits_i = 0;
1851            float toll = 0.02; //200 micron
1852            for (int ih = 0; ih < GetGPamela()->Nthspe; ih++) {
1853              int ip = (Int_t) GetGPamela()->Itrpb[ih] - 1;
1854              if (tp && tp->YGood(ip) && fabs(tp->ym[ip] - GetGPamela()->Yavspe[ih]) < toll && true)
1855                ngphits_p++;
1856              if (ti && ti->YGood(ip) && fabs(ti->ym[ip] - GetGPamela()->Yavspe[ih]) < toll && true)
1857                ngphits_i++;
1858            }
1859            if (ngphits_p > ngphits_i && true) {
1860              tp_score++;
1861              totp_score++;
1862            }
1863            if (ngphits_p < ngphits_i && true) {
1864              ti_score++;
1865              toti_score++;
1866            }
1867          }
1868    
1869          // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
1870        // the winner is....        // the winner is....
1871        // ------------------------                  // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
1872        if      (tp_score > ti_score) {        if (tp_score > ti_score) {
1873          //              ts = tp;//the track sorted by the tracker!!  
1874          //              cs = cp;        }
1875          //              os = op;        else if (tp_score < ti_score) {
1876          //      cout << "It's primary!" << endl;  
1877            ts = ti;//its image!!
1878        }else if (tp_score < ti_score) {          cs = ci;
1879            os = oi;
1880          //      cout << "It's image!" << endl;          rs = ri;
1881            Int_t totis = toti_score;
1882          ts = ti;//its image!!  
1883          cs = ci;          ti = tp;//its image!!
1884          os = oi;          ci = cp;
1885            oi = op;
1886          ti = tp;//its image!!          ri = rp;
1887          ci = cp;  
1888          oi = op;          tp = ts;//its image!!
1889            cp = cs;
1890          tp = ts;//its image!!          op = os;
1891          cp = cs;          rp = rs;
1892          op = os;  
1893            toti_score = totp_score;
1894            totp_score = totis;
1895    
1896          }
1897          else {
1898    
1899            //      cout << "Warning - track image ambiguity not solved" << endl;
1900    
                   
       }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;  
1901        };        };
1902                
1903      }else{      }
1904        else {
1905          totp_score = 1;
1906          toti_score = 0;
1907    
1908        //            ts = tp;        //            ts = tp;
1909        //            cs = cp;        //            cs = cp;
1910        //            os = op;        //            os = op;
1911      };      };
1912            
1913      //  cout <<" SortTracks() "<<i<<" -- "<<ts<<endl;      //  cout <<" SortTracks() "<<i<<" -- "<<ts<<endl;
1914      //  sorted_tracks->Add(ts);//save the track in the sorted array      //  sorted_tracks->Add(ts);//save the track in the sorted array
1915      //  sorted_tracks.Add(ts);//save the track in the sorted array      //  sorted_tracks.Add(ts);//save the track in the sorted array
# Line 957  void PamLevel2::SortTracks(){ Line 1918  void PamLevel2::SortTracks(){
1918      //  cout<<"o "<<tp<<endl;      //  cout<<"o "<<tp<<endl;
1919      //  cout<<"o "<<cp<<endl;      //  cout<<"o "<<cp<<endl;
1920      //  cout<<"o "<<op<<endl;      //  cout<<"o "<<op<<endl;
1921      new(ttsorted[i]) PamTrack(tp,cp,op);  
1922      new(ttimage[i])  PamTrack(ti,ci,oi);      new (ttsorted[i]) PamTrack(tp, cp, op, rp);
1923        new (ttimage[i]) PamTrack(ti, ci, oi, ri);
1924    
1925        ((PamTrack*) (ttsorted[i]))->SetPScore(totp_score);
1926        ((PamTrack*) (ttsorted[i]))->SetIScore(toti_score);
1927        ((PamTrack*) (ttimage[i]))->SetPScore(totp_score);
1928        ((PamTrack*) (ttimage[i]))->SetIScore(toti_score);
1929    };    };
1930    
1931    if( tsorted->GetEntries() != trk2_obj->GetNTracks() ){    if (tsorted->GetEntries() != trk2_obj->GetNTracks()) {
1932      cout << "void PamLevel2::SortTracks(): tsorted->GetEntries() "<<tsorted->GetEntries()<<" != trk2_obj->GetNTracks() = "<<trk2_obj->GetNTracks() <<endl;      cout << "void PamLevel2::SortTracks(): tsorted->GetEntries() " << tsorted->GetEntries()
1933      tsorted->Delete(); tsorted=0;          << " != trk2_obj->GetNTracks() = " << trk2_obj->GetNTracks() << endl;
1934      timage->Delete(); timage=0;      tsorted->Delete();
1935        tsorted = 0;
1936        timage->Delete();
1937        timage = 0;
1938    }    }
1939    
1940    //Restore Object count    //Restore Object count
1941    //To save space in the table keeping track of all referenced objects    //To save space in the table keeping track of all referenced objects
1942    //We reset the object count to what it was at the beginning of the event.    //We reset the object count to what it was at the beginning of the event.
1943    TProcessID::SetObjectCount(ObjectNumber);    TProcessID::SetObjectCount(ObjectNumber);
1944    
1945      //Everything went fine so the current event can be tagged as sorted
1946      issorted = true;
1947      lastsorted = GetReadEntry();
1948    
1949    }
1950    ;
1951    //
1952    //--------------------------------------
1953    /**
1954     * Sort physical (tracker) tracks.
1955     * @param how String to set the sorting cryterium (es: "CAL" or "TRK+CAL+TOF" ecc...).
1956     * Sorting cryteria:
1957     * TRK: lower chi**2
1958     * CAL: lower Y spatial residual on the first calorimeter plane
1959     * TOF: bigger numebr of hit PMTs along the track, on S12 S21 S32 (where paddles are along the Y axis).
1960     * S1: (ask Emiliano)
1961     * S2: (ask Emiliano)
1962     * S3: (ask Emiliano)
1963     * GP: more GP hits
1964     * The default sorting cryterium is "TOF+CAL".
1965     *
1966     * The total number of physical tracks is always given by GetNTracks() and the it-th physical track can be retrieved by means of the methods GetTrack(int it) and GetTrack(int it, TString how).
1967     *
1968     * New version, with handling of extended tracks and nuclei tracks.
1969     */
1970    void PamLevel2::SortTracksNew() {
1971    
1972      //--------------------------------------------------
1973      //Check if the current event has already been sorted
1974      //--------------------------------------------------
1975      if (issorted_new && lastsorted_new == GetReadEntry()) {
1976          return; //already done for this event
1977      }
1978    
1979    
1980    //  cout << "SORT" << endl;
1981    
1982      //Reset the sort flags, just in case something will go wrong...
1983      issorted_new = false;
1984      lastsorted_new = -1;
1985    
1986      //--------------------------------------------------
1987      // set input variables
1988      //--------------------------------------------------
1989    
1990      TString how = howtosort;
1991      //Save current Object count
1992      Int_t ObjectNumber = TProcessID::GetObjectCount();
1993    
1994    
1995    
1996    
1997      TrkLevel2  * trk2 ;
1998      CaloLevel2 * calo2;
1999      ToFLevel2  * tof2  ;
2000      OrbitalInfo  * orb2 ;
2001      
2002      TClonesArray * trkext ;
2003      TClonesArray * caloext;
2004      TClonesArray * tofext ;
2005      TClonesArray * orbext ;
2006    
2007    
2008    //   cout << "trk2_obj" << trk2_obj<< endl;
2009    //   cout << "trk2_nuc_obj" << trk2_nuc_obj<< endl;
2010    //   cout << " trk_ext_obj "<<trk_ext_obj<< endl;
2011    //   cout << " trk_ext_nuc_obj "<<trk_ext_nuc_obj<< endl;
2012    
2013      //-----------------------------------------------------------
2014      // create/reset TCloneArrays to store tracks and their images
2015      //-----------------------------------------------------------
2016    
2017    //  cout << " PamLevel2::SortTracksNew() --- Clear TClonesArray objects"<<endl;
2018      
2019      // main tracks from standard alg
2020    //   if (!tsorted)
2021    //       tsorted = new TClonesArray("PamTrack", trk2_obj->GetNTracks());
2022    //   tsorted->Clear("C+C");//Delete();
2023    //   // track images from standard alg
2024    //   if (!timage)
2025    //       timage = new TClonesArray("PamTrack", trk2_obj->GetNTracks());
2026    //   timage->Clear("C+C");//Delete();
2027    //   // tracks from extended algorythm
2028    //   if(EXT && !text)
2029    //       text = new TClonesArray("PamTrack",trk_ext_obj->GetEntries());
2030    //   if(text)text->Clear("C+C");//Delete();
2031    
2032      if(tsorted)delete tsorted;
2033      if(timage) delete timage;
2034      if(text)   delete text;
2035      tsorted = new TClonesArray("PamTrack", trk2_obj->GetNTracks());
2036      timage = new TClonesArray("PamTrack", trk2_obj->GetNTracks());
2037      text = new TClonesArray("PamTrack",trk_ext_obj->GetEntries());
2038    
2039      //-----------------------------------------------------------
2040      // create/reset TCloneArrays to store tracks and their images
2041      //-----------------------------------------------------------
2042      if(NUC){
2043    
2044          
2045          if(tsorted_nuc)delete tsorted_nuc;
2046          if(timage_nuc) delete timage_nuc;
2047          if(text_nuc)   delete text_nuc;
2048          tsorted_nuc = new TClonesArray("PamTrack", trk2_nuc_obj->GetNTracks());
2049          timage_nuc = new TClonesArray("PamTrack", trk2_nuc_obj->GetNTracks());
2050          text_nuc = new TClonesArray("PamTrack",trk_ext_nuc_obj->GetEntries());
2051    
2052      // main tracks from standard alg
2053    //       if (!tsorted_nuc)
2054    //        tsorted_nuc = new TClonesArray("PamTrack", trk2_nuc_obj->GetNTracks());
2055    //       tsorted_nuc->Clear("C+C");//Delete();
2056    //       // track images from standard alg
2057    //       if (!timage_nuc)
2058    //        timage_nuc = new TClonesArray("PamTrack", trk2_nuc_obj->GetNTracks());
2059    //       timage_nuc->Clear("C+C");//Delete();
2060    //       // tracks from extended algorythm
2061    //       if(EXT && !text_nuc)
2062    //        text_nuc = new TClonesArray("PamTrack",trk_ext_nuc_obj->GetEntries());
2063    //       if(text_nuc)text_nuc->Clear("C+C");//Delete();
2064    
2065      }
2066      //--------------------------------------------------
2067      // retrieve sorting method
2068      //--------------------------------------------------
2069      Bool_t use_TRK = how.Contains("TRK", TString::kIgnoreCase);
2070      Bool_t use_CAL = how.Contains("CAL", TString::kIgnoreCase);
2071      Bool_t use_TOF = how.Contains("TOF", TString::kIgnoreCase);
2072      Bool_t use_S1 = how.Contains("S1", TString::kIgnoreCase);
2073      Bool_t use_S2 = how.Contains("S2", TString::kIgnoreCase);
2074      Bool_t use_S3 = how.Contains("S3", TString::kIgnoreCase);
2075      Bool_t use_GP = how.Contains("GP", TString::kIgnoreCase);
2076    
2077      if (use_TOF) {
2078        use_S1 = true;
2079        use_S2 = true;
2080        use_S3 = true;
2081      };
2082      if (!CAL2 && use_CAL)
2083        use_CAL = false;
2084      if (!TOF) {
2085        use_TOF = false;
2086        use_S1 = false;
2087        use_S2 = false;
2088        use_S3 = false;
2089      }
2090      if (!GP) {
2091        use_GP = false;
2092      }
2093    
2094      if (!TRK2) {
2095        cout << "SortTracks() : without tracker does not work!!! (not yet)" << endl;
2096        return;
2097      };
2098    
2099    
2100      ///////////////////////////////////////////////////////////////////////////////////
2101      //
2102      //   sort tracks and fill PamTrack arrays
2103      //
2104      ///////////////////////////////////////////////////////////////////////////////////
2105      for(int doit=0; doit<2; doit++){
2106    
2107    //       cout << "doit "<<doit<<endl;
2108    
2109    
2110          if(doit == 0){
2111    
2112              trk2  = trk2_obj;
2113              calo2 = calo2_obj;
2114              tof2  = tof2_obj;
2115              orb2  = orb2_obj;
2116          
2117              trkext = trk_ext_obj;
2118              caloext = calo_ext_obj;
2119              tofext = tof_ext_obj;
2120              orbext = orb_ext_obj;
2121            
2122          
2123          
2124          
2125    
2126          }else if (doit == 1){
2127    
2128              if(!NUC)break;
2129    
2130          
2131              trk2  = trk2_nuc_obj;
2132              calo2 = calo2_nuc_obj;
2133              tof2  = tof2_nuc_obj;
2134              orb2  = orb2_nuc_obj;
2135          
2136              trkext = trk_ext_nuc_obj;
2137              caloext = calo_ext_nuc_obj;
2138              tofext = tof_ext_nuc_obj;
2139              orbext = orb_ext_nuc_obj;
2140          
2141          
2142          
2143    
2144          }
2145    
2146    //       cout << "trk2" << trk2<<endl;
2147    //       cout << "calo2" << calo2<<endl;
2148    //       cout << "tof2" << tof2<<endl;
2149    //       cout << "orb2" << orb2<<endl;
2150    //       cout << "trkext" <<trkext <<endl;
2151    //       cout << "tofext" << tofext<<endl;
2152    //       cout << "caloext" << caloext<<endl;
2153    //       cout << "orbext" << orbext<<endl;
2154    
2155          TClonesArray &ttext    = (doit==0 ? *text : *text_nuc);
2156          TClonesArray &ttimage  = (doit==0 ? *timage : *timage_nuc);
2157          TClonesArray &ttsorted = (doit==0 ? *tsorted : *tsorted_nuc);
2158      
2159    //       cout << "tsorted + timage "<<doit<<endl;
2160    
2161          //--------------------------------------------------
2162          // loop over "physical" tracks sorted by the tracker
2163          //--------------------------------------------------
2164          for (Int_t i = 0; i < trk2->TrkLevel2::GetNTracks(); i++) {
2165    
2166              TrkTrack *ts = 0;
2167              CaloTrkVar *cs = 0;
2168              ToFTrkVar *os = 0;
2169              OrbitalInfoTrkVar *rs = 0;
2170    
2171              // get tracker tracks
2172              TrkTrack *tp = trk2->GetTrack(i); //tracker
2173              CaloTrkVar *cp = calo2->GetCaloStoredTrack(tp->GetSeqNo());
2174              ToFTrkVar *op = tof2->GetToFStoredTrack(tp->GetSeqNo());
2175              OrbitalInfoTrkVar *rp = orb2->GetOrbitalInfoStoredTrack(tp->GetSeqNo());
2176    
2177              TrkTrack *ti = 0; //tracker (image)
2178              CaloTrkVar *ci = 0;
2179              ToFTrkVar *oi = 0;
2180              OrbitalInfoTrkVar *ri = 0;
2181              //    cout << "trk track n. "<<i << " "<<hex<< tp <<dec<< endl;
2182              // if track has an image, check image selection
2183    
2184              Int_t tp_score = 0; //main track sorted by the tracker
2185              Int_t ti_score = 0; //image track
2186              Int_t totp_score = 0; //main track sorted by the tracker
2187              Int_t toti_score = 0; //image track
2188    
2189              if (tp->HasImage()) {
2190    
2191                  ti = trk2->GetTrackImage(i); //tracker (image)
2192                  ci = calo2->GetCaloStoredTrack(ti->GetSeqNo());
2193                  oi = tof2->GetToFStoredTrack(ti->GetSeqNo());
2194                  ri = orb2->GetOrbitalInfoStoredTrack(ti->GetSeqNo());
2195    
2196                  //            cout << "its image "<<i << " "<<hex<< ti <<dec<< endl;
2197    
2198                  //assign starting scores
2199                  tp_score = 0; //main track sorted by the tracker
2200                  ti_score = 0; //image track
2201    
2202                  // -----------------------------------------------------------------------------------------
2203                  // *****************************************************************************************
2204                  // -----------------------------------------------------------------------------------------
2205                  // calorimeter check
2206                  // -----------------------------------------------------------------------------------------
2207                  if (use_CAL && !calo2) {
2208                      cout << "void PamLevel2::SortTracks(): howtosort= " << how << " but CaloLevel2 not loaded !!!";
2209                      return;
2210                  };
2211                  if (use_CAL && !cp && ci) {
2212                      ti_score++;
2213                      toti_score++;
2214                  };
2215                  if (use_CAL && cp && !ci) {
2216                      tp_score++;
2217                      totp_score++;
2218                  };
2219                  if (use_CAL && cp && ci && true) {
2220    
2221                      if (cp->npresh > ci->npresh && true) {
2222                          tp_score++;
2223                          totp_score++;
2224                      };
2225                      if (cp->npresh < ci->npresh && true) {
2226                          ti_score++;
2227                          toti_score++;
2228                      };
2229    
2230                      //    cout << "CALO "<<tp_score<<ti_score<<endl;
2231    
2232                  };
2233                  // -----------------------------------------------------------------------------------------
2234                  // *****************************************************************************************
2235                  // -----------------------------------------------------------------------------------------
2236                  // TOF check
2237                  // -----------------------------------------------------------------------------------------
2238                  // check the number of hit pmts along the track
2239                  // on S12 S21 and S32, where paddles are parallel to Y axis
2240                  if ((use_TOF || use_S1 || use_S2 || use_S3) && !tof2) {
2241                      cout << "void PamLevel2::SortTracks(): howtosort= " << how << " but ToFLevel2 not loaded !!!";
2242                      return;
2243                  };
2244                  //
2245                  if ((use_TOF || use_S1 || use_S2 || use_S3) && !op && oi) {
2246                      ti_score++;
2247                      toti_score++;
2248                  };
2249                  if ((use_TOF || use_S1 || use_S2 || use_S3) && op && !oi) {
2250                      tp_score++;
2251                      totp_score++;
2252                  };
2253                  if ((use_TOF || use_S1 || use_S2 || use_S3) && op && oi) {
2254                      //
2255                      Float_t sen = 0.;
2256                      for (Int_t ih = 0; ih < op->npmtadc; ih++) {
2257                          Int_t pl = tof2->GetPlaneIndex((op->pmtadc).At(ih));
2258                          if (pl == 2 || pl == 3 || pl == 4 || pl == 5)
2259                              sen += (op->dedx).At(ih);
2260                      };
2261                      for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
2262                          Int_t pl = tof2->GetPlaneIndex((oi->pmtadc).At(ih));
2263                          if (pl == 2 || pl == 3 || pl == 4 || pl == 5)
2264                              sen += (oi->dedx).At(ih);
2265                      };
2266                      //
2267                      if (sen >= sortthr && false) { // temporary disabled NUCLEI special algorithm since the new one should work for every particle (to be checked!)
2268                          //printf(" IS A NUCLEUS! en = %f \n",sen);
2269                          //
2270                          // is a nucleus use a different algorithm
2271                          //
2272                          Int_t nz = 6;
2273                          Float_t zin[6]; // << define TOF z-coordinates
2274                          for (Int_t ip = 0; ip < nz; ip++)
2275                              zin[ip] = tof2->GetZTOF(tof2->GetToFPlaneID(ip)); // << read ToF plane z-coordinates
2276                          Trajectory *tr = new Trajectory(nz, zin);
2277                          //
2278                          Int_t nphit_p = 0;
2279                          Int_t nphit_i = 0;
2280                          Float_t enhit_p = 0.;
2281                          Float_t enhit_i = 0.;
2282                          //
2283                          for (Int_t ih = 0; ih < op->npmtadc; ih++) {
2284                              Int_t pl = tof2->GetPlaneIndex((op->pmtadc).At(ih));
2285                              if (pl == 1 || pl == 2 || pl == 5) {
2286                                  nphit_p++;
2287                                  enhit_p += (op->dedx).At(ih);
2288                              };
2289                          };
2290                          //
2291                          tp->DoTrack2(tr);
2292                          //
2293                          if (fabs(tr->y[0] - oi->ytofpos[0]) < 2.) {
2294                              for (Int_t ih = 0; ih < op->npmtadc; ih++) {
2295                                  Int_t pl = tof2->GetPlaneIndex((op->pmtadc).At(ih));
2296                                  if (pl == 0) {
2297                                      nphit_p++;
2298                                      enhit_p += (op->dedx).At(ih);
2299                                  };
2300                              };
2301                          };
2302                          if (fabs(tr->y[3] - oi->ytofpos[1]) < 2.) {
2303                              for (Int_t ih = 0; ih < op->npmtadc; ih++) {
2304                                  Int_t pl = tof2->GetPlaneIndex((op->pmtadc).At(ih));
2305                                  if (pl == 3) {
2306                                      nphit_p++;
2307                                      enhit_p += (op->dedx).At(ih);
2308                                  };
2309                              };
2310                          };
2311                          if (fabs(tr->y[4] - oi->ytofpos[2]) < 2.) {
2312                              for (Int_t ih = 0; ih < op->npmtadc; ih++) {
2313                                  Int_t pl = tof2->GetPlaneIndex((op->pmtadc).At(ih));
2314                                  if (pl == 4) {
2315                                      nphit_p++;
2316                                      enhit_p += (op->dedx).At(ih);
2317                                  };
2318                              };
2319                          };
2320    
2321                          for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
2322                              Int_t pl = tof2->GetPlaneIndex((oi->pmtadc).At(ih));
2323                              if (pl == 1 || pl == 2 || pl == 5) {
2324                                  nphit_i++;
2325                                  enhit_i += (op->dedx).At(ih);
2326                              };
2327                          };
2328                          //
2329                          ti->DoTrack2(tr);
2330                          //
2331                          if (fabs(tr->y[0] - oi->ytofpos[0]) < 2.) {
2332                              for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
2333                                  Int_t pl = tof2->GetPlaneIndex((oi->pmtadc).At(ih));
2334                                  if (pl == 0) {
2335                                      nphit_i++;
2336                                      enhit_i += (op->dedx).At(ih);
2337                                  };
2338                              };
2339                          };
2340                          if (fabs(tr->y[3] - oi->ytofpos[1]) < 2.) {
2341                              for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
2342                                  Int_t pl = tof2->GetPlaneIndex((oi->pmtadc).At(ih));
2343                                  if (pl == 3) {
2344                                      nphit_i++;
2345                                      enhit_i += (op->dedx).At(ih);
2346                                  };
2347                              };
2348                          };
2349                          if (fabs(tr->y[4] - oi->ytofpos[2]) < 2.) {
2350                              for (Int_t ih = 0; ih < oi->npmtadc; ih++) {
2351                                  Int_t pl = tof2->GetPlaneIndex((oi->pmtadc).At(ih));
2352                                  if (pl == 4) {
2353                                      nphit_i++;
2354                                      enhit_i += (op->dedx).At(ih);
2355                                  };
2356                              };
2357                          };
2358    
2359                          if ((use_TOF || use_S1 || use_S2 || use_S3) && (nphit_p + nphit_i) != 0 && true) {
2360    
2361                              //        printf(" seqno %i nphit_p %i nphit_i %i enhit_p %f enhit_i %f \n",trk2_obj->TrkLevel2::GetSeqNo(i),nphit_p,nphit_i,enhit_p,enhit_i);
2362                              //        printf(" score p %i score i %i \n",tp_score,ti_score);
2363                              //              if( enhit_p > enhit_i ) tp_score++;
2364                              //              if( nphit_p >= nphit_i && enhit_p > enhit_i ) tp_score++;
2365                              if (nphit_p > nphit_i)
2366                                  tp_score++;
2367                              if (nphit_p < nphit_i)
2368                                  ti_score++;
2369                              if (nphit_p == nphit_i) {
2370                                  if (enhit_p > enhit_i)
2371                                      tp_score++;
2372                                  else
2373                                      ti_score++;
2374                              };
2375                              //        printf(" dopo score p %i score i %i \n",tp_score,ti_score);
2376                          };
2377                          delete tr;
2378                          //
2379                      }
2380                      else {
2381                          // -------------
2382                          // NOT a NUCLEUS
2383                          // -------------
2384                          //printf(" NOT a NUCLEUS! en = %f \n",sen);
2385    
2386                          Int_t nphit_p = 0;
2387                          Int_t nphit_i = 0;
2388    
2389                          /*                                cout << "track: npmtadc "<< op->npmtadc << endl;
2390                            cout << "track: npmttdc "<< op->npmttdc << endl;
2391                            cout << "image: npmtadc "<< oi->npmtadc << endl;
2392                            cout << "image: npmttdc "<< oi->npmttdc << endl;*/
2393    
2394                          //          for (Int_t ih=0; ih < op->npmtadc; ih++){
2395                          //            Int_t pl = tof2_obj->GetPlaneIndex( (op->pmtadc).At(ih) );
2396                          //            if(pl == 1 || pl == 2 || pl == 5)nphit_p++;
2397                          //          };
2398    
2399                          //          for (Int_t ih=0; ih < oi->npmtadc; ih++){
2400                          //            Int_t pl = tof2_obj->GetPlaneIndex( (oi->pmtadc).At(ih) );
2401                          //            if(pl == 1 || pl == 2 || pl == 5)nphit_i++;
2402                          //          };
2403                          // --- modified to count tdc signals (more efficient?)
2404                          // --- and to implement check on tdcflag
2405                          for (Int_t ih = 0; ih < op->npmttdc; ih++) {
2406                              Int_t pl = tof2->GetPlaneIndex((op->pmttdc).At(ih));
2407                              //        if( (op->tdcflag).At(ih)==0 && (pl == 1 || pl == 2 || pl == 5) )nphit_p++;
2408                              if ((use_S1 && (pl == 0 || pl == 1)) || (use_S2 && (pl == 2 || pl == 3))
2409                                  || (use_S3 && (pl == 4 || pl == 5))) {
2410                                  if ((op->tdcflag).At(ih) == 0)
2411                                      nphit_p++;
2412                              };
2413                          };
2414    
2415                          for (Int_t ih = 0; ih < oi->npmttdc; ih++) {
2416                              Int_t pl = tof2->GetPlaneIndex((oi->pmttdc).At(ih));
2417                              //        if( (oi->tdcflag).At(ih)==0 && (pl == 1 || pl == 2 || pl == 5) )nphit_i++;
2418                              if ((use_S1 && (pl == 0 || pl == 1)) || (use_S2 && (pl == 2 || pl == 3))
2419                                  || (use_S3 && (pl == 4 || pl == 5))) {
2420                                  if ((oi->tdcflag).At(ih) == 0)
2421                                      nphit_i++;
2422                              };
2423                          };
2424    
2425                          if ((nphit_p + nphit_i) != 0 && true) {
2426    
2427                              if (nphit_p != nphit_i) {
2428                                  totp_score += nphit_p;
2429                                  toti_score += nphit_i;
2430                                  tp_score += nphit_p;
2431                                  ti_score += nphit_i;
2432                              };
2433                              //        if     ( nphit_p > nphit_i) tp_score+=nphit_p;
2434                              //        else if( nphit_p < nphit_i) ti_score+=nphit_i;
2435                              //        else ;//niente
2436                          };
2437                      };
2438                      //    cout << "TOF "<<tp_score<<ti_score<<endl;
2439                  };
2440    
2441                  //      if(tp_score == ti_score) use_TRK = true;
2442    
2443    
2444                  // -----------------------------------------------------------------------------------------
2445                  // *****************************************************************************************
2446                  // -----------------------------------------------------------------------------------------
2447                  // tracker check
2448                  // -----------------------------------------------------------------------------------------
2449                  // chi**2 difference is not always large enough to distinguish among
2450                  // the real track and its image.
2451                  // Tracker check will be applied always when calorimeter and tof information is ambiguous.
2452                  // *** MODIFIED ON AUGUST 2007 ***
2453                  if (use_TRK) {
2454                      //    if(      tp->chi2 > 0 && tp->chi2 < ti->chi2 ) tp_score++ ;
2455                      //    else if( ti->chi2 > 0 && ti->chi2 < tp->chi2 ) ti_score++ ;
2456    
2457                      // CHECK 1 : number of points along X
2458                      if (tp->GetNX() >= ti->GetNX()) {
2459                          tp_score++;
2460                          totp_score++;
2461                      };
2462                      if (tp->GetNX() <= ti->GetNX()) {
2463                          ti_score++;
2464                          toti_score++;
2465                      };
2466                      // CHECK 2 : number of points along Y
2467                      if (tp->GetNY() >= ti->GetNY()) {
2468                          tp_score++;
2469                          totp_score++;
2470                      };
2471                      if (tp->GetNY() <= ti->GetNY()) {
2472                          ti_score++;
2473                          toti_score++;
2474                      };
2475    
2476                      //    cout << "TRK "<<tp_score<<ti_score<<endl;
2477                  };
2478    
2479                  // -----------------------------------------------------------------------------------------
2480                  // *****************************************************************************************
2481                  // -----------------------------------------------------------------------------------------
2482                  // GPamela check
2483                  // -----------------------------------------------------------------------------------------
2484    
2485                  //---------------------------------------------------
2486                  // count the number of GP hits
2487                  //---------------------------------------------------
2488                  if (use_GP) {
2489                      int ngphits_p = 0;
2490                      int ngphits_i = 0;
2491                      float toll = 0.02; //200 micron
2492                      for (int ih = 0; ih < GetGPamela()->Nthspe; ih++) {
2493                          int ip = (Int_t) GetGPamela()->Itrpb[ih] - 1;
2494                          if (tp && tp->YGood(ip) && fabs(tp->ym[ip] - GetGPamela()->Yavspe[ih]) < toll && true)
2495                              ngphits_p++;
2496                          if (ti && ti->YGood(ip) && fabs(ti->ym[ip] - GetGPamela()->Yavspe[ih]) < toll && true)
2497                              ngphits_i++;
2498                      }
2499                      if (ngphits_p > ngphits_i && true) {
2500                          tp_score++;
2501                          totp_score++;
2502                      }
2503                      if (ngphits_p < ngphits_i && true) {
2504                          ti_score++;
2505                          toti_score++;
2506                      }
2507                  }
2508    
2509                  // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
2510                  // the winner is....
2511                  // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
2512                  if (tp_score > ti_score) {
2513    
2514                  }
2515                  else if (tp_score < ti_score) {
2516    
2517                      ts = ti;//its image!!
2518                      cs = ci;
2519                      os = oi;
2520                      rs = ri;
2521                      Int_t totis = toti_score;
2522    
2523                      ti = tp;//its image!!
2524                      ci = cp;
2525                      oi = op;
2526                      ri = rp;
2527    
2528                      tp = ts;//its image!!
2529                      cp = cs;
2530                      op = os;
2531                      rp = rs;
2532    
2533                      toti_score = totp_score;
2534                      totp_score = totis;
2535    
2536                  }
2537                  else {
2538    
2539                      //    cout << "Warning - track image ambiguity not solved" << endl;
2540    
2541                  };
2542    
2543              }
2544              else {
2545                  totp_score = 1;
2546                  toti_score = 0;
2547    
2548                  //            ts = tp;
2549                  //            cs = cp;
2550                  //            os = op;
2551              };
2552    
2553              //    cout <<" SortTracks() "<<i<<" -- "<<ts<<endl;
2554              //    sorted_tracks->Add(ts);//save the track in the sorted array
2555              //    sorted_tracks.Add(ts);//save the track in the sorted array
2556              //    sorted_tracks.Add(tp);//save the track in the sorted array
2557              //    cout << "SortTracks:: sorted_tracks->Add(it) "<<i<<" "<<ts<<endl;
2558              //    cout<<"o "<<tp<<endl;
2559              //    cout<<"o "<<cp<<endl;
2560              //    cout<<"o "<<op<<endl;
2561    
2562              new (ttsorted[i]) PamTrack(tp, cp, op, rp);
2563              new (ttimage[i]) PamTrack(ti, ci, oi, ri);
2564    
2565              ((PamTrack*) (ttsorted[i]))->SetPScore(totp_score);
2566              ((PamTrack*) (ttsorted[i]))->SetIScore(toti_score);
2567              ((PamTrack*) (ttimage[i]))->SetPScore(totp_score);
2568              ((PamTrack*) (ttimage[i]))->SetIScore(toti_score);
2569          };
2570    
2571    
2572    
2573    
2574    
2575    //   if (tsorted->GetEntries() != trk2->GetNTracks()) {
2576    //     cout << "void PamLevel2::SortTracks(): tsorted->GetEntries() " << tsorted->GetEntries()
2577    //         << " != trk2->GetNTracks() = " << trk2->GetNTracks() << endl;
2578    //     tsorted->Delete();
2579    //     tsorted = 0;
2580    //     timage->Delete();
2581    //     timage = 0;
2582    //   }
2583    
2584    
2585    //       cout << "text "<<doit<<endl;
2586    
2587    
2588          //--------------------------------------------------
2589          // fill array with extended tracks (this is easy...)
2590          //--------------------------------------------------
2591          if(EXT){
2592              for(int it=0; it<trkext->GetEntries(); it++){
2593                  
2594                  new (ttext[it]) PamTrack((ExtTrack*)(*trkext)[it], (CaloTrkVar*)(*caloext)[it], (ToFTrkVar*)(*tofext)[it], (OrbitalInfoTrkVar*)(*orbext)[it]);
2595                  
2596              }
2597          }
2598          
2599    
2600    
2601      };
2602    
2603    
2604      //Restore Object count
2605      //To save space in the table keeping track of all referenced objects
2606      //We reset the object count to what it was at the beginning of the event.
2607      TProcessID::SetObjectCount(ObjectNumber);
2608    
2609      //Everything went fine so the current event can be tagged as sorted
2610      issorted_new = true;
2611      lastsorted_new = GetReadEntry();
2612    
2613    //   cout << " tsorted "<< tsorted << " "<<(tsorted ? tsorted->GetEntries() : 0)<<endl;
2614    //   cout << " timage  "<< timage  << " "<<(timage  ? timage->GetEntries() : 0)<<endl;
2615    //   cout << " text    "<< text    << " "<<(text    ? text->GetEntries() : 0)<<endl;
2616    
2617    
2618  };  };
2619  //--------------------------------------  //--------------------------------------
2620  //  //
# Line 981  void PamLevel2::SortTracks(){ Line 2624  void PamLevel2::SortTracks(){
2624   * This method overrides TrkLevel2::GetTracks(), where sorting is done by decreasing number of fit points and increasing chi^2.   * This method overrides TrkLevel2::GetTracks(), where sorting is done by decreasing number of fit points and increasing chi^2.
2625   * PamLevel2::GetTracks() keeps the same track order given by TrkLevel2::GetTracks(), but checks image selection by using calorimeter and ToF tracking information.   * PamLevel2::GetTracks() keeps the same track order given by TrkLevel2::GetTracks(), but checks image selection by using calorimeter and ToF tracking information.
2626   */   */
2627    
2628  // TRefArray *PamLevel2::GetTracks(){  // TRefArray *PamLevel2::GetTracks(){
2629    
2630  // //  *-*-*-*-*-*-*-*-*-*-*-*-*  // //  *-*-*-*-*-*-*-*-*-*-*-*-*
# Line 989  void PamLevel2::SortTracks(){ Line 2633  void PamLevel2::SortTracks(){
2633    
2634  // //   return  sorted_tracks;  // //   return  sorted_tracks;
2635  //     return &sorted_tracks;  //     return &sorted_tracks;
2636        
2637  //  };  //  };
 TClonesArray *PamLevel2::GetTracks(){  
2638    
 //  *-*-*-*-*-*-*-*-*-*-*-*-*  
     SortTracks();  
 //  *-*-*-*-*-*-*-*-*-*-*-*-*  
2639    
     return tsorted;  
       
  };  
2640  //--------------------------------------  //--------------------------------------
2641   //  //
2642   //  //
2643  //--------------------------------------  //--------------------------------------
2644    
2645  /**  /**
2646   * Retrieves the it-th Pamela "physical" track.   * Retrieves the it-th Pamela "physical" track.
2647   * It override TrkLevel2::GetTrack(int it).   * It override TrkLevel2::GetTrack(int it).
2648   * @param it Track number, ranging from 0 to GetNTracks().   * @param it Track number, ranging from 0 to GetNTracks().
2649   */   */
2650  PamTrack *PamLevel2::GetTrack(int it){  PamTrack *PamLevel2::GetTrackOld(int it) {
2651    
2652  //    if(!trk2_obj) return 0;    PamTrack *track = NULL;
2653            
2654  // //  *-*-*-*+-*-*-*-*-*-*-*-*-*    //  *-*-*-*-*-*-*-*-*-*-*-*-*
2655  //     SortTracks("+CAL+TOF");    SortTracks();
2656  // //  *-*-*-*-*-*-*-*-*-*-*-*-*    //  *-*-*-*-*-*-*-*-*-*-*-*-*
2657  // //    if(!sorted_tracks)return 0;    if (!tsorted)
2658  //     if(sorted_tracks.IsEmpty())return 0;      return track;
2659      if (!tsorted->GetEntries())
2660        return track;
2661    
 //     PamTrack *track = 0;  
       
 //     if( it >=0 && it < trk2_obj->TrkLevel2::GetNTracks() && it<sorted_tracks.GetEntriesFast() ){      
 //      TrkTrack   *t = (TrkTrack*)sorted_tracks.At(it);  
 //      track = GetPamTrackAlong(t);  
 //     }else{  
 //      cout << "PamLevel2::GetTrack(int) : tracker track SeqNo "<< it <<" does not exist (GetNTracks() = "<<trk2_obj->TrkLevel2::GetNTracks()<<")"<<endl;  
 //     };  
       
 //     return track;  
2662    
2663  //    cout << "PamLevel2::GetTrack(int it) "<<endl;    if (it >= 0 && it < trk2_obj->TrkLevel2::GetNTracks()) {
2664  //  *-*-*-*-*-*-*-*-*-*-*-*-*      track = (PamTrack*)((*tsorted)[it]);
2665      SortTracks();    }
2666  //  *-*-*-*-*-*-*-*-*-*-*-*-*    else {
2667      if(!tsorted)return 0;      cout << "PamLevel2::GetTrackOld(int) : tracker track SeqNo " << it << " does not exist (GetNTracks() = "
2668      if(!tsorted->GetEntries())return 0;          << trk2_obj->TrkLevel2::GetNTracks() << ")" << endl;
2669      };
2670    
2671      return track;
2672    
2673    };
2674    
2675      PamTrack *track = 0;  //PamTrack *PamLevel2::GetTrack(int it) { return GetTrack(it,trkAlg); };
2676    
2677    /**
2678     * Retrieves the it-th Pamela "physical" track.
2679     * It override TrkLevel2::GetTrack(int it).
2680     * @param it Track number, ranging from 0 to GetNTracks().
2681     * @param alg Algorythm, see SetTrakingAlgorythm(char *alg) for explanation.
2682     */
2683    PamTrack *PamLevel2::GetTrack(int it, const char* alg) {
2684    
2685        TString s(alg);
2686        if(!s.CompareTo("") ||!s.CompareTo("STD") )return GetTrackOld(it); //old algorythm
2687    
2688    
2689        SortTracksNew();
2690        // >> fill tsorted, timage and text
2691    
2692        if ( ( !s.Contains("EXTF", TString::kIgnoreCase) || !EXT )){ //not forced exteded-alg requested (or exteded-data missing)
2693    
2694            if( s.Contains("NUC")){
2695                if(
2696                    tsorted_nuc &&
2697                    it < tsorted_nuc->GetEntries() &&                             //enough tracks found
2698                    it >= 0 &&                                                //valid index
2699                    true) return (PamTrack*)((*tsorted_nuc)[it]);                 //ok return the track
2700            }else{
2701                if(
2702                    tsorted &&
2703                    it < tsorted->GetEntries() &&                             //enough tracks found
2704                    it >= 0 &&                                                //valid index
2705                    true )return (PamTrack*)((*tsorted)[it]);                 //ok return the track
2706            }
2707    
2708        }
2709        
2710    
2711        /////////////////////////////////////////////////////////////////////////
2712        /// if requested get track from extended algorythm output
2713        /////////////////////////////////////////////////////////////////////////
2714            
2715      if( it >=0 && it < trk2_obj->TrkLevel2::GetNTracks()){      if(s.Contains("EXT", TString::kIgnoreCase) && EXT){//if exteded-alg requested
 //      TrkTrack   *t = (TrkTrack*)sorted_tracks.At(it);  
 //      track = GetPamTrackAlong(t);  
         TClonesArray &t = *(tsorted);  
         track = (PamTrack*)t[it];  
2716                    
2717      }else{          if(s.Contains("NUC")){
2718          cout << "PamLevel2::GetTrack(int) : tracker track SeqNo "<< it <<" does not exist (GetNTracks() = "<<trk2_obj->TrkLevel2::GetNTracks()<<")"<<endl;              if(
2719                    text_nuc &&
2720                    it < text_nuc->GetEntries() &&                             //enough tracks found
2721                    it >= 0 &&                                                //valid index
2722                    true) return (PamTrack*)((*text_nuc)[it]);
2723            }else{
2724                if(
2725                    text &&
2726                    it < text->GetEntries() &&                             //enough tracks found
2727                    it >= 0 &&                                                //valid index
2728                    true) return (PamTrack*)((*text)[it]);
2729            }
2730    
2731      };      };
2732            
     return track;  
2733            
2734  };      cout << "PamTrack *PamLevel2::GetTrack("<<it<<","<<alg<<") -- wrong track number or unrecognised algorithm"<<endl;
2735        
2736        return NULL;
2737    
2738    }
2739    ;
2740    TClonesArray *PamLevel2::GetTracks() {
2741    
2742      //  *-*-*-*-*-*-*-*-*-*-*-*-*
2743      SortTracks();
2744      //  *-*-*-*-*-*-*-*-*-*-*-*-*
2745    
2746      return tsorted;
2747    
2748    }
2749    ;
2750    Int_t  PamLevel2::GetNTracks(const char* alg) {
2751    
2752    
2753    //    cout << " trk_nuc_obj->GetEntries() "<<trk_nuc_obj->GetEntries()<<" trk2_nuc_obj->GetNTracks() "<<trk2_nuc_obj->GetNTracks()<<endl;
2754    
2755        TString s(alg);
2756    
2757        if(!s.CompareTo("") || !s.CompareTo("STD"))return trk2_obj->TrkLevel2::GetNTracks(); //standard algorythm
2758            
2759        if(s.Contains("EXTF", TString::kIgnoreCase) && EXT){
2760            if(s.Contains("NUC", TString::kIgnoreCase) && NUC)return trk_ext_nuc_obj->GetEntries();//ok
2761            return trk_ext_obj->GetEntries();//ok
2762        }
2763        if( s.Contains("EXT", TString::kIgnoreCase) && EXT) {
2764            if(s.Contains("NUC", TString::kIgnoreCase) && NUC)
2765                return (trk2_nuc_obj->TrkLevel2::GetNTracks() ?  trk2_nuc_obj->TrkLevel2::GetNTracks() :  trk_ext_nuc_obj->GetEntries() );  
2766            return (trk2_obj->TrkLevel2::GetNTracks() ?  trk2_obj->TrkLevel2::GetNTracks() :  trk_ext_obj->GetEntries() );
2767        }
2768        if(s.Contains("NUC", TString::kIgnoreCase) && NUC )
2769            return trk2_nuc_obj->TrkLevel2::GetNTracks();
2770        
2771        cout << "Int_t  PamLevel2::GetNTracks("<<alg<<") -- unrecognised algorithm"<<endl;
2772    
2773        return 0;
2774    
2775    }
2776    
2777    
2778  //--------------------------------------  //--------------------------------------
2779  //  //
2780  //  //
2781  //--------------------------------------  //--------------------------------------
2782  /**  /**
2783   * Retrieves (if present) the image of the it-th Pamela "physical" track, sorted by the method PamLevel2::SortTracks().   * Retrieves (if present) the image of the it-th Pamela "physical" track, sorted by the method PamLevel2::SortTracks().
2784   * @param it Track number, ranging from 0 to GetNTracks().   * @param it Track number, ranging from 0 to GetNTracks().
2785   */   */
2786  PamTrack *PamLevel2::GetTrackImage(int it){  PamTrack *PamLevel2::GetTrackImageOld(int it) {
2787    
2788  //     if(!trk2_obj) return 0;    //  *-*-*-*-*-*-*-*-*-*-*-*-*
2789      SortTracks();
2790      //  *-*-*-*-*-*-*-*-*-*-*-*-*
2791      if (!timage)
2792        return 0;
2793      if (!timage->GetEntries())
2794        return 0;
2795    
2796      PamTrack *image = 0;
2797    
2798      if (it >= 0 && it < trk2_obj->TrkLevel2::GetNTracks()) {
2799        TClonesArray &t = *(tsorted);
2800        PamTrack *temp = (PamTrack*) t[it];
2801        if (temp->GetTrkTrack()->HasImage()) {
2802          TClonesArray & t = *(timage);
2803          image = (PamTrack*) t[it];
2804        }
2805        else {
2806          //            cout <<"PamLevel2::GetTrackImage(int) : Track SeqNo "<<it<<" does not have image"<<endl;
2807        };
2808      }
2809      else {
2810        cout << "PamLevel2::GetTrackImageOld(int) : Tracker track SeqNo " << it << " does not exist (GetNTracks() = "
2811            << trk2_obj->TrkLevel2::GetNTracks() << ")" << endl;
2812      };
2813    
2814  // //  *-*-*-*-*-*-*-*-*-*-*-*-*    return image;
2815  //     SortTracks("+CAL+TOF");  }
2816  // //  *-*-*-*-*-*-*-*-*-*-*-*-*  /**
2817  // //    if(!sorted_tracks)return 0;   * Retrieves (if present) the image of the it-th Pamela "physical" track, sorted by the method PamLevel2::SortTracks().
2818  //     if(sorted_tracks.IsEmpty())return 0;   * @param it Track number, ranging from 0 to GetNTracks().
2819         * @param alg Algorythm, see SetTrakingAlgorythm(char *alg) for explanation.
2820  //     PamTrack *image = 0;   */
2821        PamTrack *PamLevel2::GetTrackImage(int it, const char* alg) {
 //     if( it >=0 && it < trk2_obj->TrkLevel2::GetNTracks() ){  
 //      TrkTrack *temp = (TrkTrack*)sorted_tracks.At(it);  
 //      if( temp->HasImage() ){  
 //          TrkTrack   *t = trk2_obj->TrkLevel2::GetStoredTrack(temp->GetImageSeqNo());  
 //          image = GetPamTrackAlong(t);  
 //      }else{  
 //          cout <<"PamLevel2::GetTrackImage(int) : Track SeqNo "<<it<<" does not have image"<<endl;  
 //      };  
 //     }else{  
 //      cout << "PamLevel2::GetTrackImage(int) : Tracker track SeqNo "<< it <<" does not exist (GetNTracks() = "<<trk2_obj->TrkLevel2::GetNTracks()<<")"<<endl;  
 //     };  
       
 //     return image;  
2822    
2823        TString s(alg);
2824        if(!s.CompareTo("") || !s.CompareTo("STD"))return GetTrackImageOld(it); //old algorythm
2825    
2826  //  *-*-*-*-*-*-*-*-*-*-*-*-*  
2827      SortTracks();      SortTracksNew();
2828  //  *-*-*-*-*-*-*-*-*-*-*-*-*      // >> fill tsorted, timage and text
2829      if(!timage)return 0;  
2830      if(!timage->GetEntries())return 0;      if ( ( !s.Contains("EXTF", TString::kIgnoreCase) || !EXT )){ //not forced exteded-alg requested (or exteded-data missing)
2831        
2832      PamTrack *image = 0;          if( s.Contains("NUC")){
2833                    if(
2834      if( it >=0 && it < trk2_obj->TrkLevel2::GetNTracks() ){                  tsorted_nuc &&
2835          TClonesArray &t = *(tsorted);                  it < tsorted_nuc->GetEntries() &&                             //enough tracks found
2836          PamTrack *temp = (PamTrack*)t[it];                  it >= 0 &&                                                //valid index
2837          if( temp->GetTrkTrack()->HasImage() ){                  true){
2838              TClonesArray &t = *(timage);                  TClonesArray &t = *(tsorted_nuc);
2839              image = (PamTrack*)t[it];                  PamTrack *temp = (PamTrack*) t[it];
2840                    if (temp->GetTrkTrack()->HasImage()) {
2841                        return (PamTrack*)((*timage_nuc)[it]);                 //ok return the track
2842                    }else{
2843                        return NULL;
2844                    }
2845                    
2846                }
2847          }else{          }else{
2848  //          cout <<"PamLevel2::GetTrackImage(int) : Track SeqNo "<<it<<" does not have image"<<endl;              if(
2849          };                  tsorted &&
2850      }else{                  it < tsorted->GetEntries() &&                             //enough tracks found
2851          cout << "PamLevel2::GetTrackImage(int) : Tracker track SeqNo "<< it <<" does not exist (GetNTracks() = "<<trk2_obj->TrkLevel2::GetNTracks()<<")"<<endl;                  it >= 0 &&                                                //valid index
2852      };                  true ){
2853                        TClonesArray &t = *(tsorted);
2854      return image;                  PamTrack *temp = (PamTrack*) t[it];
2855                    if (temp->GetTrkTrack()->HasImage()) {              
2856                        return (PamTrack*)((*timage)[it]);                 //ok return the track
2857                    }else{
2858                        return NULL;
2859                    }
2860                }
2861            }
2862    
2863        }
2864    
2865        cout << "PamTrack *PamLevel2::GetTrackImage("<<it<<","<<alg<<") -- wrong track number or unrecognised algorithm"<<endl;
2866          
2867        return NULL;
2868    
2869  }  }
2870    ;
2871    
2872  //--------------------------------------  //--------------------------------------
2873  //  //
# Line 1122  PamTrack *PamLevel2::GetTrackImage(int i Line 2879  PamTrack *PamLevel2::GetTrackImage(int i
2879   * @param detlist String to select trees to be included   * @param detlist String to select trees to be included
2880   * @return Pointer to a TTree   * @return Pointer to a TTree
2881   */   */
2882  TTree *PamLevel2::GetPamTree(TFile *f, TString detlist ){  TTree *PamLevel2::GetPamTree(TFile *f, TString detlist) {
2883    
2884      if (detlist.Contains("+AUTO", TString::kIgnoreCase)) {
2885        cout << "+AUTO" << endl;
2886        GetWhichTrees(f);
2887      };
2888      SetWhichTrees(detlist);
2889    
2890  //     if( !detlist.IsNull() ) SetWhichTrees(detlist);    if (pam_tree) {
 //     else                    GetWhichTrees(f);  
   if ( pam_tree ){  
2891      printf("WARNING: TTree *PamLevel2::GetPamTree(TFile *fl, TString detlist) -- pam_tree already exists!\n ");      printf("WARNING: TTree *PamLevel2::GetPamTree(TFile *fl, TString detlist) -- pam_tree already exists!\n ");
2892      return pam_tree;      return pam_tree;
2893    };    };
2894    //    //
2895    
2896      cout << "TTree *PamLevel2::GetPamTree(TFile *f, TString detlist ) -- obsolte "<<endl;    cout << "TTree *PamLevel2::GetPamTree(TFile *f, TString detlist ) -- obsolte " << endl;
2897    
2898      SetWhichTrees(detlist);    //    SetWhichTrees(detlist);
2899    
2900      TTree *Trout =0;    TTree *Trout = 0;
2901    
2902      TString fname = f->GetName();    TString fname = f->GetName();
2903      if(!CheckLevel2File(fname))return NULL;    if (!CheckLevel2File(fname))
2904        return NULL;
2905    
2906  //    UInt_t *found=0;        //    UInt_t *found=0;
2907    
2908      cout<< "GetPamTree(TFile*,TString): detector list --> ";    cout << "GetPamTree(TFile*,TString): detector list --> ";
2909      if(TRK1)cout<<"TRK1 ";    if (TRK1)
2910      if(TRK2)cout<<"TRK2 ";      cout << "TRK1 ";
2911      if(TRKh)cout<<"TRKH ";    if (TRK2)
2912      if(CAL1)cout<<"CAL1 ";      cout << "TRK2 ";
2913      if(CAL2)cout<<"CAL2 ";    if (TRKh)
2914      if(TOF)cout<<"TOF ";      cout << "TRKH ";
2915      if(TRG)cout<<"TRG ";    if (CAL1)
2916      if(AC)cout<<"AC ";      cout << "CAL1 ";
2917      if(ND)cout<<"ND ";    if (CAL2)
2918      if(S4)cout<<"S4 ";      cout << "CAL2 ";
2919      if(ORB)cout<<"ORB ";    if (TOF)
2920      cout << endl;      cout << "TOF ";
2921      if(SELLI)cout<<">>> Found selection-list <<<"<<endl;    if (TRG)
2922        cout << "TRG ";
2923      f->cd();    if (AC)
2924        cout << "AC ";
2925  // Tracker    if (ND)
2926      TTree *T = (TTree*)f->Get("Tracker");      cout << "ND ";
2927      if(T && (TRK2||TRK1||TRKh)) {    if (S4)
2928          if(TRK2)T->SetBranchAddress("TrkLevel2", GetPointerTo("TrkLevel2"));      cout << "S4 ";
2929  //      else    T->SetBranchStatus("TrkLevel2",0,found);    if (ORB)
2930          if(TRK2)cout << "Tracker      : set branch address TrkLevel2"<<endl;      cout << "ORB ";
2931          if(TRK1)T->SetBranchAddress("TrkLevel1", GetPointerTo("TrkLevel1"));    if (GP)
2932  //      else    T->SetBranchStatus("TrkLevel1",0,found);      cout << "GP ";
2933          if(TRK1)cout << "Tracker      : set branch address TrkLevel1"<<endl;    cout << endl;
2934          if(TRKh)T->SetBranchAddress("TrkHough", GetPointerTo("TrkHough"));    if (SELLI && SELLI != 2)
2935  //      else    T->SetBranchStatus("TrkHough",0,found);      cout << ">>> Found selection-list <<<" << endl; //EMILIANO
2936          if(TRKh)cout << "Tracker      : set branch address TrkHough"<<endl;  
2937          if(!Trout)Trout=T;    f->cd();
2938          else Trout->AddFriend(T);  
2939      }else{    // Tracker
2940          cout << "Tracker      : missing tree"<<endl;    TTree *T = (TTree*) f->Get("Tracker");
2941      };    if (T && (TRK2 || TRK1 || TRKh)) {
2942      // Calorimeter      if (TRK2)
2943      TTree *C = (TTree*)f->Get("Calorimeter");        T->SetBranchAddress("TrkLevel2", GetPointerTo("TrkLevel2"));
2944      if(C && (CAL2||CAL1)) {      //  else    T->SetBranchStatus("TrkLevel2",0,found);
2945          if(CAL2)C->SetBranchAddress("CaloLevel2", GetPointerTo("CaloLevel2"));      if (TRK2)
2946  //      else    C->SetBranchStatus("CaloLevel2",0,found);        cout << "Tracker      : set branch address TrkLevel2" << endl;
2947          if(CAL2)cout << "Calorimeter  : set branch address CaloLevel2"<<endl;      if (TRK1)
2948          if(CAL1)C->SetBranchAddress("CaloLevel1", GetPointerTo("CaloLevel1"));        T->SetBranchAddress("TrkLevel1", GetPointerTo("TrkLevel1"));
2949  //      else    C->SetBranchStatus("CaloLevel1",0,found);      //  else    T->SetBranchStatus("TrkLevel1",0,found);
2950          if(CAL1)cout << "Calorimeter  : set branch address CaloLevel1"<<endl;      if (TRK1)
2951          if(!Trout)Trout=C;        cout << "Tracker      : set branch address TrkLevel1" << endl;
2952          else Trout->AddFriend(C);      if (TRKh)
2953      }else{        T->SetBranchAddress("TrkHough", GetPointerTo("TrkHough"));
2954          cout << "Calorimeter  : missing tree"<<endl;      //  else    T->SetBranchStatus("TrkHough",0,found);
2955      };      if (TRKh)
2956          cout << "Tracker      : set branch address TrkHough" << endl;
2957      // ToF          if (!Trout)
2958      TTree *O = (TTree*)f->Get("ToF");        Trout = T;
2959      if(O && TOF) {      else
2960          O->SetBranchAddress("ToFLevel2", GetPointerTo("ToFLevel2"));          Trout->AddFriend(T);
2961          cout << "ToF          : set branch address ToFLevel2"<<endl;    }
2962          if(!Trout)Trout=O;    else {
2963          else Trout->AddFriend(O);      cout << "Tracker      : missing tree" << endl;
2964      }else{    };
2965          cout << "ToF         : missing tree"<<endl;    // Calorimeter
2966      };    TTree *C = (TTree*) f->Get("Calorimeter");
2967      // Trigger    if (C && (CAL2 || CAL1)) {
2968      TTree *R = (TTree*)f->Get("Trigger");      if (CAL2)
2969      if(R && TRG) {        C->SetBranchAddress("CaloLevel2", GetPointerTo("CaloLevel2"));
2970          R->SetBranchAddress("TrigLevel2", GetPointerTo("TrigLevel2"));      //  else    C->SetBranchStatus("CaloLevel2",0,found);
2971          cout << "Trigger      : set branch address TrigLevel2"<<endl;      if (CAL2)
2972          if(!Trout)Trout=R;        cout << "Calorimeter  : set branch address CaloLevel2" << endl;
2973          else Trout->AddFriend(R);      if (CAL1)
2974      }else{        C->SetBranchAddress("CaloLevel1", GetPointerTo("CaloLevel1"));
2975          cout << "Trigger      : missing tree"<<endl;      //  else    C->SetBranchStatus("CaloLevel1",0,found);
2976      };      if (CAL1)
2977      // S4        cout << "Calorimeter  : set branch address CaloLevel1" << endl;
2978      TTree *S = (TTree*)f->Get("S4");      if (!Trout)
2979      if(S && S4) {        Trout = C;
2980          S->SetBranchAddress("S4Level2", GetPointerTo("S4Level2"));      else
2981          cout << "S4           : set branch address S4Level2"<<endl;        Trout->AddFriend(C);
2982          if(!Trout)Trout=S;    }
2983          else Trout->AddFriend(S);    else {
2984      }else{      cout << "Calorimeter  : missing tree" << endl;
2985          cout << "S4           : missing tree"<<endl;    };
2986      };  
2987      // Neutron Detector    // ToF
2988      TTree *N = (TTree*)f->Get("NeutronD");    TTree *O = (TTree*) f->Get("ToF");
2989      if(N && ND) {    if (O && TOF) {
2990          N->SetBranchAddress("NDLevel2", GetPointerTo("NDLevel2"));      O->SetBranchAddress("ToFLevel2", GetPointerTo("ToFLevel2"));
2991          cout << "NeutronD     : set branch address NDLevel2"<<endl;      cout << "ToF          : set branch address ToFLevel2" << endl;
2992          if(!Trout)Trout=N;      if (!Trout)
2993          else Trout->AddFriend(N);        Trout = O;
2994      }else{      else
2995          cout << "NeutronD     : missing tree"<<endl;        Trout->AddFriend(O);
2996      };    }
2997      // Anticounters    else {
2998      TTree *A = (TTree*)f->Get("Anticounter");      cout << "ToF         : missing tree" << endl;
2999      if(A && AC) {    };
3000          A->SetBranchAddress("AcLevel2", GetPointerTo("AcLevel2"));    // Trigger
3001          cout << "Anticounter  : set branch address AcLevel2"<<endl;    TTree *R = (TTree*) f->Get("Trigger");
3002          if(!Trout)Trout=A;    if (R && TRG) {
3003          else Trout->AddFriend(A);      R->SetBranchAddress("TrigLevel2", GetPointerTo("TrigLevel2"));
3004      }else{      cout << "Trigger      : set branch address TrigLevel2" << endl;
3005          cout << "Anticounter  : missing tree"<<endl;      if (!Trout)
3006      };        Trout = R;
3007      // Orbital Info      else
3008      TTree *B = (TTree*)f->Get("OrbitalInfo");        Trout->AddFriend(R);
3009      if(B && ORB) {    }
3010          B->SetBranchAddress("OrbitalInfo", GetPointerTo("OrbitalInfo"));    else {
3011          cout << "OrbitalInfo  : set branch address OrbitalInfo"<<endl;      cout << "Trigger      : missing tree" << endl;
3012          if(!Trout)Trout=B;    };
3013          else Trout->AddFriend(B);    // S4
3014      }else{    TTree *S = (TTree*) f->Get("S4");
3015          cout << "OrbitalInfo  : missing tree"<<endl;    if (S && S4) {
3016      };      S->SetBranchAddress("S4Level2", GetPointerTo("S4Level2"));
3017        cout << "S4           : set branch address S4Level2" << endl;
3018      TTree *L = (TTree*)f->Get("SelectionList");      if (!Trout)
3019      if(L && SELLI==1) {        Trout = S;
3020  //      L->SetBranchAddress("RunEntry",&irun);      else
3021  //      cout << "SelectionList: set branch address RunEntry"<<endl;        Trout->AddFriend(S);
3022  //      L->SetBranchAddress("EventEntry",&irunentry);    }
3023  //      cout << "SelectionList: set branch address EventEntry"<<endl;    else {
3024  //      if(!Trout)Trout=O;      cout << "S4           : missing tree" << endl;
3025  //      else Trout->AddFriend("SelectionList");    };
3026          cout << " TTree *PamLevel2::GetPamTree(TFile, TString) >>> SelectionList not implemente!!!!"<<endl;    // Neutron Detector
3027          sel_tree = 0;    TTree *N = (TTree*) f->Get("NeutronD");
3028      }else{    if (N && ND) {
3029          cout << "SelectionList  : missing tree"<<endl;      N->SetBranchAddress("NDLevel2", GetPointerTo("NDLevel2"));
3030      };      cout << "NeutronD     : set branch address NDLevel2" << endl;
3031            if (!Trout)
3032      cout<<endl<<" Number of entries: "<<Trout->GetEntries()<<endl<<endl;        Trout = N;
3033        else
3034          Trout->AddFriend(N);
3035      }
3036      else {
3037        cout << "NeutronD     : missing tree" << endl;
3038      };
3039      // Anticounters
3040      TTree *A = (TTree*) f->Get("Anticounter");
3041      if (A && AC) {
3042        A->SetBranchAddress("AcLevel2", GetPointerTo("AcLevel2"));
3043        cout << "Anticounter  : set branch address AcLevel2" << endl;
3044        if (!Trout)
3045          Trout = A;
3046        else
3047          Trout->AddFriend(A);
3048      }
3049      else {
3050        cout << "Anticounter  : missing tree" << endl;
3051      };
3052      // Orbital Info
3053      TTree *B = (TTree*) f->Get("OrbitalInfo");
3054      if (B && ORB) {
3055        B->SetBranchAddress("OrbitalInfo", GetPointerTo("OrbitalInfo"));
3056        cout << "OrbitalInfo  : set branch address OrbitalInfo" << endl;
3057        if (!Trout)
3058          Trout = B;
3059        else
3060          Trout->AddFriend(B);
3061      }
3062      else {
3063        cout << "OrbitalInfo  : missing tree" << endl;
3064      };
3065    
3066      // GPamela
3067      TTree *G = (TTree*) f->Get("h20");
3068      if (G && GP) {
3069        if (!gp_obj)
3070          gp_obj = new GPamela();
3071        //      ------------------------------------
3072        //      ATTENZIONE!!!
3073        //      non so per quale arcano motivo,
3074        //      per l'albero di gpamela il branch address lo devo settare
3075        //      DOPO aver fatto friend
3076        //      FGRRRVZZZZUTSALKJMSLKJ!!!
3077        //      ------------------------------------
3078        //  gp_obj->SetBranchAddress(G); //ho dovuto fare in maniera diversa dagli altri
3079        //  cout << "h20          : set branch address GPamela "<<endl;
3080        if (!Trout)
3081          Trout = G;
3082        else
3083          Trout->AddFriend(G);
3084      }
3085      else {
3086        //  cout << "h20          : missing tree"<<endl;
3087      };
3088    
3089      TTree *L = (TTree*) f->Get("SelectionList");
3090      if (L && SELLI == 1) {
3091        cout << " TTree *PamLevel2::GetPamTree(TFile, TString) >>> SelectionList not implemented!!!!" << endl;
3092        sel_tree = 0;
3093      }
3094      else {
3095        cout << "SelectionList  : missing tree" << endl;
3096      };
3097    
3098      cout << endl << " Number of entries: " << Trout->GetEntries() << endl << endl;
3099    
3100      //      ------------------------------------
3101      //      ATTENZIONE!!!
3102      //      non so per quale arcano motivo,
3103      //      per l'albero di gpamela il branch address lo devo settare
3104      //      DOPO aver fatto friend
3105      //      FGRRRVZZZZUTSALKJMSLKJ!!!
3106      //      ------------------------------------
3107      if (G && GP) {
3108        gp_obj->SetBranchAddress(Trout); //ho dovuto fare in maniera diversa dagli altri
3109        cout << "h20          : set branch address GPamela " << endl;
3110      }
3111      else {
3112        cout << "h20          : missing tree" << endl;
3113      };
3114    
3115      pam_tree = (TChain*) Trout;
3116    
3117      return Trout;
3118    
     pam_tree = (TChain*)Trout;  
       
     return Trout;  
       
3119  }  }
3120  //--------------------------------------  //--------------------------------------
3121  //  //
# Line 1285  TTree *PamLevel2::GetPamTree(TFile *f, T Line 3128  TTree *PamLevel2::GetPamTree(TFile *f, T
3128   * @return Pointer to a TList of TSystemFiles   * @return Pointer to a TList of TSystemFiles
3129   * If no input file list is given , all the Level2 files inside the directory are processed.   * If no input file list is given , all the Level2 files inside the directory are processed.
3130   */   */
3131  TList*  PamLevel2::GetListOfLevel2Files(TString ddir, TString flisttxt = ""){  TList* PamLevel2::GetListOfLevel2Files(TString ddir, TString flisttxt = "") {
3132            
3133      TString wdir = gSystem->WorkingDirectory();    TString wdir = gSystem->WorkingDirectory();
3134        
3135      //    if(ddir=="")ddir = wdir;    if (ddir != "") {
3136  //      TSystemDirectory *datadir = new TSystemDirectory(gSystem->BaseName(ddir),ddir);      cout << "Level2 data directory : " << ddir << endl;
3137      if ( ddir != ""){    }
3138        cout << "Level2 data directory : "<<  ddir << endl;    else {
3139      } else {      cout << "Level2 data directory not given as input: trying to evaluate from list or taking working directory "
3140        cout << "Level2 data directory not given as input: trying to evaluate from list or taking working directory " << endl;          << endl;
3141      };    };
3142      TList *contents  = new TList; // create output list    TList *contents = new TList; // create output list
3143      contents->SetOwner();    contents->SetOwner();
3144        
3145  //    char *fullpath;    // --------------------------------------
3146  //    const char *fullpath;    // case 1 : input file/file-list provided
3147          // --------------------------------------
3148      // if no input file list is given:      if (flisttxt != "") {
3149      if ( flisttxt != "" ){  
3150                // --------------------------------------
3151  //      if( !gSystem->IsFileInIncludePath(flisttxt,&fullpath) ){              // a list of files given as input
3152  //      if( !(fullpath = gSystem->FindFile("./",flisttxt)) ){      // --------------------------------------
3153  //          cout <<"File "<<flisttxt<<" not found"<<endl;      if (!flisttxt.EndsWith(".root")) {
3154  //          return 0;  
3155  //      }              TString dir = gSystem->DirName(flisttxt);
3156  //      flisttxt = fullpath;        //            cout << " List directory "<<dir<<endl;
3157        if ( !flisttxt.EndsWith(".root") ){        if (dir == "." || dir == "")
3158            flisttxt = gSystem->ConcatFileName(wdir.Data(), gSystem->BaseName(flisttxt));
3159          flisttxt = gSystem->ConcatFileName(gSystem->DirName(flisttxt),gSystem->BaseName(flisttxt));        //                flisttxt = gSystem->ConcatFileName(gSystem->DirName(flisttxt),gSystem->BaseName(flisttxt));
3160    
3161          if( !gSystem->ChangeDirectory(ddir) ){        if (!gSystem->ChangeDirectory(ddir)) {
3162              cout << "Cannot change directory : "<<ddir<<endl;          cout << "Cannot change directory : " << ddir << endl;
3163              return 0;          return 0;
3164          }        }
3165            
3166          cout <<"Input file list : " << flisttxt <<endl;        cout << "Input file list : " << flisttxt << endl;
3167          ifstream in;        ifstream in;
3168          in.open(flisttxt, ios::in); //open input file list        in.open(flisttxt, ios::in); //open input file list
3169          if(!in.good()){        if (!in.good()) {
3170              cout <<" ERROR opening the file "<<endl;          cout << " TList*  PamLevel2::GetListOfLevel2Files(TString, TString) --> ERROR opening the file " << endl;
3171              gSystem->ChangeDirectory(wdir); // back to the working directory          gSystem->ChangeDirectory(wdir); // back to the working directory
3172              return 0;          return 0;
3173          }              }
3174          int line=0;        int line = 0;
3175          while (1) {        // ...........................
3176              TString file;        // loop over file-list records
3177              in >> file;        // ...........................
3178              if (!in.good()) break;        while (1) {
3179              line++;          TString file;
3180  //          cout <<"(1) " << file << endl;          in >> file;
3181              if(file.IsNull()){          if (!in.good())
3182                  cout << "-- list interrupted at line "<<line <<endl;            break;
3183                  break;          line++;
3184              }          cout << "(*) " << file << endl;
3185              if(file.Contains("#"))file = file(0,file.First("#"));          if (file.IsNull()) {
3186  //          cout <<"(2) " << file << endl;            cout << "-- list interrupted at line " << line << endl;
3187  //          if( gSystem->IsFileInIncludePath(file,&fullpath) ){            break;
3188  //          if( (fullpath = gSystem->FindFile(ddir,file)) ){          }
3189              if( file.EndsWith(".root") ){          if (file.Contains("#"))
3190                TString filedir;            file = file(0, file.First("#"));
3191                if (ddir != ""){          //
3192                  filedir = ddir; // take the input dir          // take only root files
3193                } else {          //
3194                  gSystem->ChangeDirectory(wdir); // back to the working directory          if (file.EndsWith(".root")) {
3195                  filedir = gSystem->DirName(file); // this will take the path if exist in the list otherwise it will return automatically the working dir            TString filedir;
3196                };            cout << ddir << endl;
3197                  char *fullpath = gSystem->ConcatFileName(gSystem->DirName(filedir),gSystem->BaseName(file));            if ( ddir != "" ) {
3198                  contents->Add(new TSystemFile(fullpath,gSystem->DirName(fullpath)));// add file to the list              filedir = ddir; // take the input dir
3199                  delete fullpath;            }
3200              }            else {
3201  //          }else{              gSystem->ChangeDirectory(wdir); // back to the working directory
3202  //              if(file.Data()!="")cout << "File: "<<file<<" ---> missing "<< endl;              filedir = gSystem->DirName(file); // this will take the path if exist in the list otherwise it will return automatically the working dir
3203  //          };            };
3204          };            filedir.Append("/");
3205          in.close();            //          char *fullpath = gSystem->ConcatFileName(gSystem->DirName(filedir), gSystem->BaseName(file));
3206        } else {            char *fullpath = gSystem->ConcatFileName(filedir.Data(), gSystem->BaseName(file));
3207            if(flisttxt.Contains("#"))flisttxt = flisttxt(0,flisttxt.First("#"));            contents->Add(new TSystemFile(fullpath, gSystem->DirName(fullpath)));// add file to the list
3208            char *fullpath = gSystem->ConcatFileName(gSystem->DirName(flisttxt),gSystem->BaseName(flisttxt));            cout << fullpath << endl;
3209            contents->Add(new TSystemFile(fullpath,gSystem->DirName(fullpath)));// add file to the list            delete fullpath;
3210            delete fullpath;          }
3211        };                  //          }else{
3212      }else{          //              if(file.Data()!="")cout << "File: "<<file<<" ---> missing "<< endl;
3213                    //          };
3214          cout << "No input file list given."<<endl;        };
3215          cout << "Check for existing root files."<<endl;        in.close();
3216  //              cout << "Warking directory: "<< gSystem->WorkingDirectory()<< endl;        // --------------------------------------
3217          if ( ddir == "" ){        // a single root file given as input
3218            ddir = wdir;        // --------------------------------------
3219            cout << "Level2 data directory : "<<  ddir << endl;      }
3220          };      else {
3221          if (flisttxt.Contains("#"))
3222          TSystemDirectory *datadir = new TSystemDirectory(gSystem->BaseName(ddir),ddir);          flisttxt = flisttxt(0, flisttxt.First("#"));
3223          TList *temp = datadir->GetListOfFiles();        char *fullpath = gSystem->ConcatFileName(gSystem->DirName(flisttxt), gSystem->BaseName(flisttxt));
3224  //              temp->Print();        contents->Add(new TSystemFile(fullpath, gSystem->DirName(fullpath)));// add file to the list
3225  //              cout << "*************************************" << endl;        delete fullpath;
3226                };
3227          TIter next(temp);      // ---------------------------------------------------------------------------------
3228          TSystemFile *questo = 0;      // case 2 : no input file/file-list provided --> read all files insede the directory
3229                // ---------------------------------------------------------------------------------
3230              }
3231          while ( (questo = (TSystemFile*) next()) ) {    else {
3232              TString name =  questo-> GetName();  
3233              if( name.EndsWith(".root") ){      cout << "No input file list given." << endl;
3234  //              const char *fullpath = gSystem->FindFile(ddir,name);      cout << "Check for existing root files." << endl;
3235  //              char *fullpath;      //          cout << "Warking directory: "<< gSystem->WorkingDirectory()<< endl;
3236  //              gSystem->IsFileInIncludePath(name,&fullpath);      if (ddir == "") {
3237                  char *fullpath = gSystem->ConcatFileName(gSystem->DirName(ddir),gSystem->BaseName(name));        ddir = wdir;
3238                  contents->Add(new TSystemFile(fullpath,gSystem->DirName(fullpath)));        cout << "Level2 data directory : " << ddir << endl;
3239                  delete fullpath;      };
3240              };  
3241          }      TSystemDirectory *datadir = new TSystemDirectory(gSystem->BaseName(ddir), ddir);
3242          delete temp;      TList *temp = datadir->GetListOfFiles();
3243          delete datadir;      if (!temp)
3244                  return 0;
3245      };      //          temp->Print();
3246      gSystem->ChangeDirectory(wdir); // back to the working directory      //          cout << "*************************************" << endl;
3247  //      cout << endl << "Selected files:" << endl;  
3248  //      contents->Print();      TIter next(temp);
3249      cout << contents->GetEntries()<<" files \n";      TSystemFile *questo = 0;
3250  //      cout << endl;  
3251  //      cout << "Working directory: "<< gSystem->WorkingDirectory()<< endl;      while ((questo = (TSystemFile*) next())) {
3252      return contents;        TString name = questo-> GetName();
3253  };        if (name.EndsWith(".root")) {
3254            //              const char *fullpath = gSystem->FindFile(ddir,name);
3255            //              char *fullpath;
3256            //              gSystem->IsFileInIncludePath(name,&fullpath);
3257            char *fullpath = gSystem->ConcatFileName(gSystem->DirName(ddir), gSystem->BaseName(name));
3258            contents->Add(new TSystemFile(fullpath, gSystem->DirName(fullpath)));
3259            delete fullpath;
3260          };
3261        }
3262        delete temp;
3263        delete datadir;
3264    
3265      };
3266      gSystem->ChangeDirectory(wdir); // back to the working directory
3267      //    cout << endl << "Selected files:" << endl;
3268      //    contents->Print();
3269      cout << contents->GetEntries() << " files \n";
3270      //    cout << endl;
3271      //    cout << "Working directory: "<< gSystem->WorkingDirectory()<< endl;
3272      return contents;
3273    }
3274    ;
3275  //--------------------------------------  //--------------------------------------
3276  //  //
3277  //  //
3278  //--------------------------------------  //--------------------------------------
3279  /**  /**
3280   * Get the Pamela detector chains from a list of files and make them friends.   * Get the Pamela detector chains from a list of files and make them friends.
3281   * @param fl Pointer to a TList of TSystemFiles   * @param fl Pointer to a TList of TSystemFiles
3282   * @param detlist String to select trees to be included   * @param detlist String to select trees to be included
3283   * @return Pointer to a TChain   * @return Pointer to a TChain
3284   */   */
3285  TChain *PamLevel2::GetPamTree(TList *fl, TString detlist ){  TChain *PamLevel2::GetPamTree(TList *fl, TString detlist) {
3286    //    //
3287    //    //
3288    //    //
3289    if ( pam_tree ){    if (pam_tree) {
3290      printf("WARNING: TChain *PamLevel2::GetPamTree(TList *fl, TString detlist) -- pam_tree already exists!\n ");      printf("WARNING: TChain *PamLevel2::GetPamTree(TList *fl, TString detlist) -- pam_tree already exists!\n ");
3291      return pam_tree;      return pam_tree;
3292    };    };
3293    //    //
       
     TChain *Trout =0;  
3294    
3295  //    if( !detlist.IsNull() )SetWhichTrees(detlist);    TChain *Trout = 0;
     SetWhichTrees(detlist);  
       
     cout<< "GetPamTree(TList*,TString): input detector list --> ";  
     if(TRK1)cout<<"TRK1 ";  
     if(TRK2)cout<<"TRK2 ";  
     if(TRKh)cout<<"TRKH ";  
     if(CAL1)cout<<"CAL1 ";  
     if(CAL2)cout<<"CAL2 ";  
     if(TOF)cout<<"TOF ";  
     if(TRG)cout<<"TRG ";  
     if(AC)cout<<"AC ";  
     if(ND)cout<<"ND ";  
     if(S4)cout<<"S4 ";  
     if(ORB)cout<<"ORB ";  
     cout << endl;  
   
      TChain *T = 0;      
      TChain *C = 0;  
      TChain *O = 0;  
      TChain *R = 0;  
      TChain *S = 0;  
      TChain *N = 0;  
      TChain *A = 0;  
      TChain *B = 0;  
3296    
3297       TChain *L = 0;    // -------------------------------------------
3298          // set flags to include/exclude trees/branches
3299      if(TRK2||TRK1||TRKh) T = new TChain("Tracker");        // -------------------------------------------
3300      if(CAL2||CAL1)       C = new TChain("Calorimeter");    if (detlist.Contains("+AUTO", TString::kIgnoreCase)) {
3301      if(TOF)              O = new TChain("ToF");      if (fl->GetEntries() > 0) {
3302      if(TRG)              R = new TChain("Trigger");        cout << "+AUTO" << endl;
3303      if(S4)               S = new TChain("S4");        TFile *fprimo = new TFile(fl->At(0)->GetName());
3304      if(ND)               N = new TChain("NeutronD");        GetWhichTrees(fprimo);
3305      if(AC)               A = new TChain("Anticounter");        fprimo->Close();// AAAAARGGGGGHHHHH!!!!!!! non commentare questa riga, altrimenti si incasina il TChain
3306      if(ORB)              B = new TChain("OrbitalInfo");        fprimo->Delete();
3307       L = new TChain("SelectionList");      }
3308          };
3309      // loop over files and create chains            SetWhichTrees(detlist);
     TIter next(fl);  
     TSystemFile *questo = 0;  
     while ( (questo = (TSystemFile*) next()) ) {  
         TString name =  questo->GetName();  
         cout << "File: "<< name << endl;  
         if( CheckLevel2File(name) ){  
             if(TRK2||TRK1||TRKh) T->Add(name);  
             if(CAL1||CAL2)       C->Add(name);  
             if(TOF)              O->Add(name);  
             if(TRG)              R->Add(name);  
             if(S4)               S->Add(name);  
             if(ND)               N->Add(name);  
             if(AC)               A->Add(name);  
             if(ORB)              B->Add(name);  
             if(SELLI==1)         L->Add(name);  
         };  
     };  
       
     cout << "done chain \n";  
     cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;  
3310    
3311  //    UInt_t *found=0;    // -------------------------------------------
3312  // Tracker    // build chains
3313      if(T && (TRK2||TRK1||TRKh)) {    // -------------------------------------------
3314          if(TRK2)T->SetBranchAddress("TrkLevel2", GetPointerTo("TrkLevel2"));    TChain *T = 0;
3315  //      else    T->SetBranchStatus("TrkLevel2",0,found);    TChain *C = 0;
3316          if(TRK2)cout << "Tracker      : set branch address TrkLevel2"<<endl;    TChain *O = 0;
3317          if(TRK1)T->SetBranchAddress("TrkLevel1", GetPointerTo("TrkLevel1"));    TChain *R = 0;
3318  //      else    T->SetBranchStatus("TrkLevel1",0,found);    TChain *S = 0;
3319          if(TRK1)cout << "Tracker      : set branch address TrkLevel1"<<endl;    TChain *N = 0;
3320          if(TRKh)T->SetBranchAddress("TrkHough", GetPointerTo("TrkHough"));    TChain *A = 0;
3321  //      else    T->SetBranchStatus("TrkHough",0,found);    TChain *B = 0;
3322          if(TRKh)cout << "Tracker      : set branch address TrkHough"<<endl;    TChain *G = 0;
3323          if(!Trout)Trout=T;  
3324          else Trout->AddFriend("Tracker");    TChain *L = 0;
3325      }else{    TChain *P = 0;
3326          cout << "Tracker      : missing tree"<<endl;  
3327      };    if (TRK2 || TRK1 || TRKh)
3328      // Calorimeter      T = new TChain("Tracker");
3329      if(C && (CAL2||CAL1)) {    if (CAL2 || CAL1)
3330          if(CAL2)C->SetBranchAddress("CaloLevel2", GetPointerTo("CaloLevel2"));      C = new TChain("Calorimeter");
3331  //      else    C->SetBranchStatus("CaloLevel2",0,found);    if (TOF)
3332          if(CAL2)cout << "Calorimeter  : set branch address CaloLevel2"<<endl;      O = new TChain("ToF");
3333          if(CAL1)C->SetBranchAddress("CaloLevel1", GetPointerTo("CaloLevel1"));    if (TRG)
3334  //      else    C->SetBranchStatus("CaloLevel1",0,found);      R = new TChain("Trigger");
3335          if(CAL1)cout << "Calorimeter  : set branch address CaloLevel1"<<endl;    if (S4)
3336          if(!Trout)Trout=C;      S = new TChain("S4");
3337          else Trout->AddFriend("Calorimeter");    if (ND)
3338      }else{      N = new TChain("NeutronD");
3339          cout << "Calorimeter  : missing tree"<<endl;    if (AC)
3340      };      A = new TChain("Anticounter");
3341      // ToF        if (ORB)
3342      if(O && TOF) {      B = new TChain("OrbitalInfo");
3343          O->SetBranchAddress("ToFLevel2", GetPointerTo("ToFLevel2"));    if (GP)
3344          cout << "ToF          : set branch address ToFLevel2"<<endl;      G = new TChain("h20");
3345          if(!Trout)Trout=O;    if (PROC)
3346          else Trout->AddFriend("ToF");      P = new TChain("ProcessingInfo");
3347      }else{    L = new TChain("SelectionList");
3348          cout << "ToF         : missing tree"<<endl;  
3349      };    // loop over files and create chains
3350      // Trigger    TIter next(fl);
3351      if(R && TRG) {    TSystemFile *questo = 0;
3352          R->SetBranchAddress("TrigLevel2", GetPointerTo("TrigLevel2"));    while ((questo = (TSystemFile*) next())) {
3353          cout << "Trigger      : set branch address TrigLevel2"<<endl;      TString name = questo->GetName();
3354          if(!Trout)Trout=O;      cout << "File: " << name << endl;
3355          else Trout->AddFriend("Trigger");      if (CheckLevel2File(name)) {
3356      }else{        if (TRK2 || TRK1 || TRKh)
3357          cout << "Trigger      : missing tree"<<endl;          T->Add(name);
3358      };        if (CAL1 || CAL2)
3359      // S4          C->Add(name);
3360      if(S && S4) {        if (TOF)
3361          S->SetBranchAddress("S4Level2", GetPointerTo("S4Level2"));          O->Add(name);
3362          cout << "S4           : set branch address S4Level2"<<endl;        if (TRG)
3363          if(!Trout)Trout=O;          R->Add(name);
3364          else Trout->AddFriend("S4");        if (S4)
3365      }else{          S->Add(name);
3366          cout << "S4           : missing tree"<<endl;        if (ND)
3367      };          N->Add(name);
3368      // Neutron Detector        if (AC)
3369      if(N && ND) {          A->Add(name);
3370          N->SetBranchAddress("NDLevel2", GetPointerTo("NDLevel2"));        if (ORB)
3371          cout << "NeutronD     : set branch address NDLevel2"<<endl;          B->Add(name);
3372          if(!Trout)Trout=O;        if (GP)
3373          else Trout->AddFriend("NeutronD");          G->Add(name);
3374      }else{        if (P)
3375          cout << "NeutronD     : missing tree"<<endl;          P->Add(name);
3376      };        if (SELLI == 1)
3377      // Anticounters          L->Add(name);
3378      if(A && AC) {       };
3379          A->SetBranchAddress("AcLevel2", GetPointerTo("AcLevel2"));    };
         cout << "Anticounter  : set branch address AcLevel2"<<endl;  
         if(!Trout)Trout=O;  
         else Trout->AddFriend("Anticounter");  
     }else{  
         cout << "Anticounter  : missing tree"<<endl;  
     };  
     // Orbital Info  
     if(B && ORB) {  
         B->SetBranchAddress("OrbitalInfo", GetPointerTo("OrbitalInfo"));  
         cout << "OrbitalInfo  : set branch address OrbitalInfo"<<endl;  
         if(!Trout)Trout=O;  
         else Trout->AddFriend("OrbitalInfo");  
     }else{  
         cout << "OrbitalInfo  : missing tree"<<endl;  
     };  
     cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;  
   
     // Selection List  
     if(L && SELLI==1) {  
         cout<<">>> Found selection-list <<<"<<endl;  
         L->SetBranchAddress("RunEntry",&irun);  
         cout << "SelectionList: set branch address RunEntry"<<endl;  
         L->SetBranchAddress("EventEntry",&irunentry);  
         cout << "SelectionList: set branch address EventEntry"<<endl;  
         sel_tree = L;  
 //      if(!Trout)Trout=O;  
 //      else Trout->AddFriend("SelectionList");  
         cout << "----------------------------------------------------" <<endl;  
     }else{  
 //      cout << "SelectionList  : missing tree"<<endl;  
         if(L)L->Delete();  
     };  
       
 //    cout<<endl<<" Number of entries: "<<Trout->GetEntries()<<endl<<endl;  
3380    
3381      pam_tree = Trout;    cout << "done data-tree chains  "<<  T->GetNtrees() <<" \n";
3382      cout << "----------------------------------------------------" << endl;
3383    
3384      return Trout;    // -------------------------------------------
3385  }    // make friends
3386      // -------------------------------------------
3387    
3388      // Tracker
3389      cout << "Friends: " << endl;
3390      if (T && (TRK2 || TRK1 || TRKh)) {
3391        if (!Trout)
3392          Trout = T;
3393        else
3394          Trout->AddFriend("Tracker");
3395        //  cout << "+Tacker"<<endl;
3396      };
3397      // Calorimeter
3398      if (C && (CAL2 || CAL1)) {
3399        if (!Trout)
3400          Trout = C;
3401        else
3402          Trout->AddFriend("Calorimeter");
3403        //  cout << "+Calorimeter"<<endl;
3404      };
3405      // ToF
3406      if (O && TOF) {
3407        if (!Trout)
3408          Trout = O;
3409        else
3410          Trout->AddFriend("ToF");
3411        //  cout << "+ToF"<<endl;
3412      };
3413      // Trigger
3414      if (R && TRG) {
3415        if (!Trout)
3416          Trout = O;
3417        else
3418          Trout->AddFriend("Trigger");
3419        //  cout << "+Trigger"<<endl;
3420      };
3421      // S4
3422      if (S && S4) {
3423        if (!Trout)
3424          Trout = O;
3425        else
3426          Trout->AddFriend("S4");
3427        //  cout << "+S4"<<endl;
3428      };
3429      // Neutron Detector
3430      if (N && ND) {
3431        if (!Trout)
3432          Trout = O;
3433        else
3434          Trout->AddFriend("NeutronD");
3435        //  cout << "+NeutronD"<<endl;
3436      };
3437      // Anticounters
3438      if (A && AC) {
3439        if (!Trout)
3440          Trout = O;
3441        else
3442          Trout->AddFriend("Anticounter");
3443        //  cout << "+Anticounter"<<endl;
3444      };
3445      // Orbital Info
3446      if (B && ORB) {
3447        if (!Trout)
3448          Trout = O;
3449        else
3450          Trout->AddFriend("OrbitalInfo");
3451        //  cout << "+OrbitalInfo"<<endl;
3452      };
3453      // GPamela
3454      if (G && GP) {
3455        if (!Trout)
3456          Trout = G;
3457        else
3458          Trout->AddFriend("h20");
3459        //  cout << "+h20"<<endl;
3460      };
3461    
3462      //  =====================================
3463      //  SET BRANCH-ADDRESS AFTER CHAIN+FRIEND
3464      //  =====================================
3465      if( Trout->GetNtrees() )SetBranchAddress(Trout);
3466    
3467      //  ------------------------------------
3468      //  finally handle selection trees...
3469      //  (it is not friend of pamela tree)
3470      //  ------------------------------------
3471    
3472      cout << "----------------------------------------------------" << endl;
3473    
3474      // Selection List
3475      if (L && SELLI == 1) {
3476        cout << ">>> Found selection-list <<<" << endl;
3477        //  L->SetBranchAddress("RunEntry",&irun);
3478        L->SetBranchAddress("RunEntry", &irunt);//NEWNEW
3479        cout << "SelectionList: set branch address RunEntry" << endl;
3480        L->SetBranchAddress("EventEntry", &irunentry);
3481        cout << "SelectionList: set branch address EventEntry" << endl;
3482        /*    if ( L->GetBranch("L0EventEntry") ){
3483          hasL0EE = true;
3484          L->SetBranchAddress("L0EventEntry", &il0entry);
3485          cout << "SelectionList: set branch address L0EventEntry" << endl;
3486        } else {
3487          hasL0EE = false; // backward compatibility with old preselected files...
3488          }*/
3489        sel_tree = L;
3490        //          if(!Trout)Trout=O;
3491        //          else Trout->AddFriend("SelectionList");
3492        cout << "+SelectionList" << endl;
3493        cout << "----------------------------------------------------" << endl;
3494      }
3495      else {
3496        //  cout << "SelectionList  : missing tree"<<endl;
3497        if (L)
3498          L->Delete();
3499      };
3500    
3501      //ProcessingInfo EM
3502      if ( P && P->GetEntries() ){
3503        cout << "----------------------------------------------------" << endl;
3504        cout << ">>> Found ProcessingInfo <<<" << endl;
3505        //  L->SetBranchAddress("RunEntry",&irun);
3506        P->SetBranchAddress("ProcInfo", &proc_obj);//NEWNEW
3507      }
3508      //  --------------------------------------------
3509      //  return the pamela chain with all the friends
3510      //  --------------------------------------------
3511    
3512      pam_tree = Trout;
3513    
3514      return Trout;
3515    }
3516    
3517  //--------------------------------------  //--------------------------------------
3518  //  //
# Line 1608  TChain *PamLevel2::GetPamTree(TList *fl, Line 3521  TChain *PamLevel2::GetPamTree(TList *fl,
3521  /**  /**
3522   * Set branch addresses for Pamela friend trees   * Set branch addresses for Pamela friend trees
3523   */   */
3524  void PamLevel2::SetBranchAddress(TTree *t){  void PamLevel2::SetBranchAddress(TTree *t) {
3525    
3526      TRK2    = TRK2 & t->GetBranchStatus("TrkLevel2");  //   TRK2 = TRK2 & t->GetBranchStatus("TrkLevel2");
3527      TRK1    = TRK1 & t->GetBranchStatus("TrkLevel1");  //   TRK1 = TRK1 & t->GetBranchStatus("TrkLevel1");
3528      TRKh    = TRKh & t->GetBranchStatus("TrkHough");  //   TRKh = TRKh & t->GetBranchStatus("TrkHough");
3529      CAL2    = CAL2 & t->GetBranchStatus("CaloLevel2");  //   CAL2 = CAL2 & t->GetBranchStatus("CaloLevel2");
3530      CAL1    = CAL1 & t->GetBranchStatus("CaloLevel1");  //   CAL1 = CAL1 & t->GetBranchStatus("CaloLevel1");
3531      TOF    = TOF & t->GetBranchStatus("ToFLevel2");  //   TOF = TOF & t->GetBranchStatus("ToFLevel2");
3532      TRG    = TRG & t->GetBranchStatus("TrigLevel2");  //   TRG = TRG & t->GetBranchStatus("TrigLevel2");
3533      S4     = S4  & t->GetBranchStatus("S4Level2");  //   S4 = S4 & t->GetBranchStatus("S4Level2");
3534      ND     = ND  & t->GetBranchStatus("NDLevel2");  //   ND = ND & t->GetBranchStatus("NDLevel2");
3535      AC     = AC  & t->GetBranchStatus("AcLevel2");  //   AC = AC & t->GetBranchStatus("AcLevel2");
3536      ORB    = ORB & t->GetBranchStatus("OrbitalInfo");  //   ORB = ORB & t->GetBranchStatus("OrbitalInfo");
3537    //   GP = GP & t->GetBranchStatus("h20");
3538    
3539      // Tracker  
3540      if(TRK1) {    // Tracker
3541          t->SetBranchAddress("TrkLevel1", GetPointerTo("TrkLevel2"));    if (TRK1) {
3542          cout << "Tracker      : set branch address TrkLevel1"<<endl;      t->SetBranchAddress("TrkLevel1", GetPointerTo("TrkLevel2"));
3543      };      cout << "Tracker      : set branch address TrkLevel1" << endl;
3544      if(TRK2) {    };
3545          t->SetBranchAddress("TrkLevel2", GetPointerTo("TrkLevel1"));    if (TRK2) {
3546          cout << "Tracker      : set branch address TrkLevel2"<<endl;      t->SetBranchAddress("TrkLevel2", GetPointerTo("TrkLevel1"));
3547      };      cout << "Tracker      : set branch address TrkLevel2" << endl;
3548      if(TRKh) {      NUC = t->GetBranchStatus("TrackNuclei");
3549          t->SetBranchAddress("TrkHough", GetPointerTo("TrkHough"));      EXT = t->GetBranchStatus("RecoveredTrack") && (NUC ? t->GetBranchStatus("RecoveredTrackNuclei"): true );    
3550          cout << "Tracker      : set branch address TrkHough"<<endl;    };
3551      };    if (TRKh) {
3552            t->SetBranchAddress("TrkHough", GetPointerTo("TrkHough"));
3553      // Calorimeter      cout << "Tracker      : set branch address TrkHough" << endl;
3554      if(CAL1) {    };
3555          t->SetBranchAddress("CaloLevel1", GetPointerTo("CaloLevel1"));  
3556          cout << "Calorimeter  : set branch address CaloLevel1"<<endl;    // Calorimeter
3557      };    if (CAL1) {
3558      if(CAL2) {      t->SetBranchAddress("CaloLevel1", GetPointerTo("CaloLevel1"));
3559          t->SetBranchAddress("CaloLevel2", GetPointerTo("CaloLevel2"));      cout << "Calorimeter  : set branch address CaloLevel1" << endl;
3560          cout << "Calorimeter  : set branch address CaloLevel2"<<endl;    };
3561      };    if (CAL2) {
3562            t->SetBranchAddress("CaloLevel2", GetPointerTo("CaloLevel2"));
3563      // ToF          cout << "Calorimeter  : set branch address CaloLevel2" << endl;
3564      if(TOF) {    };
3565          t->SetBranchAddress("ToFLevel2", GetPointerTo("ToFLevel2"));  
3566          cout << "ToF          : set branch address ToFLevel2"<<endl;    // ToF
3567      };    if (TOF) {
3568      // Trigger      t->SetBranchAddress("ToFLevel2", GetPointerTo("ToFLevel2"));
3569      if(TRG) {      cout << "ToF          : set branch address ToFLevel2" << endl;
3570          t->SetBranchAddress("TrigLevel2", GetPointerTo("TrigLevel2"));    };
3571          cout << "Trigger      : set branch address TrigLevel2"<<endl;    // Trigger
3572      };    if (TRG) {
3573      // S4      t->SetBranchAddress("TrigLevel2", GetPointerTo("TrigLevel2"));
3574      if(S4) {      cout << "Trigger      : set branch address TrigLevel2" << endl;
3575          t->SetBranchAddress("S4Level2", GetPointerTo("S4Level2"));    };
3576          cout << "S4           : set branch address S4Level2"<<endl;    // S4
3577      };    if (S4) {
3578      // Neutron Detector      t->SetBranchAddress("S4Level2", GetPointerTo("S4Level2"));
3579      if(ND) {      cout << "S4           : set branch address S4Level2" << endl;
3580          t->SetBranchAddress("NDLevel2", GetPointerTo("NDLevel2"));    };
3581          cout << "NeutronD     : set branch address NDLevel2"<<endl;    // Neutron Detector
3582      };    if (ND) {
3583      // Anticounters      t->SetBranchAddress("NDLevel2", GetPointerTo("NDLevel2"));
3584      if(AC) {      cout << "NeutronD     : set branch address NDLevel2" << endl;
3585          t->SetBranchAddress("AcLevel2", GetPointerTo("AcLevel2"));    };
3586          cout << "Anticounter  : set branch address AcLevel2"<<endl;    // Anticounters
3587      };    if (AC) {
3588      // OrbitalInfo      t->SetBranchAddress("AcLevel2", GetPointerTo("AcLevel2"));
3589      if(ORB) {      cout << "Anticounter  : set branch address AcLevel2" << endl;
3590          t->SetBranchAddress("OrbitalInfo", GetPointerTo("OrbitalInfo"));    };
3591          cout << "OrbitalInfo  : set branch address OrbitalInfo"<<endl;    // OrbitalInfo
3592      };    if (ORB) {
3593      // SelectionList      t->SetBranchAddress("OrbitalInfo", GetPointerTo("OrbitalInfo"));
3594      if(SELLI==1) {      cout << "OrbitalInfo  : set branch address OrbitalInfo" << endl;
3595          t->SetBranchAddress("RunEntry", &irun);    };
3596          cout << "SelectionList: set branch address RunEntry"<<endl;    // GPamela
3597          t->SetBranchAddress("EventEntry", &irunentry);    if (GP) {
3598          cout << "SelectionList: set branch address EventEntry"<<endl;      //  GetPointerTo("GPamela");
3599      };      if (!gp_obj)
3600              gp_obj = new GPamela();
3601        //  gp_obj->SetBranchAddress(t); //ho dovuto fare in maniera diversa dagli altri
3602        // //       t->SetBranchAddress("GPamela", GetPointerTo("GPamela"));
3603        if (SELLI)
3604          t->SetBranchAddress("GPamela", GetPointerTo("GPamela"));
3605        else
3606          gp_obj->SetBranchAddress(t); //ho dovuto fare in maniera diversa dagli altri
3607    
3608        cout << "h20          : set branch address GPamela " << endl;
3609      };
3610      if(NUC){
3611          
3612          cout << "Found nuclei-track branches" << endl;
3613    
3614          if( !trk_nuc_obj )trk_nuc_obj = new TClonesArray("TrkTrack");
3615          if( !calo_nuc_obj)calo_nuc_obj= new TClonesArray("CaloTrkVar");
3616          if( !tof_nuc_obj)tof_nuc_obj= new TClonesArray("ToFTrkVar");
3617          if( !orb_nuc_obj)orb_nuc_obj= new TClonesArray("OrbitalInfoTrkVar");
3618          if (TRK2)t->                          SetBranchAddress("TrackNuclei",&trk_nuc_obj);
3619          if (CAL2)t->GetFriend("Calorimeter")->SetBranchAddress("TrackNuclei",&calo_nuc_obj);
3620          if (TOF )t->GetFriend("ToF")->        SetBranchAddress("TrackNuclei",&tof_nuc_obj);
3621          if (ORB )t->GetFriend("OrbitalInfo")->SetBranchAddress("TrackNuclei",&orb_nuc_obj);
3622    
3623          ///copy the vector content inside a "fake" object (all aother info are missing)    
3624    
3625          if( !trk2_nuc_obj )trk2_nuc_obj =  new TrkLevel2();
3626          if( !calo2_nuc_obj )calo2_nuc_obj =  new CaloLevel2();
3627          if( !tof2_nuc_obj )tof2_nuc_obj =  new ToFLevel2();
3628          if( !orb2_nuc_obj )orb2_nuc_obj =  new OrbitalInfo();
3629    //       *(trk2_nuc_obj->GetPointerToTrackArray()) = new TClonesArray(*trk_nuc_obj);
3630    //       *(calo2_nuc_obj->GetPointerToTrackArray()) = new TClonesArray(*calo_nuc_obj);
3631    //       *(tof2_nuc_obj->GetPointerToTrackArray()) = new TClonesArray(*tof_nuc_obj);
3632    //       *(orb2_nuc_obj->GetPointerToTrackArray()) = new TClonesArray(*orb_nuc_obj);
3633    
3634          trk2_nuc_obj->SetTrackArray(  trk_nuc_obj  );
3635          calo2_nuc_obj->SetTrackArray( calo_nuc_obj );
3636          tof2_nuc_obj->SetTrackArray(  tof_nuc_obj  );
3637          orb2_nuc_obj->SetTrackArray(  orb_nuc_obj  );
3638    
3639          
3640      }    
3641    
3642      if(EXT){
3643          
3644          cout << "Found extended tracking algorythm branches" << endl;
3645    
3646          if( !trk_ext_obj )trk_ext_obj = new TClonesArray("ExtTrack");
3647          if( !calo_ext_obj)calo_ext_obj= new TClonesArray("CaloTrkVar");
3648          if( !tof_ext_obj)tof_ext_obj= new TClonesArray("ToFTrkVar");
3649          if( !orb_ext_obj)orb_ext_obj= new TClonesArray("OrbitalInfoTrkVar");
3650          
3651          if (TRK2)t->                          SetBranchAddress("RecoveredTrack",&trk_ext_obj);
3652          if (CAL2)t->GetFriend("Calorimeter")->SetBranchAddress("RecoveredTrack",&calo_ext_obj);
3653          if (TOF )t->GetFriend("ToF")->        SetBranchAddress("RecoveredTrack",&tof_ext_obj);
3654          if (ORB )t->GetFriend("OrbitalInfo")->SetBranchAddress("RecoveredTrack",&orb_ext_obj);
3655    
3656        
3657          if(NUC){
3658              if( !trk_ext_nuc_obj )trk_ext_nuc_obj = new TClonesArray("ExtTrack");
3659              if( !calo_ext_nuc_obj)calo_ext_nuc_obj= new TClonesArray("CaloTrkVar");
3660              if( !tof_ext_nuc_obj)tof_ext_nuc_obj= new TClonesArray("ToFTrkVar");
3661              if( !orb_ext_nuc_obj)orb_ext_nuc_obj= new TClonesArray("OrbitalInfoTrkVar");
3662              if (TRK2)t->                          SetBranchAddress("RecoveredTrackNuclei",&trk_ext_nuc_obj);
3663              if (CAL2)t->GetFriend("Calorimeter")->SetBranchAddress("RecoveredTrackNuclei",&calo_ext_nuc_obj);
3664              if (TOF )t->GetFriend("ToF")->        SetBranchAddress("RecoveredTrackNuclei",&tof_ext_nuc_obj);
3665              if (ORB )t->GetFriend("OrbitalInfo")->SetBranchAddress("RecoveredTrackNuclei",&orb_ext_nuc_obj);
3666          }
3667      }    
3668    }
3669    /**
3670     * Set branch addresses for Pamela friend trees
3671     */
3672    void PamLevel2::SetBranchAddress(TChain *t) {
3673    
3674      //     TRK2    = TRK2 & t->GetBranchStatus("TrkLevel2");
3675      //     TRK1    = TRK1 & t->GetBranchStatus("TrkLevel1");
3676      //     TRKh    = TRKh & t->GetBranchStatus("TrkHough");
3677      //     CAL1    = CAL1 & t->GetBranchStatus("CaloLevel1");
3678      //     CAL2    = CAL2 & t->GetBranchStatus("CaloLevel2");
3679      //     TOF    = TOF & t->GetBranchStatus("ToFLevel2");
3680      //     TRG    = TRG & t->GetBranchStatus("TrigLevel2");
3681      //     S4     = S4  & t->GetBranchStatus("S4Level2");
3682      //     ND     = ND  & t->GetBranchStatus("NDLevel2");
3683      //     AC     = AC  & t->GetBranchStatus("AcLevel2");
3684      //     ORB    = ORB & t->GetBranchStatus("OrbitalInfo");
3685      //    GP     = GP & t->GetBranchStatus("h20");
3686    
3687      // Tracker
3688      if (TRK2) {
3689        t->SetBranchAddress("TrkLevel2", GetPointerTo("TrkLevel2"));
3690        cout << "Tracker      : set branch address TrkLevel2" << endl;
3691        NUC = t->GetBranchStatus("TrackNuclei");
3692        EXT = t->GetBranchStatus("RecoveredTrack") && (NUC ? t->GetBranchStatus("RecoveredTrackNuclei"): true );
3693      };
3694      if (TRK1) {
3695        t->SetBranchAddress("TrkLevel1", GetPointerTo("TrkLevel1"));
3696        cout << "Tracker      : set branch address TrkLevel1" << endl;
3697      };
3698      if (TRKh) {
3699        t->SetBranchAddress("TrkHough", GetPointerTo("TrkHough"));
3700        cout << "Tracker      : set branch address TrkHough" << endl;
3701      };
3702    
3703      // Calorimeter
3704      if (CAL2) {
3705        t->SetBranchAddress("CaloLevel2", GetPointerTo("CaloLevel2"));
3706        cout << "Calorimeter  : set branch address CaloLevel2" << endl;    
3707      };
3708      if (CAL1) {
3709        t->SetBranchAddress("CaloLevel1", GetPointerTo("CaloLevel1"));
3710        cout << "Calorimeter  : set branch address CaloLevel1" << endl;
3711      };
3712    
3713      // ToF
3714      if (TOF) {
3715        t->SetBranchAddress("ToFLevel2", GetPointerTo("ToFLevel2"));
3716        cout << "ToF          : set branch address ToFLevel2" << endl;
3717      };
3718      // Trigger
3719      if (TRG) {
3720        t->SetBranchAddress("TrigLevel2", GetPointerTo("TrigLevel2"));
3721        cout << "Trigger      : set branch address TrigLevel2" << endl;
3722      };
3723      // S4
3724      if (S4) {
3725        t->SetBranchAddress("S4Level2", GetPointerTo("S4Level2"));
3726        cout << "S4           : set branch address S4Level2" << endl;
3727      };
3728      // Neutron Detector
3729      if (ND) {
3730        t->SetBranchAddress("NDLevel2", GetPointerTo("NDLevel2"));
3731        cout << "NeutronD     : set branch address NDLevel2" << endl;
3732      };
3733      // Anticounters
3734      if (AC) {
3735        t->SetBranchAddress("AcLevel2", GetPointerTo("AcLevel2"));
3736        cout << "Anticounter  : set branch address AcLevel2" << endl;
3737      };
3738      // OrbitalInfo
3739      if (ORB) {
3740        t->SetBranchAddress("OrbitalInfo", GetPointerTo("OrbitalInfo"));
3741        cout << "OrbitalInfo  : set branch address OrbitalInfo" << endl;
3742      };
3743      // GPamela
3744      //    cout <<"GP "<<GP<<endl;
3745      if (GP) {
3746        //  GetPointerTo("GPamela");
3747        if (!gp_obj)
3748          gp_obj = new GPamela();
3749        if (SELLI)
3750          t->SetBranchAddress("GPamela", GetPointerTo("GPamela"));
3751        else
3752          gp_obj->SetBranchAddress(t); //ho dovuto fare in maniera diversa dagli altri
3753        //  gp_obj->SetBranchAddress(t); //ho dovuto fare in maniera diversa dagli altri
3754        cout << "h20          : set branch address GPamela " << endl;
3755      };
3756      // SelectionList
3757      //     if(SELLI==1){
3758      //    t->SetBranchAddress("RunEntry",&irunt);//NEWNEW
3759      //    cout << "SelectionList: set branch address RunEntry"<<endl;
3760      //    t->SetBranchAddress("EventEntry",&irunentry);
3761      //    cout << "SelectionList: set branch address EventEntry"<<endl;
3762    
3763      //     }
3764      if(NUC){
3765          
3766          cout << "Found nuclei-track branches" << endl;
3767    
3768          if( !trk_nuc_obj )trk_nuc_obj = new TClonesArray("TrkTrack");
3769          if( !calo_nuc_obj)calo_nuc_obj= new TClonesArray("CaloTrkVar");
3770          if( !tof_nuc_obj)tof_nuc_obj= new TClonesArray("ToFTrkVar");
3771          if( !orb_nuc_obj)orb_nuc_obj= new TClonesArray("OrbitalInfoTrkVar");
3772          if (TRK2)t->                          SetBranchAddress("TrackNuclei",&trk_nuc_obj);
3773          if (CAL2)t->GetFriend("Calorimeter")->SetBranchAddress("TrackNuclei",&calo_nuc_obj);
3774          if (TOF )t->GetFriend("ToF")->        SetBranchAddress("TrackNuclei",&tof_nuc_obj);
3775          if (ORB )t->GetFriend("OrbitalInfo")->SetBranchAddress("TrackNuclei",&orb_nuc_obj);
3776          
3777          ///copy the vector content inside a "fake" object (all aother info are missing)    
3778    
3779          if( !trk2_nuc_obj )trk2_nuc_obj =  new TrkLevel2();
3780          if( !calo2_nuc_obj )calo2_nuc_obj =  new CaloLevel2();
3781          if( !tof2_nuc_obj )tof2_nuc_obj =  new ToFLevel2();
3782          if( !orb2_nuc_obj )orb2_nuc_obj =  new OrbitalInfo();
3783    
3784    //       *(trk2_nuc_obj->GetPointerToTrackArray()) = new TClonesArray(*trk_nuc_obj);
3785    //       *(calo2_nuc_obj->GetPointerToTrackArray()) = new TClonesArray(*calo_nuc_obj);
3786    //       *(tof2_nuc_obj->GetPointerToTrackArray()) = new TClonesArray(*tof_nuc_obj);
3787    //       *(orb2_nuc_obj->GetPointerToTrackArray()) = new TClonesArray(*orb_nuc_obj);
3788          trk2_nuc_obj->SetTrackArray(  trk_nuc_obj  );
3789          calo2_nuc_obj->SetTrackArray( calo_nuc_obj );
3790          tof2_nuc_obj->SetTrackArray(  tof_nuc_obj  );
3791          orb2_nuc_obj->SetTrackArray(  orb_nuc_obj  );
3792    
3793      }    
3794      if(EXT){
3795          
3796          cout << "Found extended tracking algorythm branches" << endl;
3797    
3798          t->SetBranchAddress("extAlgFlag",&extAlgFlag);
3799    
3800          if( !trk_ext_obj )trk_ext_obj = new TClonesArray("ExtTrack");
3801          if( !calo_ext_obj)calo_ext_obj= new TClonesArray("CaloTrkVar");
3802          if( !tof_ext_obj)tof_ext_obj= new TClonesArray("ToFTrkVar");
3803          if( !orb_ext_obj)orb_ext_obj= new TClonesArray("OrbitalInfoTrkVar");
3804          
3805          if (TRK2)t->                          SetBranchAddress("RecoveredTrack",&trk_ext_obj);
3806          if (CAL2)t->GetFriend("Calorimeter")->SetBranchAddress("RecoveredTrack",&calo_ext_obj);
3807          if (TOF )t->GetFriend("ToF")->        SetBranchAddress("RecoveredTrack",&tof_ext_obj);
3808          if (ORB )t->GetFriend("OrbitalInfo")->SetBranchAddress("RecoveredTrack",&orb_ext_obj);
3809          
3810          if(NUC){
3811              if( !trk_ext_nuc_obj )trk_ext_nuc_obj = new TClonesArray("ExtTrack");
3812              if( !calo_ext_nuc_obj)calo_ext_nuc_obj= new TClonesArray("CaloTrkVar");
3813              if( !tof_ext_nuc_obj)tof_ext_nuc_obj= new TClonesArray("ToFTrkVar");
3814              if( !orb_ext_nuc_obj)orb_ext_nuc_obj= new TClonesArray("OrbitalInfoTrkVar");
3815              if (TRK2)t->                          SetBranchAddress("RecoveredTrackNuclei",&trk_ext_nuc_obj);
3816              if (CAL2)t->GetFriend("Calorimeter")->SetBranchAddress("RecoveredTrackNuclei",&calo_ext_nuc_obj);
3817              if (TOF )t->GetFriend("ToF")->        SetBranchAddress("RecoveredTrackNuclei",&tof_ext_nuc_obj);
3818              if (ORB )t->GetFriend("OrbitalInfo")->SetBranchAddress("RecoveredTrackNuclei",&orb_ext_nuc_obj);
3819          }
3820      }    
3821      
3822  }  }
3823    
3824  /**  /**
3825   * Set branch addresses for Pamela friend trees   * Set the tracking algorythm
3826     * @param alg String to choose the track.
3827     * "" --> take the output of the standard tracking algorythm
3828     * "STD" --> take the output of the standard tracking algorythm
3829     * "NUC" --> take the output of the standard tracking algorythm for nuclei cluster selection
3830     * "EXT" --> in case the standard tracking algorythm has not found any track, take the output of the extended one
3831     * "EXTF" --> force the extended tracking algorythm
3832     * "NUCEXT" --> as "EXT", but for nuclei
3833     * "NUCEXTF" --> as "EXTF", but for nuclei
3834   */   */
3835  void PamLevel2::SetBranchAddress(TChain *t){  // void PamLevel2::SetTrackingAlgorythm(const char *alg){
3836    
3837    
3838    //     TString s(alg);
3839    //     if(s.Contains("NUC", TString::kIgnoreCase) && !NUC)
3840    //      cout << "Warning! NUC algorythm requested, but branches are missing"<<endl;
3841    //     if(s.Contains("EXT", TString::kIgnoreCase) && !EXT)
3842    //      cout << "Warning! EXT algorythm requested, but branches are missing"<<endl;;
3843                
3844    //     trkAlg = alg;
3845    
3846    // };
3847    // const char* PamLevel2::GetTrackingAlgorythm(){
3848    
3849    
3850    //     cout<<endl<<" Implemented tracking algorythm: ";
3851    //     cout<<endl<<"  \"\" or \"STD\"  --> take the output of the standard tracking algorythm";
3852    //     cout<<endl<<"  \"NUC\"      --> take the output of the standard tracking algorythm for nuclei cluster selection";
3853    //     cout<<endl<<"  \"EXT\"      --> in case the standard tracking algorythm has not found any track,";
3854    //     cout<<endl<<"                 take the output of the extended one";
3855    //     cout<<endl<<"  \"EXTF\"     --> force the extended tracking algorythm";
3856    //     cout<<endl<<"  \"NUCEXT\"   --> as \"EXT\", but for nuclei ";
3857    //     cout<<endl<<"  \"NUCEXTF\"  --> as \"EXTF\", but for nuclei";
3858    
3859    //     cout<<endl;
3860    //     cout<<" <<Currently set algorythm>> "<<trkAlg<<endl;
3861    //     cout<<endl;
3862    
3863    //     return trkAlg;
3864    // };
3865    
     TRK2    = TRK2 & t->GetBranchStatus("TrkLevel2");  
     TRK1    = TRK1 & t->GetBranchStatus("TrkLevel1");  
     TRKh    = TRKh & t->GetBranchStatus("TrkHough");  
     CAL1    = CAL1 & t->GetBranchStatus("CaloLevel1");  
     CAL2    = CAL2 & t->GetBranchStatus("CaloLevel2");  
     TOF    = TOF & t->GetBranchStatus("ToFLevel2");  
     TRG    = TRG & t->GetBranchStatus("TrigLevel2");  
     S4     = S4  & t->GetBranchStatus("S4Level2");  
     ND     = ND  & t->GetBranchStatus("NDLevel2");  
     AC     = AC  & t->GetBranchStatus("AcLevel2");  
     ORB    = ORB & t->GetBranchStatus("OrbitalInfo");  
   
     // Tracker  
      if(TRK2) {  
         t->SetBranchAddress("TrkLevel2", GetPointerTo("TrkLevel2"));  
         cout << "Tracker      : set branch address TrkLevel2"<<endl;  
     };  
     if(TRK1) {  
         t->SetBranchAddress("TrkLevel1", GetPointerTo("TrkLevel1"));  
         cout << "Tracker      : set branch address TrkLevel1"<<endl;  
     };  
      if(TRKh) {  
         t->SetBranchAddress("TrkHough", GetPointerTo("TrkHough"));  
         cout << "Tracker      : set branch address TrkHough"<<endl;  
      };  
       
     // Calorimeter  
     if(CAL2) {  
         t->SetBranchAddress("CaloLevel2", GetPointerTo("CaloLevel2"));  
         cout << "Calorimeter  : set branch address CaloLevel2"<<endl;  
     };    
     if(CAL1) {  
         t->SetBranchAddress("CaloLevel1", GetPointerTo("CaloLevel1"));  
         cout << "Calorimeter  : set branch address CaloLevel1"<<endl;  
     };  
       
     // ToF      
     if(TOF) {  
         t->SetBranchAddress("ToFLevel2", GetPointerTo("ToFLevel2"));  
         cout << "ToF          : set branch address ToFLevel2"<<endl;  
     };  
     // Trigger  
     if(TRG) {  
         t->SetBranchAddress("TrigLevel2", GetPointerTo("TrigLevel2"));  
         cout << "Trigger      : set branch address TrigLevel2"<<endl;  
     };  
     // S4  
     if(S4) {  
         t->SetBranchAddress("S4Level2", GetPointerTo("S4Level2"));  
         cout << "S4           : set branch address S4Level2"<<endl;  
     };  
     // Neutron Detector  
     if(ND) {  
         t->SetBranchAddress("NDLevel2", GetPointerTo("NDLevel2"));  
         cout << "NeutronD     : set branch address NDLevel2"<<endl;  
     };  
     // Anticounters  
     if(AC) {  
         t->SetBranchAddress("AcLevel2", GetPointerTo("AcLevel2"));  
         cout << "Anticounter  : set branch address AcLevel2"<<endl;  
     };  
     // OrbitalInfo  
     if(ORB) {  
         t->SetBranchAddress("OrbitalInfo", GetPointerTo("OrbitalInfo"));  
         cout << "OrbitalInfo  : set branch address OrbitalInfo"<<endl;  
     };  
     // SelectionList  
     if(SELLI==1) {  
         t->SetBranchAddress("RunEntry", &irun);  
         cout << "SelectionList: set branch address RunEntry"<<endl;  
         t->SetBranchAddress("EventEntry", &irunentry);  
         cout << "SelectionList: set branch address EventEntry"<<endl;  
     };  
       
 }  
3866    
3867    
3868  //--------------------------------------  //--------------------------------------
# Line 1774  void PamLevel2::SetBranchAddress(TChain Line 3871  void PamLevel2::SetBranchAddress(TChain
3871  //--------------------------------------  //--------------------------------------
3872  /**  /**
3873   * Get the Run tree chain from a list of files.   * Get the Run tree chain from a list of files.
3874   * @param fl Pointer to a TList of TSystemFiles   * @param fl Pointer to a TList of TSystemFiles
3875   * @return Pointer to a TChain   * @return Pointer to a TChain
3876   */   */
3877  TChain *PamLevel2::GetRunTree(TList *fl){  TChain *PamLevel2::GetRunTree(TList *fl) {
3878    //    //
3879    //    //
3880    //    //
3881    if ( run_tree ){    if (run_tree) {
3882      printf("WARNING: TChain *PamLevel2::GetRunTree(TList *fl) -- run_tree already exists!\n ");      printf("WARNING: TChain *PamLevel2::GetRunTree(TList *fl) -- run_tree already exists!\n ");
3883      return run_tree;      return run_tree;
3884    };        };
3885    //    //
3886    
3887    
3888    TChain *R = new TChain("Run");    TChain *R = new TChain("Run");
       
     // loop over files and create chains          
     TIter next(fl);  
     TSystemFile *questo = 0;  
     while ( (questo = (TSystemFile*) next()) ) {  
         TString name =  questo->GetName();  
 //              cout << "File: "<< name << endl;  
         if( CheckLevel2File(name) ){  
             R->Add(name);  
         };  
     }  
3889    
3890      if(R->GetNtrees()){    // loop over files and create chains
3891          TIter next(fl);
3892          R->SetBranchAddress("RunInfo", GetPointerTo("RunInfo"));    TSystemFile *questo = 0;
3893          cout << "Run         : set branch address RunInfo"<<endl;    while ((questo = (TSystemFile*) next())) {
3894          R->SetBranchAddress("SoftInfo", GetPointerTo("SoftInfo")); // Emiliano      TString name = questo->GetName();
3895          cout << "Software    : set branch address SoftInfo"<<endl; // Emiliano      //          cout << "File: "<< name << endl;
3896      }else{      if (CheckLevel2File(name)) {
3897          delete R;        R->Add(name);
3898          R=0;      };
3899      }
3900    
3901      cout << "done run chain  "<<  R->GetNtrees() <<" \n";
3902    
3903    
3904      if (RUN && R->GetNtrees()) {
3905    
3906        R->SetBranchAddress("RunInfo", GetPointerTo("RunInfo"));
3907        cout << "Run         : set branch address RunInfo" << endl;
3908        R->SetBranchAddress("SoftInfo", GetPointerTo("SoftInfo")); // Emiliano
3909        cout << "Software    : set branch address SoftInfo" << endl; // Emiliano
3910    
3911        irunoffset = new int[R->GetNtrees()];
3912        if (DBG) {
3913          cout << "----------------------------------------------------" << endl;
3914          cout << "irun\t | ";
3915          cout << "tree\t |";
3916          //        cout << "offset\t |";
3917          cout << "RUN\t";
3918          cout << "FRAG\t";
3919          cout << "NEVENTS\t";
3920          cout << "absolute time\t\t\t";
3921          cout << "on-board time";
3922          cout << endl;
3923        }
3924        for (Int_t ii = 0; ii < R->GetEntries(); ii++) {
3925          R->GetEntry(ii);
3926          if (DBG) {
3927            cout << ii << "\t | ";
3928            cout << R->GetTreeNumber() << "\t |";
3929            //          cout << R->GetChainOffset()<< "\t |";
3930            cout << GetRunInfo()->ID << "\t";
3931            cout << GetRunInfo()->ID_RUN_FRAG << "\t";
3932            cout << GetRunInfo()->NEVENTS << "\t";
3933            cout << GetRunInfo()->RUNHEADER_TIME << " <---> " << GetRunInfo()->RUNTRAILER_TIME << "\t";
3934            cout << GetRunInfo()->RUNHEADER_OBT << " <---> " << GetRunInfo()->RUNTRAILER_OBT << "\t";
3935            cout << endl;
3936          }
3937          irunoffset[R->GetTreeNumber()] = R->GetChainOffset();
3938      }      }
3939        cout << "N.run = " << R->GetEntries() << endl;
3940        cout << "----------------------------------------------------" << endl;
3941    
3942      }
3943    //   else {
3944    //     delete R;
3945    //     R = 0;
3946    //   }
3947    
3948      run_tree = R;    run_tree = R;
3949    
3950      return R;
3951    
     return R;  
       
3952  }  }
3953  //--------------------------------------  //--------------------------------------
3954  //  //
# Line 1821  TChain *PamLevel2::GetRunTree(TList *fl) Line 3956  TChain *PamLevel2::GetRunTree(TList *fl)
3956  //--------------------------------------  //--------------------------------------
3957  /**  /**
3958   * Get the Run tree  from a file.   * Get the Run tree  from a file.
3959   * @param f Pointer to a TFile   * @param f Pointer to a TFile
3960   * @return Pointer to a TTree   * @return Pointer to a TTree
3961   */   */
3962  TTree *PamLevel2::GetRunTree(TFile *f){  TTree *PamLevel2::GetRunTree(TFile *f) {
3963    if ( run_tree ){    if (run_tree) {
3964      printf("WARNING: TTree *PamLevel2::GetRunTree(TFile *f) -- run_tree already exists!\n ");      printf("WARNING: TTree *PamLevel2::GetRunTree(TFile *f) -- run_tree already exists!\n ");
3965      return run_tree;      return run_tree;
3966    };    };
           
3967    
3968      cout << "TTree *PamLevel2::GetRunTree(TFile *f) -- obsolte "<<endl;    cout << "TTree *PamLevel2::GetRunTree(TFile *f) -- obsolte " << endl;
3969    
3970      TTree *T = (TTree*)f->Get("Run");    TTree *T = (TTree*) f->Get("Run");
       
     if(T){  
         T->SetBranchAddress("RunInfo", GetPointerTo("RunInfo"));  
         cout << "Run         : set branch address RunInfo"<<endl;  
         T->SetBranchAddress("SoftInfo", GetPointerTo("SoftInfo")); // Emiliano  
         cout << "Software    : set branch address SoftInfo"<<endl; // Emiliano  
     }  
3971    
3972      run_tree = (TChain*)T;    if (T) {
3973        T->SetBranchAddress("RunInfo", GetPointerTo("RunInfo"));
3974        cout << "Run         : set branch address RunInfo" << endl;
3975        T->SetBranchAddress("SoftInfo", GetPointerTo("SoftInfo")); // Emiliano
3976        cout << "Software    : set branch address SoftInfo" << endl; // Emiliano
3977    
3978      }
3979    
3980      run_tree = (TChain*) T;
3981    
3982      return T;
3983    
     return T;  
       
3984  }  }
3985  /**  
3986   * Update the runinfo informations (to be used to have Run infos event by event basis)  Bool_t PamLevel2::UpdateRunInfo(Long64_t iev) {
3987   * @param run Pointer to the chain/tree which contains run infos  
3988   * @return true if a new run has been read, false if it is still the same run    if (DBG) printf("PamLevel2::UpdateRunInfo(Long64_t) - inside\n");
3989   */  
3990  Bool_t PamLevel2::UpdateRunInfo(TChain *run, Long64_t iev){    if (!run_tree) {
3991    //      cout << " Bool_t PamLevel2::UpdateRunInfo(ULong64_t iev) -- ERROR -- run tree not loaded" << endl;
3992    // check if we have already called once GetEntry, if not call it      return false;
3993    //    }
3994      cout << "Bool_t PamLevel2::UpdateRunInfo(TChain *run, Long64_t iev) --- NON FUNZIONA BENISSIMO.... "<<endl;    if (run_tree->GetEntries() <= 0) {
3995      if(!run){      cout << " Bool_t PamLevel2::UpdateRunInfo(ULong64_t iev) -- ERROR -- run tree is empty" << endl;
3996            cout << "Bool_t PamLevel2::UpdateRunInfo(TChain *run, ULong64_t iev) -- ERROR -- missing RunInfo tree "<<endl;      return (false);
3997            return(false);            }
3998    
3999    
4000      Int_t oldrun = irun; // store current run index
4001    
4002      // -----------------------------------------------------------------------
4003      // the first time the routine is called, set run search from the beginning
4004      // -----------------------------------------------------------------------
4005    
4006      if (irun < 0) {
4007        irun = 0LL;
4008        irunt = 0LL;
4009        totrunentry = 0LL;
4010        totrunentrymin = 0LL;
4011        totrunentrymax = 0LL;
4012        irunentry = 0LL;
4013        il0entry = 0LL;
4014        prevshift = 0;
4015        yprevshift = 0;
4016        prevabstime = 0;
4017        prevpktnum = 0;
4018        abstime = 0ULL;
4019        pktnum = 0;
4020        isFragment = false;
4021        run_tree->GetEntry(irun);
4022        if (!GetOrbitalInfo())
4023          cout << "** WARNING ** missing OrbitalInfo ---> run info might be not correctly updated " << endl;
4024        if ( fUseDBinRunInfo ){
4025          if (gltsync)
4026            delete gltsync; //Emiliano
4027          if (!dbc || (dbc && !dbc->IsConnected()))
4028            SetDBConnection(); //Emiliano
4029          gltsync = new GL_TIMESYNC(GetRunInfo()->ID_ROOT_L0, "ID", dbc, false); //Emiliano // the "false" means not to use level0 file (not necessary here)
4030          if (dbc){
4031            dbc->Close();// Emiliano
4032            delete dbc;
4033            dbc=0;
4034          }
4035      }      }
4036      if ( run->GetEntries() <= 0 ) return(false);    }
4037    //    // ---------------------------------------------------------------
4038        // retrieve OBT and absolute time of the event
4039    //  Int_t oldrun = irun;    // ---------------------------------------------------------------
4040    Long64_t oldrun = irun;    Long64_t obt = 0LL; // Emiliano, Long64_t GL_TIMESYNC::DBobt(UInt_t obt) since depending on the situation OBT is lowered or boosted
4041      prevabstime = abstime;
4042      prevpktnum = pktnum;
4043      if (GetOrbitalInfo()) {
4044        abstime = GetOrbitalInfo()->absTime;
4045        if ( fUseDBinRunInfo ) obt = gltsync->DBobt(GetOrbitalInfo()->OBT); // Emiliano
4046        pktnum = GetOrbitalInfo()->pkt_num; // Emiliano
4047      }
4048      else {
4049        abstime = GetRunInfo()->RUNHEADER_TIME;
4050        if ( fUseDBinRunInfo ) obt = gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT); // Emiliano
4051        pktnum = GetRunInfo()->RUNHEADER_PKT; // Emiliano
4052      }
4053    
4054    // --------------------------------------    if (DBG){
4055        printf("0abstime %lld %lld pktnum %d %d obt %lld \n",abstime,prevabstime,pktnum,prevpktnum,obt);
4056        printf("0        rth %d %d nevents %d  \n",GetRunInfo()->RUNHEADER_TIME,GetRunInfo()->RUNTRAILER_TIME,GetRunInfo()->NEVENTS);
4057        printf("0        rto %d %d \n",GetRunInfo()->RUNHEADER_OBT,GetRunInfo()->RUNTRAILER_OBT);
4058        if ( fUseDBinRunInfo ) printf("0        rto2 %lld %lld \n",gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT),gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT));
4059        printf("0        bo irunentry %lld prevshift %lld irun %lld  \n",irunentry,prevshift,irun);
4060        printf("0        min %lld iev %lld max %lld tot %lld \n",totrunentrymin,iev,totrunentrymax,totrunentry);
4061      }
4062    
4063      // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
4064    // if it is a full file (not preselected)    // if it is a full file (not preselected)
4065    // --------------------------------------    // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
4066    if(SELLI==0){    if (SELLI == 0 || SELLI == 2) { // Emiliano
4067    
4068        //      // ---------------------------------------------------------------
4069        // the absolute time is necessary to relate the event with the run      // increment dead and live-time counters
4070        //      // (only when reading a file not preselected)
4071        if( !GetOrbitalInfo() ){      // ---------------------------------------------------------------
4072            cout << "Bool_t PamLevel2::UpdateRunInfo(TChain *run, ULong64_t iev) -- ERROR -- missing OrbitalInfo "<<endl;      if (SELLI == 0) {
4073            return(false);        if (GetTrigLevel2()) {
4074            totdltime[0] += GetTrigLevel2()->dltime[0];
4075            totdltime[1] += GetTrigLevel2()->dltime[1];
4076        }        }
4077          totdltime[2]++;
4078        }
4079    
4080        //      //
4081        // the first time the routine is called, set run search from the beginning      bool a = true;
4082        //      bool b = true;
4083        if ( irun < 0LL ){      if ( fUseDBinRunInfo ){
4084            irun = 0LL;        a = false;    
4085            run->GetEntry(irun);        b = false;
4086            runfirstentry = 0LL;        if ( obt < gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT) ) a = true;
4087            runlastentry += (Long64_t)(this->GetRunInfo()->NEVENTS);        if ( obt > gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT) ) b = true;
4088            if ( (Long64_t)(this->GetRunInfo()->NEVENTS) > 0LL ) runlastentry -= 1LL;      }
4089        };            if ( iev < totrunentrymin || iev > totrunentrymax // entry is outside run limits
4090        //           || iev == 0 // or it is the first entry
4091         if ( irun == run->GetEntries()-1LL &&           || (!isSync && (
4092             !(GetOrbitalInfo()->absTime >= GetRunInfo()->RUNHEADER_TIME &&                           (abstime <= GetRunInfo()->RUNHEADER_TIME && a ) // or it is outside obt limits (and abstime limits for security reasons)
4093               GetOrbitalInfo()->absTime <= GetRunInfo()->RUNTRAILER_TIME)                           || (abstime >= GetRunInfo()->RUNTRAILER_TIME && b ) ))// or it is outside obt limits (and abstime limits for security reasons)
4094              ){           ){ // check on abstime and obt needed to handle nested+DV_skipped packets
4095           irun = -1LL;        
4096           runfirstentry = 0LL;        // check for a new run (ma prima il primo!)
4097           runlastentry = -1LL;        if (DBG){
4098         };          printf("1abstime %lld %lld pktnum %d %d obt %lld \n",abstime,prevabstime,pktnum,prevpktnum,obt);
4099        // modificato il controllo sull'aggiornamento del run, per evitare problemi          printf("1        rth %d %d nevents %d  \n",GetRunInfo()->RUNHEADER_TIME,GetRunInfo()->RUNTRAILER_TIME,GetRunInfo()->NEVENTS);
4100        // dovuti agli eventi annidati (NB! NEVENTS conta anche questi!!)          printf("1        rto %d %d \n",GetRunInfo()->RUNHEADER_OBT,GetRunInfo()->RUNTRAILER_OBT);
4101        //          if ( fUseDBinRunInfo ) printf("1        rto2 %lld %lld \n",gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT),gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT));
4102        bool fromfirst = true;          printf("1        bo irunentry %lld prevshift %lld irun %lld  \n",irunentry,prevshift,irun);
4103        //          printf("1        min %lld iev %lld max %lld tot %lld \n",totrunentrymin,iev,totrunentrymax,totrunentry);
       while ( !(GetOrbitalInfo()->absTime >= GetRunInfo()->RUNHEADER_TIME && GetOrbitalInfo()->absTime <= GetRunInfo()->RUNTRAILER_TIME) && irun < run->GetEntries()-1LL ){  
 //      while ( iev > (runfirstentry+(ULong64_t)(this->GetRunInfo()->NEVENTS-1)) && irun < run->GetEntries() ){  
           irun++;  
           run->GetEntry(irun);  
           runfirstentry = runlastentry;  
           if ( (Long64_t)(this->GetRunInfo()->NEVENTS) > 0LL ) runfirstentry += 1LL;  
           runlastentry += (Long64_t)(this->GetRunInfo()->NEVENTS);  
 //        cout << " ))))) UPDATE RUN INFO (((((  @iev "<<iev<<" run "<<GetRunInfo()->ID<<" irun "<<irun<<endl;  
 //        cout << "runfirstentry "<<runfirstentry<<endl;  
           //      printf(" iev %llu %u %llu \n",iev,this->GetRunInfo()->NEVENTS,(ULong64_t)(runfirstentry+(ULong64_t)(this->GetRunInfo()->NEVENTS)));  
           //      printf(" abstime %u trailertime %u \n",GetOrbitalInfo()->absTime,GetRunInfo()->RUNTRAILER_TIME);  
           //      printf(" IDRUN %u \n",GetRunInfo()->ID);  
           //  
 //        prevshift = 0;  
           //  
           if ( irun == (Long64_t)(run->GetEntries()-1LL) && fromfirst && !(GetOrbitalInfo()->absTime >= GetRunInfo()->RUNHEADER_TIME && GetOrbitalInfo()->absTime <= GetRunInfo()->RUNTRAILER_TIME)){  
               printf(" resetting irun  (it should NOT happen!!!)\n");  
               fromfirst = false;  
               irun = 0;  
               run->GetEntry(irun);  
               runfirstentry = 0ULL;  
               runlastentry += (Long64_t)(this->GetRunInfo()->NEVENTS);  
               if ( (Long64_t)(this->GetRunInfo()->NEVENTS) > 0LL ) runlastentry -= 1LL;  
           };  
           //  
       };  
       //  
       if (  
            !(GetOrbitalInfo()->absTime >= GetRunInfo()->RUNHEADER_TIME &&  
              GetOrbitalInfo()->absTime <= GetRunInfo()->RUNTRAILER_TIME)  
           ) {  
           printf(" Something very wrong here: cannot find RUN containing absolute time %u \n",GetOrbitalInfo()->absTime);  
           return false;  
4104        }        }
4105        //        //        printf("1abstime %lld %lld pktnum %d %d obt %lld \n",abstime,prevabstime,pktnum,prevpktnum,obt);
4106        if ( irun == oldrun || irun >= run->GetEntries() ) return(false);        //        printf("1        rth %d %d nevents %d  \n",GetRunInfo()->RUNHEADER_TIME,GetRunInfo()->RUNTRAILER_TIME,GetRunInfo()->NEVENTS);
4107        //        //        printf("1        rto %d %d \n",GetRunInfo()->RUNHEADER_OBT,GetRunInfo()->RUNTRAILER_OBT);
4108        //  printf(" iev %llu irun %i nevents %u 1st %llu last %llu \n",iev,irun,this->GetRunInfo()->NEVENTS,(ULong64_t)runfirstentry,(ULong64_t)runlastentry);        //        printf("1        rto2 %lld %lld \n",gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT),gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT));
4109        //        //        printf("1        bo irunentry %lld prevshift %lld irun %lld  \n",irunentry,prevshift,irun);
4110        prevshift = 0;        //        printf("1        min %lld iev %lld max %lld tot %lld \n",totrunentrymin,iev,totrunentrymax,totrunentry);//TOGLITOGLI
4111        cout << " ))))) UPDATE RUN INFO (((((  @iev "<<iev<<" run "<<GetRunInfo()->ID<<" irun "<<irun<<endl;  
4112  //      cout << "runfirstentry "<<runfirstentry<<endl;        totrunentry = 0LL;
4113        return(true);            runfirstentry = 0LL;
4114    };        for (Int_t r=0; r< run_tree->GetEntries();r++){
4115    // ----------------------------------------------------          // -------------------------------------------------------------------
4116            // save the index of the first entry of the run, relative to pam_tree,
4117            // and read a new run
4118            // -------------------------------------------------------------------
4119            run_tree->GetEntry(r);//update runinfo
4120            if ( r > 0 ){
4121              totrunentrymin = totrunentrymax+1;
4122            } else {
4123              totrunentrymin = 0LL;
4124            }
4125            totrunentry += GetRunInfo()->NEVENTS;
4126            totrunentrymax = totrunentry - 1 - prevshift; // prevshift is needed to handle nested+DV_skipped packets
4127            irun = r;        
4128            if ( fUseDBinRunInfo ){
4129              a = false;    
4130              b = false;
4131              if ( obt < gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT) ) a = true;
4132              if ( obt > gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT) ) b = true;
4133            }
4134            if ( (iev >= totrunentrymin && iev <= totrunentrymax) || // entry is inside run limits
4135                 ( !isSync &&
4136                   ( abstime >= GetRunInfo()->RUNHEADER_TIME  && a // or it is inside obt limits (and abstime limits for security reasons)
4137                     && abstime <= GetRunInfo()->RUNTRAILER_TIME && b))  // or it is inside obt limits (and abstime limits for security reasons)
4138                 ){ // check on abstime and obt needed to handle nested+DV_skipped packets
4139              if ( totrunentrymin > iev ){ // there is a shift (nested+DV_skipped packets)
4140                if ( !isSync ){
4141                  if (DBG) printf("PamLevel2::UpdateRunInfo(Long64_t) - unconsistent iev - nevents, probable DBL0-L2 async\n");
4142                  if (DBG) printf("PamLevel2::UpdateRunInfo(Long64_t) - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);
4143                  //              printf("PamLevel2::UpdateRunInfo(Long64_t) - unconsistent iev - nevents, probable DBL0-L2 async\n");
4144                  //              printf("PamLevel2::UpdateRunInfo(Long64_t) - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);//TOGLITOGLI
4145                  prevshift += (totrunentrymin-iev); // add the new shift to total shift
4146                  totrunentrymin -= (totrunentrymin-iev); // shift run position min
4147                  totrunentrymax -= (totrunentrymin-iev); // shift run position max
4148                  if (DBG) printf("PamLevel2::UpdateRunInfo(Long64_t) - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);
4149                  //              printf("PamLevel2::UpdateRunInfo(Long64_t) - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);//TOGLITOGLI
4150                } else {
4151                  printf(" PamLevel2::UpdateRunInfo(Long64_t) ERROR! sync file but unconsistent totrunetrymin %lld and iev %lld!!! \n",totrunentrymin,iev);
4152                  cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
4153                  cout << "\nFor bug reporting instructions, please see for example:\n";
4154                  cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
4155                  cout << "  " << endl;
4156                }
4157              }
4158              runfirstentry = totrunentrymin; // first entry of the run in the level2
4159              
4160    
4161              //
4162              if ( fUseDBinRunInfo ){
4163                if (gltsync)
4164                  delete gltsync; // Emiliano
4165                if (!dbc || (dbc && !dbc->IsConnected()))
4166                  SetDBConnection(); //Emiliano
4167                gltsync = new GL_TIMESYNC(GetRunInfo()->ID_ROOT_L0, "ID", dbc, false); // Emiliano
4168                TrkParams::Set(GetRunInfo(), dbc);
4169                if (dbc){
4170                  dbc->Close(); // Emiliano
4171                  delete dbc;
4172                  dbc=0;
4173                }          
4174                if (gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT) > gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT)) { // Emiliano
4175                  cout << "Bool_t PamLevel2::UpdateRunInfo(Long64_t iev) -- WARNING -- irun " << irun
4176                       << "  has RUNHEADER_OBT>=RUNTRAILER_OBT " << endl;
4177                  cout
4178                    << "                                                            (NB!! in this case some events could be assigned to a wrong run)"
4179                    << endl;
4180                }
4181              }
4182              //
4183              if (DBG) printf(" found \n");
4184              //          printf(" found \n");//TOGLITOGLI
4185              //
4186              break;
4187            }
4188          } // loop over run
4189          
4190          // --------------------------------------
4191          // if there was no need to update the run
4192          // ---> exit with FALSE
4193          // --------------------------------------
4194          if (irun == oldrun){
4195            if (DBG) printf(" no new run \n");
4196            //        printf(" no new run \n");//TOGLITOGLI
4197            return (false);
4198          }      
4199          // --------------------------------------
4200          // ... otherwise
4201          // ---> exit with TRUE
4202          // --------------------------------------
4203    
4204          if (SELLI != 2) {
4205            /// decrement counters since this event belongs to a new run
4206            if (GetTrigLevel2()) {
4207              totdltime[0] -= GetTrigLevel2()->dltime[0];//live-time
4208              totdltime[1] -= GetTrigLevel2()->dltime[1];//dead-time
4209            }
4210            totdltime[2]--; //event counter
4211            if (DBG) {
4212              cout << endl;
4213              cout << "n.events     : " << totdltime[2] << endl;
4214              cout << "RUN LIVE-TIME: " << totdltime[0] * 0.16 << " ms" << endl;
4215              cout << "RUN DEAD-TIME: " << totdltime[1] * 0.01 << " ms" << endl;
4216            }
4217            // add an entry
4218            if (run_tree_clone && totdltime[2] > 0)
4219              if (run_tree_clone->GetBranch("DeadLiveTime")->GetEntries() < run_tree->GetEntries())
4220                run_tree_clone->GetBranch("DeadLiveTime")->Fill();
4221            // reset counters
4222            if ( totdltime[2] > 0 ){
4223              if (GetTrigLevel2()) {
4224                totdltime[0] = GetTrigLevel2()->dltime[0];//live-time
4225                totdltime[1] = 0; //dead-time
4226              }
4227              totdltime[2] = 1; //event counter
4228            }
4229          }
4230    
4231          if (DBG){
4232            cout << endl << " ))))) UPDATE RUN INFO (((((  @iev " << iev << " run " << GetRunInfo()->ID << " irun " << irun
4233                 << endl;        
4234            printf("2abstime %lld %lld pktnum %d %d obt %lld \n",abstime,prevabstime,pktnum,prevpktnum,obt);
4235            printf("2        rth %d %d nevents %d  \n",GetRunInfo()->RUNHEADER_TIME,GetRunInfo()->RUNTRAILER_TIME,GetRunInfo()->NEVENTS);
4236            printf("2        rto %d %d \n",GetRunInfo()->RUNHEADER_OBT,GetRunInfo()->RUNTRAILER_OBT);
4237            if ( fUseDBinRunInfo ) printf("2        rto2 %lld %lld \n",gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT),gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT));
4238            printf("2        bo irunentry %lld prevshift %lld irun %lld  \n",irunentry,prevshift,irun);
4239            printf("2        min %lld iev %lld max %lld tot %lld \n",totrunentrymin,iev,totrunentrymax,totrunentry);
4240          }
4241          //        printf("2abstime %lld %lld pktnum %d %d obt %lld \n",abstime,prevabstime,pktnum,prevpktnum,obt);
4242          //        printf("2        rth %d %d nevents %d  \n",GetRunInfo()->RUNHEADER_TIME,GetRunInfo()->RUNTRAILER_TIME,GetRunInfo()->NEVENTS);
4243          //        printf("2        rto %d %d \n",GetRunInfo()->RUNHEADER_OBT,GetRunInfo()->RUNTRAILER_OBT);
4244          //        printf("2        rto2 %lld %lld \n",gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT),gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT));
4245          //        printf("2        bo irunentry %lld prevshift %lld irun %lld  \n",irunentry,prevshift,irun);
4246          //        printf("2        min %lld iev %lld max %lld tot %lld \n",totrunentrymin,iev,totrunentrymax,totrunentry);//TOGLITOGLI
4247    
4248          return (true);
4249        } // need for run upgrade
4250        if (DBG) printf("return false\n");
4251        return (false);
4252      }// SELLI = 0 SELLI = 2
4253      
4254      // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
4255    // if it is a preselected file (there is SelectionList)    // if it is a preselected file (there is SelectionList)
4256    // NBNB - the event tree MUST be read first    // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
4257    // ----------------------------------------------------    // irun  = run entry relative to the chain
4258    if(SELLI==1){          // irunt = run entry relative to the tree
4259        sel_tree->GetEntry(iev);    if (SELLI == 1) {
4260  //      cout << irun << " "<< irunentry << endl;      sel_tree->GetEntry(iev);// read irunt from SelectionList
4261        if(irun != oldrun){      irun = irunt + irunoffset[sel_tree->GetTreeNumber()];//NEWNEW
4262            run->GetEntry(irun);      if (irun != oldrun) {
4263            cout << " ))))) UPDATE RUN INFO (((((  @iev "<<iev<<" run "<<GetRunInfo()->ID<<" irun "<<irun<<endl;        if (irun < run_tree->GetEntries())
4264            prevshift = 0;          run_tree->GetEntry(irun);
4265            return true;        // check if the time is ok (with merged files it is not...)
4266          // if not loop over run and look for the proper entry
4267          bool SECONDO_GIRO = false;
4268          //            Long64_t irun_start   = irun;
4269          int offset_start = irunoffset[sel_tree->GetTreeNumber()];
4270          while (((!(abstime >= GetRunInfo()->RUNHEADER_TIME && // check on absolute time (s)
4271              abstime <= GetRunInfo()->RUNTRAILER_TIME)
4272          //                        ||
4273          //                        !(obt >= GetRunInfo()->RUNHEADER_OBT &&         // additional check on OBT (ms)
4274          //                          obt <= GetRunInfo()->RUNTRAILER_OBT)
4275          ) || GetRunInfo()->NEVENTS == 0)
4276          //                && irun < run_tree->GetEntries()
4277          ) {
4278    
4279            if (DBG) {
4280              cout << " (test) ";
4281              cout << " tree " << sel_tree->GetTreeNumber();
4282              cout << " irunt " << irunt;
4283              cout << " offset " << irunoffset[sel_tree->GetTreeNumber()];
4284              cout << " abs " << abstime;
4285              cout << " >> " << GetRunInfo()->RUNHEADER_TIME << " " << GetRunInfo()->RUNTRAILER_TIME;
4286              cout << " obt " << obt;
4287              cout << " >> " << GetRunInfo()->RUNHEADER_OBT << " " << GetRunInfo()->RUNTRAILER_OBT;
4288              cout << " *** JUMP RUN *** irun " << irun;
4289              cout << endl;
4290            }
4291            //              irun++;
4292            irunoffset[sel_tree->GetTreeNumber()]++;
4293            irun = irunt + irunoffset[sel_tree->GetTreeNumber()];//NEWNEW
4294            if (irun == run_tree->GetEntries() && SECONDO_GIRO) {
4295              //            if(irun == irun_start ){
4296              cout << " ...grrrvzzkhhhajsdkj!!!! " << endl;
4297              irunoffset[sel_tree->GetTreeNumber()] = offset_start;
4298              return false;
4299            }
4300            if (irun >= run_tree->GetEntries() || irun < 0) {
4301              cout << "irun = " << irun << " >>  search from the beginning... <<" << endl;
4302              SECONDO_GIRO = true;
4303              irun = 0;
4304              irunoffset[sel_tree->GetTreeNumber()] = -irunt;
4305            }
4306            run_tree->GetEntry(irun);
4307          }
4308    
4309          if (DBG) {
4310            cout << " (test) ";
4311            cout << " tree " << sel_tree->GetTreeNumber();
4312            cout << " irunt " << irunt;
4313            cout << " offset " << irunoffset[sel_tree->GetTreeNumber()];
4314            cout << " abs " << abstime;
4315            cout << " >> " << GetRunInfo()->RUNHEADER_TIME << " " << GetRunInfo()->RUNTRAILER_TIME;
4316            cout << " obt " << obt;
4317            cout << " >> " << GetRunInfo()->RUNHEADER_OBT << " " << GetRunInfo()->RUNTRAILER_OBT;
4318          }
4319          if (DBG)
4320            cout << endl;
4321          if (DBG)
4322            cout << endl << " ))))) UPDATE RUN INFO (((((  @iev " << iev << " run " << GetRunInfo()->ID << " (run-entry "
4323                << irun << ")" << endl;
4324          // ----------------------------------------------------
4325          // update the tracker parameters
4326          // (non ho trovato nessun altro modo sicuro di farlo...)
4327          // ----------------------------------------------------
4328          if ( fUseDBinRunInfo ){
4329            if (!dbc || (dbc && !dbc->IsConnected()))
4330              SetDBConnection();
4331            TrkParams::Set(GetRunInfo(), dbc);
4332            if (dbc){
4333              dbc->Close();
4334              delete dbc;
4335              dbc=0;
4336            }
4337        }        }
4338        return false;        //            cout << endl;
4339          prevshift = 0;
4340          yprevshift = 0;
4341          return true;
4342        }
4343        return false;
4344    }    }
4345    
4346    return false;    return false;
4347    //    //
4348  };  }
   
 Bool_t PamLevel2::UpdateRunInfo(Long64_t iev){  
   
     if(!run_tree){  
         cout << " Bool_t PamLevel2::UpdateRunInfo(ULong64_t iev) -- ERROR -- run tree not loaded"<<endl;  
         return false;  
     }  
     if ( run_tree->GetEntries() <= 0 ) {  
         cout << " Bool_t PamLevel2::UpdateRunInfo(ULong64_t iev) -- ERROR -- run tree is empty"<<endl;  
         return(false);  
     }  
     
     Int_t oldrun = irun; // store current run index  
4349    
4350      // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-  /**
4351      // if it is a full file (not preselected)   * Update the runinfo informations (to be used to have Run infos event by event basis)
4352      // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-   * @param run Pointer to the chain/tree which contains run infos
4353      if(SELLI==0){   * @return true if a new run has been read, false if it is still the same run
4354     */
4355          // ---------------------------------------------------------------  Bool_t PamLevel2::UpdateRunInfo(TChain *run, Long64_t iev) {
4356          // the absolute time is necessary to relate the event with the run    return (UpdateRunInfo(iev));
4357          // ---------------------------------------------------------------  }
         if( !GetOrbitalInfo() ){  
             cout << "Bool_t PamLevel2::UpdateRunInfo(Long64_t iev) -- ERROR -- missing OrbitalInfo "<<endl;  
             return(false);  
         }  
         
         // -----------------------------------------------------------------------  
         // the first time the routine is called, set run search from the beginning  
         // -----------------------------------------------------------------------  
         if ( irun < 0 ){  
             irun = 0LL;  
             irunentry = 0;  
             prevshift = 0;  
             run_tree->GetEntry(irun);  
         };        
         //  
         bool fromfirst = true; // first loop over runs  
   
 //      Bool_t hasfrag = false;  
 //      if( GetRunInfo()->ID_RUN_FRAG!=0 && GetRunInfo()->ID_RUN_FRAG != GetRunInfo()->ID)hasfrag=true;  
 //      ULong64_t fragid = GetRunInfo()->ID_RUN_FRAG;  
   
         // ------------------------------------------------------  
         // loop over runs to find the one that contains the event  
         // ------------------------------------------------------  
         while (  
             (  
                 (  
                     !(GetOrbitalInfo()->absTime >= GetRunInfo()->RUNHEADER_TIME &&    // check on absolute time (s)  
                       GetOrbitalInfo()->absTime <= GetRunInfo()->RUNTRAILER_TIME) &&  
                     !(GetOrbitalInfo()->OBT >= GetRunInfo()->RUNHEADER_OBT &&         // additional check on OBT (ms)  
                       GetOrbitalInfo()->OBT <= GetRunInfo()->RUNTRAILER_OBT)  
                     )  
                 || GetRunInfo()->NEVENTS==0  
                 || !(irunentry < GetRunInfo()->NEVENTS-1-prevshift)  
                 )  
                 && irun < run_tree->GetEntries() ){  
   
             irun++;  
             // ------------------------------------  
             // if the end of run tree is reached...  
             // ------------------------------------  
             if( irun == run_tree->GetEntries() ){  
                 if(!fromfirst){  
                     // -----------------------------------------------------  
                     // if it happened already once and the run was not found  
                     // ---> exit with error  
                     // -----------------------------------------------------  
                     cout << "Bool_t PamLevel2::UpdateRunInfo(Long64_t iev) -- ERROR -- event entry #"<<iev<<" does not belong to any run (should not happen)" <<endl;  
                     return false;  
                 }  
                 // -----------------------------------------  
                 // ...otherwise repeat search from beginning  
                 // -----------------------------------------  
                 cout << "Bool_t PamLevel2::UpdateRunInfo(Long64_t iev) -- WARNING -- reached end of run tree. searchin again from beginning " <<endl;  
                 fromfirst = false;  
                 irun = 0LL;  
                 runfirstentry = 0LL;  
             }  
             // -------------------------------------------------------------------  
             // save the index of the first entry of the run, relative to pam_tree,  
             // and read a new run  
             // -------------------------------------------------------------------  
             if(irun>0)runfirstentry += (GetRunInfo()->NEVENTS)-prevshift;  
             irunentry = 0;  
             prevshift = 0;  
             run_tree->GetEntry(irun);        
             if(GetRunInfo()->RUNHEADER_OBT>GetRunInfo()->RUNTRAILER_OBT ){  
                 cout << "Bool_t PamLevel2::UpdateRunInfo(Long64_t iev) -- WARNING -- irun "<<irun<<"  has RUNHEADER_OBT>=RUNTRAILER_OBT " <<endl;  
                 cout << "                                                            (NB!! in this case some events are assigned to a wrong run)"<<endl;  
             }  
 //          if(hasfrag &&  fragid != GetRunInfo()->ID){  
 //              cout << "... where is the next fragment ??"<<endl;  
 //          }  
         };  
   
   
         // --------------------------------------  
         // if there was no need to update the run  
         // ---> exit with FALSE  
         // --------------------------------------  
         if ( irun == oldrun ) return(false);  
   
         // --------------------------------------  
         // ... otherwise  
         // ---> exit with TRUE  
         // --------------------------------------  
         cout << endl << " ))))) UPDATE RUN INFO (((((  @iev "<<iev<<" run "<<GetRunInfo()->ID<<" irun "<<irun<<endl;  
         // ----------------------------------------------------  
         // then check if the run has a fragment  
         // in this case we have to switch to the next fragment  
         // when the end of the first fragment is reached  
         // ----------------------------------------------------  
         if(  
             GetRunInfo()->ID_RUN_FRAG != 0 &&  
 //          GetRunInfo()->ID_RUN_FRAG != GetRunInfo()->ID &&  
             true ){  
             cout << "* fragment *"<<endl;                
         }  
           
         return(true);      
     };  
     // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-  
     // if it is a preselected file (there is SelectionList)  
     // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-  
     if(SELLI==1){        
         sel_tree->GetEntry(iev);  
         if(irun != oldrun){  
             run_tree->GetEntry(irun);  
             cout << endl << " ))))) UPDATE RUN INFO (((((  @iev "<<iev<<" run "<<GetRunInfo()->ID<<" irun "<<irun<<endl;  
             prevshift = 0;  
             return true;  
         }  
         return false;  
     }  
4358    
     return false;  
     //  
 };  
4359  /**  /**
4360   * Update the runinfo informations (to be used to have Run infos event by event basis)   * Update the runinfo informations (to be used to have Run infos event by event basis)
4361   * @param run Pointer to the chain/tree which contains run infos   * @param run Pointer to the chain/tree which contains run infos
4362   * @return true if a new run has been read, false if it is still the same run   * @return true if a new run has been read, false if it is still the same run
4363   */   */
4364  Bool_t PamLevel2::UpdateRunInfo(TTree *run, Long64_t iev){  Bool_t PamLevel2::UpdateRunInfo(TTree *run, Long64_t iev) {
4365    return(UpdateRunInfo((TChain*)run,iev));    return (UpdateRunInfo((TChain*) run, iev));
4366  };  }
4367    
4368    
4369  //--------------------------------------  //--------------------------------------
4370  //  //
# Line 2122  Bool_t PamLevel2::UpdateRunInfo(TTree *r Line 4372  Bool_t PamLevel2::UpdateRunInfo(TTree *r
4372  //--------------------------------------  //--------------------------------------
4373  /**  /**
4374   * Set which trees shoul be analysed   * Set which trees shoul be analysed
4375   * @param detlist TString containing the sequence of trees required   * @param detlist TString containing the sequence of trees required
4376  */   */
4377  void PamLevel2::SetWhichTrees(TString detlist){  void PamLevel2::SetWhichTrees(TString detlist) {
           
     if(detlist.IsNull() || detlist.Contains("+ALL", TString::kIgnoreCase)){  
         CAL0 = false;  
         CAL1 = true;  
         CAL2 = true;  
         TRK2 = true;  
         TRK1 = false;  
         TRKh = false;  
         TRK0 = false;  
         TRG = true;  
         TOF = true;  
         TOF0 = false;  
         S4  = true;  
         ND  = true;  
         AC  = true;  
         ORB = true;  
     }else if( detlist.Contains("-ALL", TString::kIgnoreCase) ){  
         CAL0 = false;  
         CAL1 = false;  
         CAL2 = false;  
         TRK2 = false;  
         TRK1 = false;  
         TRKh = false;  
         TRK0 = false;  
         TRG = false;  
         TOF = false;  
         TOF0 = false;  
         S4  = false;  
         ND  = false;  
         AC  = false;  
         ORB = false;  
     };  
       
 //  -------------------------------------------------------------------------  
     if( detlist.Contains("CAL1", TString::kIgnoreCase) ){  
         if ( detlist.Contains("-CAL1", TString::kIgnoreCase) )CAL1=false;  
         if ( detlist.Contains("+CAL1", TString::kIgnoreCase) )CAL1=true;  
     };  
4378    
4379      if( detlist.Contains("CAL0", TString::kIgnoreCase) ){    //    if(detlist.IsNull() || detlist.Contains("+ALL", TString::kIgnoreCase)){
4380          if ( detlist.Contains("-CAL0", TString::kIgnoreCase) )CAL0=false;    if (detlist.Contains("+ALL", TString::kIgnoreCase)) {
         if ( detlist.Contains("+CAL0", TString::kIgnoreCase) )CAL0=true;  
     };  
           
     if( detlist.Contains("CAL2", TString::kIgnoreCase)){  
         if ( detlist.Contains("-CAL2", TString::kIgnoreCase) )CAL2=false;  
         if ( detlist.Contains("+CAL2", TString::kIgnoreCase) )CAL2=true;  
     };  
           
     if( detlist.Contains("+CAL", TString::kIgnoreCase) && !CAL1 && !CAL2 )CAL2=true;  
     if( detlist.Contains("-CAL", TString::kIgnoreCase) && CAL1 && CAL2 ){  
         CAL2=false;  
         CAL1=false;  
     }  
 //  -------------------------------------------------------------------------  
     if( detlist.Contains("TRK0", TString::kIgnoreCase) ){  
         if ( detlist.Contains("-TRK0", TString::kIgnoreCase) )TRK0=false;  
         if ( detlist.Contains("+TRK0", TString::kIgnoreCase) )TRK0=true;  
     };  
4381    
4382      if( detlist.Contains("TRK1", TString::kIgnoreCase) ){      cout << " ======================================================== " << endl;
4383          if ( detlist.Contains("-TRK1", TString::kIgnoreCase) )TRK1=false;      cout << "                       (( WARNING ))                      " << endl;
4384          if ( detlist.Contains("+TRK1", TString::kIgnoreCase) )TRK1=true;      cout << " The meaning of the option +ALL has changed!!             " << endl;
4385      };      cout << " Now it includes really all (level0+level1+level2+gpamela)" << endl;
4386                cout << " and the file is discarded if it does not contain         " << endl;
4387      if( detlist.Contains("TRK2", TString::kIgnoreCase)){      cout << " all trees or  if level0 files are not available!!        " << endl;
4388          if ( detlist.Contains("-TRK2", TString::kIgnoreCase) )TRK2=false;      cout << " ======================================================== " << endl;
         if ( detlist.Contains("+TRK2", TString::kIgnoreCase) )TRK2=true;  
     };  
4389    
4390      if( detlist.Contains("TRKh", TString::kIgnoreCase)){      CAL0 = true;
4391          if ( detlist.Contains("-TRKh", TString::kIgnoreCase) )TRKh=false;      CAL1 = true;
4392          if ( detlist.Contains("+TRKh", TString::kIgnoreCase) )TRKh=true;      CAL2 = true;
4393      };      TRK2 = true;
4394                TRK1 = true;
4395      if( detlist.Contains("+TRK", TString::kIgnoreCase) && !TRK1 && !TRK2 && !TRKh )TRK2=true;      TRKh = true;
4396      if( detlist.Contains("-TRK", TString::kIgnoreCase) && TRK1 && TRK2 && TRKh){      TRK0 = true;
4397          TRK2=false;      TRG = true;
4398          TRK1=false;      TOF = true;
4399          TRKh=false;      TOF0 = true;
4400      }      S4 = true;
4401  //  -------------------------------------------------------------------------      ND = true;
4402            AC = true;
4403      if( detlist.Contains("-TRG", TString::kIgnoreCase) )TRG = false;      ORB = true;
4404      else if( detlist.Contains("+TRG", TString::kIgnoreCase) )TRG = true;      GP = true;
4405          }
4406      if( detlist.Contains("-TOF", TString::kIgnoreCase) )TOF = false;    else if (detlist.Contains("-ALL", TString::kIgnoreCase)) {
4407      else if( detlist.Contains("+TOF", TString::kIgnoreCase) )TOF = true;      CAL0 = false;
4408        CAL1 = false;
4409        CAL2 = false;
4410        TRK2 = false;
4411        TRK1 = false;
4412        TRKh = false;
4413        TRK0 = false;
4414        TRG = false;
4415        TOF = false;
4416        TOF0 = false;
4417        S4 = false;
4418        ND = false;
4419        AC = false;
4420        ORB = false;
4421        GP = false;
4422      };
4423    
4424      if( detlist.Contains("-TOF0", TString::kIgnoreCase) )TOF0 = false;    //  -------------------------------------------------------------------------
4425      else if( detlist.Contains("+TOF0", TString::kIgnoreCase) )TOF0 = true;    if (detlist.Contains("CAL1", TString::kIgnoreCase)) {
4426            if (detlist.Contains("-CAL1", TString::kIgnoreCase))
4427      if( detlist.Contains("-S4",  TString::kIgnoreCase) )S4  = false;        CAL1 = false;
4428      else if( detlist.Contains("+S4",  TString::kIgnoreCase) )S4  = true;      if (detlist.Contains("+CAL1", TString::kIgnoreCase))
4429              CAL1 = true;
4430      if( detlist.Contains("-ND",  TString::kIgnoreCase) )ND  = false;    };
     else if( detlist.Contains("+ND",  TString::kIgnoreCase) )ND  = true;  
       
     if( detlist.Contains("-AC",  TString::kIgnoreCase) )AC  = false;  
     else if( detlist.Contains("+AC",  TString::kIgnoreCase) )AC  = true;  
       
     if( detlist.Contains("-ORB", TString::kIgnoreCase) )ORB = false;  
     else if( detlist.Contains("+ORB", TString::kIgnoreCase) )ORB = true;  
4431    
4432  //     cout<< "Set detector list --> ";    if (detlist.Contains("CAL0", TString::kIgnoreCase)) {
4433  //     if(TRK1)cout<<"TRK1 ";      if (detlist.Contains("-CAL0", TString::kIgnoreCase))
4434  //     if(TRK2)cout<<"TRK2 ";        CAL0 = false;
4435  //     if(TRKh)cout<<"TRKH ";      if (detlist.Contains("+CAL0", TString::kIgnoreCase))
4436  //     if(CAL1)cout<<"CAL1 ";        CAL0 = true;
4437  //     if(CAL2)cout<<"CAL2 ";    };
 //     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;  
       
 };  
4438    
4439      if (detlist.Contains("CAL2", TString::kIgnoreCase)) {
4440        if (detlist.Contains("-CAL2", TString::kIgnoreCase))
4441          CAL2 = false;
4442        if (detlist.Contains("+CAL2", TString::kIgnoreCase))
4443          CAL2 = true;
4444      };
4445    
4446      if (detlist.Contains("+CAL", TString::kIgnoreCase) && !CAL1 && !CAL2)
4447        CAL2 = true;
4448      if (detlist.Contains("-CAL", TString::kIgnoreCase) && CAL1 && CAL2) {
4449        CAL2 = false;
4450        CAL1 = false;
4451      }
4452      //  -------------------------------------------------------------------------
4453      if (detlist.Contains("TRK0", TString::kIgnoreCase)) {
4454        if (detlist.Contains("-TRK0", TString::kIgnoreCase))
4455          TRK0 = false;
4456        if (detlist.Contains("+TRK0", TString::kIgnoreCase))
4457          TRK0 = true;
4458      };
4459    
4460      if (detlist.Contains("TRK1", TString::kIgnoreCase)) {
4461        if (detlist.Contains("-TRK1", TString::kIgnoreCase))
4462          TRK1 = false;
4463        if (detlist.Contains("+TRK1", TString::kIgnoreCase))
4464          TRK1 = true;
4465      };
4466    
4467      if (detlist.Contains("TRK2", TString::kIgnoreCase)) {
4468        if (detlist.Contains("-TRK2", TString::kIgnoreCase))
4469          TRK2 = false;
4470        if (detlist.Contains("+TRK2", TString::kIgnoreCase))
4471          TRK2 = true;
4472      };
4473    
4474      if (detlist.Contains("TRKh", TString::kIgnoreCase)) {
4475        if (detlist.Contains("-TRKh", TString::kIgnoreCase))
4476          TRKh = false;
4477        if (detlist.Contains("+TRKh", TString::kIgnoreCase))
4478          TRKh = true;
4479      };
4480    
4481      if (detlist.Contains("+TRK", TString::kIgnoreCase) && !TRK1 && !TRK2 && !TRKh)
4482        TRK2 = true;
4483      if (detlist.Contains("-TRK", TString::kIgnoreCase) && TRK1 && TRK2 && TRKh) {
4484        TRK2 = false;
4485        TRK1 = false;
4486        TRKh = false;
4487      }
4488      //  -------------------------------------------------------------------------
4489    
4490      if (detlist.Contains("-TRG", TString::kIgnoreCase))
4491        TRG = false;
4492      else if (detlist.Contains("+TRG", TString::kIgnoreCase))
4493        TRG = true;
4494    
4495      if (detlist.Contains("-TOF", TString::kIgnoreCase))
4496        TOF = false;
4497      else if (detlist.Contains("+TOF", TString::kIgnoreCase))
4498        TOF = true;
4499    
4500      if (detlist.Contains("-TOF0", TString::kIgnoreCase))
4501        TOF0 = false;
4502      else if (detlist.Contains("+TOF0", TString::kIgnoreCase))
4503        TOF0 = true;
4504    
4505      if (detlist.Contains("-S4", TString::kIgnoreCase))
4506        S4 = false;
4507      else if (detlist.Contains("+S4", TString::kIgnoreCase))
4508        S4 = true;
4509    
4510      if (detlist.Contains("-ND", TString::kIgnoreCase))
4511        ND = false;
4512      else if (detlist.Contains("+ND", TString::kIgnoreCase))
4513        ND = true;
4514    
4515      if (detlist.Contains("-AC", TString::kIgnoreCase))
4516        AC = false;
4517      else if (detlist.Contains("+AC", TString::kIgnoreCase))
4518        AC = true;
4519    
4520      if (detlist.Contains("-ORB", TString::kIgnoreCase))
4521        ORB = false;
4522      else if (detlist.Contains("+ORB", TString::kIgnoreCase))
4523        ORB = true;
4524    
4525      if (detlist.Contains("-GP", TString::kIgnoreCase))
4526        GP = false;
4527      else if (detlist.Contains("+GP", TString::kIgnoreCase))
4528        GP = true;
4529    
4530      cout << "tree/branch list from input --> ";
4531      if (TRK0)
4532        cout << "TRK0 ";
4533      if (TRK1)
4534        cout << "TRK1 ";
4535      if (TRK2)
4536        cout << "TRK2 ";
4537      if (TRKh)
4538        cout << "TRKH ";
4539      if (CAL0)
4540        cout << "CAL0 ";
4541      if (CAL1)
4542        cout << "CAL1 ";
4543      if (CAL2)
4544        cout << "CAL2 ";
4545      if (TOF)
4546        cout << "TOF ";
4547      if (TRG)
4548        cout << "TRG ";
4549      if (AC)
4550        cout << "AC ";
4551      if (ND)
4552        cout << "ND ";
4553      if (S4)
4554        cout << "S4 ";
4555      if (ORB)
4556        cout << "ORB ";
4557      if (GP)
4558        cout << "GP ";
4559      cout << endl;
4560      //     cout<< "Set detector list --> ";
4561      //     if(TRK1)cout<<"TRK1 ";
4562      //     if(TRK2)cout<<"TRK2 ";
4563      //     if(TRKh)cout<<"TRKH ";
4564      //     if(CAL1)cout<<"CAL1 ";
4565      //     if(CAL2)cout<<"CAL2 ";
4566      //     if(TOF0)cout<<"TOF0 ";
4567      //     if(TOF)cout<<"TOF ";
4568      //     if(TRG)cout<<"TRG ";
4569      //     if(AC)cout<<"AC ";
4570      //     if(ND)cout<<"ND ";
4571      //     if(S4)cout<<"S4 ";
4572      //     if(ORB)cout<<"ORB ";
4573      //     cout << endl;
4574    
4575    }
4576    ;
4577    
4578  /**  /**
4579   * Set tree/branch detector flags from the content of a tree   * Set tree/branch detector flags from the content of a tree
4580   */   */
4581  void  PamLevel2::GetWhichTrees(TFile* f){  void PamLevel2::GetWhichTrees(TFile* f) {
       
4582    
4583      //    cout << "void  PamLevel2::GetWhichTrees(TFile* f) --- WARNING!! --- ...potrebbe non funzionare "<<endl;
4584      // -----------
4585      // reset flags
4586      // -----------
4587      CAL1 = false;
4588      CAL2 = false;
4589      TRK2 = false;
4590      TRK1 = false;
4591      TRKh = false;
4592      TRG = false;
4593      TOF = false;
4594      S4 = false;
4595      ND = false;
4596      AC = false;
4597      ORB = false;
4598      GP = false;
4599    
4600      RUN = false;
4601    
4602      //    cout << "Checking file: "<<f->GetName()<<endl;
4603      if (!f || f->IsZombie()) {
4604        cout << "File: " << f->GetName() << " Non valid root file" << endl;
4605        fDiscarded = true;
4606        return;
4607      }
4608    
4609      cout << "void  PamLevel2::GetWhichTrees(TFile* f) --- WARNING!! --- ...potrebbe non funzionare "<<endl;    TList *lk = f->GetListOfKeys();
4610      // -----------    if (!lk)
4611      // reset flags      return;
4612      // -----------    TIter next(lk);
4613      CAL1   = false;        TKey *key = 0;
     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;  
     }  
4614    
4615      TList *lk = f->GetListOfKeys();    Int_t nev = 0;
     TIter next(lk);  
     TKey *key =0;  
4616    
4617      Int_t nev = 0;    while ((key = (TKey*) next())) {
4618    
4619      while( (key = (TKey*)next()) ){      if (!strcmp(key->GetName(), "Run"))
4620                  RUN = true;
4621          if( !strcmp(key->GetName(),"Run"        ) )RUN = true;  
4622        //=========================================================
4623        if (!strcmp(key->GetName(), "Trigger")) {
4624          TRG = true;
4625          Int_t nevt = ((TTree*) f->Get("Trigger"))->GetEntries();
4626          if (nev && nevt != nev) {
4627            cout << "File: " << f->GetName() << " Trigger tree has " << nevt << " events instead of " << nev << endl;
4628            TRG = false;
4629          }
4630          else
4631            nev = nevt;
4632        }
4633        //=========================================================
4634        if (!strcmp(key->GetName(), "ToF")) {
4635          TOF = true;
4636          Int_t nevt = ((TTree*) f->Get("ToF"))->GetEntries();
4637          if (nev && nevt != nev) {
4638            cout << "File: " << f->GetName() << "     ToF tree has " << nevt << " events instead of " << nev << endl;
4639            TOF = false;
4640          }
4641          else
4642            nev = nevt;
4643        }
4644        //=========================================================
4645        if (!strcmp(key->GetName(), "S4")) {
4646          S4 = true;
4647          Int_t nevt = ((TTree*) f->Get("S4"))->GetEntries();
4648          if (nev && nevt != nev) {
4649            cout << "File: " << f->GetName() << "      S4 tree has " << nevt << " events instead of " << nev << endl;
4650            S4 = false;
4651          }
4652          else
4653            nev = nevt;
4654        }
4655        //=========================================================
4656    
4657          //=========================================================          if (!strcmp(key->GetName(), "NeutronD")) {
4658          if( !strcmp(key->GetName(),"Trigger"    ) ){        ND = true;
4659              TRG = true;        Int_t nevt = ((TTree*) f->Get("NeutronD"))->GetEntries();
4660              Int_t nevt = ((TTree*)f->Get("Trigger"))->GetEntries();        if (nev && nevt != nev) {
4661              if( nev && nevt!=nev){          cout << "File: " << f->GetName() << "NeutronD tree has " << nevt << " events instead of " << nev << endl;
4662                  cout << "File: "<< f->GetName() <<" Trigger tree has "<<nevt<<" events instead of "<<nev<< endl;          ND = false;
4663                  TRG = false;        }
4664              }else nev=nevt;        else
4665          }          nev = nevt;
4666          //=========================================================          }
4667          if( !strcmp(key->GetName(),"ToF"        ) ){      //=========================================================
4668              TOF = true;      if (!strcmp(key->GetName(), "Anticounter")) {
4669              Int_t nevt = ((TTree*)f->Get("ToF"))->GetEntries();        AC = true;
4670              if( nev && nevt!=nev){        Int_t nevt = ((TTree*) f->Get("Anticounter"))->GetEntries();
4671                  cout << "File: "<< f->GetName() <<"     ToF tree has "<<nevt<<" events instead of "<<nev<< endl;        if (nev && nevt != nev) {
4672                  TOF = false;          cout << "File: " << f->GetName() << " Anticounter tree has " << nevt << " events instead of " << nev << endl;
4673              }else nev=nevt;          AC = false;
4674          }        }
4675          //=========================================================          else
4676          if( !strcmp(key->GetName(),"S4"         ) ){          nev = nevt;
4677              S4 = true;      }
4678              Int_t nevt = ((TTree*)f->Get("S4"))->GetEntries();      //=========================================================
4679              if( nev && nevt!=nev){      if (!strcmp(key->GetName(), "OrbitalInfo")) {
4680                  cout << "File: "<< f->GetName() <<"      S4 tree has "<<nevt<<" events instead of "<<nev<< endl;        ORB = true;
4681                  S4 = false;        Int_t nevt = ((TTree*) f->Get("OrbitalInfo"))->GetEntries();
4682              }else nev=nevt;        if (nev && nevt != nev) {
4683          }          cout << "File: " << f->GetName() << " OrbitalInfo tree has " << nevt << " events instead of " << nev << endl;
4684          //=========================================================            ORB = false;
4685          }
4686          else
4687            nev = nevt;
4688        }
4689        //=========================================================
4690        if (!strcmp(key->GetName(), "Tracker")) {
4691          TTree *T = (TTree*) f->Get("Tracker");
4692          for (Int_t i = 0; i < T->GetListOfBranches()->GetEntries(); i++) {
4693            TString name = T->GetListOfBranches()->At(i)->GetName();
4694            if (!name.CompareTo("TrkLevel1"))
4695              TRK1 = true;
4696            if (!name.CompareTo("TrkLevel2"))
4697              TRK2 = true;
4698            if (!name.CompareTo("TrkHough"))
4699              TRKh = true;
4700          };
4701          Int_t nevt = T->GetEntries();
4702          if (nev && nevt != nev) {
4703            cout << "File: " << f->GetName() << " Tracker tree has " << nevt << " events instead of " << nev << endl;
4704            TRK1 = false;
4705            TRK2 = false;
4706            TRKh = false;
4707          }
4708          else
4709            nev = nevt;
4710          //            T->Delete();
4711        };
4712        //=========================================================
4713        if (!strcmp(key->GetName(), "Calorimeter")) {
4714          TTree *T = (TTree*) f->Get("Calorimeter");
4715          for (Int_t i = 0; i < T->GetListOfBranches()->GetEntries(); i++) {
4716            TString name = T->GetListOfBranches()->At(i)->GetName();
4717            if (!name.CompareTo("CaloLevel1"))
4718              CAL1 = true;
4719            if (!name.CompareTo("CaloLevel2"))
4720              CAL2 = true;
4721          };
4722          Int_t nevt = T->GetEntries();
4723          if (nev && nevt != nev) {
4724            cout << "File: " << f->GetName() << "  Calorimeter tree has " << nevt << " events instead of " << nev << endl;
4725            CAL1 = false;
4726            CAL2 = false;
4727          }
4728          else
4729            nev = nevt;
4730          //            T->Delete();
4731        };
4732        //=========================================================
4733        if (!strcmp(key->GetName(), "h20")) {
4734          GP = true;
4735          Int_t nevt = ((TTree*) f->Get("h20"))->GetEntries();
4736          if (nev && nevt != nev) {
4737            cout << "File: " << f->GetName() << " h20 tree has " << nevt << " events instead of " << nev << endl;
4738            GP = false;
4739          }
4740          else
4741            nev = nevt;
4742        }
4743    
4744          if( !strcmp(key->GetName(),"NeutronD"   ) ){    };
             ND = true;  
             Int_t nevt = ((TTree*)f->Get("NeutronD"))->GetEntries();  
             if( nev && nevt!=nev){  
                 cout << "File: "<< f->GetName() <<"NeutronD tree has "<<nevt<<" events instead of "<<nev<< endl;  
                 ND =false;  
             }else nev=nevt;  
         }        
         //=========================================================    
         if( !strcmp(key->GetName(),"Anticounter") ){  
             AC = true;  
             Int_t nevt = ((TTree*)f->Get("Anticounter"))->GetEntries();  
             if( nev && nevt!=nev){  
                 cout << "File: "<< f->GetName() <<" Anticounter tree has "<<nevt<<" events instead of "<<nev<< endl;  
                 AC =false;  
             }else nev=nevt;  
         }  
         //=========================================================    
         if( !strcmp(key->GetName(),"OrbitalInfo") ){  
             ORB = true;  
             Int_t nevt = ((TTree*)f->Get("OrbitalInfo"))->GetEntries();  
             if( nev && nevt!=nev){  
                 cout << "File: "<< f->GetName() <<" OrbitalInfo tree has "<<nevt<<" events instead of "<<nev<< endl;  
                 ORB = false;  
             }else nev=nevt;  
         }  
         //=========================================================    
         if( !strcmp(key->GetName(),"Tracker"    ) ){  
             TTree *T = (TTree*)f->Get("Tracker");  
             for(Int_t i=0; i<T->GetListOfBranches()->GetEntries(); i++){  
                 TString name = T->GetListOfBranches()->At(i)->GetName();  
                 if( !name.CompareTo("TrkLevel1") )TRK1=true;  
                 if( !name.CompareTo("TrkLevel2") )TRK2=true;  
                 if( !name.CompareTo("TrkHough") )TRKh=true;  
             };        
             Int_t nevt = T->GetEntries();  
             if( nev && nevt!=nev){  
                 cout << "File: "<< f->GetName() <<" Tracker tree has "<<nevt<<" events instead of "<<nev<< endl;  
                 TRK1 = false;  
                 TRK2 = false;  
                 TRKh = false;  
             }else nev=nevt;  
             T->Delete();  
         };  
         //=========================================================    
         if( !strcmp(key->GetName(),"Calorimeter"    ) ){  
             TTree *T = (TTree*)f->Get("Calorimeter");  
             for(Int_t i=0; i<T->GetListOfBranches()->GetEntries(); i++){  
                 TString name = T->GetListOfBranches()->At(i)->GetName();  
                 if( !name.CompareTo("CaloLevel1") )CAL1=true;  
                 if( !name.CompareTo("CaloLevel2") )CAL2=true;  
             };      
             Int_t nevt = T->GetEntries();  
             if( nev && nevt!=nev){  
                 cout << "File: "<< f->GetName() <<"  Calorimeter tree has "<<nevt<<" events instead of "<<nev<< endl;  
                 CAL1 = false;  
                 CAL2 = false;  
             }else nev=nevt;  
             T->Delete();  
         };        
4745    
4746      };    //    delete lk;
       
     delete lk;  
4747    
4748  //     cout<< "Get detector list from input file --> ";    cout << "tree/branch list from file  --> ";
4749  //     if(TRK1)cout<<"TRK1 ";    if (TRK1)
4750  //     if(TRK2)cout<<"TRK2 ";      cout << "TRK1 ";
4751  //     if(TRKh)cout<<"TRKH ";    if (TRK2)
4752  //     if(CAL1)cout<<"CAL1 ";      cout << "TRK2 ";
4753  //     if(CAL2)cout<<"CAL2 ";    if (TRKh)
4754  //     if(TOF)cout<<"TOF ";      cout << "TRKH ";
4755  //     if(TRG)cout<<"TRG ";    if (CAL1)
4756  //     if(AC)cout<<"AC ";      cout << "CAL1 ";
4757  //     if(ND)cout<<"ND ";    if (CAL2)
4758  //     if(S4)cout<<"S4 ";      cout << "CAL2 ";
4759  //     if(ORB)cout<<"ORB ";    if (TOF)
4760  //     cout << endl;      cout << "TOF ";
4761            if (TRG)
4762      return ;      cout << "TRG ";
4763              if (AC)
4764  };      cout << "AC ";
4765      if (ND)
4766        cout << "ND ";
4767      if (S4)
4768        cout << "S4 ";
4769      if (ORB)
4770        cout << "ORB ";
4771      if (GP)
4772        cout << "GP ";
4773      cout << endl;
4774    
4775      return;
4776    
4777    }
4778    ;
4779    
4780  //--------------------------------------  //--------------------------------------
4781  //  //
# Line 2409  void  PamLevel2::GetWhichTrees(TFile* f) Line 4786  void  PamLevel2::GetWhichTrees(TFile* f)
4786   * @param name File name   * @param name File name
4787   * @return true if the file is ok.   * @return true if the file is ok.
4788   */   */
4789  Bool_t  PamLevel2::CheckLevel2File(TString name){  Bool_t PamLevel2::CheckLevel2File(TString name) {
4790            
4791      Bool_t CAL1__ok   = false;        Bool_t CAL1__ok = false;
4792      Bool_t CAL2__ok   = false;        Bool_t CAL2__ok = false;
4793      Bool_t TRK2__ok   = false;        Bool_t TRK2__ok = false;
4794      Bool_t TRK1__ok   = false;        Bool_t TRK1__ok = false;
4795      Bool_t TRKh__ok   = false;        Bool_t TRKh__ok = false;
4796      Bool_t TRG__ok    = false;        Bool_t TRG__ok = false;
4797      Bool_t TOF__ok    = false;        Bool_t TOF__ok = false;
4798      Bool_t S4__ok     = false;        Bool_t S4__ok = false;
4799      Bool_t ND__ok     = false;        Bool_t ND__ok = false;
4800      Bool_t AC__ok     = false;        Bool_t AC__ok = false;
4801      Bool_t ORB__ok    = false;        Bool_t ORB__ok = false;
4802          Bool_t GP__ok = false;
4803      Bool_t RUN__ok    = false;  
4804          Bool_t RUN__ok = false;
4805      Bool_t SELLI__ok  = false;  
4806      Bool_t SELLI__ok = false;
4807    
4808      //    cout << "Checking file: "<<name<<endl;
4809      TFile *f = new TFile(name.Data());
4810      if (!f || f->IsZombie()) {
4811        cout << "File: " << f->GetName() << " discarded ---- Non valid root file" << endl;
4812        fDiscarded = true;
4813        return false;
4814      }
4815      //    cout << "Get list of keys: "<<f<<endl;
4816      TList *lk = f->GetListOfKeys();
4817      //    lk->Print();
4818      TIter next(lk);
4819      TKey *key = 0;
4820    
4821      Int_t nev = 0;
4822    
4823      while ((key = (TKey*) next())) {
4824    
4825        //  cout << key->GetName() << endl;
4826        //  cout << key->GetName() << ""<<key->GetClassName()<<endl;
4827        //          cout << " Get tree: " << f->Get(key->GetName())<<endl;
4828        //  nev_previous = nev;
4829        //  cout << " n.entries  "<< nev <<endl;
4830        //  if( key->GetClassName()=="TTree" && nev_previous && nev != nev_previous ){
4831        //      nev = ((TTree*)f->Get(key->GetName()))->GetEntries();
4832        //      cout << "File: "<< f->GetName() <<" discarded ---- "<< key->GetName() << " tree: n.entries does not match "<<nev<<" "<<nev_previous<< endl;
4833        //      return false;
4834        //  };
4835    
4836        //=========================================================
4837        // check if the file
4838    
4839    
4840        if (!strcmp(key->GetName(), "Run"))
4841          RUN__ok = true;
4842    
4843        //=========================================================
4844        if (!strcmp(key->GetName(), "SelectionList")) {
4845          SELLI__ok = true;
4846          if (SELLI == 1) {
4847            Int_t nevt = ((TTree*) f->Get("SelectionList"))->GetEntries();
4848            if (nev && nevt != nev) {
4849              cout << "File: " << f->GetName() << " discarded ---- SelectionList tree has " << nevt
4850                  << " events instead of " << nev << endl;
4851              fDiscarded = true;
4852              return false;
4853            }
4854            nev = nevt;
4855          }
4856        }
4857    
4858        //=========================================================
4859        if (!strcmp(key->GetName(), "Trigger")) {
4860          TRG__ok = true;
4861          if (TRG) {
4862            Int_t nevt = ((TTree*) f->Get("Trigger"))->GetEntries();
4863            if (nev && nevt != nev) {
4864              cout << "File: " << f->GetName() << " discarded ---- Trigger tree has " << nevt << " events instead of "
4865                  << nev << endl;
4866              fDiscarded = true;
4867              return false;
4868            }
4869            nev = nevt;
4870          }
4871        }
4872        //=========================================================
4873        if (!strcmp(key->GetName(), "ToF")) {
4874          TOF__ok = true;
4875          if (TOF) {
4876            Int_t nevt = ((TTree*) f->Get("ToF"))->GetEntries();
4877            if (nev && nevt != nev) {
4878              cout << "File: " << f->GetName() << " discarded ---- ToF tree has " << nevt << " events instead of " << nev
4879                  << endl;
4880              fDiscarded = true;
4881              return false;
4882            }
4883            nev = nevt;
4884          }
4885        }
4886        //=========================================================
4887        if (!strcmp(key->GetName(), "S4")) {
4888          S4__ok = true;
4889          if (S4) {
4890            Int_t nevt = ((TTree*) f->Get("S4"))->GetEntries();
4891            if (nev && nevt != nev) {
4892              cout << "File: " << f->GetName() << " discarded ---- S4 tree has " << nevt << " events instead of " << nev
4893                  << endl;
4894              fDiscarded = true;
4895              return false;
4896            }
4897            nev = nevt;
4898          }
4899        }
4900        //=========================================================
4901    
4902      cout << "Checking file: "<<name<<endl;      if (!strcmp(key->GetName(), "NeutronD")) {
4903      TFile *f = new TFile(name.Data());        ND__ok = true;
4904      if( !f || f->IsZombie() ){        if (ND) {
4905          cout << "File: "<< f->GetName() <<" discarded ---- Non valid root file"<< endl; return false;          Int_t nevt = ((TTree*) f->Get("NeutronD"))->GetEntries();
4906      }          if (nev && nevt != nev) {
4907  //    cout << "Get list of keys: "<<f<<endl;            cout << "File: " << f->GetName() << " discarded ---- NeutronD tree has " << nevt << " events instead of "
4908      TList *lk = f->GetListOfKeys();                << nev << endl;
4909  //    lk->Print();            fDiscarded = true;
4910      TIter next(lk);            return false;
4911      TKey *key =0;          }
4912            nev = nevt;
4913          }
4914        }
4915        //=========================================================
4916        if (!strcmp(key->GetName(), "Anticounter")) {
4917          AC__ok = true;
4918          if (AC) {
4919            Int_t nevt = ((TTree*) f->Get("Anticounter"))->GetEntries();
4920            if (nev && nevt != nev) {
4921              cout << "File: " << f->GetName() << " discarded ---- Anticounter tree has " << nevt << " events instead of "
4922                  << nev << endl;
4923              fDiscarded = true;
4924              return false;
4925            }
4926            nev = nevt;
4927          }
4928        }
4929        //=========================================================
4930        if (!strcmp(key->GetName(), "OrbitalInfo")) {
4931          ORB__ok = true;
4932          if (ORB) {
4933            Int_t nevt = ((TTree*) f->Get("OrbitalInfo"))->GetEntries();
4934            if (nev && nevt != nev) {
4935              cout << "File: " << f->GetName() << " discarded ---- OrbitalInfo tree has " << nevt << " events instead of "
4936                  << nev << endl;
4937              fDiscarded = true;
4938              return false;
4939            }
4940            nev = nevt;
4941          }
4942        }
4943        //=========================================================
4944        if (!strcmp(key->GetName(), "Tracker")) {
4945          TTree *T = (TTree*) f->Get("Tracker");
4946          if (TRK1 || TRK2 || TRKh) {
4947            Int_t nevt = T->GetEntries();
4948            if (nev && nevt != nev) {
4949              cout << "File: " << f->GetName() << " discarded ---- Tracker tree has " << nevt << " events instead of "
4950                  << nev << endl;
4951              fDiscarded = true;
4952              return false;
4953            }
4954            nev = nevt;
4955          }
4956          for (Int_t i = 0; i < T->GetListOfBranches()->GetEntries(); i++) {
4957            TString name = T->GetListOfBranches()->At(i)->GetName();
4958            if (!name.CompareTo("TrkLevel1"))
4959              TRK1__ok = true;
4960            if (!name.CompareTo("TrkLevel2"))
4961              TRK2__ok = true;
4962            if (!name.CompareTo("TrkHough"))
4963              TRKh__ok = true;
4964          };
4965          T->Delete();
4966        };
4967        //=========================================================
4968        if (!strcmp(key->GetName(), "Calorimeter")) {
4969          TTree *T = (TTree*) f->Get("Calorimeter");
4970          if (CAL1 || CAL2) {
4971            Int_t nevt = T->GetEntries();
4972            if (nev && nevt != nev) {
4973              cout << "File: " << f->GetName() << " discarded ---- Calorimeter tree has " << nevt << " events instead of "
4974                  << nev << endl;
4975              fDiscarded = true;
4976              return false;
4977            }
4978            nev = nevt;
4979          }
4980          for (Int_t i = 0; i < T->GetListOfBranches()->GetEntries(); i++) {
4981            TString name = T->GetListOfBranches()->At(i)->GetName();
4982            if (!name.CompareTo("CaloLevel1"))
4983              CAL1__ok = true;
4984            if (!name.CompareTo("CaloLevel2"))
4985              CAL2__ok = true;
4986          };
4987          T->Delete();
4988        };
4989        //=========================================================
4990        if (!strcmp(key->GetName(), "h20")) {
4991          ISGP = true;
4992          GP__ok = true;
4993          if (GP) {
4994            Int_t nevt = ((TTree*) f->Get("h20"))->GetEntries();
4995            if (nev && nevt != nev) {
4996              cout << "File: " << f->GetName() << " discarded ---- h20 tree has " << nevt << " events instead of " << nev
4997                  << endl;
4998              fDiscarded = true;
4999              return false;
5000            }
5001            nev = nevt;
5002          }
5003        }
5004    
5005      Int_t nev = 0;    };
5006    
5007      while( (key = (TKey*)next()) ){    if (SELLI == -1)
5008                SELLI = (Int_t) SELLI__ok;
5009  //      cout << key->GetName() << endl;    if (SELLI == 0 && SELLI__ok) {
5010  //      cout << key->GetName() << ""<<key->GetClassName()<<endl;      cout << "File: " << f->GetName() << " discarded ---- found SelectionList (it is not a full-event file)" << endl;
5011  //              cout << " Get tree: " << f->Get(key->GetName())<<endl;      fDiscarded = true;
5012  //      nev_previous = nev;      return false;
5013  //      cout << " n.entries  "<< nev <<endl;    }
5014  //      if( key->GetClassName()=="TTree" && nev_previous && nev != nev_previous ){    if (SELLI == 1 && !SELLI__ok) {
5015  //          nev = ((TTree*)f->Get(key->GetName()))->GetEntries();      cout << "File: " << f->GetName() << " discarded ---- SelectionList missing" << endl;
5016  //          cout << "File: "<< f->GetName() <<" discarded ---- "<< key->GetName() << " tree: n.entries does not match "<<nev<<" "<<nev_previous<< endl;      fDiscarded = true;
5017  //          return false;      return false;
5018  //      };    }
   
   
         if( !strcmp(key->GetName(),"Run"        ) )RUN__ok = true;        
   
         //=========================================================      
         if( !strcmp(key->GetName(),"SelectionList"    ) ){  
             SELLI__ok = true;  
             if(SELLI==1){  
                 Int_t nevt = ((TTree*)f->Get("SelectionList"))->GetEntries();  
                 if( nev && nevt!=nev){  
                     cout << "File: "<< f->GetName() <<" discarded ---- SelectionList tree has "<<nevt<<" events instead of "<<nev<< endl;  
                     return false;  
                 }  
                 nev=nevt;  
             }  
         }  
5019    
5020          //=========================================================        //    cout << "SELLI "<<SELLI<<endl;
         if( !strcmp(key->GetName(),"Trigger"    ) ){  
             TRG__ok = true;  
             if(TRG){  
                 Int_t nevt = ((TTree*)f->Get("Trigger"))->GetEntries();  
                 if( nev && nevt!=nev){  
                     cout << "File: "<< f->GetName() <<" discarded ---- Trigger tree has "<<nevt<<" events instead of "<<nev<< endl;  
                     return false;  
                 }  
                 nev=nevt;  
             }  
         }  
         //=========================================================      
         if( !strcmp(key->GetName(),"ToF"        ) ){  
             TOF__ok = true;  
             if(TOF){  
                 Int_t nevt = ((TTree*)f->Get("ToF"))->GetEntries();  
                 if( nev && nevt!=nev){  
                     cout << "File: "<< f->GetName() <<" discarded ---- ToF tree has "<<nevt<<" events instead of "<<nev<< endl;  
                     return false;  
                 }  
                 nev=nevt;  
             }  
         }  
         //=========================================================    
         if( !strcmp(key->GetName(),"S4"         ) ){  
             S4__ok = true;  
             if(S4){  
                 Int_t nevt = ((TTree*)f->Get("S4"))->GetEntries();  
                 if( nev && nevt!=nev){  
                     cout << "File: "<< f->GetName() <<" discarded ---- S4 tree has "<<nevt<<" events instead of "<<nev<< endl;  
                     return false;  
                 }  
                 nev=nevt;  
             }  
         }  
         //=========================================================    
5021    
5022          if( !strcmp(key->GetName(),"NeutronD"   ) ){    //     cout<< "CheckLevel2File(TString): detector list --> ";
5023              ND__ok = true;    //     if(TRK1__ok)cout<<"TRK1 ";
5024              if(ND){    //     if(TRK2__ok)cout<<"TRK2 ";
5025                  Int_t nevt = ((TTree*)f->Get("NeutronD"))->GetEntries();    //     if(TRKh__ok)cout<<"TRKH ";
5026                  if( nev && nevt!=nev){    //     if(CAL1__ok)cout<<"CAL1 ";
5027                      cout << "File: "<< f->GetName() <<" discarded ---- NeutronD tree has "<<nevt<<" events instead of "<<nev<< endl;    //     if(CAL2__ok)cout<<"CAL2 ";
5028                      return false;    //     if(TOF__ok)cout<<"TOF ";
5029                  }    //     if(TRG__ok)cout<<"TRG ";
5030                  nev=nevt;    //     if(AC__ok)cout<<"AC ";
5031              }    //     if(ND__ok)cout<<"ND ";
5032          }          //     if(S4__ok)cout<<"S4 ";
5033          //=========================================================      //     if(ORB__ok)cout<<"ORB ";
5034          if( !strcmp(key->GetName(),"Anticounter") ){    //     cout << endl;
5035              AC__ok = true;  
5036              if(AC){  
5037                  Int_t nevt = ((TTree*)f->Get("Anticounter"))->GetEntries();    if (TRK2 && TRK1__ok)
5038                  if( nev && nevt!=nev){      TRK1 = 1;
5039                      cout << "File: "<< f->GetName() <<" discarded ---- Anticounter tree has "<<nevt<<" events instead of "<<nev<< endl;    // ----------------------------------------------------------------------------
5040                      return false;    // NOTA
5041                  }    // se c'e` il level1, lo devo necessarimente leggere.
5042                  nev=nevt;    // infatti (non ho capito perche`) i cluster vengono letti e allocati in memoria
5043              }    // comunque, ma non vengono disallocati da PamLevel2::Clear()
5044          }    // ----------------------------------------------------------------------------
5045          //=========================================================    
5046          if( !strcmp(key->GetName(),"OrbitalInfo") ){  
5047              ORB__ok = true;    if (!RUN__ok) {
5048              if(ORB){      cout << "File: " << f->GetName() << " *WARNING* ---- Missing RunInfo tree (NB: RUN infos will not be updated)"
5049                  Int_t nevt = ((TTree*)f->Get("OrbitalInfo"))->GetEntries();          << endl;
5050                  if( nev && nevt!=nev){      RUN = false;
5051                      cout << "File: "<< f->GetName() <<" discarded ---- OrbitalInfo tree has "<<nevt<<" events instead of "<<nev<< endl;    };
                     return false;  
                 }  
                 nev=nevt;  
             }  
         }  
         //=========================================================    
         if( !strcmp(key->GetName(),"Tracker"    ) ){  
             TTree *T = (TTree*)f->Get("Tracker");  
             if(TRK1||TRK2||TRKh){  
                 Int_t nevt = T->GetEntries();  
                 if( nev && nevt!=nev){  
                     cout << "File: "<< f->GetName() <<" discarded ---- Tracker tree has "<<nevt<<" events instead of "<<nev<< endl;  
                     return false;  
                 }  
                 nev=nevt;  
             }  
             for(Int_t i=0; i<T->GetListOfBranches()->GetEntries(); i++){  
                 TString name = T->GetListOfBranches()->At(i)->GetName();  
                 if( !name.CompareTo("TrkLevel1") )TRK1__ok=true;  
                 if( !name.CompareTo("TrkLevel2") )TRK2__ok=true;  
                 if( !name.CompareTo("TrkHough") )TRKh__ok=true;  
             };        
             T->Delete();  
         };  
         //=========================================================    
         if( !strcmp(key->GetName(),"Calorimeter"    ) ){  
             TTree *T = (TTree*)f->Get("Calorimeter");  
             if(CAL1||CAL2){  
                 Int_t nevt = T->GetEntries();  
                 if( nev && nevt!=nev){  
                     cout << "File: "<< f->GetName() <<" discarded ---- Calorimeter tree has "<<nevt<<" events instead of "<<nev<< endl;  
                     return false;  
                 }  
                 nev=nevt;  
             }  
             for(Int_t i=0; i<T->GetListOfBranches()->GetEntries(); i++){  
                 TString name = T->GetListOfBranches()->At(i)->GetName();  
                 if( !name.CompareTo("CaloLevel1") )CAL1__ok=true;  
                 if( !name.CompareTo("CaloLevel2") )CAL2__ok=true;  
             };      
             T->Delete();  
         };        
5052    
5053      };    if (CAL1 && !CAL1__ok) {
5054        cout << "File: " << f->GetName() << " discarded ---- Missing CaloLevel1 branch" << endl;
5055        fDiscarded = true;
5056        return false;
5057      };
5058      if (CAL2 && !CAL2__ok) {
5059        cout << "File: " << f->GetName() << " discarded ---- Missing CaloLevel2 branch" << endl;
5060        fDiscarded = true;
5061        return false;
5062      };
5063      if (TRK2 && !TRK2__ok) {
5064        cout << "File: " << f->GetName() << " discarded ---- Missing TrkLevel2 branch" << endl;
5065        fDiscarded = true;
5066        return false;
5067      };
5068      if (TRK1 && !TRK1__ok) {
5069        cout << "File: " << f->GetName() << " discarded ---- Missing TrkLevel1 branch" << endl;
5070        fDiscarded = true;
5071        return false;
5072      };
5073      if (TRKh && !TRKh__ok) {
5074        cout << "File: " << f->GetName() << " discarded ---- Missing TrkHough branch" << endl;
5075        fDiscarded = true;
5076        return false;
5077      };
5078      if (ORB && !ORB__ok) {
5079        cout << "File: " << f->GetName() << " discarded ---- Missing ORB tree" << endl;
5080        fDiscarded = true;
5081        return false;
5082      };
5083      if (AC && !AC__ok) {
5084        cout << "File: " << f->GetName() << " discarded ---- Missing AC tree" << endl;
5085        fDiscarded = true;
5086        return false;
5087      };
5088      if (S4 && !S4__ok) {
5089        cout << "File: " << f->GetName() << " discarded ---- Missing S4 tree" << endl;
5090        fDiscarded = true;
5091        return false;
5092      };
5093      if (TOF && !TOF__ok) {
5094        cout << "File: " << f->GetName() << " discarded ---- Missing ToF tree" << endl;
5095        fDiscarded = true;
5096        return false;
5097      };
5098    
5099      if( SELLI==-1 )SELLI = (Int_t)SELLI__ok;    if (ND && !ND__ok) {
5100      if( SELLI==0 && SELLI__ok ){      cout << "File: " << f->GetName() << " discarded ---- Missing ND tree" << endl;
5101          cout << "File: "<< f->GetName() <<" discarded ---- found SelectionList (it is not a full-event file)" << endl;      fDiscarded = true;
5102          return false;        return false;
5103      }    };
5104      if( SELLI==1 && !SELLI__ok ){    if (TRG && !TRG__ok) {
5105          cout << "File: "<< f->GetName() <<" discarded ---- SelectionList missing" << endl;      cout << "File: " << f->GetName() << " discarded ---- Missing Trigger tree" << endl;
5106          return false;      fDiscarded = true;
5107      }      return false;
5108          };
5109  //    cout << "SELLI "<<SELLI<<endl;    if (GP && !GP__ok) {
5110        cout << "File: " << f->GetName() << " discarded ---- Missing h20 tree" << endl;
5111        fDiscarded = true;
5112        return false;
5113      };
5114    
5115  //     cout<< "CheckLevel2File(TString): detector list --> ";    //    lk->Delete();
5116  //     if(TRK1__ok)cout<<"TRK1 ";    //    delete lk;
5117  //     if(TRK2__ok)cout<<"TRK2 ";    f->Close();
5118  //     if(TRKh__ok)cout<<"TRKH ";  
5119  //     if(CAL1__ok)cout<<"CAL1 ";    //     cout<< "CheckLevel2File(TString): detector list --> ";
5120  //     if(CAL2__ok)cout<<"CAL2 ";    //     if(TRK1)cout<<"TRK1 ";
5121  //     if(TOF__ok)cout<<"TOF ";    //     if(TRK2)cout<<"TRK2 ";
5122  //     if(TRG__ok)cout<<"TRG ";    //     if(TRKh)cout<<"TRKH ";
5123  //     if(AC__ok)cout<<"AC ";    //     if(CAL1)cout<<"CAL1 ";
5124  //     if(ND__ok)cout<<"ND ";    //     if(CAL2)cout<<"CAL2 ";
5125  //     if(S4__ok)cout<<"S4 ";    //     if(TOF)cout<<"TOF ";
5126  //     if(ORB__ok)cout<<"ORB ";    //     if(TRG)cout<<"TRG ";
5127  //     cout << endl;    //     if(AC)cout<<"AC ";
5128      //     if(ND)cout<<"ND ";
5129      //     if(S4)cout<<"S4 ";
5130      if(TRK2 && TRK1__ok)TRK1=1;    //     if(ORB)cout<<"ORB ";
5131  // ----------------------------------------------------------------------------    //     if(GP)cout<<"GP ";
5132  // NOTA    //     cout << endl;
 // se c'e` il level1, lo devo necessarimente leggere.  
 // infatti (non ho capito perche`) i cluster vengono letti e allocati in memoria  
 // comunque, ma non vengono disallocati da PamLevel2::Clear()  
 // ----------------------------------------------------------------------------  
   
   
     if(!RUN__ok) {  
         cout << "File: "<< f->GetName() <<" *WARNING* ---- Missing RunInfo tree"<< endl;  
 //      return false;  
     };  
   
     if(CAL1 && !CAL1__ok){  
         cout << "File: "<< f->GetName() <<" discarded ---- Missing CaloLevel1 branch"<< endl;  
         return false;  
     };  
     if(CAL2 && !CAL2__ok){  
         cout << "File: "<< f->GetName() <<" discarded ---- Missing CaloLevel2 branch"<< endl;  
         return false;  
     };  
     if(TRK2 && !TRK2__ok){  
         cout << "File: "<< f->GetName() <<" discarded ---- Missing TrkLevel2 branch"<< endl;  
         return false;  
     };  
     if(TRK1 && !TRK1__ok){  
         cout << "File: "<< f->GetName() <<" discarded ---- Missing TrkLevel1 branch"<< endl;  
         return false;  
     };  
     if(TRKh && !TRKh__ok){  
         cout << "File: "<< f->GetName() <<" discarded ---- Missing TrkHough branch"<< endl;  
         return false;  
     };  
     if(ORB && !ORB__ok){  
         cout << "File: "<< f->GetName() <<" discarded ---- Missing ORB tree"<< endl;  
         return false;  
     };  
     if(AC && !AC__ok){  
         cout << "File: "<< f->GetName() <<" discarded ---- Missing AC tree"<< endl;  
         return false;  
     };  
     if(S4 && !S4__ok){  
         cout << "File: "<< f->GetName() <<" discarded ---- Missing S4 tree"<< endl;  
         return false;  
     };  
     if(TOF && !TOF__ok){  
         cout << "File: "<< f->GetName() <<" discarded ---- Missing ToF tree"<< endl;  
         return false;  
     };  
   
     if(ND && !ND__ok){  
         cout << "File: "<< f->GetName() <<" discarded ---- Missing ND tree"<< endl;  
         return false;  
     };  
     if(TRG && !TRG__ok){  
         cout << "File: "<< f->GetName() <<" discarded ---- Missing Trigger tree"<< endl;  
         return false;  
     };  
       
5133    
5134  //    lk->Delete();    return true;
 //    delete lk;  
     f->Close();  
   
 //     cout<< "CheckLevel2File(TString): detector list --> ";  
 //     if(TRK1)cout<<"TRK1 ";  
 //     if(TRK2)cout<<"TRK2 ";  
 //     if(TRKh)cout<<"TRKH ";  
 //     if(CAL1)cout<<"CAL1 ";  
 //     if(CAL2)cout<<"CAL2 ";  
 //     if(TOF)cout<<"TOF ";  
 //     if(TRG)cout<<"TRG ";  
 //     if(AC)cout<<"AC ";  
 //     if(ND)cout<<"ND ";  
 //     if(S4)cout<<"S4 ";  
 //     if(ORB)cout<<"ORB ";  
 //     cout << endl;  
         
     return true;  
           
 };  
5135    
5136    }
5137    ;
5138    
5139  /**  /**
5140   * Create clone-trees   * Create clone-trees
5141   */   */
5142  void PamLevel2::CreateCloneTrees0( TChain *fChain, TFile *ofile ){  void PamLevel2::CreateCloneTrees0(TChain *fChain, TFile *ofile) {
5143    
5144      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;    cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
5145      cout << "Create clones of PAMELA trees "<<endl;    cout << "Create clones of PAMELA trees " << endl;
5146        
5147      Int_t i=0;    Int_t i = 0;
5148      pam_tree_clone[i] = fChain->GetTree()->CloneTree(0);    pam_tree_clone[i] = fChain->GetTree()->CloneTree(0);
5149      TString name =  pam_tree_clone[i]->GetName();    TString name = pam_tree_clone[i]->GetName();
5150      name.Append("_clone");
5151      //    pam_tree_clone[i]->SetName(name.Data());
5152      cout << pam_tree_clone[i]->GetName() << endl;
5153      i++;
5154    
5155      TList *li = fChain->GetListOfFriends();
5156      TIter next(li);
5157      TFriendElement* T_friend = 0;
5158      ofile->cd();
5159      while ((T_friend = (TFriendElement*) next())) {
5160        //  cout<<T_friend->IsA()->GetName()<<" "<<T_friend->GetName()<<hex << T_friend->GetTree() << dec<<endl;
5161        //  cout<<T_friend->GetTree()->GetName()<< endl;
5162        pam_tree_clone[i] = T_friend->GetTree()->CloneTree(0);
5163        pam_tree_clone[i]->SetAutoSave(1000000);
5164        name = pam_tree_clone[i]->GetName();
5165      name.Append("_clone");      name.Append("_clone");
5166  //    pam_tree_clone[i]->SetName(name.Data());      //  pam_tree_clone[i]->SetName(name.Data());
5167      cout << pam_tree_clone[i]->GetName() <<endl;      cout << pam_tree_clone[i]->GetName() << endl;
5168      i++;      i++;
5169      }
5170    
5171      TList *li = fChain->GetListOfFriends();    delete li;
     TIter next(li);  
     TFriendElement* T_friend=0;  
     ofile->cd();  
     while( (T_friend = (TFriendElement*)next()) ){  
 //      cout<<T_friend->IsA()->GetName()<<" "<<T_friend->GetName()<<hex << T_friend->GetTree() << dec<<endl;  
 //      cout<<T_friend->GetTree()->GetName()<< endl;  
         pam_tree_clone[i] = T_friend->GetTree()->CloneTree(0);  
         pam_tree_clone[i]->SetAutoSave(1000000);  
         name =  pam_tree_clone[i]->GetName();  
         name.Append("_clone");  
 //      pam_tree_clone[i]->SetName(name.Data());  
         cout << pam_tree_clone[i]->GetName() << endl;  
         i++;  
     }  
       
     delete li;  
5172    
5173      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;    cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
5174    
5175  }  }
5176    
5177  /**  /**
5178   * Create clone-trees   * Create clone-trees
5179   */   */
5180  void PamLevel2::CreateCloneTrees(TFile *ofile){  void PamLevel2::CreateCloneTrees(TFile *ofile) {
   
5181    
5182  //  if the pointer is null, create a default file    //  if the pointer is null, create a default file
5183      if (!run_tree)
5184        return;
5185    
5186      if(!ofile){    if (!ofile) {
5187          cout << "void PamLevel2::CreateCloneTrees(TFile*) -- WARNING -- Creating file: clone-tree.root "<<endl;      cout << "void PamLevel2::CreateCloneTrees(TFile*) -- WARNING -- Creating file: clone-tree.root " << endl;
5188          ofile = new TFile("clone-tree.root","recreate");      ofile = new TFile("clone-tree.root", "recreate");
5189      }    }
5190    
5191      ofile->cd();    ofile->cd();
5192    
5193      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;    cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
5194      cout << "Create new PAMELA trees "<<endl;    cout << "Create new PAMELA trees " << endl;
           
5195    
5196      run_tree_clone = new TTree("Run","PAMELA Level2 data from the GL_RUN table ");    run_tree_clone = new TTree("Run", "PAMELA Level2 data from the GL_RUN table ");
5197      run_tree_clone->Branch("RunInfo","GL_RUN",GetPointerTo("RunInfo"));    run_tree_clone->Branch("RunInfo", "GL_RUN", GetPointerTo("RunInfo"));
5198      cout << "Run          : branch RunInfo"<<endl;    cout << "Run          : branch RunInfo" << endl;
5199      run_tree_clone->Branch("SoftInfo","SoftInfo",GetPointerTo("SoftInfo"));    run_tree_clone->Branch("SoftInfo", "SoftInfo", GetPointerTo("SoftInfo"));
5200      cout << "Run          : branch SoftInfo"<<endl;    cout << "Run          : branch SoftInfo" << endl;
5201      // ------------------
5202      // replicate run tree
5203      // ------------------
5204      //    cout << "----------------------------------------------------"<<endl;
5205      //    cout << "irun\t | RUN\t NEVENTS\t absolute time"<<endl;
5206      for (Int_t i = 0; i < run_tree->GetEntries(); i++) {
5207        run_tree->GetEntry(i);
5208        //  cout << i<< "\t | "<<GetRunInfo()->ID<<"\t "<<GetRunInfo()->NEVENTS<< "\t "<<GetRunInfo()->RUNHEADER_TIME<<" <---> "<<GetRunInfo()->RUNTRAILER_TIME<<endl;
5209        run_tree_clone->Fill();
5210      }
5211      if ( PROC ){
5212        proc_tree_clone = new TTree("ProcessingInfo","Log of data processing");
5213        proc_tree_clone->Branch("ProcInfo", "ProcInfo", GetPointerTo("ProcInfo"));
5214        cout << "ProcessingInfo: branch ProcessingInfo" << endl;  
5215      // ------------------      // ------------------
5216      // replicate run tree      // replicate processinginfo tree
5217      // ------------------      // ------------------
5218      cout << "----------------------------------------------------"<<endl;      //    cout << "----------------------------------------------------"<<endl;
5219      cout << "irun\t | RUN\t NEVENTS\t absolute time"<<endl;      //    cout << "irun\t | RUN\t NEVENTS\t absolute time"<<endl;
5220      for (Int_t i=0; i<run_tree->GetEntries(); i++){      for (Int_t i = 0; i < proc_tree->GetEntries(); i++) {
5221          run_tree->GetEntry(i);        proc_tree->GetEntry(i);
5222          cout << i<< "\t | "<<GetRunInfo()->ID<<"\t "<<GetRunInfo()->NEVENTS<< "\t "<<GetRunInfo()->RUNHEADER_TIME<<" <---> "<<GetRunInfo()->RUNTRAILER_TIME<<endl;        //        cout << i<< "\t | "<<GetRunInfo()->ID<<"\t "<<GetRunInfo()->NEVENTS<< "\t "<<GetRunInfo()->RUNHEADER_TIME<<" <---> "<<GetRunInfo()->RUNTRAILER_TIME<<endl;
5223          run_tree_clone->Fill();        proc_tree_clone->Fill();
5224      }      }
5225      cout << "----------------------------------------------------"<<endl;      if ( SELLI != 2 || true ){      
5226          proc_obj->runID = 0;
5227          TTimeStamp *dt = new TTimeStamp();
5228          proc_obj->date = dt->AsString();
5229          delete dt;
5230          proc_obj->commandLine = Form("PamelaLevel2 was called");
5231          proc_obj->outputFilename = "";
5232          proc_obj->localDir = gSystem->WorkingDirectory();
5233          proc_obj->uname = gSystem->GetFromPipe("uname -a");
5234          proc_obj->DB = Form("mysql://%s/%s",dbc->GetHost(),dbc->GetDB());
5235          proc_tree_clone->Fill();
5236        }
5237        cout << "----------------------------------------------------" << endl;
5238      }
5239      // ------------------------------------
5240      // add branch with dead and live times
5241      // ------------------------------------
5242      if (SELLI != 2) { // EMILIANO
5243        run_tree_clone->Branch("DeadLiveTime", totdltime, "dltime[3]/l");
5244        cout << "Run          : branch DeadLiveTime" << endl;
5245    
5246        sel_tree_clone = new TTree("SelectionList", "List of selected events ");
5247        //    sel_tree_clone->Branch("RunEntry",&irun,"runentry/L");
5248        sel_tree_clone->Branch("RunEntry", &irunt, "runentry/L");//NEWNEW
5249        sel_tree_clone->Branch("EventEntry", &irunentry, "eventry/L");
5250        //    if ( hasL0EE ) sel_tree_clone->Branch("L0EventEntry", &il0entry, "l0eventry/L");
5251      };
5252    
5253      Int_t i = 0;
5254      if (TRK1 || TRK2 || TRKh) {
5255        pam_tree_clone[i] = new TTree("Tracker", "PAMELA tracker level2 data ");
5256        if (TRK1) {
5257          pam_tree_clone[i]->Branch("TrkLevel1", "TrkLevel1", GetPointerTo("TrkLevel1"));
5258          pam_tree_clone[i]->BranchRef();
5259          cout << "Tracker      : branch TrkLevel1" << endl;
5260          //            cout << "CreateCloneTrees " << GetTrkLevel1()<<endl;
5261        };
5262        if (TRK2) {
5263          pam_tree_clone[i]->Branch("TrkLevel2", "TrkLevel2", GetPointerTo("TrkLevel2"));
5264          cout << "Tracker      : branch TrkLevel2" << endl;
5265        };
5266        if (TRKh) {
5267          pam_tree_clone[i]->Branch("TrkHough", "TrkHough", GetPointerTo("TrkHough"));
5268          cout << "Tracker      : branch TrkHough" << endl;
5269        };
5270        if(NUC){
5271            pam_tree_clone[i]->Branch("TrackNuclei","TClonesArray",&trk_nuc_obj);
5272            cout << "Tracker      : branch TrackNuclei" << endl;    
5273        }
5274        if(EXT){
5275            pam_tree_clone[i]->Branch("extAlgFlag",&extAlgFlag,"extAlgFlag/I");
5276            pam_tree_clone[i]->Branch("RecoveredTrack","TClonesArray",&trk_ext_obj);
5277            cout << "Tracker      : branch RecoveredTrack" << endl;
5278            if(NUC){
5279                pam_tree_clone[i]->Branch("RecoveredTrackNuclei","TClonesArray",&trk_ext_nuc_obj);
5280                cout << "Tracker      : branch RecoveredTrackNuclei" << endl;                  
5281            }
5282        }
5283    
5284      sel_tree_clone = new TTree("SelectionList","List of selected events ");      i++;
5285      sel_tree_clone->Branch("RunEntry",&irun,"runentry/L");    }
     sel_tree_clone->Branch("EventEntry",&irunentry,"eventry/L");  
       
5286    
5287      Int_t i=0;    // Calorimeter
5288      if(TRK1||TRK2||TRKh){    if (CAL1 || CAL2) {
5289          pam_tree_clone[i] = new TTree("Tracker","PAMELA tracker level2 data ");      pam_tree_clone[i] = new TTree("Calorimeter", "PAMELA calorimeter level2 data ");
5290          if(TRK1) {      if (CAL1) {
5291              pam_tree_clone[i]->Branch("TrkLevel1","TrkLevel1", GetPointerTo("TrkLevel1"));        pam_tree_clone[i]->Branch("CaloLevel1", "CaloLevel1", GetPointerTo("CaloLevel1"));
5292              pam_tree_clone[i]->BranchRef();        cout << "Calorimeter  : branch CaloLevel1" << endl;
5293              cout << "Tracker      : branch TrkLevel1"<<endl;      };
5294  //          cout << "CreateCloneTrees " << GetTrkLevel1()<<endl;      if (CAL2) {
5295          };        pam_tree_clone[i]->Branch("CaloLevel2", "CaloLevel2", GetPointerTo("CaloLevel2"));
5296          if(TRK2) {        cout << "Calorimeter  : branch CaloLevel2" << endl;
5297              pam_tree_clone[i]->Branch("TrkLevel2", "TrkLevel2",GetPointerTo("TrkLevel2"));      };
5298              cout << "Tracker      : branch TrkLevel2"<<endl;              if(NUC){
5299          };          pam_tree_clone[i]->Branch("TrackNuclei","TClonesArray",&calo_nuc_obj);
5300          if(TRKh) {          cout << "Calorimeter  : branch TrackNuclei" << endl;    
5301              pam_tree_clone[i]->Branch("TrkHough","TrkHough", GetPointerTo("TrkHough"));      }
5302              cout << "Tracker      : branch TrkHough"<<endl;      if(EXT){
5303          };          pam_tree_clone[i]->Branch("RecoveredTrack","TClonesArray",&calo_ext_obj);
5304          i++;          cout << "Calorimeter  : branch RecoveredTrack" << endl;
5305      }          if(NUC){
5306                pam_tree_clone[i]->Branch("RecoveredTrackNuclei","TClonesArray",&calo_ext_nuc_obj);
5307      // Calorimeter              cout << "Calorimeter  : branch RecoveredTrackNuclei" << endl;                  
5308      if(CAL1||CAL2){          }
5309          pam_tree_clone[i] = new TTree("Calorimeter","PAMELA calorimeter level2 data ");      }
5310          if(CAL1) {      i++;
5311              pam_tree_clone[i]->Branch("CaloLevel1", "CaloLevel1", GetPointerTo("CaloLevel1"));    }
             cout << "Calorimeter  : branch CaloLevel1"<<endl;  
         };  
         if(CAL2) {  
             pam_tree_clone[i]->Branch("CaloLevel2","CaloLevel2", GetPointerTo("CaloLevel2"));  
             cout << "Calorimeter  : branch CaloLevel2"<<endl;  
         };  
         i++;  
     }      
   
     // ToF      
     if(TOF) {  
         pam_tree_clone[i] = new TTree("ToF","PAMELA ToF level2 data ");  
         pam_tree_clone[i]->Branch("ToFLevel2","ToFLevel2", GetPointerTo("ToFLevel2"));  
         cout << "ToF          : branch ToFLevel2"<<endl;  
         i++;  
     };  
     // Trigger  
     if(TRG) {  
         pam_tree_clone[i] = new TTree("Trigger","PAMELA trigger level2 data ");  
         pam_tree_clone[i]->Branch("TrigLevel2","TrigLevel2", GetPointerTo("TrigLevel2"));  
         cout << "Trigger      : branch TrigLevel2"<<endl;  
         i++;  
     };  
     // S4  
     if(S4) {  
         pam_tree_clone[i] = new TTree("S4","PAMELA S4 level2 data ");    
         pam_tree_clone[i]->Branch("S4Level2","S4Level2", GetPointerTo("S4Level2"));  
         cout << "S4           : branch S4Level2"<<endl;  
         i++;  
     };  
     // Neutron Detector  
     if(ND) {  
         pam_tree_clone[i] = new TTree("NeutronD","PAMELA neutron detector level2 data ");        
         pam_tree_clone[i]->Branch("NDLevel2","NDLevel2", GetPointerTo("NDLevel2"));  
         cout << "NeutronD     : branch NDLevel2"<<endl;  
         i++;  
     };  
     // Anticounters  
     if(AC) {  
         pam_tree_clone[i] = new TTree("Anticounter","PAMELA anticounter detector level2 data ");          
         pam_tree_clone[i]->Branch("AcLevel2","AcLevel2", GetPointerTo("AcLevel2"));  
         cout << "Anticounter  : branch AcLevel2"<<endl;  
         i++;  
     };  
     // OrbitalInfo  
     if(ORB) {  
         pam_tree_clone[i] = new TTree("OrbitalInfo","PAMELA oribital info  ");    
         pam_tree_clone[i]->Branch("OrbitalInfo","OrbitalInfo", GetPointerTo("OrbitalInfo"));  
         cout << "OrbitalInfo  : branch OrbitalInfo"<<endl;  
         i++;  
     };  
     cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;  
5312    
5313  }    // ToF
5314      if (TOF) {
5315        pam_tree_clone[i] = new TTree("ToF", "PAMELA ToF level2 data ");
5316        pam_tree_clone[i]->Branch("ToFLevel2", "ToFLevel2", GetPointerTo("ToFLevel2"));
5317        cout << "ToF          : branch ToFLevel2" << endl;
5318        if(NUC){
5319            pam_tree_clone[i]->Branch("TrackNuclei","TClonesArray",&tof_nuc_obj);
5320            cout << "ToF          : branch TrackNuclei" << endl;    
5321        }
5322        if(EXT){
5323            pam_tree_clone[i]->Branch("RecoveredTrack","TClonesArray",&tof_ext_obj);
5324            cout << "ToF          : branch RecoveredTrack" << endl;
5325            if(NUC){
5326                pam_tree_clone[i]->Branch("RecoveredTrackNuclei","TClonesArray",&tof_ext_nuc_obj);
5327                cout << "ToF          : branch RecoveredTrackNuclei" << endl;                  
5328            }
5329        }
5330        i++;
5331      };
5332      // Trigger
5333      if (TRG) {
5334        pam_tree_clone[i] = new TTree("Trigger", "PAMELA trigger level2 data ");
5335        pam_tree_clone[i]->Branch("TrigLevel2", "TrigLevel2", GetPointerTo("TrigLevel2"));
5336        cout << "Trigger      : branch TrigLevel2" << endl;
5337        i++;
5338      };
5339      // S4
5340      if (S4) {
5341        pam_tree_clone[i] = new TTree("S4", "PAMELA S4 level2 data ");
5342        pam_tree_clone[i]->Branch("S4Level2", "S4Level2", GetPointerTo("S4Level2"));
5343        cout << "S4           : branch S4Level2" << endl;
5344        i++;
5345      };
5346      // Neutron Detector
5347      if (ND) {
5348        pam_tree_clone[i] = new TTree("NeutronD", "PAMELA neutron detector level2 data ");
5349        pam_tree_clone[i]->Branch("NDLevel2", "NDLevel2", GetPointerTo("NDLevel2"));
5350        cout << "NeutronD     : branch NDLevel2" << endl;
5351        i++;
5352      };
5353      // Anticounters
5354      if (AC) {
5355        pam_tree_clone[i] = new TTree("Anticounter", "PAMELA anticounter detector level2 data ");
5356        pam_tree_clone[i]->Branch("AcLevel2", "AcLevel2", GetPointerTo("AcLevel2"));
5357        cout << "Anticounter  : branch AcLevel2" << endl;
5358        i++;
5359      };
5360      // OrbitalInfo
5361      if (ORB) {
5362        pam_tree_clone[i] = new TTree("OrbitalInfo", "PAMELA orbital info  ");
5363        pam_tree_clone[i]->Branch("OrbitalInfo", "OrbitalInfo", GetPointerTo("OrbitalInfo"));
5364        cout << "OrbitalInfo  : branch OrbitalInfo" << endl;
5365        if(NUC){
5366            pam_tree_clone[i]->Branch("TrackNuclei","TClonesArray",&orb_nuc_obj);
5367            cout << "OrbitalInfo  : branch TrackNuclei" << endl;    
5368        }
5369        if(EXT){
5370            pam_tree_clone[i]->Branch("RecoveredTrack","TClonesArray",&orb_ext_obj);
5371            cout << "OrbitalInfo  : branch RecoveredTrack" << endl;
5372            if(NUC){
5373                pam_tree_clone[i]->Branch("RecoveredTrackNuclei","TClonesArray",&orb_ext_nuc_obj);
5374                cout << "OrbitalInfo  : branch RecoveredTrackNuclei" << endl;                  
5375            }
5376        }
5377        i++;
5378      };
5379      // GPamela
5380      if (GP) {
5381        pam_tree_clone[i] = new TTree("h20", "GPAMELA info ");
5382        pam_tree_clone[i]->Branch("GPamela", "GPamela", GetPointerTo("GPamela"), 32000, 1);//split
5383        cout << "GPamela  : branch GPamela" << endl;
5384        i++;
5385      };
5386    
5387    
5388      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
5389    
5390    }
5391    
5392  /**  /**
5393   * Fill tree (created with CreateCloneTrees)   * Fill tree (created with CreateCloneTrees)
5394   *   *
5395   */   */
5396  //void PamLevel2::FillNewPamTree(TTree *T){  //void PamLevel2::FillNewPamTree(TTree *T){
5397  void PamLevel2::FillCloneTrees(){  void PamLevel2::FillCloneTrees() {
       
 //    cout << "PamLevel2::FillCloneTrees()" << irunentry << endl;  
5398    
5399      for(Int_t i=0; i<NCLONES; i++){    //    cout << "PamLevel2::FillCloneTrees()" << irunentry << endl;
         if(pam_tree_clone[i])pam_tree_clone[i]->Fill();  
     }  
     if(sel_tree_clone)sel_tree_clone->Fill();      
5400    
5401  }    for (Int_t i = 0; i < NCLONES; i++) {
5402        if (pam_tree_clone[i])
5403          pam_tree_clone[i]->Fill();
5404      }
5405      if (sel_tree_clone)
5406        sel_tree_clone->Fill();
5407    
5408    }
5409    
5410  TTree* PamLevel2::GetCloneTree(TString name){  TTree* PamLevel2::GetCloneTree(TString name) {
5411    
5412      for(Int_t i=0; i<NCLONES; i++){        for (Int_t i = 0; i < NCLONES; i++) {
5413          if(pam_tree_clone[i]){      if (pam_tree_clone[i]) {
5414              TString na = pam_tree_clone[i]->GetName();        TString na = pam_tree_clone[i]->GetName();
5415              if(!name.CompareTo(na))return pam_tree_clone[i];        if (!name.CompareTo(na))
5416          };          return pam_tree_clone[i];
5417      }      };
5418      if(run_tree_clone){    }
5419          TString na = run_tree_clone->GetName();    if (run_tree_clone) {
5420          if(!name.CompareTo(na))return run_tree_clone;      TString na = run_tree_clone->GetName();
5421      }      if (!name.CompareTo(na))
5422      if(sel_tree_clone){        return run_tree_clone;
5423          TString na = sel_tree_clone->GetName();    }
5424          if(!name.CompareTo(na))return sel_tree_clone;    if (sel_tree_clone) {
5425      }      TString na = sel_tree_clone->GetName();
5426      return NULL;      if (!name.CompareTo(na))
5427          return sel_tree_clone;
5428      }
5429      if (proc_tree_clone && PROC) {
5430        TString na = proc_tree_clone->GetName();
5431        if (!name.CompareTo(na))
5432          return proc_tree_clone;
5433      }
5434      return NULL;
5435    
5436  }  }
5437  void PamLevel2::WriteCloneTrees(){  void PamLevel2::WriteCloneTrees() {
5438      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;    cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
5439      cout << "Write clones of PAMELA trees "<<endl;    cout << "Write clones of PAMELA trees " << endl;
5440      cout << run_tree_clone->GetName()<<endl;        cout << run_tree_clone->GetName() << endl;
5441      run_tree_clone->Write();    if (SELLI != 2) {// Emiliano
5442      cout << sel_tree_clone->GetName()<<endl;          if (run_tree_clone->GetBranch("DeadLiveTime")->GetEntries() < run_tree->GetEntries())
5443          run_tree_clone->GetBranch("DeadLiveTime")->Fill();
5444      };
5445      run_tree_clone->Write();
5446      if (SELLI != 2) { //Emiliano
5447        cout << sel_tree_clone->GetName() << endl;
5448      sel_tree_clone->Write();      sel_tree_clone->Write();
5449      for(Int_t i=0; i<NCLONES; i++){        };
5450          if(pam_tree_clone[i]){    for (Int_t i = 0; i < NCLONES; i++) {
5451              cout << pam_tree_clone[i]->GetName()<<endl;      if (pam_tree_clone[i]) {
5452              pam_tree_clone[i]->Write();        cout << pam_tree_clone[i]->GetName() << endl;
5453          };        pam_tree_clone[i]->Write(pam_tree_clone[i]->GetName(),TObject::kOverwrite);
5454      }      };
5455      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;    }
5456      
5457      if ( PROC ){
5458        proc_tree_clone->Write("ProcessingInfo",TObject::kOverwrite);
5459      }
5460      cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" << endl;
5461    
5462  }  }
5463    
5464  /**  /**
5465   * Method to get level2-trees entry, the corresponding run entry and (if required) the level0 entry.   * Method to get level2-trees entry, the corresponding run entry and (if required) the level0 entry.
5466   */   */
5467  //Int_t PamLevel2::GetEntry(Int_t iee){  Int_t PamLevel2::GetEntry(Long64_t iee) {
 Int_t PamLevel2::GetEntry(Long64_t iee){  
       
 //     cout << "-------------------------------------"<<endl;  
 //     cout << "Int_t PamLevel2::GetEntry("<<iee<<")"<<endl;  
   
     if(!pam_tree){  
         cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- level2 trees not loaded"<<endl;  
         return 0;  
     }  
5468    
5469      if (!pam_tree) {
5470        cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- level2 trees not loaded" << endl;
5471        return 0;
5472      }
5473    
5474      //    //
5475      // This is a sort of bug: if you don't have the run tree you don't want to exit here you want to have loaded the event anyway...    // This is a sort of bug: if you don't have the run tree you don't want to exit here you want to have loaded the event anyway...
5476      //    //
5477      //    if(!run_tree ){    //    if(!run_tree ){
5478      //  cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- run tree not loeaded"<<endl;    //    cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- run tree not loeaded"<<endl;
5479      //  return 0;    //    return 0;
5480      //    }    //    }
5481    
5482      Long64_t ii=0;    //-------------------------------
5483      //-------------------------------    if (!pam_tree->GetEntry(iee)) {
5484      ii = iee;      cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- error reading pam tree" << endl;
5485      if( !pam_tree->GetEntry(ii) ){            return 0;
5486          cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- error reading pam tree"<<endl;    }
5487          return 0;    //
5488      // ... 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.
5489      // 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
5490      // a problem if you don't check the return code of getentry.
5491      //
5492      if (!RUN || !run_tree) {
5493        if (TRK0 || CAL0 || TOF0 || RUN) { //forse cosi` va bene per tornare 1?
5494          cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- run tree not loaded" << endl;
5495          return 0;
5496      }      }
5497      //      else {
5498      // ... that's way I put it here. Notice that nothing change in the code (is backward compatible) since in any case you return with 0.        return 1; //cosi` se non c'e` run esce qua...
     // in theory one would like to return 1 if run is not loaded but now I don't have the will to add that 2 lines of code and it is not  
     // a problem if you don't check the return code of getentry.  
     //  
     if(!run_tree ){  
         if ( TRK0 || CAL0 || TOF0 || RUN ) { //forse cosi` va bene per tornare 1?  
             cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- run tree not loaded"<<endl;  
             return 0;  
         }  else {  
             return 1; //cosi` se non c'e` run esce qua...  
         }  
5499      }      }
5500      }
5501    
5502      //-------------------------------
5503      //
5504      if ( fUpdateRunInfo ) UpdateRunInfo(iee); // Emiliano
5505      if (SELLI == 0 || SELLI == 2) irunentry = iee - runfirstentry;
5506    
5507      //-------------------------------    return 1;
     ii = iee;  
 //    Bool_t UPDATED = UpdateRunInfo(run_tree,ii);  
 //    Bool_t UPDATED = UpdateRunInfo(ii);  
     UpdateRunInfo(ii);  
     if(SELLI==0)irunentry = iee-runfirstentry;  
 //    if(UPDATED && run_tree_clone)run_tree_clone->Fill();  
     
 //    cout << "PamLevel2::GetEntry("<<iee<<") "<<irun<<" "<<runfirstentry<<" "<<irunentry<<endl;  
   
 //     cout << "irunentry     "<<irunentry << endl;  
 //     cout << "runfirstentry "<<runfirstentry << endl;  
 //     cout << "nevents       "<<GetRunInfo()->NEVENTS<< endl;  
   
 //     if( TRK0 || CAL0 || TOF0 ){  
 //      if( !GetYodaEntry( ) ){  
 //          cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- error reading level0 tree"<<endl;  
 //          return 0;  
 //      }  
 //     }  
   
   
     return 1;  
5508    
5509  }  }
5510    
5511  TrkLevel0    *PamLevel2::GetTrkLevel0(){  TrkLevel0 *PamLevel2::GetTrkLevel0() {
5512      if( !TRK0 )return NULL;    if (!TRK0)
5513      if( !GetYodaEntry( ) ){      return NULL;
5514          cout << " Int_t PamLevel2::GetTrkLevel0() -- ERROR -- error reading level0 tree"<<endl;    if (!GetYodaEntry()) {
5515          return 0;      cout << " Int_t PamLevel2::GetTrkLevel0() -- ERROR -- error reading level0 tree" << endl;
5516      }      return 0;
5517      return trk0_obj;    }
5518  };    return trk0_obj;
5519  CaloLevel0    *PamLevel2::GetCaloLevel0(){  }
5520      if( !CAL0 )return NULL;  ;
5521      if( !GetYodaEntry( ) ){  CaloLevel0 *PamLevel2::GetCaloLevel0() {
5522          cout << " Int_t PamLevel2::GetCaloLevel0() -- ERROR -- error reading level0 tree"<<endl;    if (!CAL0)
5523          return 0;      return NULL;
5524      }    if (!GetYodaEntry()) {
5525      return calo0_obj;      cout << " Int_t PamLevel2::GetCaloLevel0() -- ERROR -- error reading level0 tree" << endl;
5526  };      return 0;
5527      }
5528      return calo0_obj;
5529    }
5530    ;
5531    
5532  /**  /**
5533   * Method to retrieve the level0 tree (YODA tree) that contains the current event.   * Method to retrieve the level0 tree (YODA tree) that contains the current event.
# Line 3001  CaloLevel0    *PamLevel2::GetCaloLevel0( Line 5535  CaloLevel0    *PamLevel2::GetCaloLevel0(
5535   * @return Pointer to the tree   * @return Pointer to the tree
5536   */   */
5537    
5538    TTree* PamLevel2::GetYodaTree() {
5539    
5540  TTree* PamLevel2::GetYodaTree( ){    //    cout << "TTree* PamLevel2::GetYodaTree( )"<<endl;
5541          //===================================
5542  //    cout << "TTree* PamLevel2::GetYodaTree( )"<<endl;    // check if iroot has changed
5543      //===================================    //===================================
5544      // check if iroot has changed    if (irun < 0) {
5545      //===================================      cout << "PamLevel2::GetYodaTree() -- ERROR -- irun = " << irun << endl;
5546      if( irun<0 ){      if (DBG) cout << "In order to use this method you have to first load the RunInfo tree "<<endl;
5547          cout << "PamLevel2::GetYodaTree() -- ERROR -- irun = "<<irun<<endl;      return NULL;
5548  //      cout << "In order to use this method you have to first load the RunInfo tree "<<endl;    }
5549          return NULL;    Int_t irootnew = GetRunInfo()->ID_ROOT_L0;
5550      }        if (DBG){
5551      Int_t irootnew = run_obj->ID_ROOT_L0;      cout << "iroot    "<<iroot<<endl;
5552  //      cout << "iroot    "<<iroot<<endl;      cout << "irootnew "<<irootnew<<endl;
5553  //      cout << "irootnew "<<irootnew<<endl;    }
5554    
5555      //===================================
5556      // load the level0 file
5557      // (if not already loaded)
5558      //===================================
5559      if (iroot != irootnew || !l0_tree) {
5560        iroot = irootnew;
5561      //===================================      //===================================
5562      // load the level0 file      // open the DB connection
5563      // (if not already loaded)      // (if not already opened)
5564      //===================================      //===================================
5565      if( iroot != irootnew || !l0_tree){      if (!dbc || (dbc && !dbc->IsConnected()))
5566          iroot = irootnew;        SetDBConnection();
5567          //===================================      GL_ROOT glroot = GL_ROOT();
5568          // open the DB connection      if (glroot.Query_GL_ROOT(iroot, dbc)) {
5569          // (if not already opened)        cout << "TTree* PamLevel2::GetYodaTree( ) -- ERROR -- level0 file iroot = " << iroot << " does not exists"
5570          //===================================            << endl;
5571          if(!dbc || (dbc && !dbc->IsConnected())){        return NULL;
5572              cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;      };
5573              cout<<"Connecting to DB"<<endl;      TString filename = glroot.PATH + glroot.NAME;
5574              cout<<"HOST "<<host<<endl;      if (l0_file) {
5575              cout<<"USER "<<user<<endl;        l0_file->Close();
5576              cout<<"PSW  "<<psw<<endl;        l0_file->Delete();
             dbc = TSQLServer::Connect(host.Data(),user.Data(),psw.Data());  
             if( !dbc )return NULL;  
             if( !dbc->IsConnected() )return NULL;      
 //          cout<<"...done"<<endl;  
             cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;  
         }else{  
 //          cout<<"DB already connected"<<endl;  
         }  
         GL_ROOT glroot = GL_ROOT();  
         if( glroot.Query_GL_ROOT(iroot,dbc) ){  
             cout << "TTree* PamLevel2::GetYodaTree( ) -- ERROR -- level0 file iroot = "<<iroot<< " does not exists"<<endl;  
             return NULL;  
         };  
         TString filename = glroot.PATH + glroot.NAME;  
         if(l0_file){  
             l0_file->Close();  
             l0_file->Delete();  
         }  
         cout << "Opening LEVEL0 file: "<< filename << endl;  
         FileStat_t t;  
         if( gSystem->GetPathInfo(filename.Data(),t) ){  
             cout << " PamLevel2::GetYodaTree() -- ERROR opening file "<<endl;  
             return NULL;  
         }  
         l0_file = new TFile(filename);  
         if( !l0_file )return NULL;  
         l0_tree = (TTree*)l0_file->Get("Physics");  
         if(!h0_obj)h0_obj = new EventHeader();  
         l0_tree->SetBranchAddress("Header" ,&h0_obj);  
         prevshift = 0;  
         //---------------------------------------------------  
         // TRACKER:  
         if(TRK0){  
             if(!trk0_obj){  
                 trk0_obj = new TrkLevel0();  
                 trk0_obj->Set();  
             };  
             l0_tree->SetBranchAddress("Tracker" ,trk0_obj->GetPointerToTrackerEvent());  
         }  
         //--------------------------------------------------  
         // CALORIMETER:  
         if(CAL0){  
             if(!calo0_obj){  
                 calo0_obj = new CaloLevel0();  
                 calo0_obj->Set();  
             };  
             l0_tree->SetBranchAddress("Calorimeter" ,calo0_obj->GetPointerToCalorimeterEvent());  
             //      cout << "PamLevel2::GetYodaTree() --- level0 calorimeter not implemented "<<endl;  
         }  
         //---------------------------------------------------  
         // TOF:  
         if(TOF0){  
             cout << "PamLevel2::GetYodaTree() --- level0 TOF not implemented "<<endl;  
         }  
   
     };  
   
     if(!dbc || (dbc && !dbc->IsConnected())){  
         cout << " TTree* PamLevel2::GetYodaTree( ) -- no DB connected... hai fatto qualche cazzata "<<endl;  
5577      }      }
5578        cout << "Opening LEVEL0 file: " << filename << endl;
5579      if ( TRK0 ){      FileStat_t t;
5580          TrkParams::Load(6);      if (gSystem->GetPathInfo(filename.Data(), t)) {
5581          if( !TrkParams::IsLoaded(6) ){        cout << " PamLevel2::GetYodaTree() -- ERROR opening file " << endl;
5582              cout << " TTree* PamLevel2::GetYodaTree( ) -- WARNING -- VK-mask not loaded"<<endl;        return NULL;
5583          };      }
5584          TrkParams::SetCalib(run_obj,dbc);      l0_file = new TFile(filename);
5585          TrkParams::LoadCalib( );      if (!l0_file)
5586          if( !TrkParams::CalibIsLoaded() ){        return NULL;
5587              cout << " TTree* PamLevel2::GetYodaTree( ) -- WARNING -- Calibration not loaded"<<endl;      l0_tree = (TTree*) l0_file->Get("Physics");
5588          };      if (!h0_obj)
5589          h0_obj = new EventHeader();
5590        l0_tree->SetBranchAddress("Header", &h0_obj);
5591        yprevshift = 0; // yes, yprevshift is the shift in the level0, prevshift is the shift in the level2
5592        //---------------------------------------------------
5593        // TRACKER:
5594        if (TRK0) {
5595          if (!trk0_obj) {
5596            trk0_obj = new TrkLevel0();
5597            trk0_obj->Set();
5598          };
5599          l0_tree->SetBranchAddress("Tracker", trk0_obj->GetPointerToTrackerEvent());
5600        }
5601        //--------------------------------------------------
5602        // CALORIMETER:
5603        if (CAL0) {
5604          if (!calo0_obj) {
5605            calo0_obj = new CaloLevel0();
5606            calo0_obj->Set();
5607          };
5608          l0_tree->SetBranchAddress("Calorimeter", calo0_obj->GetPointerToCalorimeterEvent());
5609        }
5610        //---------------------------------------------------
5611        // TOF:
5612        if (TOF0) {
5613          cout << "PamLevel2::GetYodaTree() --- level0 TOF not implemented " << endl;
5614      }      }
5615    
5616  //    cout << l0_tree << endl;      dbc->Close(); // EMILIANO, do not leave open connections, open only when needed
5617            delete dbc;
5618      return l0_tree;      dbc=0;
5619    
5620      };
5621    
5622      if (TRK0) {
5623        if(!dbc || (dbc && !dbc->IsConnected()))SetDBConnection();
5624        TrkParams::SetCalib(run_obj, dbc);
5625        TrkParams::LoadCalib();
5626        if (!TrkParams::CalibIsLoaded()) {
5627          cout << " TTree* PamLevel2::GetYodaTree( ) -- WARNING -- Calibration not loaded" << endl;
5628        };
5629        if(dbc){
5630          dbc->Close(); // EMILIANO, do not leave open connections, open only when needed
5631          delete dbc;
5632          dbc=0;
5633        };
5634      }
5635      return l0_tree;
5636  }  }
5637    
5638  /**  /**
5639   * Method to retrieve the level0 tree (YODA tree) that contains the current event.   * Method to retrieve the level0 tree (YODA tree) that contains the current event.
5640   */   */
5641  Int_t PamLevel2::GetYodaEntry(){  Int_t PamLevel2::GetYodaEntry() {
5642    
5643  //    cout << "Int_t PamLevel2::GetYodaEntry()"<<endl;    Long64_t iev = this->GetReadEntry();
5644      if(!GetYodaTree())return 0;  
5645          // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
5646      // patch    // if it is a full file (not preselected)
5647      if( irunentry < 0){    // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
5648  //      cout << "Int_t PamLevel2::GetYodaEntry() -- ATTENZIONE -- irunentry negativo?!?! "<<(Int_t)irunentry<<endl;    //  if (SELLI == 0 || SELLI == 2 || !hasL0EE) {
5649          irunentry=0LL;  
5650        if (!GetYodaTree()){
5651          printf(" PamLevel2::GetYodaEntry() : ERROR no level0 file loaded!\n");
5652          return 0;
5653        }
5654    
5655        if (irunentry < 0) {
5656          if (DBG) cout << "Int_t PamLevel2::GetYodaEntry() -- ATTENZIONE -- irunentry negativo?!?! "<<(Int_t)irunentry<<endl;
5657          //      cout << "Int_t PamLevel2::GetYodaEntry() -- ATTENZIONE -- irunentry negativo?!?! "<<(Int_t)irunentry<<endl; // TOGLITOGLI
5658          irunentry = 0LL;
5659      }      }
5660      //  ---------------------------------      //  ---------------------------------
5661      //  if file is NOT a preselected file      //  if file is NOT a preselected file
5662      //  ---------------------------------      //  ---------------------------------
5663      Long64_t quellagiusta = irunentry + (Long64_t)(run_obj->EV_FROM);      Long64_t quellagiusta = irunentry + (Long64_t)(run_obj->EV_FROM); // prevshift already included in irunentry
5664  //     cout << " irunentry "<<irunentry<<endl;  
5665  //     cout << " EV_FROM "<<run_obj->EV_FROM<<endl;      if (DBG){
5666  //     cout << " quellagiusta = irunentry + EV_FROM "<< quellagiusta << endl;        cout << " irun "<< irun << " irunentry "<< irunentry<<" run_obj->EV_FROM "<<run_obj->EV_FROM <<" quella giusta "<<quellagiusta << endl;
5667          cout << " iroot "<<iroot<<" run_obj->ID_ROOT_L0 "<<run_obj->ID_ROOT_L0<<endl;
5668  //     cout << " irun "<< irun << " irunentry "<< irunentry<<" run_obj->EV_FROM "<<run_obj->EV_FROM <<" quella giusta "<<quellagiusta << endl;        cout << " time "<< abstime << endl;
5669  //     cout << " iroot "<<iroot<<" run_obj->ID_ROOT_L0 "<<run_obj->ID_ROOT_L0<<endl;      }
5670  //     cout << " time "<< GetOrbitalInfo()->absTime << endl;  
5671  //     cout << " trk_calib_used "<<run_obj->TRK_CALIB_USED<< endl;      ULong64_t obt = 0;
5672            ULong64_t pktn = 0;
5673      if( !GetOrbitalInfo() ){      if (GetOrbitalInfo()) {
5674          cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- missing OrbitalInfo "<<endl;        obt = GetOrbitalInfo()->OBT;
5675          return 0;        pktn = GetOrbitalInfo()->pkt_num;
5676      }      }
5677      if( GetOrbitalInfo()->OBT==0 && GetOrbitalInfo()->pkt_num==0 ){  
5678          cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- level2 event corrupted ?? "<<endl;      if (!GetOrbitalInfo() && !ISGP) {
5679          return 0;        cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- missing OrbitalInfo " << endl;
5680          return 0;
5681        }
5682        if (obt == 0 && pktn == 0 && !ISGP) {
5683          cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- level2 event corrupted ?? " << endl;
5684          return 0;
5685      }      }
5686    
5687      // ---------------------------------------------------------------------      // ---------------------------------------------------------------------
# Line 3158  Int_t PamLevel2::GetYodaEntry(){ Line 5695  Int_t PamLevel2::GetYodaEntry(){
5695      // of the OBT and pkt-number. In case of mismatch, the level0 entry number      // of the OBT and pkt-number. In case of mismatch, the level0 entry number
5696      // is shift forward until when the packets match.      // is shift forward until when the packets match.
5697      // ---------------------------------------------------------------------      // ---------------------------------------------------------------------
5698      Int_t answer = 0;      Long64_t shift = 0LL;
5699      Int_t shift =0;      Long64_t answer = quellagiusta + shift + yprevshift;
5700      //    printf(" siamo qui %i %i \n",shift,prevshift);      Int_t readl0 = 0;
5701      Int_t maxshift = 10;      readl0 = l0_tree->GetEntry(answer); // prevshift already included in irunentry
5702      do{  
5703          if(shift>0){          if (DBG){
5704              cout << " PKTNUM  L2 --- "<< GetOrbitalInfo()->pkt_num << " --- L0 --- "<< GetEventHeader()->GetPscuHeader()->GetCounter()<<endl;        printf(" siamo qui shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);
5705              cout << "         RUN: ID "<< GetRunInfo()->ID << " ID_ROOT_L0 "<<run_obj->ID_ROOT_L0<<" ID_RUN_FRAG "<<GetRunInfo()->ID_RUN_FRAG << " EV_FROM "<<GetRunInfo()->EV_FROM  <<endl;      }
5706              cout << "         L2 <--> L0 mismatch ( irun "<<irun<<" irunentry "<<irunentry<<" shift "<<shift<<" prevshift "<<prevshift<<" )"<<endl;  
5707          }  
5708          answer = l0_tree->GetEntry(quellagiusta+(Long64_t)shift+(Long64_t)prevshift);      if (ISGP) {
5709          shift++;        obt = (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()); //BARBATRUCCO
5710          if( !GetEventHeader() ){        pktn = (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter()); //BARBATRUCCO
5711              cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- missing EventHeader "<<endl;      }
5712              return 0;  
5713          }      while ( (obt != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()) || pktn != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter())) && (quellagiusta + (Long64_t) shift) < GetYodaTree()->GetEntries() && shift < maxshift ){
5714  //      cout << "PKTNUM "<<shift<<" ==  L2 --- "<< GetOrbitalInfo()->pkt_num << " --- L0 --- "<< GetEventHeader()->GetPscuHeader()->GetCounter()<<endl;        if ( isSync && shift == 0LL ){
5715  //      cout << " L2 --- "<< GetOrbitalInfo()->OBT << " --- L0 --- "<< GetEventHeader()->GetPscuHeader()->GetOrbitalTime()<<endl;          printf(" PamLevel2::GetYodaEntry() ERROR! sync file but the level0 entry not found in place!!! \n");
5716  //      if( (quellagiusta+shift) == l0_tree->GetEntries()+1 )cout << ">>> end of level0 tree <<<"<<endl;          cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
5717  //      cout << " GetOrbitalInfo()->OBT "<< GetOrbitalInfo()->OBT << endl;          cout << "\nFor bug reporting instructions, please see for example:\n";
5718  //      cout << " GetEventHeader()->GetPscuHeader()->GetOrbitalTime() "<< GetEventHeader()->GetPscuHeader()->GetOrbitalTime() << endl;          cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
5719  //      cout << " GetOrbitalInfo()->pkt_num "<< GetOrbitalInfo()->pkt_num << endl;          cout << "  " << endl;
5720  //      cout << " GetEventHeader()->GetPscuHeader()->GetCounter() "<< GetEventHeader()->GetPscuHeader()->GetCounter() << endl;        }
5721  //      printf(" IDRUN %u \n",GetRunInfo()->ID);        if (shift > 0) {
5722  //          if (DBG) cout << " PKTNUM  L2 --- " << pktn << " --- L0 --- " << GetEventHeader()->GetPscuHeader()->GetCounter() << endl;
5723          if ( prevshift != 0 && (quellagiusta+(Long64_t)shift) == GetYodaTree()->GetEntries() ){          if (DBG)
5724            prevshift = 0;            cout << "         RUN: ID " << GetRunInfo()->ID << " ID_ROOT_L0 " << run_obj->ID_ROOT_L0 << " ID_RUN_FRAG "
5725            shift = -1;                 << GetRunInfo()->ID_RUN_FRAG << " EV_FROM " << GetRunInfo()->EV_FROM << endl;
5726          };          if (DBG)
5727              cout << "         L2 <--> L0 mismatch ( irun " << irun << " irunentry " << irunentry << " shift " << shift
5728      }while( ( GetOrbitalInfo()->OBT != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()) || GetOrbitalInfo()->pkt_num != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter())) && (quellagiusta+(Long64_t)shift) < GetYodaTree()->GetEntries() && shift < maxshift);                 << " prevshift " << prevshift << " )" << endl;
5729          }
5730      if ( (quellagiusta+(Long64_t)shift+(Long64_t)prevshift) > GetYodaTree()->GetEntries() || shift == maxshift ) {        answer = quellagiusta +  shift+ yprevshift;
5731          cout << " Big trouble here, no such event in Level0 data! " <<endl;        readl0 = l0_tree->GetEntry(answer);
5732          return 0;        //      printf(" inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);//TOGLITOGLI
5733      }  
5734  //    cout << "LA ENTRY GIUSTA E`: "<<quellagiusta<<" (spero...)"<<endl;        if (!GetEventHeader()) {
5735  //    return GetYodaTree()->GetEntry(quellagiusta);          cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- missing EventHeader " << endl;
5736      if ( shift > 1 ) prevshift += (shift-1);          return 0;
5737              }
5738      return answer;  
5739          //
5740          if (yprevshift != 0 && (quellagiusta + (Long64_t) shift) == GetYodaTree()->GetEntries()) {
5741            if (DBG) printf(" reset inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);
5742            //        printf(" reset inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);//TOGLITOGLI
5743            yprevshift = 0LL;
5744            shift = -1LL;
5745          };
5746            
5747          shift++;
5748        }
5749                                      
5750    
5751        if ( obt != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()) || pktn != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter()) ){
5752          if ( isSync ){
5753            printf(" PamLevel2::GetYodaEntry() ERROR! sync file but the level0 entry not found AT ALL!!! \n");
5754            cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
5755            cout << "\nFor bug reporting instructions, please see for example:\n";
5756            cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
5757            cout << "  " << endl;
5758          }
5759          cout << "Int_t PamLevel2::GetYodaEntry() -- WARNING -- " << endl;
5760          cout << " Big trouble here, no such event in Level0 data! (NB maxshift set to " << maxshift << " )" << endl;    
5761          cout << " Nested and/or DarthVader skipped packets in fragmented run? checking and trying to fix " <<endl;
5762          // query the DB for runs containing the event, loop over LEVEL0 files which could contain the level0 event and try to find it
5763          // 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
5764          // connect to db
5765          if (!dbc || (dbc && !dbc->IsConnected())) SetDBConnection(); //Emiliano
5766          //
5767          if (GetOrbitalInfo()){
5768            abstime = GetOrbitalInfo()->absTime;
5769          } else {
5770            printf(" PamLevel2::GetYodaEntry() ERROR! no OrbitalInfo, cannot get the absolute time for event \n");
5771            return 0;
5772          }
5773          // query DB looking for runs containing the processed event
5774          TSQLResult *pResult;
5775          TSQLRow *Row = NULL;
5776          TString myquery = Form("select ID,NEVENTS from GL_RUN where RUNHEADER_TIME<=%lld and RUNTRAILER_TIME>=%lld;",abstime,abstime);
5777          if ( DBG ) printf(" query is %s \n",myquery.Data());
5778          //      printf(" query is %s \n",myquery.Data());// TOGLITOGLI
5779          pResult = dbc->Query(myquery.Data());    
5780          if (!pResult->GetRowCount()){
5781            printf(" PamLevel2::GetYodaEntry() ERROR! event is not included in any run!!! \n");
5782            cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
5783            cout << "\nFor bug reporting instructions, please see for example:\n";
5784            cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
5785            cout << "  " << endl;
5786            return 0;
5787          }
5788          if ( pResult->GetRowCount() == 1 ){
5789            if (DBG) printf(" PamLevel2::GetYodaEntry() - WARNING - YodaEntry not found but only one run containing the event, it should not happen \n");
5790            //        printf(" PamLevel2::GetYodaEntry() - WARNING - YodaEntry not found but only one run containing the event, it should not happen \n");//TOGLITOGLI
5791          }
5792          for( Int_t ru=0; ru < pResult->GetRowCount(); ru++){ // loop over runs containing the event
5793            if (Row) delete Row;
5794            Row = pResult->Next();  
5795            if( Row == NULL ) break;
5796            UInt_t idrun = (UInt_t)atoll(Row->GetField(0));
5797            UInt_t nev = (UInt_t)atoll(Row->GetField(1));
5798            if (DBG) printf(" inside loop over runs: ru %i idrun %i nev %i \n",ru,idrun,nev);
5799            //        printf(" inside loop over runs: ru %i idrun %i nev %i \n",ru,idrun,nev);//TOGLITOGLI
5800    
5801            // now look for this run in the level2 file, it must be present! code is taken from updateruninfo of course
5802            Bool_t rfound = false;
5803            totrunentry = 0LL;
5804            runfirstentry = 0LL;
5805            for (Int_t r=0; r< run_tree->GetEntries();r++){
5806              run_tree->GetEntry(r);//update runinfo
5807              if ( r > 0 ){
5808                totrunentrymin = totrunentrymax+1;
5809              } else {
5810                totrunentrymin = 0LL;
5811              }
5812              totrunentry += GetRunInfo()->NEVENTS;
5813              totrunentrymax = totrunentry - 1 - prevshift; // prevshift is needed to handle nested+DV_skipped packets
5814              irun = r;        
5815    
5816              if (idrun == GetRunInfo()->ID){
5817                if ( totrunentrymin > iev ){ // there is a shift (nested+DV_skipped packets)
5818                  if (DBG) printf("PamLevel2::GetYodaEntry - unconsistent iev - nevents, probable DBL0-L2 async\n");
5819                  if (DBG) printf("PamLevel2::GetYodaEntry - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);
5820                  //              printf("PamLevel2::GetYodaEntry - unconsistent iev - nevents, probable DBL0-L2 async\n");
5821                  //              printf("PamLevel2::GetYodaEntry - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);//TOGLITOGLI
5822                  prevshift += (totrunentrymin-iev); // add the new shift to total shift
5823                  totrunentrymin -= (totrunentrymin-iev); // shift run position min
5824                  totrunentrymax -= (totrunentrymin-iev); // shift run position max
5825                  if (DBG) printf("PamLevel2::GetYodaEntry - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);
5826                  //              printf("PamLevel2::GetYodaEntry - totrunentrymin %lld iev %lld prevshift %lld totrunentrymax %lld \n",totrunentrymin,iev,prevshift,totrunentrymax);//TOGLITOGLI
5827                }
5828                runfirstentry = totrunentrymin; // first entry of the run in the level2
5829              
5830    
5831                //
5832                if (gltsync)
5833                  delete gltsync; // Emiliano
5834                if (!dbc || (dbc && !dbc->IsConnected()))
5835                  SetDBConnection(); //Emiliano
5836                gltsync = new GL_TIMESYNC(GetRunInfo()->ID_ROOT_L0, "ID", dbc, false); // Emiliano
5837                if (dbc){
5838                  dbc->Close(); // Emiliano
5839                  delete dbc;
5840                  dbc=0;
5841                }          
5842                if (gltsync->DBobt(GetRunInfo()->RUNHEADER_OBT) > gltsync->DBobt(GetRunInfo()->RUNTRAILER_OBT)) { // Emiliano
5843                  cout << "Bool_t PamLevel2::UpdateRunInfo(Long64_t iev) -- WARNING -- irun " << irun
5844                       << "  has RUNHEADER_OBT>=RUNTRAILER_OBT " << endl;
5845                  cout
5846                    << "                                                            (NB!! in this case some events could be assigned to a wrong run)"
5847                    << endl;
5848                }
5849                //
5850                if (DBG) printf(" found \n");
5851                //            printf(" found \n");//TOGLITOGLI
5852                rfound = true;
5853                //
5854                break;
5855              }
5856            } // loop over run
5857            if ( !rfound ){
5858              printf(" PamLevel2::GetYodaEntry() ERROR! run is not present in the level2 file!!! \n");
5859              cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
5860              cout << "\nFor bug reporting instructions, please see for example:\n";
5861              cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
5862              cout << "  " << endl;        
5863              return 0;
5864            }
5865    
5866            // here we got the first run and we can check if it contains the level0 event
5867            if (!GetYodaTree()){
5868              printf(" PamLevel2::GetYodaEntry() : ERROR no level0 file loaded!\n");
5869              return 0;
5870            }      
5871    
5872            // get the current run entry
5873            irunentry = iev - runfirstentry;
5874            if (irunentry < 0) {
5875              if (DBG) cout << "Int_t PamLevel2::GetYodaEntry() -- ATTENZIONE -- irunentry negativo?!?! "<<(Int_t)irunentry<<endl;
5876              //          cout << "Int_t PamLevel2::GetYodaEntry() -- ATTENZIONE -- irunentry negativo?!?! "<<(Int_t)irunentry<<endl; // TOGLITOGLI
5877              irunentry = 0LL;
5878            }
5879            //  ---------------------------------
5880            //  if file is NOT a preselected file
5881            //  ---------------------------------
5882            quellagiusta = irunentry + (Long64_t)(run_obj->EV_FROM); // prevshift already included in irunentry
5883          
5884            if (DBG){
5885              cout << " irun "<< irun << " irunentry "<< irunentry<<" run_obj->EV_FROM "<<run_obj->EV_FROM <<" quella giusta "<<quellagiusta << endl;
5886              cout << " iroot "<<iroot<<" run_obj->ID_ROOT_L0 "<<run_obj->ID_ROOT_L0<<endl;
5887              cout << " time "<< abstime << endl;
5888            }
5889            //        cout << " irun "<< irun << " irunentry "<< irunentry<<" run_obj->EV_FROM "<<run_obj->EV_FROM <<" quella giusta "<<quellagiusta << endl;
5890            //        cout << " iroot "<<iroot<<" run_obj->ID_ROOT_L0 "<<run_obj->ID_ROOT_L0<<endl;
5891            //        cout << " time "<< abstime << endl; // TOGLITOGLI
5892          
5893            shift = 0;
5894            answer = quellagiusta + shift + yprevshift; // prevshift already included in irunentry
5895            readl0 = l0_tree->GetEntry(answer); // prevshift already included in irunentry
5896    
5897            if (DBG){
5898              printf(" siamo qua shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);
5899            }
5900            //        printf(" siamo qua shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);//TOGLITOGLI
5901          
5902            while ( (obt != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()) || pktn != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter())) && (quellagiusta + (Long64_t) shift) < GetYodaTree()->GetEntries() && shift < maxshift ){
5903              if (shift > 0) {
5904                if (DBG) cout << " PKTNUM  L2 --- " << pktn << " --- L0 --- " << GetEventHeader()->GetPscuHeader()->GetCounter() << endl;
5905                if (DBG)
5906                  cout << "         RUN: ID " << GetRunInfo()->ID << " ID_ROOT_L0 " << run_obj->ID_ROOT_L0 << " ID_RUN_FRAG "
5907                       << GetRunInfo()->ID_RUN_FRAG << " EV_FROM " << GetRunInfo()->EV_FROM << endl;
5908                if (DBG)
5909                  cout << "         L2 <--> L0 mismatch ( irun " << irun << " irunentry " << irunentry << " shift " << shift
5910                       << " prevshift " << prevshift << " )" << endl;
5911              }
5912              answer = quellagiusta +  shift+ yprevshift;
5913              readl0 = l0_tree->GetEntry(answer);
5914              //          printf(" inside inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);//TOGLITOGLI
5915            
5916              if (!GetEventHeader()) {
5917                cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- missing EventHeader " << endl;
5918                return 0;
5919              }
5920              //
5921              if (yprevshift != 0 && (quellagiusta + (Long64_t) shift) == GetYodaTree()->GetEntries()) {
5922                if (DBG) printf(" reset inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);
5923                //            printf(" reset inside while shift %lld yprevshift %lld answer %lld \n",shift,yprevshift,answer);//TOGLITOGLI
5924                yprevshift = 0;
5925                shift = -1;
5926              };
5927            
5928              shift++;
5929            }
5930          
5931            if ( obt != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()) || pktn != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter()) ){
5932              //still not the good run... continue with the nex one!
5933              printf("still not the good run... continue with the nex one!\n");
5934            } else {
5935              if (DBG) cout << "LA ENTRY GIUSTA E`: "<<quellagiusta<<" (spero...)"<<endl;
5936              //          cout << "LA ENTRY GIUSTA E`: "<<answer<<" (spero...)"<<endl;//TOGLITOGLI
5937              if (shift > 1) yprevshift = (shift - 1);
5938              if (Row) delete Row;
5939              delete pResult;  
5940              if (dbc){
5941                dbc->Close(); // Emiliano
5942                delete dbc;
5943                dbc=0;
5944              }    
5945              il0entry = answer;
5946              return readl0;
5947            }
5948            // perhaps it is all
5949          }// loop over runs containing the event
5950          if (Row) delete Row;
5951          delete pResult;  
5952          if (dbc){
5953            dbc->Close(); // Emiliano
5954            delete dbc;
5955            dbc=0;
5956          }          
5957          // arriving here it means no run found, cannot be! error!
5958          printf(" PamLevel2::GetYodaEntry() ERROR! run is not present in the level0 files!!! \n");
5959          cout << " OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
5960          cout << "\nFor bug reporting instructions, please see for example:\n";
5961          cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
5962          cout << "  " << endl;        
5963          return 0;
5964        } else {
5965          if (DBG) cout << "=> LA ENTRY GIUSTA E`: "<<answer<<" (spero...)"<<endl;
5966          //    cout << "=> LA ENTRY GIUSTA E`: "<<answer<<" (spero...)"<<endl;
5967          //    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()) );
5968          if (shift > 1) yprevshift = (shift - 1);
5969          il0entry = answer;
5970          return readl0;
5971        }
5972    
5973        /*  } // if selli 0 || 2
5974      if ( SELLI == 1 && hasL0EE ){
5975        sel_tree->GetEntry(iev);  
5976        Long64_t answer = il0entry;
5977        Int_t readl0 = 0;
5978        readl0 = l0_tree->GetEntry(answer);
5979        return readl0;
5980        }*/
5981      printf(" PamLevel2::GetYodaEntry() ERROR! \n");
5982      cout << " Entry not found! OK this is a bug, write to Emiliano, Emiliano.Mocchiutti@ts.infn.it " << endl;
5983      cout << "\nFor bug reporting instructions, please see for example:\n";
5984      cout << "     <http://www.ts.infn.it/~mocchiut/bugs/bugs.html>.\n";
5985      cout << "  " << endl;
5986      return 0;
5987  }  }
5988    
5989  /**  /**
5990   * \Brief Set DB connection   * \Brief Set DB connection
5991   */   */
5992  Bool_t PamLevel2::SetDBConnection(){  Bool_t PamLevel2::SetDBConnection() {
5993    
5994      //    cout << "PamLevel2::SetDBConnection()" << endl;
5995      if (DBG) {
5996        cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
5997        cout << "Connecting to DB" << endl;
5998        cout << "HOST " << host << endl;
5999        cout << "USER " << user << endl;
6000        cout << "PSW  " << psw << endl;
6001      }
6002      Bool_t notconn = true;
6003      Int_t trials = 0;
6004      while ( notconn && trials < 10 ){
6005        //    gSystem->Sleep(500);
6006        dbc = TSQLServer::Connect(host.Data(), user.Data(), psw.Data());
6007        //dbc->Connect(host.Data(), user.Data(), psw.Data());
6008        if ( dbc ) notconn = false;
6009        if (DBG) printf("<%i> test connection...\n ",trials);
6010        if (!dbc){
6011          if (DBG) printf(" :( failed, no pointer \n");
6012          notconn = true;
6013          //      return false;
6014        };
6015        if (dbc && !dbc->IsConnected()){
6016          if (DBG) printf(" :( failed, no connection \n");
6017          notconn = true;
6018          //      return false;
6019        };
6020        trials++;
6021      };
6022      if ( notconn ) return false;
6023      //
6024      if (DBG) printf("=connected!\n");
6025      stringstream myquery; // EMILIANO
6026      myquery.str(""); // EMILIANO
6027      myquery << "SET time_zone='+0:00'"; // EMILIANO
6028      dbc->Query(myquery.str().c_str()); // EMILIANO
6029      if ( DBG ) printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
6030      return true;
6031    
6032    }
6033    
6034    /**
6035     * \Brief Add a friend to the pamela chain.
6036     * @param cname name of the chain to be added
6037     */
6038    
6039    TChain* PamLevel2::AddFriend(TString cname) {
6040    
6041      if (!GetPamTree()) {
6042        cout << " TChain* PamLevel2::AddFriend(TString cname) --- a pamela tree must be created first" << endl;
6043        return NULL;
6044      }
6045    
6046      TChain *c = new TChain(cname.Data());
6047    
6048      TIter next(GetPamTree()->GetListOfFiles());
6049      Int_t nf = 0;
6050      TChainElement* element = 0;
6051      while ((element = (TChainElement*) next())) {
6052        c->Add(element->GetTitle());
6053        nf++;
6054      }
6055    
6056      GetPamTree()->AddFriend(cname.Data());
6057    
6058      cout << "external chain created and added to pamela friends :" << cname << endl;
6059      cout << "n.files " << nf << endl;
6060    
6061      return c;
6062    
6063      cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;  }
6064      cout<<"Connecting to DB"<<endl;  
6065      cout<<"HOST "<<host<<endl;  /**
6066      cout<<"USER "<<user<<endl;   * Returns the current read entry. This method simply returns the result of the call to
6067      cout<<"PSW  "<<psw<<endl;   * pam_tree->GetReadEntry(), so it is entirely handled by ROOT.
6068      dbc = TSQLServer::Connect(host.Data(),user.Data(),psw.Data());   */
6069      if( !dbc )return false;  Long64_t PamLevel2::GetReadEntry() {
6070      if( !dbc->IsConnected() )return false;        return pam_tree->GetReadEntry();
6071      cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;  }
     return true;  
6072    
6073    /**
6074     * Sets the sorting method. If the new method is different from the previous, the issorted
6075     * flag is set to false, forcing a new sort the next time GetTrack is called.
6076     * @see GetTrack
6077     */
6078    void PamLevel2::SetSortingMethod(TString how) {
6079      if (howtosort != how) {
6080        issorted = false;
6081        issorted_new = false;
6082      }
6083      howtosort = how;
6084  }  }

Legend:
Removed from v.1.40  
changed lines
  Added in v.1.101

  ViewVC Help
Powered by ViewVC 1.1.23