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

Legend:
Removed from v.1.75  
changed lines
  Added in v.1.94

  ViewVC Help
Powered by ViewVC 1.1.23