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