]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/AliReconstruction.cxx
Changes requested in report #61429: PID: Separating response functions from ESD ...
[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 <TArrayD.h>
112 #include <TArrayF.h>
113 #include <TArrayS.h>
114 #include <TChain.h>
115 #include <TFile.h>
116 #include <TGeoGlobalMagField.h>
117 #include <TGeoManager.h>
118 #include <TList.h>
119 #include <TLorentzVector.h>
120 #include <TMap.h>
121 #include <TObjArray.h>
122 #include <TPRegexp.h>
123 #include <TParameter.h>
124 #include <TPluginManager.h>
125 #include <TProof.h>
126 #include <TProofOutputFile.h>
127 #include <TROOT.h>
128 #include <TSystem.h>
129 #include <THashTable.h>
130 #include <TGrid.h>
131 #include <TMessage.h>
132
133 #include "AliAlignObj.h"
134 #include "AliCDBEntry.h"
135 #include "AliCDBManager.h"
136 #include "AliCDBStorage.h"
137 #include "AliCTPRawStream.h"
138 #include "AliCascadeVertexer.h"
139 #include "AliCentralTrigger.h"
140 #include "AliCodeTimer.h"
141 #include "AliDAQ.h"
142 #include "AliDetectorRecoParam.h"
143 #include "AliESDCaloCells.h"
144 #include "AliESDCaloCluster.h"
145 #include "AliESDEvent.h"
146 #include "AliESDMuonTrack.h"
147 #include "AliESDPmdTrack.h"
148 #include "AliESDTagCreator.h"
149 #include "AliESDVertex.h"
150 #include "AliESDcascade.h"
151 #include "AliESDfriend.h"
152 #include "AliESDkink.h"
153 #include "AliESDpid.h"
154 #include "AliESDtrack.h"
155 #include "AliESDtrack.h"
156 #include "AliEventInfo.h"
157 #include "AliGRPObject.h"
158 #include "AliGRPRecoParam.h"
159 #include "AliGenEventHeader.h"
160 #include "AliGeomManager.h"
161 #include "AliGlobalQADataMaker.h" 
162 #include "AliHeader.h"
163 #include "AliLog.h"
164 #include "AliMagF.h"
165 #include "AliMultiplicity.h"
166 #include "AliPID.h"
167 #include "AliPlaneEff.h"
168 #include "AliQAv1.h"
169 #include "AliQADataMakerRec.h" 
170 #include "AliQAManager.h"
171 #include "AliRawVEvent.h"
172 #include "AliRawEventHeaderBase.h"
173 #include "AliRawHLTManager.h"
174 #include "AliRawReaderDate.h"
175 #include "AliRawReaderFile.h"
176 #include "AliRawReaderRoot.h"
177 #include "AliReconstruction.h"
178 #include "AliReconstructor.h"
179 #include "AliRun.h"
180 #include "AliRunInfo.h"
181 #include "AliRunLoader.h"
182 #include "AliSysInfo.h" // memory snapshots
183 #include "AliTrackPointArray.h"
184 #include "AliTracker.h"
185 #include "AliTriggerClass.h"
186 #include "AliTriggerCluster.h"
187 #include "AliTriggerIR.h"
188 #include "AliTriggerConfiguration.h"
189 #include "AliV0vertexer.h"
190 #include "AliVertexer.h"
191 #include "AliVertexerTracks.h"
192 #include "AliTriggerRunScalers.h"
193 #include "AliCTPTimeParams.h" 
194 #include "AliESDHLTDecision.h"
195
196 ClassImp(AliReconstruction)
197
198 //_____________________________________________________________________________
199 const char* AliReconstruction::fgkDetectorName[AliReconstruction::kNDetectors] = {"ITS", "TPC", "TRD", "TOF", "PHOS", "HMPID", "EMCAL", "MUON", "FMD", "ZDC", "PMD", "T0", "VZERO", "ACORDE", "HLT"};
200
201 //_____________________________________________________________________________
202 AliReconstruction::AliReconstruction(const char* gAliceFilename) :
203   TSelector(),
204   fRunVertexFinder(kTRUE),
205   fRunVertexFinderTracks(kTRUE),
206   fRunHLTTracking(kFALSE),
207   fRunMuonTracking(kFALSE),
208   fRunV0Finder(kTRUE),
209   fRunCascadeFinder(kTRUE),
210   fStopOnError(kTRUE),
211   fWriteAlignmentData(kFALSE),
212   fWriteESDfriend(kFALSE),
213   fFillTriggerESD(kTRUE),
214
215   fCleanESD(kTRUE),
216   fV0DCAmax(3.),
217   fV0CsPmin(0.),
218   fDmax(50.),
219   fZmax(50.),
220
221   fRunLocalReconstruction("ALL"),
222   fRunTracking("ALL"),
223   fFillESD("ALL"),
224   fLoadCDB(""),
225   fUseTrackingErrorsForAlignment(""),
226   fGAliceFileName(gAliceFilename),
227   fRawInput(""),
228   fESDOutput(""),
229   fProofOutputFileName(""),
230   fProofOutputLocation(""),
231   fProofOutputDataset(kFALSE),
232   fProofOutputArchive(""),
233   fEquipIdMap(""),
234   fFirstEvent(0),
235   fLastEvent(-1),
236   fNumberOfEventsPerFile((UInt_t)-1),
237   fOptions(),
238   fLoadAlignFromCDB(kTRUE),
239   fLoadAlignData("ALL"),
240   fUseHLTData(),
241   fRunInfo(NULL),
242   fEventInfo(),
243   fRunScalers(NULL),
244   fCTPTimeParams(NULL),  
245
246   fRunLoader(NULL),
247   fRawReader(NULL),
248   fParentRawReader(NULL),
249
250   fRecoParam(),
251
252   fSPDTrackleter(NULL),
253
254   fDiamondProfileSPD(NULL),
255   fDiamondProfile(NULL),
256   fDiamondProfileTPC(NULL),
257   fListOfCosmicTriggers(NULL),
258   
259   fGRPData(NULL),
260
261   fAlignObjArray(NULL),
262   fCDBUri(),
263   fQARefUri(),
264   fSpecCDBUri(), 
265   fInitCDBCalled(kFALSE),
266   fSetRunNumberFromDataCalled(kFALSE),
267   fQADetectors("ALL"), 
268   fQATasks("ALL"), 
269   fRunQA(kTRUE),  
270   fRunGlobalQA(kTRUE),
271   fSameQACycle(kFALSE),
272   fInitQACalled(kFALSE), 
273   fWriteQAExpertData(kTRUE), 
274   fRunPlaneEff(kFALSE),
275
276   fesd(NULL),
277   fhltesd(NULL),
278   fesdf(NULL),
279   ffile(NULL),
280   ftree(NULL),
281   fhlttree(NULL),
282   ftVertexer(NULL),
283   fIsNewRunLoader(kFALSE),
284   fRunAliEVE(kFALSE),
285   fChain(NULL)
286 {
287 // create reconstruction object with default parameters
288   gGeoManager = NULL;
289   
290   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
291     fReconstructor[iDet] = NULL;
292     fLoader[iDet] = NULL;
293     fTracker[iDet] = NULL;
294   }
295   for (Int_t iDet = 0; iDet < AliQAv1::kNDET; iDet++) {
296     fQACycles[iDet] = 999999 ;
297     fQAWriteExpert[iDet] = kFALSE ; 
298   }
299     
300   AliPID pid;
301 }
302
303 //_____________________________________________________________________________
304 AliReconstruction::AliReconstruction(const AliReconstruction& rec) :
305   TSelector(),
306   fRunVertexFinder(rec.fRunVertexFinder),
307   fRunVertexFinderTracks(rec.fRunVertexFinderTracks),
308   fRunHLTTracking(rec.fRunHLTTracking),
309   fRunMuonTracking(rec.fRunMuonTracking),
310   fRunV0Finder(rec.fRunV0Finder),
311   fRunCascadeFinder(rec.fRunCascadeFinder),
312   fStopOnError(rec.fStopOnError),
313   fWriteAlignmentData(rec.fWriteAlignmentData),
314   fWriteESDfriend(rec.fWriteESDfriend),
315   fFillTriggerESD(rec.fFillTriggerESD),
316
317   fCleanESD(rec.fCleanESD),
318   fV0DCAmax(rec.fV0DCAmax),
319   fV0CsPmin(rec.fV0CsPmin),
320   fDmax(rec.fDmax),
321   fZmax(rec.fZmax),
322
323   fRunLocalReconstruction(rec.fRunLocalReconstruction),
324   fRunTracking(rec.fRunTracking),
325   fFillESD(rec.fFillESD),
326   fLoadCDB(rec.fLoadCDB),
327   fUseTrackingErrorsForAlignment(rec.fUseTrackingErrorsForAlignment),
328   fGAliceFileName(rec.fGAliceFileName),
329   fRawInput(rec.fRawInput),
330   fESDOutput(rec.fESDOutput),
331   fProofOutputFileName(rec.fProofOutputFileName),
332   fProofOutputLocation(rec.fProofOutputLocation),
333   fProofOutputDataset(rec.fProofOutputDataset),
334   fProofOutputArchive(rec.fProofOutputArchive),
335   fEquipIdMap(rec.fEquipIdMap),
336   fFirstEvent(rec.fFirstEvent),
337   fLastEvent(rec.fLastEvent),
338   fNumberOfEventsPerFile(rec.fNumberOfEventsPerFile),
339   fOptions(),
340   fLoadAlignFromCDB(rec.fLoadAlignFromCDB),
341   fLoadAlignData(rec.fLoadAlignData),
342   fUseHLTData(rec.fUseHLTData),
343   fRunInfo(NULL),
344   fEventInfo(),
345   fRunScalers(NULL),
346   fCTPTimeParams(NULL),
347
348   fRunLoader(NULL),
349   fRawReader(NULL),
350   fParentRawReader(NULL),
351
352   fRecoParam(rec.fRecoParam),
353
354   fSPDTrackleter(NULL),
355
356   fDiamondProfileSPD(rec.fDiamondProfileSPD),
357   fDiamondProfile(rec.fDiamondProfile),
358   fDiamondProfileTPC(rec.fDiamondProfileTPC),
359   fListOfCosmicTriggers(NULL),
360   
361   fGRPData(NULL),
362
363   fAlignObjArray(rec.fAlignObjArray),
364   fCDBUri(rec.fCDBUri),
365   fQARefUri(rec.fQARefUri),
366   fSpecCDBUri(), 
367   fInitCDBCalled(rec.fInitCDBCalled),
368   fSetRunNumberFromDataCalled(rec.fSetRunNumberFromDataCalled),
369   fQADetectors(rec.fQADetectors), 
370   fQATasks(rec.fQATasks), 
371   fRunQA(rec.fRunQA),  
372   fRunGlobalQA(rec.fRunGlobalQA),
373   fSameQACycle(rec.fSameQACycle),
374   fInitQACalled(rec.fInitQACalled),
375   fWriteQAExpertData(rec.fWriteQAExpertData), 
376   fRunPlaneEff(rec.fRunPlaneEff),
377
378   fesd(NULL),
379   fhltesd(NULL),
380   fesdf(NULL),
381   ffile(NULL),
382   ftree(NULL),
383   fhlttree(NULL),
384   ftVertexer(NULL),
385   fIsNewRunLoader(rec.fIsNewRunLoader),
386   fRunAliEVE(kFALSE),
387   fChain(NULL)
388 {
389 // copy constructor
390
391   for (Int_t i = 0; i < rec.fOptions.GetEntriesFast(); i++) {
392     if (rec.fOptions[i]) fOptions.Add(rec.fOptions[i]->Clone());
393   }
394   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
395     fReconstructor[iDet] = NULL;
396     fLoader[iDet] = NULL;
397     fTracker[iDet] = NULL;
398   }  
399   
400   for (Int_t iDet = 0; iDet < AliQAv1::kNDET; iDet++) {
401     fQACycles[iDet] = rec.fQACycles[iDet];
402     fQAWriteExpert[iDet] = rec.fQAWriteExpert[iDet] ; 
403   }
404
405   for (Int_t i = 0; i < rec.fSpecCDBUri.GetEntriesFast(); i++) {
406     if (rec.fSpecCDBUri[i]) fSpecCDBUri.Add(rec.fSpecCDBUri[i]->Clone());
407   }
408 }
409
410 //_____________________________________________________________________________
411 AliReconstruction& AliReconstruction::operator = (const AliReconstruction& rec)
412 {
413 // assignment operator
414 // Used in PROOF mode
415 // Be very careful while modifing it!
416 // Simple rules to follow:
417 // for persistent data members - use their assignment operators
418 // for non-persistent ones - do nothing or take the default values from constructor
419 // TSelector members should not be touched
420   if(&rec == this) return *this;
421
422   fRunVertexFinder       = rec.fRunVertexFinder;
423   fRunVertexFinderTracks = rec.fRunVertexFinderTracks;
424   fRunHLTTracking        = rec.fRunHLTTracking;
425   fRunMuonTracking       = rec.fRunMuonTracking;
426   fRunV0Finder           = rec.fRunV0Finder;
427   fRunCascadeFinder      = rec.fRunCascadeFinder;
428   fStopOnError           = rec.fStopOnError;
429   fWriteAlignmentData    = rec.fWriteAlignmentData;
430   fWriteESDfriend        = rec.fWriteESDfriend;
431   fFillTriggerESD        = rec.fFillTriggerESD;
432
433   fCleanESD  = rec.fCleanESD;
434   fV0DCAmax  = rec.fV0DCAmax;
435   fV0CsPmin  = rec.fV0CsPmin;
436   fDmax      = rec.fDmax;
437   fZmax      = rec.fZmax;
438
439   fRunLocalReconstruction        = rec.fRunLocalReconstruction;
440   fRunTracking                   = rec.fRunTracking;
441   fFillESD                       = rec.fFillESD;
442   fLoadCDB                       = rec.fLoadCDB;
443   fUseTrackingErrorsForAlignment = rec.fUseTrackingErrorsForAlignment;
444   fGAliceFileName                = rec.fGAliceFileName;
445   fRawInput                      = rec.fRawInput;
446   fESDOutput                     = rec.fESDOutput;
447   fProofOutputFileName           = rec.fProofOutputFileName;
448   fProofOutputLocation           = rec.fProofOutputLocation;
449   fProofOutputDataset            = rec.fProofOutputDataset;
450   fProofOutputArchive            = rec.fProofOutputArchive;
451   fEquipIdMap                    = rec.fEquipIdMap;
452   fFirstEvent                    = rec.fFirstEvent;
453   fLastEvent                     = rec.fLastEvent;
454   fNumberOfEventsPerFile         = rec.fNumberOfEventsPerFile;
455
456   for (Int_t i = 0; i < rec.fOptions.GetEntriesFast(); i++) {
457     if (rec.fOptions[i]) fOptions.Add(rec.fOptions[i]->Clone());
458   }
459
460   fLoadAlignFromCDB              = rec.fLoadAlignFromCDB;
461   fLoadAlignData                 = rec.fLoadAlignData;
462   fUseHLTData                    = rec.fUseHLTData;
463
464   delete fRunInfo; fRunInfo = NULL;
465   if (rec.fRunInfo) fRunInfo = new AliRunInfo(*rec.fRunInfo);
466
467   fEventInfo                     = rec.fEventInfo;
468
469   delete fRunScalers; fRunScalers = NULL;
470   if (rec.fRunScalers) fRunScalers = new AliTriggerRunScalers(*rec.fRunScalers); 
471
472   delete fCTPTimeParams; fCTPTimeParams = NULL;
473   if (rec.fCTPTimeParams) fCTPTimeParams = new AliCTPTimeParams(*rec.fCTPTimeParams);
474
475   fRunLoader       = NULL;
476   fRawReader       = NULL;
477   fParentRawReader = NULL;
478
479   fRecoParam = rec.fRecoParam;
480
481   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
482     delete fReconstructor[iDet]; fReconstructor[iDet] = NULL;
483     delete fLoader[iDet]; fLoader[iDet] = NULL;
484     delete fTracker[iDet]; fTracker[iDet] = NULL;
485   }
486   
487   for (Int_t iDet = 0; iDet < AliQAv1::kNDET; iDet++) {
488     fQACycles[iDet] = rec.fQACycles[iDet];
489     fQAWriteExpert[iDet] = rec.fQAWriteExpert[iDet] ;
490   } 
491
492   delete fSPDTrackleter; fSPDTrackleter = NULL;
493     
494   delete fDiamondProfileSPD; fDiamondProfileSPD = NULL;
495   if (rec.fDiamondProfileSPD) fDiamondProfileSPD = new AliESDVertex(*rec.fDiamondProfileSPD);
496   delete fDiamondProfile; fDiamondProfile = NULL;
497   if (rec.fDiamondProfile) fDiamondProfile = new AliESDVertex(*rec.fDiamondProfile);
498   delete fDiamondProfileTPC; fDiamondProfileTPC = NULL;
499   if (rec.fDiamondProfileTPC) fDiamondProfileTPC = new AliESDVertex(*rec.fDiamondProfileTPC);
500
501   delete fListOfCosmicTriggers; fListOfCosmicTriggers = NULL;
502   if (rec.fListOfCosmicTriggers) fListOfCosmicTriggers = (THashTable*)((rec.fListOfCosmicTriggers)->Clone());
503
504   delete fGRPData; fGRPData = NULL;
505   //  if (rec.fGRPData) fGRPData = (TMap*)((rec.fGRPData)->Clone());
506   if (rec.fGRPData) fGRPData = (AliGRPObject*)((rec.fGRPData)->Clone());
507
508   delete fAlignObjArray; fAlignObjArray = NULL;
509
510   fCDBUri        = "";
511   fQARefUri      = rec.fQARefUri;
512   fSpecCDBUri.Delete();
513   fInitCDBCalled               = rec.fInitCDBCalled;
514   fSetRunNumberFromDataCalled  = rec.fSetRunNumberFromDataCalled;
515   fQADetectors                 = rec.fQADetectors;
516   fQATasks                     = rec.fQATasks; 
517   fRunQA                       = rec.fRunQA;  
518   fRunGlobalQA                 = rec.fRunGlobalQA;
519   fSameQACycle                 = rec.fSameQACycle;
520   fInitQACalled                = rec.fInitQACalled;
521   fWriteQAExpertData           = rec.fWriteQAExpertData;
522   fRunPlaneEff                 = rec.fRunPlaneEff;
523
524   fesd     = NULL;
525   fhltesd  = NULL;
526   fesdf    = NULL;
527   ffile    = NULL;
528   ftree    = NULL;
529   fhlttree = NULL;
530   ftVertexer = NULL;
531   fIsNewRunLoader = rec.fIsNewRunLoader;
532   fRunAliEVE = kFALSE;
533   fChain = NULL;
534
535   return *this;
536 }
537
538 //_____________________________________________________________________________
539 AliReconstruction::~AliReconstruction()
540 {
541 // clean up
542
543   CleanUp();
544   if (fListOfCosmicTriggers) {
545     fListOfCosmicTriggers->Delete();
546     delete fListOfCosmicTriggers;
547   }
548   delete fGRPData;
549   delete fRunScalers;
550   delete fCTPTimeParams;
551   fOptions.Delete();
552   if (fAlignObjArray) {
553     fAlignObjArray->Delete();
554     delete fAlignObjArray;
555   }
556   fSpecCDBUri.Delete();
557
558   AliCodeTimer::Instance()->Print();
559 }
560
561 //_____________________________________________________________________________
562 void AliReconstruction::InitQA()
563 {
564   //Initialize the QA and start of cycle 
565   AliCodeTimerAuto("",0);
566   
567   if (fInitQACalled) return;
568   fInitQACalled = kTRUE;
569   
570   AliQAManager * qam = AliQAManager::QAManager(AliQAv1::kRECMODE) ; 
571   if (fWriteQAExpertData)
572     qam->SetWriteExpert() ; 
573  
574   if (qam->IsDefaultStorageSet()) {
575     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
576     AliWarning("Default QA reference storage has been already set !");
577     AliWarning(Form("Ignoring the default storage declared in AliReconstruction: %s",fQARefUri.Data()));
578     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
579     fQARefUri = qam->GetDefaultStorage()->GetURI();
580   } else {
581     if (fQARefUri.Length() > 0) {
582         AliDebug(2,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
583         AliDebug(2, Form("Default QA reference storage is set to: %s", fQARefUri.Data()));
584         AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
585       } else {
586         fQARefUri="local://$ALICE_ROOT/QAref";
587         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
588         AliWarning("Default QA refeference storage not yet set !!!!");
589         AliWarning(Form("Setting it now to: %s", fQARefUri.Data()));
590         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
591                 
592       }
593     qam->SetDefaultStorage(fQARefUri);
594   }
595   
596   if (fRunQA) {
597   qam->SetActiveDetectors(fQADetectors) ; 
598   for (Int_t det = 0 ; det < AliQAv1::kNDET ; det++) {
599     qam->SetCycleLength(AliQAv1::DETECTORINDEX_t(det), fQACycles[det]) ;  
600     qam->SetWriteExpert(AliQAv1::DETECTORINDEX_t(det)) ;
601   }
602   if (!fRawReader && !fInput && IsInTasks(AliQAv1::kRAWS))
603     fQATasks.ReplaceAll(Form("%d",AliQAv1::kRAWS), "") ;
604   qam->SetTasks(fQATasks) ; 
605   qam->InitQADataMaker(AliCDBManager::Instance()->GetRun()) ; 
606   }
607   if (fRunGlobalQA) {
608     Bool_t sameCycle = kFALSE ;
609     AliQADataMaker *qadm = qam->GetQADataMaker(AliQAv1::kGLOBAL);
610     AliInfo(Form("Initializing the global QA data maker"));
611     if (IsInTasks(AliQAv1::kRECPOINTS)) {
612       qadm->StartOfCycle(AliQAv1::kRECPOINTS, AliCDBManager::Instance()->GetRun(), sameCycle) ; 
613       TObjArray **arr=qadm->Init(AliQAv1::kRECPOINTS);
614       AliTracker::SetResidualsArray(arr);
615       sameCycle = kTRUE ; 
616     }
617     if (IsInTasks(AliQAv1::kESDS)) {
618       qadm->StartOfCycle(AliQAv1::kESDS, AliCDBManager::Instance()->GetRun(), sameCycle) ; 
619       qadm->Init(AliQAv1::kESDS);
620     }
621   }
622     AliSysInfo::AddStamp("InitQA") ; 
623 }
624
625 //_____________________________________________________________________________
626 void AliReconstruction::MergeQA(const char *fileName)
627 {
628   //Initialize the QA and start of cycle 
629   AliCodeTimerAuto("",0) ;
630   AliQAManager::QAManager()->Merge(AliCDBManager::Instance()->GetRun(),fileName) ; 
631   AliSysInfo::AddStamp("MergeQA") ; 
632 }
633   
634 //_____________________________________________________________________________
635 void AliReconstruction::InitCDB()
636 {
637 // activate a default CDB storage
638 // First check if we have any CDB storage set, because it is used 
639 // to retrieve the calibration and alignment constants
640   AliCodeTimerAuto("",0);
641
642   if (fInitCDBCalled) return;
643   fInitCDBCalled = kTRUE;
644
645   AliCDBManager* man = AliCDBManager::Instance();
646   if (man->IsDefaultStorageSet())
647   {
648     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
649     AliWarning("Default CDB storage has been already set !");
650     AliWarning(Form("Ignoring the default storage declared in AliReconstruction: %s",fCDBUri.Data()));
651     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
652     fCDBUri = man->GetDefaultStorage()->GetURI();
653   }
654   else {
655     if (fCDBUri.Length() > 0) 
656     {
657         AliDebug(2,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
658         AliDebug(2, Form("Default CDB storage is set to: %s", fCDBUri.Data()));
659         AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
660         man->SetDefaultStorage(fCDBUri);
661     } 
662     else if (!man->GetRaw()){
663         fCDBUri="local://$ALICE_ROOT/OCDB";
664         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
665         AliWarning("Default CDB storage not yet set !!!!");
666         AliWarning(Form("Setting it now to: %s", fCDBUri.Data()));
667         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
668         man->SetDefaultStorage(fCDBUri);
669     }
670     else {    
671         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
672         AliWarning("Default storage will be set after setting the Run Number!!!");
673         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");                    
674     }
675   }
676
677   // Now activate the detector specific CDB storage locations
678   for (Int_t i = 0; i < fSpecCDBUri.GetEntriesFast(); i++) {
679     TObject* obj = fSpecCDBUri[i];
680     if (!obj) continue;
681     AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
682     AliDebug(2, Form("Specific CDB storage for %s is set to: %s",obj->GetName(),obj->GetTitle()));
683     AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
684     man->SetSpecificStorage(obj->GetName(), obj->GetTitle());
685   }
686   AliSysInfo::AddStamp("InitCDB");
687 }
688
689 //_____________________________________________________________________________
690 void AliReconstruction::SetDefaultStorage(const char* uri) {
691 // Store the desired default CDB storage location
692 // Activate it later within the Run() method
693
694   fCDBUri = uri;
695
696 }
697
698 //_____________________________________________________________________________
699 void AliReconstruction::SetQARefDefaultStorage(const char* uri) {
700   // Store the desired default CDB storage location
701   // Activate it later within the Run() method
702   
703   fQARefUri = uri;
704   AliQAv1::SetQARefStorage(fQARefUri.Data()) ;
705   
706 }
707 //_____________________________________________________________________________
708 void AliReconstruction::SetSpecificStorage(const char* calibType, const char* uri) {
709 // Store a detector-specific CDB storage location
710 // Activate it later within the Run() method
711
712   AliCDBPath aPath(calibType);
713   if(!aPath.IsValid()){
714         // if calibType is not wildcard but it is a valid detector, add "/*" to make it a valid path
715         for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
716                 if(!strcmp(calibType, fgkDetectorName[iDet])) {
717                         aPath.SetPath(Form("%s/*", calibType));
718                         AliInfo(Form("Path for specific storage set to %s", aPath.GetPath().Data()));
719                         break;
720                 }
721         }
722         if(!aPath.IsValid()){
723                 AliError(Form("Not a valid path or detector: %s", calibType));
724                 return;
725         }
726   }
727
728 //  // check that calibType refers to a "valid" detector name
729 //  Bool_t isDetector = kFALSE;
730 //  for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
731 //    TString detName = fgkDetectorName[iDet];
732 //    if(aPath.GetLevel0() == detName) {
733 //      isDetector = kTRUE;
734 //      break;
735 //    }
736 //  }
737 //
738 //  if(!isDetector) {
739 //      AliError(Form("Not a valid detector: %s", aPath.GetLevel0().Data()));
740 //      return;
741 //  }
742
743   TObject* obj = fSpecCDBUri.FindObject(aPath.GetPath().Data());
744   if (obj) fSpecCDBUri.Remove(obj);
745   fSpecCDBUri.Add(new TNamed(aPath.GetPath().Data(), uri));
746
747 }
748
749 //_____________________________________________________________________________
750 Bool_t AliReconstruction::SetRunNumberFromData()
751 {
752   // The method is called in Run() in order
753   // to set a correct run number.
754   // In case of raw data reconstruction the
755   // run number is taken from the raw data header
756
757   if (fSetRunNumberFromDataCalled) return kTRUE;
758   fSetRunNumberFromDataCalled = kTRUE;
759   
760   AliCDBManager* man = AliCDBManager::Instance();
761  
762   if(fRawReader) {
763     if(fRawReader->NextEvent()) {
764       if(man->GetRun() > 0) {
765         AliWarning("Run number is taken from raw-event header! Ignoring settings in AliCDBManager!");
766       } 
767       man->SetRun(fRawReader->GetRunNumber());
768       fRawReader->RewindEvents();
769     }
770     else {
771       if(man->GetRun() > 0) {
772         AliWarning("No raw-data events are found ! Using settings in AliCDBManager !");
773       }
774       else {
775         AliWarning("Neither raw events nor settings in AliCDBManager are found !");
776         return kFALSE;
777       }
778     }
779   }
780   else {
781     AliRunLoader *rl = AliRunLoader::Open(fGAliceFileName.Data());
782     if (!rl) {
783       AliError(Form("No run loader found in file %s", fGAliceFileName.Data()));
784       return kFALSE;
785     }
786     else {
787       rl->LoadHeader();
788       // read run number from gAlice
789       if(rl->GetHeader()) {
790         man->SetRun(rl->GetHeader()->GetRun());
791         rl->UnloadHeader();
792         delete rl;
793       }
794       else {
795         AliError("Neither run-loader header nor RawReader objects are found !");
796         delete rl;
797         return kFALSE;
798       }
799     }
800   }
801
802   man->Print();  
803   
804   return kTRUE;
805 }
806
807 //_____________________________________________________________________________
808 void AliReconstruction::SetCDBLock() {
809   // Set CDB lock: from now on it is forbidden to reset the run number
810   // or the default storage or to activate any further storage!
811   
812   AliCDBManager::Instance()->SetLock(1);
813 }
814
815 //_____________________________________________________________________________
816 Bool_t AliReconstruction::MisalignGeometry(const TString& detectors)
817 {
818   // Read the alignment objects from CDB.
819   // Each detector is supposed to have the
820   // alignment objects in DET/Align/Data CDB path.
821   // All the detector objects are then collected,
822   // sorted by geometry level (starting from ALIC) and
823   // then applied to the TGeo geometry.
824   // Finally an overlaps check is performed.
825
826   // Load alignment data from CDB and fill fAlignObjArray 
827   if(fLoadAlignFromCDB){
828         
829     TString detStr = detectors;
830     TString loadAlObjsListOfDets = "";
831     
832     for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
833       if(!IsSelected(fgkDetectorName[iDet], detStr)) continue;
834       if(!strcmp(fgkDetectorName[iDet],"HLT")) continue;
835       
836       if(AliGeomManager::GetNalignable(fgkDetectorName[iDet]) != 0)
837       {
838         loadAlObjsListOfDets += fgkDetectorName[iDet];
839         loadAlObjsListOfDets += " ";
840       }
841     } // end loop over detectors
842     
843     if(AliGeomManager::GetNalignable("GRP") != 0)
844       loadAlObjsListOfDets.Prepend("GRP "); //add alignment objects for non-sensitive modules
845     AliGeomManager::ApplyAlignObjsFromCDB(loadAlObjsListOfDets.Data());
846     AliCDBManager::Instance()->UnloadFromCache("*/Align/*");
847   }else{
848     // Check if the array with alignment objects was
849     // provided by the user. If yes, apply the objects
850     // to the present TGeo geometry
851     if (fAlignObjArray) {
852       if (gGeoManager && gGeoManager->IsClosed()) {
853         if (AliGeomManager::ApplyAlignObjsToGeom(*fAlignObjArray) == kFALSE) {
854           AliError("The misalignment of one or more volumes failed!"
855                    "Compare the list of simulated detectors and the list of detector alignment data!");
856           return kFALSE;
857         }
858       }
859       else {
860         AliError("Can't apply the misalignment! gGeoManager doesn't exist or it is still opened!");
861         return kFALSE;
862       }
863     }
864   }
865   
866   if (fAlignObjArray) {
867     fAlignObjArray->Delete();
868     delete fAlignObjArray; fAlignObjArray=NULL;
869   }
870
871   return kTRUE;
872 }
873
874 //_____________________________________________________________________________
875 void AliReconstruction::SetGAliceFile(const char* fileName)
876 {
877 // set the name of the galice file
878
879   fGAliceFileName = fileName;
880 }
881
882 //_____________________________________________________________________________
883 void AliReconstruction::SetInput(const char* input) 
884 {
885   // In case the input string starts with 'mem://', we run in an online mode
886   // and AliRawReaderDateOnline object is created. In all other cases a raw-data
887   // file is assumed. One can give as an input:
888   // mem://: - events taken from DAQ monitoring libs online
889   //  or
890   // mem://<filename> - emulation of the above mode (via DATE monitoring libs)
891   if (input) fRawInput = input;
892 }
893
894 //_____________________________________________________________________________
895 void AliReconstruction::SetOutput(const char* output) 
896 {
897   // Set the output ESD filename
898   // 'output' is a normalt ROOT url
899   // The method is used in case of raw-data reco with PROOF
900   if (output) fESDOutput = output;
901 }
902
903 //_____________________________________________________________________________
904 void AliReconstruction::SetOption(const char* detector, const char* option)
905 {
906 // set options for the reconstruction of a detector
907
908   TObject* obj = fOptions.FindObject(detector);
909   if (obj) fOptions.Remove(obj);
910   fOptions.Add(new TNamed(detector, option));
911 }
912
913 //_____________________________________________________________________________
914 void AliReconstruction::SetRecoParam(const char* detector, AliDetectorRecoParam *par)
915 {
916   // Set custom reconstruction parameters for a given detector
917   // Single set of parameters for all the events
918
919   // First check if the reco-params are global
920   if(!strcmp(detector, "GRP")) {
921     par->SetAsDefault();
922     fRecoParam.AddDetRecoParam(kNDetectors,par);
923     return;
924   }
925
926   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
927     if(!strcmp(detector, fgkDetectorName[iDet])) {
928       par->SetAsDefault();
929       fRecoParam.AddDetRecoParam(iDet,par);
930       break;
931     }
932   }
933
934 }
935
936 //_____________________________________________________________________________
937 Bool_t AliReconstruction::InitGRP() {
938   //------------------------------------
939   // Initialization of the GRP entry 
940   //------------------------------------
941   AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/GRP/Data");
942
943   if (entry) {
944
945     TMap* m = dynamic_cast<TMap*>(entry->GetObject());  // old GRP entry
946
947     if (m) {
948        AliInfo("Found a TMap in GRP/GRP/Data, converting it into an AliGRPObject");
949        m->Print();
950        fGRPData = new AliGRPObject();
951        fGRPData->ReadValuesFromMap(m);
952     }
953
954     else {
955        AliInfo("Found an AliGRPObject in GRP/GRP/Data, reading it");
956        fGRPData = dynamic_cast<AliGRPObject*>(entry->GetObject());  // new GRP entry
957        entry->SetOwner(0);
958     }
959
960     //    FIX ME: The unloading of GRP entry is temporarily disabled
961     //    because ZDC and VZERO are using it in order to initialize
962     //    their reconstructor objects. In the future one has to think
963     //    of propagating AliRunInfo to the reconstructors.
964     //    AliCDBManager::Instance()->UnloadFromCache("GRP/GRP/Data");
965   }
966
967   if (!fGRPData) {
968      AliError("No GRP entry found in OCDB!");
969      return kFALSE;
970   }
971
972   TString lhcState = fGRPData->GetLHCState();
973   if (lhcState==AliGRPObject::GetInvalidString()) {
974     AliError("GRP/GRP/Data entry:  missing value for the LHC state ! Using UNKNOWN");
975     lhcState = "UNKNOWN";
976   }
977
978   TString beamType = fGRPData->GetBeamType();
979   if (beamType==AliGRPObject::GetInvalidString()) {
980     AliError("GRP/GRP/Data entry:  missing value for the beam type ! Using UNKNOWN");
981     beamType = "UNKNOWN";
982   }
983
984   Float_t beamEnergy = fGRPData->GetBeamEnergy();
985   if (beamEnergy==AliGRPObject::GetInvalidFloat()) {
986     AliError("GRP/GRP/Data entry:  missing value for the beam energy ! Using 0");
987     beamEnergy = 0;
988   }
989
990   TString runType = fGRPData->GetRunType();
991   if (runType==AliGRPObject::GetInvalidString()) {
992     AliError("GRP/GRP/Data entry:  missing value for the run type ! Using UNKNOWN");
993     runType = "UNKNOWN";
994   }
995
996   Int_t activeDetectors = fGRPData->GetDetectorMask();
997   if (activeDetectors==AliGRPObject::GetInvalidUInt()) {
998     AliError("GRP/GRP/Data entry:  missing value for the detector mask ! Using 1074790399");
999     activeDetectors = 1074790399;
1000   }
1001
1002   fRunInfo = new AliRunInfo(lhcState, beamType, beamEnergy, runType, activeDetectors);
1003   fRunInfo->Dump();
1004
1005
1006   // Process the list of active detectors
1007   if (activeDetectors) {
1008     UInt_t detMask = activeDetectors;
1009     fRunLocalReconstruction = MatchDetectorList(fRunLocalReconstruction,detMask);
1010     fRunTracking = MatchDetectorList(fRunTracking,detMask);
1011     fFillESD = MatchDetectorList(fFillESD,detMask);
1012     fQADetectors = MatchDetectorList(fQADetectors,detMask);
1013     fLoadCDB.Form("%s %s %s %s",
1014                   fRunLocalReconstruction.Data(),
1015                   fRunTracking.Data(),
1016                   fFillESD.Data(),
1017                   fQADetectors.Data());
1018     fLoadCDB = MatchDetectorList(fLoadCDB,detMask);
1019     if (!((detMask >> AliDAQ::DetectorID("ITSSPD")) & 0x1) &&
1020         !((detMask >> AliDAQ::DetectorID("ITSSDD")) & 0x1) &&
1021         !((detMask >> AliDAQ::DetectorID("ITSSSD")) & 0x1) ) {
1022       // switch off the vertexer
1023       AliInfo("SPD,SDD,SSD is not in the list of active detectors. Vertexer switched off.");
1024       fRunVertexFinder = kFALSE;
1025     }
1026     if (!((detMask >> AliDAQ::DetectorID("TRG")) & 0x1)) {
1027       // switch off the reading of CTP raw-data payload
1028       if (fFillTriggerESD) {
1029         AliInfo("CTP is not in the list of active detectors. CTP data reading switched off.");
1030         fFillTriggerESD = kFALSE;
1031       }
1032     }
1033   }
1034
1035   AliInfo("===================================================================================");
1036   AliInfo(Form("Running local reconstruction for detectors: %s",fRunLocalReconstruction.Data()));
1037   AliInfo(Form("Running tracking for detectors: %s",fRunTracking.Data()));
1038   AliInfo(Form("Filling ESD for detectors: %s",fFillESD.Data()));
1039   AliInfo(Form("Quality assurance is active for detectors: %s",fQADetectors.Data()));
1040   AliInfo(Form("CDB and reconstruction parameters are loaded for detectors: %s",fLoadCDB.Data()));
1041   AliInfo("===================================================================================");
1042
1043   //*** Dealing with the magnetic field map
1044   if ( TGeoGlobalMagField::Instance()->IsLocked() ) {
1045     if (TGeoGlobalMagField::Instance()->GetField()->TestBit(AliMagF::kOverrideGRP)) {
1046       AliInfo("ExpertMode!!! GRP information will be ignored !");
1047       AliInfo("ExpertMode!!! Running with the externally locked B field !");
1048     }
1049     else {
1050       AliInfo("Destroying existing B field instance!");
1051       delete TGeoGlobalMagField::Instance();
1052     }    
1053   }
1054   if ( !TGeoGlobalMagField::Instance()->IsLocked() ) {
1055     // Construct the field map out of the information retrieved from GRP.
1056     Bool_t ok = kTRUE;
1057     // L3
1058     Float_t l3Current = fGRPData->GetL3Current((AliGRPObject::Stats)0);
1059     if (l3Current == AliGRPObject::GetInvalidFloat()) {
1060       AliError("GRP/GRP/Data entry:  missing value for the L3 current !");
1061       ok = kFALSE;
1062     }
1063     
1064     Char_t l3Polarity = fGRPData->GetL3Polarity();
1065     if (l3Polarity == AliGRPObject::GetInvalidChar()) {
1066       AliError("GRP/GRP/Data entry:  missing value for the L3 polarity !");
1067       ok = kFALSE;
1068     }
1069
1070     // Dipole
1071     Float_t diCurrent = fGRPData->GetDipoleCurrent((AliGRPObject::Stats)0);
1072     if (diCurrent == AliGRPObject::GetInvalidFloat()) {
1073       AliError("GRP/GRP/Data entry:  missing value for the dipole current !");
1074       ok = kFALSE;
1075     }
1076
1077     Char_t diPolarity = fGRPData->GetDipolePolarity();
1078     if (diPolarity == AliGRPObject::GetInvalidChar()) {
1079       AliError("GRP/GRP/Data entry:  missing value for the dipole polarity !");
1080       ok = kFALSE;
1081     }
1082
1083     // read special bits for the polarity convention and map type
1084     Int_t  polConvention = fGRPData->IsPolarityConventionLHC() ? AliMagF::kConvLHC : AliMagF::kConvDCS2008;
1085     Bool_t uniformB = fGRPData->IsUniformBMap();
1086
1087     if (ok) { 
1088       AliMagF* fld = AliMagF::CreateFieldMap(TMath::Abs(l3Current) * (l3Polarity ? -1:1), 
1089                                              TMath::Abs(diCurrent) * (diPolarity ? -1:1), 
1090                                              polConvention,uniformB,beamEnergy, beamType.Data());
1091       if (fld) {
1092         TGeoGlobalMagField::Instance()->SetField( fld );
1093         TGeoGlobalMagField::Instance()->Lock();
1094         AliInfo("Running with the B field constructed out of GRP !");
1095       }
1096       else AliFatal("Failed to create a B field map !");
1097     }
1098     else AliFatal("B field is neither set nor constructed from GRP ! Exitig...");
1099   }
1100   
1101   //*** Get the diamond profiles from OCDB
1102   entry = AliCDBManager::Instance()->Get("GRP/Calib/MeanVertexSPD");
1103   if (entry) {
1104     fDiamondProfileSPD = dynamic_cast<AliESDVertex*> (entry->GetObject());  
1105   } else {
1106      AliError("No SPD diamond profile found in OCDB!");
1107   }
1108
1109   entry = AliCDBManager::Instance()->Get("GRP/Calib/MeanVertex");
1110   if (entry) {
1111     fDiamondProfile = dynamic_cast<AliESDVertex*> (entry->GetObject());  
1112   } else {
1113      AliError("No diamond profile found in OCDB!");
1114   }
1115
1116   entry = AliCDBManager::Instance()->Get("GRP/Calib/MeanVertexTPC");
1117   if (entry) {
1118     fDiamondProfileTPC = dynamic_cast<AliESDVertex*> (entry->GetObject());  
1119   } else {
1120      AliError("No TPC diamond profile found in OCDB!");
1121   }
1122
1123   entry = AliCDBManager::Instance()->Get("GRP/Calib/CosmicTriggers");
1124   if (entry) {
1125     fListOfCosmicTriggers = dynamic_cast<THashTable*>(entry->GetObject());
1126     entry->SetOwner(0);
1127     AliCDBManager::Instance()->UnloadFromCache("GRP/Calib/CosmicTriggers");
1128   }
1129
1130   if (!fListOfCosmicTriggers) {
1131     AliWarning("Can not get list of cosmic triggers from OCDB! Cosmic event specie will be effectively disabled!");
1132   }
1133
1134   return kTRUE;
1135
1136
1137 //_____________________________________________________________________________
1138 Bool_t AliReconstruction::LoadCDB()
1139 {
1140   AliCodeTimerAuto("",0);
1141
1142   AliCDBManager::Instance()->Get("GRP/CTP/Config");
1143
1144   TString detStr = fLoadCDB;
1145   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
1146     if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
1147     AliCDBManager::Instance()->GetAll(Form("%s/Calib/*",fgkDetectorName[iDet]));
1148   }
1149
1150   // Temporary fix - one has to define the correct policy in order
1151   // to load the trigger OCDB entries only for the detectors that
1152   // in the trigger or that are needed in order to put correct
1153   // information in ESD
1154   AliCDBManager::Instance()->GetAll("TRIGGER/*/*");
1155
1156   return kTRUE;
1157 }
1158 //_____________________________________________________________________________
1159 Bool_t AliReconstruction::LoadTriggerScalersCDB()
1160 {
1161   AliCodeTimerAuto("",0);
1162
1163   AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/CTP/Scalers");
1164
1165   if (entry) { 
1166    
1167        AliInfo("Found an AliTriggerRunScalers in GRP/CTP/Scalers, reading it");
1168        fRunScalers = dynamic_cast<AliTriggerRunScalers*> (entry->GetObject());
1169        entry->SetOwner(0);
1170        if (fRunScalers->CorrectScalersOverflow() == 0) AliInfo("32bit Trigger counters corrected for overflow");
1171
1172   }
1173   return kTRUE;
1174 }
1175 //_____________________________________________________________________________
1176 Bool_t AliReconstruction::LoadCTPTimeParamsCDB()
1177 {
1178   AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/CTP/CTPtiming");
1179
1180   if (entry) {
1181
1182        AliInfo("Found an AliCTPTimeParams in GRP/CTP/CTPtiming, reading it");
1183        fCTPTimeParams = dynamic_cast<AliCTPTimeParams*> (entry->GetObject());
1184        entry->SetOwner(0);
1185        return kTRUE;
1186   }
1187   
1188   return kFALSE; 
1189 }
1190 //_____________________________________________________________________________
1191 Bool_t AliReconstruction::Run(const char* input)
1192 {
1193   // Run Run Run
1194   AliCodeTimerAuto("",0);
1195
1196   InitRun(input);
1197   if (GetAbort() != TSelector::kContinue) return kFALSE;
1198
1199   TChain *chain = NULL;
1200   if (fRawReader && (chain = fRawReader->GetChain())) {
1201     Long64_t nEntries = (fLastEvent < 0) ? (TChain::kBigNumber) : (fLastEvent - fFirstEvent + 1);
1202     // Proof mode
1203     if (gProof) {
1204       // Temporary fix for long raw-data runs (until socket timeout handling in PROOF is revised)
1205       gProof->Exec("gEnv->SetValue(\"Proof.SocketActivityTimeout\",-1)", kTRUE);
1206
1207       if (gGrid)
1208         gProof->Exec("TGrid::Connect(\"alien://\")",kTRUE);
1209
1210       TMessage::EnableSchemaEvolutionForAll(kTRUE);
1211       gProof->Exec("TMessage::EnableSchemaEvolutionForAll(kTRUE)",kTRUE);
1212
1213       gProof->AddInput(this);
1214
1215       if (!ParseOutput()) return kFALSE;
1216
1217       gProof->SetParameter("PROOF_MaxSlavesPerNode", 9999);
1218       chain->SetProof();
1219       chain->Process("AliReconstruction","",nEntries,fFirstEvent);
1220     }
1221     else {
1222       chain->Process(this,"",nEntries,fFirstEvent);
1223     }
1224   }
1225   else {
1226     Begin(NULL);
1227     if (GetAbort() != TSelector::kContinue) return kFALSE;
1228     SlaveBegin(NULL);
1229     if (GetAbort() != TSelector::kContinue) return kFALSE;
1230     //******* The loop over events
1231     AliInfo("Starting looping over events");
1232     Int_t iEvent = 0;
1233     while ((iEvent < fRunLoader->GetNumberOfEvents()) ||
1234            (fRawReader && fRawReader->NextEvent())) {
1235       if (!ProcessEvent(iEvent)) {
1236         Abort("ProcessEvent",TSelector::kAbortFile);
1237         return kFALSE;
1238       }
1239       iEvent++;
1240     }
1241     SlaveTerminate();
1242     if (GetAbort() != TSelector::kContinue) return kFALSE;
1243     Terminate();
1244     if (GetAbort() != TSelector::kContinue) return kFALSE;
1245   }
1246
1247   return kTRUE;
1248 }
1249
1250 //_____________________________________________________________________________
1251 void AliReconstruction::InitRawReader(const char* input)
1252 {
1253   AliCodeTimerAuto("",0);
1254
1255   // Init raw-reader and
1256   // set the input in case of raw data
1257   if (input) fRawInput = input;
1258   fRawReader = AliRawReader::Create(fRawInput.Data());
1259   if (!fRawReader) {
1260     if (fRawInput.IsNull()) {
1261       AliInfo("Reconstruction will run over digits");
1262     }
1263     else {
1264       AliFatal("Can not create raw-data reader ! Exiting..."); 
1265     }
1266   }
1267
1268   if (!fEquipIdMap.IsNull() && fRawReader)
1269     fRawReader->LoadEquipmentIdsMap(fEquipIdMap);
1270
1271   if (!fUseHLTData.IsNull()) {
1272     // create the RawReaderHLT which performs redirection of HLT input data for
1273     // the specified detectors
1274     AliRawReader* pRawReader=AliRawHLTManager::CreateRawReaderHLT(fRawReader, fUseHLTData.Data());
1275     if (pRawReader) {
1276       fParentRawReader=fRawReader;
1277       fRawReader=pRawReader;
1278     } else {
1279       AliError(Form("can not create Raw Reader for HLT input %s", fUseHLTData.Data()));
1280     }
1281   }
1282   AliSysInfo::AddStamp("CreateRawReader");
1283 }
1284
1285 //_____________________________________________________________________________
1286 void AliReconstruction::InitRun(const char* input)
1287 {
1288   // Initialization of raw-reader,
1289   // run number, CDB etc.
1290   AliCodeTimerAuto("",0);
1291   AliSysInfo::AddStamp("Start");
1292
1293   // Initialize raw-reader if any
1294   InitRawReader(input);
1295
1296   // Initialize the CDB storage
1297   InitCDB();
1298
1299   // Set run number in CDBManager (if it is not already set by the user)
1300   if (!SetRunNumberFromData()) {
1301     Abort("SetRunNumberFromData", TSelector::kAbortProcess);
1302     return;
1303   }
1304
1305   // Set CDB lock: from now on it is forbidden to reset the run number
1306   // or the default storage or to activate any further storage!
1307   SetCDBLock();
1308   
1309 }
1310
1311 //_____________________________________________________________________________
1312 void AliReconstruction::Begin(TTree *)
1313 {
1314   // Initialize AlReconstruction before
1315   // going into the event loop
1316   // Should follow the TSelector convention
1317   // i.e. initialize only the object on the client side
1318   AliCodeTimerAuto("",0);
1319
1320   AliReconstruction *reco = NULL;
1321   if (fInput) {
1322     if ((reco = (AliReconstruction*)fInput->FindObject("AliReconstruction"))) {
1323       *this = *reco;
1324     }
1325     AliSysInfo::AddStamp("ReadInputInBegin");
1326   }
1327
1328   // Import ideal TGeo geometry and apply misalignment
1329   if (!gGeoManager) {
1330     TString geom(gSystem->DirName(fGAliceFileName));
1331     geom += "/geometry.root";
1332     AliGeomManager::LoadGeometry(geom.Data());
1333     if (!gGeoManager) {
1334       Abort("LoadGeometry", TSelector::kAbortProcess);
1335       return;
1336     }
1337     AliSysInfo::AddStamp("LoadGeom");
1338     TString detsToCheck=fRunLocalReconstruction;
1339     if(!AliGeomManager::CheckSymNamesLUT(detsToCheck.Data())) {
1340       Abort("CheckSymNamesLUT", TSelector::kAbortProcess);
1341       return;
1342     }
1343     AliSysInfo::AddStamp("CheckGeom");
1344   }
1345
1346   if (!MisalignGeometry(fLoadAlignData)) {
1347     Abort("MisalignGeometry", TSelector::kAbortProcess);
1348     return;
1349   }
1350   AliCDBManager::Instance()->UnloadFromCache("GRP/Geometry/Data");
1351   AliSysInfo::AddStamp("MisalignGeom");
1352
1353   if (!InitGRP()) {
1354     Abort("InitGRP", TSelector::kAbortProcess);
1355     return;
1356   }
1357   AliSysInfo::AddStamp("InitGRP");
1358
1359   if (!LoadCDB()) {
1360     Abort("LoadCDB", TSelector::kAbortProcess);
1361     return;
1362   }
1363   AliSysInfo::AddStamp("LoadCDB");
1364
1365   if (!LoadTriggerScalersCDB()) {
1366     Abort("LoadTriggerScalersCDB", TSelector::kAbortProcess);
1367     return;
1368   }
1369   AliSysInfo::AddStamp("LoadTriggerScalersCDB");
1370
1371   if (!LoadCTPTimeParamsCDB()) {
1372     Abort("LoadCTPTimeParamsCDB", TSelector::kAbortProcess);
1373     return;
1374   }
1375   AliSysInfo::AddStamp("LoadCTPTimeParamsCDB");
1376
1377   // Read the reconstruction parameters from OCDB
1378   if (!InitRecoParams()) {
1379     AliWarning("Not all detectors have correct RecoParam objects initialized");
1380   }
1381   AliSysInfo::AddStamp("InitRecoParams");
1382
1383   if (fInput && gProof) {
1384     if (reco) *reco = *this;
1385
1386     gGeoManager->SetName("Geometry");
1387     gProof->AddInputData(gGeoManager,kTRUE);
1388     gGeoManager = NULL;
1389     gProof->AddInputData(const_cast<TMap*>(AliCDBManager::Instance()->GetEntryCache()),kTRUE);
1390     fInput->Add(new TParameter<Int_t>("RunNumber",AliCDBManager::Instance()->GetRun()));
1391     AliMagF *magFieldMap = (AliMagF*)TGeoGlobalMagField::Instance()->GetField();
1392     magFieldMap->SetName("MagneticFieldMap");
1393     gProof->AddInputData(magFieldMap,kTRUE);
1394   }
1395
1396 }
1397
1398 //_____________________________________________________________________________
1399 void AliReconstruction::SlaveBegin(TTree*)
1400 {
1401   // Initialization related to run-loader,
1402   // vertexer, trackers, recontructors
1403   // In proof mode it is executed on the slave
1404   AliCodeTimerAuto("",0);
1405
1406   TProofOutputFile *outProofFile = NULL;
1407   if (fInput) {
1408     if (AliDebugLevel() > 0) fInput->Print();
1409     if (AliDebugLevel() > 10) fInput->Dump();
1410     if (AliReconstruction *reco = (AliReconstruction*)fInput->FindObject("AliReconstruction")) {
1411       *this = *reco;
1412     }
1413     if (TGeoManager *tgeo = (TGeoManager*)fInput->FindObject("Geometry")) {
1414       gGeoManager = tgeo;
1415       AliGeomManager::SetGeometry(tgeo);
1416     }
1417     if (TMap *entryCache = (TMap*)fInput->FindObject("CDBEntryCache")) {
1418       Int_t runNumber = -1;
1419       if (TProof::GetParameter(fInput,"RunNumber",runNumber) == 0) {
1420         AliCDBManager *man = AliCDBManager::Instance(entryCache,runNumber);
1421         man->SetCacheFlag(kTRUE);
1422         man->SetLock(kTRUE);
1423         man->Print();
1424       }
1425     }
1426     if (AliMagF *map = (AliMagF*)fInput->FindObject("MagneticFieldMap")) {
1427       AliMagF *newMap = new AliMagF(*map);
1428       if (!newMap->LoadParameterization()) {
1429         Abort("AliMagF::LoadParameterization", TSelector::kAbortProcess);
1430         return;
1431       }
1432       TGeoGlobalMagField::Instance()->SetField(newMap);
1433       TGeoGlobalMagField::Instance()->Lock();
1434     }
1435     if (TNamed *outputFileName = (TNamed*)fInput->FindObject("PROOF_OUTPUTFILE"))
1436       fProofOutputFileName = outputFileName->GetTitle();
1437     if (TNamed *outputLocation = (TNamed*)fInput->FindObject("PROOF_OUTPUTFILE_LOCATION"))
1438       fProofOutputLocation = outputLocation->GetTitle();
1439     if (fInput->FindObject("PROOF_OUTPUTFILE_DATASET"))
1440       fProofOutputDataset = kTRUE;
1441     if (TNamed *archiveList = (TNamed*)fInput->FindObject("PROOF_OUTPUTFILE_ARCHIVE"))
1442       fProofOutputArchive = archiveList->GetTitle();
1443     if (!fProofOutputFileName.IsNull() &&
1444         !fProofOutputLocation.IsNull() &&
1445         fProofOutputArchive.IsNull()) {
1446       if (!fProofOutputDataset) {
1447         outProofFile = new TProofOutputFile(fProofOutputFileName.Data(),"M");
1448         outProofFile->SetOutputFileName(Form("%s%s",fProofOutputLocation.Data(),fProofOutputFileName.Data()));
1449       }
1450       else {
1451         outProofFile = new TProofOutputFile(fProofOutputFileName.Data(),"DROV",fProofOutputLocation.Data());
1452       }
1453       if (AliDebugLevel() > 0) outProofFile->Dump();
1454       fOutput->Add(outProofFile);
1455     }
1456     AliSysInfo::AddStamp("ReadInputInSlaveBegin");
1457   }
1458
1459   // get the run loader
1460   if (!InitRunLoader()) {
1461     Abort("InitRunLoader", TSelector::kAbortProcess);
1462     return;
1463   }
1464   AliSysInfo::AddStamp("LoadLoader");
1465  
1466   ftVertexer = new AliVertexerTracks(AliTracker::GetBz());
1467
1468   // get trackers
1469   if (!fRunTracking.IsNull() && !CreateTrackers(fRunTracking)) {
1470     Abort("CreateTrackers", TSelector::kAbortProcess);
1471     return;
1472   }      
1473   AliSysInfo::AddStamp("CreateTrackers");
1474
1475   // create the ESD output file and tree
1476   if (!outProofFile) {
1477     ffile = TFile::Open("AliESDs.root", "RECREATE");
1478     ffile->SetCompressionLevel(2);
1479     if (!ffile->IsOpen()) {
1480       Abort("OpenESDFile", TSelector::kAbortProcess);
1481       return;
1482     }
1483   }
1484   else {
1485     AliInfo(Form("Opening output PROOF file: %s/%s",
1486                  outProofFile->GetDir(), outProofFile->GetFileName()));
1487     if (!(ffile = outProofFile->OpenFile("RECREATE"))) {
1488       Abort(Form("Problems opening output PROOF file: %s/%s",
1489                  outProofFile->GetDir(), outProofFile->GetFileName()),
1490             TSelector::kAbortProcess);
1491       return;
1492     }
1493   }
1494
1495   ftree = new TTree("esdTree", "Tree with ESD objects");
1496   fesd = new AliESDEvent();
1497   fesd->CreateStdContent();
1498   if (fesd->GetESDRun()) ((AliESDRun*)fesd->GetESDRun())->SetBeamEnergyIsSqrtSHalfGeV();
1499   // add a so far non-std object to the ESD, this will
1500   // become part of the std content
1501   fesd->AddObject(new AliESDHLTDecision);
1502
1503   fesd->WriteToTree(ftree);
1504   if (fWriteESDfriend) {
1505     // careful:
1506     // Since we add the branch manually we must 
1507     // book and add it after WriteToTree
1508     // otherwise it is created twice,
1509     // once via writetotree and once here.
1510     // The case for AliESDfriend is now 
1511     // caught also in AlIESDEvent::WriteToTree but 
1512     // be careful when changing the name (AliESDfriend is not 
1513     // a TNamed so we had to hardwire it)
1514     fesdf = new AliESDfriend();
1515     TBranch *br=ftree->Branch("ESDfriend.","AliESDfriend", &fesdf);
1516     br->SetFile("AliESDfriends.root");
1517     fesd->AddObject(fesdf);
1518   }
1519   ftree->GetUserInfo()->Add(fesd);
1520
1521   fhlttree = new TTree("HLTesdTree", "Tree with HLT ESD objects");
1522   fhltesd = new AliESDEvent();
1523   fhltesd->CreateStdContent();
1524   if (fhltesd->GetESDRun()) ((AliESDRun*)fhltesd->GetESDRun())->SetBeamEnergyIsSqrtSHalfGeV();
1525   // read the ESD template from CDB
1526   // HLT is allowed to put non-std content to its ESD, the non-std
1527   // objects need to be created before invocation of WriteToTree in
1528   // order to create all branches. Initialization is done from an
1529   // ESD layout template in CDB
1530   AliCDBManager* man = AliCDBManager::Instance();
1531   AliCDBPath hltESDConfigPath("HLT/ConfigHLT/esdLayout");
1532   AliCDBEntry* hltESDConfig=NULL;
1533   if (man->GetId(hltESDConfigPath)!=NULL &&
1534       (hltESDConfig=man->Get(hltESDConfigPath))!=NULL) {
1535     AliESDEvent* pESDLayout=dynamic_cast<AliESDEvent*>(hltESDConfig->GetObject());
1536     if (pESDLayout) {
1537       // init all internal variables from the list of objects
1538       pESDLayout->GetStdContent();
1539
1540       // copy content and create non-std objects
1541       *fhltesd=*pESDLayout;
1542       fhltesd->Reset();
1543     } else {
1544       AliError(Form("error setting hltEsd layout from %s: invalid object type",
1545                     hltESDConfigPath.GetPath().Data()));
1546     }
1547   }
1548
1549   fhltesd->WriteToTree(fhlttree);
1550   fhlttree->GetUserInfo()->Add(fhltesd);
1551
1552   ProcInfo_t procInfo;
1553   gSystem->GetProcInfo(&procInfo);
1554   AliInfo(Form("Current memory usage %d %d", procInfo.fMemResident, procInfo.fMemVirtual));
1555   
1556   //QA
1557   //Initialize the QA and start of cycle 
1558   if (fRunQA || fRunGlobalQA) 
1559     InitQA() ; 
1560
1561   //Initialize the Plane Efficiency framework
1562   if (fRunPlaneEff && !InitPlaneEff()) {
1563     Abort("InitPlaneEff", TSelector::kAbortProcess);
1564     return;
1565   }
1566
1567   if (strcmp(gProgName,"alieve") == 0)
1568     fRunAliEVE = InitAliEVE();
1569
1570   return;
1571 }
1572
1573 //_____________________________________________________________________________
1574 Bool_t AliReconstruction::Process(Long64_t entry)
1575 {
1576   // run the reconstruction over a single entry
1577   // from the chain with raw data
1578   AliCodeTimerAuto("",0);
1579
1580   TTree *currTree = fChain->GetTree();
1581   AliRawVEvent *event = NULL;
1582   currTree->SetBranchAddress("rawevent",&event);
1583   currTree->GetEntry(entry);
1584   fRawReader = new AliRawReaderRoot(event);
1585   fStatus = ProcessEvent(fRunLoader->GetNumberOfEvents());  
1586   delete fRawReader;
1587   fRawReader = NULL;
1588   delete event;
1589
1590   return fStatus;
1591 }
1592
1593 //_____________________________________________________________________________
1594 void AliReconstruction::Init(TTree *tree)
1595 {
1596   if (tree == 0) {
1597     AliError("The input tree is not found!");
1598     return;
1599   }
1600   fChain = tree;
1601 }
1602
1603 //_____________________________________________________________________________
1604 Bool_t AliReconstruction::ProcessEvent(Int_t iEvent)
1605 {
1606   // run the reconstruction over a single event
1607   // The event loop is steered in Run method
1608
1609
1610   static Long_t oldMres=0;
1611   static Long_t oldMvir=0;
1612   static Float_t oldCPU=0;
1613
1614   AliCodeTimerAuto("",0);
1615
1616   AliESDpid PID;
1617
1618   if (iEvent >= fRunLoader->GetNumberOfEvents()) {
1619     fRunLoader->SetEventNumber(iEvent);
1620     fRunLoader->GetHeader()->Reset(fRawReader->GetRunNumber(), 
1621                                    iEvent, iEvent);
1622     fRunLoader->TreeE()->Fill();
1623     if (fRawReader && fRawReader->UseAutoSaveESD())
1624       fRunLoader->TreeE()->AutoSave("SaveSelf");
1625   }
1626
1627   if ((iEvent < fFirstEvent) || ((fLastEvent >= 0) && (iEvent > fLastEvent))) {
1628     return kTRUE;
1629   }
1630
1631
1632   fRunLoader->GetEvent(iEvent);
1633
1634   // Fill Event-info object
1635   GetEventInfo();
1636   fRecoParam.SetEventSpecie(fRunInfo,fEventInfo,fListOfCosmicTriggers);
1637   AliInfo(Form("================================= Processing event %d of type %-10s ==================================", iEvent,fRecoParam.PrintEventSpecie()));
1638
1639   // Set the reco-params
1640   {
1641     TString detStr = fLoadCDB;
1642     for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
1643       if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
1644       AliReconstructor *reconstructor = GetReconstructor(iDet);
1645       if (reconstructor && fRecoParam.GetDetRecoParamArray(iDet)) {
1646         const AliDetectorRecoParam *par = fRecoParam.GetDetRecoParam(iDet);
1647         reconstructor->SetRecoParam(par);
1648         reconstructor->GetPidSettings(&PID);
1649         reconstructor->SetEventInfo(&fEventInfo);
1650         if (fRunQA) {
1651           AliQAManager::QAManager()->SetRecoParam(iDet, par) ; 
1652           AliQAManager::QAManager()->SetEventSpecie(AliRecoParam::Convert(par->GetEventSpecie())) ;
1653         }
1654       }
1655     }
1656     const AliDetectorRecoParam *grppar = fRecoParam.GetDetRecoParam(kNDetectors);
1657     AliQAManager::QAManager()->SetRecoParam(AliQAv1::kGLOBAL, grppar) ; 
1658     AliQAManager::QAManager()->SetEventSpecie(AliRecoParam::Convert(grppar->GetEventSpecie())) ;
1659   }
1660
1661     // QA on single raw 
1662   if (fRunQA && IsInTasks(AliQAv1::kRAWS)) {
1663     AliQAManager::QAManager()->SetEventSpecie(fRecoParam.GetEventSpecie()) ;
1664     AliQAManager::QAManager()->RunOneEvent(fRawReader) ;  
1665   }
1666     // local single event reconstruction
1667     if (!fRunLocalReconstruction.IsNull()) {
1668       TString detectors=fRunLocalReconstruction;
1669       // run HLT event reconstruction first
1670       // ;-( IsSelected changes the string
1671       if (IsSelected("HLT", detectors) &&
1672           !RunLocalEventReconstruction("HLT")) {
1673         if (fStopOnError) {CleanUp(); return kFALSE;}
1674       }
1675       detectors=fRunLocalReconstruction;
1676       detectors.ReplaceAll("HLT", "");
1677       if (!RunLocalEventReconstruction(detectors)) {
1678         if (fStopOnError) {
1679           CleanUp(); 
1680           return kFALSE;
1681         }
1682       }
1683     }
1684
1685   
1686     // fill Event header information from the RawEventHeader
1687     if (fRawReader){FillRawEventHeaderESD(fesd);}
1688     if (fRawReader){FillRawEventHeaderESD(fhltesd);}
1689
1690     fesd->SetRunNumber(fRunLoader->GetHeader()->GetRun());
1691     fhltesd->SetRunNumber(fRunLoader->GetHeader()->GetRun());
1692     fesd->SetEventNumberInFile(fRunLoader->GetHeader()->GetEventNrInRun());
1693     fhltesd->SetEventNumberInFile(fRunLoader->GetHeader()->GetEventNrInRun());
1694
1695     fesd->SetEventSpecie(fRecoParam.GetEventSpecie());
1696     fhltesd->SetEventSpecie(fRecoParam.GetEventSpecie());
1697     
1698     // Set magnetic field from the tracker
1699     fesd->SetMagneticField(AliTracker::GetBz());
1700     fhltesd->SetMagneticField(AliTracker::GetBz());
1701     //
1702     AliMagF* fld = (AliMagF*)TGeoGlobalMagField::Instance()->GetField();
1703     if (fld) { // set info needed for field initialization
1704       fesd->SetCurrentL3(fld->GetCurrentSol());
1705       fesd->SetCurrentDip(fld->GetCurrentDip());
1706       fesd->SetBeamEnergy(fld->GetBeamEnergy());
1707       fesd->SetBeamType(fld->GetBeamTypeText());
1708       fesd->SetUniformBMap(fld->IsUniform());
1709       fesd->SetBInfoStored();
1710       //
1711       fhltesd->SetCurrentL3(fld->GetCurrentSol());
1712       fhltesd->SetCurrentDip(fld->GetCurrentDip());
1713       fhltesd->SetBeamEnergy(fld->GetBeamEnergy());
1714       fhltesd->SetBeamType(fld->GetBeamTypeText());
1715       fhltesd->SetUniformBMap(fld->IsUniform());
1716       fhltesd->SetBInfoStored();
1717     }
1718     //
1719     // Set most probable pt, for B=0 tracking
1720     // Get the global reco-params. They are atposition 16 inside the array of detectors in fRecoParam
1721     const AliGRPRecoParam *grpRecoParam = dynamic_cast<const AliGRPRecoParam*>(fRecoParam.GetDetRecoParam(kNDetectors));
1722     if (grpRecoParam) AliExternalTrackParam::SetMostProbablePt(grpRecoParam->GetMostProbablePt());
1723     
1724     // Fill raw-data error log into the ESD
1725     if (fRawReader) FillRawDataErrorLog(iEvent,fesd);
1726
1727     // vertex finder
1728     if (fRunVertexFinder) {
1729       if (!RunVertexFinder(fesd)) {
1730         if (fStopOnError) {CleanUp(); return kFALSE;}
1731       }
1732     }
1733
1734     // For Plane Efficiency: run the SPD trackleter
1735     if (fRunPlaneEff && fSPDTrackleter) {
1736       if (!RunSPDTrackleting(fesd)) {
1737         if (fStopOnError) {CleanUp(); return kFALSE;}
1738       }
1739     }
1740
1741     // Muon tracking
1742     if (!fRunTracking.IsNull()) {
1743       if (fRunMuonTracking) {
1744         if (!RunMuonTracking(fesd)) {
1745           if (fStopOnError) {CleanUp(); return kFALSE;}
1746         }
1747       }
1748     }
1749
1750     // barrel tracking
1751     if (!fRunTracking.IsNull()) {
1752       if (!RunTracking(fesd,PID)) {
1753         if (fStopOnError) {CleanUp(); return kFALSE;}
1754       }
1755     }
1756
1757     // fill ESD
1758     if (!fFillESD.IsNull()) {
1759       TString detectors=fFillESD;
1760       // run HLT first and on hltesd
1761       // ;-( IsSelected changes the string
1762       if (IsSelected("HLT", detectors) &&
1763           !FillESD(fhltesd, "HLT")) {
1764         if (fStopOnError) {CleanUp(); return kFALSE;}
1765       }
1766       detectors=fFillESD;
1767       // Temporary fix to avoid problems with HLT that overwrites the offline ESDs
1768       if (detectors.Contains("ALL")) {
1769         detectors="";
1770         for (Int_t idet=0; idet<kNDetectors; ++idet){
1771           detectors += fgkDetectorName[idet];
1772           detectors += " ";
1773         }
1774       }
1775       detectors.ReplaceAll("HLT", "");
1776       if (!FillESD(fesd, detectors)) {
1777         if (fStopOnError) {CleanUp(); return kFALSE;}
1778       }
1779     }
1780  
1781     // combined PID
1782     PID.MakePID(fesd);
1783
1784     if (fFillTriggerESD) {
1785       if (!FillTriggerESD(fesd)) {
1786         if (fStopOnError) {CleanUp(); return kFALSE;}
1787       }
1788     }
1789     // Always fill scalers
1790     if (!FillTriggerScalers(fesd)) {
1791        if (fStopOnError) {CleanUp(); return kFALSE;}
1792     }
1793     
1794
1795     ffile->cd();
1796
1797     //
1798     // Propagate track to the beam pipe  (if not already done by ITS)
1799     //
1800     const Int_t ntracks = fesd->GetNumberOfTracks();
1801     const Double_t kRadius  = 2.8; //something less than the beam pipe radius
1802
1803     TObjArray trkArray;
1804     UShort_t *selectedIdx=new UShort_t[ntracks];
1805
1806     for (Int_t itrack=0; itrack<ntracks; itrack++){
1807       const Double_t kMaxStep = 1;   //max step over the material
1808       Bool_t ok;
1809
1810       AliESDtrack *track = fesd->GetTrack(itrack);
1811       if (!track) continue;
1812
1813       AliExternalTrackParam *tpcTrack =
1814            (AliExternalTrackParam *)track->GetTPCInnerParam();
1815       ok = kFALSE;
1816       if (tpcTrack)
1817         ok = AliTracker::
1818           PropagateTrackToBxByBz(tpcTrack,kRadius,track->GetMass(),kMaxStep,kFALSE);
1819
1820       if (ok) {
1821         Int_t n=trkArray.GetEntriesFast();
1822         selectedIdx[n]=track->GetID();
1823         trkArray.AddLast(tpcTrack);
1824       }
1825
1826       //Tracks refitted by ITS should already be at the SPD vertex
1827       if (track->IsOn(AliESDtrack::kITSrefit)) continue;
1828
1829       AliTracker::
1830          PropagateTrackToBxByBz(track,kRadius,track->GetMass(),kMaxStep,kFALSE);
1831       Double_t x[3]; track->GetXYZ(x);
1832       Double_t b[3]; AliTracker::GetBxByBz(x,b);
1833       track->RelateToVertexBxByBz(fesd->GetPrimaryVertexSPD(), b, kVeryBig);
1834
1835     }
1836
1837     //
1838     // Improve the reconstructed primary vertex position using the tracks
1839     //
1840     Bool_t runVertexFinderTracks = fRunVertexFinderTracks;
1841     if(fesd->GetPrimaryVertexSPD()) {
1842       TString vtitle = fesd->GetPrimaryVertexSPD()->GetTitle();
1843       if(vtitle.Contains("cosmics")) {
1844         runVertexFinderTracks=kFALSE;
1845       }
1846     }
1847
1848     if (runVertexFinderTracks) {
1849        // TPC + ITS primary vertex
1850        ftVertexer->SetITSMode();
1851        ftVertexer->SetConstraintOff();
1852        // get cuts for vertexer from AliGRPRecoParam
1853        if (grpRecoParam) {
1854          Int_t nCutsVertexer = grpRecoParam->GetVertexerTracksNCuts();
1855          Double_t *cutsVertexer = new Double_t[nCutsVertexer];
1856          grpRecoParam->GetVertexerTracksCutsITS(cutsVertexer);
1857          ftVertexer->SetCuts(cutsVertexer);
1858          delete [] cutsVertexer; cutsVertexer = NULL; 
1859          if(fDiamondProfile && grpRecoParam->GetVertexerTracksConstraintITS())
1860            ftVertexer->SetVtxStart(fDiamondProfile);
1861        }
1862        AliESDVertex *pvtx=ftVertexer->FindPrimaryVertex(fesd);
1863        if (pvtx) {
1864           if (pvtx->GetStatus()) {
1865              fesd->SetPrimaryVertexTracks(pvtx);
1866              for (Int_t i=0; i<ntracks; i++) {
1867                  AliESDtrack *t = fesd->GetTrack(i);
1868                  Double_t x[3]; t->GetXYZ(x);
1869                  Double_t b[3]; AliTracker::GetBxByBz(x,b);
1870                  t->RelateToVertexBxByBz(pvtx, b, kVeryBig);
1871              } 
1872           }
1873           delete pvtx; pvtx=NULL;
1874        }
1875
1876        // TPC-only primary vertex
1877        ftVertexer->SetTPCMode();
1878        ftVertexer->SetConstraintOff();
1879        // get cuts for vertexer from AliGRPRecoParam
1880        if (grpRecoParam) {
1881          Int_t nCutsVertexer = grpRecoParam->GetVertexerTracksNCuts();
1882          Double_t *cutsVertexer = new Double_t[nCutsVertexer];
1883          grpRecoParam->GetVertexerTracksCutsTPC(cutsVertexer);
1884          ftVertexer->SetCuts(cutsVertexer);
1885          delete [] cutsVertexer; cutsVertexer = NULL; 
1886          if(fDiamondProfileTPC && grpRecoParam->GetVertexerTracksConstraintTPC())
1887            ftVertexer->SetVtxStart(fDiamondProfileTPC);
1888        }
1889        pvtx=ftVertexer->FindPrimaryVertex(&trkArray,selectedIdx);
1890        if (pvtx) {
1891           if (pvtx->GetStatus()) {
1892              fesd->SetPrimaryVertexTPC(pvtx);
1893              for (Int_t i=0; i<ntracks; i++) {
1894                  AliESDtrack *t = fesd->GetTrack(i);
1895                  Double_t x[3]; t->GetXYZ(x);
1896                  Double_t b[3]; AliTracker::GetBxByBz(x,b);
1897                  t->RelateToVertexTPCBxByBz(pvtx, b, kVeryBig);
1898              } 
1899           }
1900           delete pvtx; pvtx=NULL;
1901        }
1902
1903     }
1904     delete[] selectedIdx;
1905
1906     if(fDiamondProfile) fesd->SetDiamond(fDiamondProfile);
1907     
1908
1909     if (fRunV0Finder) {
1910        // V0 finding
1911        AliV0vertexer vtxer;
1912        vtxer.Tracks2V0vertices(fesd);
1913
1914        if (fRunCascadeFinder) {
1915           // Cascade finding
1916           AliCascadeVertexer cvtxer;
1917           cvtxer.V0sTracks2CascadeVertices(fesd);
1918        }
1919     }
1920  
1921     // write ESD
1922     if (fCleanESD) CleanESD(fesd);
1923
1924   if (fRunQA && IsInTasks(AliQAv1::kESDS)) {
1925     AliQAManager::QAManager()->SetEventSpecie(fRecoParam.GetEventSpecie()) ;
1926     AliQAManager::QAManager()->RunOneEvent(fesd, fhltesd) ; 
1927   }
1928   if (fRunGlobalQA) {
1929     AliQADataMaker *qadm = AliQAManager::QAManager()->GetQADataMaker(AliQAv1::kGLOBAL);
1930       qadm->SetEventSpecie(fRecoParam.GetEventSpecie()) ;
1931     if (qadm && IsInTasks(AliQAv1::kESDS))
1932       qadm->Exec(AliQAv1::kESDS, fesd);
1933   }
1934
1935   // copy HLT decision from HLTesd to esd
1936   // the most relevant information is stored in a reduced container in the esd,
1937   // while the full information can be found in the HLTesd
1938   TObject* pHLTSrc=fhltesd->FindListObject(AliESDHLTDecision::Name());
1939   TObject* pHLTTgt=fesd->FindListObject(AliESDHLTDecision::Name());
1940   if (pHLTSrc && pHLTTgt) {
1941     pHLTSrc->Copy(*pHLTTgt);
1942   }
1943
1944     if (fWriteESDfriend) {
1945       //      fesdf->~AliESDfriend();
1946       //  new (fesdf) AliESDfriend(); // Reset...
1947       fesd->GetESDfriend(fesdf);
1948     }
1949     ftree->Fill();
1950
1951     // Auto-save the ESD tree in case of prompt reco @P2
1952     if (fRawReader && fRawReader->UseAutoSaveESD()) {
1953       ftree->AutoSave("SaveSelf");
1954       TFile *friendfile = (TFile *)(gROOT->GetListOfFiles()->FindObject("AliESDfriends.root"));
1955       if (friendfile) friendfile->Save();
1956     }
1957
1958     // write HLT ESD
1959     fhlttree->Fill();
1960
1961     // call AliEVE
1962     if (fRunAliEVE) RunAliEVE();
1963
1964     fesd->Reset();
1965     fhltesd->Reset();
1966     if (fWriteESDfriend) {
1967       fesdf->~AliESDfriend();
1968       new (fesdf) AliESDfriend(); // Reset...
1969     }
1970  
1971     ProcInfo_t procInfo;
1972     gSystem->GetProcInfo(&procInfo);
1973     AliInfo(Form("========================= End Event %d: memory res %d(%3d) vir %d(%3d) CPU %5.2f =====================",
1974                  iEvent, procInfo.fMemResident/1024, (procInfo.fMemResident-oldMres)/1024, 
1975                  procInfo.fMemVirtual/1024,(procInfo.fMemVirtual-oldMvir)/1024,procInfo.fCpuUser+procInfo.fCpuSys-oldCPU));
1976     oldMres=procInfo.fMemResident;
1977     oldMvir=procInfo.fMemVirtual;
1978     oldCPU=procInfo.fCpuUser+procInfo.fCpuSys;
1979   
1980     fEventInfo.Reset();
1981     for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
1982       if (fReconstructor[iDet]) {
1983         fReconstructor[iDet]->SetRecoParam(NULL);
1984         fReconstructor[iDet]->SetEventInfo(NULL);
1985       }
1986       if (fTracker[iDet]) fTracker[iDet]->SetEventInfo(NULL);
1987     }
1988         
1989   if (fRunQA || fRunGlobalQA) 
1990     AliQAManager::QAManager()->Increment() ; 
1991   
1992     return kTRUE;
1993 }
1994
1995 //_____________________________________________________________________________
1996 void AliReconstruction::SlaveTerminate()
1997 {
1998   // Finalize the run on the slave side
1999   // Called after the exit
2000   // from the event loop
2001   AliCodeTimerAuto("",0);
2002
2003   if (fIsNewRunLoader) { // galice.root didn't exist
2004     fRunLoader->WriteHeader("OVERWRITE");
2005     fRunLoader->CdGAFile();
2006     fRunLoader->Write(0, TObject::kOverwrite);
2007   }
2008
2009   const TMap *cdbMap = AliCDBManager::Instance()->GetStorageMap();       
2010   const TList *cdbList = AliCDBManager::Instance()->GetRetrievedIds();   
2011                  
2012    TMap *cdbMapCopy = new TMap(cdbMap->GetEntries());    
2013    cdbMapCopy->SetOwner(1);      
2014    cdbMapCopy->SetName("cdbMap");        
2015    TIter iter(cdbMap->GetTable());       
2016          
2017    TPair* pair = 0;      
2018    while((pair = dynamic_cast<TPair*> (iter.Next()))){   
2019          TObjString* keyStr = dynamic_cast<TObjString*> (pair->Key());   
2020          TObjString* valStr = dynamic_cast<TObjString*> (pair->Value());         
2021          cdbMapCopy->Add(new TObjString(keyStr->GetName()), new TObjString(valStr->GetName()));  
2022    }     
2023          
2024    TList *cdbListCopy = new TList();     
2025    cdbListCopy->SetOwner(1);     
2026    cdbListCopy->SetName("cdbList");      
2027          
2028    TIter iter2(cdbList);         
2029          
2030         AliCDBId* id=0;
2031         while((id = dynamic_cast<AliCDBId*> (iter2.Next()))){    
2032          cdbListCopy->Add(new TObjString(id->ToString().Data()));        
2033    }     
2034          
2035    ftree->GetUserInfo()->Add(cdbMapCopy);        
2036    ftree->GetUserInfo()->Add(cdbListCopy);
2037
2038
2039   ffile->cd();
2040
2041   if (fWriteESDfriend)
2042     ftree->SetBranchStatus("ESDfriend*",0);
2043   // we want to have only one tree version number
2044   ftree->Write(ftree->GetName(),TObject::kOverwrite);
2045   fhlttree->Write(fhlttree->GetName(),TObject::kOverwrite);
2046
2047 // Finish with Plane Efficiency evaluation: before of CleanUp !!!
2048   if (fRunPlaneEff && !FinishPlaneEff()) {
2049    AliWarning("Finish PlaneEff evaluation failed");
2050   }
2051
2052   // End of cycle for the in-loop  
2053
2054   if (fRunQA || fRunGlobalQA) {
2055     AliQAManager::QAManager()->EndOfCycle() ;
2056     if (fInput &&
2057         !fProofOutputLocation.IsNull() &&
2058         fProofOutputArchive.IsNull() &&
2059         !fProofOutputDataset) {
2060       TString qaOutputFile(Form("%sMerged.%s.Data.root",
2061                                 fProofOutputLocation.Data(),
2062                                 AliQAv1::GetQADataFileName()));
2063       TProofOutputFile *qaProofFile = new TProofOutputFile(Form("Merged.%s.Data.root",
2064                                                                 AliQAv1::GetQADataFileName()));
2065       qaProofFile->SetOutputFileName(qaOutputFile.Data());
2066       if (AliDebugLevel() > 0) qaProofFile->Dump();
2067       fOutput->Add(qaProofFile);
2068       MergeQA(qaProofFile->GetFileName());
2069     }
2070     else {
2071       MergeQA();
2072     }
2073   }
2074
2075   gROOT->cd();
2076   CleanUp();
2077
2078   if (fInput) {
2079     if (!fProofOutputFileName.IsNull() &&
2080         !fProofOutputLocation.IsNull() &&
2081         fProofOutputDataset &&
2082         !fProofOutputArchive.IsNull()) {
2083       TProofOutputFile *zipProofFile = new TProofOutputFile(fProofOutputFileName.Data(),
2084                                                             "DROV",
2085                                                             fProofOutputLocation.Data());
2086       if (AliDebugLevel() > 0) zipProofFile->Dump();
2087       fOutput->Add(zipProofFile);
2088       TString fileList(fProofOutputArchive.Data());
2089       fileList.ReplaceAll(","," ");
2090       TString command;
2091 #if ROOT_SVN_REVISION >= 30174
2092       command.Form("zip -n root %s/%s %s",zipProofFile->GetDir(kTRUE),zipProofFile->GetFileName(),fileList.Data());
2093 #else
2094       command.Form("zip -n root %s/%s %s",zipProofFile->GetDir(),zipProofFile->GetFileName(),fileList.Data());
2095 #endif
2096       AliInfo(Form("Executing: %s",command.Data()));
2097       gSystem->Exec(command.Data());
2098     }
2099   }
2100 }
2101     
2102 //_____________________________________________________________________________
2103 void AliReconstruction::Terminate()
2104 {
2105   // Create tags for the events in the ESD tree (the ESD tree is always present)
2106   // In case of empty events the tags will contain dummy values
2107   AliCodeTimerAuto("",0);
2108
2109   // Do not call the ESD tag creator in case of PROOF-based reconstruction
2110   if (!fInput) {
2111     AliESDTagCreator *esdtagCreator = new AliESDTagCreator();
2112     esdtagCreator->CreateESDTags(fFirstEvent,fLastEvent,fGRPData, AliQAv1::Instance()->GetQA(), AliQAv1::Instance()->GetEventSpecies(), AliQAv1::kNDET, AliRecoParam::kNSpecies);
2113     delete esdtagCreator;
2114   }
2115
2116   // Cleanup of CDB manager: cache and active storages!
2117   AliCDBManager::Instance()->ClearCache();
2118 }
2119
2120 //_____________________________________________________________________________
2121 Bool_t AliReconstruction::RunLocalEventReconstruction(const TString& detectors)
2122 {
2123 // run the local reconstruction
2124
2125   static Int_t eventNr=0;
2126   AliCodeTimerAuto("",0)
2127
2128   TString detStr = detectors;
2129   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2130     if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
2131     AliReconstructor* reconstructor = GetReconstructor(iDet);
2132     if (!reconstructor) continue;
2133     AliLoader* loader = fLoader[iDet];
2134     // Matthias April 2008: temporary fix to run HLT reconstruction
2135     // although the HLT loader is missing
2136     if (strcmp(fgkDetectorName[iDet], "HLT")==0) {
2137       if (fRawReader) {
2138         reconstructor->Reconstruct(fRawReader, NULL);
2139       } else {
2140         TTree* dummy=NULL;
2141         reconstructor->Reconstruct(dummy, NULL);
2142       }
2143       continue;
2144     }
2145     if (!loader) {
2146       AliWarning(Form("No loader is defined for %s!",fgkDetectorName[iDet]));
2147       continue;
2148     }
2149     // conversion of digits
2150     if (fRawReader && reconstructor->HasDigitConversion()) {
2151       AliInfo(Form("converting raw data digits into root objects for %s", 
2152                    fgkDetectorName[iDet]));
2153 //      AliCodeTimerAuto(Form("converting raw data digits into root objects for %s", 
2154 //                            fgkDetectorName[iDet]),0);
2155       loader->LoadDigits("update");
2156       loader->CleanDigits();
2157       loader->MakeDigitsContainer();
2158       TTree* digitsTree = loader->TreeD();
2159       reconstructor->ConvertDigits(fRawReader, digitsTree);
2160       loader->WriteDigits("OVERWRITE");
2161       loader->UnloadDigits();
2162     }
2163     // local reconstruction
2164     AliInfo(Form("running reconstruction for %s", fgkDetectorName[iDet]));
2165     //AliCodeTimerAuto(Form("running reconstruction for %s", fgkDetectorName[iDet]),0);
2166     loader->LoadRecPoints("update");
2167     loader->CleanRecPoints();
2168     loader->MakeRecPointsContainer();
2169     TTree* clustersTree = loader->TreeR();
2170     if (fRawReader && !reconstructor->HasDigitConversion()) {
2171       reconstructor->Reconstruct(fRawReader, clustersTree);
2172     } else {
2173       loader->LoadDigits("read");
2174       TTree* digitsTree = loader->TreeD();
2175       if (!digitsTree) {
2176         AliError(Form("Can't get the %s digits tree", fgkDetectorName[iDet]));
2177         if (fStopOnError) 
2178           return kFALSE;
2179       } else {
2180         reconstructor->Reconstruct(digitsTree, clustersTree);
2181         if (fRunQA && IsInTasks(AliQAv1::kDIGITSR)) {
2182           AliQAManager::QAManager()->SetEventSpecie(fRecoParam.GetEventSpecie()) ;
2183           AliQAManager::QAManager()->RunOneEventInOneDetector(iDet, digitsTree) ; 
2184         }
2185       }
2186       loader->UnloadDigits();
2187     }
2188                 if (fRunQA && IsInTasks(AliQAv1::kRECPOINTS)) {
2189       AliQAManager::QAManager()->SetEventSpecie(fRecoParam.GetEventSpecie()) ;
2190                         AliQAManager::QAManager()->RunOneEventInOneDetector(iDet, clustersTree) ; 
2191     }
2192     loader->WriteRecPoints("OVERWRITE");
2193     loader->UnloadRecPoints();
2194     AliSysInfo::AddStamp(Form("LRec%s_%d",fgkDetectorName[iDet],eventNr), iDet,1,eventNr);
2195   }
2196   IsSelected("CTP", detStr);
2197   if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
2198     AliError(Form("the following detectors were not found: %s",
2199                   detStr.Data()));
2200     if (fStopOnError) 
2201       return kFALSE;
2202   }
2203   eventNr++;
2204   return kTRUE;
2205 }
2206 //_____________________________________________________________________________
2207 Bool_t AliReconstruction::RunSPDTrackleting(AliESDEvent*& esd)
2208 {
2209 // run the SPD trackleting (for SPD efficiency purpouses)
2210
2211   AliCodeTimerAuto("",0)
2212
2213   Double_t vtxPos[3] = {0, 0, 0};
2214   Double_t vtxErr[3] = {0.0, 0.0, 0.0};
2215 /*
2216   TArrayF mcVertex(3);
2217   // if(MC)
2218   if (fRunLoader->GetHeader() && fRunLoader->GetHeader()->GenEventHeader()) {
2219     fRunLoader->GetHeader()->GenEventHeader()->PrimaryVertex(mcVertex);
2220     for (Int_t i = 0; i < 3; i++) vtxPos[i] = mcVertex[i];
2221   }
2222 */
2223   const AliESDVertex *vertex = esd->GetVertex();
2224   if(!vertex){
2225     AliWarning("Vertex not found");
2226     return kFALSE;
2227   }
2228   vertex->GetXYZ(vtxPos);
2229   vertex->GetSigmaXYZ(vtxErr);
2230   if (fSPDTrackleter) {
2231     AliInfo("running the SPD Trackleter for Plane Efficiency Evaluation");
2232
2233     // load clusters
2234     fLoader[0]->LoadRecPoints("read");
2235     TTree* tree = fLoader[0]->TreeR();
2236     if (!tree) {
2237       AliError("Can't get the ITS cluster tree");
2238       return kFALSE;
2239     }
2240     fSPDTrackleter->LoadClusters(tree);
2241     fSPDTrackleter->SetVertex(vtxPos, vtxErr);
2242     // run trackleting
2243     if (fSPDTrackleter->Clusters2Tracks(esd) != 0) {
2244       AliError("AliITSTrackleterSPDEff Clusters2Tracks failed");
2245      // fLoader[0]->UnloadRecPoints();
2246       return kFALSE;
2247     }
2248 //fSPDTrackleter->UnloadRecPoints();
2249   } else {
2250     AliWarning("SPDTrackleter not available");
2251     return kFALSE;
2252   }
2253   return kTRUE;
2254 }
2255
2256 //_____________________________________________________________________________
2257 Bool_t AliReconstruction::RunVertexFinder(AliESDEvent*& esd)
2258 {
2259 // run the barrel tracking
2260
2261   AliCodeTimerAuto("",0)
2262
2263   AliVertexer *vertexer = CreateVertexer();
2264   if (!vertexer) return kFALSE;
2265
2266   AliInfo("running the ITS vertex finder");
2267   AliESDVertex* vertex = NULL;
2268   if (fLoader[0]) {
2269     fLoader[0]->LoadRecPoints();
2270     TTree* cltree = fLoader[0]->TreeR();
2271     if (cltree) {
2272       if(fDiamondProfileSPD) vertexer->SetVtxStart(fDiamondProfileSPD);
2273       vertex = vertexer->FindVertexForCurrentEvent(cltree);
2274     }
2275     else {
2276       AliError("Can't get the ITS cluster tree");
2277     }
2278     fLoader[0]->UnloadRecPoints();
2279   }
2280   else {
2281     AliError("Can't get the ITS loader");
2282   }
2283   if(!vertex){
2284     AliWarning("Vertex not found");
2285     vertex = new AliESDVertex();
2286     vertex->SetName("default");
2287   }
2288   else {
2289     vertex->SetName("reconstructed");
2290   }
2291
2292   Double_t vtxPos[3];
2293   Double_t vtxErr[3];
2294   vertex->GetXYZ(vtxPos);
2295   vertex->GetSigmaXYZ(vtxErr);
2296
2297   esd->SetPrimaryVertexSPD(vertex);
2298   AliESDVertex *vpileup = NULL;
2299   Int_t novertices = 0;
2300   vpileup = vertexer->GetAllVertices(novertices);
2301   if(novertices>1){
2302     for (Int_t kk=1; kk<novertices; kk++)esd->AddPileupVertexSPD(&vpileup[kk]);
2303   }
2304   // if SPD multiplicity has been determined, it is stored in the ESD
2305   AliMultiplicity *mult = vertexer->GetMultiplicity();
2306   if(mult)esd->SetMultiplicity(mult);
2307
2308   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2309     if (fTracker[iDet]) fTracker[iDet]->SetVertex(vtxPos, vtxErr);
2310   }  
2311   delete vertex;
2312
2313   delete vertexer;
2314
2315   return kTRUE;
2316 }
2317
2318 //_____________________________________________________________________________
2319 Bool_t AliReconstruction::RunHLTTracking(AliESDEvent*& esd)
2320 {
2321 // run the HLT barrel tracking
2322
2323   AliCodeTimerAuto("",0)
2324
2325   if (!fRunLoader) {
2326     AliError("Missing runLoader!");
2327     return kFALSE;
2328   }
2329
2330   AliInfo("running HLT tracking");
2331
2332   // Get a pointer to the HLT reconstructor
2333   AliReconstructor *reconstructor = GetReconstructor(kNDetectors-1);
2334   if (!reconstructor) return kFALSE;
2335
2336   // TPC + ITS
2337   for (Int_t iDet = 1; iDet >= 0; iDet--) {
2338     TString detName = fgkDetectorName[iDet];
2339     AliDebug(1, Form("%s HLT tracking", detName.Data()));
2340     reconstructor->SetOption(detName.Data());
2341     AliTracker *tracker = reconstructor->CreateTracker();
2342     if (!tracker) {
2343       AliWarning(Form("couldn't create a HLT tracker for %s", detName.Data()));
2344       if (fStopOnError) return kFALSE;
2345       continue;
2346     }
2347     Double_t vtxPos[3];
2348     Double_t vtxErr[3]={0.005,0.005,0.010};
2349     const AliESDVertex *vertex = esd->GetVertex();
2350     vertex->GetXYZ(vtxPos);
2351     tracker->SetVertex(vtxPos,vtxErr);
2352     if(iDet != 1) {
2353       fLoader[iDet]->LoadRecPoints("read");
2354       TTree* tree = fLoader[iDet]->TreeR();
2355       if (!tree) {
2356         AliError(Form("Can't get the %s cluster tree", detName.Data()));
2357         return kFALSE;
2358       }
2359       tracker->LoadClusters(tree);
2360     }
2361     if (tracker->Clusters2Tracks(esd) != 0) {
2362       AliError(Form("HLT %s Clusters2Tracks failed", fgkDetectorName[iDet]));
2363       return kFALSE;
2364     }
2365     if(iDet != 1) {
2366       tracker->UnloadClusters();
2367     }
2368     delete tracker;
2369   }
2370
2371   return kTRUE;
2372 }
2373
2374 //_____________________________________________________________________________
2375 Bool_t AliReconstruction::RunMuonTracking(AliESDEvent*& esd)
2376 {
2377 // run the muon spectrometer tracking
2378
2379   AliCodeTimerAuto("",0)
2380
2381   if (!fRunLoader) {
2382     AliError("Missing runLoader!");
2383     return kFALSE;
2384   }
2385   Int_t iDet = 7; // for MUON
2386
2387   AliInfo("is running...");
2388
2389   // Get a pointer to the MUON reconstructor
2390   AliReconstructor *reconstructor = GetReconstructor(iDet);
2391   if (!reconstructor) return kFALSE;
2392
2393   
2394   TString detName = fgkDetectorName[iDet];
2395   AliDebug(1, Form("%s tracking", detName.Data()));
2396   AliTracker *tracker =  reconstructor->CreateTracker();
2397   if (!tracker) {
2398     AliWarning(Form("couldn't create a tracker for %s", detName.Data()));
2399     return kFALSE;
2400   }
2401      
2402   // read RecPoints
2403   fLoader[iDet]->LoadRecPoints("read");  
2404
2405   tracker->LoadClusters(fLoader[iDet]->TreeR());
2406   
2407   Int_t rv = tracker->Clusters2Tracks(esd);
2408   
2409   fLoader[iDet]->UnloadRecPoints();
2410
2411   tracker->UnloadClusters();
2412   
2413   delete tracker;
2414   
2415   if ( rv )
2416   {
2417     AliError(Form("%s Clusters2Tracks failed", fgkDetectorName[iDet]));
2418     return kFALSE;
2419   }
2420   
2421   return kTRUE;
2422 }
2423
2424
2425 //_____________________________________________________________________________
2426 Bool_t AliReconstruction::RunTracking(AliESDEvent*& esd,AliESDpid &PID)
2427 {
2428 // run the barrel tracking
2429   static Int_t eventNr=0;
2430   AliCodeTimerAuto("",0)
2431
2432   AliInfo("running tracking");
2433
2434   // Set the event info which is used
2435   // by the trackers in order to obtain
2436   // information about read-out detectors,
2437   // trigger etc.
2438   AliDebug(1, "Setting event info");
2439   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2440     if (!fTracker[iDet]) continue;
2441     fTracker[iDet]->SetEventInfo(&fEventInfo);
2442   }
2443
2444   //Fill the ESD with the T0 info (will be used by the TOF) 
2445   if (fReconstructor[11] && fLoader[11]) {
2446     fLoader[11]->LoadRecPoints("READ");
2447     TTree *treeR = fLoader[11]->TreeR();
2448     if (treeR) {
2449       GetReconstructor(11)->FillESD((TTree *)NULL,treeR,esd);
2450     }
2451   }
2452
2453   // pass 1: TPC + ITS inwards
2454   for (Int_t iDet = 1; iDet >= 0; iDet--) {
2455     if (!fTracker[iDet]) continue;
2456     AliDebug(1, Form("%s tracking", fgkDetectorName[iDet]));
2457
2458     // load clusters
2459     fLoader[iDet]->LoadRecPoints("read");
2460     AliSysInfo::AddStamp(Form("RLoadCluster%s_%d",fgkDetectorName[iDet],eventNr),iDet,1, eventNr);
2461     TTree* tree = fLoader[iDet]->TreeR();
2462     if (!tree) {
2463       AliError(Form("Can't get the %s cluster tree", fgkDetectorName[iDet]));
2464       return kFALSE;
2465     }
2466     fTracker[iDet]->LoadClusters(tree);
2467     AliSysInfo::AddStamp(Form("TLoadCluster%s_%d",fgkDetectorName[iDet],eventNr), iDet,2, eventNr);
2468     // run tracking
2469     if (fTracker[iDet]->Clusters2Tracks(esd) != 0) {
2470       AliError(Form("%s Clusters2Tracks failed", fgkDetectorName[iDet]));
2471       return kFALSE;
2472     }
2473     // preliminary PID in TPC needed by the ITS tracker
2474     if (iDet == 1) {
2475       GetReconstructor(1)->FillESD((TTree*)NULL, (TTree*)NULL, esd);
2476       PID.MakePID(esd,kTRUE);
2477     } 
2478     AliSysInfo::AddStamp(Form("Tracking0%s_%d",fgkDetectorName[iDet],eventNr), iDet,3,eventNr);
2479   }
2480
2481   // pass 2: ALL backwards
2482
2483   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2484     if (!fTracker[iDet]) continue;
2485     AliDebug(1, Form("%s back propagation", fgkDetectorName[iDet]));
2486
2487     // load clusters
2488     if (iDet > 1) {     // all except ITS, TPC
2489       TTree* tree = NULL;
2490       fLoader[iDet]->LoadRecPoints("read");
2491       AliSysInfo::AddStamp(Form("RLoadCluster0%s_%d",fgkDetectorName[iDet],eventNr), iDet,1, eventNr);
2492       tree = fLoader[iDet]->TreeR();
2493       if (!tree) {
2494         AliError(Form("Can't get the %s cluster tree", fgkDetectorName[iDet]));
2495         return kFALSE;
2496       }
2497       fTracker[iDet]->LoadClusters(tree); 
2498       AliSysInfo::AddStamp(Form("TLoadCluster0%s_%d",fgkDetectorName[iDet],eventNr), iDet,2, eventNr);
2499     }
2500
2501     // run tracking
2502     if (iDet>1) // start filling residuals for the "outer" detectors
2503       if (fRunGlobalQA) {
2504         AliTracker::SetFillResiduals(fRecoParam.GetEventSpecie(), kTRUE);     
2505         TObjArray ** arr = AliTracker::GetResidualsArray() ; 
2506         if (arr) {
2507           AliRecoParam::EventSpecie_t es=fRecoParam.GetEventSpecie();
2508           TObjArray * elem = arr[AliRecoParam::AConvert(es)];
2509           if ( elem && (! elem->At(0)) ) {
2510             AliQADataMaker *qadm = AliQAManager::QAManager()->GetQADataMaker(AliQAv1::kGLOBAL);
2511             if (qadm) qadm->InitRecPointsForTracker() ; 
2512           }
2513         }
2514       }
2515     if (fTracker[iDet]->PropagateBack(esd) != 0) {
2516       AliError(Form("%s backward propagation failed", fgkDetectorName[iDet]));
2517       //      return kFALSE;
2518     }
2519
2520     // unload clusters
2521     if (iDet > 3) {     // all except ITS, TPC, TRD and TOF
2522       fTracker[iDet]->UnloadClusters();
2523       fLoader[iDet]->UnloadRecPoints();
2524     }
2525     // updated PID in TPC needed by the ITS tracker -MI
2526     if (iDet == 1) {
2527       //GetReconstructor(1)->FillESD((TTree*)NULL, (TTree*)NULL, esd);
2528       //AliESDpid::MakePID(esd);
2529       PID.MakePID(esd,kTRUE);
2530     }
2531     AliSysInfo::AddStamp(Form("Tracking1%s_%d",fgkDetectorName[iDet],eventNr), iDet,3, eventNr);
2532   }
2533   //stop filling residuals for the "outer" detectors
2534   if (fRunGlobalQA) AliTracker::SetFillResiduals(fRecoParam.GetEventSpecie(), kFALSE);     
2535
2536   // pass 3: TRD + TPC + ITS refit inwards
2537
2538   for (Int_t iDet = 2; iDet >= 0; iDet--) {
2539     if (!fTracker[iDet]) continue;
2540     AliDebug(1, Form("%s inward refit", fgkDetectorName[iDet]));
2541
2542     // run tracking
2543     if (iDet<2) // start filling residuals for TPC and ITS
2544       if (fRunGlobalQA) {
2545         AliTracker::SetFillResiduals(fRecoParam.GetEventSpecie(), kTRUE);     
2546         TObjArray ** arr = AliTracker::GetResidualsArray() ; 
2547         if (arr) {
2548           AliRecoParam::EventSpecie_t es=fRecoParam.GetEventSpecie();
2549           TObjArray * elem = arr[AliRecoParam::AConvert(es)];
2550           if ( elem && (! elem->At(0)) ) {
2551             AliQADataMaker *qadm = AliQAManager::QAManager()->GetQADataMaker(AliQAv1::kGLOBAL);
2552             if (qadm) qadm->InitRecPointsForTracker() ; 
2553           }
2554         }
2555       }
2556     
2557     if (fTracker[iDet]->RefitInward(esd) != 0) {
2558       AliError(Form("%s inward refit failed", fgkDetectorName[iDet]));
2559       //      return kFALSE;
2560     }
2561     // run postprocessing
2562     if (fTracker[iDet]->PostProcess(esd) != 0) {
2563       AliError(Form("%s postprocessing failed", fgkDetectorName[iDet]));
2564       //      return kFALSE;
2565     }
2566     AliSysInfo::AddStamp(Form("Tracking2%s_%d",fgkDetectorName[iDet],eventNr), iDet,3, eventNr);
2567   }
2568
2569   // write space-points to the ESD in case alignment data output
2570   // is switched on
2571   if (fWriteAlignmentData)
2572     WriteAlignmentData(esd);
2573
2574   for (Int_t iDet = 3; iDet >= 0; iDet--) {
2575     if (!fTracker[iDet]) continue;
2576     // unload clusters
2577     fTracker[iDet]->UnloadClusters();
2578     AliSysInfo::AddStamp(Form("TUnloadCluster%s_%d",fgkDetectorName[iDet],eventNr), iDet,4, eventNr);
2579     fLoader[iDet]->UnloadRecPoints();
2580     AliSysInfo::AddStamp(Form("RUnloadCluster%s_%d",fgkDetectorName[iDet],eventNr), iDet,5, eventNr);
2581   }
2582   // stop filling residuals for TPC and ITS
2583   if (fRunGlobalQA) AliTracker::SetFillResiduals(fRecoParam.GetEventSpecie(), kFALSE);     
2584
2585   eventNr++;
2586   return kTRUE;
2587 }
2588
2589 //_____________________________________________________________________________
2590 Bool_t AliReconstruction::CleanESD(AliESDEvent *esd){
2591   //
2592   // Remove the data which are not needed for the physics analysis.
2593   //
2594
2595   Int_t nTracks=esd->GetNumberOfTracks();
2596   Int_t nV0s=esd->GetNumberOfV0s();
2597   AliInfo
2598   (Form("Number of ESD tracks and V0s before cleaning: %d %d",nTracks,nV0s));
2599
2600   Float_t cleanPars[]={fV0DCAmax,fV0CsPmin,fDmax,fZmax};
2601   Bool_t rc=esd->Clean(cleanPars);
2602
2603   nTracks=esd->GetNumberOfTracks();
2604   nV0s=esd->GetNumberOfV0s();
2605   AliInfo
2606   (Form("Number of ESD tracks and V0s after cleaning %d %d",nTracks,nV0s));
2607
2608   return rc;
2609 }
2610
2611 //_____________________________________________________________________________
2612 Bool_t AliReconstruction::FillESD(AliESDEvent*& esd, const TString& detectors)
2613 {
2614 // fill the event summary data
2615
2616   AliCodeTimerAuto("",0)
2617     static Int_t eventNr=0; 
2618   TString detStr = detectors;
2619   
2620   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2621   if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
2622     AliReconstructor* reconstructor = GetReconstructor(iDet);
2623     if (!reconstructor) continue;
2624     AliDebug(1, Form("filling ESD for %s", fgkDetectorName[iDet]));
2625     TTree* clustersTree = NULL;
2626     if (fLoader[iDet]) {
2627       fLoader[iDet]->LoadRecPoints("read");
2628       clustersTree = fLoader[iDet]->TreeR();
2629       if (!clustersTree) {
2630         AliError(Form("Can't get the %s clusters tree", 
2631                       fgkDetectorName[iDet]));
2632         if (fStopOnError) return kFALSE;
2633       }
2634     }
2635     if (fRawReader && !reconstructor->HasDigitConversion()) {
2636       reconstructor->FillESD(fRawReader, clustersTree, esd);
2637     } else {
2638       TTree* digitsTree = NULL;
2639       if (fLoader[iDet]) {
2640         fLoader[iDet]->LoadDigits("read");
2641         digitsTree = fLoader[iDet]->TreeD();
2642         if (!digitsTree) {
2643           AliError(Form("Can't get the %s digits tree", 
2644                         fgkDetectorName[iDet]));
2645           if (fStopOnError) return kFALSE;
2646         }
2647       }
2648       reconstructor->FillESD(digitsTree, clustersTree, esd);
2649       if (fLoader[iDet]) fLoader[iDet]->UnloadDigits();
2650     }
2651     if (fLoader[iDet]) {
2652       fLoader[iDet]->UnloadRecPoints();
2653     }
2654   }
2655   
2656   IsSelected("CTP", detStr);
2657   if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
2658     AliError(Form("the following detectors were not found: %s", 
2659                   detStr.Data()));
2660     if (fStopOnError) return kFALSE;
2661   }
2662   AliSysInfo::AddStamp(Form("FillESD%d",eventNr), 0,1, eventNr);
2663   eventNr++;
2664   return kTRUE;
2665 }
2666
2667 //_____________________________________________________________________________
2668 Bool_t AliReconstruction::FillTriggerESD(AliESDEvent*& esd)
2669 {
2670   // Reads the trigger decision which is
2671   // stored in Trigger.root file and fills
2672   // the corresponding esd entries
2673
2674   AliCodeTimerAuto("",0)
2675   
2676   AliInfo("Filling trigger information into the ESD");
2677
2678   if (fRawReader) {
2679     AliCTPRawStream input(fRawReader);
2680     if (!input.Next()) {
2681       AliWarning("No valid CTP (trigger) DDL raw data is found ! The trigger info is taken from the event header!");
2682     }
2683     else {
2684       if (esd->GetTriggerMask() != input.GetClassMask())
2685         AliError(Form("Invalid trigger pattern found in CTP raw-data: %llx %llx",
2686                       input.GetClassMask(),esd->GetTriggerMask()));
2687       if (esd->GetOrbitNumber() != input.GetOrbitID())
2688         AliError(Form("Invalid orbit id found in CTP raw-data: %x %x",
2689                       input.GetOrbitID(),esd->GetOrbitNumber()));
2690       if (esd->GetBunchCrossNumber() != input.GetBCID())
2691         AliError(Form("Invalid bunch-crossing id found in CTP raw-data: %x %x",
2692                       input.GetBCID(),esd->GetBunchCrossNumber()));
2693       AliESDHeader* esdheader = esd->GetHeader();
2694       esdheader->SetL0TriggerInputs(input.GetL0Inputs());
2695       esdheader->SetL1TriggerInputs(input.GetL1Inputs());
2696       esdheader->SetL2TriggerInputs(input.GetL2Inputs());
2697       // IR
2698       UInt_t orbit=input.GetOrbitID();
2699        for(Int_t i=0 ; i<input.GetNIRs() ; i++ )
2700           if(TMath::Abs(Int_t(orbit-(input.GetIR(i))->GetOrbit()))<=1){
2701              esdheader->AddTriggerIR(input.GetIR(i));
2702           }
2703     }
2704   }
2705   return kTRUE;
2706 }
2707 //_____________________________________________________________________________
2708 Bool_t AliReconstruction::FillTriggerScalers(AliESDEvent*& esd)
2709 {
2710   //Scalers
2711   //fRunScalers->Print();
2712   if(fRunScalers && fRunScalers->CheckRunScalers()){
2713      AliTimeStamp* timestamp = new AliTimeStamp(esd->GetOrbitNumber(), esd->GetPeriodNumber(), esd->GetBunchCrossNumber());
2714      //AliTimeStamp* timestamp = new AliTimeStamp(10308000, 0, (ULong64_t)486238);
2715      AliESDHeader* esdheader = fesd->GetHeader();
2716      for(Int_t i=0;i<50;i++){
2717           if((1ull<<i) & esd->GetTriggerMask()){
2718           AliTriggerScalersESD* scalesd = fRunScalers->GetScalersForEventClass( timestamp, i+1);
2719           if(scalesd)esdheader->SetTriggerScalersRecord(scalesd);
2720         }
2721      }
2722   }
2723   return kTRUE;
2724 }
2725 //_____________________________________________________________________________
2726 Bool_t AliReconstruction::FillRawEventHeaderESD(AliESDEvent*& esd)
2727 {
2728   // 
2729   // Filling information from RawReader Header
2730   // 
2731
2732   if (!fRawReader) return kFALSE;
2733
2734   AliInfo("Filling information from RawReader Header");
2735
2736   esd->SetBunchCrossNumber(fRawReader->GetBCID());
2737   esd->SetOrbitNumber(fRawReader->GetOrbitID());
2738   esd->SetPeriodNumber(fRawReader->GetPeriod());
2739
2740   esd->SetTimeStamp(fRawReader->GetTimestamp());  
2741   esd->SetEventType(fRawReader->GetType());
2742
2743   return kTRUE;
2744 }
2745
2746
2747 //_____________________________________________________________________________
2748 Bool_t AliReconstruction::IsSelected(TString detName, TString& detectors) const
2749 {
2750 // check whether detName is contained in detectors
2751 // if yes, it is removed from detectors
2752
2753   // check if all detectors are selected
2754   if ((detectors.CompareTo("ALL") == 0) ||
2755       detectors.BeginsWith("ALL ") ||
2756       detectors.EndsWith(" ALL") ||
2757       detectors.Contains(" ALL ")) {
2758     detectors = "ALL";
2759     return kTRUE;
2760   }
2761
2762   // search for the given detector
2763   Bool_t result = kFALSE;
2764   if ((detectors.CompareTo(detName) == 0) ||
2765       detectors.BeginsWith(detName+" ") ||
2766       detectors.EndsWith(" "+detName) ||
2767       detectors.Contains(" "+detName+" ")) {
2768     detectors.ReplaceAll(detName, "");
2769     result = kTRUE;
2770   }
2771
2772   // clean up the detectors string
2773   while (detectors.Contains("  ")) detectors.ReplaceAll("  ", " ");
2774   while (detectors.BeginsWith(" ")) detectors.Remove(0, 1);
2775   while (detectors.EndsWith(" ")) detectors.Remove(detectors.Length()-1, 1);
2776
2777   return result;
2778 }
2779
2780 //_____________________________________________________________________________
2781 Bool_t AliReconstruction::InitRunLoader()
2782 {
2783 // get or create the run loader
2784
2785   if (gAlice) delete gAlice;
2786   gAlice = NULL;
2787
2788   TFile *gafile = TFile::Open(fGAliceFileName.Data());
2789   //  if (!gSystem->AccessPathName(fGAliceFileName.Data())) { // galice.root exists
2790   if (gafile) { // galice.root exists
2791     gafile->Close();
2792     delete gafile;
2793
2794     // load all base libraries to get the loader classes
2795     TString libs = gSystem->GetLibraries();
2796     for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2797       TString detName = fgkDetectorName[iDet];
2798       if (detName == "HLT") continue;
2799       if (libs.Contains("lib" + detName + "base.so")) continue;
2800       gSystem->Load("lib" + detName + "base.so");
2801     }
2802     fRunLoader = AliRunLoader::Open(fGAliceFileName.Data());
2803     if (!fRunLoader) {
2804       AliError(Form("no run loader found in file %s", fGAliceFileName.Data()));
2805       CleanUp();
2806       return kFALSE;
2807     }
2808
2809     fRunLoader->CdGAFile();
2810     fRunLoader->LoadgAlice();
2811
2812     //PH This is a temporary fix to give access to the kinematics
2813     //PH that is needed for the labels of ITS clusters
2814     fRunLoader->LoadHeader();
2815     fRunLoader->LoadKinematics();
2816
2817   } else {               // galice.root does not exist
2818     if (!fRawReader) {
2819       AliError(Form("the file %s does not exist", fGAliceFileName.Data()));
2820     }
2821     fRunLoader = AliRunLoader::Open(fGAliceFileName.Data(),
2822                                     AliConfig::GetDefaultEventFolderName(),
2823                                     "recreate");
2824     if (!fRunLoader) {
2825       AliError(Form("could not create run loader in file %s", 
2826                     fGAliceFileName.Data()));
2827       CleanUp();
2828       return kFALSE;
2829     }
2830     fIsNewRunLoader = kTRUE;
2831     fRunLoader->MakeTree("E");
2832
2833     if (fNumberOfEventsPerFile > 0)
2834       fRunLoader->SetNumberOfEventsPerFile(fNumberOfEventsPerFile);
2835     else
2836       fRunLoader->SetNumberOfEventsPerFile((UInt_t)-1);
2837   }
2838
2839   return kTRUE;
2840 }
2841
2842 //_____________________________________________________________________________
2843 AliReconstructor* AliReconstruction::GetReconstructor(Int_t iDet)
2844 {
2845 // get the reconstructor object and the loader for a detector
2846
2847   if (fReconstructor[iDet]) {
2848     if (fRecoParam.GetDetRecoParamArray(iDet) && !AliReconstructor::GetRecoParam(iDet)) {
2849       const AliDetectorRecoParam *par = fRecoParam.GetDetRecoParam(iDet);
2850       fReconstructor[iDet]->SetRecoParam(par);
2851       fReconstructor[iDet]->SetRunInfo(fRunInfo);
2852     }
2853     return fReconstructor[iDet];
2854   }
2855
2856   // load the reconstructor object
2857   TPluginManager* pluginManager = gROOT->GetPluginManager();
2858   TString detName = fgkDetectorName[iDet];
2859   TString recName = "Ali" + detName + "Reconstructor";
2860
2861   if (!fIsNewRunLoader && !fRunLoader->GetLoader(detName+"Loader") && (detName != "HLT")) return NULL;
2862
2863   AliReconstructor* reconstructor = NULL;
2864   // first check if a plugin is defined for the reconstructor
2865   TPluginHandler* pluginHandler = 
2866     pluginManager->FindHandler("AliReconstructor", detName);
2867   // if not, add a plugin for it
2868   if (!pluginHandler) {
2869     AliDebug(1, Form("defining plugin for %s", recName.Data()));
2870     TString libs = gSystem->GetLibraries();
2871     if (libs.Contains("lib" + detName + "base.so") ||
2872         (gSystem->Load("lib" + detName + "base.so") >= 0)) {
2873       pluginManager->AddHandler("AliReconstructor", detName, 
2874                                 recName, detName + "rec", recName + "()");
2875     } else {
2876       pluginManager->AddHandler("AliReconstructor", detName, 
2877                                 recName, detName, recName + "()");
2878     }
2879     pluginHandler = pluginManager->FindHandler("AliReconstructor", detName);
2880   }
2881   if (pluginHandler && (pluginHandler->LoadPlugin() == 0)) {
2882     reconstructor = (AliReconstructor*) pluginHandler->ExecPlugin(0);
2883   }
2884   if (reconstructor) {
2885     TObject* obj = fOptions.FindObject(detName.Data());
2886     if (obj) reconstructor->SetOption(obj->GetTitle());
2887     reconstructor->SetRunInfo(fRunInfo);
2888     reconstructor->Init();
2889     fReconstructor[iDet] = reconstructor;
2890   }
2891
2892   // get or create the loader
2893   if (detName != "HLT") {
2894     fLoader[iDet] = fRunLoader->GetLoader(detName + "Loader");
2895     if (!fLoader[iDet]) {
2896       AliConfig::Instance()
2897         ->CreateDetectorFolders(fRunLoader->GetEventFolder(), 
2898                                 detName, detName);
2899       // first check if a plugin is defined for the loader
2900       pluginHandler = 
2901         pluginManager->FindHandler("AliLoader", detName);
2902       // if not, add a plugin for it
2903       if (!pluginHandler) {
2904         TString loaderName = "Ali" + detName + "Loader";
2905         AliDebug(1, Form("defining plugin for %s", loaderName.Data()));
2906         pluginManager->AddHandler("AliLoader", detName, 
2907                                   loaderName, detName + "base", 
2908                                   loaderName + "(const char*, TFolder*)");
2909         pluginHandler = pluginManager->FindHandler("AliLoader", detName);
2910       }
2911       if (pluginHandler && (pluginHandler->LoadPlugin() == 0)) {
2912         fLoader[iDet] = 
2913           (AliLoader*) pluginHandler->ExecPlugin(2, detName.Data(), 
2914                                                  fRunLoader->GetEventFolder());
2915       }
2916       if (!fLoader[iDet]) {   // use default loader
2917         fLoader[iDet] = new AliLoader(detName, fRunLoader->GetEventFolder());
2918       }
2919       if (!fLoader[iDet]) {
2920         AliWarning(Form("couldn't get loader for %s", detName.Data()));
2921         if (fStopOnError) return NULL;
2922       } else {
2923         fRunLoader->AddLoader(fLoader[iDet]);
2924         fRunLoader->CdGAFile();
2925         if (gFile && !gFile->IsWritable()) gFile->ReOpen("UPDATE");
2926         fRunLoader->Write(0, TObject::kOverwrite);
2927       }
2928     }
2929   }
2930       
2931   if (fRecoParam.GetDetRecoParamArray(iDet) && !AliReconstructor::GetRecoParam(iDet)) {
2932     const AliDetectorRecoParam *par = fRecoParam.GetDetRecoParam(iDet);
2933     reconstructor->SetRecoParam(par);
2934     reconstructor->SetRunInfo(fRunInfo);
2935   }
2936   return reconstructor;
2937 }
2938
2939 //_____________________________________________________________________________
2940 AliVertexer* AliReconstruction::CreateVertexer()
2941 {
2942 // create the vertexer
2943 // Please note that the caller is the owner of the
2944 // vertexer
2945
2946   AliVertexer* vertexer = NULL;
2947   AliReconstructor* itsReconstructor = GetReconstructor(0);
2948   if (itsReconstructor && ((fRunLocalReconstruction.Contains("ITS")) || fRunTracking.Contains("ITS"))) {
2949     vertexer = itsReconstructor->CreateVertexer();
2950   }
2951   if (!vertexer) {
2952     AliWarning("couldn't create a vertexer for ITS");
2953   }
2954
2955   return vertexer;
2956 }
2957
2958 //_____________________________________________________________________________
2959 Bool_t AliReconstruction::CreateTrackers(const TString& detectors)
2960 {
2961 // create the trackers
2962         AliInfo("Creating trackers");
2963
2964   TString detStr = detectors;
2965   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2966     if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
2967     AliReconstructor* reconstructor = GetReconstructor(iDet);
2968     if (!reconstructor) continue;
2969     TString detName = fgkDetectorName[iDet];
2970     if (detName == "HLT") {
2971       fRunHLTTracking = kTRUE;
2972       continue;
2973     }
2974     if (detName == "MUON") {
2975       fRunMuonTracking = kTRUE;
2976       continue;
2977     }
2978
2979
2980     fTracker[iDet] = reconstructor->CreateTracker();
2981     if (!fTracker[iDet] && (iDet < 7)) {
2982       AliWarning(Form("couldn't create a tracker for %s", detName.Data()));
2983       if (fStopOnError) return kFALSE;
2984     }
2985     AliSysInfo::AddStamp(Form("LTracker%s",fgkDetectorName[iDet]), iDet,0);
2986   }
2987
2988   return kTRUE;
2989 }
2990
2991 //_____________________________________________________________________________
2992 void AliReconstruction::CleanUp()
2993 {
2994 // delete trackers and the run loader and close and delete the file
2995
2996   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2997     delete fReconstructor[iDet];
2998     fReconstructor[iDet] = NULL;
2999     fLoader[iDet] = NULL;
3000     delete fTracker[iDet];
3001     fTracker[iDet] = NULL;
3002   }
3003   delete fRunInfo;
3004   fRunInfo = NULL;
3005
3006   delete fSPDTrackleter;
3007   fSPDTrackleter = NULL;
3008
3009   delete ftVertexer;
3010   ftVertexer = NULL;
3011   
3012   delete fRunLoader;
3013   fRunLoader = NULL;
3014   delete fRawReader;
3015   fRawReader = NULL;
3016   delete fParentRawReader;
3017   fParentRawReader=NULL;
3018
3019   if (ffile) {
3020     ffile->Close();
3021     delete ffile;
3022     ffile = NULL;
3023   }
3024
3025   if (AliQAManager::QAManager())
3026     AliQAManager::QAManager()->ShowQA() ; 
3027   AliQAManager::Destroy() ; 
3028   
3029 }
3030
3031 void AliReconstruction::WriteAlignmentData(AliESDEvent* esd)
3032 {
3033   // Write space-points which are then used in the alignment procedures
3034   // For the moment only ITS, TPC, TRD and TOF
3035
3036   Int_t ntracks = esd->GetNumberOfTracks();
3037   for (Int_t itrack = 0; itrack < ntracks; itrack++)
3038     {
3039       AliESDtrack *track = esd->GetTrack(itrack);
3040       Int_t nsp = 0;
3041       Int_t idx[200];
3042       for (Int_t i=0; i<200; ++i) idx[i] = -1; //PH avoid uninitialized values
3043       for (Int_t iDet = 5; iDet >= 0; iDet--) {// TOF, TRD, TPC, ITS clusters
3044           nsp += (iDet==GetDetIndex("TRD")) ? track->GetTRDntracklets():track->GetNcls(iDet);
3045
3046           if (iDet==GetDetIndex("ITS")) { // ITS "extra" clusters
3047              track->GetClusters(iDet,idx);
3048              for (Int_t i=6; i<12; i++) if(idx[i] >= 0) nsp++;
3049           }  
3050       }
3051
3052       if (nsp) {
3053         AliTrackPointArray *sp = new AliTrackPointArray(nsp);
3054         track->SetTrackPointArray(sp);
3055         Int_t isptrack = 0;
3056         for (Int_t iDet = 5; iDet >= 0; iDet--) {
3057           AliTracker *tracker = fTracker[iDet];
3058           if (!tracker) continue;
3059           Int_t nspdet = (iDet==GetDetIndex("TRD")) ? track->GetTRDtracklets(idx):track->GetClusters(iDet,idx);
3060
3061           if (iDet==GetDetIndex("ITS")) // ITS "extra" clusters             
3062              for (Int_t i=6; i<12; i++) if(idx[i] >= 0) nspdet++;
3063
3064           if (nspdet <= 0) continue;
3065           AliTrackPoint p;
3066           Int_t isp = 0;
3067           Int_t isp2 = 0;
3068           while (isp2 < nspdet) {
3069             Bool_t isvalid=kTRUE;
3070
3071             Int_t index=idx[isp++];
3072             if (index < 0) continue;
3073
3074             TString dets = fgkDetectorName[iDet];
3075             if ((fUseTrackingErrorsForAlignment.CompareTo(dets) == 0) ||
3076             fUseTrackingErrorsForAlignment.BeginsWith(dets+" ") ||
3077             fUseTrackingErrorsForAlignment.EndsWith(" "+dets) ||
3078             fUseTrackingErrorsForAlignment.Contains(" "+dets+" ")) {
3079               isvalid = tracker->GetTrackPointTrackingError(index,p,track);
3080             } else {
3081               isvalid = tracker->GetTrackPoint(index,p); 
3082             } 
3083             isp2++;
3084             if (!isvalid) continue;
3085             if (iDet==GetDetIndex("ITS") && (isp-1)>=6) p.SetExtra();
3086             sp->AddPoint(isptrack,&p); isptrack++;
3087           }
3088         }       
3089       }
3090     }
3091 }
3092
3093 //_____________________________________________________________________________
3094 void AliReconstruction::FillRawDataErrorLog(Int_t iEvent, AliESDEvent* esd)
3095 {
3096   // The method reads the raw-data error log
3097   // accumulated within the rawReader.
3098   // It extracts the raw-data errors related to
3099   // the current event and stores them into
3100   // a TClonesArray inside the esd object.
3101
3102   if (!fRawReader) return;
3103
3104   for(Int_t i = 0; i < fRawReader->GetNumberOfErrorLogs(); i++) {
3105
3106     AliRawDataErrorLog *log = fRawReader->GetErrorLog(i);
3107     if (!log) continue;
3108     if (iEvent != log->GetEventNumber()) continue;
3109
3110     esd->AddRawDataErrorLog(log);
3111   }
3112
3113 }
3114
3115 //_____________________________________________________________________________
3116 void AliReconstruction::CheckQA()
3117 {
3118 // check the QA of SIM for this run and remove the detectors 
3119 // with status Fatal
3120   
3121 //      TString newRunLocalReconstruction ; 
3122 //      TString newRunTracking ;
3123 //      TString newFillESD ;
3124 //       
3125 //      for (Int_t iDet = 0; iDet < AliQAv1::kNDET; iDet++) {
3126 //              TString detName(AliQAv1::GetDetName(iDet)) ;
3127 //              AliQAv1 * qa = AliQAv1::Instance(AliQAv1::DETECTORINDEX_t(iDet)) ;       
3128 //      if ( qa->IsSet(AliQAv1::DETECTORINDEX_t(iDet), AliQAv1::kSIM, specie, AliQAv1::kFATAL)) {
3129 //        AliInfo(Form("QA status for %s %s in Hits and/or SDIGITS  and/or Digits was Fatal; No reconstruction performed", 
3130 //                   detName.Data(), AliRecoParam::GetEventSpecieName(es))) ;
3131 //                      } else {
3132 //                      if ( fRunLocalReconstruction.Contains(AliQAv1::GetDetName(iDet)) || 
3133 //                                      fRunLocalReconstruction.Contains("ALL") )  {
3134 //                              newRunLocalReconstruction += detName ; 
3135 //                              newRunLocalReconstruction += " " ;                      
3136 //                      }
3137 //                      if ( fRunTracking.Contains(AliQAv1::GetDetName(iDet)) || 
3138 //                                      fRunTracking.Contains("ALL") )  {
3139 //                              newRunTracking += detName ; 
3140 //                              newRunTracking += " " ;                         
3141 //                      }
3142 //                      if ( fFillESD.Contains(AliQAv1::GetDetName(iDet)) || 
3143 //                                      fFillESD.Contains("ALL") )  {
3144 //                              newFillESD += detName ; 
3145 //                              newFillESD += " " ;                     
3146 //                      }
3147 //              }
3148 //      }
3149 //      fRunLocalReconstruction = newRunLocalReconstruction ; 
3150 //      fRunTracking            = newRunTracking ; 
3151 //      fFillESD                = newFillESD ; 
3152 }
3153
3154 //_____________________________________________________________________________
3155 Int_t AliReconstruction::GetDetIndex(const char* detector)
3156 {
3157   // return the detector index corresponding to detector
3158   Int_t index = -1 ; 
3159   for (index = 0; index < kNDetectors ; index++) {
3160     if ( strcmp(detector, fgkDetectorName[index]) == 0 )
3161         break ; 
3162   }     
3163   return index ; 
3164 }
3165 //_____________________________________________________________________________
3166 Bool_t AliReconstruction::FinishPlaneEff() {
3167  //
3168  // Here execute all the necessary operationis, at the end of the tracking phase,
3169  // in case that evaluation of PlaneEfficiencies was required for some detector.
3170  // E.g., write into a DataBase file the PlaneEfficiency which have been evaluated.
3171  //
3172  // This Preliminary version works only FOR ITS !!!!!
3173  // other detectors (TOF,TRD, etc. have to develop their specific codes)
3174  //
3175  //  Input: none
3176  //  Return: kTRUE if all operations have been done properly, kFALSE otherwise
3177  //
3178  Bool_t ret=kFALSE;
3179  TString detStr = fLoadCDB;
3180  //for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
3181  for (Int_t iDet = 0; iDet < 1; iDet++) { // for the time being only ITS
3182    if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
3183    if(fTracker[iDet] && fTracker[iDet]->GetPlaneEff()) {
3184       AliPlaneEff *planeeff=fTracker[iDet]->GetPlaneEff();
3185       TString name=planeeff->GetName();
3186       name+=".root";
3187       TFile* pefile = TFile::Open(name, "RECREATE");
3188       ret=(Bool_t)planeeff->Write();
3189       pefile->Close();
3190       if(planeeff->GetCreateHistos()) {
3191         TString hname=planeeff->GetName();
3192         hname+="Histo.root";
3193         ret*=planeeff->WriteHistosToFile(hname,"RECREATE");
3194       }
3195    }
3196    if(fSPDTrackleter) {
3197      AliPlaneEff *planeeff=fSPDTrackleter->GetPlaneEff();
3198       TString name="AliITSPlaneEffSPDtracklet.root";
3199       TFile* pefile = TFile::Open(name, "RECREATE");
3200       ret=(Bool_t)planeeff->Write();
3201       pefile->Close();
3202       AliESDEvent *dummy=NULL;
3203       ret=(Bool_t)fSPDTrackleter->PostProcess(dummy); // take care of writing other files
3204    }
3205  }
3206  return ret;
3207 }
3208 //_____________________________________________________________________________
3209 Bool_t AliReconstruction::InitPlaneEff() {
3210 //
3211  // Here execute all the necessary operations, before of the tracking phase,
3212  // for the evaluation of PlaneEfficiencies, in case required for some detectors.
3213  // E.g., read from a DataBase file a first evaluation of the PlaneEfficiency
3214  // which should be updated/recalculated.
3215  //
3216  // This Preliminary version will work only FOR ITS !!!!!
3217  // other detectors (TOF,TRD, etc. have to develop their specific codes)
3218  //
3219  //  Input: none
3220  //  Return: kTRUE if all operations have been done properly, kFALSE otherwise
3221  //
3222  AliWarning(Form("Implementation of this method not yet completed !! Method return kTRUE"));
3223
3224   fSPDTrackleter = NULL;
3225   TString detStr = fLoadCDB;
3226   if (IsSelected(fgkDetectorName[0], detStr)) {
3227     AliReconstructor* itsReconstructor = GetReconstructor(0);
3228     if (itsReconstructor) {
3229       fSPDTrackleter = itsReconstructor->CreateTrackleter(); // this is NULL unless required in RecoParam
3230     }
3231     if (fSPDTrackleter) {
3232       AliInfo("Trackleter for SPD has been created");
3233     }
3234   }
3235  return kTRUE;
3236 }
3237
3238 //_____________________________________________________________________________
3239 Bool_t AliReconstruction::InitAliEVE()
3240 {
3241   // This method should be called only in case 
3242   // AliReconstruction is run
3243   // within the alieve environment.
3244   // It will initialize AliEVE in a way
3245   // so that it can visualize event processed
3246   // by AliReconstruction.
3247   // The return flag shows whenever the
3248   // AliEVE initialization was successful or not.
3249
3250   TString macroStr;
3251   macroStr.Form("%s/EVE/macros/alieve_online.C",gSystem->ExpandPathName("$ALICE_ROOT"));
3252   AliInfo(Form("Loading AliEVE macro: %s",macroStr.Data()));
3253   if (gROOT->LoadMacro(macroStr.Data()) != 0) return kFALSE;
3254
3255   gROOT->ProcessLine("if (!AliEveEventManager::GetMaster()){new AliEveEventManager();AliEveEventManager::GetMaster()->AddNewEventCommand(\"alieve_online_on_new_event()\");gEve->AddEvent(AliEveEventManager::GetMaster());};");
3256   gROOT->ProcessLine("alieve_online_init()");
3257
3258   return kTRUE;
3259 }
3260   
3261 //_____________________________________________________________________________
3262 void AliReconstruction::RunAliEVE()
3263 {
3264   // Runs AliEVE visualisation of
3265   // the current event.
3266   // Should be executed only after
3267   // successful initialization of AliEVE.
3268
3269   AliInfo("Running AliEVE...");
3270   gROOT->ProcessLine(Form("AliEveEventManager::GetMaster()->SetEvent((AliRunLoader*)0x%lx,(AliRawReader*)0x%lx,(AliESDEvent*)0x%lx,(AliESDfriend*)0x%lx);",fRunLoader,fRawReader,fesd,fesdf));
3271   gSystem->Run();
3272 }
3273
3274 //_____________________________________________________________________________
3275 Bool_t AliReconstruction::SetRunQA(TString detAndAction) 
3276 {
3277         // Allows to run QA for a selected set of detectors
3278         // and a selected set of tasks among RAWS, DIGITSR, RECPOINTS and ESDS
3279         // all selected detectors run the same selected tasks
3280         
3281         if (!detAndAction.Contains(":")) {
3282                 AliError( Form("%s is a wrong syntax, use \"DetectorList:ActionList\" \n", detAndAction.Data()) ) ;
3283                 fRunQA = kFALSE ;
3284                 return kFALSE ;                 
3285         }
3286         Int_t colon = detAndAction.Index(":") ; 
3287         fQADetectors = detAndAction(0, colon) ; 
3288         fQATasks   = detAndAction(colon+1, detAndAction.Sizeof() ) ; 
3289         if (fQATasks.Contains("ALL") ) {
3290                 fQATasks = Form("%d %d %d %d", AliQAv1::kRAWS, AliQAv1::kDIGITSR, AliQAv1::kRECPOINTS, AliQAv1::kESDS) ; 
3291         } else {
3292                 fQATasks.ToUpper() ; 
3293                 TString tempo("") ; 
3294                 if ( fQATasks.Contains("RAW") ) 
3295                         tempo = Form("%d ", AliQAv1::kRAWS) ; 
3296                 if ( fQATasks.Contains("DIGIT") ) 
3297                         tempo += Form("%d ", AliQAv1::kDIGITSR) ; 
3298                 if ( fQATasks.Contains("RECPOINT") ) 
3299                         tempo += Form("%d ", AliQAv1::kRECPOINTS) ; 
3300                 if ( fQATasks.Contains("ESD") ) 
3301                         tempo += Form("%d ", AliQAv1::kESDS) ; 
3302                 fQATasks = tempo ; 
3303                 if (fQATasks.IsNull()) {
3304                         AliInfo("No QA requested\n")  ;
3305                         fRunQA = kFALSE ;
3306                         return kTRUE ; 
3307                 }
3308         }       
3309         TString tempo(fQATasks) ; 
3310         tempo.ReplaceAll(Form("%d", AliQAv1::kRAWS), AliQAv1::GetTaskName(AliQAv1::kRAWS))      ;
3311         tempo.ReplaceAll(Form("%d", AliQAv1::kDIGITSR), AliQAv1::GetTaskName(AliQAv1::kDIGITSR)) ;      
3312         tempo.ReplaceAll(Form("%d", AliQAv1::kRECPOINTS), AliQAv1::GetTaskName(AliQAv1::kRECPOINTS)) ;  
3313         tempo.ReplaceAll(Form("%d", AliQAv1::kESDS), AliQAv1::GetTaskName(AliQAv1::kESDS)) ;    
3314         AliInfo( Form("QA will be done on \"%s\" for \"%s\"\n", fQADetectors.Data(), tempo.Data()) ) ;  
3315         fRunQA = kTRUE ;
3316         return kTRUE; 
3317
3318
3319 //_____________________________________________________________________________
3320 Bool_t AliReconstruction::InitRecoParams() 
3321 {
3322   // The method accesses OCDB and retrieves all
3323   // the available reco-param objects from there.
3324
3325   Bool_t isOK = kTRUE;
3326
3327   if (fRecoParam.GetDetRecoParamArray(kNDetectors)) {
3328     AliInfo("Using custom GRP reconstruction parameters");
3329   }
3330   else {
3331     AliInfo("Loading GRP reconstruction parameter objects");
3332
3333     AliCDBPath path("GRP","Calib","RecoParam");
3334     AliCDBEntry *entry=AliCDBManager::Instance()->Get(path.GetPath());
3335     if(!entry){ 
3336       AliWarning("Couldn't find GRP RecoParam entry in OCDB");
3337       isOK = kFALSE;
3338     }
3339     else {
3340       TObject *recoParamObj = entry->GetObject();
3341       if (dynamic_cast<TObjArray*>(recoParamObj)) {
3342         // GRP has a normal TobjArray of AliDetectorRecoParam objects
3343         // Registering them in AliRecoParam
3344         fRecoParam.AddDetRecoParamArray(kNDetectors,dynamic_cast<TObjArray*>(recoParamObj));
3345       }
3346       else if (dynamic_cast<AliDetectorRecoParam*>(recoParamObj)) {
3347         // GRP has only onse set of reco parameters
3348         // Registering it in AliRecoParam
3349         AliInfo("Single set of GRP reconstruction parameters found");
3350         dynamic_cast<AliDetectorRecoParam*>(recoParamObj)->SetAsDefault();
3351         fRecoParam.AddDetRecoParam(kNDetectors,dynamic_cast<AliDetectorRecoParam*>(recoParamObj));
3352       }
3353       else {
3354         AliError("No valid GRP RecoParam object found in the OCDB");
3355         isOK = kFALSE;
3356       }
3357       entry->SetOwner(0);
3358     }
3359   }
3360
3361   TString detStr = fLoadCDB;
3362   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
3363
3364     if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
3365
3366     if (fRecoParam.GetDetRecoParamArray(iDet)) {
3367       AliInfo(Form("Using custom reconstruction parameters for detector %s",fgkDetectorName[iDet]));
3368       continue;
3369     }
3370
3371     AliInfo(Form("Loading reconstruction parameter objects for detector %s",fgkDetectorName[iDet]));
3372   
3373     AliCDBPath path(fgkDetectorName[iDet],"Calib","RecoParam");
3374     AliCDBEntry *entry=AliCDBManager::Instance()->Get(path.GetPath());
3375     if(!entry){ 
3376       AliWarning(Form("Couldn't find RecoParam entry in OCDB for detector %s",fgkDetectorName[iDet]));
3377       isOK = kFALSE;
3378     }
3379     else {
3380       TObject *recoParamObj = entry->GetObject();
3381       if (dynamic_cast<TObjArray*>(recoParamObj)) {
3382         // The detector has a normal TobjArray of AliDetectorRecoParam objects
3383         // Registering them in AliRecoParam
3384         fRecoParam.AddDetRecoParamArray(iDet,dynamic_cast<TObjArray*>(recoParamObj));
3385       }
3386       else if (dynamic_cast<AliDetectorRecoParam*>(recoParamObj)) {
3387         // The detector has only onse set of reco parameters
3388         // Registering it in AliRecoParam
3389         AliInfo(Form("Single set of reconstruction parameters found for detector %s",fgkDetectorName[iDet]));
3390         dynamic_cast<AliDetectorRecoParam*>(recoParamObj)->SetAsDefault();
3391         fRecoParam.AddDetRecoParam(iDet,dynamic_cast<AliDetectorRecoParam*>(recoParamObj));
3392       }
3393       else {
3394         AliError(Form("No valid RecoParam object found in the OCDB for detector %s",fgkDetectorName[iDet]));
3395         isOK = kFALSE;
3396       }
3397       entry->SetOwner(0);
3398       //      FIX ME: We have to disable the unloading of reco-param CDB
3399       //      entries because QA framework is using them. Has to be fix in
3400       //      a way that the QA takes the objects already constructed in
3401       //      this method.
3402       //      AliCDBManager::Instance()->UnloadFromCache(path.GetPath());
3403     }
3404   }
3405
3406   if (AliDebugLevel() > 0) fRecoParam.Print();
3407
3408   return isOK;
3409 }
3410
3411 //_____________________________________________________________________________
3412 Bool_t AliReconstruction::GetEventInfo() 
3413 {
3414   // Fill the event info object
3415   // ...
3416   AliCodeTimerAuto("",0)
3417
3418   AliCentralTrigger *aCTP = NULL;
3419   if (fRawReader) {
3420     fEventInfo.SetEventType(fRawReader->GetType());
3421
3422     ULong64_t mask = fRawReader->GetClassMask();
3423     fEventInfo.SetTriggerMask(mask);
3424     UInt_t clmask = fRawReader->GetDetectorPattern()[0];
3425     fEventInfo.SetTriggerCluster(AliDAQ::ListOfTriggeredDetectors(clmask));
3426
3427     aCTP = new AliCentralTrigger();
3428     TString configstr("");
3429     if (!aCTP->LoadConfiguration(configstr)) { // Load CTP config from OCDB
3430       AliError("No trigger configuration found in OCDB! The trigger configuration information will not be used!");
3431       delete aCTP;
3432       return kFALSE;
3433     }
3434     aCTP->SetClassMask(mask);
3435     aCTP->SetClusterMask(clmask);
3436   }
3437   else {
3438     fEventInfo.SetEventType(AliRawEventHeaderBase::kPhysicsEvent);
3439
3440     if (fRunLoader && (!fRunLoader->LoadTrigger())) {
3441       aCTP = fRunLoader->GetTrigger();
3442       fEventInfo.SetTriggerMask(aCTP->GetClassMask());
3443       // get inputs from actp - just get
3444       AliESDHeader* esdheader = fesd->GetHeader();
3445       esdheader->SetL0TriggerInputs(aCTP->GetL0TriggerInputs());
3446       esdheader->SetL1TriggerInputs(aCTP->GetL1TriggerInputs());
3447       esdheader->SetL2TriggerInputs(aCTP->GetL2TriggerInputs());
3448       fEventInfo.SetTriggerCluster(AliDAQ::ListOfTriggeredDetectors(aCTP->GetClusterMask()));
3449     }
3450     else {
3451       AliWarning("No trigger can be loaded! The trigger information will not be used!");
3452       return kFALSE;
3453     }
3454   }
3455
3456   AliTriggerConfiguration *config = aCTP->GetConfiguration();
3457   if (!config) {
3458     AliError("No trigger configuration has been found! The trigger configuration information will not be used!");
3459     if (fRawReader) delete aCTP;
3460     return kFALSE;
3461   }
3462
3463   UChar_t clustmask = 0;
3464   TString trclasses;
3465   ULong64_t trmask = fEventInfo.GetTriggerMask();
3466   const TObjArray& classesArray = config->GetClasses();
3467   Int_t nclasses = classesArray.GetEntriesFast();
3468   for( Int_t iclass=0; iclass < nclasses; iclass++ ) {
3469     AliTriggerClass* trclass = (AliTriggerClass*)classesArray.At(iclass);
3470     if (trclass) {
3471       Int_t trindex = TMath::Nint(TMath::Log2(trclass->GetMask()));
3472       fesd->SetTriggerClass(trclass->GetName(),trindex);
3473       if (fRawReader) fRawReader->LoadTriggerClass(trclass->GetName(),trindex);
3474       if (trmask & (1ull << trindex)) {
3475         trclasses += " ";
3476         trclasses += trclass->GetName();
3477         trclasses += " ";
3478         clustmask |= trclass->GetCluster()->GetClusterMask();
3479       }
3480     }
3481   }
3482   fEventInfo.SetTriggerClasses(trclasses);
3483
3484   // Set the information in ESD
3485   fesd->SetTriggerMask(trmask);
3486   fesd->SetTriggerCluster(clustmask);
3487
3488   if (!aCTP->CheckTriggeredDetectors()) {
3489     if (fRawReader) delete aCTP;
3490     return kFALSE;
3491   }    
3492
3493   if (fRawReader) delete aCTP;
3494
3495   // We have to fill also the HLT decision here!!
3496   // ...
3497
3498   return kTRUE;
3499 }
3500
3501 const char *AliReconstruction::MatchDetectorList(const char *detectorList, UInt_t detectorMask)
3502 {
3503   // Match the detector list found in the rec.C or the default 'ALL'
3504   // to the list found in the GRP (stored there by the shuttle PP which
3505   // gets the information from ECS)
3506   static TString resultList;
3507   TString detList = detectorList;
3508
3509   resultList = "";
3510
3511   for(Int_t iDet = 0; iDet < (AliDAQ::kNDetectors-1); iDet++) {
3512     if ((detectorMask >> iDet) & 0x1) {
3513       TString det = AliDAQ::OfflineModuleName(iDet);
3514       if ((detList.CompareTo("ALL") == 0) ||
3515           ((detList.BeginsWith("ALL ") ||
3516             detList.EndsWith(" ALL") ||
3517             detList.Contains(" ALL ")) &&
3518            !(detList.BeginsWith("-"+det+" ") ||
3519              detList.EndsWith(" -"+det) ||
3520              detList.Contains(" -"+det+" "))) ||
3521           (detList.CompareTo(det) == 0) ||
3522           detList.BeginsWith(det+" ") ||
3523           detList.EndsWith(" "+det) ||
3524           detList.Contains( " "+det+" " )) {
3525         if (!resultList.EndsWith(det + " ")) {
3526           resultList += det;
3527           resultList += " ";
3528         }
3529       }        
3530     }
3531   }
3532
3533   // HLT
3534   if ((detectorMask >> AliDAQ::kHLTId) & 0x1) {
3535     TString hltDet = AliDAQ::OfflineModuleName(AliDAQ::kNDetectors-1);
3536     if ((detList.CompareTo("ALL") == 0) ||
3537         ((detList.BeginsWith("ALL ") ||
3538           detList.EndsWith(" ALL") ||
3539           detList.Contains(" ALL ")) &&
3540          !(detList.BeginsWith("-"+hltDet+" ") ||
3541            detList.EndsWith(" -"+hltDet) ||
3542            detList.Contains(" -"+hltDet+" "))) ||
3543         (detList.CompareTo(hltDet) == 0) ||
3544         detList.BeginsWith(hltDet+" ") ||
3545         detList.EndsWith(" "+hltDet) ||
3546         detList.Contains( " "+hltDet+" " )) {
3547       resultList += hltDet;
3548     }
3549   }
3550
3551   return resultList.Data();
3552
3553 }
3554
3555 //______________________________________________________________________________
3556 void AliReconstruction::Abort(const char *method, EAbort what)
3557 {
3558   // Abort processing. If what = kAbortProcess, the Process() loop will be
3559   // aborted. If what = kAbortFile, the current file in a chain will be
3560   // aborted and the processing will continue with the next file, if there
3561   // is no next file then Process() will be aborted. Abort() can also  be
3562   // called from Begin(), SlaveBegin(), Init() and Notify(). After abort
3563   // the SlaveTerminate() and Terminate() are always called. The abort flag
3564   // can be checked in these methods using GetAbort().
3565   //
3566   // The method is overwritten in AliReconstruction for better handling of
3567   // reco specific errors 
3568
3569   if (!fStopOnError) return;
3570
3571   CleanUp();
3572
3573   TString whyMess = method;
3574   whyMess += " failed! Aborting...";
3575
3576   AliError(whyMess.Data());
3577
3578   fAbort = what;
3579   TString mess = "Abort";
3580   if (fAbort == kAbortProcess)
3581     mess = "AbortProcess";
3582   else if (fAbort == kAbortFile)
3583     mess = "AbortFile";
3584
3585   Info(mess, whyMess.Data());
3586 }
3587
3588 //______________________________________________________________________________
3589 Bool_t AliReconstruction::ProcessEvent(void* event)
3590 {
3591   // Method that is used in case the event loop
3592   // is steered from outside, for example by AMORE
3593   // 'event' is a pointer to the DATE event in the memory
3594
3595   if (fRawReader) delete fRawReader;
3596   fRawReader = new AliRawReaderDate(event);
3597   fStatus = ProcessEvent(fRunLoader->GetNumberOfEvents());  
3598   delete fRawReader;
3599   fRawReader = NULL;
3600
3601   return fStatus;
3602 }
3603
3604 //______________________________________________________________________________
3605 Bool_t AliReconstruction::ParseOutput()
3606 {
3607   // The method parses the output file
3608   // location string in order to steer
3609   // properly the selector
3610
3611   TPMERegexp re1("(\\w+\\.zip#\\w+\\.root):([,*\\w+\\.root,*]+)@dataset://(\\w++)");
3612   TPMERegexp re2("(\\w+\\.root)?@?dataset://(\\w++)");
3613
3614   if (re1.Match(fESDOutput) == 4) {
3615     // root archive with output files stored and regustered
3616     // in proof dataset
3617     gProof->AddInput(new TNamed("PROOF_OUTPUTFILE",re1[1].Data()));
3618     gProof->AddInput(new TNamed("PROOF_OUTPUTFILE_LOCATION",re1[3].Data()));
3619     gProof->AddInput(new TNamed("PROOF_OUTPUTFILE_DATASET",""));
3620     gProof->AddInput(new TNamed("PROOF_OUTPUTFILE_ARCHIVE",re1[2].Data()));
3621     AliInfo(Form("%s files will be stored within %s in dataset %s",
3622                  re1[2].Data(),
3623                  re1[1].Data(),
3624                  re1[3].Data()));
3625   }
3626   else if (re2.Match(fESDOutput) == 3) {
3627     // output file stored and registered
3628     // in proof dataset
3629     gProof->AddInput(new TNamed("PROOF_OUTPUTFILE",(re2[1].IsNull()) ? "AliESDs.root" : re2[1].Data()));
3630     gProof->AddInput(new TNamed("PROOF_OUTPUTFILE_LOCATION",re2[2].Data()));
3631     gProof->AddInput(new TNamed("PROOF_OUTPUTFILE_DATASET",""));
3632     AliInfo(Form("%s will be stored in dataset %s",
3633                  (re2[1].IsNull()) ? "AliESDs.root" : re2[1].Data(),
3634                  re2[2].Data()));
3635   }
3636   else {
3637     if (fESDOutput.IsNull()) {
3638       // Output location not given.
3639       // Assuming xrootd has been already started and
3640       // the output file has to be sent back
3641       // to the client machine
3642       TString esdUrl(Form("root://%s/%s/",
3643                           TUrl(gSystem->HostName()).GetHostFQDN(),
3644                           gSystem->pwd()));
3645       gProof->AddInput(new TNamed("PROOF_OUTPUTFILE","AliESDs.root"));
3646       gProof->AddInput(new TNamed("PROOF_OUTPUTFILE_LOCATION",esdUrl.Data()));
3647       AliInfo(Form("AliESDs.root will be stored in %s",
3648                    esdUrl.Data()));
3649     }
3650     else {
3651       // User specified an output location.
3652       // Ones has just to parse it here
3653       TUrl outputUrl(fESDOutput.Data());
3654       TString outputFile(gSystem->BaseName(outputUrl.GetFile()));
3655       gProof->AddInput(new TNamed("PROOF_OUTPUTFILE",outputFile.IsNull() ? "AliESDs.root" : outputFile.Data()));
3656       TString outputLocation(outputUrl.GetUrl());
3657       outputLocation.ReplaceAll(outputFile.Data(),"");
3658       gProof->AddInput(new TNamed("PROOF_OUTPUTFILE_LOCATION",outputLocation.Data()));
3659       AliInfo(Form("%s will be stored in %s",
3660                    outputFile.IsNull() ? "AliESDs.root" : outputFile.Data(),
3661                    outputLocation.Data()));
3662     }
3663   }
3664
3665   return kTRUE;
3666 }