]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/AliReconstruction.cxx
76016869cbee0cd898f9d078093fe219d2d16729
[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 //                                                                           //
109 ///////////////////////////////////////////////////////////////////////////////
110
111 #include <TArrayF.h>
112 #include <TFile.h>
113 #include <TList.h>
114 #include <TSystem.h>
115 #include <TROOT.h>
116 #include <TPluginManager.h>
117 #include <TGeoManager.h>
118 #include <TLorentzVector.h>
119 #include <TArrayS.h>
120 #include <TArrayD.h>
121 #include <TObjArray.h>
122 #include <TMap.h>
123 #include <TChain.h>
124 #include <TProof.h>
125 #include <TProofOutputFile.h>
126 #include <TParameter.h>
127
128 #include "AliReconstruction.h"
129 #include "AliCodeTimer.h"
130 #include "AliReconstructor.h"
131 #include "AliLog.h"
132 #include "AliRunLoader.h"
133 #include "AliRun.h"
134 #include "AliRawReaderFile.h"
135 #include "AliRawReaderDate.h"
136 #include "AliRawReaderRoot.h"
137 #include "AliRawEventHeaderBase.h"
138 #include "AliRawEvent.h"
139 #include "AliESDEvent.h"
140 #include "AliESDMuonTrack.h"
141 #include "AliESDfriend.h"
142 #include "AliESDVertex.h"
143 #include "AliESDcascade.h"
144 #include "AliESDkink.h"
145 #include "AliESDtrack.h"
146 #include "AliESDCaloCluster.h"
147 #include "AliESDCaloCells.h"
148 #include "AliMultiplicity.h"
149 #include "AliTracker.h"
150 #include "AliVertexer.h"
151 #include "AliVertexerTracks.h"
152 #include "AliV0vertexer.h"
153 #include "AliCascadeVertexer.h"
154 #include "AliHeader.h"
155 #include "AliGenEventHeader.h"
156 #include "AliPID.h"
157 #include "AliESDpid.h"
158 #include "AliESDtrack.h"
159 #include "AliESDPmdTrack.h"
160
161 #include "AliESDTagCreator.h"
162
163 #include "AliGeomManager.h"
164 #include "AliTrackPointArray.h"
165 #include "AliCDBManager.h"
166 #include "AliCDBStorage.h"
167 #include "AliCDBEntry.h"
168 #include "AliAlignObj.h"
169
170 #include "AliCentralTrigger.h"
171 #include "AliTriggerConfiguration.h"
172 #include "AliTriggerClass.h"
173 #include "AliTriggerCluster.h"
174 #include "AliCTPRawStream.h"
175
176 #include "AliQADataMakerRec.h" 
177 #include "AliGlobalQADataMaker.h" 
178 #include "AliQA.h"
179 #include "AliQADataMakerSteer.h"
180
181 #include "AliPlaneEff.h"
182
183 #include "AliSysInfo.h" // memory snapshots
184 #include "AliRawHLTManager.h"
185
186 #include "AliMagWrapCheb.h"
187
188 #include "AliDetectorRecoParam.h"
189 #include "AliRunInfo.h"
190 #include "AliEventInfo.h"
191
192 #include "AliDAQ.h"
193
194 ClassImp(AliReconstruction)
195
196 //_____________________________________________________________________________
197 const char* AliReconstruction::fgkDetectorName[AliReconstruction::fgkNDetectors] = {"ITS", "TPC", "TRD", "TOF", "PHOS", "HMPID", "EMCAL", "MUON", "FMD", "ZDC", "PMD", "T0", "VZERO", "ACORDE", "HLT"};
198
199 //_____________________________________________________________________________
200 AliReconstruction::AliReconstruction(const char* gAliceFilename) :
201   TSelector(),
202   fUniformField(kFALSE),
203   fForcedFieldMap(NULL),
204   fRunVertexFinder(kTRUE),
205   fRunVertexFinderTracks(kTRUE),
206   fRunHLTTracking(kFALSE),
207   fRunMuonTracking(kFALSE),
208   fRunV0Finder(kTRUE),
209   fRunCascadeFinder(kTRUE),
210   fStopOnError(kFALSE),
211   fWriteAlignmentData(kFALSE),
212   fWriteESDfriend(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   fLoadCDB(""),
225   fUseTrackingErrorsForAlignment(""),
226   fGAliceFileName(gAliceFilename),
227   fRawInput(""),
228   fEquipIdMap(""),
229   fFirstEvent(0),
230   fLastEvent(-1),
231   fNumberOfEventsPerFile(1),
232   fOptions(),
233   fLoadAlignFromCDB(kTRUE),
234   fLoadAlignData("ALL"),
235   fESDPar(""),
236   fUseHLTData(),
237   fRunInfo(NULL),
238   fEventInfo(),
239
240   fRunLoader(NULL),
241   fRawReader(NULL),
242   fParentRawReader(NULL),
243
244   fRecoParam(),
245
246   fVertexer(NULL),
247   fDiamondProfile(NULL),
248   fDiamondProfileTPC(NULL),
249   fMeanVertexConstraint(kTRUE),
250
251   fGRPData(NULL),
252
253   fAlignObjArray(NULL),
254   fCDBUri(),
255   fSpecCDBUri(), 
256   fInitCDBCalled(kFALSE),
257   fSetRunNumberFromDataCalled(kFALSE),
258   fQADetectors("ALL"), 
259   fQASteer(NULL),  
260   fQATasks("ALL"), 
261   fRunQA(kTRUE),  
262   fRunGlobalQA(kTRUE),
263   fInLoopQA(kFALSE),
264   fSameQACycle(kFALSE),
265
266   fRunPlaneEff(kFALSE),
267
268   fesd(NULL),
269   fhltesd(NULL),
270   fesdf(NULL),
271   ffile(NULL),
272   ftree(NULL),
273   fhlttree(NULL),
274   ftVertexer(NULL),
275   fIsNewRunLoader(kFALSE),
276   fRunAliEVE(kFALSE),
277   fChain(NULL)
278 {
279 // create reconstruction object with default parameters
280   gGeoManager = NULL;
281   
282   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
283     fReconstructor[iDet] = NULL;
284     fLoader[iDet] = NULL;
285     fTracker[iDet] = NULL;
286     fQACycles[iDet] = 999999;   
287   }
288   fQATasks = Form("%d %d %d", AliQA::kRAWS, AliQA::kRECPOINTS, AliQA::kESDS) ; 
289   AliPID pid;
290 }
291
292 //_____________________________________________________________________________
293 AliReconstruction::AliReconstruction(const AliReconstruction& rec) :
294   TSelector(),
295   fUniformField(rec.fUniformField),
296   fForcedFieldMap(NULL),
297   fRunVertexFinder(rec.fRunVertexFinder),
298   fRunVertexFinderTracks(rec.fRunVertexFinderTracks),
299   fRunHLTTracking(rec.fRunHLTTracking),
300   fRunMuonTracking(rec.fRunMuonTracking),
301   fRunV0Finder(rec.fRunV0Finder),
302   fRunCascadeFinder(rec.fRunCascadeFinder),
303   fStopOnError(rec.fStopOnError),
304   fWriteAlignmentData(rec.fWriteAlignmentData),
305   fWriteESDfriend(rec.fWriteESDfriend),
306   fFillTriggerESD(rec.fFillTriggerESD),
307
308   fCleanESD(rec.fCleanESD),
309   fV0DCAmax(rec.fV0DCAmax),
310   fV0CsPmin(rec.fV0CsPmin),
311   fDmax(rec.fDmax),
312   fZmax(rec.fZmax),
313
314   fRunLocalReconstruction(rec.fRunLocalReconstruction),
315   fRunTracking(rec.fRunTracking),
316   fFillESD(rec.fFillESD),
317   fLoadCDB(rec.fLoadCDB),
318   fUseTrackingErrorsForAlignment(rec.fUseTrackingErrorsForAlignment),
319   fGAliceFileName(rec.fGAliceFileName),
320   fRawInput(rec.fRawInput),
321   fEquipIdMap(rec.fEquipIdMap),
322   fFirstEvent(rec.fFirstEvent),
323   fLastEvent(rec.fLastEvent),
324   fNumberOfEventsPerFile(rec.fNumberOfEventsPerFile),
325   fOptions(),
326   fLoadAlignFromCDB(rec.fLoadAlignFromCDB),
327   fLoadAlignData(rec.fLoadAlignData),
328   fESDPar(rec.fESDPar),
329   fUseHLTData(rec.fUseHLTData),
330   fRunInfo(NULL),
331   fEventInfo(),
332
333   fRunLoader(NULL),
334   fRawReader(NULL),
335   fParentRawReader(NULL),
336
337   fRecoParam(rec.fRecoParam),
338
339   fVertexer(NULL),
340   fDiamondProfile(rec.fDiamondProfile),
341   fDiamondProfileTPC(rec.fDiamondProfileTPC),
342   fMeanVertexConstraint(rec.fMeanVertexConstraint),
343
344   fGRPData(NULL),
345
346   fAlignObjArray(rec.fAlignObjArray),
347   fCDBUri(rec.fCDBUri),
348   fSpecCDBUri(), 
349   fInitCDBCalled(rec.fInitCDBCalled),
350   fSetRunNumberFromDataCalled(rec.fSetRunNumberFromDataCalled),
351   fQADetectors(rec.fQADetectors), 
352   fQASteer(NULL),  
353   fQATasks(rec.fQATasks), 
354   fRunQA(rec.fRunQA),  
355   fRunGlobalQA(rec.fRunGlobalQA),
356   fInLoopQA(rec.fInLoopQA),
357   fSameQACycle(rec.fSameQACycle),
358   fRunPlaneEff(rec.fRunPlaneEff),
359
360   fesd(NULL),
361   fhltesd(NULL),
362   fesdf(NULL),
363   ffile(NULL),
364   ftree(NULL),
365   fhlttree(NULL),
366   ftVertexer(NULL),
367   fIsNewRunLoader(rec.fIsNewRunLoader),
368   fRunAliEVE(kFALSE),
369   fChain(NULL)
370 {
371 // copy constructor
372
373   for (Int_t i = 0; i < rec.fOptions.GetEntriesFast(); i++) {
374     if (rec.fOptions[i]) fOptions.Add(rec.fOptions[i]->Clone());
375   }
376   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
377     fReconstructor[iDet] = NULL;
378     fLoader[iDet] = NULL;
379     fTracker[iDet] = NULL;
380     fQACycles[iDet] = rec.fQACycles[iDet];      
381   }
382   for (Int_t i = 0; i < rec.fSpecCDBUri.GetEntriesFast(); i++) {
383     if (rec.fSpecCDBUri[i]) fSpecCDBUri.Add(rec.fSpecCDBUri[i]->Clone());
384   }
385
386 }
387
388 //_____________________________________________________________________________
389 AliReconstruction& AliReconstruction::operator = (const AliReconstruction& rec)
390 {
391 // assignment operator
392 // Used in PROOF mode
393 // Be very careful while modifing it!
394 // Simple rules to follow:
395 // for persistent data members - use their assignment operators
396 // for non-persistent ones - do nothing or take the default values from constructor
397 // TSelector members should not be touched
398   if(&rec == this) return *this;
399
400   fUniformField          = rec.fUniformField;
401   fForcedFieldMap        = NULL;
402   fRunVertexFinder       = rec.fRunVertexFinder;
403   fRunVertexFinderTracks = rec.fRunVertexFinderTracks;
404   fRunHLTTracking        = rec.fRunHLTTracking;
405   fRunMuonTracking       = rec.fRunMuonTracking;
406   fRunV0Finder           = rec.fRunV0Finder;
407   fRunCascadeFinder      = rec.fRunCascadeFinder;
408   fStopOnError           = rec.fStopOnError;
409   fWriteAlignmentData    = rec.fWriteAlignmentData;
410   fWriteESDfriend        = rec.fWriteESDfriend;
411   fFillTriggerESD        = rec.fFillTriggerESD;
412
413   fCleanESD  = rec.fCleanESD;
414   fV0DCAmax  = rec.fV0DCAmax;
415   fV0CsPmin  = rec.fV0CsPmin;
416   fDmax      = rec.fDmax;
417   fZmax      = rec.fZmax;
418
419   fRunLocalReconstruction        = rec.fRunLocalReconstruction;
420   fRunTracking                   = rec.fRunTracking;
421   fFillESD                       = rec.fFillESD;
422   fLoadCDB                       = rec.fLoadCDB;
423   fUseTrackingErrorsForAlignment = rec.fUseTrackingErrorsForAlignment;
424   fGAliceFileName                = rec.fGAliceFileName;
425   fRawInput                      = rec.fRawInput;
426   fEquipIdMap                    = rec.fEquipIdMap;
427   fFirstEvent                    = rec.fFirstEvent;
428   fLastEvent                     = rec.fLastEvent;
429   fNumberOfEventsPerFile         = rec.fNumberOfEventsPerFile;
430
431   for (Int_t i = 0; i < rec.fOptions.GetEntriesFast(); i++) {
432     if (rec.fOptions[i]) fOptions.Add(rec.fOptions[i]->Clone());
433   }
434
435   fLoadAlignFromCDB              = rec.fLoadAlignFromCDB;
436   fLoadAlignData                 = rec.fLoadAlignData;
437   fESDPar                        = rec.fESDPar;
438   fUseHLTData                    = rec.fUseHLTData;
439
440   delete fRunInfo; fRunInfo = NULL;
441   if (rec.fRunInfo) fRunInfo = new AliRunInfo(*rec.fRunInfo);
442
443   fEventInfo                     = rec.fEventInfo;
444
445   fRunLoader       = NULL;
446   fRawReader       = NULL;
447   fParentRawReader = NULL;
448
449   fRecoParam = rec.fRecoParam;
450
451   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
452     delete fReconstructor[iDet]; fReconstructor[iDet] = NULL;
453     delete fLoader[iDet]; fLoader[iDet] = NULL;
454     delete fTracker[iDet]; fTracker[iDet] = NULL;
455     fQACycles[iDet] = rec.fQACycles[iDet];      
456   }
457
458   fVertexer             = NULL;
459   delete fDiamondProfile; fDiamondProfile = NULL;
460   if (rec.fDiamondProfile) fDiamondProfile = new AliESDVertex(*rec.fDiamondProfile);
461   delete fDiamondProfileTPC; fDiamondProfileTPC = NULL;
462   if (rec.fDiamondProfileTPC) fDiamondProfileTPC = new AliESDVertex(*rec.fDiamondProfileTPC);
463   fMeanVertexConstraint = rec.fMeanVertexConstraint;
464
465   delete fGRPData; fGRPData = NULL;
466   if (rec.fGRPData) fGRPData = (TMap*)((rec.fGRPData)->Clone());
467
468   delete fAlignObjArray; fAlignObjArray = NULL;
469
470   fCDBUri        = "";
471   fSpecCDBUri.Delete();
472   fInitCDBCalled               = rec.fInitCDBCalled;
473   fSetRunNumberFromDataCalled  = rec.fSetRunNumberFromDataCalled;
474   fQADetectors                 = rec.fQADetectors;
475   fQASteer                     = NULL;  
476   fQATasks                     = rec.fQATasks; 
477   fRunQA                       = rec.fRunQA;  
478   fRunGlobalQA                 = rec.fRunGlobalQA;
479   fInLoopQA                    = rec.fInLoopQA;
480   fSameQACycle                 = rec.fSameQACycle;
481   fRunPlaneEff                 = rec.fRunPlaneEff;
482
483   fesd     = NULL;
484   fhltesd  = NULL;
485   fesdf    = NULL;
486   ffile    = NULL;
487   ftree    = NULL;
488   fhlttree = NULL;
489   ftVertexer = NULL;
490   fIsNewRunLoader = rec.fIsNewRunLoader;
491   fRunAliEVE = kFALSE;
492   fChain = NULL;
493
494   return *this;
495 }
496
497 //_____________________________________________________________________________
498 AliReconstruction::~AliReconstruction()
499 {
500 // clean up
501
502   CleanUp();
503   delete fForcedFieldMap;
504   fOptions.Delete();
505   if (fAlignObjArray) {
506     fAlignObjArray->Delete();
507     delete fAlignObjArray;
508   }
509   fSpecCDBUri.Delete();
510   delete fQASteer;
511   AliCodeTimer::Instance()->Print();
512 }
513
514 //_____________________________________________________________________________
515 void AliReconstruction::InitCDB()
516 {
517 // activate a default CDB storage
518 // First check if we have any CDB storage set, because it is used 
519 // to retrieve the calibration and alignment constants
520   AliCodeTimerAuto("");
521
522   if (fInitCDBCalled) return;
523   fInitCDBCalled = kTRUE;
524
525   AliCDBManager* man = AliCDBManager::Instance();
526   if (man->IsDefaultStorageSet())
527   {
528     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
529     AliWarning("Default CDB storage has been already set !");
530     AliWarning(Form("Ignoring the default storage declared in AliReconstruction: %s",fCDBUri.Data()));
531     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
532     fCDBUri = man->GetDefaultStorage()->GetURI();
533   }
534   else {
535     if (fCDBUri.Length() > 0) 
536     {
537         AliDebug(2,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
538         AliDebug(2, Form("Default CDB storage is set to: %s", fCDBUri.Data()));
539         AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
540     } else {
541         fCDBUri="local://$ALICE_ROOT";
542         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
543         AliWarning("Default CDB storage not yet set !!!!");
544         AliWarning(Form("Setting it now to: %s", fCDBUri.Data()));
545         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
546                 
547     }
548     man->SetDefaultStorage(fCDBUri);
549   }
550
551   // Now activate the detector specific CDB storage locations
552   for (Int_t i = 0; i < fSpecCDBUri.GetEntriesFast(); i++) {
553     TObject* obj = fSpecCDBUri[i];
554     if (!obj) continue;
555     AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
556     AliDebug(2, Form("Specific CDB storage for %s is set to: %s",obj->GetName(),obj->GetTitle()));
557     AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
558     man->SetSpecificStorage(obj->GetName(), obj->GetTitle());
559   }
560   AliSysInfo::AddStamp("InitCDB");
561 }
562
563 //_____________________________________________________________________________
564 void AliReconstruction::SetDefaultStorage(const char* uri) {
565 // Store the desired default CDB storage location
566 // Activate it later within the Run() method
567
568   fCDBUri = uri;
569
570 }
571
572 //_____________________________________________________________________________
573 void AliReconstruction::SetSpecificStorage(const char* calibType, const char* uri) {
574 // Store a detector-specific CDB storage location
575 // Activate it later within the Run() method
576
577   AliCDBPath aPath(calibType);
578   if(!aPath.IsValid()){
579         // if calibType is not wildcard but it is a valid detector, add "/*" to make it a valid path
580         for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
581                 if(!strcmp(calibType, fgkDetectorName[iDet])) {
582                         aPath.SetPath(Form("%s/*", calibType));
583                         AliInfo(Form("Path for specific storage set to %s", aPath.GetPath().Data()));
584                         break;
585                 }
586         }
587         if(!aPath.IsValid()){
588                 AliError(Form("Not a valid path or detector: %s", calibType));
589                 return;
590         }
591   }
592
593 //  // check that calibType refers to a "valid" detector name
594 //  Bool_t isDetector = kFALSE;
595 //  for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
596 //    TString detName = fgkDetectorName[iDet];
597 //    if(aPath.GetLevel0() == detName) {
598 //      isDetector = kTRUE;
599 //      break;
600 //    }
601 //  }
602 //
603 //  if(!isDetector) {
604 //      AliError(Form("Not a valid detector: %s", aPath.GetLevel0().Data()));
605 //      return;
606 //  }
607
608   TObject* obj = fSpecCDBUri.FindObject(aPath.GetPath().Data());
609   if (obj) fSpecCDBUri.Remove(obj);
610   fSpecCDBUri.Add(new TNamed(aPath.GetPath().Data(), uri));
611
612 }
613
614 //_____________________________________________________________________________
615 Bool_t AliReconstruction::SetRunNumberFromData()
616 {
617   // The method is called in Run() in order
618   // to set a correct run number.
619   // In case of raw data reconstruction the
620   // run number is taken from the raw data header
621
622   if (fSetRunNumberFromDataCalled) return kTRUE;
623   fSetRunNumberFromDataCalled = kTRUE;
624   
625   AliCDBManager* man = AliCDBManager::Instance();
626  
627   if(fRawReader) {
628     if(fRawReader->NextEvent()) {
629       if(man->GetRun() > 0) {
630         AliWarning("Run number is taken from raw-event header! Ignoring settings in AliCDBManager!");
631       } 
632       man->SetRun(fRawReader->GetRunNumber());
633       fRawReader->RewindEvents();
634     }
635     else {
636       if(man->GetRun() > 0) {
637         AliWarning("No raw-data events are found ! Using settings in AliCDBManager !");
638       }
639       else {
640         AliWarning("Neither raw events nor settings in AliCDBManager are found !");
641         return kFALSE;
642       }
643     }
644   }
645   else {
646     AliRunLoader *rl = AliRunLoader::Open(fGAliceFileName.Data());
647     if (!rl) {
648       AliError(Form("No run loader found in file %s", fGAliceFileName.Data()));
649       return kFALSE;
650     }
651     else {
652       rl->LoadHeader();
653       // read run number from gAlice
654       if(rl->GetHeader()) {
655         man->SetRun(rl->GetHeader()->GetRun());
656         rl->UnloadHeader();
657         delete rl;
658       }
659       else {
660         AliError("Neither run-loader header nor RawReader objects are found !");
661         delete rl;
662         return kFALSE;
663       }
664     }
665   }
666
667   man->Print();  
668   
669   return kTRUE;
670 }
671
672 //_____________________________________________________________________________
673 void AliReconstruction::SetCDBLock() {
674   // Set CDB lock: from now on it is forbidden to reset the run number
675   // or the default storage or to activate any further storage!
676   
677   AliCDBManager::Instance()->SetLock(1);
678 }
679
680 //_____________________________________________________________________________
681 Bool_t AliReconstruction::MisalignGeometry(const TString& detectors)
682 {
683   // Read the alignment objects from CDB.
684   // Each detector is supposed to have the
685   // alignment objects in DET/Align/Data CDB path.
686   // All the detector objects are then collected,
687   // sorted by geometry level (starting from ALIC) and
688   // then applied to the TGeo geometry.
689   // Finally an overlaps check is performed.
690
691   // Load alignment data from CDB and fill fAlignObjArray 
692   if(fLoadAlignFromCDB){
693         
694     TString detStr = detectors;
695     TString loadAlObjsListOfDets = "";
696     
697     for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
698       if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
699       loadAlObjsListOfDets += fgkDetectorName[iDet];
700       loadAlObjsListOfDets += " ";
701     } // end loop over detectors
702     loadAlObjsListOfDets.Prepend("GRP "); //add alignment objects for non-sensitive modules
703     AliGeomManager::ApplyAlignObjsFromCDB(loadAlObjsListOfDets.Data());
704   }else{
705     // Check if the array with alignment objects was
706     // provided by the user. If yes, apply the objects
707     // to the present TGeo geometry
708     if (fAlignObjArray) {
709       if (gGeoManager && gGeoManager->IsClosed()) {
710         if (AliGeomManager::ApplyAlignObjsToGeom(*fAlignObjArray) == kFALSE) {
711           AliError("The misalignment of one or more volumes failed!"
712                    "Compare the list of simulated detectors and the list of detector alignment data!");
713           return kFALSE;
714         }
715       }
716       else {
717         AliError("Can't apply the misalignment! gGeoManager doesn't exist or it is still opened!");
718         return kFALSE;
719       }
720     }
721   }
722   
723   if (fAlignObjArray) {
724     fAlignObjArray->Delete();
725     delete fAlignObjArray; fAlignObjArray=NULL;
726   }
727
728   return kTRUE;
729 }
730
731 //_____________________________________________________________________________
732 void AliReconstruction::SetGAliceFile(const char* fileName)
733 {
734 // set the name of the galice file
735
736   fGAliceFileName = fileName;
737 }
738
739 //_____________________________________________________________________________
740 void AliReconstruction::SetInput(const char* input) 
741 {
742   // In case the input string starts with 'mem://', we run in an online mode
743   // and AliRawReaderDateOnline object is created. In all other cases a raw-data
744   // file is assumed. One can give as an input:
745   // mem://: - events taken from DAQ monitoring libs online
746   //  or
747   // mem://<filename> - emulation of the above mode (via DATE monitoring libs)
748   if (input) fRawInput = input;
749 }
750
751 //_____________________________________________________________________________
752 void AliReconstruction::SetOption(const char* detector, const char* option)
753 {
754 // set options for the reconstruction of a detector
755
756   TObject* obj = fOptions.FindObject(detector);
757   if (obj) fOptions.Remove(obj);
758   fOptions.Add(new TNamed(detector, option));
759 }
760
761 //_____________________________________________________________________________
762 void AliReconstruction::SetRecoParam(const char* detector, AliDetectorRecoParam *par)
763 {
764   // Set custom reconstruction parameters for a given detector
765   // Single set of parameters for all the events
766   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
767     if(!strcmp(detector, fgkDetectorName[iDet])) {
768       par->SetAsDefault();
769       fRecoParam.AddDetRecoParam(iDet,par);
770       break;
771     }
772   }
773
774 }
775
776 //_____________________________________________________________________________
777 Bool_t AliReconstruction::SetFieldMap(Float_t l3Current, Float_t diCurrent, Float_t factor, const char *path) {
778   //------------------------------------------------
779   // The magnetic field map, defined externally...
780   // L3 current 30000 A  -> 0.5 T
781   // L3 current 12000 A  -> 0.2 T
782   // dipole current 6000 A
783   // The polarities must be the same
784   //------------------------------------------------
785   const Float_t l3NominalCurrent1=30000.; // (A)
786   const Float_t l3NominalCurrent2=12000.; // (A)
787   const Float_t diNominalCurrent =6000. ; // (A)
788
789   const Float_t tolerance=0.03; // relative current tolerance
790   const Float_t zero=77.;       // "zero" current (A)
791
792   Int_t map=0;
793   Bool_t dipoleON=kFALSE;
794
795   TString s=(factor < 0) ? "L3: -" : "L3: +";
796
797   l3Current = TMath::Abs(l3Current);
798   if (TMath::Abs(l3Current-l3NominalCurrent1)/l3NominalCurrent1 < tolerance) {
799     map=AliMagWrapCheb::k5kG;
800     s+="0.5 T;  ";
801   } else
802   if (TMath::Abs(l3Current-l3NominalCurrent2)/l3NominalCurrent2 < tolerance) {
803     map=AliMagWrapCheb::k2kG;
804     s+="0.2 T;  ";
805   } else
806   if (l3Current < zero) {
807     map=AliMagWrapCheb::k2kG;
808     s+="0.0 T;  ";
809     factor=0.;                  // in fact, this is a global factor...
810     fUniformField=kTRUE;        // track with the uniform (zero) B field
811   } else {
812     AliError(Form("Wrong L3 current (%f A)!",l3Current));
813     return kFALSE;
814   }
815
816   diCurrent = TMath::Abs(diCurrent);
817   if (TMath::Abs(diCurrent-diNominalCurrent)/diNominalCurrent < tolerance) {
818     // 3% current tolerance...
819     dipoleON=kTRUE;
820     s+="Dipole ON";
821   } else
822   if (diCurrent < zero) { // some small current..
823     dipoleON=kFALSE;
824     s+="Dipole OFF";
825   } else {
826     AliError(Form("Wrong dipole current (%f A)!",diCurrent));
827     return kFALSE;
828   }
829
830   delete fForcedFieldMap;
831   fForcedFieldMap=
832     new AliMagWrapCheb("B field map  ",s,2,factor,10.,map,dipoleON,path);
833
834   fForcedFieldMap->Print();
835
836   AliTracker::SetFieldMap(fForcedFieldMap,fUniformField);    
837
838   return kTRUE;
839 }
840
841
842 Bool_t AliReconstruction::InitGRP() {
843   //------------------------------------
844   // Initialization of the GRP entry 
845   //------------------------------------
846   AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/GRP/Data");
847
848   if (entry) {
849     fGRPData = dynamic_cast<TMap*>(entry->GetObject());
850     entry->SetOwner(0);
851     AliCDBManager::Instance()->UnloadFromCache("GRP/GRP/Data");
852   }
853
854   if (!fGRPData) {
855      AliError("No GRP entry found in OCDB!");
856      return kFALSE;
857   }
858
859   TObjString *lhcState=
860     dynamic_cast<TObjString*>(fGRPData->GetValue("fLHCState"));
861   if (!lhcState) {
862     AliError("GRP/GRP/Data entry:  missing value for the LHC state ! Using UNKNOWN");
863   }
864
865   TObjString *beamType=
866     dynamic_cast<TObjString*>(fGRPData->GetValue("fAliceBeamType"));
867   if (!beamType) {
868     AliError("GRP/GRP/Data entry:  missing value for the beam type ! Using UNKNOWN");
869   }
870
871   TObjString *beamEnergyStr=
872     dynamic_cast<TObjString*>(fGRPData->GetValue("fAliceBeamEnergy"));
873   if (!beamEnergyStr) {
874     AliError("GRP/GRP/Data entry:  missing value for the beam energy ! Using 0");
875   }
876
877   TObjString *runType=
878     dynamic_cast<TObjString*>(fGRPData->GetValue("fRunType"));
879   if (!runType) {
880     AliError("GRP/GRP/Data entry:  missing value for the run type ! Using UNKNOWN");
881   }
882
883   TObjString *activeDetectors=
884     dynamic_cast<TObjString*>(fGRPData->GetValue("fDetectorMask"));
885   if (!activeDetectors) {
886     AliError("GRP/GRP/Data entry:  missing value for the detector mask ! Using 1074790399");
887   }
888
889   fRunInfo = new AliRunInfo(lhcState ? lhcState->GetString().Data() : "UNKNOWN",
890                             beamType ? beamType->GetString().Data() : "UNKNOWN",
891                             beamEnergyStr ? beamEnergyStr->GetString().Atof() : 0,
892                             runType  ? runType->GetString().Data()  : "UNKNOWN",
893                             activeDetectors ? activeDetectors->GetString().Atoi() : 1074790399);
894
895   // Process the list of active detectors
896   if (activeDetectors && activeDetectors->GetString().IsDigit()) {
897     UInt_t detMask = activeDetectors->GetString().Atoi();
898     fLoadCDB.Form("%s %s %s %s",
899                   fRunLocalReconstruction.Data(),
900                   fRunTracking.Data(),
901                   fFillESD.Data(),
902                   fQADetectors.Data());
903     fRunLocalReconstruction = MatchDetectorList(fRunLocalReconstruction,detMask);
904     fRunTracking = MatchDetectorList(fRunTracking,detMask);
905     fFillESD = MatchDetectorList(fFillESD,detMask);
906     fQADetectors = MatchDetectorList(fQADetectors,detMask);
907     fLoadCDB = MatchDetectorList(fLoadCDB,detMask);
908   }
909
910   AliInfo("===================================================================================");
911   AliInfo(Form("Running local reconstruction for detectors: %s",fRunLocalReconstruction.Data()));
912   AliInfo(Form("Running tracking for detectors: %s",fRunTracking.Data()));
913   AliInfo(Form("Filling ESD for detectors: %s",fFillESD.Data()));
914   AliInfo(Form("Quality assurance is active for detectors: %s",fQADetectors.Data()));
915   AliInfo(Form("CDB and reconstruction parameters are loaded for detectors: %s",fLoadCDB.Data()));
916   AliInfo("===================================================================================");
917
918   //*** Dealing with the magnetic field map
919   if (AliTracker::GetFieldMap()) {
920     AliInfo("Running with the externally set B field !");
921   } else {
922     // Construct the field map out of the information retrieved from GRP.
923
924     Bool_t ok = kTRUE;
925
926     // L3
927     TObjString *l3Current=
928        dynamic_cast<TObjString*>(fGRPData->GetValue("fL3Current"));
929     if (!l3Current) {
930       AliError("GRP/GRP/Data entry:  missing value for the L3 current !");
931       ok = kFALSE;
932     }
933     TObjString *l3Polarity=
934        dynamic_cast<TObjString*>(fGRPData->GetValue("fL3Polarity"));
935     if (!l3Polarity) {
936       AliError("GRP/GRP/Data entry:  missing value for the L3 polarity !");
937       ok = kFALSE;
938     }
939
940     // Dipole
941     TObjString *diCurrent=
942        dynamic_cast<TObjString*>(fGRPData->GetValue("fDipoleCurrent"));
943     if (!diCurrent) {
944       AliError("GRP/GRP/Data entry:  missing value for the dipole current !");
945       ok = kFALSE;
946     }
947     TObjString *diPolarity=
948        dynamic_cast<TObjString*>(fGRPData->GetValue("fDipolePolarity"));
949     if (!diPolarity) {
950       AliError("GRP/GRP/Data entry:  missing value for the dipole polarity !");
951       ok = kFALSE;
952     }
953
954     if (ok) { 
955        Float_t l3Cur=TMath::Abs(atof(l3Current->GetName()));
956        Float_t diCur=TMath::Abs(atof(diCurrent->GetName()));
957        Float_t l3Pol=atof(l3Polarity->GetName());
958        Float_t factor=1.;
959        if (l3Pol != 0.) factor=-1.;
960     
961
962       if (!SetFieldMap(l3Cur, diCur, factor)) {
963          AliFatal("Failed to creat a B field map ! Exiting...");
964       }
965       AliInfo("Running with the B field constructed out of GRP !");
966     }
967     else {
968       AliFatal("B field is neither set nor constructed from GRP ! Exitig...");
969     }
970
971   }
972
973   //*** Get the diamond profile from OCDB
974   entry = AliCDBManager::Instance()->Get("GRP/Calib/MeanVertex");
975   if (entry) {
976     if (fMeanVertexConstraint)
977       fDiamondProfile = dynamic_cast<AliESDVertex*> (entry->GetObject());  
978   } else {
979      AliError("No diamond profile found in OCDB!");
980   }
981
982   entry = AliCDBManager::Instance()->Get("GRP/Calib/MeanVertexTPC");
983   if (entry) {
984     if (fMeanVertexConstraint)
985       fDiamondProfileTPC = dynamic_cast<AliESDVertex*> (entry->GetObject());  
986   } else {
987      AliError("No diamond profile found in OCDB!");
988   }
989
990   return kTRUE;
991
992
993 //_____________________________________________________________________________
994 Bool_t AliReconstruction::LoadCDB()
995 {
996   AliCodeTimerAuto("");
997
998   AliCDBManager::Instance()->Get("GRP/CTP/Config");
999
1000   TString detStr = fLoadCDB;
1001   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
1002     if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
1003     AliCDBManager::Instance()->GetAll(Form("%s/Calib/*",fgkDetectorName[iDet]));
1004   }
1005   return kTRUE;
1006 }
1007
1008 //_____________________________________________________________________________
1009 Bool_t AliReconstruction::Run(const char* input)
1010 {
1011   // Run Run Run
1012   AliCodeTimerAuto("");
1013
1014   InitRun(input);
1015   if (GetAbort() != TSelector::kContinue) return kFALSE;
1016
1017   TChain *chain = NULL;
1018   if (fRawReader && (chain = fRawReader->GetChain())) {
1019     // Proof mode
1020     if (gProof) {
1021       gProof->AddInput(this);
1022       TUrl outputFile;
1023       outputFile.SetProtocol("root",kTRUE);
1024       outputFile.SetHost(gSystem->HostName());
1025       outputFile.SetFile(Form("%s/AliESDs.root",gSystem->pwd()));
1026       AliInfo(Form("Output file with ESDs is %s",outputFile.GetUrl()));
1027       gProof->AddInput(new TNamed("PROOF_OUTPUTFILE",outputFile.GetUrl()));
1028       chain->SetProof();
1029       chain->Process("AliReconstruction");
1030     }
1031     else {
1032       chain->Process(this);
1033     }
1034   }
1035   else {
1036     Begin(NULL);
1037     if (GetAbort() != TSelector::kContinue) return kFALSE;
1038     SlaveBegin(NULL);
1039     if (GetAbort() != TSelector::kContinue) return kFALSE;
1040     //******* The loop over events
1041     Int_t iEvent = 0;
1042     while ((iEvent < fRunLoader->GetNumberOfEvents()) ||
1043            (fRawReader && fRawReader->NextEvent())) {
1044       if (!ProcessEvent(iEvent)) {
1045         Abort("ProcessEvent",TSelector::kAbortFile);
1046         return kFALSE;
1047       }
1048       iEvent++;
1049     }
1050     SlaveTerminate();
1051     if (GetAbort() != TSelector::kContinue) return kFALSE;
1052     Terminate();
1053     if (GetAbort() != TSelector::kContinue) return kFALSE;
1054   }
1055
1056   return kTRUE;
1057 }
1058
1059 //_____________________________________________________________________________
1060 void AliReconstruction::InitRawReader(const char* input)
1061 {
1062   AliCodeTimerAuto("");
1063
1064   // Init raw-reader and
1065   // set the input in case of raw data
1066   if (input) fRawInput = input;
1067   fRawReader = AliRawReader::Create(fRawInput.Data());
1068   if (!fRawReader)
1069     AliInfo("Reconstruction will run over digits");
1070
1071   if (!fEquipIdMap.IsNull() && fRawReader)
1072     fRawReader->LoadEquipmentIdsMap(fEquipIdMap);
1073
1074   if (!fUseHLTData.IsNull()) {
1075     // create the RawReaderHLT which performs redirection of HLT input data for
1076     // the specified detectors
1077     AliRawReader* pRawReader=AliRawHLTManager::CreateRawReaderHLT(fRawReader, fUseHLTData.Data());
1078     if (pRawReader) {
1079       fParentRawReader=fRawReader;
1080       fRawReader=pRawReader;
1081     } else {
1082       AliError(Form("can not create Raw Reader for HLT input %s", fUseHLTData.Data()));
1083     }
1084   }
1085   AliSysInfo::AddStamp("CreateRawReader");
1086 }
1087
1088 //_____________________________________________________________________________
1089 void AliReconstruction::InitRun(const char* input)
1090 {
1091   // Initialization of raw-reader,
1092   // run number, CDB etc.
1093   AliCodeTimerAuto("");
1094   AliSysInfo::AddStamp("Start");
1095
1096   // Initialize raw-reader if any
1097   InitRawReader(input);
1098
1099   // Initialize the CDB storage
1100   InitCDB();
1101
1102   // Set run number in CDBManager (if it is not already set by the user)
1103   if (!SetRunNumberFromData()) {
1104     Abort("SetRunNumberFromData", TSelector::kAbortProcess);
1105     return;
1106   }
1107
1108   // Set CDB lock: from now on it is forbidden to reset the run number
1109   // or the default storage or to activate any further storage!
1110   SetCDBLock();
1111   
1112 }
1113
1114 //_____________________________________________________________________________
1115 void AliReconstruction::Begin(TTree *)
1116 {
1117   // Initialize AlReconstruction before
1118   // going into the event loop
1119   // Should follow the TSelector convention
1120   // i.e. initialize only the object on the client side
1121   AliCodeTimerAuto("");
1122
1123   AliReconstruction *reco = NULL;
1124   if (fInput) {
1125     if ((reco = (AliReconstruction*)fInput->FindObject("AliReconstruction"))) {
1126       *this = *reco;
1127     }
1128     AliSysInfo::AddStamp("ReadInputInBegin");
1129   }
1130
1131   // Import ideal TGeo geometry and apply misalignment
1132   if (!gGeoManager) {
1133     TString geom(gSystem->DirName(fGAliceFileName));
1134     geom += "/geometry.root";
1135     AliGeomManager::LoadGeometry(geom.Data());
1136     if (!gGeoManager) {
1137       Abort("LoadGeometry", TSelector::kAbortProcess);
1138       return;
1139     }
1140     AliSysInfo::AddStamp("LoadGeom");
1141     TString detsToCheck=fRunLocalReconstruction;
1142     if(!AliGeomManager::CheckSymNamesLUT(detsToCheck.Data())) {
1143       Abort("CheckSymNamesLUT", TSelector::kAbortProcess);
1144       return;
1145     }
1146     AliSysInfo::AddStamp("CheckGeom");
1147   }
1148
1149   if (!MisalignGeometry(fLoadAlignData)) {
1150     Abort("MisalignGeometry", TSelector::kAbortProcess);
1151     return;
1152   }
1153   AliCDBManager::Instance()->UnloadFromCache("GRP/Geometry/Data");
1154   AliSysInfo::AddStamp("MisalignGeom");
1155
1156   if (!InitGRP()) {
1157     Abort("InitGRP", TSelector::kAbortProcess);
1158     return;
1159   }
1160   AliSysInfo::AddStamp("InitGRP");
1161
1162   if (!LoadCDB()) {
1163     Abort("LoadCDB", TSelector::kAbortProcess);
1164     return;
1165   }
1166   AliSysInfo::AddStamp("LoadCDB");
1167
1168   // Read the reconstruction parameters from OCDB
1169   if (!InitRecoParams()) {
1170     AliWarning("Not all detectors have correct RecoParam objects initialized");
1171   }
1172   AliSysInfo::AddStamp("InitRecoParams");
1173
1174   if (fInput) {
1175     if (reco) *reco = *this;
1176     fInput->Add(gGeoManager);
1177     gGeoManager = NULL;
1178     fInput->Add(const_cast<TMap*>(AliCDBManager::Instance()->GetEntryCache()));
1179     fInput->Add(new TParameter<Int_t>("RunNumber",AliCDBManager::Instance()->GetRun()));
1180     fInput->Add((AliMagF*)AliTracker::GetFieldMap());
1181   }
1182
1183 }
1184
1185 //_____________________________________________________________________________
1186 void AliReconstruction::SlaveBegin(TTree*)
1187 {
1188   // Initialization related to run-loader,
1189   // vertexer, trackers, recontructors
1190   // In proof mode it is executed on the slave
1191   AliCodeTimerAuto("");
1192
1193   TProofOutputFile *outProofFile = NULL;
1194   if (fInput) {
1195     if (AliReconstruction *reco = (AliReconstruction*)fInput->FindObject("AliReconstruction")) {
1196       *this = *reco;
1197     }
1198     if (TGeoManager *tgeo = (TGeoManager*)fInput->FindObject("Geometry")) {
1199       gGeoManager = tgeo;
1200       AliGeomManager::SetGeometry(tgeo);
1201     }
1202     if (TMap *entryCache = (TMap*)fInput->FindObject("CDBEntryCache")) {
1203       Int_t runNumber = -1;
1204       if (TProof::GetParameter(fInput,"RunNumber",runNumber) == 0) {
1205         AliCDBManager *man = AliCDBManager::Instance(entryCache,runNumber);
1206         man->SetCacheFlag(kTRUE);
1207         man->SetLock(kTRUE);
1208         man->Print();
1209       }
1210     }
1211     if (AliMagF *map = (AliMagF*)fInput->FindObject("Maps")) {
1212       AliTracker::SetFieldMap(map,fUniformField);
1213     }
1214     if (TNamed *outputFileName = (TNamed *) fInput->FindObject("PROOF_OUTPUTFILE")) {
1215       outProofFile = new TProofOutputFile(gSystem->BaseName(TUrl(outputFileName->GetTitle()).GetFile()));
1216       outProofFile->SetOutputFileName(outputFileName->GetTitle());
1217       fOutput->Add(outProofFile);
1218     }
1219     AliSysInfo::AddStamp("ReadInputInSlaveBegin");
1220   }
1221
1222   // get the run loader
1223   if (!InitRunLoader()) {
1224     Abort("InitRunLoader", TSelector::kAbortProcess);
1225     return;
1226   }
1227   AliSysInfo::AddStamp("LoadLoader");
1228  
1229   ftVertexer = new AliVertexerTracks(AliTracker::GetBz());
1230   if(fDiamondProfile && fMeanVertexConstraint) ftVertexer->SetVtxStart(fDiamondProfile);
1231
1232   // get vertexer
1233   if (fRunVertexFinder && !CreateVertexer()) {
1234     Abort("CreateVertexer", TSelector::kAbortProcess);
1235     return;
1236   }
1237   AliSysInfo::AddStamp("CreateVertexer");
1238
1239   // get trackers
1240   if (!fRunTracking.IsNull() && !CreateTrackers(fRunTracking)) {
1241     Abort("CreateTrackers", TSelector::kAbortProcess);
1242     return;
1243   }      
1244   AliSysInfo::AddStamp("CreateTrackers");
1245
1246   // create the ESD output file and tree
1247   if (!outProofFile) {
1248     ffile = TFile::Open("AliESDs.root", "RECREATE");
1249     ffile->SetCompressionLevel(2);
1250     if (!ffile->IsOpen()) {
1251       Abort("OpenESDFile", TSelector::kAbortProcess);
1252       return;
1253     }
1254   }
1255   else {
1256     if (!(ffile = outProofFile->OpenFile("RECREATE"))) {
1257       Abort(Form("Problems opening output PROOF file: %s/%s",
1258                  outProofFile->GetDir(), outProofFile->GetFileName()),
1259             TSelector::kAbortProcess);
1260       return;
1261     }
1262   }
1263
1264   ftree = new TTree("esdTree", "Tree with ESD objects");
1265   fesd = new AliESDEvent();
1266   fesd->CreateStdContent();
1267   fesd->WriteToTree(ftree);
1268
1269   fhlttree = new TTree("HLTesdTree", "Tree with HLT ESD objects");
1270   fhltesd = new AliESDEvent();
1271   fhltesd->CreateStdContent();
1272   fhltesd->WriteToTree(fhlttree);
1273
1274
1275   if (fWriteESDfriend) {
1276     fesdf = new AliESDfriend();
1277     TBranch *br=ftree->Branch("ESDfriend.","AliESDfriend", &fesdf);
1278     br->SetFile("AliESDfriends.root");
1279     fesd->AddObject(fesdf);
1280   }
1281
1282   ProcInfo_t ProcInfo;
1283   gSystem->GetProcInfo(&ProcInfo);
1284   AliInfo(Form("Current memory usage %d %d", ProcInfo.fMemResident, ProcInfo.fMemVirtual));
1285   
1286   //QA
1287   fQASteer = new AliQADataMakerSteer("rec") ; 
1288   fQASteer->SetActiveDetectors(fQADetectors) ; 
1289   fQASteer->SetTasks(fQATasks) ; 
1290
1291   if ( !fInLoopQA ) {
1292     if (fRunQA && fRawReader && fQATasks.Contains(Form("%d", AliQA::kRAWS))) { 
1293       fQASteer->Run(fQADetectors, fRawReader) ; 
1294       fSameQACycle = kTRUE ; 
1295     }
1296   }
1297         
1298   //Initialize the QA and start of cycle for out-of-loop QA
1299   if (fRunQA) {
1300     fQASteer->InitQADataMaker(AliCDBManager::Instance()->GetRun(), fRecoParam, fSameQACycle, !fInLoopQA) ;
1301   }
1302         
1303   if (fRunGlobalQA) {
1304     fSameQACycle = kFALSE;
1305     AliQADataMaker *qadm = fQASteer->GetQADataMaker(AliQA::kGLOBAL);
1306     AliInfo(Form("Initializing the global QA data maker"));
1307     if (fQATasks.Contains(Form("%d", AliQA::kRECPOINTS))) {
1308       TObjArray *arr=qadm->Init(AliQA::kRECPOINTS, AliCDBManager::Instance()->GetRun());
1309       AliTracker::SetResidualsArray(arr);
1310       if (!fInLoopQA) {
1311         qadm->StartOfCycle(AliQA::kRECPOINTS, fSameQACycle);
1312         fSameQACycle = kTRUE;
1313       }
1314     }
1315     if (fQATasks.Contains(Form("%d", AliQA::kESDS))) {
1316       qadm->Init(AliQA::kESDS, AliCDBManager::Instance()->GetRun());
1317       if (!fInLoopQA) {
1318         qadm->StartOfCycle(AliQA::kESDS, fSameQACycle);
1319         fSameQACycle = kTRUE;   
1320       }
1321     }
1322   }
1323
1324   //Initialize the Plane Efficiency framework
1325   if (fRunPlaneEff && !InitPlaneEff()) {
1326     Abort("InitPlaneEff", TSelector::kAbortProcess);
1327     return;
1328   }
1329
1330   if (strcmp(gProgName,"alieve") == 0)
1331     fRunAliEVE = InitAliEVE();
1332
1333   return;
1334 }
1335
1336 //_____________________________________________________________________________
1337 Bool_t AliReconstruction::Process(Long64_t entry)
1338 {
1339   // run the reconstruction over a single entry
1340   // from the chain with raw data
1341   AliCodeTimerAuto("");
1342
1343   TTree *currTree = fChain->GetTree();
1344   AliRawEvent *event = new AliRawEvent;
1345   currTree->SetBranchAddress("rawevent",&event);
1346   currTree->GetEntry(entry);
1347   fRawReader = new AliRawReaderRoot(event);
1348   fStatus = ProcessEvent(fRunLoader->GetNumberOfEvents());  
1349   delete fRawReader;
1350   fRawReader = NULL;
1351   delete event;
1352
1353   return fStatus;
1354 }
1355
1356 //_____________________________________________________________________________
1357 void AliReconstruction::Init(TTree *tree)
1358 {
1359   if (tree == 0) {
1360     AliError("The input tree is not found!");
1361     return;
1362   }
1363   fChain = tree;
1364 }
1365
1366 //_____________________________________________________________________________
1367 Bool_t AliReconstruction::ProcessEvent(Int_t iEvent)
1368 {
1369   // run the reconstruction over a single event
1370   // The event loop is steered in Run method
1371
1372   AliCodeTimerAuto("");
1373
1374   if (iEvent >= fRunLoader->GetNumberOfEvents()) {
1375     fRunLoader->SetEventNumber(iEvent);
1376     fRunLoader->GetHeader()->Reset(fRawReader->GetRunNumber(), 
1377                                    iEvent, iEvent);
1378     fRunLoader->TreeE()->Fill();
1379     if (fRawReader && fRawReader->UseAutoSaveESD())
1380       fRunLoader->TreeE()->AutoSave("SaveSelf");
1381   }
1382
1383   if ((iEvent < fFirstEvent) || ((fLastEvent >= 0) && (iEvent > fLastEvent))) {
1384     return kTRUE;
1385   }
1386
1387   AliInfo(Form("processing event %d", iEvent));
1388
1389   // Fill Event-info object
1390   GetEventInfo();
1391   fRecoParam.SetEventSpecie(fRunInfo,fEventInfo);
1392
1393   //Start of cycle for the in-loop QA
1394   if (fInLoopQA && fRunQA) {
1395     fQASteer->InitQADataMaker(AliCDBManager::Instance()->GetRun(), fRecoParam, fSameQACycle, fInLoopQA) ;
1396   }
1397   if (fInLoopQA && fRunGlobalQA) {
1398     fSameQACycle = kFALSE;
1399     AliQADataMaker *qadm = fQASteer->GetQADataMaker(AliQA::kGLOBAL);
1400     if (fQATasks.Contains(Form("%d", AliQA::kRECPOINTS))) {
1401       qadm->StartOfCycle(AliQA::kRECPOINTS, fSameQACycle);
1402       fSameQACycle = kTRUE;
1403     }
1404     if (fQATasks.Contains(Form("%d", AliQA::kESDS))) {
1405       qadm->StartOfCycle(AliQA::kESDS, fSameQACycle);
1406       fSameQACycle = kTRUE;
1407     }
1408   }                
1409
1410   fRunLoader->GetEvent(iEvent);
1411
1412     // QA on single raw 
1413     if (fInLoopQA && fRunQA) 
1414                         fQASteer->RunOneEvent(fRawReader) ;  
1415
1416     // local single event reconstruction
1417     if (!fRunLocalReconstruction.IsNull()) {
1418       TString detectors=fRunLocalReconstruction;
1419       // run HLT event reconstruction first
1420       // ;-( IsSelected changes the string
1421       if (IsSelected("HLT", detectors) &&
1422           !RunLocalEventReconstruction("HLT")) {
1423         if (fStopOnError) {CleanUp(); return kFALSE;}
1424       }
1425       detectors=fRunLocalReconstruction;
1426       detectors.ReplaceAll("HLT", "");
1427       if (!RunLocalEventReconstruction(detectors)) {
1428         if (fStopOnError) {CleanUp(); return kFALSE;}
1429       }
1430     }
1431
1432     fesd->SetRunNumber(fRunLoader->GetHeader()->GetRun());
1433     fhltesd->SetRunNumber(fRunLoader->GetHeader()->GetRun());
1434     fesd->SetEventNumberInFile(fRunLoader->GetHeader()->GetEventNrInRun());
1435     fhltesd->SetEventNumberInFile(fRunLoader->GetHeader()->GetEventNrInRun());
1436     
1437     // Set magnetic field from the tracker
1438     fesd->SetMagneticField(AliTracker::GetBz());
1439     fhltesd->SetMagneticField(AliTracker::GetBz());
1440
1441     
1442     
1443     // Fill raw-data error log into the ESD
1444     if (fRawReader) FillRawDataErrorLog(iEvent,fesd);
1445
1446     // vertex finder
1447     if (fRunVertexFinder) {
1448       if (!RunVertexFinder(fesd)) {
1449         if (fStopOnError) {CleanUp(); return kFALSE;}
1450       }
1451     }
1452
1453     // Muon tracking
1454     if (!fRunTracking.IsNull()) {
1455       if (fRunMuonTracking) {
1456         if (!RunMuonTracking(fesd)) {
1457           if (fStopOnError) {CleanUp(); return kFALSE;}
1458         }
1459       }
1460     }
1461
1462     // barrel tracking
1463     if (!fRunTracking.IsNull()) {
1464       if (!RunTracking(fesd)) {
1465         if (fStopOnError) {CleanUp(); return kFALSE;}
1466       }
1467     }
1468
1469     // fill ESD
1470     if (!fFillESD.IsNull()) {
1471       TString detectors=fFillESD;
1472       // run HLT first and on hltesd
1473       // ;-( IsSelected changes the string
1474       if (IsSelected("HLT", detectors) &&
1475           !FillESD(fhltesd, "HLT")) {
1476         if (fStopOnError) {CleanUp(); return kFALSE;}
1477       }
1478       detectors=fFillESD;
1479       // Temporary fix to avoid problems with HLT that overwrites the offline ESDs
1480       if (detectors.Contains("ALL")) {
1481         detectors="";
1482         for (Int_t idet=0; idet<fgkNDetectors; ++idet){
1483           detectors += fgkDetectorName[idet];
1484           detectors += " ";
1485         }
1486       }
1487       detectors.ReplaceAll("HLT", "");
1488       if (!FillESD(fesd, detectors)) {
1489         if (fStopOnError) {CleanUp(); return kFALSE;}
1490       }
1491     }
1492   
1493     // fill Event header information from the RawEventHeader
1494     if (fRawReader){FillRawEventHeaderESD(fesd);}
1495
1496     // combined PID
1497     AliESDpid::MakePID(fesd);
1498
1499     if (fFillTriggerESD) {
1500       if (!FillTriggerESD(fesd)) {
1501         if (fStopOnError) {CleanUp(); return kFALSE;}
1502       }
1503     }
1504
1505     ffile->cd();
1506
1507     //
1508     // Propagate track to the beam pipe  (if not already done by ITS)
1509     //
1510     const Int_t ntracks = fesd->GetNumberOfTracks();
1511     const Double_t kBz = fesd->GetMagneticField();
1512     const Double_t kRadius  = 2.8; //something less than the beam pipe radius
1513
1514     TObjArray trkArray;
1515     UShort_t *selectedIdx=new UShort_t[ntracks];
1516
1517     for (Int_t itrack=0; itrack<ntracks; itrack++){
1518       const Double_t kMaxStep = 5;   //max step over the material
1519       Bool_t ok;
1520
1521       AliESDtrack *track = fesd->GetTrack(itrack);
1522       if (!track) continue;
1523
1524       AliExternalTrackParam *tpcTrack =
1525            (AliExternalTrackParam *)track->GetTPCInnerParam();
1526       ok = kFALSE;
1527       if (tpcTrack)
1528         ok = AliTracker::
1529           PropagateTrackTo(tpcTrack,kRadius,track->GetMass(),kMaxStep,kTRUE);
1530
1531       if (ok) {
1532         Int_t n=trkArray.GetEntriesFast();
1533         selectedIdx[n]=track->GetID();
1534         trkArray.AddLast(tpcTrack);
1535       }
1536
1537       //Tracks refitted by ITS should already be at the SPD vertex
1538       if (track->IsOn(AliESDtrack::kITSrefit)) continue;
1539
1540       AliTracker::
1541          PropagateTrackTo(track,kRadius,track->GetMass(),kMaxStep,kTRUE);
1542       track->RelateToVertex(fesd->GetPrimaryVertexSPD(), kBz, kVeryBig);
1543
1544     }
1545
1546     //
1547     // Improve the reconstructed primary vertex position using the tracks
1548     //
1549     TObject *obj = fOptions.FindObject("ITS");
1550     if (obj) {
1551       TString optITS = obj->GetTitle();
1552       if (optITS.Contains("cosmics") || optITS.Contains("COSMICS")) 
1553         fRunVertexFinderTracks=kFALSE;
1554     }
1555     if (fRunVertexFinderTracks) {
1556        // TPC + ITS primary vertex
1557        ftVertexer->SetITSrefitRequired();
1558        if(fDiamondProfile && fMeanVertexConstraint) {
1559          ftVertexer->SetVtxStart(fDiamondProfile);
1560        } else {
1561          ftVertexer->SetConstraintOff();
1562        }
1563        AliESDVertex *pvtx=ftVertexer->FindPrimaryVertex(fesd);
1564        if (pvtx) {
1565           if (pvtx->GetStatus()) {
1566              fesd->SetPrimaryVertex(pvtx);
1567              for (Int_t i=0; i<ntracks; i++) {
1568                  AliESDtrack *t = fesd->GetTrack(i);
1569                  t->RelateToVertex(pvtx, kBz, kVeryBig);
1570              } 
1571           }
1572        }
1573
1574        // TPC-only primary vertex
1575        ftVertexer->SetITSrefitNotRequired();
1576        if(fDiamondProfileTPC && fMeanVertexConstraint) {
1577          ftVertexer->SetVtxStart(fDiamondProfileTPC);
1578        } else {
1579          ftVertexer->SetConstraintOff();
1580        }
1581        pvtx=ftVertexer->FindPrimaryVertex(&trkArray,selectedIdx);
1582        if (pvtx) {
1583           if (pvtx->GetStatus()) {
1584              fesd->SetPrimaryVertexTPC(pvtx);
1585              for (Int_t i=0; i<ntracks; i++) {
1586                  AliESDtrack *t = fesd->GetTrack(i);
1587                  t->RelateToVertexTPC(pvtx, kBz, kVeryBig);
1588              } 
1589           }
1590        }
1591
1592     }
1593     delete[] selectedIdx;
1594
1595     if(fDiamondProfile) fesd->SetDiamond(fDiamondProfile);
1596     
1597
1598     if (fRunV0Finder) {
1599        // V0 finding
1600        AliV0vertexer vtxer;
1601        vtxer.Tracks2V0vertices(fesd);
1602
1603        if (fRunCascadeFinder) {
1604           // Cascade finding
1605           AliCascadeVertexer cvtxer;
1606           cvtxer.V0sTracks2CascadeVertices(fesd);
1607        }
1608     }
1609  
1610     // write ESD
1611     if (fCleanESD) CleanESD(fesd);
1612
1613     if (fRunGlobalQA) {
1614       AliQADataMaker *qadm = fQASteer->GetQADataMaker(AliQA::kGLOBAL);
1615       if (qadm && fQATasks.Contains(Form("%d", AliQA::kESDS)))
1616         qadm->Exec(AliQA::kESDS, fesd);
1617     }
1618
1619     if (fWriteESDfriend) {
1620       fesdf->~AliESDfriend();
1621       new (fesdf) AliESDfriend(); // Reset...
1622       fesd->GetESDfriend(fesdf);
1623     }
1624     ftree->Fill();
1625
1626     // Auto-save the ESD tree in case of prompt reco @P2
1627     if (fRawReader && fRawReader->UseAutoSaveESD())
1628       ftree->AutoSave("SaveSelf");
1629
1630     // write HLT ESD
1631     fhlttree->Fill();
1632
1633     // call AliEVE
1634     if (fRunAliEVE) RunAliEVE();
1635
1636     fesd->Reset();
1637     fhltesd->Reset();
1638     if (fWriteESDfriend) {
1639       fesdf->~AliESDfriend();
1640       new (fesdf) AliESDfriend(); // Reset...
1641     }
1642  
1643     ProcInfo_t ProcInfo;
1644     gSystem->GetProcInfo(&ProcInfo);
1645     AliInfo(Form("Event %d -> Current memory usage %d %d",iEvent, ProcInfo.fMemResident, ProcInfo.fMemVirtual));
1646   
1647
1648   // End of cycle for the in-loop  
1649     if (fInLoopQA && fRunQA) {
1650       fQASteer->RunOneEvent(fesd) ; 
1651       fQASteer->EndOfCycle() ;
1652     }
1653     if (fInLoopQA && fRunGlobalQA) {
1654       AliQADataMaker *qadm = fQASteer->GetQADataMaker(AliQA::kGLOBAL);
1655       if (qadm) {
1656         if (fQATasks.Contains(Form("%d", AliQA::kRECPOINTS))) 
1657           qadm->EndOfCycle(AliQA::kRECPOINTS);
1658         if (fQATasks.Contains(Form("%d", AliQA::kESDS))) 
1659           qadm->EndOfCycle(AliQA::kESDS);
1660         qadm->Finish();
1661       }
1662     }
1663
1664     fEventInfo.Reset();
1665     for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
1666       if (fReconstructor[iDet])
1667                                 fReconstructor[iDet]->SetRecoParam(NULL);
1668     }
1669         
1670     return kTRUE;
1671 }
1672
1673 //_____________________________________________________________________________
1674 void AliReconstruction::SlaveTerminate()
1675 {
1676   // Finalize the run on the slave side
1677   // Called after the exit
1678   // from the event loop
1679   AliCodeTimerAuto("");
1680
1681   if (fIsNewRunLoader) { // galice.root didn't exist
1682     fRunLoader->WriteHeader("OVERWRITE");
1683     fRunLoader->CdGAFile();
1684     fRunLoader->Write(0, TObject::kOverwrite);
1685   }
1686
1687   ftree->GetUserInfo()->Add(fesd);
1688   fhlttree->GetUserInfo()->Add(fhltesd);
1689   
1690   const TMap *cdbMap = AliCDBManager::Instance()->GetStorageMap();       
1691   const TList *cdbList = AliCDBManager::Instance()->GetRetrievedIds();   
1692                  
1693    TMap *cdbMapCopy = new TMap(cdbMap->GetEntries());    
1694    cdbMapCopy->SetOwner(1);      
1695    cdbMapCopy->SetName("cdbMap");        
1696    TIter iter(cdbMap->GetTable());       
1697          
1698    TPair* pair = 0;      
1699    while((pair = dynamic_cast<TPair*> (iter.Next()))){   
1700          TObjString* keyStr = dynamic_cast<TObjString*> (pair->Key());   
1701          TObjString* valStr = dynamic_cast<TObjString*> (pair->Value());         
1702          cdbMapCopy->Add(new TObjString(keyStr->GetName()), new TObjString(valStr->GetName()));  
1703    }     
1704          
1705    TList *cdbListCopy = new TList();     
1706    cdbListCopy->SetOwner(1);     
1707    cdbListCopy->SetName("cdbList");      
1708          
1709    TIter iter2(cdbList);         
1710          
1711         AliCDBId* id=0;
1712         while((id = dynamic_cast<AliCDBId*> (iter2.Next()))){    
1713          cdbListCopy->Add(new TObjString(id->ToString().Data()));        
1714    }     
1715          
1716    ftree->GetUserInfo()->Add(cdbMapCopy);        
1717    ftree->GetUserInfo()->Add(cdbListCopy);
1718
1719
1720   if(fESDPar.Contains("ESD.par")){
1721     AliInfo("Attaching ESD.par to Tree");
1722     TNamed *fn = CopyFileToTNamed(fESDPar.Data(),"ESD.par");
1723     ftree->GetUserInfo()->Add(fn);
1724   }
1725
1726
1727   ffile->cd();
1728
1729   if (fWriteESDfriend)
1730     ftree->SetBranchStatus("ESDfriend*",0);
1731   // we want to have only one tree version number
1732   ftree->Write(ftree->GetName(),TObject::kOverwrite);
1733   fhlttree->Write();
1734
1735 // Finish with Plane Efficiency evaluation: before of CleanUp !!!
1736   if (fRunPlaneEff && !FinishPlaneEff()) {
1737    AliWarning("Finish PlaneEff evaluation failed");
1738   }
1739
1740   //Finish QA and end of cycle for out-of-loop QA
1741   if (!fInLoopQA && fRunQA) 
1742     fQASteer->Run(fRunLocalReconstruction.Data(), AliQA::kNULLTASKINDEX, fSameQACycle) ; 
1743   if (!fInLoopQA && fRunGlobalQA) {
1744     AliQADataMaker *qadm = fQASteer->GetQADataMaker(AliQA::kGLOBAL);
1745     if (qadm) {
1746       if (fQATasks.Contains(Form("%d", AliQA::kRECPOINTS))) 
1747         qadm->EndOfCycle(AliQA::kRECPOINTS);
1748       if (fQATasks.Contains(Form("%d", AliQA::kESDS))) 
1749         qadm->EndOfCycle(AliQA::kESDS);
1750       qadm->Finish();
1751     }
1752   }
1753
1754   gROOT->cd();
1755   CleanUp();
1756 }
1757     
1758 //_____________________________________________________________________________
1759 void AliReconstruction::Terminate()
1760 {
1761   // Create tags for the events in the ESD tree (the ESD tree is always present)
1762   // In case of empty events the tags will contain dummy values
1763   AliCodeTimerAuto("");
1764
1765   AliESDTagCreator *esdtagCreator = new AliESDTagCreator();
1766   esdtagCreator->CreateESDTags(fFirstEvent,fLastEvent,fGRPData);
1767
1768   // Cleanup of CDB manager: cache and active storages!
1769   AliCDBManager::Instance()->ClearCache();
1770 }
1771
1772 //_____________________________________________________________________________
1773 Bool_t AliReconstruction::RunLocalEventReconstruction(const TString& detectors)
1774 {
1775 // run the local reconstruction
1776
1777   static Int_t eventNr=0;
1778   AliCodeTimerAuto("")
1779
1780   TString detStr = detectors;
1781   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
1782     if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
1783     AliReconstructor* reconstructor = GetReconstructor(iDet);
1784     if (!reconstructor) continue;
1785     AliLoader* loader = fLoader[iDet];
1786     // Matthias April 2008: temporary fix to run HLT reconstruction
1787     // although the HLT loader is missing
1788     if (strcmp(fgkDetectorName[iDet], "HLT")==0) {
1789       if (fRawReader) {
1790         reconstructor->Reconstruct(fRawReader, NULL);
1791       } else {
1792         TTree* dummy=NULL;
1793         reconstructor->Reconstruct(dummy, NULL);
1794       }
1795       continue;
1796     }
1797     if (!loader) {
1798       AliWarning(Form("No loader is defined for %s!",fgkDetectorName[iDet]));
1799       continue;
1800     }
1801     // conversion of digits
1802     if (fRawReader && reconstructor->HasDigitConversion()) {
1803       AliInfo(Form("converting raw data digits into root objects for %s", 
1804                    fgkDetectorName[iDet]));
1805 //      AliCodeTimerAuto(Form("converting raw data digits into root objects for %s", 
1806 //                            fgkDetectorName[iDet]));
1807       loader->LoadDigits("update");
1808       loader->CleanDigits();
1809       loader->MakeDigitsContainer();
1810       TTree* digitsTree = loader->TreeD();
1811       reconstructor->ConvertDigits(fRawReader, digitsTree);
1812       loader->WriteDigits("OVERWRITE");
1813       loader->UnloadDigits();
1814     }
1815     // local reconstruction
1816     AliInfo(Form("running reconstruction for %s", fgkDetectorName[iDet]));
1817     //AliCodeTimerAuto(Form("running reconstruction for %s", fgkDetectorName[iDet]));
1818     loader->LoadRecPoints("update");
1819     loader->CleanRecPoints();
1820     loader->MakeRecPointsContainer();
1821     TTree* clustersTree = loader->TreeR();
1822     if (fRawReader && !reconstructor->HasDigitConversion()) {
1823       reconstructor->Reconstruct(fRawReader, clustersTree);
1824     } else {
1825       loader->LoadDigits("read");
1826       TTree* digitsTree = loader->TreeD();
1827       if (!digitsTree) {
1828         AliError(Form("Can't get the %s digits tree", fgkDetectorName[iDet]));
1829         if (fStopOnError) return kFALSE;
1830       } else {
1831         reconstructor->Reconstruct(digitsTree, clustersTree);
1832       }
1833       loader->UnloadDigits();
1834     }
1835
1836     // In-loop QA for local reconstrucion 
1837                 TString detQAStr(fQADetectors) ; 
1838                 if (fRunQA && fInLoopQA) 
1839                         fQASteer->RunOneEventInOneDetector(iDet, clustersTree) ; 
1840     
1841         loader->WriteRecPoints("OVERWRITE");
1842         loader->UnloadRecPoints();
1843         AliSysInfo::AddStamp(Form("LRec%s_%d",fgkDetectorName[iDet],eventNr), iDet,1,eventNr);
1844         }
1845         if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
1846     AliError(Form("the following detectors were not found: %s",
1847                   detStr.Data()));
1848     if (fStopOnError) return kFALSE;
1849   }
1850   eventNr++;
1851   return kTRUE;
1852 }
1853
1854 //_____________________________________________________________________________
1855 Bool_t AliReconstruction::RunVertexFinder(AliESDEvent*& esd)
1856 {
1857 // run the barrel tracking
1858
1859   AliCodeTimerAuto("")
1860
1861   AliESDVertex* vertex = NULL;
1862   Double_t vtxPos[3] = {0, 0, 0};
1863   Double_t vtxErr[3] = {0.07, 0.07, 0.1};
1864   TArrayF mcVertex(3); 
1865   if (fRunLoader->GetHeader() && fRunLoader->GetHeader()->GenEventHeader()) {
1866     fRunLoader->GetHeader()->GenEventHeader()->PrimaryVertex(mcVertex);
1867     for (Int_t i = 0; i < 3; i++) vtxPos[i] = mcVertex[i];
1868   }
1869
1870   if (fVertexer) {
1871     AliInfo("running the ITS vertex finder");
1872     if (fLoader[0]) {
1873       fLoader[0]->LoadRecPoints();
1874       TTree* cltree = fLoader[0]->TreeR();
1875       if (cltree) {
1876         if(fDiamondProfile) fVertexer->SetVtxStart(fDiamondProfile);
1877         vertex = fVertexer->FindVertexForCurrentEvent(cltree);
1878       }
1879       else {
1880         AliError("Can't get the ITS cluster tree");
1881       }
1882       fLoader[0]->UnloadRecPoints();
1883     }
1884     else {
1885       AliError("Can't get the ITS loader");
1886     }
1887     if(!vertex){
1888       AliWarning("Vertex not found");
1889       vertex = new AliESDVertex();
1890       vertex->SetName("default");
1891     }
1892     else {
1893       vertex->SetName("reconstructed");
1894     }
1895
1896   } else {
1897     AliInfo("getting the primary vertex from MC");
1898     vertex = new AliESDVertex(vtxPos, vtxErr);
1899   }
1900
1901   if (vertex) {
1902     vertex->GetXYZ(vtxPos);
1903     vertex->GetSigmaXYZ(vtxErr);
1904   } else {
1905     AliWarning("no vertex reconstructed");
1906     vertex = new AliESDVertex(vtxPos, vtxErr);
1907   }
1908   esd->SetPrimaryVertexSPD(vertex);
1909   // if SPD multiplicity has been determined, it is stored in the ESD
1910   AliMultiplicity *mult = fVertexer->GetMultiplicity();
1911   if(mult)esd->SetMultiplicity(mult);
1912
1913   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
1914     if (fTracker[iDet]) fTracker[iDet]->SetVertex(vtxPos, vtxErr);
1915   }  
1916   delete vertex;
1917
1918   return kTRUE;
1919 }
1920
1921 //_____________________________________________________________________________
1922 Bool_t AliReconstruction::RunHLTTracking(AliESDEvent*& esd)
1923 {
1924 // run the HLT barrel tracking
1925
1926   AliCodeTimerAuto("")
1927
1928   if (!fRunLoader) {
1929     AliError("Missing runLoader!");
1930     return kFALSE;
1931   }
1932
1933   AliInfo("running HLT tracking");
1934
1935   // Get a pointer to the HLT reconstructor
1936   AliReconstructor *reconstructor = GetReconstructor(fgkNDetectors-1);
1937   if (!reconstructor) return kFALSE;
1938
1939   // TPC + ITS
1940   for (Int_t iDet = 1; iDet >= 0; iDet--) {
1941     TString detName = fgkDetectorName[iDet];
1942     AliDebug(1, Form("%s HLT tracking", detName.Data()));
1943     reconstructor->SetOption(detName.Data());
1944     AliTracker *tracker = reconstructor->CreateTracker();
1945     if (!tracker) {
1946       AliWarning(Form("couldn't create a HLT tracker for %s", detName.Data()));
1947       if (fStopOnError) return kFALSE;
1948       continue;
1949     }
1950     Double_t vtxPos[3];
1951     Double_t vtxErr[3]={0.005,0.005,0.010};
1952     const AliESDVertex *vertex = esd->GetVertex();
1953     vertex->GetXYZ(vtxPos);
1954     tracker->SetVertex(vtxPos,vtxErr);
1955     if(iDet != 1) {
1956       fLoader[iDet]->LoadRecPoints("read");
1957       TTree* tree = fLoader[iDet]->TreeR();
1958       if (!tree) {
1959         AliError(Form("Can't get the %s cluster tree", detName.Data()));
1960         return kFALSE;
1961       }
1962       tracker->LoadClusters(tree);
1963     }
1964     if (tracker->Clusters2Tracks(esd) != 0) {
1965       AliError(Form("HLT %s Clusters2Tracks failed", fgkDetectorName[iDet]));
1966       return kFALSE;
1967     }
1968     if(iDet != 1) {
1969       tracker->UnloadClusters();
1970     }
1971     delete tracker;
1972   }
1973
1974   return kTRUE;
1975 }
1976
1977 //_____________________________________________________________________________
1978 Bool_t AliReconstruction::RunMuonTracking(AliESDEvent*& esd)
1979 {
1980 // run the muon spectrometer tracking
1981
1982   AliCodeTimerAuto("")
1983
1984   if (!fRunLoader) {
1985     AliError("Missing runLoader!");
1986     return kFALSE;
1987   }
1988   Int_t iDet = 7; // for MUON
1989
1990   AliInfo("is running...");
1991
1992   // Get a pointer to the MUON reconstructor
1993   AliReconstructor *reconstructor = GetReconstructor(iDet);
1994   if (!reconstructor) return kFALSE;
1995
1996   
1997   TString detName = fgkDetectorName[iDet];
1998   AliDebug(1, Form("%s tracking", detName.Data()));
1999   AliTracker *tracker =  reconstructor->CreateTracker();
2000   if (!tracker) {
2001     AliWarning(Form("couldn't create a tracker for %s", detName.Data()));
2002     return kFALSE;
2003   }
2004      
2005   // read RecPoints
2006   fLoader[iDet]->LoadRecPoints("read");  
2007
2008   tracker->LoadClusters(fLoader[iDet]->TreeR());
2009   
2010   Int_t rv = tracker->Clusters2Tracks(esd);
2011   
2012   if ( rv )
2013   {
2014     AliError(Form("%s Clusters2Tracks failed", fgkDetectorName[iDet]));
2015     return kFALSE;
2016   }
2017   
2018   fLoader[iDet]->UnloadRecPoints();
2019
2020   tracker->UnloadClusters();
2021   
2022   delete tracker;
2023   
2024   return kTRUE;
2025 }
2026
2027
2028 //_____________________________________________________________________________
2029 Bool_t AliReconstruction::RunTracking(AliESDEvent*& esd)
2030 {
2031 // run the barrel tracking
2032   static Int_t eventNr=0;
2033   AliCodeTimerAuto("")
2034
2035   AliInfo("running tracking");
2036
2037   //Fill the ESD with the T0 info (will be used by the TOF) 
2038   if (fReconstructor[11] && fLoader[11]) {
2039     fLoader[11]->LoadRecPoints("READ");
2040     TTree *treeR = fLoader[11]->TreeR();
2041     GetReconstructor(11)->FillESD((TTree *)NULL,treeR,esd);
2042   }
2043
2044   // pass 1: TPC + ITS inwards
2045   for (Int_t iDet = 1; iDet >= 0; iDet--) {
2046     if (!fTracker[iDet]) continue;
2047     AliDebug(1, Form("%s tracking", fgkDetectorName[iDet]));
2048
2049     // load clusters
2050     fLoader[iDet]->LoadRecPoints("read");
2051     AliSysInfo::AddStamp(Form("RLoadCluster%s_%d",fgkDetectorName[iDet],eventNr),iDet,1, eventNr);
2052     TTree* tree = fLoader[iDet]->TreeR();
2053     if (!tree) {
2054       AliError(Form("Can't get the %s cluster tree", fgkDetectorName[iDet]));
2055       return kFALSE;
2056     }
2057     fTracker[iDet]->LoadClusters(tree);
2058     AliSysInfo::AddStamp(Form("TLoadCluster%s_%d",fgkDetectorName[iDet],eventNr), iDet,2, eventNr);
2059     // run tracking
2060     if (fTracker[iDet]->Clusters2Tracks(esd) != 0) {
2061       AliError(Form("%s Clusters2Tracks failed", fgkDetectorName[iDet]));
2062       return kFALSE;
2063     }
2064     // preliminary PID in TPC needed by the ITS tracker
2065     if (iDet == 1) {
2066       GetReconstructor(1)->FillESD((TTree*)NULL, (TTree*)NULL, esd);
2067       AliESDpid::MakePID(esd);
2068     } 
2069     AliSysInfo::AddStamp(Form("Tracking0%s_%d",fgkDetectorName[iDet],eventNr), iDet,3,eventNr);
2070   }
2071
2072   // pass 2: ALL backwards
2073
2074   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
2075     if (!fTracker[iDet]) continue;
2076     AliDebug(1, Form("%s back propagation", fgkDetectorName[iDet]));
2077
2078     // load clusters
2079     if (iDet > 1) {     // all except ITS, TPC
2080       TTree* tree = NULL;
2081       fLoader[iDet]->LoadRecPoints("read");
2082       AliSysInfo::AddStamp(Form("RLoadCluster0%s_%d",fgkDetectorName[iDet],eventNr), iDet,1, eventNr);
2083       tree = fLoader[iDet]->TreeR();
2084       if (!tree) {
2085         AliError(Form("Can't get the %s cluster tree", fgkDetectorName[iDet]));
2086         return kFALSE;
2087       }
2088       fTracker[iDet]->LoadClusters(tree); 
2089       AliSysInfo::AddStamp(Form("TLoadCluster0%s_%d",fgkDetectorName[iDet],eventNr), iDet,2, eventNr);
2090     }
2091
2092     // run tracking
2093     if (iDet>1) // start filling residuals for the "outer" detectors
2094     if (fRunGlobalQA) AliTracker::SetFillResiduals(kTRUE);     
2095
2096     if (fTracker[iDet]->PropagateBack(esd) != 0) {
2097       AliError(Form("%s backward propagation failed", fgkDetectorName[iDet]));
2098       //      return kFALSE;
2099     }
2100
2101     // unload clusters
2102     if (iDet > 3) {     // all except ITS, TPC, TRD and TOF
2103       fTracker[iDet]->UnloadClusters();
2104       fLoader[iDet]->UnloadRecPoints();
2105     }
2106     // updated PID in TPC needed by the ITS tracker -MI
2107     if (iDet == 1) {
2108       GetReconstructor(1)->FillESD((TTree*)NULL, (TTree*)NULL, esd);
2109       AliESDpid::MakePID(esd);
2110     }
2111     AliSysInfo::AddStamp(Form("Tracking1%s_%d",fgkDetectorName[iDet],eventNr), iDet,3, eventNr);
2112   }
2113   //stop filling residuals for the "outer" detectors
2114   if (fRunGlobalQA) AliTracker::SetFillResiduals(kFALSE);     
2115
2116   // pass 3: TRD + TPC + ITS refit inwards
2117
2118   for (Int_t iDet = 2; iDet >= 0; iDet--) {
2119     if (!fTracker[iDet]) continue;
2120     AliDebug(1, Form("%s inward refit", fgkDetectorName[iDet]));
2121
2122     // run tracking
2123     if (iDet<2) // start filling residuals for TPC and ITS
2124     if (fRunGlobalQA) AliTracker::SetFillResiduals(kTRUE);     
2125
2126     if (fTracker[iDet]->RefitInward(esd) != 0) {
2127       AliError(Form("%s inward refit failed", fgkDetectorName[iDet]));
2128       //      return kFALSE;
2129     }
2130     // run postprocessing
2131     if (fTracker[iDet]->PostProcess(esd) != 0) {
2132       AliError(Form("%s postprocessing failed", fgkDetectorName[iDet]));
2133       //      return kFALSE;
2134     }
2135     AliSysInfo::AddStamp(Form("Tracking2%s_%d",fgkDetectorName[iDet],eventNr), iDet,3, eventNr);
2136   }
2137
2138   // write space-points to the ESD in case alignment data output
2139   // is switched on
2140   if (fWriteAlignmentData)
2141     WriteAlignmentData(esd);
2142
2143   for (Int_t iDet = 3; iDet >= 0; iDet--) {
2144     if (!fTracker[iDet]) continue;
2145     // unload clusters
2146     fTracker[iDet]->UnloadClusters();
2147     AliSysInfo::AddStamp(Form("TUnloadCluster%s_%d",fgkDetectorName[iDet],eventNr), iDet,4, eventNr);
2148     fLoader[iDet]->UnloadRecPoints();
2149     AliSysInfo::AddStamp(Form("RUnloadCluster%s_%d",fgkDetectorName[iDet],eventNr), iDet,5, eventNr);
2150   }
2151   // stop filling residuals for TPC and ITS
2152   if (fRunGlobalQA) AliTracker::SetFillResiduals(kFALSE);     
2153
2154   eventNr++;
2155   return kTRUE;
2156 }
2157
2158 //_____________________________________________________________________________
2159 Bool_t AliReconstruction::CleanESD(AliESDEvent *esd){
2160   //
2161   // Remove the data which are not needed for the physics analysis.
2162   //
2163
2164   Int_t nTracks=esd->GetNumberOfTracks();
2165   Int_t nV0s=esd->GetNumberOfV0s();
2166   AliInfo
2167   (Form("Number of ESD tracks and V0s before cleaning: %d %d",nTracks,nV0s));
2168
2169   Float_t cleanPars[]={fV0DCAmax,fV0CsPmin,fDmax,fZmax};
2170   Bool_t rc=esd->Clean(cleanPars);
2171
2172   nTracks=esd->GetNumberOfTracks();
2173   nV0s=esd->GetNumberOfV0s();
2174   AliInfo
2175   (Form("Number of ESD tracks and V0s after cleaning %d %d",nTracks,nV0s));
2176
2177   return rc;
2178 }
2179
2180 //_____________________________________________________________________________
2181 Bool_t AliReconstruction::FillESD(AliESDEvent*& esd, const TString& detectors)
2182 {
2183 // fill the event summary data
2184
2185   AliCodeTimerAuto("")
2186     static Int_t eventNr=0; 
2187   TString detStr = detectors;
2188   
2189   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
2190   if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
2191     AliReconstructor* reconstructor = GetReconstructor(iDet);
2192     if (!reconstructor) continue;
2193     AliDebug(1, Form("filling ESD for %s", fgkDetectorName[iDet]));
2194     TTree* clustersTree = NULL;
2195     if (fLoader[iDet]) {
2196       fLoader[iDet]->LoadRecPoints("read");
2197       clustersTree = fLoader[iDet]->TreeR();
2198       if (!clustersTree) {
2199         AliError(Form("Can't get the %s clusters tree", 
2200                       fgkDetectorName[iDet]));
2201         if (fStopOnError) return kFALSE;
2202       }
2203     }
2204     if (fRawReader && !reconstructor->HasDigitConversion()) {
2205       reconstructor->FillESD(fRawReader, clustersTree, esd);
2206     } else {
2207       TTree* digitsTree = NULL;
2208       if (fLoader[iDet]) {
2209         fLoader[iDet]->LoadDigits("read");
2210         digitsTree = fLoader[iDet]->TreeD();
2211         if (!digitsTree) {
2212           AliError(Form("Can't get the %s digits tree", 
2213                         fgkDetectorName[iDet]));
2214           if (fStopOnError) return kFALSE;
2215         }
2216       }
2217       reconstructor->FillESD(digitsTree, clustersTree, esd);
2218       if (fLoader[iDet]) fLoader[iDet]->UnloadDigits();
2219     }
2220     if (fLoader[iDet]) {
2221       fLoader[iDet]->UnloadRecPoints();
2222     }
2223   }
2224
2225   if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
2226     AliError(Form("the following detectors were not found: %s", 
2227                   detStr.Data()));
2228     if (fStopOnError) return kFALSE;
2229   }
2230   AliSysInfo::AddStamp(Form("FillESD%d",eventNr), 0,1, eventNr);
2231   eventNr++;
2232   return kTRUE;
2233 }
2234
2235 //_____________________________________________________________________________
2236 Bool_t AliReconstruction::FillTriggerESD(AliESDEvent*& esd)
2237 {
2238   // Reads the trigger decision which is
2239   // stored in Trigger.root file and fills
2240   // the corresponding esd entries
2241
2242   AliCodeTimerAuto("")
2243   
2244   AliInfo("Filling trigger information into the ESD");
2245
2246   if (fRawReader) {
2247     AliCTPRawStream input(fRawReader);
2248     if (!input.Next()) {
2249       AliWarning("No valid CTP (trigger) DDL raw data is found ! The trigger info is taken from the event header!");
2250     }
2251     else {
2252       if (esd->GetTriggerMask() != input.GetClassMask())
2253         AliError(Form("Invalid trigger pattern found in CTP raw-data: %llx %llx",
2254                       input.GetClassMask(),esd->GetTriggerMask()));
2255       if (esd->GetOrbitNumber() != input.GetOrbitID())
2256         AliError(Form("Invalid orbit id found in CTP raw-data: %x %x",
2257                       input.GetOrbitID(),esd->GetOrbitNumber()));
2258       if (esd->GetBunchCrossNumber() != input.GetBCID())
2259         AliError(Form("Invalid bunch-crossing id found in CTP raw-data: %x %x",
2260                       input.GetBCID(),esd->GetBunchCrossNumber()));
2261     }
2262
2263   // Here one has to add the filling of trigger inputs and
2264   // interaction records
2265   // ...
2266   }
2267   return kTRUE;
2268 }
2269
2270
2271
2272
2273
2274 //_____________________________________________________________________________
2275 Bool_t AliReconstruction::FillRawEventHeaderESD(AliESDEvent*& esd)
2276 {
2277   // 
2278   // Filling information from RawReader Header
2279   // 
2280
2281   if (!fRawReader) return kFALSE;
2282
2283   AliInfo("Filling information from RawReader Header");
2284
2285   esd->SetBunchCrossNumber(fRawReader->GetBCID());
2286   esd->SetOrbitNumber(fRawReader->GetOrbitID());
2287   esd->SetPeriodNumber(fRawReader->GetPeriod());
2288
2289   esd->SetTimeStamp(fRawReader->GetTimestamp());  
2290   esd->SetEventType(fRawReader->GetType());
2291
2292   return kTRUE;
2293 }
2294
2295
2296 //_____________________________________________________________________________
2297 Bool_t AliReconstruction::IsSelected(TString detName, TString& detectors) const
2298 {
2299 // check whether detName is contained in detectors
2300 // if yes, it is removed from detectors
2301
2302   // check if all detectors are selected
2303   if ((detectors.CompareTo("ALL") == 0) ||
2304       detectors.BeginsWith("ALL ") ||
2305       detectors.EndsWith(" ALL") ||
2306       detectors.Contains(" ALL ")) {
2307     detectors = "ALL";
2308     return kTRUE;
2309   }
2310
2311   // search for the given detector
2312   Bool_t result = kFALSE;
2313   if ((detectors.CompareTo(detName) == 0) ||
2314       detectors.BeginsWith(detName+" ") ||
2315       detectors.EndsWith(" "+detName) ||
2316       detectors.Contains(" "+detName+" ")) {
2317     detectors.ReplaceAll(detName, "");
2318     result = kTRUE;
2319   }
2320
2321   // clean up the detectors string
2322   while (detectors.Contains("  ")) detectors.ReplaceAll("  ", " ");
2323   while (detectors.BeginsWith(" ")) detectors.Remove(0, 1);
2324   while (detectors.EndsWith(" ")) detectors.Remove(detectors.Length()-1, 1);
2325
2326   return result;
2327 }
2328
2329 //_____________________________________________________________________________
2330 Bool_t AliReconstruction::InitRunLoader()
2331 {
2332 // get or create the run loader
2333
2334   if (gAlice) delete gAlice;
2335   gAlice = NULL;
2336
2337   if (!gSystem->AccessPathName(fGAliceFileName.Data())) { // galice.root exists
2338     // load all base libraries to get the loader classes
2339     TString libs = gSystem->GetLibraries();
2340     for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
2341       TString detName = fgkDetectorName[iDet];
2342       if (detName == "HLT") continue;
2343       if (libs.Contains("lib" + detName + "base.so")) continue;
2344       gSystem->Load("lib" + detName + "base.so");
2345     }
2346     fRunLoader = AliRunLoader::Open(fGAliceFileName.Data());
2347     if (!fRunLoader) {
2348       AliError(Form("no run loader found in file %s", fGAliceFileName.Data()));
2349       CleanUp();
2350       return kFALSE;
2351     }
2352
2353     fRunLoader->CdGAFile();
2354     fRunLoader->LoadgAlice();
2355
2356     //PH This is a temporary fix to give access to the kinematics
2357     //PH that is needed for the labels of ITS clusters
2358     fRunLoader->LoadHeader();
2359     fRunLoader->LoadKinematics();
2360
2361   } else {               // galice.root does not exist
2362     if (!fRawReader) {
2363       AliError(Form("the file %s does not exist", fGAliceFileName.Data()));
2364     }
2365     fRunLoader = AliRunLoader::Open(fGAliceFileName.Data(),
2366                                     AliConfig::GetDefaultEventFolderName(),
2367                                     "recreate");
2368     if (!fRunLoader) {
2369       AliError(Form("could not create run loader in file %s", 
2370                     fGAliceFileName.Data()));
2371       CleanUp();
2372       return kFALSE;
2373     }
2374     fIsNewRunLoader = kTRUE;
2375     fRunLoader->MakeTree("E");
2376
2377     if (fNumberOfEventsPerFile > 0)
2378       fRunLoader->SetNumberOfEventsPerFile(fNumberOfEventsPerFile);
2379     else
2380       fRunLoader->SetNumberOfEventsPerFile((UInt_t)-1);
2381   }
2382
2383   return kTRUE;
2384 }
2385
2386 //_____________________________________________________________________________
2387 AliReconstructor* AliReconstruction::GetReconstructor(Int_t iDet)
2388 {
2389 // get the reconstructor object and the loader for a detector
2390
2391   if (fReconstructor[iDet]) {
2392     if (fRecoParam.GetDetRecoParamArray(iDet) && !AliReconstructor::GetRecoParam(iDet)) {
2393       const AliDetectorRecoParam *par = fRecoParam.GetDetRecoParam(iDet);
2394       fReconstructor[iDet]->SetRecoParam(par);
2395     }
2396     return fReconstructor[iDet];
2397   }
2398
2399   // load the reconstructor object
2400   TPluginManager* pluginManager = gROOT->GetPluginManager();
2401   TString detName = fgkDetectorName[iDet];
2402   TString recName = "Ali" + detName + "Reconstructor";
2403
2404   if (!fIsNewRunLoader && !fRunLoader->GetLoader(detName+"Loader") && (detName != "HLT")) return NULL;
2405
2406   AliReconstructor* reconstructor = NULL;
2407   // first check if a plugin is defined for the reconstructor
2408   TPluginHandler* pluginHandler = 
2409     pluginManager->FindHandler("AliReconstructor", detName);
2410   // if not, add a plugin for it
2411   if (!pluginHandler) {
2412     AliDebug(1, Form("defining plugin for %s", recName.Data()));
2413     TString libs = gSystem->GetLibraries();
2414     if (libs.Contains("lib" + detName + "base.so") ||
2415         (gSystem->Load("lib" + detName + "base.so") >= 0)) {
2416       pluginManager->AddHandler("AliReconstructor", detName, 
2417                                 recName, detName + "rec", recName + "()");
2418     } else {
2419       pluginManager->AddHandler("AliReconstructor", detName, 
2420                                 recName, detName, recName + "()");
2421     }
2422     pluginHandler = pluginManager->FindHandler("AliReconstructor", detName);
2423   }
2424   if (pluginHandler && (pluginHandler->LoadPlugin() == 0)) {
2425     reconstructor = (AliReconstructor*) pluginHandler->ExecPlugin(0);
2426   }
2427   if (reconstructor) {
2428     TObject* obj = fOptions.FindObject(detName.Data());
2429     if (obj) reconstructor->SetOption(obj->GetTitle());
2430     reconstructor->Init();
2431     fReconstructor[iDet] = reconstructor;
2432   }
2433
2434   // get or create the loader
2435   if (detName != "HLT") {
2436     fLoader[iDet] = fRunLoader->GetLoader(detName + "Loader");
2437     if (!fLoader[iDet]) {
2438       AliConfig::Instance()
2439         ->CreateDetectorFolders(fRunLoader->GetEventFolder(), 
2440                                 detName, detName);
2441       // first check if a plugin is defined for the loader
2442       pluginHandler = 
2443         pluginManager->FindHandler("AliLoader", detName);
2444       // if not, add a plugin for it
2445       if (!pluginHandler) {
2446         TString loaderName = "Ali" + detName + "Loader";
2447         AliDebug(1, Form("defining plugin for %s", loaderName.Data()));
2448         pluginManager->AddHandler("AliLoader", detName, 
2449                                   loaderName, detName + "base", 
2450                                   loaderName + "(const char*, TFolder*)");
2451         pluginHandler = pluginManager->FindHandler("AliLoader", detName);
2452       }
2453       if (pluginHandler && (pluginHandler->LoadPlugin() == 0)) {
2454         fLoader[iDet] = 
2455           (AliLoader*) pluginHandler->ExecPlugin(2, detName.Data(), 
2456                                                  fRunLoader->GetEventFolder());
2457       }
2458       if (!fLoader[iDet]) {   // use default loader
2459         fLoader[iDet] = new AliLoader(detName, fRunLoader->GetEventFolder());
2460       }
2461       if (!fLoader[iDet]) {
2462         AliWarning(Form("couldn't get loader for %s", detName.Data()));
2463         if (fStopOnError) return NULL;
2464       } else {
2465         fRunLoader->AddLoader(fLoader[iDet]);
2466         fRunLoader->CdGAFile();
2467         if (gFile && !gFile->IsWritable()) gFile->ReOpen("UPDATE");
2468         fRunLoader->Write(0, TObject::kOverwrite);
2469       }
2470     }
2471   }
2472       
2473   if (fRecoParam.GetDetRecoParamArray(iDet) && !AliReconstructor::GetRecoParam(iDet)) {
2474     const AliDetectorRecoParam *par = fRecoParam.GetDetRecoParam(iDet);
2475     reconstructor->SetRecoParam(par);
2476   }
2477   return reconstructor;
2478 }
2479
2480 //_____________________________________________________________________________
2481 Bool_t AliReconstruction::CreateVertexer()
2482 {
2483 // create the vertexer
2484
2485   fVertexer = NULL;
2486   AliReconstructor* itsReconstructor = GetReconstructor(0);
2487   if (itsReconstructor) {
2488     fVertexer = itsReconstructor->CreateVertexer();
2489   }
2490   if (!fVertexer) {
2491     AliWarning("couldn't create a vertexer for ITS");
2492     if (fStopOnError) return kFALSE;
2493   }
2494
2495   return kTRUE;
2496 }
2497
2498 //_____________________________________________________________________________
2499 Bool_t AliReconstruction::CreateTrackers(const TString& detectors)
2500 {
2501 // create the trackers
2502
2503   TString detStr = detectors;
2504   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
2505     if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
2506     AliReconstructor* reconstructor = GetReconstructor(iDet);
2507     if (!reconstructor) continue;
2508     TString detName = fgkDetectorName[iDet];
2509     if (detName == "HLT") {
2510       fRunHLTTracking = kTRUE;
2511       continue;
2512     }
2513     if (detName == "MUON") {
2514       fRunMuonTracking = kTRUE;
2515       continue;
2516     }
2517
2518
2519     fTracker[iDet] = reconstructor->CreateTracker();
2520     if (!fTracker[iDet] && (iDet < 7)) {
2521       AliWarning(Form("couldn't create a tracker for %s", detName.Data()));
2522       if (fStopOnError) return kFALSE;
2523     }
2524     AliSysInfo::AddStamp(Form("LTracker%s",fgkDetectorName[iDet]), iDet,0);
2525   }
2526
2527   return kTRUE;
2528 }
2529
2530 //_____________________________________________________________________________
2531 void AliReconstruction::CleanUp()
2532 {
2533 // delete trackers and the run loader and close and delete the file
2534
2535   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
2536     delete fReconstructor[iDet];
2537     fReconstructor[iDet] = NULL;
2538     fLoader[iDet] = NULL;
2539     delete fTracker[iDet];
2540     fTracker[iDet] = NULL;
2541   }
2542   delete fRunInfo;
2543   fRunInfo = NULL;
2544
2545   delete fVertexer;
2546   fVertexer = NULL;
2547
2548   delete ftVertexer;
2549   ftVertexer = NULL;
2550   
2551   if(!(AliCDBManager::Instance()->GetCacheFlag())) {
2552     delete fDiamondProfile;
2553     fDiamondProfile = NULL;
2554     delete fDiamondProfileTPC;
2555     fDiamondProfileTPC = NULL;
2556   }
2557   delete fGRPData;
2558   fGRPData = NULL;
2559
2560   delete fRunLoader;
2561   fRunLoader = NULL;
2562   delete fRawReader;
2563   fRawReader = NULL;
2564   delete fParentRawReader;
2565   fParentRawReader=NULL;
2566
2567   if (ffile) {
2568     ffile->Close();
2569     delete ffile;
2570     ffile = NULL;
2571   }
2572 }
2573
2574 void AliReconstruction::WriteAlignmentData(AliESDEvent* esd)
2575 {
2576   // Write space-points which are then used in the alignment procedures
2577   // For the moment only ITS, TPC, TRD and TOF
2578
2579   Int_t ntracks = esd->GetNumberOfTracks();
2580   for (Int_t itrack = 0; itrack < ntracks; itrack++)
2581     {
2582       AliESDtrack *track = esd->GetTrack(itrack);
2583       Int_t nsp = 0;
2584       Int_t idx[200];
2585       for (Int_t iDet = 3; iDet >= 0; iDet--) {// TOF, TRD, TPC, ITS clusters
2586           nsp += track->GetNcls(iDet);
2587
2588           if (iDet==0) { // ITS "extra" clusters
2589              track->GetClusters(iDet,idx);
2590              for (Int_t i=6; i<12; i++) if(idx[i] >= 0) nsp++;
2591           }  
2592       }
2593
2594       if (nsp) {
2595         AliTrackPointArray *sp = new AliTrackPointArray(nsp);
2596         track->SetTrackPointArray(sp);
2597         Int_t isptrack = 0;
2598         for (Int_t iDet = 3; iDet >= 0; iDet--) {
2599           AliTracker *tracker = fTracker[iDet];
2600           if (!tracker) continue;
2601           Int_t nspdet = track->GetClusters(iDet,idx);
2602
2603           if (iDet==0) // ITS "extra" clusters             
2604              for (Int_t i=6; i<12; i++) if(idx[i] >= 0) nspdet++;
2605
2606           if (nspdet <= 0) continue;
2607           AliTrackPoint p;
2608           Int_t isp = 0;
2609           Int_t isp2 = 0;
2610           while (isp2 < nspdet) {
2611             Bool_t isvalid=kTRUE;
2612
2613             Int_t index=idx[isp++];
2614             if (index < 0) continue;
2615
2616             TString dets = fgkDetectorName[iDet];
2617             if ((fUseTrackingErrorsForAlignment.CompareTo(dets) == 0) ||
2618             fUseTrackingErrorsForAlignment.BeginsWith(dets+" ") ||
2619             fUseTrackingErrorsForAlignment.EndsWith(" "+dets) ||
2620             fUseTrackingErrorsForAlignment.Contains(" "+dets+" ")) {
2621               isvalid = tracker->GetTrackPointTrackingError(index,p,track);
2622             } else {
2623               isvalid = tracker->GetTrackPoint(index,p); 
2624             } 
2625             isp2++;
2626             if (!isvalid) continue;
2627             sp->AddPoint(isptrack,&p); isptrack++;
2628           }
2629         }       
2630       }
2631     }
2632 }
2633
2634 //_____________________________________________________________________________
2635 void AliReconstruction::FillRawDataErrorLog(Int_t iEvent, AliESDEvent* esd)
2636 {
2637   // The method reads the raw-data error log
2638   // accumulated within the rawReader.
2639   // It extracts the raw-data errors related to
2640   // the current event and stores them into
2641   // a TClonesArray inside the esd object.
2642
2643   if (!fRawReader) return;
2644
2645   for(Int_t i = 0; i < fRawReader->GetNumberOfErrorLogs(); i++) {
2646
2647     AliRawDataErrorLog *log = fRawReader->GetErrorLog(i);
2648     if (!log) continue;
2649     if (iEvent != log->GetEventNumber()) continue;
2650
2651     esd->AddRawDataErrorLog(log);
2652   }
2653
2654 }
2655
2656 TNamed* AliReconstruction::CopyFileToTNamed(TString fPath,TString pName){
2657   // Dump a file content into a char in TNamed
2658   ifstream in;
2659   in.open(fPath.Data(),ios::in | ios::binary|ios::ate);
2660   Int_t kBytes = (Int_t)in.tellg();
2661   printf("Size: %d \n",kBytes);
2662   TNamed *fn = 0;
2663   if(in.good()){
2664     char* memblock = new char [kBytes];
2665     in.seekg (0, ios::beg);
2666     in.read (memblock, kBytes);
2667     in.close();
2668     TString fData(memblock,kBytes);
2669     fn = new TNamed(pName,fData);
2670     printf("fData Size: %d \n",fData.Sizeof());
2671     printf("pName Size: %d \n",pName.Sizeof());
2672     printf("fn    Size: %d \n",fn->Sizeof());
2673     delete[] memblock;
2674   }
2675   else{
2676     AliInfo(Form("Could not Open %s\n",fPath.Data()));
2677   }
2678
2679   return fn;
2680 }
2681
2682 void AliReconstruction::TNamedToFile(TTree* fTree, TString pName){
2683   // This is not really needed in AliReconstruction at the moment
2684   // but can serve as a template
2685
2686   TList *fList = fTree->GetUserInfo();
2687   TNamed *fn = (TNamed*)fList->FindObject(pName.Data());
2688   printf("fn Size: %d \n",fn->Sizeof());
2689
2690   TString fTmp(fn->GetName()); // to be 100% sure in principle pName also works
2691   const char* cdata = fn->GetTitle();
2692   printf("fTmp Size %d\n",fTmp.Sizeof());
2693
2694   int size = fn->Sizeof()-fTmp.Sizeof()-sizeof(UChar_t)-sizeof(Int_t); // see dfinition of TString::SizeOf()...
2695   printf("calculated size %d\n",size);
2696   ofstream out(pName.Data(),ios::out | ios::binary);
2697   out.write(cdata,size);
2698   out.close();
2699
2700 }
2701   
2702 //_____________________________________________________________________________
2703 void AliReconstruction::CheckQA()
2704 {
2705 // check the QA of SIM for this run and remove the detectors 
2706 // with status Fatal
2707   
2708         TString newRunLocalReconstruction ; 
2709         TString newRunTracking ;
2710         TString newFillESD ;
2711          
2712         for (Int_t iDet = 0; iDet < AliQA::kNDET; iDet++) {
2713                 TString detName(AliQA::GetDetName(iDet)) ;
2714                 AliQA * qa = AliQA::Instance(AliQA::DETECTORINDEX_t(iDet)) ; 
2715                 if ( qa->IsSet(AliQA::DETECTORINDEX_t(iDet), AliQA::kSIM, AliQA::kFATAL)) {
2716                                 AliInfo(Form("QA status for %s in Hits and/or SDIGITS  and/or Digits was Fatal; No reconstruction performed", detName.Data())) ;
2717                 } else {
2718                         if ( fRunLocalReconstruction.Contains(AliQA::GetDetName(iDet)) || 
2719                                         fRunLocalReconstruction.Contains("ALL") )  {
2720                                 newRunLocalReconstruction += detName ; 
2721                                 newRunLocalReconstruction += " " ;                      
2722                         }
2723                         if ( fRunTracking.Contains(AliQA::GetDetName(iDet)) || 
2724                                         fRunTracking.Contains("ALL") )  {
2725                                 newRunTracking += detName ; 
2726                                 newRunTracking += " " ;                         
2727                         }
2728                         if ( fFillESD.Contains(AliQA::GetDetName(iDet)) || 
2729                                         fFillESD.Contains("ALL") )  {
2730                                 newFillESD += detName ; 
2731                                 newFillESD += " " ;                     
2732                         }
2733                 }
2734         }
2735         fRunLocalReconstruction = newRunLocalReconstruction ; 
2736         fRunTracking            = newRunTracking ; 
2737         fFillESD                = newFillESD ; 
2738 }
2739
2740 //_____________________________________________________________________________
2741 Int_t AliReconstruction::GetDetIndex(const char* detector)
2742 {
2743   // return the detector index corresponding to detector
2744   Int_t index = -1 ; 
2745   for (index = 0; index < fgkNDetectors ; index++) {
2746     if ( strcmp(detector, fgkDetectorName[index]) == 0 )
2747         break ; 
2748   }     
2749   return index ; 
2750 }
2751 //_____________________________________________________________________________
2752 Bool_t AliReconstruction::FinishPlaneEff() {
2753  //
2754  // Here execute all the necessary operationis, at the end of the tracking phase,
2755  // in case that evaluation of PlaneEfficiencies was required for some detector.
2756  // E.g., write into a DataBase file the PlaneEfficiency which have been evaluated.
2757  //
2758  // This Preliminary version works only FOR ITS !!!!!
2759  // other detectors (TOF,TRD, etc. have to develop their specific codes)
2760  //
2761  //  Input: none
2762  //  Return: kTRUE if all operations have been done properly, kFALSE otherwise
2763  //
2764  Bool_t ret=kFALSE;
2765  //for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
2766  for (Int_t iDet = 0; iDet < 1; iDet++) { // for the time being only ITS
2767    //if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
2768    if(fTracker[iDet]) {
2769       AliPlaneEff *planeeff=fTracker[iDet]->GetPlaneEff();
2770       TString name=planeeff->GetName();
2771       name+=".root";
2772       TFile* pefile = TFile::Open(name, "RECREATE");
2773       ret=(Bool_t)planeeff->Write();
2774       pefile->Close();
2775       if(planeeff->GetCreateHistos()) {
2776         TString hname=planeeff->GetName();
2777         hname+="Histo.root";
2778         ret*=planeeff->WriteHistosToFile(hname,"RECREATE");
2779       }
2780    }
2781  }
2782  return ret;
2783 }
2784 //_____________________________________________________________________________
2785 Bool_t AliReconstruction::InitPlaneEff() {
2786 //
2787  // Here execute all the necessary operations, before of the tracking phase,
2788  // for the evaluation of PlaneEfficiencies, in case required for some detectors.
2789  // E.g., read from a DataBase file a first evaluation of the PlaneEfficiency 
2790  // which should be updated/recalculated.
2791  //
2792  // This Preliminary version will work only FOR ITS !!!!!
2793  // other detectors (TOF,TRD, etc. have to develop their specific codes)
2794  //
2795  //  Input: none
2796  //  Return: kTRUE if all operations have been done properly, kFALSE otherwise
2797  //
2798  AliWarning(Form("Implementation of this method not yet done !! Method return kTRUE"));
2799  return kTRUE;
2800 }
2801
2802 //_____________________________________________________________________________
2803 Bool_t AliReconstruction::InitAliEVE()
2804 {
2805   // This method should be called only in case 
2806   // AliReconstruction is run
2807   // within the alieve environment.
2808   // It will initialize AliEVE in a way
2809   // so that it can visualize event processed
2810   // by AliReconstruction.
2811   // The return flag shows whenever the
2812   // AliEVE initialization was successful or not.
2813
2814   TString macroStr;
2815   macroStr.Form("%s/EVE/macros/alieve_online.C",gSystem->ExpandPathName("$ALICE_ROOT"));
2816   AliInfo(Form("Loading AliEVE macro: %s",macroStr.Data()));
2817   if (gROOT->LoadMacro(macroStr.Data()) != 0) return kFALSE;
2818
2819   gROOT->ProcessLine("if (!gAliEveEvent) {gAliEveEvent = new AliEveEventManager();gAliEveEvent->SetAutoLoad(kTRUE);gAliEveEvent->AddNewEventCommand(\"alieve_online_on_new_event()\");gEve->AddEvent(gAliEveEvent);};");
2820   gROOT->ProcessLine("alieve_online_init()");
2821
2822   return kTRUE;
2823 }
2824   
2825 //_____________________________________________________________________________
2826 void AliReconstruction::RunAliEVE()
2827 {
2828   // Runs AliEVE visualisation of
2829   // the current event.
2830   // Should be executed only after
2831   // successful initialization of AliEVE.
2832
2833   AliInfo("Running AliEVE...");
2834   gROOT->ProcessLine(Form("gAliEveEvent->SetEvent((AliRunLoader*)%p,(AliRawReader*)%p,(AliESDEvent*)%p);",fRunLoader,fRawReader,fesd));
2835   gROOT->ProcessLine("gAliEveEvent->StartStopAutoLoadTimer();");
2836   gSystem->Run();
2837 }
2838
2839 //_____________________________________________________________________________
2840 Bool_t AliReconstruction::SetRunQA(TString detAndAction) 
2841 {
2842         // Allows to run QA for a selected set of detectors
2843         // and a selected set of tasks among RAWS, RECPOINTS and ESDS
2844         // all selected detectors run the same selected tasks
2845         
2846         if (!detAndAction.Contains(":")) {
2847                 AliError( Form("%s is a wrong syntax, use \"DetectorList:ActionList\" \n", detAndAction.Data()) ) ;
2848                 fRunQA = kFALSE ;
2849                 return kFALSE ;                 
2850         }
2851         Int_t colon = detAndAction.Index(":") ; 
2852         fQADetectors = detAndAction(0, colon) ; 
2853         if (fQADetectors.Contains("ALL") )
2854                 fQADetectors = fFillESD ; 
2855                 fQATasks   = detAndAction(colon+1, detAndAction.Sizeof() ) ; 
2856         if (fQATasks.Contains("ALL") ) {
2857                 fQATasks = Form("%d %d %d", AliQA::kRAWS, AliQA::kRECPOINTS, AliQA::kESDS) ; 
2858         } else {
2859                 fQATasks.ToUpper() ; 
2860                 TString tempo("") ; 
2861                 if ( fQATasks.Contains("RAW") ) 
2862                         tempo = Form("%d ", AliQA::kRAWS) ; 
2863                 if ( fQATasks.Contains("RECPOINT") ) 
2864                         tempo += Form("%d ", AliQA::kRECPOINTS) ; 
2865                 if ( fQATasks.Contains("ESD") ) 
2866                         tempo += Form("%d ", AliQA::kESDS) ; 
2867                 fQATasks = tempo ; 
2868                 if (fQATasks.IsNull()) {
2869                         AliInfo("No QA requested\n")  ;
2870                         fRunQA = kFALSE ;
2871                         return kTRUE ; 
2872                 }
2873         }       
2874         TString tempo(fQATasks) ; 
2875         tempo.ReplaceAll(Form("%d", AliQA::kRAWS), AliQA::GetTaskName(AliQA::kRAWS))    ;
2876         tempo.ReplaceAll(Form("%d", AliQA::kRECPOINTS), AliQA::GetTaskName(AliQA::kRECPOINTS)) ;        
2877         tempo.ReplaceAll(Form("%d", AliQA::kESDS), AliQA::GetTaskName(AliQA::kESDS)) ;  
2878         AliInfo( Form("QA will be done on \"%s\" for \"%s\"\n", fQADetectors.Data(), tempo.Data()) ) ;  
2879         fRunQA = kTRUE ;
2880         return kTRUE; 
2881
2882
2883 //_____________________________________________________________________________
2884 Bool_t AliReconstruction::InitRecoParams() 
2885 {
2886   // The method accesses OCDB and retrieves all
2887   // the available reco-param objects from there.
2888
2889   Bool_t isOK = kTRUE;
2890
2891   TString detStr = fLoadCDB;
2892   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
2893
2894     if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
2895
2896     if (fRecoParam.GetDetRecoParamArray(iDet)) {
2897       AliInfo(Form("Using custom reconstruction parameters for detector %s",fgkDetectorName[iDet]));
2898       continue;
2899     }
2900
2901     AliInfo(Form("Loading reconstruction parameter objects for detector %s",fgkDetectorName[iDet]));
2902   
2903     AliCDBPath path(fgkDetectorName[iDet],"Calib","RecoParam");
2904     AliCDBEntry *entry=AliCDBManager::Instance()->Get(path.GetPath());
2905     if(!entry){ 
2906       AliWarning(Form("Couldn't find RecoParam entry in OCDB for detector %s",fgkDetectorName[iDet]));
2907       isOK = kFALSE;
2908     }
2909     else {
2910       TObject *recoParamObj = entry->GetObject();
2911       if (dynamic_cast<TObjArray*>(recoParamObj)) {
2912         // The detector has a normal TobjArray of AliDetectorRecoParam objects
2913         // Registering them in AliRecoParam
2914         fRecoParam.AddDetRecoParamArray(iDet,dynamic_cast<TObjArray*>(recoParamObj));
2915       }
2916       else if (dynamic_cast<AliDetectorRecoParam*>(recoParamObj)) {
2917         // The detector has only onse set of reco parameters
2918         // Registering it in AliRecoParam
2919         AliInfo(Form("Single set of reconstruction parameters found for detector %s",fgkDetectorName[iDet]));
2920         dynamic_cast<AliDetectorRecoParam*>(recoParamObj)->SetAsDefault();
2921         fRecoParam.AddDetRecoParam(iDet,dynamic_cast<AliDetectorRecoParam*>(recoParamObj));
2922       }
2923       else {
2924         AliError(Form("No valid RecoParam object found in the OCDB for detector %s",fgkDetectorName[iDet]));
2925         isOK = kFALSE;
2926       }
2927       entry->SetOwner(0);
2928       AliCDBManager::Instance()->UnloadFromCache(path.GetPath());
2929     }
2930   }
2931
2932   fRecoParam.Print();
2933
2934   return isOK;
2935 }
2936
2937 //_____________________________________________________________________________
2938 Bool_t AliReconstruction::GetEventInfo() 
2939 {
2940   // Fill the event info object
2941   // ...
2942   AliCodeTimerAuto("")
2943
2944   AliCentralTrigger *aCTP = NULL;
2945   if (fRawReader) {
2946     fEventInfo.SetEventType(fRawReader->GetType());
2947
2948     ULong64_t mask = fRawReader->GetClassMask();
2949     fEventInfo.SetTriggerMask(mask);
2950     UInt_t clmask = fRawReader->GetDetectorPattern()[0];
2951     fEventInfo.SetTriggerCluster(AliDAQ::ListOfTriggeredDetectors(clmask));
2952
2953     aCTP = new AliCentralTrigger();
2954     TString configstr("");
2955     if (!aCTP->LoadConfiguration(configstr)) { // Load CTP config from OCDB
2956       AliError("No trigger configuration found in OCDB! The trigger configuration information will not be used!");
2957       delete aCTP;
2958       return kFALSE;
2959     }
2960     aCTP->SetClassMask(mask);
2961     aCTP->SetClusterMask(clmask);
2962   }
2963   else {
2964     fEventInfo.SetEventType(AliRawEventHeaderBase::kPhysicsEvent);
2965
2966     if (fRunLoader && (!fRunLoader->LoadTrigger())) {
2967       aCTP = fRunLoader->GetTrigger();
2968       fEventInfo.SetTriggerMask(aCTP->GetClassMask());
2969       fEventInfo.SetTriggerCluster(AliDAQ::ListOfTriggeredDetectors(aCTP->GetClusterMask()));
2970     }
2971     else {
2972       AliWarning("No trigger can be loaded! The trigger information will not be used!");
2973       return kFALSE;
2974     }
2975   }
2976
2977   AliTriggerConfiguration *config = aCTP->GetConfiguration();
2978   if (!config) {
2979     AliError("No trigger configuration has been found! The trigger configuration information will not be used!");
2980     if (fRawReader) delete aCTP;
2981     return kFALSE;
2982   }
2983
2984   UChar_t clustmask = 0;
2985   TString trclasses;
2986   ULong64_t trmask = fEventInfo.GetTriggerMask();
2987   const TObjArray& classesArray = config->GetClasses();
2988   Int_t nclasses = classesArray.GetEntriesFast();
2989   for( Int_t iclass=0; iclass < nclasses; iclass++ ) {
2990     AliTriggerClass* trclass = (AliTriggerClass*)classesArray.At(iclass);
2991     if (trclass) {
2992       Int_t trindex = (Int_t)TMath::Log2(trclass->GetMask());
2993       fesd->SetTriggerClass(trclass->GetName(),trindex);
2994       if (trmask & (1 << trindex)) {
2995         trclasses += " ";
2996         trclasses += trclass->GetName();
2997         trclasses += " ";
2998         clustmask |= trclass->GetCluster()->GetClusterMask();
2999       }
3000     }
3001   }
3002   fEventInfo.SetTriggerClasses(trclasses);
3003
3004   // Set the information in ESD
3005   fesd->SetTriggerMask(trmask);
3006   fesd->SetTriggerCluster(clustmask);
3007
3008   if (!aCTP->CheckTriggeredDetectors()) {
3009     if (fRawReader) delete aCTP;
3010     return kFALSE;
3011   }    
3012
3013   if (fRawReader) delete aCTP;
3014
3015   // We have to fill also the HLT decision here!!
3016   // ...
3017
3018   return kTRUE;
3019 }
3020
3021 const char *AliReconstruction::MatchDetectorList(const char *detectorList, UInt_t detectorMask)
3022 {
3023   // Match the detector list found in the rec.C or the default 'ALL'
3024   // to the list found in the GRP (stored there by the shuttle PP which
3025   // gets the information from ECS)
3026   static TString resultList;
3027   TString detList = detectorList;
3028
3029   resultList = "";
3030
3031   for(Int_t iDet = 0; iDet < (AliDAQ::kNDetectors-1); iDet++) {
3032     if ((detectorMask >> iDet) & 0x1) {
3033       TString det = AliDAQ::OfflineModuleName(iDet);
3034       if ((detList.CompareTo("ALL") == 0) ||
3035           detList.BeginsWith("ALL ") ||
3036           detList.EndsWith(" ALL") ||
3037           detList.Contains(" ALL ") ||
3038           (detList.CompareTo(det) == 0) ||
3039           detList.BeginsWith(det) ||
3040           detList.EndsWith(det) ||
3041           detList.Contains( " "+det+" " )) {
3042         if (!resultList.EndsWith(det + " ")) {
3043           resultList += det;
3044           resultList += " ";
3045         }
3046       }        
3047     }
3048   }
3049
3050   // HLT
3051   if ((detectorMask >> AliDAQ::kHLTId) & 0x1) {
3052     TString hltDet = AliDAQ::OfflineModuleName(AliDAQ::kNDetectors-1);
3053     if ((detList.CompareTo("ALL") == 0) ||
3054         detList.BeginsWith("ALL ") ||
3055         detList.EndsWith(" ALL") ||
3056         detList.Contains(" ALL ") ||
3057         (detList.CompareTo(hltDet) == 0) ||
3058         detList.BeginsWith(hltDet) ||
3059         detList.EndsWith(hltDet) ||
3060         detList.Contains( " "+hltDet+" " )) {
3061       resultList += hltDet;
3062     }
3063   }
3064
3065   return resultList.Data();
3066
3067 }
3068
3069 //______________________________________________________________________________
3070 void AliReconstruction::Abort(const char *method, EAbort what)
3071 {
3072   // Abort processing. If what = kAbortProcess, the Process() loop will be
3073   // aborted. If what = kAbortFile, the current file in a chain will be
3074   // aborted and the processing will continue with the next file, if there
3075   // is no next file then Process() will be aborted. Abort() can also  be
3076   // called from Begin(), SlaveBegin(), Init() and Notify(). After abort
3077   // the SlaveTerminate() and Terminate() are always called. The abort flag
3078   // can be checked in these methods using GetAbort().
3079   //
3080   // The method is overwritten in AliReconstruction for better handling of
3081   // reco specific errors 
3082
3083   if (!fStopOnError) return;
3084
3085   CleanUp();
3086
3087   TString whyMess = method;
3088   whyMess += " failed! Aborting...";
3089
3090   AliError(whyMess.Data());
3091
3092   fAbort = what;
3093   TString mess = "Abort";
3094   if (fAbort == kAbortProcess)
3095     mess = "AbortProcess";
3096   else if (fAbort == kAbortFile)
3097     mess = "AbortFile";
3098
3099   Info(mess, whyMess.Data());
3100 }
3101