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

Legend:
Removed from v.1.71  
changed lines
  Added in v.1.108

  ViewVC Help
Powered by ViewVC 1.1.23