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