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