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

Legend:
Removed from v.1.63  
changed lines
  Added in v.1.113

  ViewVC Help
Powered by ViewVC 1.1.23