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