]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/AliReconstruction.cxx
TPCNoiseMapComponent included into build (Kelly)
[u/mrichter/AliRoot.git] / STEER / AliReconstruction.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16 /* $Id$ */
17
18 ///////////////////////////////////////////////////////////////////////////////
19 //                                                                           //
20 // class for running the reconstruction                                      //
21 //                                                                           //
22 // Clusters and tracks are created for all detectors and all events by       //
23 // typing:                                                                   //
24 //                                                                           //
25 //   AliReconstruction rec;                                                  //
26 //   rec.Run();                                                              //
27 //                                                                           //
28 // The Run method returns kTRUE in case of successful execution.             //
29 //                                                                           //
30 // If the input to the reconstruction are not simulated digits but raw data, //
31 // this can be specified by an argument of the Run method or by the method   //
32 //                                                                           //
33 //   rec.SetInput("...");                                                    //
34 //                                                                           //
35 // The input formats and the corresponding argument are:                     //
36 // - DDL raw data files: directory name, ends with "/"                       //
37 // - raw data root file: root file name, extension ".root"                   //
38 // - raw data DATE file: DATE file name, any other non-empty string          //
39 // - MC root files     : empty string, default                               //
40 //                                                                           //
41 // By default all events are reconstructed. The reconstruction can be        //
42 // limited to a range of events by giving the index of the first and the     //
43 // last event as an argument to the Run method or by calling                 //
44 //                                                                           //
45 //   rec.SetEventRange(..., ...);                                            //
46 //                                                                           //
47 // The index -1 (default) can be used for the last event to indicate no      //
48 // upper limit of the event range.                                           //
49 //                                                                           //
50 // In case of raw-data reconstruction the user can modify the default        //
51 // number of events per digits/clusters/tracks file. In case the option      //
52 // is not used the number is set 1. In case the user provides 0, than        //
53 // the number of events is equal to the number of events inside the          //
54 // raw-data file (i.e. one digits/clusters/tracks file):                     //
55 //                                                                           //
56 //   rec.SetNumberOfEventsPerFile(...);                                      //
57 //                                                                           //
58 //                                                                           //
59 // The name of the galice file can be changed from the default               //
60 // "galice.root" by passing it as argument to the AliReconstruction          //
61 // constructor or by                                                         //
62 //                                                                           //
63 //   rec.SetGAliceFile("...");                                               //
64 //                                                                           //
65 // The local reconstruction can be switched on or off for individual         //
66 // detectors by                                                              //
67 //                                                                           //
68 //   rec.SetRunLocalReconstruction("...");                                   //
69 //                                                                           //
70 // The argument is a (case sensitive) string with the names of the           //
71 // detectors separated by a space. The special string "ALL" selects all      //
72 // available detectors. This is the default.                                 //
73 //                                                                           //
74 // The reconstruction of the primary vertex position can be switched off by  //
75 //                                                                           //
76 //   rec.SetRunVertexFinder(kFALSE);                                         //
77 //                                                                           //
78 // The tracking and the creation of ESD tracks can be switched on for        //
79 // selected detectors by                                                     //
80 //                                                                           //
81 //   rec.SetRunTracking("...");                                              //
82 //                                                                           //
83 // Uniform/nonuniform field tracking switches (default: uniform field)       //
84 //                                                                           //
85 //   rec.SetUniformFieldTracking(); ( rec.SetUniformFieldTracking(kFALSE); ) //
86 //                                                                           //
87 // The filling of additional ESD information can be steered by               //
88 //                                                                           //
89 //   rec.SetFillESD("...");                                                  //
90 //                                                                           //
91 // Again, for both methods the string specifies the list of detectors.       //
92 // The default is "ALL".                                                     //
93 //                                                                           //
94 // The call of the shortcut method                                           //
95 //                                                                           //
96 //   rec.SetRunReconstruction("...");                                        //
97 //                                                                           //
98 // is equivalent to calling SetRunLocalReconstruction, SetRunTracking and    //
99 // SetFillESD with the same detector selecting string as argument.           //
100 //                                                                           //
101 // The reconstruction requires digits or raw data as input. For the creation //
102 // of digits and raw data have a look at the class AliSimulation.            //
103 //                                                                           //
104 // The input data of a detector can be replaced by the corresponding HLT     //
105 // data by calling (usual detector string)                                   //
106 // SetUseHLTData("...");                                                     //
107 //                                                                           //
108 // For debug purposes the method SetCheckPointLevel can be used. If the      //
109 // argument is greater than 0, files with ESD events will be written after   //
110 // selected steps of the reconstruction for each event:                      //
111 //   level 1: after tracking and after filling of ESD (final)                //
112 //   level 2: in addition after each tracking step                           //
113 //   level 3: in addition after the filling of ESD for each detector         //
114 // If a final check point file exists for an event, this event will be       //
115 // skipped in the reconstruction. The tracking and the filling of ESD for    //
116 // a detector will be skipped as well, if the corresponding check point      //
117 // file exists. The ESD event will then be loaded from the file instead.     //
118 //                                                                           //
119 ///////////////////////////////////////////////////////////////////////////////
120
121 #include <TArrayF.h>
122 #include <TFile.h>
123 #include <TList.h>
124 #include <TSystem.h>
125 #include <TROOT.h>
126 #include <TPluginManager.h>
127 #include <TGeoManager.h>
128 #include <TLorentzVector.h>
129 #include <TArrayS.h>
130 #include <TArrayD.h>
131 #include <TObjArray.h>
132
133 #include "AliReconstruction.h"
134 #include "AliCodeTimer.h"
135 #include "AliReconstructor.h"
136 #include "AliLog.h"
137 #include "AliRunLoader.h"
138 #include "AliRun.h"
139 #include "AliRawReaderFile.h"
140 #include "AliRawReaderDate.h"
141 #include "AliRawReaderRoot.h"
142 #include "AliRawEventHeaderBase.h"
143 #include "AliESDEvent.h"
144 #include "AliESDMuonTrack.h"
145 #include "AliESDfriend.h"
146 #include "AliESDVertex.h"
147 #include "AliESDcascade.h"
148 #include "AliESDkink.h"
149 #include "AliESDtrack.h"
150 #include "AliESDCaloCluster.h"
151 #include "AliESDCaloCells.h"
152 #include "AliMultiplicity.h"
153 #include "AliTracker.h"
154 #include "AliVertexer.h"
155 #include "AliVertexerTracks.h"
156 #include "AliV0vertexer.h"
157 #include "AliCascadeVertexer.h"
158 #include "AliHeader.h"
159 #include "AliGenEventHeader.h"
160 #include "AliPID.h"
161 #include "AliESDpid.h"
162 #include "AliESDtrack.h"
163 #include "AliESDPmdTrack.h"
164
165 #include "AliESDTagCreator.h"
166 #include "AliAODTagCreator.h"
167
168 #include "AliGeomManager.h"
169 #include "AliTrackPointArray.h"
170 #include "AliCDBManager.h"
171 #include "AliCDBStorage.h"
172 #include "AliCDBEntry.h"
173 #include "AliAlignObj.h"
174
175 #include "AliCentralTrigger.h"
176 #include "AliTriggerConfiguration.h"
177 #include "AliTriggerClass.h"
178 #include "AliCTPRawStream.h"
179
180 #include "AliQADataMakerRec.h" 
181 #include "AliGlobalQADataMaker.h" 
182 #include "AliQA.h"
183 #include "AliQADataMakerSteer.h"
184
185 #include "AliPlaneEff.h"
186
187 #include "AliSysInfo.h" // memory snapshots
188 #include "AliRawHLTManager.h"
189
190
191 ClassImp(AliReconstruction)
192
193
194 //_____________________________________________________________________________
195 const char* AliReconstruction::fgkDetectorName[AliReconstruction::fgkNDetectors] = {"ITS", "TPC", "TRD", "TOF", "PHOS", "HMPID", "EMCAL", "MUON", "FMD", "ZDC", "PMD", "T0", "VZERO", "ACORDE", "HLT"};
196
197 //_____________________________________________________________________________
198 AliReconstruction::AliReconstruction(const char* gAliceFilename,
199                                      const char* name, const char* title) :
200   TNamed(name, title),
201
202   fUniformField(kTRUE),
203   fRunVertexFinder(kTRUE),
204   fRunVertexFinderTracks(kTRUE),
205   fRunHLTTracking(kFALSE),
206   fRunMuonTracking(kFALSE),
207   fRunV0Finder(kTRUE),
208   fRunCascadeFinder(kTRUE),
209   fStopOnError(kFALSE),
210   fWriteAlignmentData(kFALSE),
211   fWriteESDfriend(kFALSE),
212   fWriteAOD(kFALSE),
213   fFillTriggerESD(kTRUE),
214
215   fCleanESD(kTRUE),
216   fV0DCAmax(3.),
217   fV0CsPmin(0.),
218   fDmax(50.),
219   fZmax(50.),
220
221   fRunLocalReconstruction("ALL"),
222   fRunTracking("ALL"),
223   fFillESD("ALL"),
224   fUseTrackingErrorsForAlignment(""),
225   fGAliceFileName(gAliceFilename),
226   fInput(""),
227   fpEvent(NULL),
228   fEquipIdMap(""),
229   fFirstEvent(0),
230   fLastEvent(-1),
231   fNumberOfEventsPerFile(1),
232   fCheckPointLevel(0),
233   fOptions(),
234   fLoadAlignFromCDB(kTRUE),
235   fLoadAlignData("ALL"),
236   fESDPar(""),
237   fUseHLTData(),
238
239   fRunLoader(NULL),
240   fRawReader(NULL),
241   fParentRawReader(NULL),
242
243   fVertexer(NULL),
244   fDiamondProfile(NULL),
245   fDiamondProfileTPC(NULL),
246   fMeanVertexConstraint(kTRUE),
247
248   fGRPList(NULL),
249
250   fAlignObjArray(NULL),
251   fCDBUri(),
252   fSpecCDBUri(), 
253   fInitCDBCalled(kFALSE),
254   fSetRunNumberFromDataCalled(kFALSE),
255   fRunQA(kTRUE),  
256   fRunGlobalQA(kTRUE),
257   fInLoopQA(kFALSE),
258   fSameQACycle(kFALSE),
259
260   fRunPlaneEff(kFALSE),
261
262   fesd(NULL),
263   fhltesd(NULL),
264   fesdf(NULL),
265   ffile(NULL),
266   ftree(NULL),
267   fhlttree(NULL),
268   ffileOld(NULL),
269   ftreeOld(NULL),
270   fhlttreeOld(NULL),
271   ftVertexer(NULL),
272   fIsNewRunLoader(kFALSE)
273 {
274 // create reconstruction object with default parameters
275   
276   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
277     fReconstructor[iDet] = NULL;
278     fLoader[iDet] = NULL;
279     fTracker[iDet] = NULL;
280     fQADataMaker[iDet] = NULL;
281         fQACycles[iDet] = 999999;       
282   }
283   fQADataMaker[fgkNDetectors]=NULL;  //Global QA
284   AliPID pid;
285 }
286
287 //_____________________________________________________________________________
288 AliReconstruction::AliReconstruction(const AliReconstruction& rec) :
289   TNamed(rec),
290
291   fUniformField(rec.fUniformField),
292   fRunVertexFinder(rec.fRunVertexFinder),
293   fRunVertexFinderTracks(rec.fRunVertexFinderTracks),
294   fRunHLTTracking(rec.fRunHLTTracking),
295   fRunMuonTracking(rec.fRunMuonTracking),
296   fRunV0Finder(rec.fRunV0Finder),
297   fRunCascadeFinder(rec.fRunCascadeFinder),
298   fStopOnError(rec.fStopOnError),
299   fWriteAlignmentData(rec.fWriteAlignmentData),
300   fWriteESDfriend(rec.fWriteESDfriend),
301   fWriteAOD(rec.fWriteAOD),
302   fFillTriggerESD(rec.fFillTriggerESD),
303
304   fCleanESD(rec.fCleanESD),
305   fV0DCAmax(rec.fV0DCAmax),
306   fV0CsPmin(rec.fV0CsPmin),
307   fDmax(rec.fDmax),
308   fZmax(rec.fZmax),
309
310   fRunLocalReconstruction(rec.fRunLocalReconstruction),
311   fRunTracking(rec.fRunTracking),
312   fFillESD(rec.fFillESD),
313   fUseTrackingErrorsForAlignment(rec.fUseTrackingErrorsForAlignment),
314   fGAliceFileName(rec.fGAliceFileName),
315   fInput(rec.fInput),
316   fpEvent(rec.fpEvent),
317   fEquipIdMap(rec.fEquipIdMap),
318   fFirstEvent(rec.fFirstEvent),
319   fLastEvent(rec.fLastEvent),
320   fNumberOfEventsPerFile(rec.fNumberOfEventsPerFile),
321   fCheckPointLevel(0),
322   fOptions(),
323   fLoadAlignFromCDB(rec.fLoadAlignFromCDB),
324   fLoadAlignData(rec.fLoadAlignData),
325   fESDPar(rec.fESDPar),
326   fUseHLTData(rec.fUseHLTData),
327
328   fRunLoader(NULL),
329   fRawReader(NULL),
330   fParentRawReader(NULL),
331
332   fVertexer(NULL),
333   fDiamondProfile(NULL),
334   fDiamondProfileTPC(NULL),
335   fMeanVertexConstraint(rec.fMeanVertexConstraint),
336
337   fGRPList(NULL),
338
339   fAlignObjArray(rec.fAlignObjArray),
340   fCDBUri(rec.fCDBUri),
341   fSpecCDBUri(), 
342   fInitCDBCalled(rec.fInitCDBCalled),
343   fSetRunNumberFromDataCalled(rec.fSetRunNumberFromDataCalled),
344   fRunQA(rec.fRunQA),  
345   fRunGlobalQA(rec.fRunGlobalQA),
346   fInLoopQA(rec.fInLoopQA),
347   fSameQACycle(rec.fSameQACycle),
348   fRunPlaneEff(rec.fRunPlaneEff),
349
350   fesd(NULL),
351   fhltesd(NULL),
352   fesdf(NULL),
353   ffile(NULL),
354   ftree(NULL),
355   fhlttree(NULL),
356   ffileOld(NULL),
357   ftreeOld(NULL),
358   fhlttreeOld(NULL),
359   ftVertexer(NULL),
360   fIsNewRunLoader(rec.fIsNewRunLoader)
361 {
362 // copy constructor
363
364   for (Int_t i = 0; i < rec.fOptions.GetEntriesFast(); i++) {
365     if (rec.fOptions[i]) fOptions.Add(rec.fOptions[i]->Clone());
366   }
367   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
368     fReconstructor[iDet] = NULL;
369     fLoader[iDet] = NULL;
370     fTracker[iDet] = NULL;
371     fQADataMaker[iDet] = NULL;
372         fQACycles[iDet] = rec.fQACycles[iDet];  
373   }
374   fQADataMaker[fgkNDetectors]=NULL;  //Global QA
375   for (Int_t i = 0; i < rec.fSpecCDBUri.GetEntriesFast(); i++) {
376     if (rec.fSpecCDBUri[i]) fSpecCDBUri.Add(rec.fSpecCDBUri[i]->Clone());
377   }
378 }
379
380 //_____________________________________________________________________________
381 AliReconstruction& AliReconstruction::operator = (const AliReconstruction& rec)
382 {
383 // assignment operator
384
385   this->~AliReconstruction();
386   new(this) AliReconstruction(rec);
387   return *this;
388 }
389
390 //_____________________________________________________________________________
391 AliReconstruction::~AliReconstruction()
392 {
393 // clean up
394
395   CleanUp();
396   fOptions.Delete();
397   fSpecCDBUri.Delete();
398
399   AliCodeTimer::Instance()->Print();
400 }
401
402 //_____________________________________________________________________________
403 void AliReconstruction::InitCDB()
404 {
405 // activate a default CDB storage
406 // First check if we have any CDB storage set, because it is used 
407 // to retrieve the calibration and alignment constants
408
409   if (fInitCDBCalled) return;
410   fInitCDBCalled = kTRUE;
411
412   AliCDBManager* man = AliCDBManager::Instance();
413   if (man->IsDefaultStorageSet())
414   {
415     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
416     AliWarning("Default CDB storage has been already set !");
417     AliWarning(Form("Ignoring the default storage declared in AliReconstruction: %s",fCDBUri.Data()));
418     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
419     fCDBUri = man->GetDefaultStorage()->GetURI();
420   }
421   else {
422     if (fCDBUri.Length() > 0) 
423     {
424         AliDebug(2,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
425         AliDebug(2, Form("Default CDB storage is set to: %s", fCDBUri.Data()));
426         AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
427     } else {
428         fCDBUri="local://$ALICE_ROOT";
429         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
430         AliWarning("Default CDB storage not yet set !!!!");
431         AliWarning(Form("Setting it now to: %s", fCDBUri.Data()));
432         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
433                 
434     }
435     man->SetDefaultStorage(fCDBUri);
436   }
437
438   // Now activate the detector specific CDB storage locations
439   for (Int_t i = 0; i < fSpecCDBUri.GetEntriesFast(); i++) {
440     TObject* obj = fSpecCDBUri[i];
441     if (!obj) continue;
442     AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
443     AliDebug(2, Form("Specific CDB storage for %s is set to: %s",obj->GetName(),obj->GetTitle()));
444     AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
445     man->SetSpecificStorage(obj->GetName(), obj->GetTitle());
446   }
447   
448 }
449
450 //_____________________________________________________________________________
451 void AliReconstruction::SetDefaultStorage(const char* uri) {
452 // Store the desired default CDB storage location
453 // Activate it later within the Run() method
454
455   fCDBUri = uri;
456
457 }
458
459 //_____________________________________________________________________________
460 void AliReconstruction::SetSpecificStorage(const char* calibType, const char* uri) {
461 // Store a detector-specific CDB storage location
462 // Activate it later within the Run() method
463
464   AliCDBPath aPath(calibType);
465   if(!aPath.IsValid()){
466         // if calibType is not wildcard but it is a valid detector, add "/*" to make it a valid path
467         for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
468                 if(!strcmp(calibType, fgkDetectorName[iDet])) {
469                         aPath.SetPath(Form("%s/*", calibType));
470                         AliInfo(Form("Path for specific storage set to %s", aPath.GetPath().Data()));
471                         break;
472                 }
473         }
474         if(!aPath.IsValid()){
475                 AliError(Form("Not a valid path or detector: %s", calibType));
476                 return;
477         }
478   }
479
480 //  // check that calibType refers to a "valid" detector name
481 //  Bool_t isDetector = kFALSE;
482 //  for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
483 //    TString detName = fgkDetectorName[iDet];
484 //    if(aPath.GetLevel0() == detName) {
485 //      isDetector = kTRUE;
486 //      break;
487 //    }
488 //  }
489 //
490 //  if(!isDetector) {
491 //      AliError(Form("Not a valid detector: %s", aPath.GetLevel0().Data()));
492 //      return;
493 //  }
494
495   TObject* obj = fSpecCDBUri.FindObject(aPath.GetPath().Data());
496   if (obj) fSpecCDBUri.Remove(obj);
497   fSpecCDBUri.Add(new TNamed(aPath.GetPath().Data(), uri));
498
499 }
500
501 //_____________________________________________________________________________
502 Bool_t AliReconstruction::SetRunNumberFromData()
503 {
504   // The method is called in Run() in order
505   // to set a correct run number.
506   // In case of raw data reconstruction the
507   // run number is taken from the raw data header
508
509   if (fSetRunNumberFromDataCalled) return kTRUE;
510   fSetRunNumberFromDataCalled = kTRUE;
511   
512   AliCDBManager* man = AliCDBManager::Instance();
513   
514   if(man->GetRun() > 0) {
515         AliWarning("Run number is taken from raw-event header! Ignoring settings in AliCDBManager!");
516   } 
517   
518   if (!fRunLoader) {
519       AliError("No run loader is found !"); 
520       return kFALSE;
521     }
522     // read run number from gAlice
523     if(fRunLoader->GetAliRun())
524       AliCDBManager::Instance()->SetRun(fRunLoader->GetHeader()->GetRun());
525     else {
526       if(fRawReader) {
527         if(fRawReader->NextEvent()) {
528           AliCDBManager::Instance()->SetRun(fRawReader->GetRunNumber());
529           fRawReader->RewindEvents();
530         }
531         else {
532           if(man->GetRun() > 0) {
533             AliWarning("No raw events is found ! Using settings in AliCDBManager !");
534             man->Print();  
535             return kTRUE;
536           }
537           else {
538             AliWarning("Neither raw events nor settings in AliCDBManager are found !");
539             return kFALSE;
540           }
541         }
542       }
543       else {
544         AliError("Neither gAlice nor RawReader objects are found !");
545         return kFALSE;
546       }
547   }
548
549   man->Print();  
550   
551   return kTRUE;
552 }
553
554 //_____________________________________________________________________________
555 void AliReconstruction::SetCDBLock() {
556   // Set CDB lock: from now on it is forbidden to reset the run number
557   // or the default storage or to activate any further storage!
558   
559   AliCDBManager::Instance()->SetLock(1);
560 }
561
562 //_____________________________________________________________________________
563 Bool_t AliReconstruction::MisalignGeometry(const TString& detectors)
564 {
565   // Read the alignment objects from CDB.
566   // Each detector is supposed to have the
567   // alignment objects in DET/Align/Data CDB path.
568   // All the detector objects are then collected,
569   // sorted by geometry level (starting from ALIC) and
570   // then applied to the TGeo geometry.
571   // Finally an overlaps check is performed.
572
573   // Load alignment data from CDB and fill fAlignObjArray 
574   if(fLoadAlignFromCDB){
575         
576     TString detStr = detectors;
577     TString loadAlObjsListOfDets = "";
578     
579     for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
580       if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
581       loadAlObjsListOfDets += fgkDetectorName[iDet];
582       loadAlObjsListOfDets += " ";
583     } // end loop over detectors
584     loadAlObjsListOfDets.Prepend("GRP "); //add alignment objects for non-sensitive modules
585     AliGeomManager::ApplyAlignObjsFromCDB(loadAlObjsListOfDets.Data());
586   }else{
587     // Check if the array with alignment objects was
588     // provided by the user. If yes, apply the objects
589     // to the present TGeo geometry
590     if (fAlignObjArray) {
591       if (gGeoManager && gGeoManager->IsClosed()) {
592         if (AliGeomManager::ApplyAlignObjsToGeom(*fAlignObjArray) == kFALSE) {
593           AliError("The misalignment of one or more volumes failed!"
594                    "Compare the list of simulated detectors and the list of detector alignment data!");
595           return kFALSE;
596         }
597       }
598       else {
599         AliError("Can't apply the misalignment! gGeoManager doesn't exist or it is still opened!");
600         return kFALSE;
601       }
602     }
603   }
604   
605   delete fAlignObjArray; fAlignObjArray=0;
606
607   return kTRUE;
608 }
609
610 //_____________________________________________________________________________
611 void AliReconstruction::SetGAliceFile(const char* fileName)
612 {
613 // set the name of the galice file
614
615   fGAliceFileName = fileName;
616 }
617
618 //_____________________________________________________________________________
619 void AliReconstruction::SetInput(const char* input,void **pEvent) 
620 {
621   // In case event pointer is given, we run in an online mode
622   // and the first argument is ignored.
623   // In case event pointer is NULL, we run in a normal
624   // mode over a raw-data file and the first argument points
625   // to the name of that file
626   if (!pEvent) {
627     fInput = input;
628     fpEvent = NULL;
629   }
630   else {
631     fInput = "";
632     fpEvent = pEvent;
633   }
634 }
635
636 //_____________________________________________________________________________
637 void AliReconstruction::SetOption(const char* detector, const char* option)
638 {
639 // set options for the reconstruction of a detector
640
641   TObject* obj = fOptions.FindObject(detector);
642   if (obj) fOptions.Remove(obj);
643   fOptions.Add(new TNamed(detector, option));
644 }
645
646 //_____________________________________________________________________________
647 Bool_t AliReconstruction::Run(const char* input)
648 {
649   // Run Run Run
650   AliCodeTimerAuto("");
651
652   if (!InitRun(input)) return kFALSE;
653   
654   //******* The loop over events
655   Int_t iEvent = 0;
656   while ((iEvent < fRunLoader->GetNumberOfEvents()) ||
657          (fRawReader && fRawReader->NextEvent())) {
658     if (!RunEvent(iEvent)) return kFALSE;
659     iEvent++;
660   }
661
662   if (!FinishRun()) return kFALSE;
663
664   return kTRUE;
665 }
666
667 //_____________________________________________________________________________
668 Bool_t AliReconstruction::InitRun(const char* input, void **pEvent)
669 {
670   // Initialize all the stuff before
671   // going into the event loop
672   // If the second argument is given, the first one is ignored and
673   // the reconstruction works in an online mode
674   AliCodeTimerAuto("");
675
676   if (pEvent) fpEvent = pEvent;
677   if (input) fInput = input;
678
679   // set the input in case of raw data
680   if (!fInput.IsNull() || fpEvent) {
681     if (!fInput.IsNull()) {
682       AliInfo(Form("Reconstruction will run over a raw-data file: %s",fInput.Data()));
683       TString fileName(fInput);
684       if (fInput.EndsWith("/")) {
685         fRawReader = new AliRawReaderFile(fInput);
686       } else if (fInput.EndsWith(".root")) {
687         fRawReader = new AliRawReaderRoot(fInput);
688       } else {
689         fRawReader = new AliRawReaderDate(fInput);
690       }
691     }
692     else {
693       AliInfo(Form("Reconstruction will run over an event in memory at: %p",*fpEvent));
694       fRawReader = new AliRawReaderDate((void *)(*fpEvent));
695     }
696   }
697   else {
698     AliInfo("Reconstruction will run over digits");
699   }
700
701   if (!fEquipIdMap.IsNull() && fRawReader)
702     fRawReader->LoadEquipmentIdsMap(fEquipIdMap);
703
704   if (!fUseHLTData.IsNull()) {
705     // create the RawReaderHLT which performs redirection of HLT input data for
706     // the specified detectors
707     AliRawReader* pRawReader=AliRawHLTManager::CreateRawReaderHLT(fRawReader, fUseHLTData.Data());
708     if (pRawReader) {
709       fParentRawReader=fRawReader;
710       fRawReader=pRawReader;
711     } else {
712       AliError(Form("can not create Raw Reader for HLT input %s", fUseHLTData.Data()));
713     }
714   }
715
716    AliSysInfo::AddStamp("Start");
717   // get the run loader
718   if (!InitRunLoader()) return kFALSE;
719    AliSysInfo::AddStamp("LoadLoader");
720
721   // Initialize the CDB storage
722   InitCDB();
723   
724   AliSysInfo::AddStamp("LoadCDB");
725
726   // Set run number in CDBManager (if it is not already set by the user)
727   if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
728   
729   // Set CDB lock: from now on it is forbidden to reset the run number
730   // or the default storage or to activate any further storage!
731   SetCDBLock();
732   
733   // Import ideal TGeo geometry and apply misalignment
734   if (!gGeoManager) {
735     TString geom(gSystem->DirName(fGAliceFileName));
736     geom += "/geometry.root";
737     AliGeomManager::LoadGeometry(geom.Data());
738     if (!gGeoManager) if (fStopOnError) return kFALSE;
739   }
740
741   if (!MisalignGeometry(fLoadAlignData)) if (fStopOnError) return kFALSE;
742    AliSysInfo::AddStamp("LoadGeom");
743
744   //QA
745   AliQADataMakerSteer qas ; 
746   if (fRunQA && fRawReader) { 
747     qas.Run(fRunLocalReconstruction, fRawReader) ; 
748         fSameQACycle = kTRUE ; 
749   }
750   // checking the QA of previous steps
751   //CheckQA() ; 
752  
753   /*
754   // local reconstruction
755   if (!fRunLocalReconstruction.IsNull()) {
756     if (!RunLocalReconstruction(fRunLocalReconstruction)) {
757       if (fStopOnError) {CleanUp(); return kFALSE;}
758     }
759   }
760   */
761
762   // get vertexer
763   if (fRunVertexFinder && !CreateVertexer()) {
764     if (fStopOnError) {
765       CleanUp(); 
766       return kFALSE;
767     }
768   }
769    AliSysInfo::AddStamp("Vertexer");
770
771   // get trackers
772   if (!fRunTracking.IsNull() && !CreateTrackers(fRunTracking)) {
773     if (fStopOnError) {
774       CleanUp(); 
775       return kFALSE;
776     }      
777   }
778    AliSysInfo::AddStamp("LoadTrackers");
779
780   // get the possibly already existing ESD file and tree
781   fesd = new AliESDEvent(); fhltesd = new AliESDEvent();
782   if (!gSystem->AccessPathName("AliESDs.root")){
783     gSystem->CopyFile("AliESDs.root", "AliESDs.old.root", kTRUE);
784     ffileOld = TFile::Open("AliESDs.old.root");
785     if (ffileOld && ffileOld->IsOpen()) {
786       ftreeOld = (TTree*) ffileOld->Get("esdTree");
787       if (ftreeOld)fesd->ReadFromTree(ftreeOld);
788       fhlttreeOld = (TTree*) ffileOld->Get("HLTesdTree");
789       if (fhlttreeOld)  fhltesd->ReadFromTree(fhlttreeOld);
790     }
791   }
792
793   // create the ESD output file and tree
794   ffile = TFile::Open("AliESDs.root", "RECREATE");
795   ffile->SetCompressionLevel(2);
796   if (!ffile->IsOpen()) {
797     AliError("opening AliESDs.root failed");
798     if (fStopOnError) {CleanUp(ffile, ffileOld); return kFALSE;}    
799   }
800
801   ftree = new TTree("esdTree", "Tree with ESD objects");
802   fesd = new AliESDEvent();
803   fesd->CreateStdContent();
804   fesd->WriteToTree(ftree);
805
806   fhlttree = new TTree("HLTesdTree", "Tree with HLT ESD objects");
807   fhltesd = new AliESDEvent();
808   fhltesd->CreateStdContent();
809   fhltesd->WriteToTree(fhlttree);
810
811   /* CKB Why?
812   delete esd; delete hltesd;
813   esd = NULL; hltesd = NULL;
814   */
815   // create the branch with ESD additions
816
817
818
819   if (fWriteESDfriend) {
820     fesdf = new AliESDfriend();
821     TBranch *br=ftree->Branch("ESDfriend.","AliESDfriend", &fesdf);
822     br->SetFile("AliESDfriends.root");
823     fesd->AddObject(fesdf);
824   }
825
826   
827   // Get the GRP CDB entry
828   AliCDBEntry* entryGRP = AliCDBManager::Instance()->Get("GRP/GRP/Data");
829         
830   if(entryGRP) {
831         fGRPList = dynamic_cast<TList*> (entryGRP->GetObject());  
832   } else {
833         AliError("No GRP entry found in OCDB!");
834   }
835
836   // Get the diamond profile from OCDB
837   AliCDBEntry* entry = AliCDBManager::Instance()
838         ->Get("GRP/Calib/MeanVertex");
839         
840   if(entry) {
841         fDiamondProfile = dynamic_cast<AliESDVertex*> (entry->GetObject());  
842   } else {
843         AliError("No diamond profile found in OCDB!");
844   }
845
846   entry = 0;
847   entry = AliCDBManager::Instance()
848         ->Get("GRP/Calib/MeanVertexTPC");
849         
850   if(entry) {
851         fDiamondProfileTPC = dynamic_cast<AliESDVertex*> (entry->GetObject());  
852   } else {
853         AliError("No diamond profile found in OCDB!");
854   }
855
856   ftVertexer = new AliVertexerTracks(AliTracker::GetBz());
857   if(fDiamondProfile && fMeanVertexConstraint) ftVertexer->SetVtxStart(fDiamondProfile);
858
859   if (fRawReader) fRawReader->RewindEvents();
860
861   ProcInfo_t ProcInfo;
862   gSystem->GetProcInfo(&ProcInfo);
863   AliInfo(Form("Current memory usage %d %d", ProcInfo.fMemResident, ProcInfo.fMemVirtual));
864   
865
866   //Initialize the QA and start of cycle for out-of-cycle QA
867   if (fRunQA) {
868      TString detStr(fFillESD); 
869      for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
870         if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
871         AliQADataMakerRec *qadm = GetQADataMaker(iDet);  
872         if (!qadm) continue;
873         AliInfo(Form("Initializing the QA data maker for %s", 
874                fgkDetectorName[iDet]));
875         qadm->Init(AliQA::kRECPOINTS, AliCDBManager::Instance()->GetRun());
876         qadm->Init(AliQA::kESDS, AliCDBManager::Instance()->GetRun());
877         if (!fInLoopQA) {
878                         qadm->StartOfCycle(AliQA::kRECPOINTS, fSameQACycle);
879                         qadm->StartOfCycle(AliQA::kESDS,"same");
880         }
881      }
882           if (fRunGlobalQA) {
883                   AliQADataMakerRec *qadm = GetQADataMaker(AliQA::kGLOBAL);
884                   AliInfo(Form("Initializing the global QA data maker"));
885                   TObjArray *arr=
886                         qadm->Init(AliQA::kRECPOINTS, AliCDBManager::Instance()->GetRun());
887                   AliTracker::SetResidualsArray(arr);
888                   qadm->Init(AliQA::kESDS, AliCDBManager::Instance()->GetRun());
889                   if (!fInLoopQA) {
890                           qadm->StartOfCycle(AliQA::kRECPOINTS, fSameQACycle);
891                           qadm->StartOfCycle(AliQA::kESDS, "same");
892                   }
893           }
894           if (!fInLoopQA) 
895                   fSameQACycle = kTRUE; 
896   }
897
898   //Initialize the Plane Efficiency framework
899   if (fRunPlaneEff && !InitPlaneEff()) {
900     if(fStopOnError) {CleanUp(ffile, ffileOld); return kFALSE;}
901   }
902
903   return kTRUE;
904 }
905
906 //_____________________________________________________________________________
907 Bool_t AliReconstruction::RunEvent(Int_t iEvent)
908 {
909   // run the reconstruction over a single event
910   // The event loop is steered in Run method
911
912   AliCodeTimerAuto("");
913
914   if (iEvent >= fRunLoader->GetNumberOfEvents()) {
915     fRunLoader->SetEventNumber(iEvent);
916     fRunLoader->GetHeader()->Reset(fRawReader->GetRunNumber(), 
917                                    iEvent, iEvent);
918     //??      fRunLoader->MakeTree("H");
919     fRunLoader->TreeE()->Fill();
920   }
921
922   if ((iEvent < fFirstEvent) || ((fLastEvent >= 0) && (iEvent > fLastEvent))) {
923     // copy old ESD to the new one
924     if (ftreeOld) {
925       fesd->ReadFromTree(ftreeOld);
926       ftreeOld->GetEntry(iEvent);
927       ftree->Fill();
928     }
929     if (fhlttreeOld) {
930       fesd->ReadFromTree(fhlttreeOld);
931       fhlttreeOld->GetEntry(iEvent);
932       fhlttree->Fill();
933     }
934     return kTRUE;
935   }
936
937   AliInfo(Form("processing event %d", iEvent));
938
939     //Start of cycle for the in-loop QA
940     if (fInLoopQA) {
941        if (fRunQA) {
942           TString detStr(fFillESD); 
943           for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
944              if (!IsSelected(fgkDetectorName[iDet], detStr)) 
945                                  continue;
946              AliQADataMakerRec *qadm = GetQADataMaker(iDet);  
947              if (!qadm) 
948                                  continue;
949              qadm->StartOfCycle(AliQA::kRECPOINTS, fSameQACycle);
950              qadm->StartOfCycle(AliQA::kESDS, "same") ;         
951           }
952                    if (fRunGlobalQA) {
953                            AliQADataMakerRec *qadm = GetQADataMaker(AliQA::kGLOBAL);
954                            qadm->StartOfCycle(AliQA::kRECPOINTS, fSameQACycle);
955                            qadm->StartOfCycle(AliQA::kESDS, "same");
956                    }               
957            }
958     }
959
960     fRunLoader->GetEvent(iEvent);
961
962     char aFileName[256];
963     sprintf(aFileName, "ESD_%d.%d_final.root", 
964             fRunLoader->GetHeader()->GetRun(), 
965             fRunLoader->GetHeader()->GetEventNrInRun());
966     if (!gSystem->AccessPathName(aFileName)) return kTRUE;
967
968     // local signle event reconstruction
969     if (!fRunLocalReconstruction.IsNull()) {
970       if (!RunLocalEventReconstruction(fRunLocalReconstruction)) {
971         if (fStopOnError) {CleanUp(ffile, ffileOld); return kFALSE;}
972       }
973     }
974
975     fesd->SetRunNumber(fRunLoader->GetHeader()->GetRun());
976     fhltesd->SetRunNumber(fRunLoader->GetHeader()->GetRun());
977     fesd->SetEventNumberInFile(fRunLoader->GetHeader()->GetEventNrInRun());
978     fhltesd->SetEventNumberInFile(fRunLoader->GetHeader()->GetEventNrInRun());
979     
980     // Set magnetic field from the tracker
981     fesd->SetMagneticField(AliTracker::GetBz());
982     fhltesd->SetMagneticField(AliTracker::GetBz());
983
984     
985     
986     // Fill raw-data error log into the ESD
987     if (fRawReader) FillRawDataErrorLog(iEvent,fesd);
988
989     // vertex finder
990     if (fRunVertexFinder) {
991       if (!ReadESD(fesd, "vertex")) {
992         if (!RunVertexFinder(fesd)) {
993           if (fStopOnError) {CleanUp(ffile, ffileOld); return kFALSE;}
994         }
995         if (fCheckPointLevel > 0) WriteESD(fesd, "vertex");
996       }
997     }
998
999     // HLT tracking
1000     if (!fRunTracking.IsNull()) {
1001       if (fRunHLTTracking) {
1002         fhltesd->SetPrimaryVertexSPD(fesd->GetVertex());
1003         if (!RunHLTTracking(fhltesd)) {
1004           if (fStopOnError) {CleanUp(ffile, ffileOld); return kFALSE;}
1005         }
1006       }
1007     }
1008
1009     // Muon tracking
1010     if (!fRunTracking.IsNull()) {
1011       if (fRunMuonTracking) {
1012         if (!RunMuonTracking(fesd)) {
1013           if (fStopOnError) {CleanUp(ffile, ffileOld); return kFALSE;}
1014         }
1015       }
1016     }
1017
1018     // barrel tracking
1019     if (!fRunTracking.IsNull()) {
1020       if (!ReadESD(fesd, "tracking")) {
1021         if (!RunTracking(fesd)) {
1022           if (fStopOnError) {CleanUp(ffile, ffileOld); return kFALSE;}
1023         }
1024         if (fCheckPointLevel > 0) WriteESD(fesd, "tracking");
1025       }
1026     }
1027
1028     // fill ESD
1029     if (!fFillESD.IsNull()) {
1030       if (!FillESD(fesd, fFillESD)) {
1031         if (fStopOnError) {CleanUp(ffile, ffileOld); return kFALSE;}
1032       }
1033     }
1034   
1035     // fill Event header information from the RawEventHeader
1036     if (fRawReader){FillRawEventHeaderESD(fesd);}
1037
1038     // combined PID
1039     AliESDpid::MakePID(fesd);
1040     if (fCheckPointLevel > 1) WriteESD(fesd, "PID");
1041
1042     if (fFillTriggerESD) {
1043       if (!ReadESD(fesd, "trigger")) {
1044         if (!FillTriggerESD(fesd)) {
1045           if (fStopOnError) {CleanUp(ffile, ffileOld); return kFALSE;}
1046         }
1047         if (fCheckPointLevel > 1) WriteESD(fesd, "trigger");
1048       }
1049     }
1050
1051     ffile->cd();
1052
1053     //
1054     // Propagate track to the beam pipe  (if not laready done by ITS)
1055     //
1056     const Int_t ntracks = fesd->GetNumberOfTracks();
1057     const Double_t kBz = fesd->GetMagneticField();
1058     const Double_t kRadius  = 2.8; //something less than the beam pipe radius
1059
1060     TObjArray trkArray;
1061     UShort_t *selectedIdx=new UShort_t[ntracks];
1062
1063     for (Int_t itrack=0; itrack<ntracks; itrack++){
1064       const Double_t kMaxStep = 5;   //max step over the material
1065       Bool_t ok;
1066
1067       AliESDtrack *track = fesd->GetTrack(itrack);
1068       if (!track) continue;
1069
1070       AliExternalTrackParam *tpcTrack =
1071            (AliExternalTrackParam *)track->GetTPCInnerParam();
1072       ok = kFALSE;
1073       if (tpcTrack)
1074         ok = AliTracker::
1075           PropagateTrackTo(tpcTrack,kRadius,track->GetMass(),kMaxStep,kTRUE);
1076
1077
1078
1079       if (ok) {
1080         Int_t n=trkArray.GetEntriesFast();
1081         selectedIdx[n]=track->GetID();
1082         trkArray.AddLast(tpcTrack);
1083       }
1084
1085       if (track->GetX() < kRadius) continue;
1086
1087       ok = AliTracker::
1088            PropagateTrackTo(track,kRadius,track->GetMass(),kMaxStep,kTRUE);
1089       if (ok) {
1090          track->RelateToVertex(fesd->GetPrimaryVertexSPD(), kBz, kRadius);
1091       }
1092     }
1093
1094     //
1095     // Improve the reconstructed primary vertex position using the tracks
1096     //
1097     TObject *obj = fOptions.FindObject("ITS");
1098     if (obj) {
1099       TString optITS = obj->GetTitle();
1100       if (optITS.Contains("cosmics") || optITS.Contains("COSMICS")) 
1101         fRunVertexFinderTracks=kFALSE;
1102     }
1103     if (fRunVertexFinderTracks) {
1104        // TPC + ITS primary vertex
1105        ftVertexer->SetITSrefitRequired();
1106        if(fDiamondProfile && fMeanVertexConstraint) {
1107          ftVertexer->SetVtxStart(fDiamondProfile);
1108        } else {
1109          ftVertexer->SetConstraintOff();
1110        }
1111        AliESDVertex *pvtx=ftVertexer->FindPrimaryVertex(fesd);
1112        if (pvtx) {
1113           if (pvtx->GetStatus()) {
1114              fesd->SetPrimaryVertex(pvtx);
1115              for (Int_t i=0; i<ntracks; i++) {
1116                  AliESDtrack *t = fesd->GetTrack(i);
1117                  t->RelateToVertex(pvtx, kBz, kRadius);
1118              } 
1119           }
1120        }
1121
1122        // TPC-only primary vertex
1123        ftVertexer->SetITSrefitNotRequired();
1124        if(fDiamondProfileTPC && fMeanVertexConstraint) {
1125          ftVertexer->SetVtxStart(fDiamondProfileTPC);
1126        } else {
1127          ftVertexer->SetConstraintOff();
1128        }
1129        pvtx=ftVertexer->FindPrimaryVertex(&trkArray,selectedIdx);
1130        if (pvtx) {
1131           if (pvtx->GetStatus()) {
1132              fesd->SetPrimaryVertexTPC(pvtx);
1133              Int_t nsel=trkArray.GetEntriesFast();
1134              for (Int_t i=0; i<nsel; i++) {
1135                  AliExternalTrackParam *t = 
1136                    (AliExternalTrackParam *)trkArray.UncheckedAt(i);
1137                  t->PropagateToDCA(pvtx, kBz, kRadius);
1138              } 
1139           }
1140        }
1141
1142     }
1143     delete[] selectedIdx;
1144
1145     if(fDiamondProfile) fesd->SetDiamond(fDiamondProfile);
1146     
1147
1148     if (fRunV0Finder) {
1149        // V0 finding
1150        AliV0vertexer vtxer;
1151        vtxer.Tracks2V0vertices(fesd);
1152
1153        if (fRunCascadeFinder) {
1154           // Cascade finding
1155           AliCascadeVertexer cvtxer;
1156           cvtxer.V0sTracks2CascadeVertices(fesd);
1157        }
1158     }
1159  
1160     // write ESD
1161     if (fCleanESD) CleanESD(fesd);
1162
1163         if (fRunQA) {
1164                 if (fRunGlobalQA) {
1165                         AliQADataMakerRec *qadm = GetQADataMaker(AliQA::kGLOBAL);
1166                         if (qadm) qadm->Exec(AliQA::kESDS, fesd);
1167                 }
1168         }
1169
1170     if (fWriteESDfriend) {
1171       fesdf->~AliESDfriend();
1172       new (fesdf) AliESDfriend(); // Reset...
1173       fesd->GetESDfriend(fesdf);
1174     }
1175     ftree->Fill();
1176
1177     // write HLT ESD
1178     fhlttree->Fill();
1179
1180     if (fCheckPointLevel > 0)  WriteESD(fesd, "final"); 
1181     fesd->Reset();
1182     fhltesd->Reset();
1183     if (fWriteESDfriend) {
1184       fesdf->~AliESDfriend();
1185       new (fesdf) AliESDfriend(); // Reset...
1186     }
1187  
1188     ProcInfo_t ProcInfo;
1189     gSystem->GetProcInfo(&ProcInfo);
1190     AliInfo(Form("Event %d -> Current memory usage %d %d",iEvent, ProcInfo.fMemResident, ProcInfo.fMemVirtual));
1191   
1192
1193   // End of cycle for the in-loop QA
1194      if (fInLoopQA) {
1195         if (fRunQA) {
1196            RunQA(fFillESD.Data(), fesd);
1197            TString detStr(fFillESD); 
1198            for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
1199                            if (!IsSelected(fgkDetectorName[iDet], detStr)) 
1200                                    continue;
1201                            AliQADataMakerRec * qadm = GetQADataMaker(iDet);
1202                            if (!qadm) 
1203                                    continue;
1204                            qadm->EndOfCycle(AliQA::kRECPOINTS);
1205                            qadm->EndOfCycle(AliQA::kESDS);
1206                            qadm->Finish();
1207                    }
1208         }
1209         if (fRunGlobalQA) {
1210            AliQADataMakerRec *qadm = GetQADataMaker(AliQA::kGLOBAL);
1211            if (qadm) {
1212               qadm->EndOfCycle(AliQA::kRECPOINTS);
1213               qadm->EndOfCycle(AliQA::kESDS);
1214               qadm->Finish();
1215            }
1216         }
1217      }
1218
1219      return kTRUE;
1220 }
1221
1222 //_____________________________________________________________________________
1223 Bool_t AliReconstruction::AddEventAndRun()
1224 {
1225   // for online usage only
1226   // Add an event to the run-loader
1227   // and
1228   // re-creates AliRawReaderDate for this new event
1229   AliCodeTimerAuto("");
1230
1231   if (!fpEvent) {
1232     AliError("No raw-data event in memory given as an input! Do nothing!");
1233     return kFALSE;
1234   }
1235
1236   // New raw-reader. Could be redone in a better way... To do
1237   fRawReader->~AliRawReader();
1238   new (fRawReader) AliRawReaderDate((void*)(*fpEvent));
1239   if (!fRawReader->NextEvent()) return kFALSE;
1240
1241   // Expand the number of events in the run-loader
1242
1243   Int_t nEvents = fRunLoader->GetNumberOfEvents();
1244
1245   return RunEvent(nEvents);
1246 }
1247
1248 //_____________________________________________________________________________
1249 Bool_t AliReconstruction::FinishRun()
1250 {
1251   // Finalize the run
1252   // Called after the exit
1253   // from the event loop
1254   AliCodeTimerAuto("");
1255
1256   if (fIsNewRunLoader) { // galice.root didn't exist
1257     fRunLoader->WriteHeader("OVERWRITE");
1258     fRunLoader->CdGAFile();
1259     fRunLoader->Write(0, TObject::kOverwrite);
1260   }
1261
1262   ftree->GetUserInfo()->Add(fesd);
1263   fhlttree->GetUserInfo()->Add(fhltesd);
1264   
1265   const TMap *cdbMap = AliCDBManager::Instance()->GetStorageMap();       
1266   const TList *cdbList = AliCDBManager::Instance()->GetRetrievedIds();   
1267                  
1268    TMap *cdbMapCopy = new TMap(cdbMap->GetEntries());    
1269    cdbMapCopy->SetOwner(1);      
1270    cdbMapCopy->SetName("cdbMap");        
1271    TIter iter(cdbMap->GetTable());       
1272          
1273    TPair* pair = 0;      
1274    while((pair = dynamic_cast<TPair*> (iter.Next()))){   
1275          TObjString* keyStr = dynamic_cast<TObjString*> (pair->Key());   
1276          TObjString* valStr = dynamic_cast<TObjString*> (pair->Value());         
1277          cdbMapCopy->Add(new TObjString(keyStr->GetName()), new TObjString(valStr->GetName()));  
1278    }     
1279          
1280    TList *cdbListCopy = new TList();     
1281    cdbListCopy->SetOwner(1);     
1282    cdbListCopy->SetName("cdbList");      
1283          
1284    TIter iter2(cdbList);         
1285          
1286    AliCDBId* id=0;       
1287    while((id = dynamic_cast<AliCDBId*> (iter2.Next()))){         
1288          cdbListCopy->Add(new TObjString(id->ToString().Data()));        
1289    }     
1290          
1291    ftree->GetUserInfo()->Add(cdbMapCopy);        
1292    ftree->GetUserInfo()->Add(cdbListCopy);
1293
1294
1295   if(fESDPar.Contains("ESD.par")){
1296     AliInfo("Attaching ESD.par to Tree");
1297     TNamed *fn = CopyFileToTNamed(fESDPar.Data(),"ESD.par");
1298     ftree->GetUserInfo()->Add(fn);
1299   }
1300
1301
1302   ffile->cd();
1303
1304   if (fWriteESDfriend)
1305     ftree->SetBranchStatus("ESDfriend*",0);
1306   // we want to have only one tree version number
1307   ftree->Write(ftree->GetName(),TObject::kOverwrite);
1308   fhlttree->Write();
1309
1310 // Finish with Plane Efficiency evaluation: before of CleanUp !!!
1311   if (fRunPlaneEff && !FinishPlaneEff()) {
1312    AliWarning("Finish PlaneEff evaluation failed");
1313   }
1314
1315   gROOT->cd();
1316   CleanUp(ffile, ffileOld);
1317     
1318   if (fWriteAOD) {
1319     AliWarning("AOD creation not supported anymore during reconstruction. See ANALYSIS/AliAnalysisTaskESDfilter.cxx instead.");
1320   }
1321
1322   // Create tags for the events in the ESD tree (the ESD tree is always present)
1323   // In case of empty events the tags will contain dummy values
1324   AliESDTagCreator *esdtagCreator = new AliESDTagCreator();
1325   esdtagCreator->CreateESDTags(fFirstEvent,fLastEvent,fGRPList);
1326   if (fWriteAOD) {
1327     AliWarning("AOD tag creation not supported anymore during reconstruction.");
1328   }
1329
1330   //Finish QA and end of cycle for out-of-loop QA
1331   if (!fInLoopQA) {
1332           if (fRunQA) {
1333                   AliQADataMakerSteer qas;
1334                   qas.Run(fRunLocalReconstruction.Data(), AliQA::kRECPOINTS, fSameQACycle);
1335                   //qas.Reset() ;
1336                   qas.Run(fRunTracking.Data(), AliQA::kESDS, fSameQACycle);
1337                   if (fRunGlobalQA) {
1338                          AliQADataMakerRec *qadm = GetQADataMaker(AliQA::kGLOBAL);
1339                           if (qadm) {
1340                                   qadm->EndOfCycle(AliQA::kRECPOINTS);
1341                                   qadm->EndOfCycle(AliQA::kESDS);
1342                                   qadm->Finish();
1343                           }
1344                   }
1345           }
1346   }
1347   
1348   // Cleanup of CDB manager: cache and active storages!
1349   AliCDBManager::Instance()->ClearCache();
1350   
1351   return kTRUE;
1352 }
1353
1354
1355 //_____________________________________________________________________________
1356 Bool_t AliReconstruction::RunLocalReconstruction(const TString& /*detectors*/)
1357 {
1358 // run the local reconstruction
1359   static Int_t eventNr=0;
1360   AliCodeTimerAuto("")
1361
1362  //  AliCDBManager* man = AliCDBManager::Instance();
1363 //   Bool_t origCache = man->GetCacheFlag();
1364
1365 //   TString detStr = detectors;
1366 //   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
1367 //     if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
1368 //     AliReconstructor* reconstructor = GetReconstructor(iDet);
1369 //     if (!reconstructor) continue;
1370 //     if (reconstructor->HasLocalReconstruction()) continue;
1371
1372 //     AliCodeTimerStart(Form("running reconstruction for %s", fgkDetectorName[iDet]));
1373 //     AliInfo(Form("running reconstruction for %s", fgkDetectorName[iDet]));
1374     
1375 //     AliCodeTimerStart(Form("Loading calibration data from OCDB for %s", fgkDetectorName[iDet]));                          
1376 //     AliInfo(Form("Loading calibration data from OCDB for %s", fgkDetectorName[iDet]));
1377
1378 //     man->SetCacheFlag(kTRUE);
1379 //     TString calibPath = Form("%s/Calib/*", fgkDetectorName[iDet]);
1380 //     man->GetAll(calibPath); // entries are cached!
1381
1382 //     AliCodeTimerStop(Form("Loading calibration data from OCDB for %s", fgkDetectorName[iDet]));
1383      
1384 //     if (fRawReader) {
1385 //       fRawReader->RewindEvents();
1386 //       reconstructor->Reconstruct(fRunLoader, fRawReader);
1387 //     } else {
1388 //       reconstructor->Reconstruct(fRunLoader);
1389 //     }
1390      
1391 //      AliCodeTimerStop(Form("running reconstruction for %s", fgkDetectorName[iDet]));
1392     // AliSysInfo::AddStamp(Form("LRec%s_%d",fgkDetectorName[iDet],eventNr));
1393
1394 //     // unload calibration data
1395 //     man->UnloadFromCache(calibPath);
1396 //     //man->ClearCache();
1397 //   }
1398
1399 //   man->SetCacheFlag(origCache);
1400
1401 //   if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
1402 //     AliError(Form("the following detectors were not found: %s",
1403 //                   detStr.Data()));
1404 //     if (fStopOnError) return kFALSE;
1405 //   }
1406
1407           eventNr++;
1408   return kTRUE;
1409 }
1410
1411 //_____________________________________________________________________________
1412 Bool_t AliReconstruction::RunLocalEventReconstruction(const TString& detectors)
1413 {
1414 // run the local reconstruction
1415
1416   static Int_t eventNr=0;
1417   AliCodeTimerAuto("")
1418
1419   TString detStr = detectors;
1420   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
1421     if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
1422     AliReconstructor* reconstructor = GetReconstructor(iDet);
1423     if (!reconstructor) continue;
1424     AliLoader* loader = fLoader[iDet];
1425     if (!loader) {
1426       AliWarning(Form("No loader is defined for %s!",fgkDetectorName[iDet]));
1427       continue;
1428     }
1429     // conversion of digits
1430     if (fRawReader && reconstructor->HasDigitConversion()) {
1431       AliInfo(Form("converting raw data digits into root objects for %s", 
1432                    fgkDetectorName[iDet]));
1433       AliCodeTimerAuto(Form("converting raw data digits into root objects for %s", 
1434                             fgkDetectorName[iDet]));
1435       loader->LoadDigits("update");
1436       loader->CleanDigits();
1437       loader->MakeDigitsContainer();
1438       TTree* digitsTree = loader->TreeD();
1439       reconstructor->ConvertDigits(fRawReader, digitsTree);
1440       loader->WriteDigits("OVERWRITE");
1441       loader->UnloadDigits();
1442     }
1443     // local reconstruction
1444     AliInfo(Form("running reconstruction for %s", fgkDetectorName[iDet]));
1445     AliCodeTimerAuto(Form("running reconstruction for %s", fgkDetectorName[iDet]));
1446     loader->LoadRecPoints("update");
1447     loader->CleanRecPoints();
1448     loader->MakeRecPointsContainer();
1449     TTree* clustersTree = loader->TreeR();
1450     if (fRawReader && !reconstructor->HasDigitConversion()) {
1451       reconstructor->Reconstruct(fRawReader, clustersTree);
1452     } else {
1453       loader->LoadDigits("read");
1454       TTree* digitsTree = loader->TreeD();
1455       if (!digitsTree) {
1456         AliError(Form("Can't get the %s digits tree", fgkDetectorName[iDet]));
1457         if (fStopOnError) return kFALSE;
1458       } else {
1459         reconstructor->Reconstruct(digitsTree, clustersTree);
1460       }
1461       loader->UnloadDigits();
1462     }
1463
1464     // In-loop QA for local reconstrucion 
1465     if (fRunQA && fInLoopQA) {
1466        AliQADataMakerRec * qadm = GetQADataMaker(iDet);
1467        if (qadm) {
1468           //AliCodeTimerStart
1469           //(Form("Running QA data maker for %s", fgkDetectorName[iDet]));
1470           //AliInfo
1471           //(Form("Running QA data maker for %s", fgkDetectorName[iDet]));
1472
1473           qadm->Exec(AliQA::kRECPOINTS, clustersTree) ;
1474  
1475           //AliCodeTimerStop
1476           //(Form("Running QA data maker for %s", fgkDetectorName[iDet]));
1477        }
1478     }
1479
1480     loader->WriteRecPoints("OVERWRITE");
1481     loader->UnloadRecPoints();
1482     AliSysInfo::AddStamp(Form("LRec%s_%d",fgkDetectorName[iDet],eventNr), iDet,1,eventNr);
1483   }
1484
1485   if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
1486     AliError(Form("the following detectors were not found: %s",
1487                   detStr.Data()));
1488     if (fStopOnError) return kFALSE;
1489   }
1490   eventNr++;
1491   return kTRUE;
1492 }
1493
1494 //_____________________________________________________________________________
1495 Bool_t AliReconstruction::RunVertexFinder(AliESDEvent*& esd)
1496 {
1497 // run the barrel tracking
1498
1499   AliCodeTimerAuto("")
1500
1501   AliESDVertex* vertex = NULL;
1502   Double_t vtxPos[3] = {0, 0, 0};
1503   Double_t vtxErr[3] = {0.07, 0.07, 0.1};
1504   TArrayF mcVertex(3); 
1505   if (fRunLoader->GetHeader() && fRunLoader->GetHeader()->GenEventHeader()) {
1506     fRunLoader->GetHeader()->GenEventHeader()->PrimaryVertex(mcVertex);
1507     for (Int_t i = 0; i < 3; i++) vtxPos[i] = mcVertex[i];
1508   }
1509
1510   if (fVertexer) {
1511     if(fDiamondProfile) fVertexer->SetVtxStart(fDiamondProfile);
1512     AliInfo("running the ITS vertex finder");
1513     if (fLoader[0]) fLoader[0]->LoadRecPoints();
1514     vertex = fVertexer->FindVertexForCurrentEvent(fRunLoader->GetEventNumber());
1515     if (fLoader[0]) fLoader[0]->UnloadRecPoints();
1516     if(!vertex){
1517       AliWarning("Vertex not found");
1518       vertex = new AliESDVertex();
1519       vertex->SetName("default");
1520     }
1521     else {
1522       vertex->SetName("reconstructed");
1523     }
1524
1525   } else {
1526     AliInfo("getting the primary vertex from MC");
1527     vertex = new AliESDVertex(vtxPos, vtxErr);
1528   }
1529
1530   if (vertex) {
1531     vertex->GetXYZ(vtxPos);
1532     vertex->GetSigmaXYZ(vtxErr);
1533   } else {
1534     AliWarning("no vertex reconstructed");
1535     vertex = new AliESDVertex(vtxPos, vtxErr);
1536   }
1537   esd->SetPrimaryVertexSPD(vertex);
1538   // if SPD multiplicity has been determined, it is stored in the ESD
1539   AliMultiplicity *mult = fVertexer->GetMultiplicity();
1540   if(mult)esd->SetMultiplicity(mult);
1541
1542   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
1543     if (fTracker[iDet]) fTracker[iDet]->SetVertex(vtxPos, vtxErr);
1544   }  
1545   delete vertex;
1546
1547   return kTRUE;
1548 }
1549
1550 //_____________________________________________________________________________
1551 Bool_t AliReconstruction::RunHLTTracking(AliESDEvent*& esd)
1552 {
1553 // run the HLT barrel tracking
1554
1555   AliCodeTimerAuto("")
1556
1557   if (!fRunLoader) {
1558     AliError("Missing runLoader!");
1559     return kFALSE;
1560   }
1561
1562   AliInfo("running HLT tracking");
1563
1564   // Get a pointer to the HLT reconstructor
1565   AliReconstructor *reconstructor = GetReconstructor(fgkNDetectors-1);
1566   if (!reconstructor) return kFALSE;
1567
1568   // TPC + ITS
1569   for (Int_t iDet = 1; iDet >= 0; iDet--) {
1570     TString detName = fgkDetectorName[iDet];
1571     AliDebug(1, Form("%s HLT tracking", detName.Data()));
1572     reconstructor->SetOption(detName.Data());
1573     AliTracker *tracker = reconstructor->CreateTracker();
1574     if (!tracker) {
1575       AliWarning(Form("couldn't create a HLT tracker for %s", detName.Data()));
1576       if (fStopOnError) return kFALSE;
1577       continue;
1578     }
1579     Double_t vtxPos[3];
1580     Double_t vtxErr[3]={0.005,0.005,0.010};
1581     const AliESDVertex *vertex = esd->GetVertex();
1582     vertex->GetXYZ(vtxPos);
1583     tracker->SetVertex(vtxPos,vtxErr);
1584     if(iDet != 1) {
1585       fLoader[iDet]->LoadRecPoints("read");
1586       TTree* tree = fLoader[iDet]->TreeR();
1587       if (!tree) {
1588         AliError(Form("Can't get the %s cluster tree", detName.Data()));
1589         return kFALSE;
1590       }
1591       tracker->LoadClusters(tree);
1592     }
1593     if (tracker->Clusters2Tracks(esd) != 0) {
1594       AliError(Form("HLT %s Clusters2Tracks failed", fgkDetectorName[iDet]));
1595       return kFALSE;
1596     }
1597     if(iDet != 1) {
1598       tracker->UnloadClusters();
1599     }
1600     delete tracker;
1601   }
1602
1603   return kTRUE;
1604 }
1605
1606 //_____________________________________________________________________________
1607 Bool_t AliReconstruction::RunMuonTracking(AliESDEvent*& esd)
1608 {
1609 // run the muon spectrometer tracking
1610
1611   AliCodeTimerAuto("")
1612
1613   if (!fRunLoader) {
1614     AliError("Missing runLoader!");
1615     return kFALSE;
1616   }
1617   Int_t iDet = 7; // for MUON
1618
1619   AliInfo("is running...");
1620
1621   // Get a pointer to the MUON reconstructor
1622   AliReconstructor *reconstructor = GetReconstructor(iDet);
1623   if (!reconstructor) return kFALSE;
1624
1625   
1626   TString detName = fgkDetectorName[iDet];
1627   AliDebug(1, Form("%s tracking", detName.Data()));
1628   AliTracker *tracker =  reconstructor->CreateTracker();
1629   if (!tracker) {
1630     AliWarning(Form("couldn't create a tracker for %s", detName.Data()));
1631     return kFALSE;
1632   }
1633      
1634   // read RecPoints
1635   fLoader[iDet]->LoadRecPoints("read");  
1636
1637   tracker->LoadClusters(fLoader[iDet]->TreeR());
1638   
1639   Int_t rv = tracker->Clusters2Tracks(esd);
1640   
1641   if ( rv )
1642   {
1643     AliError(Form("%s Clusters2Tracks failed", fgkDetectorName[iDet]));
1644     return kFALSE;
1645   }
1646   
1647   fLoader[iDet]->UnloadRecPoints();
1648
1649   tracker->UnloadClusters();
1650   
1651   delete tracker;
1652   
1653   return kTRUE;
1654 }
1655
1656
1657 //_____________________________________________________________________________
1658 Bool_t AliReconstruction::RunTracking(AliESDEvent*& esd)
1659 {
1660 // run the barrel tracking
1661   static Int_t eventNr=0;
1662   AliCodeTimerAuto("")
1663
1664   AliInfo("running tracking");
1665
1666   //Fill the ESD with the T0 info (will be used by the TOF) 
1667   if (fReconstructor[11] && fLoader[11]) {
1668     fLoader[11]->LoadRecPoints("READ");
1669     TTree *treeR = fLoader[11]->TreeR();
1670     GetReconstructor(11)->FillESD((TTree *)NULL,treeR,esd);
1671   }
1672
1673   // pass 1: TPC + ITS inwards
1674   for (Int_t iDet = 1; iDet >= 0; iDet--) {
1675     if (!fTracker[iDet]) continue;
1676     AliDebug(1, Form("%s tracking", fgkDetectorName[iDet]));
1677
1678     // load clusters
1679     fLoader[iDet]->LoadRecPoints("read");
1680     AliSysInfo::AddStamp(Form("RLoadCluster%s_%d",fgkDetectorName[iDet],eventNr),iDet,1, eventNr);
1681     TTree* tree = fLoader[iDet]->TreeR();
1682     if (!tree) {
1683       AliError(Form("Can't get the %s cluster tree", fgkDetectorName[iDet]));
1684       return kFALSE;
1685     }
1686     fTracker[iDet]->LoadClusters(tree);
1687     AliSysInfo::AddStamp(Form("TLoadCluster%s_%d",fgkDetectorName[iDet],eventNr), iDet,2, eventNr);
1688     // run tracking
1689     if (fTracker[iDet]->Clusters2Tracks(esd) != 0) {
1690       AliError(Form("%s Clusters2Tracks failed", fgkDetectorName[iDet]));
1691       return kFALSE;
1692     }
1693     if (fCheckPointLevel > 1) {
1694       WriteESD(esd, Form("%s.tracking", fgkDetectorName[iDet]));
1695     }
1696     // preliminary PID in TPC needed by the ITS tracker
1697     if (iDet == 1) {
1698       GetReconstructor(1)->FillESD((TTree*)NULL, (TTree*)NULL, esd);
1699       AliESDpid::MakePID(esd);
1700     } 
1701     AliSysInfo::AddStamp(Form("Tracking0%s_%d",fgkDetectorName[iDet],eventNr), iDet,3,eventNr);
1702   }
1703
1704   // pass 2: ALL backwards
1705
1706   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
1707     if (!fTracker[iDet]) continue;
1708     AliDebug(1, Form("%s back propagation", fgkDetectorName[iDet]));
1709
1710     // load clusters
1711     if (iDet > 1) {     // all except ITS, TPC
1712       TTree* tree = NULL;
1713       fLoader[iDet]->LoadRecPoints("read");
1714       AliSysInfo::AddStamp(Form("RLoadCluster0%s_%d",fgkDetectorName[iDet],eventNr), iDet,1, eventNr);
1715       tree = fLoader[iDet]->TreeR();
1716       if (!tree) {
1717         AliError(Form("Can't get the %s cluster tree", fgkDetectorName[iDet]));
1718         return kFALSE;
1719       }
1720       fTracker[iDet]->LoadClusters(tree); 
1721       AliSysInfo::AddStamp(Form("TLoadCluster0%s_%d",fgkDetectorName[iDet],eventNr), iDet,2, eventNr);
1722     }
1723
1724     // run tracking
1725     if (iDet>1) // start filling residuals for the "outer" detectors
1726     if (fRunGlobalQA) AliTracker::SetFillResiduals(kTRUE);     
1727
1728     if (fTracker[iDet]->PropagateBack(esd) != 0) {
1729       AliError(Form("%s backward propagation failed", fgkDetectorName[iDet]));
1730       //      return kFALSE;
1731     }
1732     if (fCheckPointLevel > 1) {
1733       WriteESD(esd, Form("%s.back", fgkDetectorName[iDet]));
1734     }
1735
1736     // unload clusters
1737     if (iDet > 2) {     // all except ITS, TPC, TRD
1738       fTracker[iDet]->UnloadClusters();
1739       fLoader[iDet]->UnloadRecPoints();
1740     }
1741     // updated PID in TPC needed by the ITS tracker -MI
1742     if (iDet == 1) {
1743       GetReconstructor(1)->FillESD((TTree*)NULL, (TTree*)NULL, esd);
1744       AliESDpid::MakePID(esd);
1745     }
1746     AliSysInfo::AddStamp(Form("Tracking1%s_%d",fgkDetectorName[iDet],eventNr), iDet,3, eventNr);
1747   }
1748   //stop filling residuals for the "outer" detectors
1749   if (fRunGlobalQA) AliTracker::SetFillResiduals(kFALSE);     
1750
1751   // write space-points to the ESD in case alignment data output
1752   // is switched on
1753   if (fWriteAlignmentData)
1754     WriteAlignmentData(esd);
1755
1756   // pass 3: TRD + TPC + ITS refit inwards
1757
1758   for (Int_t iDet = 2; iDet >= 0; iDet--) {
1759     if (!fTracker[iDet]) continue;
1760     AliDebug(1, Form("%s inward refit", fgkDetectorName[iDet]));
1761
1762     // run tracking
1763     if (iDet<2) // start filling residuals for TPC and ITS
1764     if (fRunGlobalQA) AliTracker::SetFillResiduals(kTRUE);     
1765
1766     if (fTracker[iDet]->RefitInward(esd) != 0) {
1767       AliError(Form("%s inward refit failed", fgkDetectorName[iDet]));
1768       //      return kFALSE;
1769     }
1770     // run postprocessing
1771     if (fTracker[iDet]->PostProcess(esd) != 0) {
1772       AliError(Form("%s postprocessing failed", fgkDetectorName[iDet]));
1773       //      return kFALSE;
1774     }
1775     if (fCheckPointLevel > 1) {
1776       WriteESD(esd, Form("%s.refit", fgkDetectorName[iDet]));
1777     }
1778     AliSysInfo::AddStamp(Form("Tracking2%s_%d",fgkDetectorName[iDet],eventNr), iDet,3, eventNr);
1779     // unload clusters
1780     fTracker[iDet]->UnloadClusters();
1781     AliSysInfo::AddStamp(Form("TUnloadCluster%s_%d",fgkDetectorName[iDet],eventNr), iDet,4, eventNr);
1782     fLoader[iDet]->UnloadRecPoints();
1783     AliSysInfo::AddStamp(Form("RUnloadCluster%s_%d",fgkDetectorName[iDet],eventNr), iDet,5, eventNr);
1784   }
1785   // stop filling residuals for TPC and ITS
1786   if (fRunGlobalQA) AliTracker::SetFillResiduals(kFALSE);     
1787
1788   eventNr++;
1789   return kTRUE;
1790 }
1791
1792 //_____________________________________________________________________________
1793 Bool_t AliReconstruction::CleanESD(AliESDEvent *esd){
1794   //
1795   // Remove the data which are not needed for the physics analysis.
1796   //
1797
1798   Int_t nTracks=esd->GetNumberOfTracks();
1799   Int_t nV0s=esd->GetNumberOfV0s();
1800   AliInfo
1801   (Form("Number of ESD tracks and V0s before cleaning: %d %d",nTracks,nV0s));
1802
1803   Float_t cleanPars[]={fV0DCAmax,fV0CsPmin,fDmax,fZmax};
1804   Bool_t rc=esd->Clean(cleanPars);
1805
1806   nTracks=esd->GetNumberOfTracks();
1807   nV0s=esd->GetNumberOfV0s();
1808   AliInfo
1809   (Form("Number of ESD tracks and V0s after cleaning %d %d",nTracks,nV0s));
1810
1811   return rc;
1812 }
1813
1814 //_____________________________________________________________________________
1815 Bool_t AliReconstruction::FillESD(AliESDEvent*& esd, const TString& detectors)
1816 {
1817 // fill the event summary data
1818
1819   AliCodeTimerAuto("")
1820     static Int_t eventNr=0; 
1821   TString detStr = detectors;
1822   
1823   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
1824   if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
1825     AliReconstructor* reconstructor = GetReconstructor(iDet);
1826     if (!reconstructor) continue;
1827     if (!ReadESD(esd, fgkDetectorName[iDet])) {
1828       AliDebug(1, Form("filling ESD for %s", fgkDetectorName[iDet]));
1829       TTree* clustersTree = NULL;
1830       if (fLoader[iDet]) {
1831         fLoader[iDet]->LoadRecPoints("read");
1832         clustersTree = fLoader[iDet]->TreeR();
1833         if (!clustersTree) {
1834           AliError(Form("Can't get the %s clusters tree", 
1835                         fgkDetectorName[iDet]));
1836           if (fStopOnError) return kFALSE;
1837         }
1838       }
1839       if (fRawReader && !reconstructor->HasDigitConversion()) {
1840         reconstructor->FillESD(fRawReader, clustersTree, esd);
1841       } else {
1842         TTree* digitsTree = NULL;
1843         if (fLoader[iDet]) {
1844           fLoader[iDet]->LoadDigits("read");
1845           digitsTree = fLoader[iDet]->TreeD();
1846           if (!digitsTree) {
1847             AliError(Form("Can't get the %s digits tree", 
1848                           fgkDetectorName[iDet]));
1849             if (fStopOnError) return kFALSE;
1850           }
1851         }
1852         reconstructor->FillESD(digitsTree, clustersTree, esd);
1853         if (fLoader[iDet]) fLoader[iDet]->UnloadDigits();
1854       }
1855       if (fLoader[iDet]) {
1856         fLoader[iDet]->UnloadRecPoints();
1857       }
1858
1859       if (fCheckPointLevel > 2) WriteESD(esd, fgkDetectorName[iDet]);
1860     }
1861   }
1862
1863   if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
1864     AliError(Form("the following detectors were not found: %s", 
1865                   detStr.Data()));
1866     if (fStopOnError) return kFALSE;
1867   }
1868   AliSysInfo::AddStamp(Form("FillESD%d",eventNr), 0,1, eventNr);
1869   eventNr++;
1870   return kTRUE;
1871 }
1872
1873 //_____________________________________________________________________________
1874 Bool_t AliReconstruction::FillTriggerESD(AliESDEvent*& esd)
1875 {
1876   // Reads the trigger decision which is
1877   // stored in Trigger.root file and fills
1878   // the corresponding esd entries
1879
1880   AliCodeTimerAuto("")
1881   
1882   AliInfo("Filling trigger information into the ESD");
1883
1884   AliCentralTrigger *aCTP = NULL;
1885
1886   if (fRawReader) {
1887     AliCTPRawStream input(fRawReader);
1888     if (!input.Next()) {
1889       AliError("No valid CTP (trigger) DDL raw data is found ! The trigger information is not stored in the ESD !");
1890       return kFALSE;
1891     }
1892     esd->SetTriggerMask(input.GetClassMask());
1893     esd->SetTriggerCluster(input.GetClusterMask());
1894
1895     aCTP = new AliCentralTrigger();
1896     TString configstr("");
1897     if (!aCTP->LoadConfiguration(configstr)) { // Load CTP config from OCDB
1898       AliError("No trigger configuration found in OCDB! The trigger classes information will no be stored in ESD!");
1899       delete aCTP;
1900       return kFALSE;
1901     }
1902   }
1903   else {
1904     AliRunLoader *runloader = AliRunLoader::GetRunLoader();
1905     if (runloader) {
1906       if (!runloader->LoadTrigger()) {
1907         aCTP = runloader->GetTrigger();
1908         esd->SetTriggerMask(aCTP->GetClassMask());
1909         esd->SetTriggerCluster(aCTP->GetClusterMask());
1910       }
1911       else {
1912         AliWarning("No trigger can be loaded! The trigger information is not stored in the ESD !");
1913         return kFALSE;
1914       }
1915     }
1916     else {
1917       AliError("No run loader is available! The trigger information is not stored in the ESD !");
1918       return kFALSE;
1919     }
1920   }
1921
1922   // Now fill the trigger class names into AliESDRun object
1923   AliTriggerConfiguration *config = aCTP->GetConfiguration();
1924   if (!config) {
1925     AliError("No trigger configuration has been found! The trigger classes information will no be stored in ESD!");
1926     if (fRawReader) delete aCTP;
1927     return kFALSE;
1928   }
1929
1930   const TObjArray& classesArray = config->GetClasses();
1931   Int_t nclasses = classesArray.GetEntriesFast();
1932   for( Int_t j=0; j<nclasses; j++ ) {
1933     AliTriggerClass* trclass = (AliTriggerClass*)classesArray.At( j );
1934     Int_t trindex = (Int_t)TMath::Log2(trclass->GetMask());
1935     esd->SetTriggerClass(trclass->GetName(),trindex);
1936   }
1937
1938   if (fRawReader) delete aCTP;
1939   return kTRUE;
1940 }
1941
1942
1943
1944
1945
1946 //_____________________________________________________________________________
1947 Bool_t AliReconstruction::FillRawEventHeaderESD(AliESDEvent*& esd)
1948 {
1949   // 
1950   // Filling information from RawReader Header
1951   // 
1952
1953   AliInfo("Filling information from RawReader Header");
1954   esd->SetBunchCrossNumber(0);
1955   esd->SetOrbitNumber(0);
1956   esd->SetPeriodNumber(0);
1957   esd->SetTimeStamp(0);
1958   esd->SetEventType(0);
1959   const AliRawEventHeaderBase * eventHeader = fRawReader->GetEventHeader();
1960   if (eventHeader){
1961
1962     const UInt_t *id = eventHeader->GetP("Id");
1963     esd->SetBunchCrossNumber((id)[1]&0x00000fff);
1964     esd->SetOrbitNumber((((id)[0]<<20)&0xf00000)|(((id)[1]>>12)&0xfffff));
1965     esd->SetPeriodNumber(((id)[0]>>4)&0x0fffffff);
1966
1967     esd->SetTimeStamp((eventHeader->Get("Timestamp")));  
1968     esd->SetEventType((eventHeader->Get("Type")));
1969   }
1970
1971   return kTRUE;
1972 }
1973
1974
1975 //_____________________________________________________________________________
1976 Bool_t AliReconstruction::IsSelected(TString detName, TString& detectors) const
1977 {
1978 // check whether detName is contained in detectors
1979 // if yes, it is removed from detectors
1980
1981   // check if all detectors are selected
1982   if ((detectors.CompareTo("ALL") == 0) ||
1983       detectors.BeginsWith("ALL ") ||
1984       detectors.EndsWith(" ALL") ||
1985       detectors.Contains(" ALL ")) {
1986     detectors = "ALL";
1987     return kTRUE;
1988   }
1989
1990   // search for the given detector
1991   Bool_t result = kFALSE;
1992   if ((detectors.CompareTo(detName) == 0) ||
1993       detectors.BeginsWith(detName+" ") ||
1994       detectors.EndsWith(" "+detName) ||
1995       detectors.Contains(" "+detName+" ")) {
1996     detectors.ReplaceAll(detName, "");
1997     result = kTRUE;
1998   }
1999
2000   // clean up the detectors string
2001   while (detectors.Contains("  ")) detectors.ReplaceAll("  ", " ");
2002   while (detectors.BeginsWith(" ")) detectors.Remove(0, 1);
2003   while (detectors.EndsWith(" ")) detectors.Remove(detectors.Length()-1, 1);
2004
2005   return result;
2006 }
2007
2008 //_____________________________________________________________________________
2009 Bool_t AliReconstruction::InitRunLoader()
2010 {
2011 // get or create the run loader
2012
2013   if (gAlice) delete gAlice;
2014   gAlice = NULL;
2015
2016   if (!gSystem->AccessPathName(fGAliceFileName.Data())) { // galice.root exists
2017     // load all base libraries to get the loader classes
2018     TString libs = gSystem->GetLibraries();
2019     for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
2020       TString detName = fgkDetectorName[iDet];
2021       if (detName == "HLT") continue;
2022       if (libs.Contains("lib" + detName + "base.so")) continue;
2023       gSystem->Load("lib" + detName + "base.so");
2024     }
2025     fRunLoader = AliRunLoader::Open(fGAliceFileName.Data());
2026     if (!fRunLoader) {
2027       AliError(Form("no run loader found in file %s", fGAliceFileName.Data()));
2028       CleanUp();
2029       return kFALSE;
2030     }
2031     fRunLoader->CdGAFile();
2032     if (gFile->GetKey(AliRunLoader::GetGAliceName())) {
2033       if (fRunLoader->LoadgAlice() == 0) {
2034         gAlice = fRunLoader->GetAliRun();
2035         AliTracker::SetFieldMap(gAlice->Field(),fUniformField);
2036       }
2037     }
2038     if (!gAlice && !fRawReader) {
2039       AliError(Form("no gAlice object found in file %s",
2040                     fGAliceFileName.Data()));
2041       CleanUp();
2042       return kFALSE;
2043     }
2044
2045     //PH This is a temporary fix to give access to the kinematics
2046     //PH that is needed for the labels of ITS clusters
2047     fRunLoader->LoadHeader();
2048     fRunLoader->LoadKinematics();
2049
2050   } else {               // galice.root does not exist
2051     if (!fRawReader) {
2052       AliError(Form("the file %s does not exist", fGAliceFileName.Data()));
2053       CleanUp();
2054       return kFALSE;
2055     }
2056     fRunLoader = AliRunLoader::Open(fGAliceFileName.Data(),
2057                                     AliConfig::GetDefaultEventFolderName(),
2058                                     "recreate");
2059     if (!fRunLoader) {
2060       AliError(Form("could not create run loader in file %s", 
2061                     fGAliceFileName.Data()));
2062       CleanUp();
2063       return kFALSE;
2064     }
2065     fIsNewRunLoader = kTRUE;
2066     fRunLoader->MakeTree("E");
2067
2068     if (fNumberOfEventsPerFile > 0)
2069       fRunLoader->SetNumberOfEventsPerFile(fNumberOfEventsPerFile);
2070     else
2071       fRunLoader->SetNumberOfEventsPerFile((UInt_t)-1);
2072   }
2073
2074   return kTRUE;
2075 }
2076
2077 //_____________________________________________________________________________
2078 AliReconstructor* AliReconstruction::GetReconstructor(Int_t iDet)
2079 {
2080 // get the reconstructor object and the loader for a detector
2081
2082   if (fReconstructor[iDet]) return fReconstructor[iDet];
2083
2084   // load the reconstructor object
2085   TPluginManager* pluginManager = gROOT->GetPluginManager();
2086   TString detName = fgkDetectorName[iDet];
2087   TString recName = "Ali" + detName + "Reconstructor";
2088   if (gAlice && !gAlice->GetDetector(detName) && (detName != "HLT")) return NULL;
2089
2090   AliReconstructor* reconstructor = NULL;
2091   // first check if a plugin is defined for the reconstructor
2092   TPluginHandler* pluginHandler = 
2093     pluginManager->FindHandler("AliReconstructor", detName);
2094   // if not, add a plugin for it
2095   if (!pluginHandler) {
2096     AliDebug(1, Form("defining plugin for %s", recName.Data()));
2097     TString libs = gSystem->GetLibraries();
2098     if (libs.Contains("lib" + detName + "base.so") ||
2099         (gSystem->Load("lib" + detName + "base.so") >= 0)) {
2100       pluginManager->AddHandler("AliReconstructor", detName, 
2101                                 recName, detName + "rec", recName + "()");
2102     } else {
2103       pluginManager->AddHandler("AliReconstructor", detName, 
2104                                 recName, detName, recName + "()");
2105     }
2106     pluginHandler = pluginManager->FindHandler("AliReconstructor", detName);
2107   }
2108   if (pluginHandler && (pluginHandler->LoadPlugin() == 0)) {
2109     reconstructor = (AliReconstructor*) pluginHandler->ExecPlugin(0);
2110   }
2111   if (reconstructor) {
2112     TObject* obj = fOptions.FindObject(detName.Data());
2113     if (obj) reconstructor->SetOption(obj->GetTitle());
2114     reconstructor->Init();
2115     fReconstructor[iDet] = reconstructor;
2116   }
2117
2118   // get or create the loader
2119   if (detName != "HLT") {
2120     fLoader[iDet] = fRunLoader->GetLoader(detName + "Loader");
2121     if (!fLoader[iDet]) {
2122       AliConfig::Instance()
2123         ->CreateDetectorFolders(fRunLoader->GetEventFolder(), 
2124                                 detName, detName);
2125       // first check if a plugin is defined for the loader
2126       pluginHandler = 
2127         pluginManager->FindHandler("AliLoader", detName);
2128       // if not, add a plugin for it
2129       if (!pluginHandler) {
2130         TString loaderName = "Ali" + detName + "Loader";
2131         AliDebug(1, Form("defining plugin for %s", loaderName.Data()));
2132         pluginManager->AddHandler("AliLoader", detName, 
2133                                   loaderName, detName + "base", 
2134                                   loaderName + "(const char*, TFolder*)");
2135         pluginHandler = pluginManager->FindHandler("AliLoader", detName);
2136       }
2137       if (pluginHandler && (pluginHandler->LoadPlugin() == 0)) {
2138         fLoader[iDet] = 
2139           (AliLoader*) pluginHandler->ExecPlugin(2, detName.Data(), 
2140                                                  fRunLoader->GetEventFolder());
2141       }
2142       if (!fLoader[iDet]) {   // use default loader
2143         fLoader[iDet] = new AliLoader(detName, fRunLoader->GetEventFolder());
2144       }
2145       if (!fLoader[iDet]) {
2146         AliWarning(Form("couldn't get loader for %s", detName.Data()));
2147         if (fStopOnError) return NULL;
2148       } else {
2149         fRunLoader->AddLoader(fLoader[iDet]);
2150         fRunLoader->CdGAFile();
2151         if (gFile && !gFile->IsWritable()) gFile->ReOpen("UPDATE");
2152         fRunLoader->Write(0, TObject::kOverwrite);
2153       }
2154     }
2155   }
2156       
2157   return reconstructor;
2158 }
2159
2160 //_____________________________________________________________________________
2161 Bool_t AliReconstruction::CreateVertexer()
2162 {
2163 // create the vertexer
2164
2165   fVertexer = NULL;
2166   AliReconstructor* itsReconstructor = GetReconstructor(0);
2167   if (itsReconstructor) {
2168     fVertexer = itsReconstructor->CreateVertexer();
2169   }
2170   if (!fVertexer) {
2171     AliWarning("couldn't create a vertexer for ITS");
2172     if (fStopOnError) return kFALSE;
2173   }
2174
2175   return kTRUE;
2176 }
2177
2178 //_____________________________________________________________________________
2179 Bool_t AliReconstruction::CreateTrackers(const TString& detectors)
2180 {
2181 // create the trackers
2182
2183   TString detStr = detectors;
2184   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
2185     if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
2186     AliReconstructor* reconstructor = GetReconstructor(iDet);
2187     if (!reconstructor) continue;
2188     TString detName = fgkDetectorName[iDet];
2189     if (detName == "HLT") {
2190       fRunHLTTracking = kTRUE;
2191       continue;
2192     }
2193     if (detName == "MUON") {
2194       fRunMuonTracking = kTRUE;
2195       continue;
2196     }
2197
2198
2199     fTracker[iDet] = reconstructor->CreateTracker();
2200     if (!fTracker[iDet] && (iDet < 7)) {
2201       AliWarning(Form("couldn't create a tracker for %s", detName.Data()));
2202       if (fStopOnError) return kFALSE;
2203     }
2204     AliSysInfo::AddStamp(Form("LTracker%s",fgkDetectorName[iDet]), iDet,0);
2205   }
2206
2207   return kTRUE;
2208 }
2209
2210 //_____________________________________________________________________________
2211 void AliReconstruction::CleanUp(TFile* file, TFile* fileOld)
2212 {
2213 // delete trackers and the run loader and close and delete the file
2214
2215   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
2216     delete fReconstructor[iDet];
2217     fReconstructor[iDet] = NULL;
2218     fLoader[iDet] = NULL;
2219     delete fTracker[iDet];
2220     fTracker[iDet] = NULL;
2221 //    delete fQADataMaker[iDet];
2222 //    fQADataMaker[iDet] = NULL;
2223   }
2224   delete fVertexer;
2225   fVertexer = NULL;
2226
2227   if (ftVertexer) delete ftVertexer;
2228   ftVertexer = NULL;
2229   
2230   if(!(AliCDBManager::Instance()->GetCacheFlag())) {
2231         delete fDiamondProfile;
2232         fDiamondProfile = NULL;
2233         delete fDiamondProfileTPC;
2234         fDiamondProfileTPC = NULL;
2235         delete fGRPList;
2236         fGRPList = NULL;
2237   }
2238
2239
2240   delete fRunLoader;
2241   fRunLoader = NULL;
2242   delete fRawReader;
2243   fRawReader = NULL;
2244   if (fParentRawReader) delete fParentRawReader;
2245   fParentRawReader=NULL;
2246
2247   if (file) {
2248     file->Close();
2249     delete file;
2250   }
2251
2252   if (fileOld) {
2253     fileOld->Close();
2254     delete fileOld;
2255     gSystem->Unlink("AliESDs.old.root");
2256   }
2257
2258 }
2259
2260 //_____________________________________________________________________________
2261
2262 Bool_t AliReconstruction::ReadESD(AliESDEvent*& esd, const char* recStep) const
2263 {
2264 // read the ESD event from a file
2265
2266   if (!esd) return kFALSE;
2267   char fileName[256];
2268   sprintf(fileName, "ESD_%d.%d_%s.root", 
2269           esd->GetRunNumber(), esd->GetEventNumberInFile(), recStep);
2270   if (gSystem->AccessPathName(fileName)) return kFALSE;
2271
2272   AliInfo(Form("reading ESD from file %s", fileName));
2273   AliDebug(1, Form("reading ESD from file %s", fileName));
2274   TFile* file = TFile::Open(fileName);
2275   if (!file || !file->IsOpen()) {
2276     AliError(Form("opening %s failed", fileName));
2277     delete file;
2278     return kFALSE;
2279   }
2280
2281   gROOT->cd();
2282   delete esd;
2283   esd = (AliESDEvent*) file->Get("ESD");
2284   file->Close();
2285   delete file;
2286   return kTRUE;
2287
2288 }
2289
2290
2291
2292 //_____________________________________________________________________________
2293 void AliReconstruction::WriteESD(AliESDEvent* esd, const char* recStep) const
2294 {
2295 // write the ESD event to a file
2296
2297   if (!esd) return;
2298   char fileName[256];
2299   sprintf(fileName, "ESD_%d.%d_%s.root", 
2300           esd->GetRunNumber(), esd->GetEventNumberInFile(), recStep);
2301
2302   AliDebug(1, Form("writing ESD to file %s", fileName));
2303   TFile* file = TFile::Open(fileName, "recreate");
2304   if (!file || !file->IsOpen()) {
2305     AliError(Form("opening %s failed", fileName));
2306   } else {
2307     esd->Write("ESD");
2308     file->Close();
2309   }
2310   delete file;
2311 }
2312
2313
2314 void AliReconstruction::WriteAlignmentData(AliESDEvent* esd)
2315 {
2316   // Write space-points which are then used in the alignment procedures
2317   // For the moment only ITS, TRD and TPC
2318
2319   // Load TOF clusters
2320   if (fTracker[3]){
2321     fLoader[3]->LoadRecPoints("read");
2322     TTree* tree = fLoader[3]->TreeR();
2323     if (!tree) {
2324       AliError(Form("Can't get the %s cluster tree", fgkDetectorName[3]));
2325       return;
2326     }
2327     fTracker[3]->LoadClusters(tree);
2328   }
2329   Int_t ntracks = esd->GetNumberOfTracks();
2330   for (Int_t itrack = 0; itrack < ntracks; itrack++)
2331     {
2332       AliESDtrack *track = esd->GetTrack(itrack);
2333       Int_t nsp = 0;
2334       Int_t idx[200];
2335       for (Int_t iDet = 3; iDet >= 0; iDet--)
2336         nsp += track->GetNcls(iDet);
2337       if (nsp) {
2338         AliTrackPointArray *sp = new AliTrackPointArray(nsp);
2339         track->SetTrackPointArray(sp);
2340         Int_t isptrack = 0;
2341         for (Int_t iDet = 3; iDet >= 0; iDet--) {
2342           AliTracker *tracker = fTracker[iDet];
2343           if (!tracker) continue;
2344           Int_t nspdet = track->GetNcls(iDet);
2345           if (nspdet <= 0) continue;
2346           track->GetClusters(iDet,idx);
2347           AliTrackPoint p;
2348           Int_t isp = 0;
2349           Int_t isp2 = 0;
2350           while (isp2 < nspdet) {
2351             Bool_t isvalid;
2352             TString dets = fgkDetectorName[iDet];
2353             if ((fUseTrackingErrorsForAlignment.CompareTo(dets) == 0) ||
2354             fUseTrackingErrorsForAlignment.BeginsWith(dets+" ") ||
2355             fUseTrackingErrorsForAlignment.EndsWith(" "+dets) ||
2356             fUseTrackingErrorsForAlignment.Contains(" "+dets+" ")) {
2357               isvalid = tracker->GetTrackPointTrackingError(idx[isp2],p,track);
2358             } else {
2359               isvalid = tracker->GetTrackPoint(idx[isp2],p); 
2360             } 
2361             isp2++;
2362             const Int_t kNTPCmax = 159;
2363             if (iDet==1 && isp2>kNTPCmax) break;   // to be fixed
2364             if (!isvalid) continue;
2365             sp->AddPoint(isptrack,&p); isptrack++; isp++;
2366           }
2367         }       
2368       }
2369     }
2370   if (fTracker[3]){
2371     fTracker[3]->UnloadClusters();
2372     fLoader[3]->UnloadRecPoints();
2373   }
2374 }
2375
2376 //_____________________________________________________________________________
2377 void AliReconstruction::FillRawDataErrorLog(Int_t iEvent, AliESDEvent* esd)
2378 {
2379   // The method reads the raw-data error log
2380   // accumulated within the rawReader.
2381   // It extracts the raw-data errors related to
2382   // the current event and stores them into
2383   // a TClonesArray inside the esd object.
2384
2385   if (!fRawReader) return;
2386
2387   for(Int_t i = 0; i < fRawReader->GetNumberOfErrorLogs(); i++) {
2388
2389     AliRawDataErrorLog *log = fRawReader->GetErrorLog(i);
2390     if (!log) continue;
2391     if (iEvent != log->GetEventNumber()) continue;
2392
2393     esd->AddRawDataErrorLog(log);
2394   }
2395
2396 }
2397
2398 TNamed* AliReconstruction::CopyFileToTNamed(TString fPath,TString fName){
2399   // Dump a file content into a char in TNamed
2400   ifstream in;
2401   in.open(fPath.Data(),ios::in | ios::binary|ios::ate);
2402   Int_t kBytes = (Int_t)in.tellg();
2403   printf("Size: %d \n",kBytes);
2404   TNamed *fn = 0;
2405   if(in.good()){
2406     char* memblock = new char [kBytes];
2407     in.seekg (0, ios::beg);
2408     in.read (memblock, kBytes);
2409     in.close();
2410     TString fData(memblock,kBytes);
2411     fn = new TNamed(fName,fData);
2412     printf("fData Size: %d \n",fData.Sizeof());
2413     printf("fName Size: %d \n",fName.Sizeof());
2414     printf("fn    Size: %d \n",fn->Sizeof());
2415     delete[] memblock;
2416   }
2417   else{
2418     AliInfo(Form("Could not Open %s\n",fPath.Data()));
2419   }
2420
2421   return fn;
2422 }
2423
2424 void AliReconstruction::TNamedToFile(TTree* fTree, TString fName){
2425   // This is not really needed in AliReconstruction at the moment
2426   // but can serve as a template
2427
2428   TList *fList = fTree->GetUserInfo();
2429   TNamed *fn = (TNamed*)fList->FindObject(fName.Data());
2430   printf("fn Size: %d \n",fn->Sizeof());
2431
2432   TString fTmp(fn->GetName()); // to be 100% sure in principle fName also works
2433   const char* cdata = fn->GetTitle();
2434   printf("fTmp Size %d\n",fTmp.Sizeof());
2435
2436   int size = fn->Sizeof()-fTmp.Sizeof()-sizeof(UChar_t)-sizeof(Int_t); // see dfinition of TString::SizeOf()...
2437   printf("calculated size %d\n",size);
2438   ofstream out(fName.Data(),ios::out | ios::binary);
2439   out.write(cdata,size);
2440   out.close();
2441
2442 }
2443   
2444 //_____________________________________________________________________________
2445 AliQADataMakerRec * AliReconstruction::GetQADataMaker(Int_t iDet)
2446 {
2447  // get the quality assurance data maker object and the loader for a detector
2448
2449   if (fQADataMaker[iDet]) 
2450     return fQADataMaker[iDet];
2451
2452   AliQADataMakerRec * qadm = NULL;
2453   if (iDet == fgkNDetectors) { //Global QA
2454      qadm = new AliGlobalQADataMaker();
2455      fQADataMaker[iDet] = qadm;
2456      return qadm;
2457   }
2458
2459   // load the QA data maker object
2460   TPluginManager* pluginManager = gROOT->GetPluginManager();
2461   TString detName = fgkDetectorName[iDet];
2462   TString qadmName = "Ali" + detName + "QADataMakerRec";
2463   if (gAlice && !gAlice->GetDetector(detName) && (detName != "HLT")) 
2464     return NULL;
2465
2466   // first check if a plugin is defined for the quality assurance data maker
2467   TPluginHandler* pluginHandler = pluginManager->FindHandler("AliQADataMakerRec", detName);
2468   // if not, add a plugin for it
2469   if (!pluginHandler) {
2470     AliDebug(1, Form("defining plugin for %s", qadmName.Data()));
2471     TString libs = gSystem->GetLibraries();
2472     if (libs.Contains("lib" + detName + "base.so") ||
2473         (gSystem->Load("lib" + detName + "base.so") >= 0)) {
2474       pluginManager->AddHandler("AliQADataMakerRec", detName, 
2475                                 qadmName, detName + "qadm", qadmName + "()");
2476     } else {
2477       pluginManager->AddHandler("AliQADataMakerRec", detName, 
2478                                 qadmName, detName, qadmName + "()");
2479     }
2480     pluginHandler = pluginManager->FindHandler("AliQADataMakerRec", detName);
2481   }
2482   if (pluginHandler && (pluginHandler->LoadPlugin() == 0)) {
2483     qadm = (AliQADataMakerRec *) pluginHandler->ExecPlugin(0);
2484   }
2485
2486   fQADataMaker[iDet] = qadm;
2487
2488   return qadm;
2489 }
2490
2491 //_____________________________________________________________________________
2492 Bool_t AliReconstruction::RunQA(const char* detectors, AliESDEvent *& esd)
2493 {
2494   // run the Quality Assurance data producer
2495
2496   AliCodeTimerAuto("")
2497   TString detStr = detectors;
2498   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
2499    if (!IsSelected(fgkDetectorName[iDet], detStr)) 
2500      continue;
2501    AliQADataMakerRec * qadm = GetQADataMaker(iDet);
2502    if (!qadm) 
2503      continue;
2504    AliCodeTimerStart(Form("running quality assurance data maker for %s", fgkDetectorName[iDet]));
2505    AliInfo(Form("running quality assurance data maker for %s", fgkDetectorName[iDet]));
2506     
2507    qadm->Exec(AliQA::kESDS, esd) ; 
2508    qadm->Increment() ; 
2509
2510    AliCodeTimerStop(Form("running quality assurance data maker for %s", fgkDetectorName[iDet]));
2511  }
2512  if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
2513    AliError(Form("the following detectors were not found: %s",
2514                  detStr.Data()));
2515    if (fStopOnError) 
2516      return kFALSE;
2517  }
2518  
2519  return kTRUE;
2520   
2521 }
2522
2523 //_____________________________________________________________________________
2524 void AliReconstruction::CheckQA()
2525 {
2526 // check the QA of SIM for this run and remove the detectors 
2527 // with status Fatal
2528   
2529         TString newRunLocalReconstruction ; 
2530         TString newRunTracking ;
2531         TString newFillESD ;
2532          
2533         for (Int_t iDet = 0; iDet < AliQA::kNDET; iDet++) {
2534                 TString detName(AliQA::GetDetName(iDet)) ;
2535                 AliQA * qa = AliQA::Instance(AliQA::DETECTORINDEX_t(iDet)) ; 
2536                 if ( qa->IsSet(AliQA::DETECTORINDEX_t(iDet), AliQA::kSIM, AliQA::kFATAL)) {
2537                                 AliInfo(Form("QA status for %s in Hits and/or SDIGITS  and/or Digits was Fatal; No reconstruction performed", detName.Data())) ;
2538                 } else {
2539                         if ( fRunLocalReconstruction.Contains(AliQA::GetDetName(iDet)) || 
2540                                         fRunLocalReconstruction.Contains("ALL") )  {
2541                                 newRunLocalReconstruction += detName ; 
2542                                 newRunLocalReconstruction += " " ;                      
2543                         }
2544                         if ( fRunTracking.Contains(AliQA::GetDetName(iDet)) || 
2545                                         fRunTracking.Contains("ALL") )  {
2546                                 newRunTracking += detName ; 
2547                                 newRunTracking += " " ;                         
2548                         }
2549                         if ( fFillESD.Contains(AliQA::GetDetName(iDet)) || 
2550                                         fFillESD.Contains("ALL") )  {
2551                                 newFillESD += detName ; 
2552                                 newFillESD += " " ;                     
2553                         }
2554                 }
2555         }
2556         fRunLocalReconstruction = newRunLocalReconstruction ; 
2557         fRunTracking            = newRunTracking ; 
2558         fFillESD                = newFillESD ; 
2559 }
2560
2561 //_____________________________________________________________________________
2562 Int_t AliReconstruction::GetDetIndex(const char* detector)
2563 {
2564   // return the detector index corresponding to detector
2565   Int_t index = -1 ; 
2566   for (index = 0; index < fgkNDetectors ; index++) {
2567     if ( strcmp(detector, fgkDetectorName[index]) == 0 )
2568         break ; 
2569   }     
2570   return index ; 
2571 }
2572 //_____________________________________________________________________________
2573 Bool_t AliReconstruction::FinishPlaneEff() {
2574  //
2575  // Here execute all the necessary operationis, at the end of the tracking phase,
2576  // in case that evaluation of PlaneEfficiencies was required for some detector. 
2577  // E.g., write into a DataBase file the PlaneEfficiency which have been evaluated. 
2578  //
2579  // This Preliminary version works only FOR ITS !!!!!
2580  // other detectors (TOF,TRD, etc. have to develop their specific codes)
2581  //
2582  //  Input: none
2583  //  Return: kTRUE if all operations have been done properly, kFALSE otherwise 
2584  //
2585  Bool_t ret=kFALSE;
2586  //for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
2587  for (Int_t iDet = 0; iDet < 1; iDet++) { // for the time being only ITS  
2588    //if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
2589    if(fTracker[iDet]) {
2590       AliPlaneEff *planeeff=fTracker[iDet]->GetPlaneEff(); 
2591       ret=planeeff->WriteIntoCDB();
2592       if(planeeff->GetCreateHistos()) {
2593         TString name="PlaneEffHisto";
2594         name+=fgkDetectorName[iDet];
2595         name+=".root";
2596         ret*=planeeff->WriteHistosToFile(name,"RECREATE");
2597       }
2598    }
2599  }
2600  return ret;
2601 }
2602 //_____________________________________________________________________________
2603 Bool_t AliReconstruction::InitPlaneEff() {
2604 //
2605  // Here execute all the necessary operations, before of the tracking phase,
2606  // for the evaluation of PlaneEfficiencies, in case required for some detectors.
2607  // E.g., read from a DataBase file a first evaluation of the PlaneEfficiency 
2608  // which should be updated/recalculated.
2609  //
2610  // This Preliminary version will work only FOR ITS !!!!!
2611  // other detectors (TOF,TRD, etc. have to develop their specific codes)
2612  //
2613  //  Input: none
2614  //  Return: kTRUE if all operations have been done properly, kFALSE otherwise
2615  //
2616  AliWarning(Form("Implementation of this method not yet done !! Method return kTRUE"));
2617  return kTRUE;
2618 }