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