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

Legend:
Removed from v.1.69  
changed lines
  Added in v.1.98

  ViewVC Help
Powered by ViewVC 1.1.23