/[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.1 by pam-fi, Fri Jun 16 16:43:55 2006 UTC revision 1.43 by pam-fi, Fri Aug 17 16:57:12 2007 UTC
# Line 7  Line 7 
7   * Default constructor   * Default constructor
8   */   */
9  PamTrack::PamTrack(){  PamTrack::PamTrack(){
10      trk_track  = this->TrkTrack::GetTrkTrack();      trk_track  = 0;
11      calo_track = this->CaloTrkVar::GetCaloTrkVar();      calo_track = 0;
12      tof_track  = this->ToFTrkVar::GetToFTrkVar();      tof_track  = 0;
13        candeleteobj = 0;
14  };  };
15  //--------------------------------------  //--------------------------------------
16  //  //
# Line 19  PamTrack::PamTrack(){ Line 20  PamTrack::PamTrack(){
20   * Constructor   * Constructor
21   */   */
22  PamTrack::PamTrack(TrkTrack* t, CaloTrkVar* c, ToFTrkVar* o){  PamTrack::PamTrack(TrkTrack* t, CaloTrkVar* c, ToFTrkVar* o){
23      trk_track  = this->TrkTrack::GetTrkTrack();  
24      calo_track = this->CaloTrkVar::GetCaloTrkVar();      trk_track  = 0;
25      tof_track  = this->ToFTrkVar::GetToFTrkVar();      calo_track = 0;
26      if(t) *trk_track  = *t;      tof_track  = 0;
27      if(c) *calo_track = *c;  //     if(t)trk_track  = new TrkTrack(*t);
28      if(o) *tof_track  = *o;  //     if(c)calo_track = new CaloTrkVar(*c);
29    //     if(o)tof_track  = new ToFTrkVar(*o);
30        if(t)trk_track  = t;
31        if(c)calo_track = c;
32        if(o)tof_track  = o;
33        candeleteobj = 0;
34    
35  };  };
36    PamTrack::PamTrack(const PamTrack& track){
37    
38        TrkTrack   *t = track.trk_track;
39        CaloTrkVar *c = track.calo_track;
40        ToFTrkVar  *o = track.tof_track;
41    
42        trk_track  = 0;
43        calo_track = 0;
44        tof_track  = 0;
45        if(t)trk_track  = new TrkTrack(*t);
46        if(c)calo_track = new CaloTrkVar(*c);
47        if(o)tof_track  = new ToFTrkVar(*o);
48        candeleteobj = 1;
49        
50    }
51    void PamTrack::Clear(){
52    
53    //    cout << "PamTrack::Clear() "<<candeleteobj<<endl;
54        if(candeleteobj){
55            if(trk_track)  trk_track->TrkTrack::Clear();
56            if(calo_track) calo_track->CaloTrkVar::Clear();//???
57            if(tof_track)  tof_track->ToFTrkVar::Clear();//???
58        }else{
59            trk_track  = 0;
60            calo_track = 0;
61            tof_track  = 0;
62        }
63    }
64    void PamTrack::Delete(){
65    //    cout << "PamTrack::Delete() "<<candeleteobj<<endl;
66        if(candeleteobj){
67            if(trk_track)  {
68                trk_track->TrkTrack::Clear();
69                delete trk_track;
70            }
71            if(calo_track){
72                calo_track->CaloTrkVar::Clear();//???
73                delete calo_track;
74            }
75            if(tof_track){
76                tof_track->ToFTrkVar::Clear();//???
77                delete tof_track;
78            }
79        }else{
80            Clear();
81        }
82    }
83  //--------------------------------------  //--------------------------------------
84  //  //
85  //  //
86  //--------------------------------------  //--------------------------------------
87  /**  /**
88   * Constructor   * Default Constructor
89   */   */
90  PamLevel2::PamLevel2(){  PamLevel2::PamLevel2(){
91      trk_obj  = this->TrkLevel2::GetTrkLevel2();    Initialize();
92      calo_obj = this->CaloLevel2::GetCaloLevel2();  };
93      tof_obj  = this->ToFLevel2::GetToFLevel2();  
94      trig_obj = this->TrigLevel2::GetTrigLevel2();  /**
95      s4_obj   = this->S4Level2::GetS4Level2();   * Constructor with given dir, list and detectors
96      nd_obj   = this->NDLevel2::GetNDLevel2();   */
97      ac_obj   = this->AcLevel2::GetAcLevel2();  PamLevel2::PamLevel2(TString ddir,TString list,TString detlist){
98      Initialize();
99      GetPamTree(GetListOfLevel2Files(ddir,list),detlist);
100      GetRunTree(GetListOfLevel2Files(ddir,list));
101    };
102    
103    /**
104     * Constructor with given dir and list
105     */
106    PamLevel2::PamLevel2(TString ddir,TString list){
107      Initialize();
108      GetPamTree(GetListOfLevel2Files(ddir,list),"");
109      GetRunTree(GetListOfLevel2Files(ddir,list));
110    };
111    
112    
113    void PamLevel2::Initialize(){
114            
115        h0_obj    = 0;
116        trk0_obj  = 0;
117        calo0_obj  = 0;
118    
119        trk2_obj  = 0;
120        trk1_obj  = 0;
121        trkh_obj  = 0;
122        calo1_obj = 0;
123        calo2_obj = 0;
124        tof_obj   = 0;
125        trig_obj  = 0;
126        s4_obj    = 0;
127        nd_obj    = 0;
128        ac_obj    = 0;
129        orb_obj   = 0;
130    
131        run_obj   = 0;//new GL_RUN();
132        soft_obj   = 0;// Emiliano
133        irun = -1LL;
134        runfirstentry = 0LL;
135        runlastentry = 0LL;
136    
137        l0_file = NULL;
138        l0_tree = NULL;
139        iroot   = -1;
140        dbc     = 0;
141    
142        prevshift = 0;
143        
144        run_tree = NULL;
145        run_tree_clone = NULL;
146        sel_tree = NULL;
147        sel_tree_clone = NULL;
148        
149        irunentry = -1LL;
150        pam_tree = NULL;
151        for(Int_t i=0; i<NCLONES; i++ )pam_tree_clone[i]=NULL;
152    
153        host = "mysql://localhost/pamelaprod";
154        user = "anonymous";
155        psw = "";
156        const char *pamdbhost=gSystem->Getenv("PAM_DBHOST");
157        const char *pamdbuser=gSystem->Getenv("PAM_DBUSER");
158        const char *pamdbpsw=gSystem->Getenv("PAM_DBPSW");
159        if ( !pamdbhost ) pamdbhost = "";
160        if ( !pamdbuser ) pamdbuser = "";
161        if ( !pamdbpsw ) pamdbpsw = "";
162        if ( strcmp(pamdbhost,"") ) host = pamdbhost;
163        if ( strcmp(pamdbuser,"") ) user = pamdbuser;
164        if ( strcmp(pamdbpsw,"") ) psw = pamdbpsw;
165    
166        
167    
168    //    sorted_tracks = 0;//new TRefArray();
169        
170        CAL0 = false;
171        CAL1 = true;
172        CAL2 = true;
173        TRK2 = true;
174        TRK1 = false;
175        TRKh = false;
176        TRKh = false;
177        TRG  = true;
178        TOF  = true;
179        TOF0 = false;
180        S4   = true;
181        ND   = true;
182        AC   = true;
183        ORB  = true;
184        
185        RUN  = true;
186    
187        SELLI = -1;
188    
189        ISGP = false;
190    
191        tsorted=0;
192        timage=0;
193        
194        howtosort = "+CAL+TOF";
195        //howtosort = "+TOF";
196        sortthr = 100.;
197    
198    };
199    /**
200     * Delete the event (act as Dtor)
201     */
202    void PamLevel2::Delete(){
203            
204        if(run_obj)delete run_obj;
205        if(soft_obj)delete soft_obj; //Emiliano
206    
207    //    cout << "void PamLevel2::Clear()"<<endl;
208        if(h0_obj)   delete h0_obj;
209        if(trk0_obj) delete trk0_obj;      
210        if(calo0_obj) delete calo0_obj;    
211        if(trk1_obj) delete trk1_obj;      
212        if(trk2_obj) delete trk2_obj;
213        if(trkh_obj) delete trkh_obj;
214        if(calo1_obj)delete calo1_obj;
215        if(calo2_obj)delete calo2_obj;
216        if(tof_obj)  delete tof_obj;
217        if(trig_obj) delete trig_obj;
218        if(s4_obj)   delete s4_obj;
219        if(nd_obj)   delete nd_obj;
220        if(ac_obj)   delete ac_obj;
221        if(orb_obj)  delete orb_obj;
222        
223        if(tsorted){
224            tsorted->Delete();
225            delete tsorted;
226        }
227        if(timage){
228            timage->Delete();
229            delete timage;
230        }
231    
232        if(dbc){
233            dbc->Close();
234            delete dbc;
235        }
236        
237        if(l0_file)l0_file->Close();
238        //    if(pam_tree)pam_tree->Delete();;
239    
240      if ( pam_tree ){
241        //
242        // 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...
243        //
244        TList *temp = pam_tree->GetListOfFriends();
245        TList *contents  = new TList; // create chain friend list
246        contents->SetOwner();
247        TIter next(temp);
248        TChain *questo = 0;
249        while ( (questo = (TChain*) next()) ){
250          TString name =  questo->GetName();
251          contents->Add((TChain*)gROOT->FindObject(name.Data()));// add object to the list
252        };
253        //
254        // deleting the main chain
255        //
256        pam_tree->Delete();
257        //
258        // deleting the friends...
259        //
260        TIter next2(contents);
261        TChain *questa = 0;
262        while ( questa = (TChain*)next2() ){
263          TString name =  questa->GetName();
264          questa->Delete();      
265          questa=NULL;
266        };
267        //
268      };
269      pam_tree = NULL;
270    
271        if(run_tree)run_tree->Delete();;
272        if(sel_tree)sel_tree->Delete();;
273        for(Int_t i=0; i<NCLONES; i++ )if(pam_tree_clone[i])pam_tree_clone[i]->Delete();;
274        if(run_tree_clone)run_tree_clone->Delete();;
275        if(sel_tree_clone)sel_tree_clone->Delete();;
276        
277    
278    };
279    
280    /**
281     * Clear the event (NB! does not deallocate objects)
282     */
283    void PamLevel2::Clear(){
284            
285    //    cout << "void PamLevel2::Clear()"<<endl;
286    
287    //
288    // 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
289    // want to load them for each event even if they are the same...
290    //
291    //    if(run_obj)delete run_obj;
292    //    if(run_obj) run_obj->Clear();  // Emiliano: Do not deallocate run_obj here, it will give segmentation fault! call clear instead
293    //    if(soft_obj) soft_obj->Clear();
294    
295        if(h0_obj)   h0_obj->Clear();      
296    //    if(trk0_obj) trk0_obj->Clear();  
297        if(trk1_obj) trk1_obj->Clear();    
298        if(trk2_obj) trk2_obj->Clear();
299        if(trkh_obj) trkh_obj->Clear();
300        if(calo0_obj) calo0_obj->Clear();  
301        if(calo1_obj)calo1_obj->Clear();
302        if(calo2_obj)calo2_obj->Clear();
303        if(tof_obj)  tof_obj->Clear();
304        if(trig_obj) trig_obj->Clear();
305        if(s4_obj)   s4_obj->Clear();
306        if(nd_obj)   nd_obj->Clear();
307        if(ac_obj)   ac_obj->Clear();
308        if(orb_obj)  orb_obj->Clear();
309        
310    //    if(sorted_tracks)sorted_tracks->Clear();
311    //    sorted_tracks.Clear();
312    
313        if(tsorted){
314            tsorted->Delete();
315        }
316        if(timage){
317            timage->Delete();
318        }
319    };
320    
321    void PamLevel2::Reset(){
322      //
323      // First of all clear everything
324      //
325      Clear();
326      //
327      // close and reset chains and pointers
328      //    
329      if ( pam_tree ){
330        //
331        // 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...
332        //
333        TList *temp = pam_tree->GetListOfFriends();
334        TList *contents  = new TList; // create chain friend list
335        contents->SetOwner();
336        TIter next(temp);
337        TChain *questo = 0;
338        while ( (questo = (TChain*) next()) ){
339          TString name =  questo->GetName();
340          contents->Add((TChain*)gROOT->FindObject(name.Data()));// add object to the list
341        };
342        //
343        // deleting the main chain
344        //
345        pam_tree->Delete();
346        //
347        // deleting the friends...
348        //
349        TIter next2(contents);
350        TChain *questa = 0;
351        while ( questa = (TChain*)next2() ){
352          TString name =  questa->GetName();
353          questa->Delete();      
354          questa=NULL;
355        };
356        //
357      };
358      pam_tree = NULL;
359      //
360      if(run_tree)run_tree->Delete();;
361      run_tree = NULL;
362      if(sel_tree)sel_tree->Delete();;
363      sel_tree = NULL;
364      //
365      // Close file
366      //
367      if(l0_file)l0_file->Close("R");
368      l0_file = NULL;
369      //
370      h0_obj    = 0;
371      trk0_obj  = 0;
372      calo0_obj  = 0;
373      //
374      trk2_obj  = 0;
375      trk1_obj  = 0;
376      trkh_obj  = 0;
377      calo1_obj = 0;
378      calo2_obj = 0;
379      tof_obj   = 0;
380      trig_obj  = 0;
381      s4_obj    = 0;
382      nd_obj    = 0;
383      ac_obj    = 0;
384      orb_obj   = 0;
385      //
386      // Reset run pointers
387      //
388      run_obj   = 0;//new GL_RUN();
389      soft_obj   = 0;// Emiliano
390      irun = -1;
391      runfirstentry = 0ULL;
392      runlastentry = 0ULL;    
393      //
394    };
395    
396    Bool_t PamLevel2::IsGood(){
397      Bool_t goodev=true;
398      //  if(trk2_obj && trk2_obj->UnpackError() != 0 ) goodev = false;
399      if(calo2_obj && calo2_obj->good != 1) goodev = false;
400      if(tof_obj && tof_obj->unpackError != 0) goodev = false;  
401      if(trig_obj && trig_obj->unpackError != 0) goodev = false;
402      if(s4_obj && s4_obj->unpackError != 0) goodev = false;  
403      if(nd_obj && nd_obj->unpackError != 0) goodev = false;  
404      if(ac_obj && ac_obj->unpackError != 255) goodev = false;  
405        //  if(orb_obj)  
406      return goodev;
407    };
408    
409    //--------------------------------------
410    //
411    //
412    //--------------------------------------
413    void *PamLevel2::GetPointerTo(const char* c ){
414    
415        TString objname = c;
416    
417        if(!objname.CompareTo("TrkLevel1"))  {
418            if(!trk1_obj){
419                trk1_obj  = new TrkLevel1();
420                trk1_obj->Set();
421            }
422            return &trk1_obj;
423        };
424        if(!objname.CompareTo("TrkLevel2"))  {
425            if(!trk2_obj){  
426                trk2_obj  = new TrkLevel2();
427                trk2_obj->Set();
428            }
429            return &trk2_obj;
430        };
431        if(!objname.CompareTo("TrkHough"))   {
432            if(!trkh_obj)  trkh_obj  = new TrkHough();
433            return &trkh_obj;
434        };
435        if(!objname.CompareTo("CaloLevel1")) {
436            if(!calo1_obj) calo1_obj = new CaloLevel1();
437            return &calo1_obj;
438        };
439        if(!objname.CompareTo("CaloLevel2")) {
440            if(!calo2_obj){
441                calo2_obj = new CaloLevel2();
442                calo2_obj->Set();
443            };
444            return &calo2_obj;
445        };
446        if(!objname.CompareTo("ToFLevel2"))  {
447            if(!tof_obj){
448                tof_obj   = new ToFLevel2();
449                tof_obj->Set();
450            }
451            return &tof_obj;
452        };
453        if(!objname.CompareTo("TrigLevel2")) {
454            if(!trig_obj)  trig_obj  = new TrigLevel2();
455            return &trig_obj;
456        };
457        if(!objname.CompareTo("S4Level2"))   {
458            if(!s4_obj)    s4_obj    = new S4Level2();
459            return &s4_obj;
460        };
461        if(!objname.CompareTo("NDLevel2"))   {
462            if(!nd_obj)    nd_obj    = new NDLevel2();
463            return &nd_obj;
464        };
465        if(!objname.CompareTo("AcLevel2"))   {
466            if(!ac_obj)    ac_obj    = new AcLevel2();
467            return &ac_obj;
468        };
469        if(!objname.CompareTo("OrbitalInfo")){
470            if(!orb_obj)   orb_obj   = new OrbitalInfo();
471            return &orb_obj;
472        };
473        
474        if(!objname.CompareTo("RunInfo"))return &run_obj;
475    
476        if(!objname.CompareTo("SoftInfo"))return &soft_obj; // Emiliano
477    
478        return NULL;
479  };  };
480  //--------------------------------------  //--------------------------------------
481  //  //
482  //  //
483  //--------------------------------------  //--------------------------------------
484  /**  /**
485     * Retrieves the calorimeter track matching the seqno-th tracker stored track.
486     * (If seqno = -1 retrieves the self-trigger calorimeter track)
487     */
488     CaloTrkVar *PamLevel2::GetCaloStoredTrack(int seqno){
489        
490         if( !calo2_obj )return 0;
491    
492         if( calo2_obj->CaloLevel2::ntrk()==0 ){
493             cout << "PamLevel2::GetCaloStoredTrack(int) : requested tracker SeqNo "<< seqno <<" but no Calorimeter tracks are stored"<<endl;
494             return NULL;
495         };
496        
497         CaloTrkVar *c = 0;
498         Int_t it_calo=0;
499        
500         do{
501             c = calo2_obj->CaloLevel2::GetCaloTrkVar(it_calo);
502             it_calo++;
503         } while( c && seqno != c->trkseqno && it_calo < calo2_obj->CaloLevel2::ntrk());    
504        
505         if(!c || seqno != c->trkseqno){
506             c = 0;
507             if(seqno!=-1)cout << "PamLevel2::GetCaloStoredTrack(int) : requested tracker SeqNo "<< seqno <<" does not match Calorimeter stored tracks"<<endl;
508         };
509         return c;
510        
511     };
512    //--------------------------------------
513     //
514     //
515    //--------------------------------------
516    /**
517      * Retrieves the ToF track matching the seqno-th tracker stored track.
518      * (If seqno = -1 retrieves the tracker-independent tof track)
519     */
520     ToFTrkVar *PamLevel2::GetToFStoredTrack(int seqno){
521            
522         if( !tof_obj )return 0;
523    
524         if( tof_obj->ToFLevel2::ntrk()==0 ){
525             cout << "PamLevel2::GetToFStoredTrack(int) : requested tracker SeqNo "<< seqno <<" but no ToF tracks are stored"<<endl;
526             return NULL;
527         };
528        
529         ToFTrkVar *c = 0;
530         Int_t it_tof=0;
531        
532         do{
533             c = tof_obj->ToFLevel2::GetToFTrkVar(it_tof);
534             it_tof++;
535         } while( c && seqno != c->trkseqno && it_tof < tof_obj->ToFLevel2::ntrk());        
536        
537         if(!c || seqno != c->trkseqno){
538             c = 0;
539             if(seqno!=-1)cout << "PamLevel2::GetToFStoredTrack(int) : requested tracker SeqNo "<< seqno <<" does not match ToF stored tracks"<<endl;
540         };
541         return c;
542        
543     };
544    
545    //--------------------------------------
546     //
547     //
548    //--------------------------------------
549    /**
550     * Give the pamela track associated to a tracker track, retrieving related calorimeter and tof track information.
551     */
552     PamTrack* PamLevel2::GetPamTrackAlong(TrkTrack* t){
553        
554         cout <<"PamLevel2::GetPamTrackAlong(TrkTrack* t) **obsolete** "<<endl;
555         cout <<"(if you use it, remember to delete the PamTrack object)"<<endl;
556    
557         CaloTrkVar *c = 0;
558         ToFTrkVar  *o = 0;
559        
560         if(CAL2) c = GetCaloStoredTrack(t->GetSeqNo());
561         if(TOF) o = GetToFStoredTrack(t->GetSeqNo());
562        
563    //    if(t && c && o)track = new PamTrack(t,c,o);
564         PamTrack *track = new PamTrack(t,c,o);
565        
566         return track;
567    
568     };
569    //--------------------------------------
570    //
571    //
572    //--------------------------------------
573    /**
574   * Retrieves the it-th stored track.   * Retrieves the it-th stored track.
575   * It override TrkLevel2::GetTrack(int it).   * It override TrkLevel2::GetTrack(int it).
576   * @param itrk Track number, ranging from 0 to GetNTracks().   * @param itrk Track number, ranging from 0 to GetNTracks().
# Line 55  PamLevel2::PamLevel2(){ Line 578  PamLevel2::PamLevel2(){
578    
579  PamTrack* PamLevel2::GetStoredTrack(Int_t itrk){  PamTrack* PamLevel2::GetStoredTrack(Int_t itrk){
580            
581      // retrieve itrk-th tracker stored track      cout <<"PamLevel2::GetStoredTrack(Int_t itrk) **to-be-updated** "<<endl;
582      TrkTrack   *t = 0;      cout <<"for the moment, better use separately the methods: TrkLevel2::GetStoredTrack(seqno) CaloLevel2::GetCaloTrkVar(Int_t notrack) ToFLevel2::GetToFTrkVar(Int_t notrack)"<<endl;
583      CaloTrkVar *c = 0;      cout <<"(if you use it, remember to delete the PamTrack object)"<<endl;
584      ToFTrkVar  *o = 0;      PamTrack *track = 0;
585        
586      if( itrk >=0 && itrk < TrkLevel2::ntrk() ){      if( itrk >=0 && itrk < trk2_obj->TrkLevel2::ntrk() ){
587          t = TrkLevel2::GetStoredTrack(itrk);              
588          c = CaloLevel2::GetCaloTrkVar(t->GetSeqNo());          TrkTrack *t = trk2_obj->TrkLevel2::GetStoredTrack(itrk);
589          o = ToFLevel2::GetToFTrkVar(t->GetSeqNo());          track = GetPamTrackAlong(t);
590            
591            
592    
593        }else{
594            cout << "PamLevel2::GetStoredTrack(int) : tracker track SeqNo "<< itrk <<" does not exist (GetNTracks() = "<<trk2_obj->TrkLevel2::GetNTracks()<<")"<<endl;
595      };      };
     //  retrieve related ToF-track  
596            
     // hence create a "PamTrack" object  
     PamTrack *track = 0;  
     if(t && c && o)track = new PamTrack(t,c,o);  
597      return track;      return track;
598            
599  }  }
600  //--------------------------------------  //--------------------------------------
601  //  //
602    
603    /**
604     * Sort physical (tracker) tracks and stores them in the TRefArray (of TrkTrack objects) which pointer is  PamLevel2::sorted_tracks. Left here as backward compatibility method.
605     **/
606    void PamLevel2::SortTracks(TString how){
607      printf(" WARNING! obsolete, use SortTracks() and SetSortingMethod(TString) instead! \n Setting sorting method to %s \n",how.Data());
608      howtosort = how;  
609      SortTracks();
610    };
611    
612  //  //
613  //--------------------------------------  //--------------------------------------
614  /**  /**
615   * Sort physical (tracker) tracks and stores them in a TObjectArray (of TrkTrack objects).   * Sort physical (tracker) tracks and stores them in the TRefArray (of TrkTrack objects) which pointer is  PamLevel2::sorted_tracks.
616   * The total number of physical tracks is given by GetNTracks() and the it-th physical track can be retrieved by means of the method GetTrack(int it).   * @param how String to set the sorting cryterium (es: "CAL" or "TRK+CAL+TOF" ecc...).
617   * This method overrides TrkLevel2::GetTracks(), where sorting is done by decreasing number of fit points and increasing chi^2.   * Sorting cryteria:
618   * PamLevel2::GetTracks() keeps the same track order given by TrkLevel2::GetTracks(), but checks image selection by using calorimeter and ToF tracking information.   * TRK: lower chi**2
619     * CAL: lower Y spatial residual on the first calorimeter plane
620     * TOF: bigger numebr of hit PMTs along the track, on S12 S21 S32 (where paddles are along the Y axis).
621     * The default sorting cryterium is "TOF+CAL".
622     *
623     * 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).
624   */   */
625  TClonesArray *PamLevel2::GetTracks(){  void PamLevel2::SortTracks(){
626      TString how = howtosort;
627    
628      // define new array for sorted tracker tracks    //    cout <<" PamLevel2::SortTracks(TString how) "<<endl;
629      TClonesArray *aa = new TClonesArray("TrkTrack");    if( !trk2_obj ){
630      TClonesArray &sorted = *aa;      cout << "void PamLevel2::SortTracks():  TrkLevel2 not loaded !!!";
631        return;
632      // loop over the tracks sorted by the tracker    };
633      for(Int_t i=0; i < TrkLevel2::GetNTracks(); i++){    //    cout << "call SortTracs() "<<endl;
634      //Save current Object count
635          TrkTrack *ts=0;    Int_t ObjectNumber = TProcessID::GetObjectCount();
636    
637          // get tracker tracks    //    cout << "ObjectNumber  "<<ObjectNumber <<endl;
638          TrkTrack   *tp = TrkLevel2::GetTrack(i);                    //tracker  
639          CaloTrkVar *cp = CaloLevel2::GetCaloTrkVar(tp->GetSeqNo()); //calorimeter    //     if(!sorted_tracks)sorted_tracks = new TRefArray();
640          ToFTrkVar  *op = ToFLevel2::GetToFTrkVar(tp->GetSeqNo());   //tof    //     sorted_tracks->Clear();
641      //    sorted_tracks.Clear();
642          // if track has an image, check image selection  
643          if(tp->HasImage()){    if(!tsorted)tsorted = new TClonesArray("PamTrack",trk2_obj->GetNTracks());
644              TrkTrack   *ti = TrkLevel2::GetTrackImage(i);              //tracker (image)    tsorted->Delete();
645              CaloTrkVar *ci = CaloLevel2::GetCaloTrkVar(ti->GetSeqNo());//calorimeter (image)    TClonesArray &ttsorted = *tsorted;
646              ToFTrkVar  *oi = ToFLevel2::GetToFTrkVar(ti->GetSeqNo());  //tof (image)    if(!timage)timage = new TClonesArray("PamTrack",trk2_obj->GetNTracks());
647      timage->Delete();
648              //assign starting scores    TClonesArray &ttimage = *timage;
             Int_t tp_score = 1;  
             Int_t ti_score = 0;  
             // ------------------------  
             // calorimeter check  
             // ------------------------  
             if(  
                       npcfit[1] > 3   &&  //no. of fit planes on Y view  
 //              varcfit[1] < 50.&&  //fit variance on Y view  
                       true){  
   
                 Float_t resy_p = cp->tbar[0][1] - cbar[0][1];if(resy_p < 0)resy_p= - resy_p;  
                 Float_t resy_i = ci->tbar[0][1] - cbar[0][1];if(resy_i < 0)resy_i= - resy_i;  
   
                 if(resy_p <= resy_i) tp_score++;  
                 else                 ti_score++;  
                       };  
             // ------------------------  
             // TOF check  
             // ------------------------      
   
             // ------------------------  
             // the winner is....  
             // ------------------------      
                       if(tp_score > ti_score) ts = tp;//the track sorted by the tracker!!  
                       else                    ts = ti;//its image!!  
649    
650          }else{  
651              ts = tp;  
652          };    //--------------------------------------------------
653      // retrieve sorting method
654      //--------------------------------------------------
655      Bool_t use_TRK = how.Contains("TRK", TString::kIgnoreCase);
656      Bool_t use_CAL = how.Contains("CAL", TString::kIgnoreCase);
657      Bool_t use_TOF = how.Contains("TOF", TString::kIgnoreCase);
658        
659      if( !CAL2 &&  use_CAL) use_CAL = false;
660      if( !TOF &&  use_TOF) use_TOF = false;
661        
662      if( !TRK2 ){
663        //  cout << "SortTracks() : without tracker does not work!!! (not yet)" << endl;
664        return;
665      };
666    
667      //   cout << "use_CAL "<<use_CAL<<" use_TOF "<<use_TOF<<" use_TRK "<<use_TRK <<endl;
668      
669    
670      //--------------------------------------------------
671      // loop over "physical" tracks sorted by the tracker
672      //--------------------------------------------------
673      for(Int_t i=0; i < trk2_obj->TrkLevel2::GetNTracks(); i++){
674                    
675          new(sorted[i]) TrkTrack(*ts); //save the track in the sorted array      TrkTrack   *ts = 0;
676      };      CaloTrkVar *cs = 0;
677        ToFTrkVar  *os = 0;
678            
679        // get tracker tracks
680        TrkTrack   *tp = trk2_obj->TrkLevel2::GetTrack(i); //tracker
681        CaloTrkVar *cp = GetCaloStoredTrack(tp->GetSeqNo());
682        ToFTrkVar  *op = GetToFStoredTrack(tp->GetSeqNo());
683    
684        TrkTrack   *ti = 0; //tracker (image)
685        CaloTrkVar *ci = 0;
686        ToFTrkVar  *oi = 0;
687        //  cout << "trk track n. "<<i << " "<<hex<< tp <<dec<< endl;
688        // if track has an image, check image selection
689        if(tp->HasImage()){
690                
691          ti = trk2_obj->TrkLevel2::GetTrackImage(i);              //tracker (image)
692          ci = GetCaloStoredTrack(ti->GetSeqNo());
693          oi = GetToFStoredTrack(ti->GetSeqNo());
694                
695          //            cout << "its image "<<i << " "<<hex<< ti <<dec<< endl;
696    
697          //assign starting scores
698          Int_t tp_score = 0;  //main track sorted by the tracker
699          Int_t ti_score = 0;  //image track
700                
701          // -----------------------------------------------------------------------------------------
702          // calorimeter check
703          // -----------------------------------------------------------------------------------------
704          // check the Y spatial residual on the first calorimeter plane
705          // (cut on calorimeter variables from Emiliano)
706          if( use_CAL && !calo2_obj ){
707            cout << "void PamLevel2::SortTracks(): howtosort= "<<how<<" but CaloLevel2 not loaded !!!";
708            return;
709          };
710          if(
711             use_CAL            &&
712    //       calo2_obj->npcfit[1] > 5     &&   //no. of fit planes on Y view
713    //       calo2_obj->varcfit[1] < 1000. &&  //fit variance on Y view
714             cp && ci &&
715             true){
716    
717                    
718    //      Float_t resy_p = cp->tbar[0][1] - calo2_obj->cbar[0][1]; if(resy_p < 0)resy_p= - resy_p;
719    //      Float_t resy_i = ci->tbar[0][1] - calo2_obj->cbar[0][1]; if(resy_i < 0)resy_i= - resy_i;
720                    
721    //      if(resy_p <= resy_i) tp_score++;
722    //      else                 ti_score++;
723            
724    
725              if( cp->npresh > ci->npresh) tp_score++;
726              if( cp->npresh < ci->npresh) ti_score++;
727              else ;//niente
728    
729            //      cout << "CALO "<<tp_score<<ti_score<<endl;
730    
731          };
732          // -----------------------------------------------------------------------------------------
733          // TOF check
734          // -----------------------------------------------------------------------------------------
735          // check the number of hit pmts along the track
736          // on S12 S21 and S32, where paddles are parallel to Y axis
737          if( use_TOF && !tof_obj ){
738            cout << "void PamLevel2::SortTracks(): howtosort= "<<how<<" but ToFLevel2 not loaded !!!";
739            return;
740          };
741          if( use_TOF && op && oi ){
742                    
743            //
744            Float_t sen = 0.;
745            for (Int_t ih=0; ih < op->npmtadc; ih++){
746              Int_t pl = tof_obj->GetPlaneIndex( (op->pmtadc).At(ih) );
747              if ( pl == 2 || pl == 3 || pl == 4 || pl == 5 ) sen += (op->dedx).At(ih);
748            };
749            for (Int_t ih=0; ih < oi->npmtadc; ih++){
750              Int_t pl = tof_obj->GetPlaneIndex( (oi->pmtadc).At(ih) );
751              if ( pl == 2 || pl == 3 || pl == 4 || pl == 5 ) sen += (oi->dedx).At(ih);
752            };
753            //
754            if (  sen >= sortthr ){
755              //printf(" IS A NUCLEUS! en = %f \n",sen);
756              //
757              // is a nucleus use a different algorithm
758              //
759              Int_t nz = 6; Float_t zin[6];                                          // << define TOF z-coordinates
760              for(Int_t ip=0; ip<nz; ip++)
761                zin[ip] = tof_obj->ToFLevel2::GetZTOF(tof_obj->ToFLevel2::GetToFPlaneID(ip));     // << read ToF plane z-coordinates
762              Trajectory *tr = new Trajectory(nz,zin);
763              //
764              Int_t nphit_p =0;
765              Int_t nphit_i =0;
766              Float_t enhit_p = 0.;
767              Float_t enhit_i = 0.;
768              //
769              for (Int_t ih=0; ih < op->npmtadc; ih++){
770                Int_t pl = tof_obj->GetPlaneIndex( (op->pmtadc).At(ih) );
771                if(pl == 1 || pl == 2 || pl == 5){
772                  nphit_p++;
773                  enhit_p += (op->dedx).At(ih);
774                };
775              };
776              //
777              tp->DoTrack2(tr);
778              //
779              if ( fabs(tr->y[0]-oi->ytofpos[0]) < 2. ){
780                for (Int_t ih=0; ih < op->npmtadc; ih++){
781                  Int_t pl = tof_obj->GetPlaneIndex( (op->pmtadc).At(ih) );
782                  if(pl == 0){
783                    nphit_p++;
784                    enhit_p += (op->dedx).At(ih);
785                  };
786                };
787              };
788              if ( fabs(tr->y[3]-oi->ytofpos[1]) < 2. ){
789                for (Int_t ih=0; ih < op->npmtadc; ih++){
790                  Int_t pl = tof_obj->GetPlaneIndex( (op->pmtadc).At(ih) );
791                  if(pl == 3){
792                    nphit_p++;
793                    enhit_p += (op->dedx).At(ih);
794                  };
795                };
796              };
797              if ( fabs(tr->y[4]-oi->ytofpos[2]) < 2. ){
798                for (Int_t ih=0; ih < op->npmtadc; ih++){
799                  Int_t pl = tof_obj->GetPlaneIndex( (op->pmtadc).At(ih) );
800                  if(pl == 4){
801                    nphit_p++;
802                    enhit_p += (op->dedx).At(ih);
803                  };
804                };
805              };
806    
807              for (Int_t ih=0; ih < oi->npmtadc; ih++){
808                Int_t pl = tof_obj->GetPlaneIndex( (oi->pmtadc).At(ih) );
809                if(pl == 1 || pl == 2 || pl == 5){
810                  nphit_i++;        
811                  enhit_i += (op->dedx).At(ih);
812                };
813              };
814              //
815              ti->DoTrack2(tr);
816              //
817              if ( fabs(tr->y[0]-oi->ytofpos[0]) < 2. ){
818                for (Int_t ih=0; ih < oi->npmtadc; ih++){
819                  Int_t pl = tof_obj->GetPlaneIndex( (oi->pmtadc).At(ih) );
820                  if(pl == 0){
821                    nphit_i++;
822                    enhit_i += (op->dedx).At(ih);
823                  };
824                };
825              };
826              if ( fabs(tr->y[3]-oi->ytofpos[1]) < 2. ){
827                for (Int_t ih=0; ih < oi->npmtadc; ih++){
828                  Int_t pl = tof_obj->GetPlaneIndex( (oi->pmtadc).At(ih) );
829                  if(pl == 3){
830                    nphit_i++;
831                    enhit_i += (op->dedx).At(ih);
832                  };
833                };
834              };
835              if ( fabs(tr->y[4]-oi->ytofpos[2]) < 2. ){
836                for (Int_t ih=0; ih < oi->npmtadc; ih++){
837                  Int_t pl = tof_obj->GetPlaneIndex( (oi->pmtadc).At(ih) );
838                  if(pl == 4){
839                    nphit_i++;
840                    enhit_i += (op->dedx).At(ih);
841                  };
842                };
843              };            
844    
845                    
846              if(
847                 use_TOF            &&
848                 (nphit_p+nphit_i) !=0 &&  
849                 true){
850                        
851                //      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);
852                //      printf(" score p %i score i %i \n",tp_score,ti_score);
853                //            if( enhit_p > enhit_i ) tp_score++;
854                //            if( nphit_p >= nphit_i && enhit_p > enhit_i ) tp_score++;
855                if ( nphit_p > nphit_i ) tp_score++;
856                if ( nphit_p < nphit_i ) ti_score++;
857                if ( nphit_p == nphit_i ){
858                  if ( enhit_p > enhit_i ) tp_score++;
859                  else ti_score++;
860                };
861                //      printf(" dopo score p %i score i %i \n",tp_score,ti_score);
862              };
863              delete tr;
864              //
865            } else {
866              //
867              // NOT a NUCLEUS
868              //
869              //printf(" NOT a NUCLEUS! en = %f \n",sen);
870    
871              Int_t nphit_p =0;
872              Int_t nphit_i =0;
873                    
874                    
875              /*                            cout << "track: npmtadc "<< op->npmtadc << endl;
876                cout << "track: npmttdc "<< op->npmttdc << endl;
877                cout << "image: npmtadc "<< oi->npmtadc << endl;
878                cout << "image: npmttdc "<< oi->npmttdc << endl;*/
879                    
880    //        for (Int_t ih=0; ih < op->npmtadc; ih++){
881    //          Int_t pl = tof_obj->GetPlaneIndex( (op->pmtadc).At(ih) );
882    //          if(pl == 1 || pl == 2 || pl == 5)nphit_p++;
883    //        };
884                    
885    //        for (Int_t ih=0; ih < oi->npmtadc; ih++){
886    //          Int_t pl = tof_obj->GetPlaneIndex( (oi->pmtadc).At(ih) );
887    //          if(pl == 1 || pl == 2 || pl == 5)nphit_i++;
888    //        };
889              // --- modified to count tdc signals (more efficient?)
890              // --- and to implement check on tdcflag
891              for (Int_t ih=0; ih < op->npmttdc; ih++){
892                Int_t pl = tof_obj->GetPlaneIndex( (op->pmttdc).At(ih) );
893    //          if( (op->tdcflag).At(ih)==0 && (pl == 1 || pl == 2 || pl == 5) )nphit_p++;
894                if( (op->tdcflag).At(ih)==0 )nphit_p++;
895              };
896                    
897              for (Int_t ih=0; ih < oi->npmttdc; ih++){
898                Int_t pl = tof_obj->GetPlaneIndex( (oi->pmttdc).At(ih) );
899    //          if( (oi->tdcflag).At(ih)==0 && (pl == 1 || pl == 2 || pl == 5) )nphit_i++;  
900                if( (oi->tdcflag).At(ih)==0 )nphit_i++;    
901              };
902                    
903              if(
904                 (nphit_p+nphit_i) !=0 &&  
905                 true){
906                        
907                if     ( nphit_p > nphit_i) tp_score++;
908                else if( nphit_p < nphit_i) ti_score++;
909                else ;//niente
910              };
911            };
912            //      cout << "TOF "<<tp_score<<ti_score<<endl;
913          };
914    
915    
916    //      if(tp_score == ti_score) use_TRK = true;
917    
918    
919      return aa;        // -----------------------------------------------------------------------------------------
920          // tracker check
921          // -----------------------------------------------------------------------------------------
922          // chi**2 difference is not always large enough to distinguish among
923          // the real track and its image.
924          // Tracker check will be applied always when calorimeter and tof information is ambiguous.
925          // *** MODIFIED ON AUGUST 2007 ***
926          if(use_TRK){
927    //      if(      tp->chi2 > 0 && tp->chi2 < ti->chi2 ) tp_score++ ;
928    //      else if( ti->chi2 > 0 && ti->chi2 < tp->chi2 ) ti_score++ ;
929    
930              // CHECK 1 : number of points along X  
931              if ( tp->GetNX() >= ti->GetNX() )tp_score++ ;
932              if ( tp->GetNX() <= ti->GetNX() )ti_score++ ;
933              // CHECK 2 : number of points along Y  
934              if ( tp->GetNY() >= ti->GetNY() )tp_score++ ;
935              if ( tp->GetNY() <= ti->GetNY() )ti_score++ ;
936              // CHECK 3 : chi**2 along X  
937    //        if(      tp->GetChi2X() > 0 && (tp->GetChi2X() < ti->GetChi2X() || ti->GetChi2X() <=0) ) tp_score++ ;
938    //        if(      ti->GetChi2X() > 0 && (ti->GetChi2X() < tp->GetChi2X() || tp->GetChi2X() <=0) ) ti_score++ ;
939              // CHECK 4 : chi**2 along Y  
940    //        if(      tp->GetChi2Y() > 0 && (tp->GetChi2Y() < ti->GetChi2Y() || ti->GetChi2Y() <=0) ) tp_score++ ;
941    //        if(      ti->GetChi2Y() > 0 && (ti->GetChi2Y() < tp->GetChi2Y() || tp->GetChi2Y() <=0) ) ti_score++ ;
942              // CHECK 5 : total chi**2  
943    //        if(      tp->chi2 > 0 && (tp->chi2 < ti->chi2 || ti->chi2 <=0) ) tp_score++ ;
944    //        if(      ti->chi2 > 0 && (ti->chi2 < tp->chi2 || tp->chi2 <=0) ) ti_score++ ;
945    
946            //      cout << "TRK "<<tp_score<<ti_score<<endl;
947          };
948                
949    
950    
951          // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
952          // the winner is....
953          // *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
954          if      (tp_score > ti_score) {
955            
956    
957          }else if (tp_score < ti_score) {
958    
959    
960            ts = ti;//its image!!
961            cs = ci;
962            os = oi;
963    
964            ti = tp;//its image!!
965            ci = cp;
966            oi = op;
967    
968            tp = ts;//its image!!
969            cp = cs;
970            op = os;
971    
972                    
973          }else {
974    
975    //      cout << "Warning - track image ambiguity not solved" << endl;
976    
977          };
978                
979        }else{
980          //            ts = tp;
981          //            cs = cp;
982          //            os = op;
983        };
984            
985        //  cout <<" SortTracks() "<<i<<" -- "<<ts<<endl;
986        //  sorted_tracks->Add(ts);//save the track in the sorted array
987        //  sorted_tracks.Add(ts);//save the track in the sorted array
988        //  sorted_tracks.Add(tp);//save the track in the sorted array
989        //  cout << "SortTracks:: sorted_tracks->Add(it) "<<i<<" "<<ts<<endl;
990        //  cout<<"o "<<tp<<endl;
991        //  cout<<"o "<<cp<<endl;
992        //  cout<<"o "<<op<<endl;
993        new(ttsorted[i]) PamTrack(tp,cp,op);
994        new(ttimage[i])  PamTrack(ti,ci,oi);
995      };
996    
997      if( tsorted->GetEntries() != trk2_obj->GetNTracks() ){
998        cout << "void PamLevel2::SortTracks(): tsorted->GetEntries() "<<tsorted->GetEntries()<<" != trk2_obj->GetNTracks() = "<<trk2_obj->GetNTracks() <<endl;
999        tsorted->Delete(); tsorted=0;
1000        timage->Delete(); timage=0;
1001      }
1002    
1003      //Restore Object count
1004      //To save space in the table keeping track of all referenced objects
1005      //We reset the object count to what it was at the beginning of the event.
1006      TProcessID::SetObjectCount(ObjectNumber);
1007        
1008  };  };
1009  //--------------------------------------  //--------------------------------------
1010  //  //
1011  //  //
1012  //--------------------------------------  //--------------------------------------
1013  /**  /**
1014     * This method overrides TrkLevel2::GetTracks(), where sorting is done by decreasing number of fit points and increasing chi^2.
1015     * PamLevel2::GetTracks() keeps the same track order given by TrkLevel2::GetTracks(), but checks image selection by using calorimeter and ToF tracking information.
1016     */
1017    // TRefArray *PamLevel2::GetTracks(){
1018    
1019    // //  *-*-*-*-*-*-*-*-*-*-*-*-*
1020    //     SortTracks("+CAL+TOF");
1021    // //  *-*-*-*-*-*-*-*-*-*-*-*-*
1022    
1023    // //   return  sorted_tracks;
1024    //     return &sorted_tracks;
1025        
1026    //  };
1027    TClonesArray *PamLevel2::GetTracks(){
1028    
1029    //  *-*-*-*-*-*-*-*-*-*-*-*-*
1030        SortTracks();
1031    //  *-*-*-*-*-*-*-*-*-*-*-*-*
1032    
1033        return tsorted;
1034        
1035     };
1036    //--------------------------------------
1037     //
1038     //
1039    //--------------------------------------
1040    /**
1041   * Retrieves the it-th Pamela "physical" track.   * Retrieves the it-th Pamela "physical" track.
1042   * It override TrkLevel2::GetTrack(int it).   * It override TrkLevel2::GetTrack(int it).
1043   * @param it Track number, ranging from 0 to GetNTracks().   * @param it Track number, ranging from 0 to GetNTracks().
1044   */   */
1045  PamTrack *PamLevel2::GetTrack(int it){  PamTrack *PamLevel2::GetTrack(int it){
1046    
1047      TClonesArray *aa = this->GetTracks();  //    if(!trk2_obj) return 0;
1048      TClonesArray &sorted = *aa;          
1049    // //  *-*-*-*+-*-*-*-*-*-*-*-*-*
1050    //     SortTracks("+CAL+TOF");
1051    // //  *-*-*-*-*-*-*-*-*-*-*-*-*
1052    // //    if(!sorted_tracks)return 0;
1053    //     if(sorted_tracks.IsEmpty())return 0;
1054    
1055    //     PamTrack *track = 0;
1056        
1057    //     if( it >=0 && it < trk2_obj->TrkLevel2::GetNTracks() && it<sorted_tracks.GetEntriesFast() ){    
1058    //      TrkTrack   *t = (TrkTrack*)sorted_tracks.At(it);
1059    //      track = GetPamTrackAlong(t);
1060    //     }else{
1061    //      cout << "PamLevel2::GetTrack(int) : tracker track SeqNo "<< it <<" does not exist (GetNTracks() = "<<trk2_obj->TrkLevel2::GetNTracks()<<")"<<endl;
1062    //     };
1063        
1064    //     return track;
1065    
1066      TrkTrack   *t = 0;  //    cout << "PamLevel2::GetTrack(int it) "<<endl;
1067      CaloTrkVar *c = 0;  //  *-*-*-*-*-*-*-*-*-*-*-*-*
1068      ToFTrkVar  *o = 0;      SortTracks();
1069    //  *-*-*-*-*-*-*-*-*-*-*-*-*
1070        if(!tsorted)return 0;
1071        if(!tsorted->GetEntries())return 0;
1072    
1073      if( it >=0 && it < TrkLevel2::GetNTracks() ){      PamTrack *track = 0;
1074          t = (TrkTrack*)sorted[it];      
1075          c = CaloLevel2::GetCaloTrkVar(t->GetSeqNo());      if( it >=0 && it < trk2_obj->TrkLevel2::GetNTracks()){
1076          o = ToFLevel2::GetToFTrkVar(t->GetSeqNo());  //      TrkTrack   *t = (TrkTrack*)sorted_tracks.At(it);
1077    //      track = GetPamTrackAlong(t);
1078            TClonesArray &t = *(tsorted);
1079            track = (PamTrack*)t[it];
1080            
1081        }else{
1082            cout << "PamLevel2::GetTrack(int) : tracker track SeqNo "<< it <<" does not exist (GetNTracks() = "<<trk2_obj->TrkLevel2::GetNTracks()<<")"<<endl;
1083      };      };
1084            
     // hence create a "PamTrack" object  
     PamTrack *track = 0;  
     if(t && c && o)track = new PamTrack(t,c,o);  
1085      return track;      return track;
1086        
1087  };  };
1088    
1089  //--------------------------------------  //--------------------------------------
1090  //  //
1091  //  //
1092  //--------------------------------------  //--------------------------------------
1093  /**  /**
1094   * Retrieves (if present) the image of the it-th Pamela "physical" track, sorted by the method PamLevel2::GetTracks().   * Retrieves (if present) the image of the it-th Pamela "physical" track, sorted by the method PamLevel2::SortTracks().
1095   * @param it Track number, ranging from 0 to GetNTracks().   * @param it Track number, ranging from 0 to GetNTracks().
1096   */   */
1097  PamTrack *PamLevel2::GetTrackImage(int it){  PamTrack *PamLevel2::GetTrackImage(int it){
1098    
1099      TClonesArray *aa = this->GetTracks();  //     if(!trk2_obj) return 0;
1100      TClonesArray &sorted = *aa;  
1101    // //  *-*-*-*-*-*-*-*-*-*-*-*-*
1102    //     SortTracks("+CAL+TOF");
1103    // //  *-*-*-*-*-*-*-*-*-*-*-*-*
1104    // //    if(!sorted_tracks)return 0;
1105    //     if(sorted_tracks.IsEmpty())return 0;
1106        
1107    //     PamTrack *image = 0;
1108        
1109    //     if( it >=0 && it < trk2_obj->TrkLevel2::GetNTracks() ){
1110    //      TrkTrack *temp = (TrkTrack*)sorted_tracks.At(it);
1111    //      if( temp->HasImage() ){
1112    //          TrkTrack   *t = trk2_obj->TrkLevel2::GetStoredTrack(temp->GetImageSeqNo());
1113    //          image = GetPamTrackAlong(t);
1114    //      }else{
1115    //          cout <<"PamLevel2::GetTrackImage(int) : Track SeqNo "<<it<<" does not have image"<<endl;
1116    //      };
1117    //     }else{
1118    //      cout << "PamLevel2::GetTrackImage(int) : Tracker track SeqNo "<< it <<" does not exist (GetNTracks() = "<<trk2_obj->TrkLevel2::GetNTracks()<<")"<<endl;
1119    //     };
1120        
1121    //     return image;
1122    
     TrkTrack   *t = 0;  
     CaloTrkVar *c = 0;  
     ToFTrkVar  *o = 0;  
1123    
1124      if( it >=0 && it < TrkLevel2::GetNTracks() ){  //  *-*-*-*-*-*-*-*-*-*-*-*-*
1125          TrkTrack *temp = (TrkTrack*)sorted[it];      SortTracks();
1126          if( temp->HasImage() ){  //  *-*-*-*-*-*-*-*-*-*-*-*-*
1127              t = TrkLevel2::GetStoredTrack(temp->GetImageSeqNo());      if(!timage)return 0;
1128              c = CaloLevel2::GetCaloTrkVar(temp->GetImageSeqNo());      if(!timage->GetEntries())return 0;
1129              o = ToFLevel2::GetToFTrkVar(temp->GetImageSeqNo());      
1130        PamTrack *image = 0;
1131        
1132        if( it >=0 && it < trk2_obj->TrkLevel2::GetNTracks() ){
1133            TClonesArray &t = *(tsorted);
1134            PamTrack *temp = (PamTrack*)t[it];
1135            if( temp->GetTrkTrack()->HasImage() ){
1136                TClonesArray &t = *(timage);
1137                image = (PamTrack*)t[it];
1138            }else{
1139    //          cout <<"PamLevel2::GetTrackImage(int) : Track SeqNo "<<it<<" does not have image"<<endl;
1140          };          };
1141        }else{
1142            cout << "PamLevel2::GetTrackImage(int) : Tracker track SeqNo "<< it <<" does not exist (GetNTracks() = "<<trk2_obj->TrkLevel2::GetNTracks()<<")"<<endl;
1143      };      };
1144            
     // hence create a "PamTrack" object  
     PamTrack *image = 0;  
     if(t && c && o)image = new PamTrack(t,c,o);  
1145      return image;      return image;
       
1146  }  }
1147    
1148  //--------------------------------------  //--------------------------------------
# Line 209  PamTrack *PamLevel2::GetTrackImage(int i Line 1150  PamTrack *PamLevel2::GetTrackImage(int i
1150  //  //
1151  //--------------------------------------  //--------------------------------------
1152  /**  /**
1153   * Get the Pamela detector trees and make them friends.   * Get the Pamela detector trees in a single file and make them friends.
1154     * @param f TFile pointer
1155     * @param detlist String to select trees to be included
1156     * @return Pointer to a TTree
1157   */   */
1158  TTree *PamLevel2::LoadPamTrees(TFile *f){  TTree *PamLevel2::GetPamTree(TFile *f, TString detlist ){
1159        
1160      TTree *Tout =0;  //     if( !detlist.IsNull() ) SetWhichTrees(detlist);
1161        //     else                    GetWhichTrees(f);
1162      // Tracker    if ( pam_tree ){
1163        printf("WARNING: TTree *PamLevel2::GetPamTree(TFile *fl, TString detlist) -- pam_tree already exists!\n ");
1164        return pam_tree;
1165      };
1166      //
1167    
1168        cout << "TTree *PamLevel2::GetPamTree(TFile *f, TString detlist ) -- obsolte "<<endl;
1169    
1170        SetWhichTrees(detlist);
1171    
1172        TTree *Trout =0;
1173    
1174        TString fname = f->GetName();
1175        if(!CheckLevel2File(fname))return NULL;
1176    
1177    //    UInt_t *found=0;    
1178    
1179        cout<< "GetPamTree(TFile*,TString): detector list --> ";
1180        if(TRK1)cout<<"TRK1 ";
1181        if(TRK2)cout<<"TRK2 ";
1182        if(TRKh)cout<<"TRKH ";
1183        if(CAL1)cout<<"CAL1 ";
1184        if(CAL2)cout<<"CAL2 ";
1185        if(TOF)cout<<"TOF ";
1186        if(TRG)cout<<"TRG ";
1187        if(AC)cout<<"AC ";
1188        if(ND)cout<<"ND ";
1189        if(S4)cout<<"S4 ";
1190        if(ORB)cout<<"ORB ";
1191        cout << endl;
1192        if(SELLI)cout<<">>> Found selection-list <<<"<<endl;
1193    
1194        f->cd();
1195    
1196    // Tracker
1197      TTree *T = (TTree*)f->Get("Tracker");      TTree *T = (TTree*)f->Get("Tracker");
1198      if(T) {      if(T && (TRK2||TRK1||TRKh)) {
1199          T->SetBranchAddress("TrkLevel2", GetPointerToTrk());          if(TRK2)T->SetBranchAddress("TrkLevel2", GetPointerTo("TrkLevel2"));
1200          cout << "Tracker      : set branch address TrkLevel2"<<endl;  //      else    T->SetBranchStatus("TrkLevel2",0,found);
1201          if(!Tout)Tout=T;          if(TRK2)cout << "Tracker      : set branch address TrkLevel2"<<endl;
1202            if(TRK1)T->SetBranchAddress("TrkLevel1", GetPointerTo("TrkLevel1"));
1203    //      else    T->SetBranchStatus("TrkLevel1",0,found);
1204            if(TRK1)cout << "Tracker      : set branch address TrkLevel1"<<endl;
1205            if(TRKh)T->SetBranchAddress("TrkHough", GetPointerTo("TrkHough"));
1206    //      else    T->SetBranchStatus("TrkHough",0,found);
1207            if(TRKh)cout << "Tracker      : set branch address TrkHough"<<endl;
1208            if(!Trout)Trout=T;
1209            else Trout->AddFriend(T);
1210      }else{      }else{
1211          cout << "Tracker      : missing tree"<<endl;          cout << "Tracker      : missing tree"<<endl;
1212      };      };
1213      // Calorimeter      // Calorimeter
1214      TTree *C = (TTree*)f->Get("Calorimeter");      TTree *C = (TTree*)f->Get("Calorimeter");
1215      if(C) {      if(C && (CAL2||CAL1)) {
1216          C->SetBranchAddress("CaloLevel2", GetPointerToCalo());          if(CAL2)C->SetBranchAddress("CaloLevel2", GetPointerTo("CaloLevel2"));
1217          cout << "Calorimeter  : set branch address CaloLevel2"<<endl;  //      else    C->SetBranchStatus("CaloLevel2",0,found);
1218          if(!Tout)Tout=C;          if(CAL2)cout << "Calorimeter  : set branch address CaloLevel2"<<endl;
1219          else Tout->AddFriend(C);          if(CAL1)C->SetBranchAddress("CaloLevel1", GetPointerTo("CaloLevel1"));
1220    //      else    C->SetBranchStatus("CaloLevel1",0,found);
1221            if(CAL1)cout << "Calorimeter  : set branch address CaloLevel1"<<endl;
1222            if(!Trout)Trout=C;
1223            else Trout->AddFriend(C);
1224      }else{      }else{
1225          cout << "Calorimeter  : missing tree"<<endl;          cout << "Calorimeter  : missing tree"<<endl;
1226      };      };
1227    
1228      // ToF          // ToF    
1229      TTree *O = (TTree*)f->Get("ToF");      TTree *O = (TTree*)f->Get("ToF");
1230      if(O) {      if(O && TOF) {
1231          O->SetBranchAddress("ToFLevel2", GetPointerToToF());          O->SetBranchAddress("ToFLevel2", GetPointerTo("ToFLevel2"));
1232          cout << "ToF          : set branch address ToFLevel2"<<endl;          cout << "ToF          : set branch address ToFLevel2"<<endl;
1233          if(!Tout)Tout=O;          if(!Trout)Trout=O;
1234          else Tout->AddFriend(O);          else Trout->AddFriend(O);
1235      }else{      }else{
1236          cout << "ToF         : missing tree"<<endl;          cout << "ToF         : missing tree"<<endl;
1237      };      };
1238      // Trigger      // Trigger
1239      TTree *R = (TTree*)f->Get("Trigger");      TTree *R = (TTree*)f->Get("Trigger");
1240      if(R) {      if(R && TRG) {
1241          R->SetBranchAddress("TrigLevel2", GetPointerToTrig());          R->SetBranchAddress("TrigLevel2", GetPointerTo("TrigLevel2"));
1242          cout << "Trigger      : set branch address TrigLevel2"<<endl;          cout << "Trigger      : set branch address TrigLevel2"<<endl;
1243          if(!Tout)Tout=O;          if(!Trout)Trout=R;
1244          else Tout->AddFriend(R);          else Trout->AddFriend(R);
1245      }else{      }else{
1246          cout << "Trigger      : missing tree"<<endl;          cout << "Trigger      : missing tree"<<endl;
1247      };      };
1248      // S4      // S4
1249      TTree *S = (TTree*)f->Get("S4");      TTree *S = (TTree*)f->Get("S4");
1250      if(S) {      if(S && S4) {
1251          S->SetBranchAddress("S4Level2", GetPointerToS4());          S->SetBranchAddress("S4Level2", GetPointerTo("S4Level2"));
1252          cout << "S4           : set branch address S4Level2"<<endl;          cout << "S4           : set branch address S4Level2"<<endl;
1253          if(!Tout)Tout=O;          if(!Trout)Trout=S;
1254          else Tout->AddFriend(S);          else Trout->AddFriend(S);
1255      }else{      }else{
1256          cout << "S4           : missing tree"<<endl;          cout << "S4           : missing tree"<<endl;
1257      };      };
1258      // Neutron Detector      // Neutron Detector
1259      TTree *N = (TTree*)f->Get("NeutronD");      TTree *N = (TTree*)f->Get("NeutronD");
1260      if(N) {      if(N && ND) {
1261          N->SetBranchAddress("NDLevel2", GetPointerToND());          N->SetBranchAddress("NDLevel2", GetPointerTo("NDLevel2"));
1262          cout << "NeutronD     : set branch address NDLevel2"<<endl;          cout << "NeutronD     : set branch address NDLevel2"<<endl;
1263          if(!Tout)Tout=O;          if(!Trout)Trout=N;
1264          else Tout->AddFriend(N);          else Trout->AddFriend(N);
1265      }else{      }else{
1266          cout << "NeutronD     : missing tree"<<endl;          cout << "NeutronD     : missing tree"<<endl;
1267      };      };
1268      // Anticounters      // Anticounters
1269      TTree *A = (TTree*)f->Get("Anticounter");      TTree *A = (TTree*)f->Get("Anticounter");
1270      if(A) {      if(A && AC) {
1271          A->SetBranchAddress("AcLevel2", GetPointerToAc());          A->SetBranchAddress("AcLevel2", GetPointerTo("AcLevel2"));
1272          cout << "Anticounter  : set branch address AcLevel2"<<endl;          cout << "Anticounter  : set branch address AcLevel2"<<endl;
1273          if(!Tout)Tout=O;          if(!Trout)Trout=A;
1274          else Tout->AddFriend(A);          else Trout->AddFriend(A);
1275      }else{      }else{
1276          cout << "Anticounter  : missing tree"<<endl;          cout << "Anticounter  : missing tree"<<endl;
1277      };      };
1278        // Orbital Info
1279        TTree *B = (TTree*)f->Get("OrbitalInfo");
1280        if(B && ORB) {
1281            B->SetBranchAddress("OrbitalInfo", GetPointerTo("OrbitalInfo"));
1282            cout << "OrbitalInfo  : set branch address OrbitalInfo"<<endl;
1283            if(!Trout)Trout=B;
1284            else Trout->AddFriend(B);
1285        }else{
1286            cout << "OrbitalInfo  : missing tree"<<endl;
1287        };
1288    
1289        TTree *L = (TTree*)f->Get("SelectionList");
1290        if(L && SELLI==1) {
1291    //      L->SetBranchAddress("RunEntry",&irun);
1292    //      cout << "SelectionList: set branch address RunEntry"<<endl;
1293    //      L->SetBranchAddress("EventEntry",&irunentry);
1294    //      cout << "SelectionList: set branch address EventEntry"<<endl;
1295    //      if(!Trout)Trout=O;
1296    //      else Trout->AddFriend("SelectionList");
1297            cout << " TTree *PamLevel2::GetPamTree(TFile, TString) >>> SelectionList not implemente!!!!"<<endl;
1298            sel_tree = 0;
1299        }else{
1300            cout << "SelectionList  : missing tree"<<endl;
1301        };
1302        
1303        cout<<endl<<" Number of entries: "<<Trout->GetEntries()<<endl<<endl;
1304    
1305        pam_tree = (TChain*)Trout;
1306        
1307        return Trout;
1308        
1309    }
1310    //--------------------------------------
1311    //
1312    //
1313    //--------------------------------------
1314    /**
1315     * Get list of Level2 files.
1316     * @param ddir Level2 data directory.
1317     * @param flisttxt Name of txt file containing file list.
1318     * @return Pointer to a TList of TSystemFiles
1319     * If no input file list is given , all the Level2 files inside the directory are processed.
1320     */
1321    TList*  PamLevel2::GetListOfLevel2Files(TString ddir, TString flisttxt = ""){
1322            
1323        TString wdir = gSystem->WorkingDirectory();
1324        
1325        //    if(ddir=="")ddir = wdir;
1326    //      TSystemDirectory *datadir = new TSystemDirectory(gSystem->BaseName(ddir),ddir);
1327        if ( ddir != ""){
1328          cout << "Level2 data directory : "<<  ddir << endl;
1329        } else {
1330          cout << "Level2 data directory not given as input: trying to evaluate from list or taking working directory " << endl;
1331        };
1332        TList *contents  = new TList; // create output list
1333        contents->SetOwner();
1334        
1335    //    char *fullpath;
1336    //    const char *fullpath;
1337        
1338        // if no input file list is given:  
1339        if ( flisttxt != "" ){
1340            
1341    //      if( !gSystem->IsFileInIncludePath(flisttxt,&fullpath) ){        
1342    //      if( !(fullpath = gSystem->FindFile("./",flisttxt)) ){
1343    //          cout <<"File "<<flisttxt<<" not found"<<endl;
1344    //          return 0;
1345    //      }      
1346    //      flisttxt = fullpath;
1347          if ( !flisttxt.EndsWith(".root") ){
1348    
1349            flisttxt = gSystem->ConcatFileName(gSystem->DirName(flisttxt),gSystem->BaseName(flisttxt));
1350    
1351            if( !gSystem->ChangeDirectory(ddir) ){
1352                cout << "Cannot change directory : "<<ddir<<endl;
1353                return 0;
1354            }
1355            
1356            cout <<"Input file list : " << flisttxt <<endl;
1357            ifstream in;
1358            in.open(flisttxt, ios::in); //open input file list
1359            if(!in.good()){
1360                cout <<" ERROR opening the file "<<endl;
1361                gSystem->ChangeDirectory(wdir); // back to the working directory
1362                return 0;
1363            }      
1364            int line=0;
1365            while (1) {
1366                TString file;
1367                in >> file;
1368                if (!in.good()) break;
1369                line++;
1370    //          cout <<"(1) " << file << endl;
1371                if(file.IsNull()){
1372                    cout << "-- list interrupted at line "<<line <<endl;
1373                    break;
1374                }
1375                if(file.Contains("#"))file = file(0,file.First("#"));
1376    //          cout <<"(2) " << file << endl;
1377    //          if( gSystem->IsFileInIncludePath(file,&fullpath) ){
1378    //          if( (fullpath = gSystem->FindFile(ddir,file)) ){
1379                if( file.EndsWith(".root") ){
1380                  TString filedir;
1381                  if (ddir != ""){
1382                    filedir = ddir; // take the input dir
1383                  } else {
1384                    gSystem->ChangeDirectory(wdir); // back to the working directory
1385                    filedir = gSystem->DirName(file); // this will take the path if exist in the list otherwise it will return automatically the working dir
1386                  };
1387                    char *fullpath = gSystem->ConcatFileName(gSystem->DirName(filedir),gSystem->BaseName(file));
1388                    contents->Add(new TSystemFile(fullpath,gSystem->DirName(fullpath)));// add file to the list
1389                    delete fullpath;
1390                }
1391    //          }else{
1392    //              if(file.Data()!="")cout << "File: "<<file<<" ---> missing "<< endl;
1393    //          };
1394            };
1395            in.close();
1396          } else {
1397              if(flisttxt.Contains("#"))flisttxt = flisttxt(0,flisttxt.First("#"));
1398              char *fullpath = gSystem->ConcatFileName(gSystem->DirName(flisttxt),gSystem->BaseName(flisttxt));
1399              contents->Add(new TSystemFile(fullpath,gSystem->DirName(fullpath)));// add file to the list
1400              delete fullpath;
1401          };        
1402        }else{
1403            
1404            cout << "No input file list given."<<endl;
1405            cout << "Check for existing root files."<<endl;
1406    //              cout << "Warking directory: "<< gSystem->WorkingDirectory()<< endl;
1407            if ( ddir == "" ){
1408              ddir = wdir;
1409              cout << "Level2 data directory : "<<  ddir << endl;
1410            };
1411    
1412            TSystemDirectory *datadir = new TSystemDirectory(gSystem->BaseName(ddir),ddir);
1413            TList *temp = datadir->GetListOfFiles();
1414    //              temp->Print();
1415    //              cout << "*************************************" << endl;
1416            
1417            TIter next(temp);
1418            TSystemFile *questo = 0;
1419            
1420            
1421            while ( (questo = (TSystemFile*) next()) ) {
1422                TString name =  questo-> GetName();
1423                if( name.EndsWith(".root") ){
1424    //              const char *fullpath = gSystem->FindFile(ddir,name);
1425    //              char *fullpath;
1426    //              gSystem->IsFileInIncludePath(name,&fullpath);
1427                    char *fullpath = gSystem->ConcatFileName(gSystem->DirName(ddir),gSystem->BaseName(name));
1428                    contents->Add(new TSystemFile(fullpath,gSystem->DirName(fullpath)));
1429                    delete fullpath;
1430                };
1431            }
1432            delete temp;
1433            delete datadir;
1434            
1435        };
1436        gSystem->ChangeDirectory(wdir); // back to the working directory
1437    //      cout << endl << "Selected files:" << endl;
1438    //      contents->Print();
1439        cout << contents->GetEntries()<<" files \n";
1440    //      cout << endl;
1441    //      cout << "Working directory: "<< gSystem->WorkingDirectory()<< endl;
1442        return contents;
1443    };
1444    //--------------------------------------
1445    //
1446    //
1447    //--------------------------------------
1448    /**
1449     * Get the Pamela detector chains from a list of files and make them friends.
1450     * @param fl Pointer to a TList of TSystemFiles
1451     * @param detlist String to select trees to be included
1452     * @return Pointer to a TChain
1453     */
1454    TChain *PamLevel2::GetPamTree(TList *fl, TString detlist ){
1455      //
1456      //
1457      //
1458      if ( pam_tree ){
1459        printf("WARNING: TChain *PamLevel2::GetPamTree(TList *fl, TString detlist) -- pam_tree already exists!\n ");
1460        return pam_tree;
1461      };
1462      //
1463        
1464        TChain *Trout =0;
1465    
1466    //    if( !detlist.IsNull() )SetWhichTrees(detlist);
1467        SetWhichTrees(detlist);
1468            
1469      return Tout;      cout<< "GetPamTree(TList*,TString): input detector list --> ";
1470        if(TRK1)cout<<"TRK1 ";
1471        if(TRK2)cout<<"TRK2 ";
1472        if(TRKh)cout<<"TRKH ";
1473        if(CAL1)cout<<"CAL1 ";
1474        if(CAL2)cout<<"CAL2 ";
1475        if(TOF)cout<<"TOF ";
1476        if(TRG)cout<<"TRG ";
1477        if(AC)cout<<"AC ";
1478        if(ND)cout<<"ND ";
1479        if(S4)cout<<"S4 ";
1480        if(ORB)cout<<"ORB ";
1481        cout << endl;
1482    
1483         TChain *T = 0;    
1484         TChain *C = 0;
1485         TChain *O = 0;
1486         TChain *R = 0;
1487         TChain *S = 0;
1488         TChain *N = 0;
1489         TChain *A = 0;
1490         TChain *B = 0;
1491    
1492         TChain *L = 0;
1493        
1494        if(TRK2||TRK1||TRKh) T = new TChain("Tracker");    
1495        if(CAL2||CAL1)       C = new TChain("Calorimeter");
1496        if(TOF)              O = new TChain("ToF");
1497        if(TRG)              R = new TChain("Trigger");
1498        if(S4)               S = new TChain("S4");
1499        if(ND)               N = new TChain("NeutronD");
1500        if(AC)               A = new TChain("Anticounter");
1501        if(ORB)              B = new TChain("OrbitalInfo");
1502         L = new TChain("SelectionList");
1503        
1504        // loop over files and create chains        
1505        TIter next(fl);
1506        TSystemFile *questo = 0;
1507        while ( (questo = (TSystemFile*) next()) ) {
1508            TString name =  questo->GetName();
1509            cout << "File: "<< name << endl;
1510            if( CheckLevel2File(name) ){
1511                if(TRK2||TRK1||TRKh) T->Add(name);
1512                if(CAL1||CAL2)       C->Add(name);
1513                if(TOF)              O->Add(name);
1514                if(TRG)              R->Add(name);
1515                if(S4)               S->Add(name);
1516                if(ND)               N->Add(name);
1517                if(AC)               A->Add(name);
1518                if(ORB)              B->Add(name);
1519                if(SELLI==1)         L->Add(name);
1520            };
1521        };
1522            
1523        cout << "done chain \n";
1524        cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;
1525    
1526    //    UInt_t *found=0;
1527    // Tracker
1528        if(T && (TRK2||TRK1||TRKh)) {
1529            if(TRK2)T->SetBranchAddress("TrkLevel2", GetPointerTo("TrkLevel2"));
1530    //      else    T->SetBranchStatus("TrkLevel2",0,found);
1531            if(TRK2)cout << "Tracker      : set branch address TrkLevel2"<<endl;
1532            if(TRK1)T->SetBranchAddress("TrkLevel1", GetPointerTo("TrkLevel1"));
1533    //      else    T->SetBranchStatus("TrkLevel1",0,found);
1534            if(TRK1)cout << "Tracker      : set branch address TrkLevel1"<<endl;
1535            if(TRKh)T->SetBranchAddress("TrkHough", GetPointerTo("TrkHough"));
1536    //      else    T->SetBranchStatus("TrkHough",0,found);
1537            if(TRKh)cout << "Tracker      : set branch address TrkHough"<<endl;
1538            if(!Trout)Trout=T;
1539            else Trout->AddFriend("Tracker");
1540        }else{
1541            cout << "Tracker      : missing tree"<<endl;
1542        };
1543        // Calorimeter
1544        if(C && (CAL2||CAL1)) {
1545            if(CAL2)C->SetBranchAddress("CaloLevel2", GetPointerTo("CaloLevel2"));
1546    //      else    C->SetBranchStatus("CaloLevel2",0,found);
1547            if(CAL2)cout << "Calorimeter  : set branch address CaloLevel2"<<endl;
1548            if(CAL1)C->SetBranchAddress("CaloLevel1", GetPointerTo("CaloLevel1"));
1549    //      else    C->SetBranchStatus("CaloLevel1",0,found);
1550            if(CAL1)cout << "Calorimeter  : set branch address CaloLevel1"<<endl;
1551            if(!Trout)Trout=C;
1552            else Trout->AddFriend("Calorimeter");
1553        }else{
1554            cout << "Calorimeter  : missing tree"<<endl;
1555        };
1556        // ToF    
1557        if(O && TOF) {
1558            O->SetBranchAddress("ToFLevel2", GetPointerTo("ToFLevel2"));
1559            cout << "ToF          : set branch address ToFLevel2"<<endl;
1560            if(!Trout)Trout=O;
1561            else Trout->AddFriend("ToF");
1562        }else{
1563            cout << "ToF         : missing tree"<<endl;
1564        };
1565        // Trigger
1566        if(R && TRG) {
1567            R->SetBranchAddress("TrigLevel2", GetPointerTo("TrigLevel2"));
1568            cout << "Trigger      : set branch address TrigLevel2"<<endl;
1569            if(!Trout)Trout=O;
1570            else Trout->AddFriend("Trigger");
1571        }else{
1572            cout << "Trigger      : missing tree"<<endl;
1573        };
1574        // S4
1575        if(S && S4) {
1576            S->SetBranchAddress("S4Level2", GetPointerTo("S4Level2"));
1577            cout << "S4           : set branch address S4Level2"<<endl;
1578            if(!Trout)Trout=O;
1579            else Trout->AddFriend("S4");
1580        }else{
1581            cout << "S4           : missing tree"<<endl;
1582        };
1583        // Neutron Detector
1584        if(N && ND) {
1585            N->SetBranchAddress("NDLevel2", GetPointerTo("NDLevel2"));
1586            cout << "NeutronD     : set branch address NDLevel2"<<endl;
1587            if(!Trout)Trout=O;
1588            else Trout->AddFriend("NeutronD");
1589        }else{
1590            cout << "NeutronD     : missing tree"<<endl;
1591        };
1592        // Anticounters
1593        if(A && AC) {
1594            A->SetBranchAddress("AcLevel2", GetPointerTo("AcLevel2"));
1595            cout << "Anticounter  : set branch address AcLevel2"<<endl;
1596            if(!Trout)Trout=O;
1597            else Trout->AddFriend("Anticounter");
1598        }else{
1599            cout << "Anticounter  : missing tree"<<endl;
1600        };
1601        // Orbital Info
1602        if(B && ORB) {
1603            B->SetBranchAddress("OrbitalInfo", GetPointerTo("OrbitalInfo"));
1604            cout << "OrbitalInfo  : set branch address OrbitalInfo"<<endl;
1605            if(!Trout)Trout=O;
1606            else Trout->AddFriend("OrbitalInfo");
1607        }else{
1608            cout << "OrbitalInfo  : missing tree"<<endl;
1609        };
1610        cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;
1611    
1612        // Selection List
1613        if(L && SELLI==1) {
1614            cout<<">>> Found selection-list <<<"<<endl;
1615            L->SetBranchAddress("RunEntry",&irun);
1616            cout << "SelectionList: set branch address RunEntry"<<endl;
1617            L->SetBranchAddress("EventEntry",&irunentry);
1618            cout << "SelectionList: set branch address EventEntry"<<endl;
1619            sel_tree = L;
1620    //      if(!Trout)Trout=O;
1621    //      else Trout->AddFriend("SelectionList");
1622            cout << "----------------------------------------------------" <<endl;
1623        }else{
1624    //      cout << "SelectionList  : missing tree"<<endl;
1625            if(L)L->Delete();
1626        };
1627        
1628    //    cout<<endl<<" Number of entries: "<<Trout->GetEntries()<<endl<<endl;
1629    
1630        pam_tree = Trout;
1631    
1632        return Trout;
1633    }
1634    
1635    
1636    
1637    //--------------------------------------
1638    //
1639    //
1640    //--------------------------------------
1641    /**
1642     * Set branch addresses for Pamela friend trees
1643     */
1644    void PamLevel2::SetBranchAddress(TTree *t){
1645    
1646        TRK2    = TRK2 & t->GetBranchStatus("TrkLevel2");
1647        TRK1    = TRK1 & t->GetBranchStatus("TrkLevel1");
1648        TRKh    = TRKh & t->GetBranchStatus("TrkHough");
1649        CAL2    = CAL2 & t->GetBranchStatus("CaloLevel2");
1650        CAL1    = CAL1 & t->GetBranchStatus("CaloLevel1");
1651        TOF    = TOF & t->GetBranchStatus("ToFLevel2");
1652        TRG    = TRG & t->GetBranchStatus("TrigLevel2");
1653        S4     = S4  & t->GetBranchStatus("S4Level2");
1654        ND     = ND  & t->GetBranchStatus("NDLevel2");
1655        AC     = AC  & t->GetBranchStatus("AcLevel2");
1656        ORB    = ORB & t->GetBranchStatus("OrbitalInfo");
1657    
1658    
1659        // Tracker
1660        if(TRK1) {
1661            t->SetBranchAddress("TrkLevel1", GetPointerTo("TrkLevel2"));
1662            cout << "Tracker      : set branch address TrkLevel1"<<endl;
1663        };
1664        if(TRK2) {
1665            t->SetBranchAddress("TrkLevel2", GetPointerTo("TrkLevel1"));
1666            cout << "Tracker      : set branch address TrkLevel2"<<endl;
1667        };
1668        if(TRKh) {
1669            t->SetBranchAddress("TrkHough", GetPointerTo("TrkHough"));
1670            cout << "Tracker      : set branch address TrkHough"<<endl;
1671        };
1672        
1673        // Calorimeter
1674        if(CAL1) {
1675            t->SetBranchAddress("CaloLevel1", GetPointerTo("CaloLevel1"));
1676            cout << "Calorimeter  : set branch address CaloLevel1"<<endl;
1677        };
1678        if(CAL2) {
1679            t->SetBranchAddress("CaloLevel2", GetPointerTo("CaloLevel2"));
1680            cout << "Calorimeter  : set branch address CaloLevel2"<<endl;
1681        };
1682        
1683        // ToF    
1684        if(TOF) {
1685            t->SetBranchAddress("ToFLevel2", GetPointerTo("ToFLevel2"));
1686            cout << "ToF          : set branch address ToFLevel2"<<endl;
1687        };
1688        // Trigger
1689        if(TRG) {
1690            t->SetBranchAddress("TrigLevel2", GetPointerTo("TrigLevel2"));
1691            cout << "Trigger      : set branch address TrigLevel2"<<endl;
1692        };
1693        // S4
1694        if(S4) {
1695            t->SetBranchAddress("S4Level2", GetPointerTo("S4Level2"));
1696            cout << "S4           : set branch address S4Level2"<<endl;
1697        };
1698        // Neutron Detector
1699        if(ND) {
1700            t->SetBranchAddress("NDLevel2", GetPointerTo("NDLevel2"));
1701            cout << "NeutronD     : set branch address NDLevel2"<<endl;
1702        };
1703        // Anticounters
1704        if(AC) {
1705            t->SetBranchAddress("AcLevel2", GetPointerTo("AcLevel2"));
1706            cout << "Anticounter  : set branch address AcLevel2"<<endl;
1707        };
1708        // OrbitalInfo
1709        if(ORB) {
1710            t->SetBranchAddress("OrbitalInfo", GetPointerTo("OrbitalInfo"));
1711            cout << "OrbitalInfo  : set branch address OrbitalInfo"<<endl;
1712        };
1713        // SelectionList
1714        if(SELLI==1) {
1715            t->SetBranchAddress("RunEntry", &irun);
1716            cout << "SelectionList: set branch address RunEntry"<<endl;
1717            t->SetBranchAddress("EventEntry", &irunentry);
1718            cout << "SelectionList: set branch address EventEntry"<<endl;
1719        };
1720        
1721    }
1722    /**
1723     * Set branch addresses for Pamela friend trees
1724     */
1725    void PamLevel2::SetBranchAddress(TChain *t){
1726    
1727        TRK2    = TRK2 & t->GetBranchStatus("TrkLevel2");
1728        TRK1    = TRK1 & t->GetBranchStatus("TrkLevel1");
1729        TRKh    = TRKh & t->GetBranchStatus("TrkHough");
1730        CAL1    = CAL1 & t->GetBranchStatus("CaloLevel1");
1731        CAL2    = CAL2 & t->GetBranchStatus("CaloLevel2");
1732        TOF    = TOF & t->GetBranchStatus("ToFLevel2");
1733        TRG    = TRG & t->GetBranchStatus("TrigLevel2");
1734        S4     = S4  & t->GetBranchStatus("S4Level2");
1735        ND     = ND  & t->GetBranchStatus("NDLevel2");
1736        AC     = AC  & t->GetBranchStatus("AcLevel2");
1737        ORB    = ORB & t->GetBranchStatus("OrbitalInfo");
1738    
1739        // Tracker
1740         if(TRK2) {
1741            t->SetBranchAddress("TrkLevel2", GetPointerTo("TrkLevel2"));
1742            cout << "Tracker      : set branch address TrkLevel2"<<endl;
1743        };
1744        if(TRK1) {
1745            t->SetBranchAddress("TrkLevel1", GetPointerTo("TrkLevel1"));
1746            cout << "Tracker      : set branch address TrkLevel1"<<endl;
1747        };
1748         if(TRKh) {
1749            t->SetBranchAddress("TrkHough", GetPointerTo("TrkHough"));
1750            cout << "Tracker      : set branch address TrkHough"<<endl;
1751         };
1752        
1753        // Calorimeter
1754        if(CAL2) {
1755            t->SetBranchAddress("CaloLevel2", GetPointerTo("CaloLevel2"));
1756            cout << "Calorimeter  : set branch address CaloLevel2"<<endl;
1757        };  
1758        if(CAL1) {
1759            t->SetBranchAddress("CaloLevel1", GetPointerTo("CaloLevel1"));
1760            cout << "Calorimeter  : set branch address CaloLevel1"<<endl;
1761        };
1762        
1763        // ToF    
1764        if(TOF) {
1765            t->SetBranchAddress("ToFLevel2", GetPointerTo("ToFLevel2"));
1766            cout << "ToF          : set branch address ToFLevel2"<<endl;
1767        };
1768        // Trigger
1769        if(TRG) {
1770            t->SetBranchAddress("TrigLevel2", GetPointerTo("TrigLevel2"));
1771            cout << "Trigger      : set branch address TrigLevel2"<<endl;
1772        };
1773        // S4
1774        if(S4) {
1775            t->SetBranchAddress("S4Level2", GetPointerTo("S4Level2"));
1776            cout << "S4           : set branch address S4Level2"<<endl;
1777        };
1778        // Neutron Detector
1779        if(ND) {
1780            t->SetBranchAddress("NDLevel2", GetPointerTo("NDLevel2"));
1781            cout << "NeutronD     : set branch address NDLevel2"<<endl;
1782        };
1783        // Anticounters
1784        if(AC) {
1785            t->SetBranchAddress("AcLevel2", GetPointerTo("AcLevel2"));
1786            cout << "Anticounter  : set branch address AcLevel2"<<endl;
1787        };
1788        // OrbitalInfo
1789        if(ORB) {
1790            t->SetBranchAddress("OrbitalInfo", GetPointerTo("OrbitalInfo"));
1791            cout << "OrbitalInfo  : set branch address OrbitalInfo"<<endl;
1792        };
1793        // SelectionList
1794        if(SELLI==1) {
1795            t->SetBranchAddress("RunEntry", &irun);
1796            cout << "SelectionList: set branch address RunEntry"<<endl;
1797            t->SetBranchAddress("EventEntry", &irunentry);
1798            cout << "SelectionList: set branch address EventEntry"<<endl;
1799        };
1800        
1801    }
1802    
1803    
1804    //--------------------------------------
1805    //
1806    //
1807    //--------------------------------------
1808    /**
1809     * Get the Run tree chain from a list of files.
1810     * @param fl Pointer to a TList of TSystemFiles
1811     * @return Pointer to a TChain
1812     */
1813    TChain *PamLevel2::GetRunTree(TList *fl){
1814      //
1815      //
1816      //
1817      if ( run_tree ){
1818        printf("WARNING: TChain *PamLevel2::GetRunTree(TList *fl) -- run_tree already exists!\n ");
1819        return run_tree;
1820      };    
1821      //
1822      TChain *R = new TChain("Run");
1823        
1824        // loop over files and create chains        
1825        TIter next(fl);
1826        TSystemFile *questo = 0;
1827        while ( (questo = (TSystemFile*) next()) ) {
1828            TString name =  questo->GetName();
1829    //              cout << "File: "<< name << endl;
1830            if( CheckLevel2File(name) ){
1831                R->Add(name);
1832            };
1833        }
1834    
1835        if(R->GetNtrees()){
1836        
1837            R->SetBranchAddress("RunInfo", GetPointerTo("RunInfo"));
1838            cout << "Run         : set branch address RunInfo"<<endl;
1839            R->SetBranchAddress("SoftInfo", GetPointerTo("SoftInfo")); // Emiliano
1840            cout << "Software    : set branch address SoftInfo"<<endl; // Emiliano
1841        }else{
1842            delete R;
1843            R=0;
1844        }
1845    
1846        run_tree = R;
1847    
1848        return R;
1849        
1850    }
1851    //--------------------------------------
1852    //
1853    //
1854    //--------------------------------------
1855    /**
1856     * Get the Run tree  from a file.
1857     * @param f Pointer to a TFile
1858     * @return Pointer to a TTree
1859     */
1860    TTree *PamLevel2::GetRunTree(TFile *f){
1861      if ( run_tree ){
1862        printf("WARNING: TTree *PamLevel2::GetRunTree(TFile *f) -- run_tree already exists!\n ");
1863        return run_tree;
1864      };
1865            
1866    
1867        cout << "TTree *PamLevel2::GetRunTree(TFile *f) -- obsolte "<<endl;
1868    
1869        TTree *T = (TTree*)f->Get("Run");
1870        
1871        if(T){
1872            T->SetBranchAddress("RunInfo", GetPointerTo("RunInfo"));
1873            cout << "Run         : set branch address RunInfo"<<endl;
1874            T->SetBranchAddress("SoftInfo", GetPointerTo("SoftInfo")); // Emiliano
1875            cout << "Software    : set branch address SoftInfo"<<endl; // Emiliano
1876        }
1877    
1878        run_tree = (TChain*)T;
1879    
1880        return T;
1881        
1882    }
1883    /**
1884     * Update the runinfo informations (to be used to have Run infos event by event basis)
1885     * @param run Pointer to the chain/tree which contains run infos
1886     * @return true if a new run has been read, false if it is still the same run
1887     */
1888    Bool_t PamLevel2::UpdateRunInfo(TChain *run, Long64_t iev){
1889      //
1890      // check if we have already called once GetEntry, if not call it
1891      //
1892        cout << "Bool_t PamLevel2::UpdateRunInfo(TChain *run, Long64_t iev) --- NON FUNZIONA BENISSIMO.... "<<endl;
1893        if(!run){
1894              cout << "Bool_t PamLevel2::UpdateRunInfo(TChain *run, ULong64_t iev) -- ERROR -- missing RunInfo tree "<<endl;
1895              return(false);        
1896        }
1897        if ( run->GetEntries() <= 0 ) return(false);
1898      //
1899      
1900      //  Int_t oldrun = irun;
1901      Long64_t oldrun = irun;
1902    
1903      // --------------------------------------
1904      // if it is a full file (not preselected)
1905      // --------------------------------------
1906      if(SELLI==0){
1907    
1908          //
1909          // the absolute time is necessary to relate the event with the run
1910          //
1911          if( !GetOrbitalInfo() && !ISGP){
1912              cout << "Bool_t PamLevel2::UpdateRunInfo(TChain *run, ULong64_t iev) -- ERROR -- missing OrbitalInfo "<<endl;
1913              return(false);
1914          }
1915    
1916          ULong64_t abstime = 0;
1917          if( GetOrbitalInfo() )abstime=GetOrbitalInfo()->absTime;
1918    
1919    
1920          //
1921          // the first time the routine is called, set run search from the beginning
1922          //
1923          if ( irun < 0LL ){
1924              irun = 0LL;
1925              run->GetEntry(irun);
1926              runfirstentry = 0LL;
1927              runlastentry += (Long64_t)(this->GetRunInfo()->NEVENTS);
1928              if ( (Long64_t)(this->GetRunInfo()->NEVENTS) > 0LL ) runlastentry -= 1LL;
1929              
1930              if( ISGP && run->GetEntries()!=1 ){
1931                  cout << "** WARNING ** simulated files are assumed to have 1 single run, not "<< run->GetEntries() << endl;
1932                  cout << "** WARNING ** run will not be updated"<<endl;
1933              }
1934    
1935          };      
1936          //
1937          if(ISGP)abstime = GetRunInfo()->RUNHEADER_TIME; // BARBATRUCCO
1938          //
1939          if ( irun == run->GetEntries()-1LL &&
1940               !(abstime >= GetRunInfo()->RUNHEADER_TIME &&
1941                 abstime <= GetRunInfo()->RUNTRAILER_TIME)
1942                ){
1943             irun = -1LL;
1944             runfirstentry = 0LL;
1945             runlastentry = -1LL;
1946           };
1947          // modificato il controllo sull'aggiornamento del run, per evitare problemi
1948          // dovuti agli eventi annidati (NB! NEVENTS conta anche questi!!)
1949          //
1950          bool fromfirst = true;
1951          //
1952          while ( !(abstime >= GetRunInfo()->RUNHEADER_TIME && abstime <= GetRunInfo()->RUNTRAILER_TIME) && irun < run->GetEntries()-1LL ){
1953    //      while ( iev > (runfirstentry+(ULong64_t)(this->GetRunInfo()->NEVENTS-1)) && irun < run->GetEntries() ){
1954              irun++;
1955              run->GetEntry(irun);
1956              runfirstentry = runlastentry;
1957              if ( (Long64_t)(this->GetRunInfo()->NEVENTS) > 0LL ) runfirstentry += 1LL;
1958              runlastentry += (Long64_t)(this->GetRunInfo()->NEVENTS);
1959    //        cout << " ))))) UPDATE RUN INFO (((((  @iev "<<iev<<" run "<<GetRunInfo()->ID<<" irun "<<irun<<endl;
1960    //        cout << "runfirstentry "<<runfirstentry<<endl;
1961              //      printf(" iev %llu %u %llu \n",iev,this->GetRunInfo()->NEVENTS,(ULong64_t)(runfirstentry+(ULong64_t)(this->GetRunInfo()->NEVENTS)));
1962              //      printf(" abstime %u trailertime %u \n",abstime,GetRunInfo()->RUNTRAILER_TIME);
1963              //      printf(" IDRUN %u \n",GetRunInfo()->ID);
1964              //
1965    //        prevshift = 0;
1966              //
1967              if ( irun == (Long64_t)(run->GetEntries()-1LL) && fromfirst && !(abstime >= GetRunInfo()->RUNHEADER_TIME && abstime <= GetRunInfo()->RUNTRAILER_TIME)){
1968                  printf(" resetting irun  (it should NOT happen!!!)\n");
1969                  fromfirst = false;
1970                  irun = 0;
1971                  run->GetEntry(irun);
1972                  runfirstentry = 0ULL;
1973                  runlastentry += (Long64_t)(this->GetRunInfo()->NEVENTS);
1974                  if ( (Long64_t)(this->GetRunInfo()->NEVENTS) > 0LL ) runlastentry -= 1LL;
1975              };
1976              //
1977          };
1978          //
1979          if (
1980               !(abstime >= GetRunInfo()->RUNHEADER_TIME &&
1981                 abstime <= GetRunInfo()->RUNTRAILER_TIME)
1982              ) {
1983              printf(" Something very wrong here: cannot find RUN containing absolute time %u \n",abstime);
1984              return false;
1985          }
1986          //
1987          if ( irun == oldrun || irun >= run->GetEntries() ) return(false);
1988          //
1989          //  printf(" iev %llu irun %i nevents %u 1st %llu last %llu \n",iev,irun,this->GetRunInfo()->NEVENTS,(ULong64_t)runfirstentry,(ULong64_t)runlastentry);
1990          //
1991          prevshift = 0;
1992          cout << " ))))) UPDATE RUN INFO (((((  @iev "<<iev<<" run "<<GetRunInfo()->ID<<" irun "<<irun<<endl;
1993    //      cout << "runfirstentry "<<runfirstentry<<endl;
1994          return(true);    
1995      };
1996      // ----------------------------------------------------
1997      // if it is a preselected file (there is SelectionList)
1998      // NBNB - the event tree MUST be read first
1999      // ----------------------------------------------------
2000      if(SELLI==1){      
2001          sel_tree->GetEntry(iev);
2002    //      cout << irun << " "<< irunentry << endl;
2003          if(irun != oldrun){
2004              run->GetEntry(irun);
2005              cout << " ))))) UPDATE RUN INFO (((((  @iev "<<iev<<" run "<<GetRunInfo()->ID<<" irun "<<irun<<endl;
2006              prevshift = 0;
2007              return true;
2008          }
2009          return false;
2010      }
2011    
2012      return false;
2013      //
2014    };
2015    
2016    Bool_t PamLevel2::UpdateRunInfo(Long64_t iev){
2017    
2018        if(!run_tree){
2019            cout << " Bool_t PamLevel2::UpdateRunInfo(ULong64_t iev) -- ERROR -- run tree not loaded"<<endl;
2020            return false;
2021        }
2022        if ( run_tree->GetEntries() <= 0 ) {
2023            cout << " Bool_t PamLevel2::UpdateRunInfo(ULong64_t iev) -- ERROR -- run tree is empty"<<endl;
2024            return(false);
2025        }
2026      
2027        Int_t oldrun = irun; // store current run index
2028    
2029        // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
2030        // if it is a full file (not preselected)
2031        // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
2032        if(SELLI==0){
2033    
2034            ULong64_t abstime = 0;
2035            ULong64_t obt     = 0;
2036            if( GetOrbitalInfo() ){
2037                abstime = GetOrbitalInfo()->absTime;
2038                obt     = GetOrbitalInfo()->OBT;
2039            }
2040            // ---------------------------------------------------------------
2041            // the absolute time is necessary to relate the event with the run
2042            // ---------------------------------------------------------------
2043            if( !GetOrbitalInfo() && !ISGP ){
2044                cout << "Bool_t PamLevel2::UpdateRunInfo(Long64_t iev) -- ERROR -- missing OrbitalInfo "<<endl;
2045                return(false);
2046            }
2047          
2048            // -----------------------------------------------------------------------
2049            // the first time the routine is called, set run search from the beginning
2050            // -----------------------------------------------------------------------
2051            if ( irun < 0 ){
2052                irun = 0LL;
2053                irunentry = 0;
2054                prevshift = 0;
2055                run_tree->GetEntry(irun);
2056    
2057                if( ISGP && run_tree->GetEntries()!=1 ){
2058                    cout << "** WARNING ** simulated files are assumed to have 1 single run, not "<< run_tree->GetEntries() << endl;
2059                    cout << "** WARNING ** run will not be updated"<<endl;
2060                }
2061            };      
2062    
2063            // -----------------------------------------------------------------------
2064            // if it is simulation, assigh abstime by end (temporaneo!!!)
2065            // -----------------------------------------------------------------------
2066            if(ISGP){
2067                abstime = GetRunInfo()->RUNHEADER_TIME; // BARBATRUCCO
2068                obt     = GetRunInfo()->RUNHEADER_OBT; // BARBATRUCCO
2069            }
2070            //
2071            bool fromfirst = true; // first loop over runs
2072    
2073    //      Bool_t hasfrag = false;
2074    //      if( GetRunInfo()->ID_RUN_FRAG!=0 && GetRunInfo()->ID_RUN_FRAG != GetRunInfo()->ID)hasfrag=true;
2075    //      ULong64_t fragid = GetRunInfo()->ID_RUN_FRAG;
2076    
2077            // ------------------------------------------------------
2078            // loop over runs to find the one that contains the event
2079            // ------------------------------------------------------
2080            while (
2081                (
2082                    (
2083                        !(abstime >= GetRunInfo()->RUNHEADER_TIME &&    // check on absolute time (s)
2084                          abstime <= GetRunInfo()->RUNTRAILER_TIME) &&
2085                        !(obt >= GetRunInfo()->RUNHEADER_OBT &&         // additional check on OBT (ms)
2086                          obt <= GetRunInfo()->RUNTRAILER_OBT)
2087                        )
2088                    || GetRunInfo()->NEVENTS==0
2089                    || !(irunentry < GetRunInfo()->NEVENTS-1-prevshift)
2090                    )
2091                    && irun < run_tree->GetEntries() ){
2092    
2093                irun++;
2094                // ------------------------------------
2095                // if the end of run tree is reached...
2096                // ------------------------------------
2097                if( irun == run_tree->GetEntries() ){
2098                    if(!fromfirst){
2099                        // -----------------------------------------------------
2100                        // if it happened already once and the run was not found
2101                        // ---> exit with error
2102                        // -----------------------------------------------------
2103                        cout << "Bool_t PamLevel2::UpdateRunInfo(Long64_t iev) -- ERROR -- event entry #"<<iev<<" does not belong to any run (should not happen)" <<endl;
2104                        return false;
2105                    }
2106                    // -----------------------------------------
2107                    // ...otherwise repeat search from beginning
2108                    // -----------------------------------------
2109                    cout << "Bool_t PamLevel2::UpdateRunInfo(Long64_t iev) -- WARNING -- reached end of run tree. searchin again from beginning " <<endl;
2110                    fromfirst = false;
2111                    irun = 0LL;
2112                    runfirstentry = 0LL;
2113                }
2114                // -------------------------------------------------------------------
2115                // save the index of the first entry of the run, relative to pam_tree,
2116                // and read a new run
2117                // -------------------------------------------------------------------
2118                if(irun>0)runfirstentry += (GetRunInfo()->NEVENTS)-prevshift;
2119                irunentry = 0;
2120                prevshift = 0;
2121                run_tree->GetEntry(irun);      
2122                if(GetRunInfo()->RUNHEADER_OBT>GetRunInfo()->RUNTRAILER_OBT ){
2123                    cout << "Bool_t PamLevel2::UpdateRunInfo(Long64_t iev) -- WARNING -- irun "<<irun<<"  has RUNHEADER_OBT>=RUNTRAILER_OBT " <<endl;
2124                    cout << "                                                            (NB!! in this case some events are assigned to a wrong run)"<<endl;
2125                }
2126    //          if(hasfrag &&  fragid != GetRunInfo()->ID){
2127    //              cout << "... where is the next fragment ??"<<endl;
2128    //          }
2129            };
2130    
2131    
2132            // --------------------------------------
2133            // if there was no need to update the run
2134            // ---> exit with FALSE
2135            // --------------------------------------
2136            if ( irun == oldrun ) return(false);
2137    
2138            // --------------------------------------
2139            // ... otherwise
2140            // ---> exit with TRUE
2141            // --------------------------------------
2142            cout << endl << " ))))) UPDATE RUN INFO (((((  @iev "<<iev<<" run "<<GetRunInfo()->ID<<" irun "<<irun<<endl;
2143            // ----------------------------------------------------
2144            // then check if the run has a fragment
2145            // in this case we have to switch to the next fragment
2146            // when the end of the first fragment is reached
2147            // ----------------------------------------------------
2148            if(
2149                GetRunInfo()->ID_RUN_FRAG != 0 &&
2150    //          GetRunInfo()->ID_RUN_FRAG != GetRunInfo()->ID &&
2151                true ){
2152                cout << "* fragment *"<<endl;              
2153            }
2154            
2155            return(true);    
2156        };
2157        // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
2158        // if it is a preselected file (there is SelectionList)
2159        // +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
2160        if(SELLI==1){      
2161            sel_tree->GetEntry(iev);
2162            if(irun != oldrun){
2163                run_tree->GetEntry(irun);
2164                cout << endl << " ))))) UPDATE RUN INFO (((((  @iev "<<iev<<" run "<<GetRunInfo()->ID<<" irun "<<irun<<endl;
2165                prevshift = 0;
2166                return true;
2167            }
2168            return false;
2169        }
2170    
2171        return false;
2172        //
2173    };
2174    /**
2175     * Update the runinfo informations (to be used to have Run infos event by event basis)
2176     * @param run Pointer to the chain/tree which contains run infos
2177     * @return true if a new run has been read, false if it is still the same run
2178     */
2179    Bool_t PamLevel2::UpdateRunInfo(TTree *run, Long64_t iev){
2180      return(UpdateRunInfo((TChain*)run,iev));
2181    };
2182    
2183    //--------------------------------------
2184    //
2185    //
2186    //--------------------------------------
2187    /**
2188     * Set which trees shoul be analysed
2189     * @param detlist TString containing the sequence of trees required
2190    */
2191    void PamLevel2::SetWhichTrees(TString detlist){
2192            
2193        if(detlist.IsNull() || detlist.Contains("+ALL", TString::kIgnoreCase)){
2194            CAL0 = false;
2195            CAL1 = true;
2196            CAL2 = true;
2197            TRK2 = true;
2198            TRK1 = false;
2199            TRKh = false;
2200            TRK0 = false;
2201            TRG = true;
2202            TOF = true;
2203            TOF0 = false;
2204            S4  = true;
2205            ND  = true;
2206            AC  = true;
2207            ORB = true;
2208        }else if( detlist.Contains("-ALL", TString::kIgnoreCase) ){
2209            CAL0 = false;
2210            CAL1 = false;
2211            CAL2 = false;
2212            TRK2 = false;
2213            TRK1 = false;
2214            TRKh = false;
2215            TRK0 = false;
2216            TRG = false;
2217            TOF = false;
2218            TOF0 = false;
2219            S4  = false;
2220            ND  = false;
2221            AC  = false;
2222            ORB = false;
2223        };
2224        
2225    //  -------------------------------------------------------------------------
2226        if( detlist.Contains("CAL1", TString::kIgnoreCase) ){
2227            if ( detlist.Contains("-CAL1", TString::kIgnoreCase) )CAL1=false;
2228            if ( detlist.Contains("+CAL1", TString::kIgnoreCase) )CAL1=true;
2229        };
2230    
2231        if( detlist.Contains("CAL0", TString::kIgnoreCase) ){
2232            if ( detlist.Contains("-CAL0", TString::kIgnoreCase) )CAL0=false;
2233            if ( detlist.Contains("+CAL0", TString::kIgnoreCase) )CAL0=true;
2234        };
2235            
2236        if( detlist.Contains("CAL2", TString::kIgnoreCase)){
2237            if ( detlist.Contains("-CAL2", TString::kIgnoreCase) )CAL2=false;
2238            if ( detlist.Contains("+CAL2", TString::kIgnoreCase) )CAL2=true;
2239        };
2240            
2241        if( detlist.Contains("+CAL", TString::kIgnoreCase) && !CAL1 && !CAL2 )CAL2=true;
2242        if( detlist.Contains("-CAL", TString::kIgnoreCase) && CAL1 && CAL2 ){
2243            CAL2=false;
2244            CAL1=false;
2245        }
2246    //  -------------------------------------------------------------------------
2247        if( detlist.Contains("TRK0", TString::kIgnoreCase) ){
2248            if ( detlist.Contains("-TRK0", TString::kIgnoreCase) )TRK0=false;
2249            if ( detlist.Contains("+TRK0", TString::kIgnoreCase) )TRK0=true;
2250        };
2251    
2252        if( detlist.Contains("TRK1", TString::kIgnoreCase) ){
2253            if ( detlist.Contains("-TRK1", TString::kIgnoreCase) )TRK1=false;
2254            if ( detlist.Contains("+TRK1", TString::kIgnoreCase) )TRK1=true;
2255        };
2256            
2257        if( detlist.Contains("TRK2", TString::kIgnoreCase)){
2258            if ( detlist.Contains("-TRK2", TString::kIgnoreCase) )TRK2=false;
2259            if ( detlist.Contains("+TRK2", TString::kIgnoreCase) )TRK2=true;
2260        };
2261    
2262        if( detlist.Contains("TRKh", TString::kIgnoreCase)){
2263            if ( detlist.Contains("-TRKh", TString::kIgnoreCase) )TRKh=false;
2264            if ( detlist.Contains("+TRKh", TString::kIgnoreCase) )TRKh=true;
2265        };
2266            
2267        if( detlist.Contains("+TRK", TString::kIgnoreCase) && !TRK1 && !TRK2 && !TRKh )TRK2=true;
2268        if( detlist.Contains("-TRK", TString::kIgnoreCase) && TRK1 && TRK2 && TRKh){
2269            TRK2=false;
2270            TRK1=false;
2271            TRKh=false;
2272        }
2273    //  -------------------------------------------------------------------------
2274        
2275        if( detlist.Contains("-TRG", TString::kIgnoreCase) )TRG = false;
2276        else if( detlist.Contains("+TRG", TString::kIgnoreCase) )TRG = true;
2277        
2278        if( detlist.Contains("-TOF", TString::kIgnoreCase) )TOF = false;
2279        else if( detlist.Contains("+TOF", TString::kIgnoreCase) )TOF = true;
2280    
2281        if( detlist.Contains("-TOF0", TString::kIgnoreCase) )TOF0 = false;
2282        else if( detlist.Contains("+TOF0", TString::kIgnoreCase) )TOF0 = true;
2283        
2284        if( detlist.Contains("-S4",  TString::kIgnoreCase) )S4  = false;
2285        else if( detlist.Contains("+S4",  TString::kIgnoreCase) )S4  = true;
2286        
2287        if( detlist.Contains("-ND",  TString::kIgnoreCase) )ND  = false;
2288        else if( detlist.Contains("+ND",  TString::kIgnoreCase) )ND  = true;
2289        
2290        if( detlist.Contains("-AC",  TString::kIgnoreCase) )AC  = false;
2291        else if( detlist.Contains("+AC",  TString::kIgnoreCase) )AC  = true;
2292        
2293        if( detlist.Contains("-ORB", TString::kIgnoreCase) )ORB = false;
2294        else if( detlist.Contains("+ORB", TString::kIgnoreCase) )ORB = true;
2295    
2296    //     cout<< "Set detector list --> ";
2297    //     if(TRK1)cout<<"TRK1 ";
2298    //     if(TRK2)cout<<"TRK2 ";
2299    //     if(TRKh)cout<<"TRKH ";
2300    //     if(CAL1)cout<<"CAL1 ";
2301    //     if(CAL2)cout<<"CAL2 ";
2302    //     if(TOF)cout<<"TOF ";
2303    //     if(TRG)cout<<"TRG ";
2304    //     if(AC)cout<<"AC ";
2305    //     if(ND)cout<<"ND ";
2306    //     if(S4)cout<<"S4 ";
2307    //     if(ORB)cout<<"ORB ";
2308    //     cout << endl;
2309        
2310    };
2311    
2312    
2313    /**
2314     * Set tree/branch detector flags from the content of a tree
2315     */
2316    void  PamLevel2::GetWhichTrees(TFile* f){
2317        
2318    
2319    
2320        cout << "void  PamLevel2::GetWhichTrees(TFile* f) --- WARNING!! --- ...potrebbe non funzionare "<<endl;
2321        // -----------
2322        // reset flags
2323        // -----------
2324        CAL1   = false;    
2325        CAL2   = false;    
2326        TRK2   = false;    
2327        TRK1   = false;    
2328        TRKh   = false;    
2329        TRG    = false;    
2330        TOF    = false;    
2331        S4     = false;    
2332        ND     = false;    
2333        AC     = false;    
2334        ORB    = false;    
2335        
2336        RUN    = false;
2337            
2338        cout << "Checking file: "<<f->GetName()<<endl;
2339        if( !f || f->IsZombie() ){
2340            cout << "File: "<< f->GetName() <<" Non valid root file"<< endl;
2341            return;
2342        }
2343    
2344        TList *lk = f->GetListOfKeys();
2345        TIter next(lk);
2346        TKey *key =0;
2347    
2348        Int_t nev = 0;
2349    
2350        while( (key = (TKey*)next()) ){
2351            
2352            if( !strcmp(key->GetName(),"Run"        ) )RUN = true;
2353    
2354            //=========================================================    
2355            if( !strcmp(key->GetName(),"Trigger"    ) ){
2356                TRG = true;
2357                Int_t nevt = ((TTree*)f->Get("Trigger"))->GetEntries();
2358                if( nev && nevt!=nev){
2359                    cout << "File: "<< f->GetName() <<" Trigger tree has "<<nevt<<" events instead of "<<nev<< endl;
2360                    TRG = false;
2361                }else nev=nevt;
2362            }
2363            //=========================================================    
2364            if( !strcmp(key->GetName(),"ToF"        ) ){
2365                TOF = true;
2366                Int_t nevt = ((TTree*)f->Get("ToF"))->GetEntries();
2367                if( nev && nevt!=nev){
2368                    cout << "File: "<< f->GetName() <<"     ToF tree has "<<nevt<<" events instead of "<<nev<< endl;
2369                    TOF = false;
2370                }else nev=nevt;
2371            }
2372            //=========================================================  
2373            if( !strcmp(key->GetName(),"S4"         ) ){
2374                S4 = true;
2375                Int_t nevt = ((TTree*)f->Get("S4"))->GetEntries();
2376                if( nev && nevt!=nev){
2377                    cout << "File: "<< f->GetName() <<"      S4 tree has "<<nevt<<" events instead of "<<nev<< endl;
2378                    S4 = false;
2379                }else nev=nevt;
2380            }
2381            //=========================================================  
2382    
2383            if( !strcmp(key->GetName(),"NeutronD"   ) ){
2384                ND = true;
2385                Int_t nevt = ((TTree*)f->Get("NeutronD"))->GetEntries();
2386                if( nev && nevt!=nev){
2387                    cout << "File: "<< f->GetName() <<"NeutronD tree has "<<nevt<<" events instead of "<<nev<< endl;
2388                    ND =false;
2389                }else nev=nevt;
2390            }      
2391            //=========================================================  
2392            if( !strcmp(key->GetName(),"Anticounter") ){
2393                AC = true;
2394                Int_t nevt = ((TTree*)f->Get("Anticounter"))->GetEntries();
2395                if( nev && nevt!=nev){
2396                    cout << "File: "<< f->GetName() <<" Anticounter tree has "<<nevt<<" events instead of "<<nev<< endl;
2397                    AC =false;
2398                }else nev=nevt;
2399            }
2400            //=========================================================  
2401            if( !strcmp(key->GetName(),"OrbitalInfo") ){
2402                ORB = true;
2403                Int_t nevt = ((TTree*)f->Get("OrbitalInfo"))->GetEntries();
2404                if( nev && nevt!=nev){
2405                    cout << "File: "<< f->GetName() <<" OrbitalInfo tree has "<<nevt<<" events instead of "<<nev<< endl;
2406                    ORB = false;
2407                }else nev=nevt;
2408            }
2409            //=========================================================  
2410            if( !strcmp(key->GetName(),"Tracker"    ) ){
2411                TTree *T = (TTree*)f->Get("Tracker");
2412                for(Int_t i=0; i<T->GetListOfBranches()->GetEntries(); i++){
2413                    TString name = T->GetListOfBranches()->At(i)->GetName();
2414                    if( !name.CompareTo("TrkLevel1") )TRK1=true;
2415                    if( !name.CompareTo("TrkLevel2") )TRK2=true;
2416                    if( !name.CompareTo("TrkHough") )TRKh=true;
2417                };      
2418                Int_t nevt = T->GetEntries();
2419                if( nev && nevt!=nev){
2420                    cout << "File: "<< f->GetName() <<" Tracker tree has "<<nevt<<" events instead of "<<nev<< endl;
2421                    TRK1 = false;
2422                    TRK2 = false;
2423                    TRKh = false;
2424                }else nev=nevt;
2425                T->Delete();
2426            };
2427            //=========================================================  
2428            if( !strcmp(key->GetName(),"Calorimeter"    ) ){
2429                TTree *T = (TTree*)f->Get("Calorimeter");
2430                for(Int_t i=0; i<T->GetListOfBranches()->GetEntries(); i++){
2431                    TString name = T->GetListOfBranches()->At(i)->GetName();
2432                    if( !name.CompareTo("CaloLevel1") )CAL1=true;
2433                    if( !name.CompareTo("CaloLevel2") )CAL2=true;
2434                };    
2435                Int_t nevt = T->GetEntries();
2436                if( nev && nevt!=nev){
2437                    cout << "File: "<< f->GetName() <<"  Calorimeter tree has "<<nevt<<" events instead of "<<nev<< endl;
2438                    CAL1 = false;
2439                    CAL2 = false;
2440                }else nev=nevt;
2441                T->Delete();
2442            };      
2443    
2444        };
2445        
2446        delete lk;
2447    
2448    //     cout<< "Get detector list from input file --> ";
2449    //     if(TRK1)cout<<"TRK1 ";
2450    //     if(TRK2)cout<<"TRK2 ";
2451    //     if(TRKh)cout<<"TRKH ";
2452    //     if(CAL1)cout<<"CAL1 ";
2453    //     if(CAL2)cout<<"CAL2 ";
2454    //     if(TOF)cout<<"TOF ";
2455    //     if(TRG)cout<<"TRG ";
2456    //     if(AC)cout<<"AC ";
2457    //     if(ND)cout<<"ND ";
2458    //     if(S4)cout<<"S4 ";
2459    //     if(ORB)cout<<"ORB ";
2460    //     cout << endl;
2461          
2462        return ;
2463            
2464    };
2465    
2466    
2467    //--------------------------------------
2468    //
2469    //
2470    //--------------------------------------
2471    /**
2472     * Check if a file contains selected Pamela Level2 trees.
2473     * @param name File name
2474     * @return true if the file is ok.
2475     */
2476    Bool_t  PamLevel2::CheckLevel2File(TString name){
2477            
2478        Bool_t CAL1__ok   = false;    
2479        Bool_t CAL2__ok   = false;    
2480        Bool_t TRK2__ok   = false;    
2481        Bool_t TRK1__ok   = false;    
2482        Bool_t TRKh__ok   = false;    
2483        Bool_t TRG__ok    = false;    
2484        Bool_t TOF__ok    = false;    
2485        Bool_t S4__ok     = false;    
2486        Bool_t ND__ok     = false;    
2487        Bool_t AC__ok     = false;    
2488        Bool_t ORB__ok    = false;    
2489        
2490        Bool_t RUN__ok    = false;
2491        
2492        Bool_t SELLI__ok  = false;
2493    
2494        cout << "Checking file: "<<name<<endl;
2495        TFile *f = new TFile(name.Data());
2496        if( !f || f->IsZombie() ){
2497            cout << "File: "<< f->GetName() <<" discarded ---- Non valid root file"<< endl; return false;
2498        }
2499    //    cout << "Get list of keys: "<<f<<endl;
2500        TList *lk = f->GetListOfKeys();
2501    //    lk->Print();
2502        TIter next(lk);
2503        TKey *key =0;
2504    
2505        Int_t nev = 0;
2506    
2507        while( (key = (TKey*)next()) ){
2508            
2509    //      cout << key->GetName() << endl;
2510    //      cout << key->GetName() << ""<<key->GetClassName()<<endl;
2511    //              cout << " Get tree: " << f->Get(key->GetName())<<endl;
2512    //      nev_previous = nev;
2513    //      cout << " n.entries  "<< nev <<endl;
2514    //      if( key->GetClassName()=="TTree" && nev_previous && nev != nev_previous ){
2515    //          nev = ((TTree*)f->Get(key->GetName()))->GetEntries();
2516    //          cout << "File: "<< f->GetName() <<" discarded ---- "<< key->GetName() << " tree: n.entries does not match "<<nev<<" "<<nev_previous<< endl;
2517    //          return false;
2518    //      };
2519    
2520    
2521            if( !strcmp(key->GetName(),"Run"        ) )RUN__ok = true;      
2522    
2523            //=========================================================    
2524            if( !strcmp(key->GetName(),"SelectionList"    ) ){
2525                SELLI__ok = true;
2526                if(SELLI==1){
2527                    Int_t nevt = ((TTree*)f->Get("SelectionList"))->GetEntries();
2528                    if( nev && nevt!=nev){
2529                        cout << "File: "<< f->GetName() <<" discarded ---- SelectionList tree has "<<nevt<<" events instead of "<<nev<< endl;
2530                        return false;
2531                    }
2532                    nev=nevt;
2533                }
2534            }
2535    
2536            //=========================================================    
2537            if( !strcmp(key->GetName(),"Trigger"    ) ){
2538                TRG__ok = true;
2539                if(TRG){
2540                    Int_t nevt = ((TTree*)f->Get("Trigger"))->GetEntries();
2541                    if( nev && nevt!=nev){
2542                        cout << "File: "<< f->GetName() <<" discarded ---- Trigger tree has "<<nevt<<" events instead of "<<nev<< endl;
2543                        return false;
2544                    }
2545                    nev=nevt;
2546                }
2547            }
2548            //=========================================================    
2549            if( !strcmp(key->GetName(),"ToF"        ) ){
2550                TOF__ok = true;
2551                if(TOF){
2552                    Int_t nevt = ((TTree*)f->Get("ToF"))->GetEntries();
2553                    if( nev && nevt!=nev){
2554                        cout << "File: "<< f->GetName() <<" discarded ---- ToF tree has "<<nevt<<" events instead of "<<nev<< endl;
2555                        return false;
2556                    }
2557                    nev=nevt;
2558                }
2559            }
2560            //=========================================================  
2561            if( !strcmp(key->GetName(),"S4"         ) ){
2562                S4__ok = true;
2563                if(S4){
2564                    Int_t nevt = ((TTree*)f->Get("S4"))->GetEntries();
2565                    if( nev && nevt!=nev){
2566                        cout << "File: "<< f->GetName() <<" discarded ---- S4 tree has "<<nevt<<" events instead of "<<nev<< endl;
2567                        return false;
2568                    }
2569                    nev=nevt;
2570                }
2571            }
2572            //=========================================================  
2573    
2574            if( !strcmp(key->GetName(),"NeutronD"   ) ){
2575                ND__ok = true;
2576                if(ND){
2577                    Int_t nevt = ((TTree*)f->Get("NeutronD"))->GetEntries();
2578                    if( nev && nevt!=nev){
2579                        cout << "File: "<< f->GetName() <<" discarded ---- NeutronD tree has "<<nevt<<" events instead of "<<nev<< endl;
2580                        return false;
2581                    }
2582                    nev=nevt;
2583                }
2584            }      
2585            //=========================================================  
2586            if( !strcmp(key->GetName(),"Anticounter") ){
2587                AC__ok = true;
2588                if(AC){
2589                    Int_t nevt = ((TTree*)f->Get("Anticounter"))->GetEntries();
2590                    if( nev && nevt!=nev){
2591                        cout << "File: "<< f->GetName() <<" discarded ---- Anticounter tree has "<<nevt<<" events instead of "<<nev<< endl;
2592                        return false;
2593                    }
2594                    nev=nevt;
2595                }
2596            }
2597            //=========================================================  
2598            if( !strcmp(key->GetName(),"OrbitalInfo") ){
2599                ORB__ok = true;
2600                if(ORB){
2601                    Int_t nevt = ((TTree*)f->Get("OrbitalInfo"))->GetEntries();
2602                    if( nev && nevt!=nev){
2603                        cout << "File: "<< f->GetName() <<" discarded ---- OrbitalInfo tree has "<<nevt<<" events instead of "<<nev<< endl;
2604                        return false;
2605                    }
2606                    nev=nevt;
2607                }
2608            }
2609            //=========================================================  
2610            if( !strcmp(key->GetName(),"Tracker"    ) ){
2611                TTree *T = (TTree*)f->Get("Tracker");
2612                if(TRK1||TRK2||TRKh){
2613                    Int_t nevt = T->GetEntries();
2614                    if( nev && nevt!=nev){
2615                        cout << "File: "<< f->GetName() <<" discarded ---- Tracker tree has "<<nevt<<" events instead of "<<nev<< endl;
2616                        return false;
2617                    }
2618                    nev=nevt;
2619                }
2620                for(Int_t i=0; i<T->GetListOfBranches()->GetEntries(); i++){
2621                    TString name = T->GetListOfBranches()->At(i)->GetName();
2622                    if( !name.CompareTo("TrkLevel1") )TRK1__ok=true;
2623                    if( !name.CompareTo("TrkLevel2") )TRK2__ok=true;
2624                    if( !name.CompareTo("TrkHough") )TRKh__ok=true;
2625                };      
2626                T->Delete();
2627            };
2628            //=========================================================  
2629            if( !strcmp(key->GetName(),"Calorimeter"    ) ){
2630                TTree *T = (TTree*)f->Get("Calorimeter");
2631                if(CAL1||CAL2){
2632                    Int_t nevt = T->GetEntries();
2633                    if( nev && nevt!=nev){
2634                        cout << "File: "<< f->GetName() <<" discarded ---- Calorimeter tree has "<<nevt<<" events instead of "<<nev<< endl;
2635                        return false;
2636                    }
2637                    nev=nevt;
2638                }
2639                for(Int_t i=0; i<T->GetListOfBranches()->GetEntries(); i++){
2640                    TString name = T->GetListOfBranches()->At(i)->GetName();
2641                    if( !name.CompareTo("CaloLevel1") )CAL1__ok=true;
2642                    if( !name.CompareTo("CaloLevel2") )CAL2__ok=true;
2643                };    
2644                T->Delete();
2645            };      
2646    
2647        };
2648    
2649        if( SELLI==-1 )SELLI = (Int_t)SELLI__ok;
2650        if( SELLI==0 && SELLI__ok ){
2651            cout << "File: "<< f->GetName() <<" discarded ---- found SelectionList (it is not a full-event file)" << endl;
2652            return false;  
2653        }
2654        if( SELLI==1 && !SELLI__ok ){
2655            cout << "File: "<< f->GetName() <<" discarded ---- SelectionList missing" << endl;
2656            return false;
2657        }
2658        
2659    //    cout << "SELLI "<<SELLI<<endl;
2660    
2661    //     cout<< "CheckLevel2File(TString): detector list --> ";
2662    //     if(TRK1__ok)cout<<"TRK1 ";
2663    //     if(TRK2__ok)cout<<"TRK2 ";
2664    //     if(TRKh__ok)cout<<"TRKH ";
2665    //     if(CAL1__ok)cout<<"CAL1 ";
2666    //     if(CAL2__ok)cout<<"CAL2 ";
2667    //     if(TOF__ok)cout<<"TOF ";
2668    //     if(TRG__ok)cout<<"TRG ";
2669    //     if(AC__ok)cout<<"AC ";
2670    //     if(ND__ok)cout<<"ND ";
2671    //     if(S4__ok)cout<<"S4 ";
2672    //     if(ORB__ok)cout<<"ORB ";
2673    //     cout << endl;
2674    
2675    
2676        if(TRK2 && TRK1__ok)TRK1=1;
2677    // ----------------------------------------------------------------------------
2678    // NOTA
2679    // se c'e` il level1, lo devo necessarimente leggere.
2680    // infatti (non ho capito perche`) i cluster vengono letti e allocati in memoria
2681    // comunque, ma non vengono disallocati da PamLevel2::Clear()
2682    // ----------------------------------------------------------------------------
2683    
2684    
2685        if(!RUN__ok) {
2686            cout << "File: "<< f->GetName() <<" *WARNING* ---- Missing RunInfo tree"<< endl;
2687    //      return false;
2688        };
2689    
2690        if(CAL1 && !CAL1__ok){
2691            cout << "File: "<< f->GetName() <<" discarded ---- Missing CaloLevel1 branch"<< endl;
2692            return false;
2693        };
2694        if(CAL2 && !CAL2__ok){
2695            cout << "File: "<< f->GetName() <<" discarded ---- Missing CaloLevel2 branch"<< endl;
2696            return false;
2697        };
2698        if(TRK2 && !TRK2__ok){
2699            cout << "File: "<< f->GetName() <<" discarded ---- Missing TrkLevel2 branch"<< endl;
2700            return false;
2701        };
2702        if(TRK1 && !TRK1__ok){
2703            cout << "File: "<< f->GetName() <<" discarded ---- Missing TrkLevel1 branch"<< endl;
2704            return false;
2705        };
2706        if(TRKh && !TRKh__ok){
2707            cout << "File: "<< f->GetName() <<" discarded ---- Missing TrkHough branch"<< endl;
2708            return false;
2709        };
2710        if(ORB && !ORB__ok){
2711            cout << "File: "<< f->GetName() <<" discarded ---- Missing ORB tree"<< endl;
2712            return false;
2713        };
2714        if(AC && !AC__ok){
2715            cout << "File: "<< f->GetName() <<" discarded ---- Missing AC tree"<< endl;
2716            return false;
2717        };
2718        if(S4 && !S4__ok){
2719            cout << "File: "<< f->GetName() <<" discarded ---- Missing S4 tree"<< endl;
2720            return false;
2721        };
2722        if(TOF && !TOF__ok){
2723            cout << "File: "<< f->GetName() <<" discarded ---- Missing ToF tree"<< endl;
2724            return false;
2725        };
2726    
2727        if(ND && !ND__ok){
2728            cout << "File: "<< f->GetName() <<" discarded ---- Missing ND tree"<< endl;
2729            return false;
2730        };
2731        if(TRG && !TRG__ok){
2732            cout << "File: "<< f->GetName() <<" discarded ---- Missing Trigger tree"<< endl;
2733            return false;
2734        };
2735        
2736    
2737    //    lk->Delete();
2738    //    delete lk;
2739        f->Close();
2740    
2741    //     cout<< "CheckLevel2File(TString): detector list --> ";
2742    //     if(TRK1)cout<<"TRK1 ";
2743    //     if(TRK2)cout<<"TRK2 ";
2744    //     if(TRKh)cout<<"TRKH ";
2745    //     if(CAL1)cout<<"CAL1 ";
2746    //     if(CAL2)cout<<"CAL2 ";
2747    //     if(TOF)cout<<"TOF ";
2748    //     if(TRG)cout<<"TRG ";
2749    //     if(AC)cout<<"AC ";
2750    //     if(ND)cout<<"ND ";
2751    //     if(S4)cout<<"S4 ";
2752    //     if(ORB)cout<<"ORB ";
2753    //     cout << endl;
2754          
2755        return true;
2756            
2757    };
2758    
2759    
2760    /**
2761     * Create clone-trees
2762     */
2763    void PamLevel2::CreateCloneTrees0( TChain *fChain, TFile *ofile ){
2764    
2765        cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;
2766        cout << "Create clones of PAMELA trees "<<endl;
2767        
2768        Int_t i=0;
2769        pam_tree_clone[i] = fChain->GetTree()->CloneTree(0);
2770        TString name =  pam_tree_clone[i]->GetName();
2771        name.Append("_clone");
2772    //    pam_tree_clone[i]->SetName(name.Data());
2773        cout << pam_tree_clone[i]->GetName() <<endl;
2774        i++;
2775    
2776        TList *li = fChain->GetListOfFriends();
2777        TIter next(li);
2778        TFriendElement* T_friend=0;
2779        ofile->cd();
2780        while( (T_friend = (TFriendElement*)next()) ){
2781    //      cout<<T_friend->IsA()->GetName()<<" "<<T_friend->GetName()<<hex << T_friend->GetTree() << dec<<endl;
2782    //      cout<<T_friend->GetTree()->GetName()<< endl;
2783            pam_tree_clone[i] = T_friend->GetTree()->CloneTree(0);
2784            pam_tree_clone[i]->SetAutoSave(1000000);
2785            name =  pam_tree_clone[i]->GetName();
2786            name.Append("_clone");
2787    //      pam_tree_clone[i]->SetName(name.Data());
2788            cout << pam_tree_clone[i]->GetName() << endl;
2789            i++;
2790        }
2791        
2792        delete li;
2793    
2794        cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;
2795    
2796    }
2797    
2798    /**
2799     * Create clone-trees
2800     */
2801    void PamLevel2::CreateCloneTrees(TFile *ofile){
2802    
2803    
2804    //  if the pointer is null, create a default file
2805    
2806        if(!ofile){
2807            cout << "void PamLevel2::CreateCloneTrees(TFile*) -- WARNING -- Creating file: clone-tree.root "<<endl;
2808            ofile = new TFile("clone-tree.root","recreate");
2809        }
2810    
2811        ofile->cd();
2812    
2813        cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;
2814        cout << "Create new PAMELA trees "<<endl;
2815            
2816    
2817        run_tree_clone = new TTree("Run","PAMELA Level2 data from the GL_RUN table ");
2818        run_tree_clone->Branch("RunInfo","GL_RUN",GetPointerTo("RunInfo"));
2819        cout << "Run          : branch RunInfo"<<endl;
2820        run_tree_clone->Branch("SoftInfo","SoftInfo",GetPointerTo("SoftInfo"));
2821        cout << "Run          : branch SoftInfo"<<endl;
2822        // ------------------
2823        // replicate run tree
2824        // ------------------
2825        cout << "----------------------------------------------------"<<endl;
2826        cout << "irun\t | RUN\t NEVENTS\t absolute time"<<endl;
2827        for (Int_t i=0; i<run_tree->GetEntries(); i++){
2828            run_tree->GetEntry(i);
2829            cout << i<< "\t | "<<GetRunInfo()->ID<<"\t "<<GetRunInfo()->NEVENTS<< "\t "<<GetRunInfo()->RUNHEADER_TIME<<" <---> "<<GetRunInfo()->RUNTRAILER_TIME<<endl;
2830            run_tree_clone->Fill();
2831        }
2832        cout << "----------------------------------------------------"<<endl;
2833    
2834    
2835        sel_tree_clone = new TTree("SelectionList","List of selected events ");
2836        sel_tree_clone->Branch("RunEntry",&irun,"runentry/L");
2837        sel_tree_clone->Branch("EventEntry",&irunentry,"eventry/L");
2838        
2839    
2840        Int_t i=0;
2841        if(TRK1||TRK2||TRKh){
2842            pam_tree_clone[i] = new TTree("Tracker","PAMELA tracker level2 data ");
2843            if(TRK1) {
2844                pam_tree_clone[i]->Branch("TrkLevel1","TrkLevel1", GetPointerTo("TrkLevel1"));
2845                pam_tree_clone[i]->BranchRef();
2846                cout << "Tracker      : branch TrkLevel1"<<endl;
2847    //          cout << "CreateCloneTrees " << GetTrkLevel1()<<endl;
2848            };
2849            if(TRK2) {
2850                pam_tree_clone[i]->Branch("TrkLevel2", "TrkLevel2",GetPointerTo("TrkLevel2"));
2851                cout << "Tracker      : branch TrkLevel2"<<endl;        
2852            };
2853            if(TRKh) {
2854                pam_tree_clone[i]->Branch("TrkHough","TrkHough", GetPointerTo("TrkHough"));
2855                cout << "Tracker      : branch TrkHough"<<endl;
2856            };
2857            i++;
2858        }
2859    
2860        // Calorimeter
2861        if(CAL1||CAL2){
2862            pam_tree_clone[i] = new TTree("Calorimeter","PAMELA calorimeter level2 data ");
2863            if(CAL1) {
2864                pam_tree_clone[i]->Branch("CaloLevel1", "CaloLevel1", GetPointerTo("CaloLevel1"));
2865                cout << "Calorimeter  : branch CaloLevel1"<<endl;
2866            };
2867            if(CAL2) {
2868                pam_tree_clone[i]->Branch("CaloLevel2","CaloLevel2", GetPointerTo("CaloLevel2"));
2869                cout << "Calorimeter  : branch CaloLevel2"<<endl;
2870            };
2871            i++;
2872        }    
2873    
2874        // ToF    
2875        if(TOF) {
2876            pam_tree_clone[i] = new TTree("ToF","PAMELA ToF level2 data ");
2877            pam_tree_clone[i]->Branch("ToFLevel2","ToFLevel2", GetPointerTo("ToFLevel2"));
2878            cout << "ToF          : branch ToFLevel2"<<endl;
2879            i++;
2880        };
2881        // Trigger
2882        if(TRG) {
2883            pam_tree_clone[i] = new TTree("Trigger","PAMELA trigger level2 data ");
2884            pam_tree_clone[i]->Branch("TrigLevel2","TrigLevel2", GetPointerTo("TrigLevel2"));
2885            cout << "Trigger      : branch TrigLevel2"<<endl;
2886            i++;
2887        };
2888        // S4
2889        if(S4) {
2890            pam_tree_clone[i] = new TTree("S4","PAMELA S4 level2 data ");  
2891            pam_tree_clone[i]->Branch("S4Level2","S4Level2", GetPointerTo("S4Level2"));
2892            cout << "S4           : branch S4Level2"<<endl;
2893            i++;
2894        };
2895        // Neutron Detector
2896        if(ND) {
2897            pam_tree_clone[i] = new TTree("NeutronD","PAMELA neutron detector level2 data ");      
2898            pam_tree_clone[i]->Branch("NDLevel2","NDLevel2", GetPointerTo("NDLevel2"));
2899            cout << "NeutronD     : branch NDLevel2"<<endl;
2900            i++;
2901        };
2902        // Anticounters
2903        if(AC) {
2904            pam_tree_clone[i] = new TTree("Anticounter","PAMELA anticounter detector level2 data ");        
2905            pam_tree_clone[i]->Branch("AcLevel2","AcLevel2", GetPointerTo("AcLevel2"));
2906            cout << "Anticounter  : branch AcLevel2"<<endl;
2907            i++;
2908        };
2909        // OrbitalInfo
2910        if(ORB) {
2911            pam_tree_clone[i] = new TTree("OrbitalInfo","PAMELA oribital info  ");  
2912            pam_tree_clone[i]->Branch("OrbitalInfo","OrbitalInfo", GetPointerTo("OrbitalInfo"));
2913            cout << "OrbitalInfo  : branch OrbitalInfo"<<endl;
2914            i++;
2915        };
2916        cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;
2917    
2918    }
2919    
2920    
2921    /**
2922     * Fill tree (created with CreateCloneTrees)
2923     *
2924     */
2925    //void PamLevel2::FillNewPamTree(TTree *T){
2926    void PamLevel2::FillCloneTrees(){
2927        
2928    //    cout << "PamLevel2::FillCloneTrees()" << irunentry << endl;
2929    
2930        for(Int_t i=0; i<NCLONES; i++){
2931            if(pam_tree_clone[i])pam_tree_clone[i]->Fill();
2932        }
2933        if(sel_tree_clone)sel_tree_clone->Fill();    
2934    
2935    }
2936    
2937    
2938    TTree* PamLevel2::GetCloneTree(TString name){
2939    
2940        for(Int_t i=0; i<NCLONES; i++){    
2941            if(pam_tree_clone[i]){
2942                TString na = pam_tree_clone[i]->GetName();
2943                if(!name.CompareTo(na))return pam_tree_clone[i];
2944            };
2945        }
2946        if(run_tree_clone){
2947            TString na = run_tree_clone->GetName();
2948            if(!name.CompareTo(na))return run_tree_clone;
2949        }
2950        if(sel_tree_clone){
2951            TString na = sel_tree_clone->GetName();
2952            if(!name.CompareTo(na))return sel_tree_clone;
2953        }
2954        return NULL;
2955    
2956    }
2957    void PamLevel2::WriteCloneTrees(){
2958        cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;
2959        cout << "Write clones of PAMELA trees "<<endl;
2960        cout << run_tree_clone->GetName()<<endl;    
2961        run_tree_clone->Write();
2962        cout << sel_tree_clone->GetName()<<endl;    
2963        sel_tree_clone->Write();
2964        for(Int_t i=0; i<NCLONES; i++){    
2965            if(pam_tree_clone[i]){
2966                cout << pam_tree_clone[i]->GetName()<<endl;
2967                pam_tree_clone[i]->Write();
2968            };
2969        }
2970        cout << "+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+" <<endl;
2971    
2972    }
2973    
2974    /**
2975     * Method to get level2-trees entry, the corresponding run entry and (if required) the level0 entry.
2976     */
2977    //Int_t PamLevel2::GetEntry(Int_t iee){
2978    Int_t PamLevel2::GetEntry(Long64_t iee){
2979        
2980    //     cout << "-------------------------------------"<<endl;
2981    //     cout << "Int_t PamLevel2::GetEntry("<<iee<<")"<<endl;
2982    
2983        if(!pam_tree){
2984            cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- level2 trees not loaded"<<endl;
2985            return 0;
2986        }
2987    
2988    
2989        //
2990        // 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...
2991        //
2992        //    if(!run_tree ){
2993        //  cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- run tree not loeaded"<<endl;
2994        //  return 0;
2995        //    }
2996    
2997        Long64_t ii=0;
2998        //-------------------------------
2999        ii = iee;
3000        if( !pam_tree->GetEntry(ii) ){      
3001            cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- error reading pam tree"<<endl;
3002            return 0;
3003        }
3004        //
3005        // ... 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.
3006        // 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
3007        // a problem if you don't check the return code of getentry.
3008        //
3009        if(!run_tree ){
3010            if ( TRK0 || CAL0 || TOF0 || RUN ) { //forse cosi` va bene per tornare 1?
3011                cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- run tree not loaded"<<endl;
3012                return 0;
3013            }  else {
3014                return 1; //cosi` se non c'e` run esce qua...
3015            }
3016        }
3017    
3018        //-------------------------------
3019        ii = iee;
3020    //    Bool_t UPDATED = UpdateRunInfo(run_tree,ii);
3021    //    Bool_t UPDATED = UpdateRunInfo(ii);
3022        UpdateRunInfo(ii);
3023        if(SELLI==0)irunentry = iee-runfirstentry;
3024    //    if(UPDATED && run_tree_clone)run_tree_clone->Fill();
3025      
3026    //    cout << "PamLevel2::GetEntry("<<iee<<") "<<irun<<" "<<runfirstentry<<" "<<irunentry<<endl;
3027    
3028    //     cout << "irunentry     "<<irunentry << endl;
3029    //     cout << "runfirstentry "<<runfirstentry << endl;
3030    //     cout << "nevents       "<<GetRunInfo()->NEVENTS<< endl;
3031    
3032    //     if( TRK0 || CAL0 || TOF0 ){
3033    //      if( !GetYodaEntry( ) ){
3034    //          cout << " Int_t PamLevel2::GetEntry(Int_t) -- ERROR -- error reading level0 tree"<<endl;
3035    //          return 0;
3036    //      }
3037    //     }
3038    
3039    
3040        return 1;
3041    
3042    }
3043    
3044    TrkLevel0    *PamLevel2::GetTrkLevel0(){
3045        if( !TRK0 )return NULL;
3046        if( !GetYodaEntry( ) ){
3047            cout << " Int_t PamLevel2::GetTrkLevel0() -- ERROR -- error reading level0 tree"<<endl;
3048            return 0;
3049        }
3050        return trk0_obj;
3051    };
3052    CaloLevel0    *PamLevel2::GetCaloLevel0(){
3053        if( !CAL0 )return NULL;
3054        if( !GetYodaEntry( ) ){
3055            cout << " Int_t PamLevel2::GetCaloLevel0() -- ERROR -- error reading level0 tree"<<endl;
3056            return 0;
3057        }
3058        return calo0_obj;
3059    };
3060    
3061    
3062    /**
3063     * Method to retrieve the level0 tree (YODA tree) that contains the current event.
3064     * Given the run ID (...), if needed it query the DB and load the proper file.
3065     * @return Pointer to the tree
3066     */
3067    
3068    
3069    TTree* PamLevel2::GetYodaTree( ){
3070        
3071    //    cout << "TTree* PamLevel2::GetYodaTree( )"<<endl;
3072        //===================================
3073        // check if iroot has changed
3074        //===================================
3075        if( irun<0 ){
3076            cout << "PamLevel2::GetYodaTree() -- ERROR -- irun = "<<irun<<endl;
3077    //      cout << "In order to use this method you have to first load the RunInfo tree "<<endl;
3078            return NULL;
3079        }    
3080        Int_t irootnew = run_obj->ID_ROOT_L0;
3081    //      cout << "iroot    "<<iroot<<endl;
3082    //      cout << "irootnew "<<irootnew<<endl;
3083    
3084        //===================================
3085        // load the level0 file
3086        // (if not already loaded)
3087        //===================================
3088        if( iroot != irootnew || !l0_tree){
3089            iroot = irootnew;
3090            //===================================
3091            // open the DB connection
3092            // (if not already opened)
3093            //===================================
3094            if(!dbc || (dbc && !dbc->IsConnected())){
3095                cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
3096                cout<<"Connecting to DB"<<endl;
3097                cout<<"HOST "<<host<<endl;
3098                cout<<"USER "<<user<<endl;
3099                cout<<"PSW  "<<psw<<endl;
3100                dbc = TSQLServer::Connect(host.Data(),user.Data(),psw.Data());
3101                if( !dbc )return NULL;
3102                if( !dbc->IsConnected() )return NULL;    
3103    //          cout<<"...done"<<endl;
3104                cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
3105            }else{
3106    //          cout<<"DB already connected"<<endl;
3107            }
3108            GL_ROOT glroot = GL_ROOT();
3109            if( glroot.Query_GL_ROOT(iroot,dbc) ){
3110                cout << "TTree* PamLevel2::GetYodaTree( ) -- ERROR -- level0 file iroot = "<<iroot<< " does not exists"<<endl;
3111                return NULL;
3112            };
3113            TString filename = glroot.PATH + glroot.NAME;
3114            if(l0_file){
3115                l0_file->Close();
3116                l0_file->Delete();
3117            }
3118            cout << "Opening LEVEL0 file: "<< filename << endl;
3119            FileStat_t t;
3120            if( gSystem->GetPathInfo(filename.Data(),t) ){
3121                cout << " PamLevel2::GetYodaTree() -- ERROR opening file "<<endl;
3122                return NULL;
3123            }
3124            l0_file = new TFile(filename);
3125            if( !l0_file )return NULL;
3126            l0_tree = (TTree*)l0_file->Get("Physics");
3127            if(!h0_obj)h0_obj = new EventHeader();
3128            l0_tree->SetBranchAddress("Header" ,&h0_obj);
3129            prevshift = 0;
3130            //---------------------------------------------------
3131            // TRACKER:
3132            if(TRK0){
3133                if(!trk0_obj){
3134                    trk0_obj = new TrkLevel0();
3135                    trk0_obj->Set();
3136                };
3137                l0_tree->SetBranchAddress("Tracker" ,trk0_obj->GetPointerToTrackerEvent());
3138            }
3139            //--------------------------------------------------
3140            // CALORIMETER:
3141            if(CAL0){
3142                if(!calo0_obj){
3143                    calo0_obj = new CaloLevel0();
3144                    calo0_obj->Set();
3145                };
3146                l0_tree->SetBranchAddress("Calorimeter" ,calo0_obj->GetPointerToCalorimeterEvent());
3147                //      cout << "PamLevel2::GetYodaTree() --- level0 calorimeter not implemented "<<endl;
3148            }
3149            //---------------------------------------------------
3150            // TOF:
3151            if(TOF0){
3152                cout << "PamLevel2::GetYodaTree() --- level0 TOF not implemented "<<endl;
3153            }
3154    
3155        };
3156    
3157        if(!dbc || (dbc && !dbc->IsConnected())){
3158            cout << " TTree* PamLevel2::GetYodaTree( ) -- no DB connected... hai fatto qualche cazzata "<<endl;
3159        }
3160    
3161        if ( TRK0 ){
3162            TrkParams::Load(6);
3163            if( !TrkParams::IsLoaded(6) ){
3164                cout << " TTree* PamLevel2::GetYodaTree( ) -- WARNING -- VK-mask not loaded"<<endl;
3165            };
3166            TrkParams::SetCalib(run_obj,dbc);
3167            TrkParams::LoadCalib( );
3168            if( !TrkParams::CalibIsLoaded() ){
3169                cout << " TTree* PamLevel2::GetYodaTree( ) -- WARNING -- Calibration not loaded"<<endl;
3170            };
3171        }
3172    
3173    //    cout << l0_tree << endl;
3174        
3175        return l0_tree;
3176    
3177    }
3178    
3179    /**
3180     * Method to retrieve the level0 tree (YODA tree) that contains the current event.
3181     */
3182    Int_t PamLevel2::GetYodaEntry(){
3183    
3184    //    cout << "Int_t PamLevel2::GetYodaEntry()"<<endl;
3185        if(!GetYodaTree())return 0;
3186        
3187        // patch
3188        if( irunentry < 0){
3189    //      cout << "Int_t PamLevel2::GetYodaEntry() -- ATTENZIONE -- irunentry negativo?!?! "<<(Int_t)irunentry<<endl;
3190            irunentry=0LL;
3191        }
3192        //  ---------------------------------
3193        //  if file is NOT a preselected file
3194        //  ---------------------------------
3195        Long64_t quellagiusta = irunentry + (Long64_t)(run_obj->EV_FROM);
3196    //     cout << " irunentry "<<irunentry<<endl;
3197    //     cout << " EV_FROM "<<run_obj->EV_FROM<<endl;
3198    //     cout << " quellagiusta = irunentry + EV_FROM "<< quellagiusta << endl;
3199    
3200    //     cout << " irun "<< irun << " irunentry "<< irunentry<<" run_obj->EV_FROM "<<run_obj->EV_FROM <<" quella giusta "<<quellagiusta << endl;
3201    //     cout << " iroot "<<iroot<<" run_obj->ID_ROOT_L0 "<<run_obj->ID_ROOT_L0<<endl;
3202    //     cout << " time "<< abstime << endl;
3203    //     cout << " trk_calib_used "<<run_obj->TRK_CALIB_USED<< endl;
3204        
3205        ULong64_t obt     = 0;
3206        ULong64_t pktn    = 0;
3207        if( GetOrbitalInfo() ){
3208            obt     = GetOrbitalInfo()->OBT;
3209            pktn    = GetOrbitalInfo()->pkt_num;
3210        }
3211    
3212        if( !GetOrbitalInfo() && !ISGP){
3213            cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- missing OrbitalInfo "<<endl;
3214            return 0;
3215        }
3216        if( obt==0 && pktn==0 && !ISGP ){
3217            cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- level2 event corrupted ?? "<<endl;
3218            return 0;
3219        }
3220    
3221        // ---------------------------------------------------------------------
3222        // ATTENTION!!!
3223        // If data are not pre-processed with cleaner, the level0 tree may contain
3224        // spurious nested physics packets.
3225        // The GL_RUN variables EV_FROM, EV_TO and NEVENTS counts also these entries
3226        // while level2 tree DOES NOT!!
3227        // This means that "quellagiusta" in these cases is not correct.
3228        // In order to retrieve the correct level0 event, I implemented a check
3229        // of the OBT and pkt-number. In case of mismatch, the level0 entry number
3230        // is shift forward until when the packets match.
3231        // ---------------------------------------------------------------------
3232        Int_t answer = 0;
3233        Int_t shift =0;
3234        //    printf(" siamo qui %i %i \n",shift,prevshift);
3235        Int_t maxshift = 10;
3236        do{
3237            if(shift>0){    
3238                cout << " PKTNUM  L2 --- "<< pktn << " --- L0 --- "<< GetEventHeader()->GetPscuHeader()->GetCounter()<<endl;
3239                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;
3240                cout << "         L2 <--> L0 mismatch ( irun "<<irun<<" irunentry "<<irunentry<<" shift "<<shift<<" prevshift "<<prevshift<<" )"<<endl;
3241            }
3242            answer = l0_tree->GetEntry(quellagiusta+(Long64_t)shift+(Long64_t)prevshift);
3243            shift++;
3244            if( !GetEventHeader() ){
3245                cout << "Int_t PamLevel2::GetYodaEntry() -- ERROR -- missing EventHeader "<<endl;
3246                return 0;
3247            }
3248    
3249            if(ISGP){
3250                obt = (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()); //BARBATRUCCO
3251                pktn = (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter()); //BARBATRUCCO
3252            }
3253    
3254    //      cout << "PKTNUM "<<shift<<" ==  L2 --- "<< pktn << " --- L0 --- "<< GetEventHeader()->GetPscuHeader()->GetCounter()<<endl;
3255    //      cout << " L2 --- "<< obt << " --- L0 --- "<< GetEventHeader()->GetPscuHeader()->GetOrbitalTime()<<endl;
3256    //      if( (quellagiusta+shift) == l0_tree->GetEntries()+1 )cout << ">>> end of level0 tree <<<"<<endl;
3257    //      cout << " obt "<< obt << endl;
3258    //      cout << " GetEventHeader()->GetPscuHeader()->GetOrbitalTime() "<< GetEventHeader()->GetPscuHeader()->GetOrbitalTime() << endl;
3259    //      cout << " pktn "<< pktn << endl;
3260    //      cout << " GetEventHeader()->GetPscuHeader()->GetCounter() "<< GetEventHeader()->GetPscuHeader()->GetCounter() << endl;
3261    //      printf(" IDRUN %u \n",GetRunInfo()->ID);
3262    //
3263            if ( prevshift != 0 && (quellagiusta+(Long64_t)shift) == GetYodaTree()->GetEntries() ){
3264              prevshift = 0;
3265              shift = -1;
3266            };
3267    
3268        }while( ( obt != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetOrbitalTime()) ||
3269                  pktn != (UInt_t)(GetEventHeader()->GetPscuHeader()->GetCounter())       )
3270                && (quellagiusta+(Long64_t)shift) < GetYodaTree()->GetEntries() && shift < maxshift);
3271    
3272        if ( (quellagiusta+(Long64_t)shift+(Long64_t)prevshift) > GetYodaTree()->GetEntries() || shift == maxshift ) {
3273            cout << " Big trouble here, no such event in Level0 data! " <<endl;
3274            return 0;
3275        }
3276    //    cout << "LA ENTRY GIUSTA E`: "<<quellagiusta<<" (spero...)"<<endl;
3277    //    return GetYodaTree()->GetEntry(quellagiusta);
3278        if ( shift > 1 ) prevshift += (shift-1);
3279        
3280        return answer;
3281        
3282    }
3283    /**
3284     * \Brief Set DB connection
3285     */
3286    Bool_t PamLevel2::SetDBConnection(){
3287    
3288        cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
3289        cout<<"Connecting to DB"<<endl;
3290        cout<<"HOST "<<host<<endl;
3291        cout<<"USER "<<user<<endl;
3292        cout<<"PSW  "<<psw<<endl;
3293        dbc = TSQLServer::Connect(host.Data(),user.Data(),psw.Data());
3294        if( !dbc )return false;
3295        if( !dbc->IsConnected() )return false;    
3296        cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
3297        return true;
3298    
3299  }  }

Legend:
Removed from v.1.1  
changed lines
  Added in v.1.43

  ViewVC Help
Powered by ViewVC 1.1.23