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