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