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

Legend:
Removed from v.1.44  
changed lines
  Added in v.1.89

  ViewVC Help
Powered by ViewVC 1.1.23