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

Legend:
Removed from v.1.74  
changed lines
  Added in v.1.97

  ViewVC Help
Powered by ViewVC 1.1.23