]> git.uio.no Git - u/mrichter/AliRoot.git/blob - STEER/STEER/AliReconstruction.cxx
Fix for #91977: Tracking cosmic muons in the TPC and momentum calculation
[u/mrichter/AliRoot.git] / STEER / STEER / AliReconstruction.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16 /* $Id$ */
17
18 ///////////////////////////////////////////////////////////////////////////////
19 //                                                                           //
20 // class for running the reconstruction                                      //
21 //                                                                           //
22 // Clusters and tracks are created for all detectors and all events by       //
23 // typing:                                                                   //
24 //                                                                           //
25 //   AliReconstruction rec;                                                  //
26 //   rec.Run();                                                              //
27 //                                                                           //
28 // The Run method returns kTRUE in case of successful execution.             //
29 //                                                                           //
30 // If the input to the reconstruction are not simulated digits but raw data, //
31 // this can be specified by an argument of the Run method or by the method   //
32 //                                                                           //
33 //   rec.SetInput("...");                                                    //
34 //                                                                           //
35 // The input formats and the corresponding argument are:                     //
36 // - DDL raw data files: directory name, ends with "/"                       //
37 // - raw data root file: root file name, extension ".root"                   //
38 // - raw data DATE file: DATE file name, any other non-empty string          //
39 // - MC root files     : empty string, default                               //
40 //                                                                           //
41 // By default all events are reconstructed. The reconstruction can be        //
42 // limited to a range of events by giving the index of the first and the     //
43 // last event as an argument to the Run method or by calling                 //
44 //                                                                           //
45 //   rec.SetEventRange(..., ...);                                            //
46 //                                                                           //
47 // The index -1 (default) can be used for the last event to indicate no      //
48 // upper limit of the event range.                                           //
49 //                                                                           //
50 // In case of raw-data reconstruction the user can modify the default        //
51 // number of events per digits/clusters/tracks file. In case the option      //
52 // is not used the number is set 1. In case the user provides 0, than        //
53 // the number of events is equal to the number of events inside the          //
54 // raw-data file (i.e. one digits/clusters/tracks file):                     //
55 //                                                                           //
56 //   rec.SetNumberOfEventsPerFile(...);                                      //
57 //                                                                           //
58 //                                                                           //
59 // The name of the galice file can be changed from the default               //
60 // "galice.root" by passing it as argument to the AliReconstruction          //
61 // constructor or by                                                         //
62 //                                                                           //
63 //   rec.SetGAliceFile("...");                                               //
64 //                                                                           //
65 // The local reconstruction can be switched on or off for individual         //
66 // detectors by                                                              //
67 //                                                                           //
68 //   rec.SetRunLocalReconstruction("...");                                   //
69 //                                                                           //
70 // The argument is a (case sensitive) string with the names of the           //
71 // detectors separated by a space. The special string "ALL" selects all      //
72 // available detectors. This is the default.                                 //
73 //                                                                           //
74 // The reconstruction of the primary vertex position can be switched off by  //
75 //                                                                           //
76 //   rec.SetRunVertexFinder(kFALSE);                                         //
77 //                                                                           //
78 // The tracking and the creation of ESD tracks can be switched on for        //
79 // selected detectors by                                                     //
80 //                                                                           //
81 //   rec.SetRunTracking("...");                                              //
82 //                                                                           //
83 // Uniform/nonuniform field tracking switches (default: uniform field)       //
84 //                                                                           //
85 //   rec.SetUniformFieldTracking(); ( rec.SetUniformFieldTracking(kFALSE); ) //
86 //                                                                           //
87 // The filling of additional ESD information can be steered by               //
88 //                                                                           //
89 //   rec.SetFillESD("...");                                                  //
90 //                                                                           //
91 // Again, for both methods the string specifies the list of detectors.       //
92 // The default is "ALL".                                                     //
93 //                                                                           //
94 // The call of the shortcut method                                           //
95 //                                                                           //
96 //   rec.SetRunReconstruction("...");                                        //
97 //                                                                           //
98 // is equivalent to calling SetRunLocalReconstruction, SetRunTracking and    //
99 // SetFillESD with the same detector selecting string as argument.           //
100 //                                                                           //
101 // The reconstruction requires digits or raw data as input. For the creation //
102 // of digits and raw data have a look at the class AliSimulation.            //
103 //                                                                           //
104 // The input data of a detector can be replaced by the corresponding HLT     //
105 // data by calling (usual detector string)                                   //
106 // SetUseHLTData("...");                                                     //
107 //                                                                           //
108 //                                                                           //
109 ///////////////////////////////////////////////////////////////////////////////
110
111 #include <TArrayD.h>
112 #include <TArrayF.h>
113 #include <TArrayS.h>
114 #include <TChain.h>
115 #include <TFile.h>
116 #include <TGeoGlobalMagField.h>
117 #include <TGeoManager.h>
118 #include <TList.h>
119 #include <TLorentzVector.h>
120 #include <TMap.h>
121 #include <TObjArray.h>
122 #include <TPRegexp.h>
123 #include <TParameter.h>
124 #include <TPluginManager.h>
125 #include <TProof.h>
126 #include <TProofOutputFile.h>
127 #include <TROOT.h>
128 #include <TSystem.h>
129 #include <THashTable.h>
130 #include <TGrid.h>
131 #include <TMessage.h>
132 #include <TUrl.h>
133 #include <TRandom.h>
134
135 #include "AliAlignObj.h"
136 #include "AliAnalysisManager.h"
137 #include "AliAnalysisDataContainer.h"
138 #include "AliCDBEntry.h"
139 #include "AliCDBManager.h"
140 #include "AliCDBStorage.h"
141 #include "AliCTPRawStream.h"
142 #include "AliCascadeVertexer.h"
143 #include "AliCentralTrigger.h"
144 #include "AliCodeTimer.h"
145 #include "AliDAQ.h"
146 #include "AliDetectorRecoParam.h"
147 #include "AliESDCaloCells.h"
148 #include "AliESDCaloCluster.h"
149 #include "AliESDEvent.h"
150 #include "AliESDMuonTrack.h"
151 #include "AliESDPmdTrack.h"
152 #include "AliESDTagCreator.h"
153 #include "AliESDVertex.h"
154 #include "AliESDcascade.h"
155 #include "AliESDfriend.h"
156 #include "AliESDkink.h"
157 #include "AliESDpid.h"
158 #include "AliESDtrack.h"
159 #include "AliESDtrack.h"
160 #include "AliEventInfo.h"
161 #include "AliGRPObject.h"
162 #include "AliGRPRecoParam.h"
163 #include "AliGenEventHeader.h"
164 #include "AliGeomManager.h"
165 #include "AliGlobalQADataMaker.h" 
166 #include "AliHeader.h"
167 #include "AliLog.h"
168 #include "AliMagF.h"
169 #include "AliMultiplicity.h"
170 #include "AliPID.h"
171 #include "AliPlaneEff.h"
172 #include "AliQAv1.h"
173 #include "AliQADataMakerRec.h" 
174 #include "AliQAManager.h"
175 #include "AliRawVEvent.h"
176 #include "AliRawEventHeaderBase.h"
177 #include "AliRawHLTManager.h"
178 #include "AliRawReaderDate.h"
179 #include "AliRawReaderFile.h"
180 #include "AliRawReaderRoot.h"
181 #include "AliRecoInputHandler.h"
182 #include "AliReconstruction.h"
183 #include "AliReconstructor.h"
184 #include "AliRun.h"
185 #include "AliRunInfo.h"
186 #include "AliRunLoader.h"
187 #include "AliSysInfo.h" // memory snapshots
188 #include "AliTrackPointArray.h"
189 #include "AliTracker.h"
190 #include "AliTriggerClass.h"
191 #include "AliTriggerCluster.h"
192 #include "AliTriggerIR.h"
193 #include "AliTriggerConfiguration.h"
194 #include "AliV0vertexer.h"
195 #include "AliVertexer.h"
196 #include "AliTrackleter.h"
197 #include "AliVertexerTracks.h"
198 #include "AliTriggerRunScalers.h"
199 #include "AliCTPTimeParams.h" 
200 #include "AliESDHLTDecision.h"
201 #include "AliTriggerInput.h"
202 #include "AliLHCData.h"
203 #include "ARVersion.h"
204 #include <RVersion.h>
205 #include <unistd.h>
206 #include <sys/resource.h>
207 ClassImp(AliReconstruction)
208
209 //_____________________________________________________________________________
210 const char* AliReconstruction::fgkStopEvFName = "_stopEvent_";
211 const char* AliReconstruction::fgkDetectorName[AliReconstruction::kNDetectors] = {"ITS", "TPC", "TRD", "TOF", "PHOS", "HMPID", "EMCAL", "MUON", "FMD", "ZDC", "PMD", "T0", "VZERO", "ACORDE"
212 // #ifdef MFT_UPGRADE
213 //                                                                                   , "MFT"
214 // #endif 
215                                                                                   , "MFT"    // AU
216                                                                                   , "HLT"
217 };
218
219 //_____________________________________________________________________________
220 AliReconstruction::AliReconstruction(const char* gAliceFilename) :
221   TSelector(),
222   fRunVertexFinder(kTRUE),
223   fRunVertexFinderTracks(kTRUE),
224   fRunHLTTracking(kFALSE),
225   fRunMuonTracking(kFALSE),
226   fRunV0Finder(kTRUE),
227   fRunCascadeFinder(kTRUE),
228   fRunMultFinder(kTRUE),
229   fStopOnError(kTRUE),
230   fWriteAlignmentData(kFALSE),
231   fWriteESDfriend(kFALSE),
232   fFillTriggerESD(kTRUE),
233
234   fCleanESD(kTRUE),
235   fV0DCAmax(3.),
236   fV0CsPmin(0.),
237   fDmax(50.),
238   fZmax(50.),
239
240   fRunLocalReconstruction("ALL"),
241   fRunTracking("ALL"),
242   fFillESD("ALL"),
243   fDeleteRecPoints(""),
244   fDeleteDigits(""),
245   fLoadCDB(""),
246   fUseTrackingErrorsForAlignment(""),
247   fGAliceFileName(gAliceFilename),
248   fRawInput(""),
249   fESDOutput(""),
250   fProofOutputFileName(""),
251   fProofOutputLocation(""),
252   fProofOutputDataset(kFALSE),
253   fProofOutputArchive(""),
254   fEquipIdMap(""),
255   fFirstEvent(0),
256   fLastEvent(-1),
257   fNumberOfEventsPerFile((UInt_t)-1),
258   fFractionFriends(0.04),
259   fOptions(),
260   fLoadAlignFromCDB(kTRUE),
261   fLoadAlignData("ALL"),
262   fUseHLTData(),
263   fRunInfo(NULL),
264   fEventInfo(),
265   fRunScalers(NULL),
266   fCTPTimeParams(NULL),  
267   fCTPTimeAlign(NULL),  
268
269   fRunLoader(NULL),
270   fRawReader(NULL),
271   fParentRawReader(NULL),
272
273   fRecoParam(),
274
275   fSPDTrackleter(NULL),
276
277   fDiamondProfileSPD(NULL),
278   fDiamondProfile(NULL),
279   fDiamondProfileTPC(NULL),
280   fListOfCosmicTriggers(NULL),
281   
282   fGRPData(NULL),
283
284   fAlignObjArray(NULL),
285   fCDBUri(),
286   fQARefUri(),
287   fSpecCDBUri(), 
288   fInitCDBCalled(kFALSE),
289   fFromCDBSnapshot(kFALSE),
290   fSnapshotFileName(""),
291   fSetRunNumberFromDataCalled(kFALSE),
292   fQADetectors("ALL"), 
293   fQATasks("ALL"), 
294   fRunQA(kTRUE),  
295   fRunGlobalQA(kTRUE),
296   fSameQACycle(kFALSE),
297   fInitQACalled(kFALSE), 
298   fWriteQAExpertData(kTRUE), 
299   fRunPlaneEff(kFALSE),
300
301   fesd(NULL),
302   fhltesd(NULL),
303   fesdf(NULL),
304   ffile(NULL),
305   ffileF(NULL),
306   ftree(NULL),
307   ftreeF(NULL),
308   fhlttree(NULL),
309   ftVertexer(NULL),
310   fIsNewRunLoader(kFALSE),
311   fRunAliEVE(kFALSE),
312   fChain(NULL),
313   fNall(0),
314   fNspecie(0),
315   fSspecie(0),
316   fNhighPt(0),
317   fShighPt(0),
318   fUpgradeModule(""),
319   fAnalysisMacro(),
320   fAnalysis(0),
321   fRecoHandler(0),
322   fDeclTriggerClasses(""),
323   fStopped(kFALSE),
324   fMaxRSS(0),
325   fMaxVMEM(0)
326 {
327 // create reconstruction object with default parameters
328   gGeoManager = NULL;
329   
330   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
331     fReconstructor[iDet] = NULL;
332     fUpgradeMask[iDet]=kFALSE;
333     fLoader[iDet] = NULL;
334     fTracker[iDet] = NULL;
335   }
336   for (Int_t iDet = 0; iDet < AliQAv1::kNDET; iDet++) {
337     fQACycles[iDet] = 999999 ;
338     fQAWriteExpert[iDet] = kFALSE ; 
339   }
340   fBeamInt[0][0]=fBeamInt[0][1]=fBeamInt[1][0]=fBeamInt[1][1] = -1;
341
342   AliPID pid;
343 }
344
345 //_____________________________________________________________________________
346 AliReconstruction::AliReconstruction(const AliReconstruction& rec) :
347   TSelector(),
348   fRunVertexFinder(rec.fRunVertexFinder),
349   fRunVertexFinderTracks(rec.fRunVertexFinderTracks),
350   fRunHLTTracking(rec.fRunHLTTracking),
351   fRunMuonTracking(rec.fRunMuonTracking),
352   fRunV0Finder(rec.fRunV0Finder),
353   fRunCascadeFinder(rec.fRunCascadeFinder),
354   fRunMultFinder(rec.fRunMultFinder),
355   fStopOnError(rec.fStopOnError),
356   fWriteAlignmentData(rec.fWriteAlignmentData),
357   fWriteESDfriend(rec.fWriteESDfriend),
358   fFillTriggerESD(rec.fFillTriggerESD),
359
360   fCleanESD(rec.fCleanESD),
361   fV0DCAmax(rec.fV0DCAmax),
362   fV0CsPmin(rec.fV0CsPmin),
363   fDmax(rec.fDmax),
364   fZmax(rec.fZmax),
365
366   fRunLocalReconstruction(rec.fRunLocalReconstruction),
367   fRunTracking(rec.fRunTracking),
368   fFillESD(rec.fFillESD),
369   fDeleteRecPoints(""),
370   fDeleteDigits(""),
371   fLoadCDB(rec.fLoadCDB),
372   fUseTrackingErrorsForAlignment(rec.fUseTrackingErrorsForAlignment),
373   fGAliceFileName(rec.fGAliceFileName),
374   fRawInput(rec.fRawInput),
375   fESDOutput(rec.fESDOutput),
376   fProofOutputFileName(rec.fProofOutputFileName),
377   fProofOutputLocation(rec.fProofOutputLocation),
378   fProofOutputDataset(rec.fProofOutputDataset),
379   fProofOutputArchive(rec.fProofOutputArchive),
380   fEquipIdMap(rec.fEquipIdMap),
381   fFirstEvent(rec.fFirstEvent),
382   fLastEvent(rec.fLastEvent),
383   fNumberOfEventsPerFile(rec.fNumberOfEventsPerFile),
384   fFractionFriends(rec.fFractionFriends),
385   fOptions(),
386   fLoadAlignFromCDB(rec.fLoadAlignFromCDB),
387   fLoadAlignData(rec.fLoadAlignData),
388   fUseHLTData(rec.fUseHLTData),
389   fRunInfo(NULL),
390   fEventInfo(),
391   fRunScalers(NULL),
392   fCTPTimeParams(NULL),
393   fCTPTimeAlign(NULL),
394
395   fRunLoader(NULL),
396   fRawReader(NULL),
397   fParentRawReader(NULL),
398
399   fRecoParam(rec.fRecoParam),
400
401   fSPDTrackleter(NULL),
402
403   fDiamondProfileSPD(rec.fDiamondProfileSPD),
404   fDiamondProfile(rec.fDiamondProfile),
405   fDiamondProfileTPC(rec.fDiamondProfileTPC),
406   fListOfCosmicTriggers(NULL),
407   
408   fGRPData(NULL),
409
410   fAlignObjArray(rec.fAlignObjArray),
411   fCDBUri(rec.fCDBUri),
412   fQARefUri(rec.fQARefUri),
413   fSpecCDBUri(), 
414   fInitCDBCalled(rec.fInitCDBCalled),
415   fFromCDBSnapshot(rec.fFromCDBSnapshot),
416   fSnapshotFileName(rec.fSnapshotFileName),
417   fSetRunNumberFromDataCalled(rec.fSetRunNumberFromDataCalled),
418   fQADetectors(rec.fQADetectors), 
419   fQATasks(rec.fQATasks), 
420   fRunQA(rec.fRunQA),  
421   fRunGlobalQA(rec.fRunGlobalQA),
422   fSameQACycle(rec.fSameQACycle),
423   fInitQACalled(rec.fInitQACalled),
424   fWriteQAExpertData(rec.fWriteQAExpertData), 
425   fRunPlaneEff(rec.fRunPlaneEff),
426
427   fesd(NULL),
428   fhltesd(NULL),
429   fesdf(NULL),
430   ffile(NULL),
431   ffileF(NULL),
432   ftree(NULL),
433   ftreeF(NULL),
434   fhlttree(NULL),
435   ftVertexer(NULL),
436   fIsNewRunLoader(rec.fIsNewRunLoader),
437   fRunAliEVE(kFALSE),
438   fChain(NULL),
439   fNall(0),
440   fNspecie(0),
441   fSspecie(0),
442   fNhighPt(0),
443   fShighPt(0),
444   fUpgradeModule(""),
445   fAnalysisMacro(rec.fAnalysisMacro),
446   fAnalysis(0),
447   fRecoHandler(0),
448   fDeclTriggerClasses(rec.fDeclTriggerClasses),
449   fStopped(kFALSE),
450   fMaxRSS(0),
451   fMaxVMEM(0)
452 {
453 // copy constructor
454
455   for (Int_t i = 0; i < rec.fOptions.GetEntriesFast(); i++) {
456     if (rec.fOptions[i]) fOptions.Add(rec.fOptions[i]->Clone());
457   }
458   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
459     fReconstructor[iDet] = NULL;
460     fUpgradeMask[iDet] = kFALSE;
461     fLoader[iDet] = NULL;
462     fTracker[iDet] = NULL;
463   }  
464   
465   for (Int_t iDet = 0; iDet < AliQAv1::kNDET; iDet++) {
466     fQACycles[iDet] = rec.fQACycles[iDet];
467     fQAWriteExpert[iDet] = rec.fQAWriteExpert[iDet] ; 
468   }
469
470   for (Int_t i = 0; i < rec.fSpecCDBUri.GetEntriesFast(); i++) {
471     if (rec.fSpecCDBUri[i]) fSpecCDBUri.Add(rec.fSpecCDBUri[i]->Clone());
472   }
473
474   for (int i=2;i--;) for (int j=2;j--;) fBeamInt[i][j] = rec.fBeamInt[i][j];
475
476 }
477
478 //_____________________________________________________________________________
479 AliReconstruction& AliReconstruction::operator = (const AliReconstruction& rec)
480 {
481 // assignment operator
482 // Used in PROOF mode
483 // Be very careful while modifing it!
484 // Simple rules to follow:
485 // for persistent data members - use their assignment operators
486 // for non-persistent ones - do nothing or take the default values from constructor
487 // TSelector members should not be touched
488   if(&rec == this) return *this;
489
490   fRunVertexFinder       = rec.fRunVertexFinder;
491   fRunVertexFinderTracks = rec.fRunVertexFinderTracks;
492   fRunHLTTracking        = rec.fRunHLTTracking;
493   fRunMuonTracking       = rec.fRunMuonTracking;
494   fRunV0Finder           = rec.fRunV0Finder;
495   fRunCascadeFinder      = rec.fRunCascadeFinder;
496   fRunMultFinder         = rec.fRunMultFinder;
497   fStopOnError           = rec.fStopOnError;
498   fWriteAlignmentData    = rec.fWriteAlignmentData;
499   fWriteESDfriend        = rec.fWriteESDfriend;
500   fFillTriggerESD        = rec.fFillTriggerESD;
501
502   fCleanESD  = rec.fCleanESD;
503   fV0DCAmax  = rec.fV0DCAmax;
504   fV0CsPmin  = rec.fV0CsPmin;
505   fDmax      = rec.fDmax;
506   fZmax      = rec.fZmax;
507
508   fRunLocalReconstruction        = rec.fRunLocalReconstruction;
509   fRunTracking                   = rec.fRunTracking;
510   fFillESD                       = rec.fFillESD;
511   fDeleteRecPoints               = rec.fDeleteRecPoints;
512   fDeleteDigits                  = rec.fDeleteDigits;
513   fLoadCDB                       = rec.fLoadCDB;
514   fUseTrackingErrorsForAlignment = rec.fUseTrackingErrorsForAlignment;
515   fGAliceFileName                = rec.fGAliceFileName;
516   fRawInput                      = rec.fRawInput;
517   fESDOutput                     = rec.fESDOutput;
518   fProofOutputFileName           = rec.fProofOutputFileName;
519   fProofOutputLocation           = rec.fProofOutputLocation;
520   fProofOutputDataset            = rec.fProofOutputDataset;
521   fProofOutputArchive            = rec.fProofOutputArchive;
522   fEquipIdMap                    = rec.fEquipIdMap;
523   fFirstEvent                    = rec.fFirstEvent;
524   fLastEvent                     = rec.fLastEvent;
525   fNumberOfEventsPerFile         = rec.fNumberOfEventsPerFile;
526   fFractionFriends               = rec.fFractionFriends;
527
528   for (Int_t i = 0; i < rec.fOptions.GetEntriesFast(); i++) {
529     if (rec.fOptions[i]) fOptions.Add(rec.fOptions[i]->Clone());
530   }
531
532   fLoadAlignFromCDB              = rec.fLoadAlignFromCDB;
533   fLoadAlignData                 = rec.fLoadAlignData;
534   fUseHLTData                    = rec.fUseHLTData;
535
536   delete fRunInfo; fRunInfo = NULL;
537   if (rec.fRunInfo) fRunInfo = new AliRunInfo(*rec.fRunInfo);
538
539   fEventInfo                     = rec.fEventInfo;
540
541   delete fRunScalers; fRunScalers = NULL;
542   if (rec.fRunScalers) fRunScalers = new AliTriggerRunScalers(*rec.fRunScalers); 
543
544   delete fCTPTimeParams; fCTPTimeParams = NULL;
545   if (rec.fCTPTimeParams) fCTPTimeParams = new AliCTPTimeParams(*rec.fCTPTimeParams);
546   delete fCTPTimeAlign; fCTPTimeAlign = NULL;
547   if (rec.fCTPTimeAlign) fCTPTimeAlign = new AliCTPTimeParams(*rec.fCTPTimeAlign);
548
549   fRunLoader       = NULL;
550   fRawReader       = NULL;
551   fParentRawReader = NULL;
552
553   fRecoParam = rec.fRecoParam;
554
555   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
556     fUpgradeMask[iDet] = kFALSE;
557     delete fReconstructor[iDet]; fReconstructor[iDet] = NULL;
558     delete fLoader[iDet]; fLoader[iDet] = NULL;
559     delete fTracker[iDet]; fTracker[iDet] = NULL;
560   }
561   
562   for (Int_t iDet = 0; iDet < AliQAv1::kNDET; iDet++) {
563     fQACycles[iDet] = rec.fQACycles[iDet];
564     fQAWriteExpert[iDet] = rec.fQAWriteExpert[iDet] ;
565   } 
566
567   delete fSPDTrackleter; fSPDTrackleter = NULL;
568     
569   delete fDiamondProfileSPD; fDiamondProfileSPD = NULL;
570   if (rec.fDiamondProfileSPD) fDiamondProfileSPD = new AliESDVertex(*rec.fDiamondProfileSPD);
571   delete fDiamondProfile; fDiamondProfile = NULL;
572   if (rec.fDiamondProfile) fDiamondProfile = new AliESDVertex(*rec.fDiamondProfile);
573   delete fDiamondProfileTPC; fDiamondProfileTPC = NULL;
574   if (rec.fDiamondProfileTPC) fDiamondProfileTPC = new AliESDVertex(*rec.fDiamondProfileTPC);
575
576   delete fListOfCosmicTriggers; fListOfCosmicTriggers = NULL;
577   if (rec.fListOfCosmicTriggers) fListOfCosmicTriggers = (THashTable*)((rec.fListOfCosmicTriggers)->Clone());
578
579   delete fGRPData; fGRPData = NULL;
580   //  if (rec.fGRPData) fGRPData = (TMap*)((rec.fGRPData)->Clone());
581   if (rec.fGRPData) fGRPData = (AliGRPObject*)((rec.fGRPData)->Clone());
582
583   delete fAlignObjArray; fAlignObjArray = NULL;
584
585   fCDBUri        = "";
586   fQARefUri      = rec.fQARefUri;
587   fSpecCDBUri.Delete();
588   fInitCDBCalled               = rec.fInitCDBCalled;
589   fFromCDBSnapshot             = rec.fFromCDBSnapshot;
590   fSnapshotFileName            = rec.fSnapshotFileName;
591   fSetRunNumberFromDataCalled  = rec.fSetRunNumberFromDataCalled;
592   fQADetectors                 = rec.fQADetectors;
593   fQATasks                     = rec.fQATasks; 
594   fRunQA                       = rec.fRunQA;  
595   fRunGlobalQA                 = rec.fRunGlobalQA;
596   fSameQACycle                 = rec.fSameQACycle;
597   fInitQACalled                = rec.fInitQACalled;
598   fWriteQAExpertData           = rec.fWriteQAExpertData;
599   fRunPlaneEff                 = rec.fRunPlaneEff;
600   for (int i=2;i--;) for (int j=2;j--;) fBeamInt[i][j] = rec.fBeamInt[i][j];
601   fesd     = NULL;
602   fhltesd  = NULL;
603   fesdf    = NULL;
604   ffile    = NULL;
605   ffileF   = NULL;
606   ftree    = NULL;
607   ftreeF   = NULL;
608   fhlttree = NULL;
609   ftVertexer = NULL;
610   fIsNewRunLoader = rec.fIsNewRunLoader;
611   fRunAliEVE = kFALSE;
612   fChain = NULL;
613   fNall = 0;
614   fNspecie = 0;
615   fSspecie = 0;
616   fNhighPt = 0;
617   fShighPt = 0;
618   fUpgradeModule="";
619   fAnalysisMacro = rec.fAnalysisMacro;
620   fAnalysis = 0;
621   fRecoHandler = 0;
622   fDeclTriggerClasses = rec.fDeclTriggerClasses;
623
624   return *this;
625 }
626
627 //_____________________________________________________________________________
628 AliReconstruction::~AliReconstruction()
629 {
630 // clean up
631
632   CleanUp();
633   if (fListOfCosmicTriggers) {
634     fListOfCosmicTriggers->Delete();
635     delete fListOfCosmicTriggers;
636   }
637   delete fGRPData;
638   delete fRunScalers;
639   delete fCTPTimeParams;
640   delete fCTPTimeAlign;
641   fOptions.Delete();
642   if (fAlignObjArray) {
643     fAlignObjArray->Delete();
644     delete fAlignObjArray;
645   }
646   fSpecCDBUri.Delete();
647
648   AliCodeTimer::Instance()->Print();
649 }
650
651 //_____________________________________________________________________________
652 void AliReconstruction::InitQA()
653 {
654   //Initialize the QA and start of cycle 
655   AliCodeTimerAuto("",0);
656   
657   if (fInitQACalled) return;
658   fInitQACalled = kTRUE;
659   
660   if (fGRPData) AliQADataMaker::SetCloningRequest( fGRPData->GetQATrigClasses(), fGRPData->GetQACloningRequest());
661
662
663   AliQAManager * qam = AliQAManager::QAManager(AliQAv1::kRECMODE) ; 
664   if (fWriteQAExpertData)
665     qam->SetWriteExpert() ; 
666  
667   if (qam->IsDefaultStorageSet()) {
668     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
669     AliWarning("Default QA reference storage has been already set !");
670     AliWarning(Form("Ignoring the default storage declared in AliReconstruction: %s",fQARefUri.Data()));
671     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
672     fQARefUri = qam->GetDefaultStorage()->GetURI();
673   } else {
674     if (fQARefUri.Length() > 0) {
675         AliDebug(2,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
676         AliDebug(2, Form("Default QA reference storage is set to: %s", fQARefUri.Data()));
677         AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
678       } else {
679         fQARefUri="local://$ALICE_ROOT/QAref";
680         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
681         AliWarning("Default QA refeference storage not yet set !!!!");
682         AliWarning(Form("Setting it now to: %s", fQARefUri.Data()));
683         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
684                 
685       }
686     qam->SetDefaultStorage(fQARefUri);
687   }
688   
689   if (fRunQA) {
690   qam->SetActiveDetectors(fQADetectors) ; 
691   for (Int_t det = 0 ; det < AliQAv1::kNDET ; det++) {
692     qam->SetCycleLength(AliQAv1::DETECTORINDEX_t(det), fQACycles[det]) ;  
693     qam->SetWriteExpert(AliQAv1::DETECTORINDEX_t(det)) ;
694   }
695   if (!fRawReader && !fInput && IsInTasks(AliQAv1::kRAWS))
696     fQATasks.ReplaceAll(Form("%d",AliQAv1::kRAWS), "") ;
697   qam->SetTasks(fQATasks) ; 
698   qam->InitQADataMaker(AliCDBManager::Instance()->GetRun()) ; 
699   }
700   if (fRunGlobalQA) {
701     Bool_t sameCycle = kFALSE ;
702     AliQADataMaker *qadm = qam->GetQADataMaker(AliQAv1::kGLOBAL);
703     AliInfo(Form("Initializing the global QA data maker"));
704     if (IsInTasks(AliQAv1::kRECPOINTS)) {
705       qadm->StartOfCycle(AliQAv1::kRECPOINTS, AliCDBManager::Instance()->GetRun(), sameCycle) ; 
706       TObjArray **arr=qadm->Init(AliQAv1::kRECPOINTS);
707       AliTracker::SetResidualsArray(arr);
708       sameCycle = kTRUE ; 
709     }
710     if (IsInTasks(AliQAv1::kESDS)) {
711       qadm->StartOfCycle(AliQAv1::kESDS, AliCDBManager::Instance()->GetRun(), sameCycle) ; 
712       qadm->Init(AliQAv1::kESDS);
713     }
714   }
715     AliSysInfo::AddStamp("InitQA") ; 
716 }
717
718 //_____________________________________________________________________________
719 void AliReconstruction::MergeQA(const char *fileName)
720 {
721   //Initialize the QA and start of cycle 
722   AliCodeTimerAuto("",0) ;
723   AliQAManager::QAManager()->Merge(AliCDBManager::Instance()->GetRun(),fileName) ; 
724   AliSysInfo::AddStamp("MergeQA") ; 
725 }
726   
727 //_____________________________________________________________________________
728 void AliReconstruction::InitCDB()
729 {
730 // activate a default CDB storage
731 // First check if we have any CDB storage set, because it is used 
732 // to retrieve the calibration and alignment constants
733   AliCodeTimerAuto("",0);
734
735   if (fInitCDBCalled) return;
736   fInitCDBCalled = kTRUE;
737
738   AliCDBManager* man = AliCDBManager::Instance();
739   if (man->IsDefaultStorageSet())
740   {
741     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
742     AliWarning("Default CDB storage has been already set !");
743     AliWarning(Form("Ignoring the default storage declared in AliReconstruction: %s",fCDBUri.Data()));
744     AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
745     fCDBUri = man->GetDefaultStorage()->GetURI();
746   }
747   else {
748     if (fCDBUri.Length() > 0) 
749     {
750         AliDebug(2,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
751         AliDebug(2, Form("Default CDB storage is set to: %s", fCDBUri.Data()));
752         AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
753         man->SetDefaultStorage(fCDBUri);
754     } 
755     else if (!man->GetRaw()){
756         fCDBUri="local://$ALICE_ROOT/OCDB";
757         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
758         AliWarning("Default CDB storage not yet set !!!!");
759         AliWarning(Form("Setting it now to: %s", fCDBUri.Data()));
760         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
761         man->SetDefaultStorage(fCDBUri);
762     }
763     else {    
764         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
765         AliWarning("Default storage will be set after setting the Run Number!!!");
766         AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");                    
767     }
768   }
769
770   // Now activate the detector specific CDB storage locations
771   for (Int_t i = 0; i < fSpecCDBUri.GetEntriesFast(); i++) {
772     TObject* obj = fSpecCDBUri[i];
773     if (!obj) continue;
774     AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
775     AliDebug(2, Form("Specific CDB storage for %s is set to: %s",obj->GetName(),obj->GetTitle()));
776     AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
777     man->SetSpecificStorage(obj->GetName(), obj->GetTitle());
778   }
779   AliSysInfo::AddStamp("InitCDB");
780 }
781
782 //_____________________________________________________________________________
783 void AliReconstruction::SetCDBSnapshotMode(const char* snapshotFileName) {
784     AliCDBManager::Instance()->SetSnapshotMode(snapshotFileName);
785 }
786
787 //_____________________________________________________________________________
788 void AliReconstruction::SetDefaultStorage(const char* uri) {
789 // Store the desired default CDB storage location
790 // Activate it later within the Run() method
791
792   fCDBUri = uri;
793
794 }
795
796 //_____________________________________________________________________________
797 void AliReconstruction::SetQARefDefaultStorage(const char* uri) {
798   // Store the desired default CDB storage location
799   // Activate it later within the Run() method
800   
801   fQARefUri = uri;
802   AliQAv1::SetQARefStorage(fQARefUri.Data()) ;
803   
804 }
805 //_____________________________________________________________________________
806 void AliReconstruction::SetSpecificStorage(const char* calibType, const char* uri) {
807 // Store a detector-specific CDB storage location
808 // Activate it later within the Run() method
809
810   AliCDBPath aPath(calibType);
811   if(!aPath.IsValid()){
812         // if calibType is not wildcard but it is a valid detector, add "/*" to make it a valid path
813         for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
814                 if(!strcmp(calibType, fgkDetectorName[iDet])) {
815                         aPath.SetPath(Form("%s/*", calibType));
816                         AliInfo(Form("Path for specific storage set to %s", aPath.GetPath().Data()));
817                         break;
818                 }
819         }
820         if(!aPath.IsValid()){
821                 AliError(Form("Not a valid path or detector: %s", calibType));
822                 return;
823         }
824   }
825
826 //  // check that calibType refers to a "valid" detector name
827 //  Bool_t isDetector = kFALSE;
828 //  for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
829 //    TString detName = fgkDetectorName[iDet];
830 //    if(aPath.GetLevel0() == detName) {
831 //      isDetector = kTRUE;
832 //      break;
833 //    }
834 //  }
835 //
836 //  if(!isDetector) {
837 //      AliError(Form("Not a valid detector: %s", aPath.GetLevel0().Data()));
838 //      return;
839 //  }
840
841   TObject* obj = fSpecCDBUri.FindObject(aPath.GetPath().Data());
842   if (obj) fSpecCDBUri.Remove(obj);
843   fSpecCDBUri.Add(new TNamed(aPath.GetPath().Data(), uri));
844
845 }
846
847 //_____________________________________________________________________________
848 Bool_t AliReconstruction::SetRunNumberFromData()
849 {
850   // The method is called in Run() in order
851   // to set a correct run number.
852   // In case of raw data reconstruction the
853   // run number is taken from the raw data header
854
855   if (fSetRunNumberFromDataCalled) return kTRUE;
856   fSetRunNumberFromDataCalled = kTRUE;
857   
858   AliCDBManager* man = AliCDBManager::Instance();
859  
860   if(fRawReader) {
861     if(fRawReader->NextEvent()) {
862       if(man->GetRun() > 0) {
863         AliWarning("Run number is taken from raw-event header! Ignoring settings in AliCDBManager!");
864       } 
865       man->SetRun(fRawReader->GetRunNumber());
866       fRawReader->RewindEvents();
867     }
868     else {
869       if(man->GetRun() > 0) {
870         AliWarning("No raw-data events are found ! Using settings in AliCDBManager !");
871       }
872       else {
873         AliWarning("Neither raw events nor settings in AliCDBManager are found !");
874         return kFALSE;
875       }
876     }
877   }
878   else {
879     AliRunLoader *rl = AliRunLoader::Open(fGAliceFileName.Data());
880     if (!rl) {
881       AliError(Form("No run loader found in file %s", fGAliceFileName.Data()));
882       return kFALSE;
883     }
884     else {
885       rl->LoadHeader();
886       // read run number from gAlice
887       if(rl->GetHeader()) {
888         man->SetRun(rl->GetHeader()->GetRun());
889         rl->UnloadHeader();
890         delete rl;
891       }
892       else {
893         AliError("Neither run-loader header nor RawReader objects are found !");
894         delete rl;
895         return kFALSE;
896       }
897     }
898   }
899
900   man->Print();  
901   
902   return kTRUE;
903 }
904
905 //_____________________________________________________________________________
906 void AliReconstruction::SetCDBLock() {
907   // Set CDB lock: from now on it is forbidden to reset the run number
908   // or the default storage or to activate any further storage!
909   
910   AliCDBManager::Instance()->SetLock(1);
911 }
912
913 //_____________________________________________________________________________
914 void AliReconstruction::MatchUpgradeDetector() {
915   // Translates detector name in a boolean.
916   // The boolean is used in GetReconstructor to load the 
917   // upgrade reconstructor instead of the standard one.
918    for(Int_t iDet = 0; iDet < kNDetectors; iDet++) {
919     if(fUpgradeModule.Contains(fgkDetectorName[iDet])) fUpgradeMask[iDet]=kTRUE;
920    }
921 }
922 //_____________________________________________________________________________
923 Bool_t AliReconstruction::MisalignGeometry(const TString& detectors)
924 {
925   // Read the alignment objects from CDB.
926   // Each detector is supposed to have the
927   // alignment objects in DET/Align/Data CDB path.
928   // All the detector objects are then collected,
929   // sorted by geometry level (starting from ALIC) and
930   // then applied to the TGeo geometry.
931   // Finally an overlaps check is performed.
932
933   // Load alignment data from CDB and fill fAlignObjArray 
934   if(fLoadAlignFromCDB){
935         
936     TString detStr = detectors;
937     TString loadAlObjsListOfDets = "";
938     
939     for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
940       if(!IsSelected(fgkDetectorName[iDet], detStr)) continue;
941       if(!strcmp(fgkDetectorName[iDet],"HLT")) continue;
942       
943       if(AliGeomManager::GetNalignable(fgkDetectorName[iDet]) != 0)
944       {
945         loadAlObjsListOfDets += fgkDetectorName[iDet];
946         loadAlObjsListOfDets += " ";
947       }
948     } // end loop over detectors
949     
950     if(AliGeomManager::GetNalignable("GRP") != 0)
951       loadAlObjsListOfDets.Prepend("GRP "); //add alignment objects for non-sensitive modules
952     AliGeomManager::ApplyAlignObjsFromCDB(loadAlObjsListOfDets.Data());
953   }else{
954     // Check if the array with alignment objects was
955     // provided by the user. If yes, apply the objects
956     // to the present TGeo geometry
957     if (fAlignObjArray) {
958       if (gGeoManager && gGeoManager->IsClosed()) {
959         if (AliGeomManager::ApplyAlignObjsToGeom(*fAlignObjArray) == kFALSE) {
960           AliError("The misalignment of one or more volumes failed!"
961                    "Compare the list of simulated detectors and the list of detector alignment data!");
962           return kFALSE;
963         }
964       }
965       else {
966         AliError("Can't apply the misalignment! gGeoManager doesn't exist or it is still opened!");
967         return kFALSE;
968       }
969     }
970   }
971   
972   if (fAlignObjArray) {
973     fAlignObjArray->Delete();
974     delete fAlignObjArray; fAlignObjArray=NULL;
975   }
976
977   return kTRUE;
978 }
979
980 //_____________________________________________________________________________
981 void AliReconstruction::SetGAliceFile(const char* fileName)
982 {
983 // set the name of the galice file
984
985   fGAliceFileName = fileName;
986 }
987
988 //_____________________________________________________________________________
989 void AliReconstruction::SetInput(const char* input) 
990 {
991   // In case the input string starts with 'mem://', we run in an online mode
992   // and AliRawReaderDateOnline object is created. In all other cases a raw-data
993   // file is assumed. One can give as an input:
994   // mem://: - events taken from DAQ monitoring libs online
995   //  or
996   // mem://<filename> - emulation of the above mode (via DATE monitoring libs)
997   if (input) fRawInput = input;
998 }
999
1000 //_____________________________________________________________________________
1001 void AliReconstruction::SetOutput(const char* output) 
1002 {
1003   // Set the output ESD filename
1004   // 'output' is a normalt ROOT url
1005   // The method is used in case of raw-data reco with PROOF
1006   if (output) fESDOutput = output;
1007 }
1008
1009 //_____________________________________________________________________________
1010 void AliReconstruction::SetOption(const char* detector, const char* option)
1011 {
1012 // set options for the reconstruction of a detector
1013
1014   TObject* obj = fOptions.FindObject(detector);
1015   if (obj) fOptions.Remove(obj);
1016   fOptions.Add(new TNamed(detector, option));
1017 }
1018
1019 //_____________________________________________________________________________
1020 void AliReconstruction::SetRecoParam(const char* detector, AliDetectorRecoParam *par)
1021 {
1022   // Set custom reconstruction parameters for a given detector
1023   // Single set of parameters for all the events
1024
1025   // First check if the reco-params are global
1026   if(!strcmp(detector, "GRP")) {
1027     par->SetAsDefault();
1028     fRecoParam.AddDetRecoParam(kNDetectors,par);
1029     return;
1030   }
1031
1032   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
1033     if(!strcmp(detector, fgkDetectorName[iDet])) {
1034       par->SetAsDefault();
1035       fRecoParam.AddDetRecoParam(iDet,par);
1036       break;
1037     }
1038   }
1039
1040 }
1041
1042 //_____________________________________________________________________________
1043 Bool_t AliReconstruction::InitGRP() {
1044   //------------------------------------
1045   // Initialization of the GRP entry 
1046   //------------------------------------
1047   AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/GRP/Data");
1048
1049   if (entry) {
1050
1051     TMap* m = dynamic_cast<TMap*>(entry->GetObject());  // old GRP entry
1052
1053     if (m) {
1054        AliInfo("Found a TMap in GRP/GRP/Data, converting it into an AliGRPObject");
1055        m->Print();
1056        fGRPData = new AliGRPObject();
1057        fGRPData->ReadValuesFromMap(m);
1058     }
1059
1060     else {
1061        AliInfo("Found an AliGRPObject in GRP/GRP/Data, reading it");
1062        fGRPData = dynamic_cast<AliGRPObject*>(entry->GetObject());  // new GRP entry
1063        entry->SetOwner(0);
1064     }
1065
1066     //    FIX ME: The unloading of GRP entry is temporarily disabled
1067     //    because ZDC and VZERO are using it in order to initialize
1068     //    their reconstructor objects. In the future one has to think
1069     //    of propagating AliRunInfo to the reconstructors.
1070     //    AliCDBManager::Instance()->UnloadFromCache("GRP/GRP/Data");
1071   }
1072
1073   if (!fGRPData) {
1074      AliError("No GRP entry found in OCDB!");
1075      return kFALSE;
1076   }
1077
1078   TString lhcState = fGRPData->GetLHCState();
1079   if (lhcState==AliGRPObject::GetInvalidString()) {
1080     AliError("GRP/GRP/Data entry:  missing value for the LHC state ! Using UNKNOWN");
1081     lhcState = "UNKNOWN";
1082   }
1083
1084   TString beamType = fGRPData->GetBeamType();
1085   if (beamType==AliGRPObject::GetInvalidString()) {
1086     AliError("GRP/GRP/Data entry:  missing value for the beam type ! Using UNKNOWN");
1087     beamType = "UNKNOWN";
1088   }
1089
1090   Float_t beamEnergy = fGRPData->GetBeamEnergy();
1091   if (beamEnergy==AliGRPObject::GetInvalidFloat()) {
1092     AliError("GRP/GRP/Data entry:  missing value for the beam energy ! Using 0");
1093     beamEnergy = 0;
1094   }
1095
1096   TString runType = fGRPData->GetRunType();
1097   if (runType==AliGRPObject::GetInvalidString()) {
1098     AliError("GRP/GRP/Data entry:  missing value for the run type ! Using UNKNOWN");
1099     runType = "UNKNOWN";
1100   }
1101
1102   Int_t activeDetectors = fGRPData->GetDetectorMask();
1103   if (activeDetectors==AliGRPObject::GetInvalidUInt()) {
1104     AliError("GRP/GRP/Data entry:  missing value for the detector mask ! Using 1074790399");
1105     activeDetectors = 1074790399;
1106   }
1107   AliDebug(1, Form("activeDetectors = %d", activeDetectors));
1108
1109   fRunInfo = new AliRunInfo(lhcState, beamType, beamEnergy, runType, activeDetectors);
1110   fRunInfo->Dump();
1111
1112
1113   // Process the list of active detectors
1114   if (activeDetectors) {
1115     UInt_t detMask = activeDetectors;
1116     AliDebug(1, Form("Detector List = %s", fRunLocalReconstruction.Data()));
1117     fRunLocalReconstruction = MatchDetectorList(fRunLocalReconstruction,detMask);
1118     AliDebug(1, Form("Detector List = %s", fRunLocalReconstruction.Data()));
1119     fRunTracking = MatchDetectorList(fRunTracking,detMask);
1120     fFillESD = MatchDetectorList(fFillESD,detMask);
1121     fQADetectors = MatchDetectorList(fQADetectors,detMask);
1122     fDeleteRecPoints = MatchDetectorList(fDeleteRecPoints,detMask);
1123     fDeleteDigits    = MatchDetectorList(fDeleteDigits,detMask);
1124     fLoadCDB.Form("%s %s %s %s",
1125                   fRunLocalReconstruction.Data(),
1126                   fRunTracking.Data(),
1127                   fFillESD.Data(),
1128                   fQADetectors.Data());
1129     fLoadCDB = MatchDetectorList(fLoadCDB,detMask);
1130     if (!((detMask >> AliDAQ::DetectorID("ITSSPD")) & 0x1) &&
1131         !((detMask >> AliDAQ::DetectorID("ITSSDD")) & 0x1) &&
1132         !((detMask >> AliDAQ::DetectorID("ITSSSD")) & 0x1) ) {
1133       // switch off the vertexer
1134       AliInfo("SPD,SDD,SSD is not in the list of active detectors. Vertexer and Trackleter are switched off.");
1135       fRunVertexFinder = kFALSE;
1136       fRunMultFinder = kFALSE;
1137     }
1138     if (!((detMask >> AliDAQ::DetectorID("TRG")) & 0x1)) {
1139       // switch off the reading of CTP raw-data payload
1140       if (fFillTriggerESD) {
1141         AliInfo("CTP is not in the list of active detectors. CTP data reading switched off.");
1142         fFillTriggerESD = kFALSE;
1143       }
1144     }
1145   }
1146
1147   AliInfo("===================================================================================");
1148   AliInfo(Form("Running local reconstruction for detectors: %s",fRunLocalReconstruction.Data()));
1149   AliInfo(Form("Running tracking for detectors: %s",fRunTracking.Data()));
1150   AliInfo(Form("Filling ESD for detectors: %s",fFillESD.Data()));
1151   AliInfo(Form("Quality assurance is active for detectors: %s",fQADetectors.Data()));
1152   AliInfo(Form("CDB and reconstruction parameters are loaded for detectors: %s",fLoadCDB.Data()));
1153   AliInfo("===================================================================================");
1154
1155   //*** Dealing with the magnetic field map
1156   if ( TGeoGlobalMagField::Instance()->IsLocked() ) {
1157     if (TGeoGlobalMagField::Instance()->GetField()->TestBit(AliMagF::kOverrideGRP)) {
1158       AliInfo("ExpertMode!!! GRP information will be ignored !");
1159       AliInfo("ExpertMode!!! Running with the externally locked B field !");
1160     }
1161     else {
1162       AliInfo("Destroying existing B field instance!");
1163       delete TGeoGlobalMagField::Instance();
1164     }    
1165   }
1166   if ( !TGeoGlobalMagField::Instance()->IsLocked() ) {
1167     // Construct the field map out of the information retrieved from GRP.
1168     Bool_t ok = kTRUE;
1169     // L3
1170     Float_t l3Current = fGRPData->GetL3Current((AliGRPObject::Stats)0);
1171     if (l3Current == AliGRPObject::GetInvalidFloat()) {
1172       AliError("GRP/GRP/Data entry:  missing value for the L3 current !");
1173       ok = kFALSE;
1174     }
1175     
1176     Char_t l3Polarity = fGRPData->GetL3Polarity();
1177     if (l3Polarity == AliGRPObject::GetInvalidChar()) {
1178       AliError("GRP/GRP/Data entry:  missing value for the L3 polarity !");
1179       ok = kFALSE;
1180     }
1181
1182     // Dipole
1183     Float_t diCurrent = fGRPData->GetDipoleCurrent((AliGRPObject::Stats)0);
1184     if (diCurrent == AliGRPObject::GetInvalidFloat()) {
1185       AliError("GRP/GRP/Data entry:  missing value for the dipole current !");
1186       ok = kFALSE;
1187     }
1188
1189     Char_t diPolarity = fGRPData->GetDipolePolarity();
1190     if (diPolarity == AliGRPObject::GetInvalidChar()) {
1191       AliError("GRP/GRP/Data entry:  missing value for the dipole polarity !");
1192       ok = kFALSE;
1193     }
1194
1195     // read special bits for the polarity convention and map type
1196     Int_t  polConvention = fGRPData->IsPolarityConventionLHC() ? AliMagF::kConvLHC : AliMagF::kConvDCS2008;
1197     Bool_t uniformB = fGRPData->IsUniformBMap();
1198
1199     if (ok) { 
1200       AliMagF* fld = AliMagF::CreateFieldMap(TMath::Abs(l3Current) * (l3Polarity ? -1:1), 
1201                                              TMath::Abs(diCurrent) * (diPolarity ? -1:1), 
1202                                              polConvention,uniformB,beamEnergy, beamType.Data());
1203       if (fld) {
1204         TGeoGlobalMagField::Instance()->SetField( fld );
1205         TGeoGlobalMagField::Instance()->Lock();
1206         AliInfo("Running with the B field constructed out of GRP !");
1207       }
1208       else AliFatal("Failed to create a B field map !");
1209     }
1210     else AliFatal("B field is neither set nor constructed from GRP ! Exitig...");
1211   }
1212   
1213   //*** Get the diamond profiles from OCDB
1214   entry = AliCDBManager::Instance()->Get("GRP/Calib/MeanVertexSPD");
1215   if (entry) {
1216     fDiamondProfileSPD = dynamic_cast<AliESDVertex*> (entry->GetObject());  
1217   } else {
1218      AliError("No SPD diamond profile found in OCDB!");
1219   }
1220
1221   entry = AliCDBManager::Instance()->Get("GRP/Calib/MeanVertex");
1222   if (entry) {
1223     fDiamondProfile = dynamic_cast<AliESDVertex*> (entry->GetObject());  
1224   } else {
1225      AliError("No diamond profile found in OCDB!");
1226   }
1227
1228   entry = AliCDBManager::Instance()->Get("GRP/Calib/MeanVertexTPC");
1229   if (entry) {
1230     fDiamondProfileTPC = dynamic_cast<AliESDVertex*> (entry->GetObject());  
1231   } else {
1232      AliError("No TPC diamond profile found in OCDB!");
1233   }
1234
1235   entry = AliCDBManager::Instance()->Get("GRP/Calib/CosmicTriggers");
1236   if (entry) {
1237     fListOfCosmicTriggers = dynamic_cast<THashTable*>(entry->GetObject());
1238     entry->SetOwner(0);
1239   }
1240
1241   if (!fListOfCosmicTriggers) {
1242     AliWarning("Can not get list of cosmic triggers from OCDB! Cosmic event specie will be effectively disabled!");
1243   }
1244
1245   return kTRUE;
1246
1247
1248 //_____________________________________________________________________________
1249 Bool_t AliReconstruction::LoadCDB()
1250 {
1251   // Load CDB entries for all active detectors.
1252   // By default we load all the entries in <det>/Calib
1253   // folder.
1254
1255   AliCodeTimerAuto("",0);
1256
1257   AliCDBManager::Instance()->Get("GRP/CTP/Config");
1258
1259   AliCDBManager::Instance()->Get("GRP/Calib/LHCClockPhase");
1260
1261   TString detStr = fLoadCDB;
1262   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
1263     if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
1264     AliCDBManager::Instance()->GetAll(Form("%s/Calib/*",fgkDetectorName[iDet]));
1265     AliCDBManager::Instance()->GetAll(Form("%s/Trigger/*",fgkDetectorName[iDet]));
1266   }
1267
1268   // Temporary fix - one has to define the correct policy in order
1269   // to load the trigger OCDB entries only for the detectors that
1270   // in the trigger or that are needed in order to put correct
1271   // information in ESD
1272   AliCDBManager::Instance()->GetAll("TRIGGER/*/*");
1273
1274   return kTRUE;
1275 }
1276 //_____________________________________________________________________________
1277 Bool_t AliReconstruction::LoadTriggerScalersCDB()
1278 {
1279   // Load CTP scalers from OCDB.
1280   // The scalers are checked for consistency.
1281
1282   AliCodeTimerAuto("",0);
1283
1284   AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/CTP/Scalers");
1285
1286   if (entry) { 
1287    
1288        AliInfo("Found an AliTriggerRunScalers in GRP/CTP/Scalers, reading it");
1289        fRunScalers = dynamic_cast<AliTriggerRunScalers*> (entry->GetObject());
1290        entry->SetOwner(0);
1291        if (fRunScalers && (fRunScalers->CorrectScalersOverflow() == 0)) AliInfo("32bit Trigger counters corrected for overflow");
1292
1293   }
1294   return kTRUE;
1295 }
1296 //_____________________________________________________________________________
1297 Bool_t AliReconstruction::LoadCTPTimeParamsCDB()
1298 {
1299   // Load CTP timing information (alignment)
1300   // from OCDB.
1301
1302   AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/CTP/CTPtiming");
1303   if (!entry) return kFALSE;
1304
1305   AliInfo("Found an AliCTPTimeParams in GRP/CTP/CTPtiming, reading it");
1306   fCTPTimeParams = dynamic_cast<AliCTPTimeParams*> (entry->GetObject());
1307   entry->SetOwner(0);
1308
1309   AliCDBEntry* entry2 = AliCDBManager::Instance()->Get("GRP/CTP/TimeAlign");
1310   if (!entry2) return kFALSE;
1311
1312   AliInfo("Found an AliCTPTimeParams in GRP/CTP/TimeAlign, reading it");
1313   fCTPTimeAlign = dynamic_cast<AliCTPTimeParams*> (entry2->GetObject());
1314   entry2->SetOwner(0);
1315
1316   return kTRUE;
1317 }
1318
1319 //_____________________________________________________________________________
1320 Bool_t AliReconstruction::ReadIntensityInfoCDB()
1321 {
1322   // Load LHC DIP data
1323   AliCDBEntry* entry    = AliCDBManager::Instance()->Get("GRP/GRP/LHCData");
1324   AliCDBEntry* entryCTP = AliCDBManager::Instance()->Get("GRP/CTP/Config");
1325   //
1326   if (!entry || !entryCTP) {
1327     AliError(Form("Failed to extract CDB objects GRP/GRP/LHCData: %p or GRP/CTP/Config: %p",entry,entryCTP));
1328     return kFALSE;
1329   }
1330   // extract BC masks
1331   enum {kA,kB,kC,kE,kNMasks};
1332   AliTriggerConfiguration* conf = (AliTriggerConfiguration*)entryCTP->GetObject();
1333   const TObjArray& clArr = conf->GetClasses();
1334   TObjArray masks(kNMasks);
1335   TIter next(&clArr);
1336   AliTriggerClass* trClass = 0;
1337   int nFound = 0;
1338   masks.SetOwner(kFALSE);
1339   //
1340   while ( (trClass=(AliTriggerClass*)next()) ) {
1341     TString trName = trClass->GetName();
1342     int ind = trName.Index("-"); // prefix in front of A,B,C,E
1343     if (ind<1) continue;   // anomaly
1344     //
1345     trName = trName.Data() + ind;
1346     AliTriggerBCMask* bcMask = trClass->GetBCMask();
1347     if (!bcMask) continue;
1348     UInt_t which = 0;
1349     if      (trName.BeginsWith("-A-"))  which |= 0x1<<kA;
1350     else if (trName.BeginsWith("-B-"))  which |= 0x1<<kB;
1351     else if (trName.BeginsWith("-C-"))  which |= 0x1<<kC;
1352     else if (trName.BeginsWith("-E-"))  which |= 0x1<<kE;
1353     else if (trName.BeginsWith("-AC-")) which |= (0x1<<kA) | (0x1<<kC);
1354     else if (trName.BeginsWith("-CA-")) which |= (0x1<<kA) | (0x1<<kC);
1355     else { AliWarning(Form("Unknown trigger type %s\n",trClass->GetName())); continue;}
1356     //
1357     for (int ip=kNMasks;ip--;) {
1358       if ( !(which&(0x1<<ip)) || masks[ip] ) continue; // does not match or already done
1359       masks[ip] = (TObject*)bcMask;
1360       nFound++;
1361     }
1362     if (nFound==kNMasks) break;
1363   }  
1364   //  
1365   AliInfo("Reading mean bunch intensities from GRP/GRP/LHCData");
1366   AliLHCData* dipData = dynamic_cast<AliLHCData*> (entry->GetObject());
1367   //
1368   for (int ib=2;ib--;) {
1369     double intI,intNI;
1370     if (dipData && (dipData->GetMeanIntensity(ib,intI,intNI,&masks)>=0)) {
1371       fBeamInt[ib][0] = intI;
1372       fBeamInt[ib][1] = intNI;  
1373       AliInfo(Form("Mean intensity for beam %d: Interacting:%.2e Non-Interacting:%.2e",ib,intI,intNI));
1374     }
1375   }
1376   return kTRUE;
1377   //
1378 }
1379
1380
1381 //_____________________________________________________________________________
1382 Bool_t AliReconstruction::Run(const char* input)
1383 {
1384   // Run Run Run
1385   AliCodeTimerAuto("",0);
1386
1387   InitRun(input);
1388   if (GetAbort() != TSelector::kContinue) return kFALSE;
1389
1390   TChain *chain = NULL;
1391   if (fRawReader && (chain = fRawReader->GetChain())) {
1392     Long64_t nEntries = (fLastEvent < 0) ? (TChain::kBigNumber) : (fLastEvent - fFirstEvent + 1);
1393     // Proof mode
1394     if (gProof) {
1395       // Temporary fix for long raw-data runs (until socket timeout handling in PROOF is revised)
1396       gProof->Exec("gEnv->SetValue(\"Proof.SocketActivityTimeout\",-1)", kTRUE);
1397
1398       if (gGrid)
1399         gProof->Exec("TGrid::Connect(\"alien://\")",kTRUE);
1400
1401       TMessage::EnableSchemaEvolutionForAll(kTRUE);
1402       gProof->Exec("TMessage::EnableSchemaEvolutionForAll(kTRUE)",kTRUE);
1403
1404       gProof->AddInput(this);
1405
1406       if (!ParseOutput()) return kFALSE;
1407
1408       gProof->SetParameter("PROOF_MaxSlavesPerNode", 9999);
1409       chain->SetProof();
1410       chain->Process("AliReconstruction","",nEntries,fFirstEvent);
1411     }
1412     else {
1413       chain->Process(this,"",nEntries,fFirstEvent);
1414     }
1415   }
1416   else {
1417     Begin(NULL);
1418     if (GetAbort() != TSelector::kContinue) return kFALSE;
1419     SlaveBegin(NULL);
1420     if (GetAbort() != TSelector::kContinue) return kFALSE;
1421     //******* The loop over events
1422     AliInfo("Starting looping over events");
1423     Int_t iEvent = 0;
1424     while ((iEvent < fRunLoader->GetNumberOfEvents()) ||
1425            (fRawReader && fRawReader->NextEvent())) {
1426       //
1427       // check if process has enough resources 
1428       if (!HasEnoughResources(iEvent)) break;
1429       if (!ProcessEvent(iEvent)) {
1430         Abort("ProcessEvent",TSelector::kAbortFile);
1431         return kFALSE;
1432       }
1433       iEvent++;
1434     }
1435     SlaveTerminate();
1436     if (GetAbort() != TSelector::kContinue) return kFALSE;
1437     Terminate();
1438     if (GetAbort() != TSelector::kContinue) return kFALSE;
1439   }
1440
1441   return kTRUE;
1442 }
1443
1444 //_____________________________________________________________________________
1445 void AliReconstruction::InitRawReader(const char* input)
1446 {
1447   // Init raw-reader and
1448   // set the input in case of raw data
1449
1450   AliCodeTimerAuto("",0);
1451
1452   if (input) fRawInput = input;
1453   fRawReader = AliRawReader::Create(fRawInput.Data());
1454   if (!fRawReader) {
1455     if (fRawInput.IsNull()) {
1456       AliInfo("Reconstruction will run over digits");
1457     }
1458     else {
1459       AliFatal("Can not create raw-data reader ! Exiting..."); 
1460     }
1461   }
1462
1463   if (!fEquipIdMap.IsNull() && fRawReader)
1464     fRawReader->LoadEquipmentIdsMap(fEquipIdMap);
1465
1466   if (!fUseHLTData.IsNull()) {
1467     // create the RawReaderHLT which performs redirection of HLT input data for
1468     // the specified detectors
1469     AliRawReader* pRawReader=AliRawHLTManager::CreateRawReaderHLT(fRawReader, fUseHLTData.Data());
1470     if (pRawReader) {
1471       fParentRawReader=fRawReader;
1472       fRawReader=pRawReader;
1473     } else {
1474       AliError(Form("can not create Raw Reader for HLT input %s", fUseHLTData.Data()));
1475     }
1476   }
1477   AliSysInfo::AddStamp("CreateRawReader");
1478 }
1479
1480 //_____________________________________________________________________________
1481 void AliReconstruction::InitRun(const char* input)
1482 {
1483   // Initialization of raw-reader,
1484   // run number, CDB etc.
1485   AliCodeTimerAuto("",0);
1486   AliSysInfo::AddStamp("Start");
1487
1488   // Initialize raw-reader if any
1489   InitRawReader(input);
1490
1491   // Initialize the CDB storage
1492   InitCDB();
1493
1494   // Set run number in CDBManager (if it is not already set by the user)
1495   if (!SetRunNumberFromData()) {
1496     Abort("SetRunNumberFromData", TSelector::kAbortProcess);
1497     return;
1498   }
1499
1500   if(fFromCDBSnapshot){
1501       AliDebug(2,"Initializing from a CDB snapshot");
1502       if(!AliCDBManager::Instance()->InitFromSnapshot(fSnapshotFileName.Data()))
1503           AliFatal("Was not able to initialize from the snapshot!");
1504   }
1505   // Set CDB lock: from now on it is forbidden to reset the run number
1506   // or the default storage or to activate any further storage!
1507   SetCDBLock();
1508   
1509 }
1510
1511 //_____________________________________________________________________________
1512 void AliReconstruction::Begin(TTree *)
1513 {
1514   // Initialize AlReconstruction before
1515   // going into the event loop
1516   // Should follow the TSelector convention
1517   // i.e. initialize only the object on the client side
1518   AliCodeTimerAuto("",0);
1519
1520   AliReconstruction *reco = NULL;
1521   if (fInput) {
1522     if ((reco = (AliReconstruction*)fInput->FindObject("AliReconstruction"))) {
1523       *this = *reco;
1524     }
1525     AliSysInfo::AddStamp("ReadInputInBegin");
1526   }
1527
1528   // Import ideal TGeo geometry and apply misalignment
1529   if (!gGeoManager) {
1530     TString geom(gSystem->DirName(fGAliceFileName));
1531     geom += "/geometry.root";
1532     AliGeomManager::LoadGeometry(geom.Data());
1533     if (!gGeoManager) {
1534       Abort("LoadGeometry", TSelector::kAbortProcess);
1535       return;
1536     }
1537     AliSysInfo::AddStamp("LoadGeom");
1538     TString detsToCheck=fRunLocalReconstruction;
1539     if(!AliGeomManager::CheckSymNamesLUT(detsToCheck.Data())) {
1540       Abort("CheckSymNamesLUT", TSelector::kAbortProcess);
1541       return;
1542     }
1543     AliSysInfo::AddStamp("CheckGeom");
1544   }
1545
1546   Bool_t toCDBSnapshot=kFALSE;
1547   TString snapshotFileOut(""); // we could use fSnapshotFileName if we are not interested
1548   // in reading from and writing to a snapshot file at the same time
1549   if(TString(gSystem->Getenv("OCDB_SNAPSHOT_CREATE")) == TString("kTRUE")){
1550       toCDBSnapshot=kTRUE;
1551       //fFromCDBSnapshot=kFALSE;
1552       TString snapshotFile(gSystem->Getenv("OCDB_SNAPSHOT_FILENAME"));
1553       if(!(snapshotFile.IsNull() || snapshotFile.IsWhitespace()))
1554           snapshotFileOut = snapshotFile;
1555       else
1556           snapshotFileOut="OCDB.root";
1557   }
1558
1559   if (!MisalignGeometry(fLoadAlignData)) {
1560     Abort("MisalignGeometry", TSelector::kAbortProcess);
1561     return;
1562   }
1563   AliCDBManager::Instance()->UnloadFromCache("GRP/Geometry/Data");
1564   if(!toCDBSnapshot) AliCDBManager::Instance()->UnloadFromCache("*/Align/*");
1565   AliSysInfo::AddStamp("MisalignGeom");
1566
1567   if (!InitGRP()) {
1568     Abort("InitGRP", TSelector::kAbortProcess);
1569     return;
1570   }
1571   AliSysInfo::AddStamp("InitGRP");
1572   if(!toCDBSnapshot) AliCDBManager::Instance()->UnloadFromCache("GRP/Calib/CosmicTriggers");
1573
1574   if(!fFromCDBSnapshot){
1575       if (!LoadCDB()) {
1576           Abort("LoadCDB", TSelector::kAbortProcess);
1577           return;
1578       }
1579       AliSysInfo::AddStamp("LoadCDB");
1580   }
1581
1582   if (!LoadTriggerScalersCDB()) {
1583     Abort("LoadTriggerScalersCDB", TSelector::kAbortProcess);
1584     return;
1585   }
1586   AliSysInfo::AddStamp("LoadTriggerScalersCDB");
1587
1588   if (!LoadCTPTimeParamsCDB()) {
1589     Abort("LoadCTPTimeParamsCDB", TSelector::kAbortProcess);
1590     return;
1591   }
1592   AliSysInfo::AddStamp("LoadCTPTimeParamsCDB");
1593
1594   if (!ReadIntensityInfoCDB()) {
1595     Abort("ReadIntensityInfoCDB", TSelector::kAbortProcess);
1596     return;
1597   }
1598   AliSysInfo::AddStamp("ReadIntensityInfoCDB");
1599
1600   // Read the reconstruction parameters from OCDB
1601   if (!InitRecoParams()) {
1602     AliWarning("Not all detectors have correct RecoParam objects initialized");
1603   }
1604   AliSysInfo::AddStamp("InitRecoParams");
1605
1606   if(toCDBSnapshot)
1607       AliCDBManager::Instance()->DumpToSnapshotFile(snapshotFileOut.Data(),kFALSE);
1608   AliCDBManager::Instance()->UnloadFromCache("*/Align/*");
1609   AliCDBManager::Instance()->UnloadFromCache("GRP/Calib/CosmicTriggers");
1610
1611   if (fInput && gProof) {
1612     if (reco) *reco = *this;
1613
1614     gGeoManager->SetName("Geometry");
1615     gProof->AddInputData(gGeoManager,kTRUE);
1616     gGeoManager = NULL;
1617     gProof->AddInputData(const_cast<TMap*>(AliCDBManager::Instance()->GetEntryCache()),kTRUE);
1618     fInput->Add(new TParameter<Int_t>("RunNumber",AliCDBManager::Instance()->GetRun()));
1619     AliMagF *magFieldMap = (AliMagF*)TGeoGlobalMagField::Instance()->GetField();
1620     magFieldMap->SetName("MagneticFieldMap");
1621     gProof->AddInputData(magFieldMap,kTRUE);
1622     if (fAnalysis) {
1623       fAnalysis->SetName("Analysis");
1624       gProof->AddInputData(fAnalysis,kTRUE);
1625     }  
1626   }
1627
1628 }
1629
1630 //_____________________________________________________________________________
1631 void AliReconstruction::SlaveBegin(TTree*)
1632 {
1633   // Initialization related to run-loader,
1634   // vertexer, trackers, recontructors
1635   // In proof mode it is executed on the slave
1636   AliCodeTimerAuto("",0);
1637
1638   TProofOutputFile *outProofFile = NULL;
1639   if (fInput) {
1640     if (AliDebugLevel() > 0) fInput->Print();
1641     if (AliDebugLevel() > 10) fInput->Dump();
1642     if (AliReconstruction *reco = (AliReconstruction*)fInput->FindObject("AliReconstruction")) {
1643       *this = *reco;
1644     }
1645     if (TGeoManager *tgeo = (TGeoManager*)fInput->FindObject("Geometry")) {
1646       gGeoManager = tgeo;
1647       AliGeomManager::SetGeometry(tgeo);
1648     }
1649     if (TMap *entryCache = (TMap*)fInput->FindObject("CDBEntryCache")) {
1650       Int_t runNumber = -1;
1651       if (TProof::GetParameter(fInput,"RunNumber",runNumber) == 0) {
1652         AliCDBManager *man = AliCDBManager::Instance(entryCache,runNumber);
1653         man->SetCacheFlag(kTRUE);
1654         man->SetLock(kTRUE);
1655         man->Print();
1656       }
1657     }
1658     if (AliMagF *map = (AliMagF*)fInput->FindObject("MagneticFieldMap")) {
1659       AliMagF *newMap = new AliMagF(*map);
1660       if (!newMap->LoadParameterization()) {
1661         Abort("AliMagF::LoadParameterization", TSelector::kAbortProcess);
1662         return;
1663       }
1664       TGeoGlobalMagField::Instance()->SetField(newMap);
1665       TGeoGlobalMagField::Instance()->Lock();
1666     }
1667     if (!fAnalysis) {
1668        // Attempt to get the analysis manager from the input list
1669        fAnalysis = (AliAnalysisManager*)fInput->FindObject("Analysis");
1670        if (fAnalysis) AliInfo("==== Analysis manager retrieved from input list ====");
1671     }   
1672     if (TNamed *outputFileName = (TNamed*)fInput->FindObject("PROOF_OUTPUTFILE"))
1673       fProofOutputFileName = outputFileName->GetTitle();
1674     if (TNamed *outputLocation = (TNamed*)fInput->FindObject("PROOF_OUTPUTFILE_LOCATION"))
1675       fProofOutputLocation = outputLocation->GetTitle();
1676     if (fInput->FindObject("PROOF_OUTPUTFILE_DATASET"))
1677       fProofOutputDataset = kTRUE;
1678     if (TNamed *archiveList = (TNamed*)fInput->FindObject("PROOF_OUTPUTFILE_ARCHIVE"))
1679       fProofOutputArchive = archiveList->GetTitle();
1680     if (!fProofOutputFileName.IsNull() &&
1681         !fProofOutputLocation.IsNull() &&
1682         fProofOutputArchive.IsNull()) {
1683       if (!fProofOutputDataset) {
1684         outProofFile = new TProofOutputFile(fProofOutputFileName.Data(),"M");
1685         outProofFile->SetOutputFileName(Form("%s%s",fProofOutputLocation.Data(),fProofOutputFileName.Data()));
1686       }
1687       else {
1688         outProofFile = new TProofOutputFile(fProofOutputFileName.Data(),"DROV",fProofOutputLocation.Data());
1689       }
1690       if (AliDebugLevel() > 0) outProofFile->Dump();
1691       fOutput->Add(outProofFile);
1692     }
1693     AliSysInfo::AddStamp("ReadInputInSlaveBegin");
1694   }
1695   // Check if analysis was requested in the reconstruction event loop
1696   if (!fAnalysis) {
1697     // Attempt to connect in-memory singleton
1698     fAnalysis = AliAnalysisManager::GetAnalysisManager();
1699     if (fAnalysis) AliInfo(Form("==== Analysis manager <%s> found in memory ====", fAnalysis->GetName()));
1700     // Check if an analysis macro was specified
1701     if (!fAnalysis && !fAnalysisMacro.IsNull()) {
1702       // Run specified analysis macro
1703       gROOT->ProcessLine(Form(".x %s",fAnalysisMacro.Data()));
1704       fAnalysis = AliAnalysisManager::GetAnalysisManager();
1705       if (!fAnalysis) AliError(Form("No analysis manager produced by analysis macro %s", fAnalysisMacro.Data()));
1706       else AliInfo(Form("==== Analysis manager <%s> produced by analysis macro <%s> ====", 
1707                         fAnalysis->GetName(), fAnalysisMacro.Data()));
1708     }
1709   }
1710   
1711   // get the run loader
1712   if (!InitRunLoader()) {
1713     Abort("InitRunLoader", TSelector::kAbortProcess);
1714     return;
1715   }
1716   AliSysInfo::AddStamp("LoadLoader");
1717  
1718   ftVertexer = new AliVertexerTracks(AliTracker::GetBz());
1719
1720   // get trackers
1721   if (!fRunTracking.IsNull() && !CreateTrackers(fRunTracking)) {
1722     Abort("CreateTrackers", TSelector::kAbortProcess);
1723     return;
1724   }      
1725   AliSysInfo::AddStamp("CreateTrackers");
1726
1727   // create the ESD output file and tree
1728   if (!outProofFile) {
1729     ffile = TFile::Open("AliESDs.root", "RECREATE");
1730     ffile->SetCompressionLevel(2);
1731     if (!ffile->IsOpen()) {
1732       Abort("OpenESDFile", TSelector::kAbortProcess);
1733       return;
1734     }
1735   }
1736   else {
1737     AliInfo(Form("Opening output PROOF file: %s/%s",
1738                  outProofFile->GetDir(), outProofFile->GetFileName()));
1739     if (!(ffile = outProofFile->OpenFile("RECREATE"))) {
1740       Abort(Form("Problems opening output PROOF file: %s/%s",
1741                  outProofFile->GetDir(), outProofFile->GetFileName()),
1742             TSelector::kAbortProcess);
1743       return;
1744     }
1745   }
1746
1747   ftree = new TTree("esdTree", "Tree with ESD objects");
1748   fesd = new AliESDEvent();
1749   fesd->CreateStdContent();
1750   // add a so far non-std object to the ESD, this will
1751   // become part of the std content
1752   fesd->AddObject(new AliESDHLTDecision);
1753
1754   fesd->WriteToTree(ftree);
1755   if (fWriteESDfriend) {
1756     ffileF = TFile::Open("AliESDfriends.root", "RECREATE");
1757     ftreeF = new TTree("esdFriendTree", "Tree with ESD Friend objects");
1758     fesdf  = new AliESDfriend();
1759     ftreeF->Branch("ESDfriend.","AliESDfriend", &fesdf);
1760     fesd->AddObject(fesdf);
1761     ffile->cd();
1762   }
1763   ftree->GetUserInfo()->Add(fesd);
1764
1765   fhlttree = new TTree("HLTesdTree", "Tree with HLT ESD objects");
1766   fhltesd = new AliESDEvent();
1767   fhltesd->CreateStdContent();
1768   // read the ESD template from CDB
1769   // HLT is allowed to put non-std content to its ESD, the non-std
1770   // objects need to be created before invocation of WriteToTree in
1771   // order to create all branches. Initialization is done from an
1772   // ESD layout template in CDB
1773   AliCDBManager* man = AliCDBManager::Instance();
1774   AliCDBPath hltESDConfigPath("HLT/Calib/esdLayout");
1775   AliCDBEntry* hltESDConfig=NULL;
1776   if (man->GetId(hltESDConfigPath)!=NULL)
1777     hltESDConfig=man->Get(hltESDConfigPath);
1778   if (!hltESDConfig) {
1779     // try the alternative path
1780     // in Feb 2012 the object has been moved from ConfigHLT to Calib
1781     AliCDBPath hltESDConfigLegacyPath("HLT/ConfigHLT/esdLayout");
1782     AliInfo(Form("can not find HLT ESD config object in %s, trying legacy path %s",
1783                  hltESDConfigPath.GetPath().Data(),
1784                  hltESDConfigLegacyPath.GetPath().Data()));
1785     hltESDConfig=man->Get(hltESDConfigLegacyPath);
1786   }
1787   if (hltESDConfig) {
1788     AliESDEvent* pESDLayout=dynamic_cast<AliESDEvent*>(hltESDConfig->GetObject());
1789     if (pESDLayout) {
1790       // init all internal variables from the list of objects
1791       pESDLayout->GetStdContent();
1792
1793       // copy content and create non-std objects
1794       *fhltesd=*pESDLayout;
1795       fhltesd->Reset();
1796     } else {
1797       AliError(Form("error setting hltEsd layout from %s: invalid object type",
1798                     hltESDConfigPath.GetPath().Data()));
1799     }
1800   }
1801
1802   fhltesd->WriteToTree(fhlttree);
1803   fhlttree->GetUserInfo()->Add(fhltesd);
1804
1805   ProcInfo_t procInfo;
1806   gSystem->GetProcInfo(&procInfo);
1807   AliInfo(Form("Current memory usage %ld %ld", procInfo.fMemResident, procInfo.fMemVirtual));
1808   
1809   //QA
1810   //Initialize the QA and start of cycle 
1811   if (fRunQA || fRunGlobalQA) 
1812     InitQA() ; 
1813
1814   //Initialize the Plane Efficiency framework
1815   if (fRunPlaneEff && !InitPlaneEff()) {
1816     Abort("InitPlaneEff", TSelector::kAbortProcess);
1817     return;
1818   }
1819
1820   if (strcmp(gProgName,"alieve") == 0)
1821     fRunAliEVE = InitAliEVE();
1822   // If we have an analysis manager, connect the AliRecoInputHandler here  
1823   if (fAnalysis) {
1824     if (!dynamic_cast<AliRecoInputHandler*>(fAnalysis->GetInputEventHandler())) {
1825        AliError("Analysis manager used in reconstruction should use AliRecoInputHandler - \
1826                  \n  ->Replacing with AliRecoInputHandler instance.");
1827        delete fAnalysis->GetInputEventHandler();
1828     }
1829     // Set the event and other data pointers
1830     fRecoHandler = new AliRecoInputHandler();
1831     fRecoHandler->Init(ftree, "LOCAL");
1832     fRecoHandler->SetEvent(fesd);
1833     fRecoHandler->SetESDfriend(fesdf);
1834     fRecoHandler->SetHLTEvent(fhltesd);
1835     fRecoHandler->SetHLTTree(fhlttree);
1836     fAnalysis->SetInputEventHandler(fRecoHandler);
1837     // Enter external loop mode
1838     fAnalysis->SetExternalLoop(kTRUE);
1839     // Initialize analysis
1840     fAnalysis->StartAnalysis("local", (TTree*)0);
1841     // Connect ESD tree with the input container
1842     fAnalysis->GetCommonInputContainer()->SetData(ftree);
1843   }  
1844   return;
1845 }
1846
1847 //_____________________________________________________________________________
1848 Bool_t AliReconstruction::Process(Long64_t entry)
1849 {
1850   // run the reconstruction over a single entry
1851   // from the chain with raw data
1852   AliCodeTimerAuto("",0);
1853
1854   TTree *currTree = fChain->GetTree();
1855   AliRawVEvent *event = NULL;
1856   currTree->SetBranchAddress("rawevent",&event);
1857   currTree->GetEntry(entry);
1858   fRawReader = new AliRawReaderRoot(event);
1859   // check if process has enough resources 
1860   if (!HasEnoughResources(entry)) return kFALSE;
1861   fStatus = ProcessEvent(fRunLoader->GetNumberOfEvents());
1862   delete fRawReader;
1863   fRawReader = NULL;
1864   delete event;
1865
1866   return fStatus;
1867 }
1868
1869 //_____________________________________________________________________________
1870 void AliReconstruction::Init(TTree *tree)
1871 {
1872   // Implementation of TSelector::Init()
1873   // method
1874   if (tree == 0) {
1875     AliError("The input tree is not found!");
1876     return;
1877   }
1878   fChain = tree;
1879 }
1880
1881 //_____________________________________________________________________________
1882 Bool_t AliReconstruction::ProcessEvent(Int_t iEvent)
1883 {
1884   // run the reconstruction over a single event
1885   // The event loop is steered in Run method
1886
1887
1888   static Long_t oldMres=0;
1889   static Long_t oldMvir=0;
1890   static Float_t oldCPU=0;
1891   static Long_t aveDMres=0;
1892   static Long_t aveDMvir=0;
1893   static Float_t aveDCPU=0;
1894
1895   AliCodeTimerAuto("",0);
1896
1897   AliESDpid pid;
1898
1899   AliSysInfo::AddStamp(Form("StartEv_%d",iEvent), 0,0,iEvent);
1900
1901   if (iEvent >= fRunLoader->GetNumberOfEvents()) {
1902     fRunLoader->SetEventNumber(iEvent);
1903     if (fRawReader)
1904       fRunLoader->GetHeader()->Reset(fRawReader->GetRunNumber(), 
1905                                      iEvent, iEvent);
1906     fRunLoader->TreeE()->Fill();
1907
1908     if (fRawReader && fRawReader->UseAutoSaveESD())
1909       fRunLoader->TreeE()->AutoSave("SaveSelf");
1910   }
1911
1912   if ((iEvent < fFirstEvent) || ((fLastEvent >= 0) && (iEvent > fLastEvent))) {
1913     return kTRUE;
1914   }
1915
1916
1917   fRunLoader->GetEvent(iEvent);
1918
1919   // Fill Event-info object
1920   GetEventInfo();
1921   fRecoParam.SetEventSpecie(fRunInfo,fEventInfo,fListOfCosmicTriggers);
1922   
1923   ProcInfo_t procInfo;
1924   if(iEvent==fFirstEvent) {
1925     gSystem->GetProcInfo(&procInfo);
1926     oldMres=procInfo.fMemResident;
1927     oldMvir=procInfo.fMemVirtual;
1928     oldCPU=procInfo.fCpuUser+procInfo.fCpuSys;
1929   }
1930   AliInfo(Form("================================= Processing event %d of type %-10s ==================================", iEvent,fRecoParam.PrintEventSpecie()));
1931
1932   AliSysInfo::AddStamp(Form("StartReco_%d",iEvent), 0,0,iEvent);
1933
1934   // Set the reco-params
1935   {
1936     TString detStr = fLoadCDB;
1937     for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
1938       if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
1939       AliReconstructor *reconstructor = GetReconstructor(iDet);
1940       if (reconstructor && fRecoParam.GetDetRecoParamArray(iDet)) {
1941         const AliDetectorRecoParam *par = fRecoParam.GetDetRecoParam(iDet);
1942         reconstructor->SetRecoParam(par);
1943         reconstructor->GetPidSettings(&pid);
1944         reconstructor->SetEventInfo(&fEventInfo);
1945         if (fRunQA) {
1946           AliQAManager::QAManager()->SetEventInfo(&fEventInfo) ;
1947           AliQAManager::QAManager()->SetRecoParam(iDet, par) ; 
1948           if (par) AliQAManager::QAManager()->SetEventSpecie(AliRecoParam::Convert(par->GetEventSpecie())) ;
1949         }
1950       }
1951     }
1952     //
1953     if (fRunQA || fRunGlobalQA) AliQADataMaker::SetEventTrigClasses(fEventInfo.GetTriggerClasses()); // RS: select which histo clones are to be filled
1954     //
1955     if (fRunQA) {
1956       const AliDetectorRecoParam *grppar = fRecoParam.GetDetRecoParam(kNDetectors);
1957       AliQAManager::QAManager()->SetRecoParam(AliQAv1::kGLOBAL, grppar) ; 
1958       AliQAManager::QAManager()->SetEventSpecie(AliRecoParam::Convert(grppar->GetEventSpecie())) ;
1959     }
1960   }
1961
1962     // QA on single raw 
1963   if (fRunQA && IsInTasks(AliQAv1::kRAWS)) {
1964     AliQAManager::QAManager()->SetEventSpecie(fRecoParam.GetEventSpecie()) ;
1965     AliQAManager::QAManager()->RunOneEvent(fRawReader) ;  
1966     AliSysInfo::AddStamp(Form("RawQA_%d",iEvent), 0,0,iEvent);
1967   }
1968     // local single event reconstruction
1969     if (!fRunLocalReconstruction.IsNull()) {
1970       TString detectors=fRunLocalReconstruction;
1971       // run HLT event reconstruction first
1972       // ;-( IsSelected changes the string
1973       if (IsSelected("HLT", detectors) &&
1974           !RunLocalEventReconstruction("HLT")) {
1975         if (fStopOnError) {CleanUp(); return kFALSE;}
1976       }
1977       detectors=fRunLocalReconstruction;
1978       detectors.ReplaceAll("HLT", "");
1979       if (!RunLocalEventReconstruction(detectors)) {
1980         if (fStopOnError) {
1981           CleanUp(); 
1982           return kFALSE;
1983         }
1984       }
1985     }
1986
1987   
1988     // fill Event header information from the RawEventHeader
1989     if (fRawReader){FillRawEventHeaderESD(fesd);}
1990     if (fRawReader){FillRawEventHeaderESD(fhltesd);}
1991
1992     fesd->SetRunNumber(fRunLoader->GetHeader()->GetRun());
1993     fhltesd->SetRunNumber(fRunLoader->GetHeader()->GetRun());
1994     
1995     ((AliESDRun*)fesd->GetESDRun())->SetDetectorsInDAQ(fRunInfo->GetDetectorMask());
1996     ((AliESDRun*)fhltesd->GetESDRun())->SetDetectorsInDAQ(fRunInfo->GetDetectorMask());
1997     ((AliESDRun*)fesd->GetESDRun())->SetDetectorsInReco(AliDAQ::DetectorPatternOffline(fFillESD.Data()));
1998     ((AliESDRun*)fhltesd->GetESDRun())->SetDetectorsInReco(AliDAQ::DetectorPatternOffline(fFillESD.Data()));
1999
2000     fesd->SetEventNumberInFile(fRunLoader->GetHeader()->GetEventNrInRun());
2001     fhltesd->SetEventNumberInFile(fRunLoader->GetHeader()->GetEventNrInRun());
2002
2003     fesd->SetEventSpecie(fRecoParam.GetEventSpecie());
2004     fhltesd->SetEventSpecie(fRecoParam.GetEventSpecie());
2005     
2006     // Set magnetic field from the tracker
2007     fesd->SetMagneticField(AliTracker::GetBz());
2008     fhltesd->SetMagneticField(AliTracker::GetBz());
2009     //
2010     AliESDRun *esdRun,*esdRunH;
2011     esdRun  = (AliESDRun*)fesd->GetESDRun();
2012     esdRunH = (AliESDRun*)fhltesd->GetESDRun();
2013     esdRun->SetBeamEnergyIsSqrtSHalfGeV();
2014     esdRunH->SetBeamEnergyIsSqrtSHalfGeV();
2015     //
2016     for (int ib=2;ib--;) for (int it=2;it--;) {
2017         esdRun->SetMeanIntensity(ib,it, fBeamInt[ib][it]); 
2018         esdRunH->SetMeanIntensity(ib,it, fBeamInt[ib][it]); 
2019       }
2020     //
2021     fesd->SetBeamEnergy(fGRPData->GetBeamEnergy());
2022     fesd->SetBeamType(fGRPData->GetBeamType().Data());
2023     fesd->SetBeamParticle(fGRPData->GetSingleBeamType(0).Atoi(),0);
2024     fesd->SetBeamParticle(fGRPData->GetSingleBeamType(1).Atoi(),1);
2025     fhltesd->SetBeamEnergy(fGRPData->GetBeamEnergy());
2026     fhltesd->SetBeamType(fGRPData->GetBeamType().Data());
2027     fhltesd->SetBeamParticle(fGRPData->GetSingleBeamType(0).Atoi(),0);
2028     fhltesd->SetBeamParticle(fGRPData->GetSingleBeamType(1).Atoi(),1);
2029     //
2030     AliMagF* fld = (AliMagF*)TGeoGlobalMagField::Instance()->GetField();
2031     if (fld) { // set info needed for field initialization
2032       fesd->SetCurrentL3(fld->GetCurrentSol());
2033       fesd->SetCurrentDip(fld->GetCurrentDip());
2034       fesd->SetUniformBMap(fld->IsUniform());
2035       fesd->SetBInfoStored();
2036       //
2037       fhltesd->SetCurrentL3(fld->GetCurrentSol());
2038       fhltesd->SetCurrentDip(fld->GetCurrentDip());
2039       fhltesd->SetUniformBMap(fld->IsUniform());
2040       fhltesd->SetBInfoStored();
2041     }
2042     //
2043     // Set most probable pt, for B=0 tracking
2044     // Get the global reco-params. They are atposition 16 inside the array of detectors in fRecoParam
2045     const AliGRPRecoParam *grpRecoParam = dynamic_cast<const AliGRPRecoParam*>(fRecoParam.GetDetRecoParam(kNDetectors));
2046     if (grpRecoParam) AliExternalTrackParam::SetMostProbablePt(grpRecoParam->GetMostProbablePt());
2047     
2048     // Fill raw-data error log into the ESD
2049     if (fRawReader) FillRawDataErrorLog(iEvent,fesd);
2050
2051     AliSysInfo::AddStamp(Form("FillHeadErrs_%d",iEvent), 0,0,iEvent);
2052
2053     // vertex finder
2054     if (fRunVertexFinder) {
2055       if (!RunVertexFinder(fesd)) {
2056         if (fStopOnError) {CleanUp(); return kFALSE;}
2057       }
2058       AliSysInfo::AddStamp(Form("VtxFinder_%d",iEvent), 0,0,iEvent);
2059     }
2060
2061     // For Plane Efficiency: run the SPD trackleter
2062     if (fRunPlaneEff && fSPDTrackleter) {
2063       if (!RunSPDTrackleting(fesd)) {
2064         if (fStopOnError) {CleanUp(); return kFALSE;}
2065       }
2066       AliSysInfo::AddStamp(Form("TrackletEff_%d",iEvent), 0,0,iEvent);
2067     }
2068
2069     // Muon tracking
2070     if (!fRunTracking.IsNull()) {
2071       if (fRunMuonTracking) {
2072         if (!RunMuonTracking(fesd)) {
2073           if (fStopOnError) {CleanUp(); return kFALSE;}
2074         }
2075       }
2076       AliSysInfo::AddStamp(Form("TrackingMUON_%d",iEvent), 0,0,iEvent);      
2077     }
2078
2079     // barrel tracking
2080     if (!fRunTracking.IsNull()) {
2081       if (!RunTracking(fesd,pid)) {
2082         if (fStopOnError) {CleanUp(); return kFALSE;}
2083       }
2084     }
2085
2086     // fill ESD
2087     if (!fFillESD.IsNull()) {
2088       TString detectors=fFillESD;
2089       // run HLT first and on hltesd
2090       // ;-( IsSelected changes the string
2091       if (IsSelected("HLT", detectors) &&
2092           !FillESD(fhltesd, "HLT")) {
2093         if (fStopOnError) {CleanUp(); return kFALSE;}
2094       }
2095       detectors=fFillESD;
2096       // Temporary fix to avoid problems with HLT that overwrites the offline ESDs
2097       if (detectors.Contains("ALL")) {
2098         detectors="";
2099         for (Int_t idet=0; idet<kNDetectors; ++idet){
2100           detectors += fgkDetectorName[idet];
2101           detectors += " ";
2102         }
2103       }
2104       detectors.ReplaceAll("HLT", "");
2105       if (!FillESD(fesd, detectors)) {
2106         if (fStopOnError) {CleanUp(); return kFALSE;}
2107       }
2108     }
2109     
2110
2111     ffile->cd();
2112
2113     //
2114     // Propagate track to the beam pipe  (if not already done by ITS)
2115     //
2116     const Int_t ntracks = fesd->GetNumberOfTracks();
2117     const Double_t kRadius  = 2.8; //something less than the beam pipe radius
2118
2119     TObjArray trkArray;
2120     UShort_t selectedIdx[ntracks];
2121
2122     for (Int_t itrack=0; itrack<ntracks; itrack++){
2123       const Double_t kMaxStep = 1;   //max step over the material
2124       Bool_t ok;
2125
2126       AliESDtrack *track = fesd->GetTrack(itrack);
2127       if (!track) continue;
2128
2129       AliExternalTrackParam *tpcTrack =
2130            (AliExternalTrackParam *)track->GetTPCInnerParam();
2131       ok = kFALSE;
2132       if (tpcTrack)
2133         ok = AliTracker::
2134           PropagateTrackToBxByBz(tpcTrack,kRadius,track->GetMass(),kMaxStep,kFALSE);
2135
2136       if (ok) {
2137         Int_t n=trkArray.GetEntriesFast();
2138         selectedIdx[n]=track->GetID();
2139         trkArray.AddLast(tpcTrack);
2140       }
2141
2142       //Tracks refitted by ITS should already be at the SPD vertex
2143       if (track->IsOn(AliESDtrack::kITSrefit)) continue;
2144
2145       AliTracker::
2146          PropagateTrackToBxByBz(track,kRadius,track->GetMass(),kMaxStep,kFALSE);
2147       Double_t x[3]; track->GetXYZ(x);
2148       Double_t b[3]; AliTracker::GetBxByBz(x,b);
2149       track->RelateToVertexBxByBz(fesd->GetPrimaryVertexSPD(), b, kVeryBig);
2150
2151     }
2152     AliSysInfo::AddStamp(Form("RelToSPDVtx_%d",iEvent), 0,0,iEvent);      
2153     //
2154     // Improve the reconstructed primary vertex position using the tracks
2155     //
2156     Bool_t runVertexFinderTracks = fRunVertexFinderTracks;
2157     if(fesd->GetPrimaryVertexSPD()) {
2158       TString vtitle = fesd->GetPrimaryVertexSPD()->GetTitle();
2159       if(vtitle.Contains("cosmics")) {
2160         runVertexFinderTracks=kFALSE;
2161       }
2162     }
2163
2164     if (runVertexFinderTracks) {
2165        // TPC + ITS primary vertex
2166        ftVertexer->SetITSMode();
2167        ftVertexer->SetConstraintOff();
2168        // get cuts for vertexer from AliGRPRecoParam
2169        Bool_t constrSPD=kFALSE;
2170        if (grpRecoParam) {
2171          Int_t nCutsVertexer = grpRecoParam->GetVertexerTracksNCuts();
2172          Double_t *cutsVertexer = new Double_t[nCutsVertexer];
2173          grpRecoParam->GetVertexerTracksCutsITS(cutsVertexer,nCutsVertexer);
2174          ftVertexer->SetCuts(cutsVertexer,nCutsVertexer);
2175          delete [] cutsVertexer; cutsVertexer = NULL; 
2176          if(grpRecoParam->GetVertexerTracksConstraintITS()) { 
2177            if(fDiamondProfile && fDiamondProfile->GetXRes()<kRadius){
2178              ftVertexer->SetVtxStart(fDiamondProfile); // apply constraint only if sigmax is smaller than the beam pipe radius 
2179            }else{
2180              if(fDiamondProfileSPD && fDiamondProfileSPD->GetXRes()<kRadius){
2181                ftVertexer->SetVtxStart(fDiamondProfileSPD);
2182                constrSPD=kTRUE;
2183              }
2184            }
2185          } 
2186        }
2187        AliESDVertex *pvtx=ftVertexer->FindPrimaryVertex(fesd);
2188        if (pvtx) {
2189          if(constrSPD){
2190            TString title=pvtx->GetTitle();
2191            title.Append("SPD");
2192            pvtx->SetTitle(title);
2193          }
2194           if (pvtx->GetStatus()) {
2195              fesd->SetPrimaryVertexTracks(pvtx);
2196              for (Int_t i=0; i<ntracks; i++) {
2197                  AliESDtrack *t = fesd->GetTrack(i);
2198                  Double_t x[3]; t->GetXYZ(x);
2199                  Double_t b[3]; AliTracker::GetBxByBz(x,b);
2200                  t->RelateToVertexBxByBz(pvtx, b, kVeryBig);
2201              } 
2202           }
2203           delete pvtx; pvtx=NULL;
2204        }
2205        AliSysInfo::AddStamp(Form("VtxTrk_%d",iEvent), 0,0,iEvent);      
2206
2207        // TPC-only primary vertex
2208        ftVertexer->SetTPCMode();
2209        ftVertexer->SetConstraintOff();
2210        // get cuts for vertexer from AliGRPRecoParam
2211        if (grpRecoParam) {
2212          Int_t nCutsVertexer = grpRecoParam->GetVertexerTracksNCuts();
2213          Double_t *cutsVertexer = new Double_t[nCutsVertexer];
2214          grpRecoParam->GetVertexerTracksCutsTPC(cutsVertexer,nCutsVertexer);
2215          ftVertexer->SetCuts(cutsVertexer,nCutsVertexer);
2216          delete [] cutsVertexer; cutsVertexer = NULL; 
2217          if(fDiamondProfileTPC && grpRecoParam->GetVertexerTracksConstraintTPC()) { 
2218            if(fDiamondProfileTPC->GetXRes()<kRadius) ftVertexer->SetVtxStart(fDiamondProfileTPC); // apply constraint only if sigmax is smaller than the beam pipe radius 
2219          } 
2220        }
2221        pvtx=ftVertexer->FindPrimaryVertex(&trkArray,selectedIdx);
2222        if (pvtx) {
2223           if (pvtx->GetStatus()) {
2224              fesd->SetPrimaryVertexTPC(pvtx);
2225              for (Int_t i=0; i<ntracks; i++) {
2226                  AliESDtrack *t = fesd->GetTrack(i);
2227                  Double_t x[3]; t->GetXYZ(x);
2228                  Double_t b[3]; AliTracker::GetBxByBz(x,b);
2229                  t->RelateToVertexTPCBxByBz(pvtx, b, kVeryBig);
2230              } 
2231           }
2232           delete pvtx; pvtx=NULL;
2233        }
2234        AliSysInfo::AddStamp(Form("VtxTPC_%d",iEvent), 0,0,iEvent);      
2235
2236     }
2237     
2238     if(fDiamondProfile && fDiamondProfile->GetXRes()<kRadius) fesd->SetDiamond(fDiamondProfile);
2239     else fesd->SetDiamond(fDiamondProfileSPD);
2240
2241     if (fRunV0Finder) {
2242        // V0 finding
2243        AliV0vertexer vtxer;
2244        // get cuts for V0vertexer from AliGRPRecoParam
2245        if (grpRecoParam) {
2246          Int_t nCutsV0vertexer = grpRecoParam->GetVertexerV0NCuts();
2247          Double_t cutsV0vertexer[nCutsV0vertexer];
2248          grpRecoParam->GetVertexerV0Cuts(cutsV0vertexer);
2249          vtxer.SetCuts(cutsV0vertexer);
2250        }
2251        vtxer.Tracks2V0vertices(fesd);
2252        AliSysInfo::AddStamp(Form("V0Finder_%d",iEvent), 0,0,iEvent); 
2253
2254        if (fRunCascadeFinder) {
2255           // Cascade finding
2256           AliCascadeVertexer cvtxer;
2257           // get cuts for CascadeVertexer from AliGRPRecoParam
2258           if (grpRecoParam) {
2259             Int_t nCutsCascadeVertexer = grpRecoParam->GetVertexerCascadeNCuts();
2260             Double_t cutsCascadeVertexer[nCutsCascadeVertexer];
2261             grpRecoParam->GetVertexerCascadeCuts(cutsCascadeVertexer);
2262             cvtxer.SetCuts(cutsCascadeVertexer);
2263           }
2264           cvtxer.V0sTracks2CascadeVertices(fesd);
2265           AliSysInfo::AddStamp(Form("CascadeFinder_%d",iEvent), 0,0,iEvent); 
2266        }
2267     }
2268
2269     // AdC+FN
2270     if (fReconstructor[3])
2271       GetReconstructor(3)->FillEventTimeWithTOF(fesd,&pid);
2272
2273     // combined PID
2274     pid.MakePID(fesd);
2275
2276     if (fFillTriggerESD) {
2277       if (!FillTriggerESD(fesd)) {
2278         if (fStopOnError) {CleanUp(); return kFALSE;}
2279       }
2280     }
2281     // Always fill scalers
2282     if (!FillTriggerScalers(fesd)) {
2283        if (fStopOnError) {CleanUp(); return kFALSE;}
2284     }
2285
2286     AliSysInfo::AddStamp(Form("FillVaria_%d",iEvent), 0,0,iEvent); 
2287
2288     // write ESD
2289     UInt_t specie = fesd->GetEventSpecie();
2290     Bool_t keepAll = (specie==AliRecoParam::kCosmic || specie==AliRecoParam::kCalib);
2291     if (fCleanESD && (!keepAll) ) {
2292       CleanESD(fesd);
2293       AliSysInfo::AddStamp(Form("CleanESD_%d",iEvent), 0,0,iEvent); 
2294     }
2295     // 
2296     // RS run updated trackleter: since we want to mark the clusters used by tracks and also mark the 
2297     // tracks interpreted as primary, this step should be done in the very end, when full 
2298     // ESD info is available (particulalry, V0s)
2299     // vertex finder
2300     if (fRunMultFinder) {
2301       if (!RunMultFinder(fesd)) {
2302         if (fStopOnError) {CleanUp(); return kFALSE;}
2303       }
2304       AliSysInfo::AddStamp(Form("MultFinder_%d",iEvent), 0,0,iEvent); 
2305     }
2306
2307   if (fRunQA && IsInTasks(AliQAv1::kESDS)) {
2308     AliQAManager::QAManager()->SetEventSpecie(fRecoParam.GetEventSpecie()) ;
2309     AliQAManager::QAManager()->RunOneEvent(fesd, fhltesd) ; 
2310     AliSysInfo::AddStamp(Form("RunQA_%d",iEvent), 0,0,iEvent); 
2311   }
2312   if (fRunGlobalQA) {
2313     AliQADataMaker *qadm = AliQAManager::QAManager()->GetQADataMaker(AliQAv1::kGLOBAL);
2314     if (qadm)
2315       qadm->SetEventSpecie(fRecoParam.GetEventSpecie()) ;
2316     if (qadm && IsInTasks(AliQAv1::kESDS))
2317       qadm->Exec(AliQAv1::kESDS, fesd);
2318     AliSysInfo::AddStamp(Form("RunGlobQA_%d",iEvent), 0,0,iEvent);     
2319   }
2320
2321   // copy HLT decision from HLTesd to esd
2322   // the most relevant information is stored in a reduced container in the esd,
2323   // while the full information can be found in the HLTesd
2324   TObject* pHLTSrc=fhltesd->FindListObject(AliESDHLTDecision::Name());
2325   TObject* pHLTTgt=fesd->FindListObject(AliESDHLTDecision::Name());
2326   if (pHLTSrc && pHLTTgt) {
2327     pHLTSrc->Copy(*pHLTTgt);
2328   }
2329   //
2330   // Perform analysis of this event if requested
2331   // RS: Should be done before WriteESDfriend, since the latter may clean the esdfriend
2332   if (fAnalysis) {
2333     fRecoHandler->BeginEvent(iEvent);
2334     fAnalysis->ExecAnalysis();
2335     fRecoHandler->FinishEvent();
2336     AliSysInfo::AddStamp(Form("Analysis_%d",iEvent), 0,0,iEvent);     
2337   }  
2338   //
2339   if (fWriteESDfriend) {
2340     fesd->GetESDfriend(fesdf);
2341     AliSysInfo::AddStamp(Form("CreateFriend_%d",iEvent), 0,0,iEvent);     
2342   
2343   }
2344   //
2345   ftree->Fill();
2346   AliSysInfo::AddStamp(Form("ESDFill_%d",iEvent), 0,0,iEvent);     
2347   //
2348   if (fWriteESDfriend) {
2349     WriteESDfriend();
2350     AliSysInfo::AddStamp(Form("WriteFriend_%d",iEvent), 0,0,iEvent);     
2351   }
2352   //
2353   //
2354   // Auto-save the ESD tree in case of prompt reco @P2
2355   if (fRawReader && fRawReader->UseAutoSaveESD()) {
2356     ftree->AutoSave("SaveSelf");
2357     if (fWriteESDfriend) ftreeF->AutoSave("SaveSelf");
2358   }
2359     // write HLT ESD
2360     fhlttree->Fill();
2361
2362     // call AliEVE
2363     if (fRunAliEVE) RunAliEVE();
2364     //
2365     fesd->Reset();
2366     fhltesd->Reset();
2367     if (fWriteESDfriend) {
2368       fesdf->~AliESDfriend();
2369       new (fesdf) AliESDfriend(); // Reset...
2370     }
2371  
2372     gSystem->GetProcInfo(&procInfo);
2373     Long_t dMres=(procInfo.fMemResident-oldMres)/1024;
2374     Long_t dMvir=(procInfo.fMemVirtual-oldMvir)/1024;
2375     Float_t dCPU=procInfo.fCpuUser+procInfo.fCpuSys-oldCPU;
2376     aveDMres+=(dMres-aveDMres)/(iEvent-fFirstEvent+1);
2377     aveDMvir+=(dMvir-aveDMvir)/(iEvent-fFirstEvent+1);
2378     aveDCPU+=(dCPU-aveDCPU)/(iEvent-fFirstEvent+1);
2379     AliInfo(Form("======================= End Event %d: Res %ld(%3ld <%3ld>) Vir %ld(%3ld <%3ld>) CPU %5.2f <%5.2f> ===================",
2380                  iEvent, procInfo.fMemResident/1024, dMres, aveDMres, procInfo.fMemVirtual/1024, dMvir, aveDMvir, dCPU, aveDCPU));
2381     oldMres=procInfo.fMemResident;
2382     oldMvir=procInfo.fMemVirtual;
2383     oldCPU=procInfo.fCpuUser+procInfo.fCpuSys;
2384   
2385     fEventInfo.Reset();
2386     for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2387       if (fReconstructor[iDet]) {
2388         fReconstructor[iDet]->SetRecoParam(NULL);
2389         fReconstructor[iDet]->SetEventInfo(NULL);
2390       }
2391       if (fTracker[iDet]) fTracker[iDet]->SetEventInfo(NULL);
2392     }
2393         
2394   if (fRunQA || fRunGlobalQA) 
2395     AliQAManager::QAManager()->Increment() ; 
2396
2397   DeleteRecPoints(fDeleteRecPoints);
2398   DeleteDigits(fDeleteDigits);
2399   //
2400   return kTRUE;
2401 }
2402
2403 //_____________________________________________________________________________
2404 void AliReconstruction::SlaveTerminate()
2405 {
2406   // Finalize the run on the slave side
2407   // Called after the exit
2408   // from the event loop
2409   AliCodeTimerAuto("",0);
2410   // If analysis was done during reconstruction, we need to call SlaveTerminate for it
2411   if (fAnalysis) {
2412      fAnalysis->PackOutput(fOutput);
2413      fAnalysis->SetSkipTerminate(kTRUE);
2414      fAnalysis->Terminate();
2415   }   
2416
2417   if (fIsNewRunLoader) { // galice.root didn't exist
2418     fRunLoader->WriteHeader("OVERWRITE");
2419     fRunLoader->WriteTrigger("OVERWRITE");
2420     fRunLoader->CdGAFile();
2421     fRunLoader->Write(0, TObject::kOverwrite);
2422   }
2423
2424   const TMap *cdbMap = AliCDBManager::Instance()->GetStorageMap();       
2425   const TList *cdbList = AliCDBManager::Instance()->GetRetrievedIds();   
2426                  
2427    TMap *cdbMapCopy = new TMap(cdbMap->GetEntries());    
2428    cdbMapCopy->SetOwner(1);      
2429    cdbMapCopy->SetName("cdbMap");        
2430    TIter iter(cdbMap->GetTable());       
2431          
2432    TPair* pair = 0;      
2433    while((pair = dynamic_cast<TPair*> (iter.Next()))){   
2434          TObjString* keyStr = dynamic_cast<TObjString*> (pair->Key());   
2435          TObjString* valStr = dynamic_cast<TObjString*> (pair->Value());
2436          if (keyStr && valStr)
2437            cdbMapCopy->Add(new TObjString(keyStr->GetName()), new TObjString(valStr->GetName()));        
2438    }     
2439          
2440    TList *cdbListCopy = new TList();     
2441    cdbListCopy->SetOwner(1);     
2442    cdbListCopy->SetName("cdbList");      
2443          
2444    TIter iter2(cdbList);         
2445          
2446         AliCDBId* id=0;
2447         while((id = dynamic_cast<AliCDBId*> (iter2.Next()))){    
2448          cdbListCopy->Add(new TObjString(id->ToString().Data()));        
2449    }     
2450          
2451    ftree->GetUserInfo()->Add(cdbMapCopy);        
2452    ftree->GetUserInfo()->Add(cdbListCopy);
2453
2454    // Add the AliRoot version that created this file
2455    TString sVersion("aliroot ");
2456    sVersion += ALIROOT_SVN_BRANCH;
2457    sVersion += ":";
2458    sVersion += ALIROOT_SVN_REVISION;
2459    sVersion += "; root ";
2460    sVersion += ROOT_SVN_BRANCH;
2461    sVersion += ":";
2462    sVersion += ROOT_SVN_REVISION;
2463    sVersion += "; metadata ";
2464    sVersion += gSystem->Getenv("PRODUCTION_METADATA");
2465                     
2466
2467    TNamed * alirootVersion = new TNamed("alirootVersion",sVersion.Data());
2468    ftree->GetUserInfo()->Add(alirootVersion); // The list becomes owner of alirootVersion
2469
2470   ffile->cd();
2471
2472   // we want to have only one tree version number
2473   ftree->Write(ftree->GetName(),TObject::kOverwrite);
2474   fhlttree->Write(fhlttree->GetName(),TObject::kOverwrite);
2475
2476   if (fWriteESDfriend) {
2477     ffileF->cd();
2478     ftreeF->Write(ftreeF->GetName(),TObject::kOverwrite);
2479   }
2480
2481 // Finish with Plane Efficiency evaluation: before of CleanUp !!!
2482   if (fRunPlaneEff && !FinishPlaneEff()) {
2483    AliWarning("Finish PlaneEff evaluation failed");
2484   }
2485
2486   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2487     if (fReconstructor[iDet]) fReconstructor[iDet]->Terminate();
2488   }
2489   // End of cycle for the in-loop  
2490
2491   if (fRunQA || fRunGlobalQA) {
2492     AliQAManager::QAManager()->EndOfCycle() ;
2493     if (fInput &&
2494         !fProofOutputLocation.IsNull() &&
2495         fProofOutputArchive.IsNull() &&
2496         !fProofOutputDataset) {
2497       TString qaOutputFile(Form("%sMerged.%s.Data.root",
2498                                 fProofOutputLocation.Data(),
2499                                 AliQAv1::GetQADataFileName()));
2500       TProofOutputFile *qaProofFile = new TProofOutputFile(Form("Merged.%s.Data.root",
2501                                                                 AliQAv1::GetQADataFileName()));
2502       qaProofFile->SetOutputFileName(qaOutputFile.Data());
2503       if (AliDebugLevel() > 0) qaProofFile->Dump();
2504       fOutput->Add(qaProofFile);
2505       MergeQA(qaProofFile->GetFileName());
2506     }
2507     else {
2508       MergeQA();
2509     }
2510   }
2511
2512   gROOT->cd();
2513   CleanUp();
2514
2515   if (fInput) {
2516     if (!fProofOutputFileName.IsNull() &&
2517         !fProofOutputLocation.IsNull() &&
2518         fProofOutputDataset &&
2519         !fProofOutputArchive.IsNull()) {
2520       TProofOutputFile *zipProofFile = new TProofOutputFile(fProofOutputFileName.Data(),
2521                                                             "DROV",
2522                                                             fProofOutputLocation.Data());
2523       if (AliDebugLevel() > 0) zipProofFile->Dump();
2524       fOutput->Add(zipProofFile);
2525       TString fileList(fProofOutputArchive.Data());
2526       fileList.ReplaceAll(","," ");
2527       TString command;
2528 #if ROOT_SVN_REVISION >= 30174
2529       command.Form("zip -n root %s/%s %s",zipProofFile->GetDir(kTRUE),zipProofFile->GetFileName(),fileList.Data());
2530 #else
2531       command.Form("zip -n root %s/%s %s",zipProofFile->GetDir(),zipProofFile->GetFileName(),fileList.Data());
2532 #endif
2533       AliInfo(Form("Executing: %s",command.Data()));
2534       gSystem->Exec(command.Data());
2535     }
2536   }
2537 }
2538     
2539 //_____________________________________________________________________________
2540 void AliReconstruction::Terminate()
2541 {
2542   // Create tags for the events in the ESD tree (the ESD tree is always present)
2543   // In case of empty events the tags will contain dummy values
2544   AliCodeTimerAuto("",0);
2545
2546   // Do not call the ESD tag creator in case of PROOF-based reconstruction
2547   if (!fInput) {
2548     AliESDTagCreator *esdtagCreator = new AliESDTagCreator();
2549     esdtagCreator->CreateESDTags(fFirstEvent,fLastEvent,fGRPData, AliQAv1::Instance()->GetQA(), AliQAv1::Instance()->GetEventSpecies(), AliQAv1::kNDET, AliRecoParam::kNSpecies);
2550     delete esdtagCreator;
2551   }
2552
2553   // Cleanup of CDB manager: cache and active storages!
2554   AliCDBManager::Instance()->ClearCache();
2555 }
2556
2557 //_____________________________________________________________________________
2558 Bool_t AliReconstruction::RunLocalEventReconstruction(const TString& detectors)
2559 {
2560 // run the local reconstruction
2561
2562   static Int_t eventNr=0;
2563   AliCodeTimerAuto("",0)
2564
2565   TString detStr = detectors;
2566   // execute HLT reconstruction first since other detector reconstruction
2567   // might depend on HLT data
2568   // key 'HLT' is removed from detStr by IsSelected
2569   if (!IsSelected("HLT", detStr)) {
2570     AliReconstructor* reconstructor = GetReconstructor(kNDetectors-1);
2571     if (reconstructor) {
2572       // there is no AliLoader for HLT, see
2573       // https://savannah.cern.ch/bugs/?35473
2574       AliInfo("running reconstruction for HLT");
2575       if (fRawReader) {
2576         AliInfo("reconstructor->Reconstruct(fRawReader, NULL)");
2577         reconstructor->Reconstruct(fRawReader, NULL);
2578       } 
2579       else {
2580         AliInfo("reconstructor->Reconstruct(dummy, NULL)");
2581         TTree* dummy=NULL;
2582         reconstructor->Reconstruct(dummy, NULL);
2583       }
2584     }
2585     AliSysInfo::AddStamp(Form("LRecHLT_%d",eventNr), -1,1,eventNr);
2586   }
2587
2588   AliInfo(Form("kNDetectors = %d",kNDetectors));
2589
2590   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2591     if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
2592     AliDebug(1, Form("Detector: %s", fgkDetectorName[iDet]));
2593     AliReconstructor* reconstructor = GetReconstructor(iDet);
2594     if (!reconstructor) continue;
2595     AliLoader* loader = fLoader[iDet];
2596     if (!loader) {
2597       AliWarning(Form("No loader is defined for %s!",fgkDetectorName[iDet]));
2598       continue;
2599     }
2600     // conversion of digits
2601     if (fRawReader && reconstructor->HasDigitConversion()) {
2602       AliInfo(Form("converting raw data digits into root objects for %s", 
2603                    fgkDetectorName[iDet]));
2604 //      AliCodeTimerAuto(Form("converting raw data digits into root objects for %s", 
2605 //                            fgkDetectorName[iDet]),0);
2606       loader->LoadDigits("update");
2607       loader->CleanDigits();
2608       loader->MakeDigitsContainer();
2609       TTree* digitsTree = loader->TreeD();
2610       reconstructor->ConvertDigits(fRawReader, digitsTree);
2611       loader->WriteDigits("OVERWRITE");
2612       loader->UnloadDigits();
2613     }
2614     // local reconstruction
2615     AliInfo(Form("running reconstruction for %s", fgkDetectorName[iDet]));
2616     //AliCodeTimerAuto(Form("running reconstruction for %s", fgkDetectorName[iDet]),0);
2617     AliDebug(1, "Loading Rec Points");
2618     loader->LoadRecPoints("update");
2619     AliDebug(1, "Cleaning Rec Points");
2620     loader->CleanRecPoints();
2621     AliDebug(1, "Making Rec Points Container");
2622     loader->MakeRecPointsContainer();
2623     TTree* clustersTree = loader->TreeR();
2624     if (fRawReader && !reconstructor->HasDigitConversion()) {
2625       reconstructor->Reconstruct(fRawReader, clustersTree);
2626     } 
2627     else {
2628       AliDebug(1, "Loading Digits");
2629       loader->LoadDigits("read");
2630       TTree* digitsTree = loader->TreeD();
2631       AliDebug(1, Form("Digits Tree = %p",digitsTree));
2632       if (!digitsTree) {
2633         AliError(Form("Can't get the %s digits tree", fgkDetectorName[iDet]));
2634         if (fStopOnError) 
2635           return kFALSE;
2636       } 
2637       else {
2638         AliDebug(1, "Digits -> Clusters");
2639         reconstructor->Reconstruct(digitsTree, clustersTree);
2640         if (fRunQA && IsInTasks(AliQAv1::kDIGITSR)) {
2641           AliQAManager::QAManager()->SetEventSpecie(fRecoParam.GetEventSpecie()) ;
2642           AliQAManager::QAManager()->RunOneEventInOneDetector(iDet, digitsTree) ; 
2643         }
2644       }
2645       loader->UnloadDigits();
2646     }
2647     if (fRunQA && IsInTasks(AliQAv1::kRECPOINTS)) {
2648       AliQAManager::QAManager()->SetEventSpecie(fRecoParam.GetEventSpecie()) ;
2649       AliQAManager::QAManager()->RunOneEventInOneDetector(iDet, clustersTree) ; 
2650     }
2651     loader->WriteRecPoints("OVERWRITE");
2652     loader->UnloadRecPoints();
2653     AliSysInfo::AddStamp(Form("LRec%s_%d",fgkDetectorName[iDet],eventNr), iDet,1,eventNr);
2654   }
2655   if (!IsSelected("CTP", detStr)) AliDebug(10,"No CTP");
2656   if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
2657     AliError(Form("the following detectors were not found: %s",
2658                   detStr.Data()));
2659     if (fStopOnError) 
2660       return kFALSE;
2661   }
2662   eventNr++;
2663   return kTRUE;
2664 }
2665 //_____________________________________________________________________________
2666 Bool_t AliReconstruction::RunSPDTrackleting(AliESDEvent*& esd)
2667 {
2668 // run the SPD trackleting (for SPD efficiency purpouses)
2669
2670   AliCodeTimerAuto("",0)
2671
2672   Double_t vtxPos[3] = {0, 0, 0};
2673   Double_t vtxErr[3] = {0.0, 0.0, 0.0};
2674 /*
2675   TArrayF m
2676 /
2677 cVertex(3);
2678   // if(MC)
2679   if (fRunLoader->GetHeader() && fRunLoader->GetHeader()->GenEventHeader()) {
2680     fRunLoader->GetHeader()->GenEventHeader()->PrimaryVertex(mcVertex);
2681     for (Int_t i = 0; i < 3; i++) vtxPos[i] = mcVertex[i];
2682   }
2683 */
2684   const AliESDVertex *vertex = esd->GetVertex();
2685   if(!vertex){
2686     AliWarning("Vertex not found");
2687     return kFALSE;
2688   }
2689   vertex->GetXYZ(vtxPos);
2690   vertex->GetSigmaXYZ(vtxErr);
2691   if (fSPDTrackleter) {
2692     AliInfo("running the SPD Trackleter for Plane Efficiency Evaluation");
2693
2694     // load clusters
2695     fLoader[0]->LoadRecPoints("read");
2696     TTree* tree = fLoader[0]->TreeR();
2697     if (!tree) {
2698       AliError("Can't get the ITS cluster tree");
2699       return kFALSE;
2700     }
2701     fSPDTrackleter->LoadClusters(tree);
2702     fSPDTrackleter->SetVertex(vtxPos, vtxErr);
2703     // run trackleting
2704     if (fSPDTrackleter->Clusters2Tracks(esd) != 0) {
2705       AliWarning("AliITSTrackleterSPDEff Clusters2Tracks failed");
2706      // fLoader[0]->UnloadRecPoints();
2707       return kFALSE;
2708     }
2709 //fSPDTrackleter->UnloadRecPoints();
2710   } else {
2711     AliWarning("SPDTrackleter not available");
2712     return kFALSE;
2713   }
2714   return kTRUE;
2715 }
2716
2717 //_____________________________________________________________________________
2718 Bool_t AliReconstruction::RunVertexFinder(AliESDEvent*& esd)
2719 {
2720 // run the barrel tracking
2721
2722   AliCodeTimerAuto("",0)
2723
2724   AliVertexer *vertexer = CreateVertexer();
2725   if (!vertexer) return kFALSE;
2726
2727   AliInfo(Form("running the ITS vertex finder: %s",vertexer->ClassName()));
2728   AliESDVertex* vertex = NULL;
2729   if (fLoader[0]) {
2730     fLoader[0]->LoadRecPoints();
2731     TTree* cltree = fLoader[0]->TreeR();
2732     if (cltree) {
2733       if(fDiamondProfileSPD) vertexer->SetVtxStart(fDiamondProfileSPD);
2734       vertex = vertexer->FindVertexForCurrentEvent(cltree);
2735     }
2736     else {
2737       AliError("Can't get the ITS cluster tree");
2738     }
2739     fLoader[0]->UnloadRecPoints();
2740   }
2741   else {
2742     AliError("Can't get the ITS loader");
2743   }
2744   if(!vertex){
2745     AliWarning("Vertex not found");
2746     vertex = new AliESDVertex();
2747     vertex->SetName("default");
2748   }
2749   else {
2750     vertex->SetName("reconstructed");
2751   }
2752
2753   Double_t vtxPos[3];
2754   Double_t vtxErr[3];
2755   vertex->GetXYZ(vtxPos);
2756   vertex->GetSigmaXYZ(vtxErr);
2757
2758   esd->SetPrimaryVertexSPD(vertex);
2759   AliESDVertex *vpileup = NULL;
2760   Int_t novertices = 0;
2761   vpileup = vertexer->GetAllVertices(novertices);
2762   if(novertices>1){
2763     for (Int_t kk=1; kk<novertices; kk++)esd->AddPileupVertexSPD(&vpileup[kk]);
2764   }
2765   /*
2766   // if SPD multiplicity has been determined, it is stored in the ESD
2767   AliMultiplicity *mult = vertexer->GetMultiplicity();
2768   if(mult)esd->SetMultiplicity(mult);
2769   */
2770   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2771     if (fTracker[iDet]) fTracker[iDet]->SetVertex(vtxPos, vtxErr);
2772   }  
2773   delete vertex;
2774
2775   delete vertexer;
2776
2777   return kTRUE;
2778 }
2779
2780 //_____________________________________________________________________________
2781 Bool_t AliReconstruction::RunMultFinder(AliESDEvent*& esd)
2782 {
2783   // run the trackleter for multiplicity study
2784
2785   AliCodeTimerAuto("",0)
2786
2787   AliTrackleter *trackleter = CreateMultFinder();
2788   if (!trackleter) return kFALSE;
2789
2790   AliInfo(Form("running the ITS multiplicity finder: %s",trackleter->ClassName()));
2791
2792   if (fLoader[0]) {
2793     fLoader[0]->LoadRecPoints();
2794     TTree* cltree = fLoader[0]->TreeR();
2795     if (cltree) {
2796       trackleter->Reconstruct(esd,cltree);
2797       AliMultiplicity *mult = trackleter->GetMultiplicity();
2798       if(mult) esd->SetMultiplicity(mult);
2799     }
2800     else {
2801       AliError("Can't get the ITS cluster tree");
2802     }
2803     fLoader[0]->UnloadRecPoints();
2804   }
2805   else {
2806     AliError("Can't get the ITS loader");
2807   }
2808
2809   delete trackleter;
2810
2811   return kTRUE;
2812 }
2813
2814 //_____________________________________________________________________________
2815 Bool_t AliReconstruction::RunHLTTracking(AliESDEvent*& esd)
2816 {
2817 // run the HLT barrel tracking
2818
2819   AliCodeTimerAuto("",0)
2820
2821   if (!fRunLoader) {
2822     AliError("Missing runLoader!");
2823     return kFALSE;
2824   }
2825
2826   AliInfo("running HLT tracking");
2827
2828   // Get a pointer to the HLT reconstructor
2829   AliReconstructor *reconstructor = GetReconstructor(kNDetectors-1);
2830   if (!reconstructor) return kFALSE;
2831
2832   // TPC + ITS
2833   for (Int_t iDet = 1; iDet >= 0; iDet--) {
2834     TString detName = fgkDetectorName[iDet];
2835     AliDebug(1, Form("%s HLT tracking", detName.Data()));
2836     reconstructor->SetOption(detName.Data());
2837     AliTracker *tracker = reconstructor->CreateTracker();
2838     if (!tracker) {
2839       AliWarning(Form("couldn't create a HLT tracker for %s", detName.Data()));
2840       if (fStopOnError) return kFALSE;
2841       continue;
2842     }
2843     Double_t vtxPos[3];
2844     Double_t vtxErr[3]={0.005,0.005,0.010};
2845     const AliESDVertex *vertex = esd->GetVertex();
2846     vertex->GetXYZ(vtxPos);
2847     tracker->SetVertex(vtxPos,vtxErr);
2848     if(iDet != 1) {
2849       fLoader[iDet]->LoadRecPoints("read");
2850       TTree* tree = fLoader[iDet]->TreeR();
2851       if (!tree) {
2852         AliError(Form("Can't get the %s cluster tree", detName.Data()));
2853         return kFALSE;
2854       }
2855       tracker->LoadClusters(tree);
2856     }
2857     if (tracker->Clusters2Tracks(esd) != 0) {
2858       AliError(Form("HLT %s Clusters2Tracks failed", fgkDetectorName[iDet]));
2859       return kFALSE;
2860     }
2861     if(iDet != 1) {
2862       tracker->UnloadClusters();
2863     }
2864     delete tracker;
2865   }
2866
2867   return kTRUE;
2868 }
2869
2870 //_____________________________________________________________________________
2871 Bool_t AliReconstruction::RunMuonTracking(AliESDEvent*& esd)
2872 {
2873 // run the muon spectrometer tracking
2874
2875   AliCodeTimerAuto("",0)
2876
2877   if (!fRunLoader) {
2878     AliError("Missing runLoader!");
2879     return kFALSE;
2880   }
2881   Int_t iDet =  GetDetIndex("MUON"); // for MUON
2882
2883   // Get a pointer to the MUON reconstructor
2884   AliReconstructor *reconstructor = GetReconstructor(iDet);
2885   if (!reconstructor) return kFALSE;
2886
2887   
2888   TString detName = fgkDetectorName[iDet];
2889   AliDebug(1, Form("%s tracking", detName.Data()));
2890   AliTracker *tracker =  reconstructor->CreateTracker();
2891   if (!tracker) {
2892     AliWarning(Form("couldn't create a tracker for %s", detName.Data()));
2893     return kFALSE;
2894   }
2895      
2896   // read RecPoints
2897   fLoader[iDet]->LoadRecPoints("read");  
2898
2899   tracker->LoadClusters(fLoader[iDet]->TreeR());
2900   
2901   Int_t rv = tracker->Clusters2Tracks(esd);
2902   
2903   fLoader[iDet]->UnloadRecPoints();
2904
2905   tracker->UnloadClusters();
2906   
2907   if ( rv )
2908   {
2909     AliError(Form("%s Clusters2Tracks failed", fgkDetectorName[iDet]));
2910     return kFALSE;
2911   }
2912   
2913   return kTRUE;
2914 }
2915
2916
2917 //_____________________________________________________________________________
2918 Bool_t AliReconstruction::RunTracking(AliESDEvent*& esd,AliESDpid &PID)
2919 {
2920 // run the barrel tracking
2921   static Int_t eventNr=0;
2922   AliCodeTimerAuto("",0)
2923
2924   AliInfo("running tracking");
2925
2926   // Set the event info which is used
2927   // by the trackers in order to obtain
2928   // information about read-out detectors,
2929   // trigger etc.
2930   AliDebug(1, "Setting event info");
2931   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2932     if (!fTracker[iDet]) continue;
2933     fTracker[iDet]->SetEventInfo(&fEventInfo);
2934   }
2935
2936   //Fill the ESD with the T0 info (will be used by the TOF) 
2937   if (fReconstructor[11] && fLoader[11]) {
2938     fLoader[11]->LoadRecPoints("READ");
2939     TTree *treeR = fLoader[11]->TreeR();
2940     if (treeR) {
2941       GetReconstructor(11)->FillESD((TTree *)NULL,treeR,esd);
2942     }
2943   }
2944
2945   // pass 1: TPC + ITS inwards
2946   for (Int_t iDet = 1; iDet >= 0; iDet--) {
2947     if (!fTracker[iDet]) continue;
2948     AliDebug(1, Form("%s tracking", fgkDetectorName[iDet]));
2949
2950     // load clusters
2951     fLoader[iDet]->LoadRecPoints("read");
2952     AliSysInfo::AddStamp(Form("RLoadCluster%s_%d",fgkDetectorName[iDet],eventNr),iDet,1, eventNr);
2953     TTree* tree = fLoader[iDet]->TreeR();
2954     if (!tree) {
2955       AliError(Form("Can't get the %s cluster tree", fgkDetectorName[iDet]));
2956       return kFALSE;
2957     }
2958     fTracker[iDet]->LoadClusters(tree);
2959     AliSysInfo::AddStamp(Form("TLoadCluster%s_%d",fgkDetectorName[iDet],eventNr), iDet,2, eventNr);
2960     // run tracking
2961     if (fTracker[iDet]->Clusters2Tracks(esd) != 0) {
2962       AliError(Form("%s Clusters2Tracks failed", fgkDetectorName[iDet]));
2963       return kFALSE;
2964     }
2965     AliSysInfo::AddStamp(Form("Tracking0%s_%d",fgkDetectorName[iDet],eventNr), iDet,3,eventNr);
2966     // preliminary PID in TPC needed by the ITS tracker
2967     if (iDet == 1) {
2968       GetReconstructor(1)->FillESD((TTree*)NULL, (TTree*)NULL, esd);
2969       PID.MakePID(esd,kTRUE);
2970       AliSysInfo::AddStamp(Form("MakePID0%s_%d",fgkDetectorName[iDet],eventNr), iDet,4,eventNr);
2971     } 
2972   }
2973
2974   // pass 2: ALL backwards
2975
2976   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
2977     if (!fTracker[iDet]) continue;
2978     AliDebug(1, Form("%s back propagation", fgkDetectorName[iDet]));
2979
2980     // load clusters
2981     if (iDet > 1) {     // all except ITS, TPC
2982       TTree* tree = NULL;
2983       fLoader[iDet]->LoadRecPoints("read");
2984       AliSysInfo::AddStamp(Form("RLoadCluster0%s_%d",fgkDetectorName[iDet],eventNr), iDet,1, eventNr);
2985       tree = fLoader[iDet]->TreeR();
2986       if (!tree) {
2987         AliError(Form("Can't get the %s cluster tree", fgkDetectorName[iDet]));
2988         return kFALSE;
2989       }
2990       fTracker[iDet]->LoadClusters(tree); 
2991       AliSysInfo::AddStamp(Form("TLoadCluster0%s_%d",fgkDetectorName[iDet],eventNr), iDet,2, eventNr);
2992     }
2993
2994     // run tracking
2995     if (iDet>1) // start filling residuals for the "outer" detectors
2996       if (fRunGlobalQA) {
2997         AliTracker::SetFillResiduals(fRecoParam.GetEventSpecie(), kTRUE);     
2998         TObjArray ** arr = AliTracker::GetResidualsArray() ; 
2999         if (arr) {
3000           AliRecoParam::EventSpecie_t es=fRecoParam.GetEventSpecie();
3001           TObjArray * elem = arr[AliRecoParam::AConvert(es)];
3002           if ( elem && (! elem->At(0)) ) {
3003             AliQADataMaker *qadm = AliQAManager::QAManager()->GetQADataMaker(AliQAv1::kGLOBAL);
3004             if (qadm) qadm->InitRecPointsForTracker() ; 
3005           }
3006         }
3007         //      AliSysInfo::AddStamp(Form("QAInitResid%s_%d",fgkDetectorName[iDet],eventNr), iDet,0, eventNr);
3008       }
3009     if (fTracker[iDet]->PropagateBack(esd) != 0) {
3010       AliError(Form("%s backward propagation failed", fgkDetectorName[iDet]));
3011       //      return kFALSE;
3012     }
3013     AliSysInfo::AddStamp(Form("Tracking1%s_%d",fgkDetectorName[iDet],eventNr), iDet,3, eventNr);
3014
3015     // unload clusters
3016     if (iDet > 3) {     // all except ITS, TPC, TRD and TOF
3017       fTracker[iDet]->UnloadClusters();
3018       fLoader[iDet]->UnloadRecPoints();
3019     }
3020     // updated PID in TPC needed by the ITS tracker -MI
3021     if (iDet == 1) {
3022       //GetReconstructor(1)->FillESD((TTree*)NULL, (TTree*)NULL, esd);
3023       //AliESDpid::MakePID(esd);
3024       PID.MakePID(esd,kTRUE);
3025       AliSysInfo::AddStamp(Form("MakePID1%s_%d",fgkDetectorName[iDet],eventNr), iDet,4,eventNr);
3026     }
3027
3028   }
3029   //stop filling residuals for the "outer" detectors
3030   if (fRunGlobalQA) AliTracker::SetFillResiduals(fRecoParam.GetEventSpecie(), kFALSE);     
3031
3032   // pass 3: TRD + TPC + ITS refit inwards
3033
3034   for (Int_t iDet = 2; iDet >= 0; iDet--) {
3035     if (!fTracker[iDet]) continue;
3036     AliDebug(1, Form("%s inward refit", fgkDetectorName[iDet]));
3037
3038     // run tracking
3039     if (iDet<2) // start filling residuals for TPC and ITS
3040       if (fRunGlobalQA) {
3041         AliTracker::SetFillResiduals(fRecoParam.GetEventSpecie(), kTRUE);     
3042         TObjArray ** arr = AliTracker::GetResidualsArray() ; 
3043         if (arr) {
3044           AliRecoParam::EventSpecie_t es=fRecoParam.GetEventSpecie();
3045           TObjArray * elem = arr[AliRecoParam::AConvert(es)];
3046           if ( elem && (! elem->At(0)) ) {
3047             AliQADataMaker *qadm = AliQAManager::QAManager()->GetQADataMaker(AliQAv1::kGLOBAL);
3048             if (qadm) qadm->InitRecPointsForTracker() ; 
3049           }
3050         }
3051       }
3052     
3053     if (fTracker[iDet]->RefitInward(esd) != 0) {
3054       AliError(Form("%s inward refit failed", fgkDetectorName[iDet]));
3055       //      return kFALSE;
3056     }
3057     // run postprocessing
3058     if (fTracker[iDet]->PostProcess(esd) != 0) {
3059       AliError(Form("%s postprocessing failed", fgkDetectorName[iDet]));
3060       //      return kFALSE;
3061     }
3062     AliSysInfo::AddStamp(Form("Tracking2%s_%d",fgkDetectorName[iDet],eventNr), iDet,3, eventNr);
3063   }
3064
3065   // write space-points to the ESD in case alignment data output
3066   // is switched on
3067   if (fWriteAlignmentData) {
3068     WriteAlignmentData(esd);
3069     AliSysInfo::AddStamp(Form("WrtAlignData_%d",eventNr), 0,0, eventNr);
3070   }
3071   
3072   for (Int_t iDet = 3; iDet >= 0; iDet--) {
3073     if (!fTracker[iDet]) continue;
3074     // unload clusters
3075     fTracker[iDet]->UnloadClusters();
3076     AliSysInfo::AddStamp(Form("TUnloadCluster%s_%d",fgkDetectorName[iDet],eventNr), iDet,4, eventNr);
3077     fLoader[iDet]->UnloadRecPoints();
3078     AliSysInfo::AddStamp(Form("RUnloadCluster%s_%d",fgkDetectorName[iDet],eventNr), iDet,5, eventNr);
3079   }
3080   // stop filling residuals for TPC and ITS
3081   if (fRunGlobalQA) AliTracker::SetFillResiduals(fRecoParam.GetEventSpecie(), kFALSE);     
3082
3083   eventNr++;
3084   return kTRUE;
3085 }
3086
3087 //_____________________________________________________________________________
3088 Bool_t AliReconstruction::CleanESD(AliESDEvent *esd){
3089   //
3090   // Remove the data which are not needed for the physics analysis.
3091   //
3092
3093   Int_t nTracks=esd->GetNumberOfTracks();
3094   Int_t nV0s=esd->GetNumberOfV0s();
3095   AliInfo
3096   (Form("Number of ESD tracks and V0s before cleaning: %d %d",nTracks,nV0s));
3097
3098   Float_t cleanPars[]={fV0DCAmax,fV0CsPmin,fDmax,fZmax};
3099   Bool_t rc=esd->Clean(cleanPars);
3100
3101   nTracks=esd->GetNumberOfTracks();
3102   nV0s=esd->GetNumberOfV0s();
3103   AliInfo
3104   (Form("Number of ESD tracks and V0s after cleaning %d %d",nTracks,nV0s));
3105
3106   return rc;
3107 }
3108
3109 //_____________________________________________________________________________
3110 Bool_t AliReconstruction::FillESD(AliESDEvent*& esd, const TString& detectors)
3111 {
3112 // fill the event summary data
3113
3114   AliCodeTimerAuto("",0)
3115     static Int_t eventNr=0; 
3116   TString detStr = detectors;
3117   
3118   AliSysInfo::AddStamp(Form("FillESDb%d",eventNr), -19,-19, eventNr);
3119   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
3120   if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
3121     AliReconstructor* reconstructor = GetReconstructor(iDet);
3122     if (!reconstructor) continue;
3123     AliDebug(1, Form("filling ESD for %s", fgkDetectorName[iDet]));
3124     TTree* clustersTree = NULL;
3125     if (fLoader[iDet]) {
3126       fLoader[iDet]->LoadRecPoints("read");
3127       clustersTree = fLoader[iDet]->TreeR();
3128       if (!clustersTree) {
3129         AliError(Form("Can't get the %s clusters tree", 
3130                       fgkDetectorName[iDet]));
3131         if (fStopOnError) return kFALSE;
3132       }
3133     }
3134     if (fRawReader && !reconstructor->HasDigitConversion()) {
3135       reconstructor->FillESD(fRawReader, clustersTree, esd);
3136     } else {
3137       TTree* digitsTree = NULL;
3138       if (fLoader[iDet]) {
3139         fLoader[iDet]->LoadDigits("read");
3140         digitsTree = fLoader[iDet]->TreeD();
3141         if (!digitsTree) {
3142           AliError(Form("Can't get the %s digits tree", 
3143                         fgkDetectorName[iDet]));
3144           if (fStopOnError) return kFALSE;
3145         }
3146       }
3147       reconstructor->FillESD(digitsTree, clustersTree, esd);
3148       if (fLoader[iDet]) fLoader[iDet]->UnloadDigits();
3149     }
3150     if (fLoader[iDet]) {
3151       fLoader[iDet]->UnloadRecPoints();
3152     }
3153   }
3154   
3155   if (!IsSelected("CTP", detStr)) AliDebug(10,"No CTP");
3156   if ((detStr.CompareTo("ALL") != 0) && !detStr.IsNull()) {
3157     AliError(Form("the following detectors were not found: %s", 
3158                   detStr.Data()));
3159     if (fStopOnError) return kFALSE;
3160   }
3161   AliSysInfo::AddStamp(Form("FillESDe%d",eventNr), -20,-20, eventNr);
3162   eventNr++;
3163   return kTRUE;
3164 }
3165
3166 //_____________________________________________________________________________
3167 Bool_t AliReconstruction::FillTriggerESD(AliESDEvent*& esd)
3168 {
3169   // Reads the trigger decision which is
3170   // stored in Trigger.root file and fills
3171   // the corresponding esd entries
3172
3173   AliCodeTimerAuto("",0)
3174   
3175   AliInfo("Filling trigger information into the ESD");
3176
3177   if (fRawReader) {
3178     AliCTPRawStream input(fRawReader);
3179     if (!input.Next()) {
3180       AliWarning("No valid CTP (trigger) DDL raw data is found ! The trigger info is taken from the event header!");
3181     }
3182     else {
3183       if (esd->GetTriggerMask() != input.GetClassMask())
3184         AliError(Form("Invalid trigger pattern found in CTP raw-data: %llx %llx",
3185                       input.GetClassMask(),esd->GetTriggerMask()));
3186       if (esd->GetOrbitNumber() != input.GetOrbitID())
3187         AliError(Form("Invalid orbit id found in CTP raw-data: %x %x",
3188                       input.GetOrbitID(),esd->GetOrbitNumber()));
3189       if (esd->GetBunchCrossNumber() != input.GetBCID())
3190         AliError(Form("Invalid bunch-crossing id found in CTP raw-data: %x %x",
3191                       input.GetBCID(),esd->GetBunchCrossNumber()));
3192       AliESDHeader* esdheader = esd->GetHeader();
3193       esdheader->SetL0TriggerInputs(input.GetL0Inputs());
3194       esdheader->SetL1TriggerInputs(input.GetL1Inputs());
3195       esdheader->SetL2TriggerInputs(input.GetL2Inputs());
3196       // IR
3197       //      UInt_t orbit=input.GetOrbitID();
3198       for(Int_t i=0 ; i<input.GetNIRs() ; i++ ) {
3199         esdheader->AddTriggerIR(input.GetIR(i));
3200       }
3201        AliCentralTrigger* rlCTP = fRunLoader->GetTrigger();
3202        if (rlCTP) {
3203          rlCTP->SetL0TriggerInputs(input.GetL0Inputs());
3204          rlCTP->SetL1TriggerInputs(input.GetL1Inputs());
3205          rlCTP->SetL2TriggerInputs(input.GetL2Inputs());
3206        }
3207     }
3208     if (fIsNewRunLoader) fRunLoader->TreeCT()->Fill();
3209   }
3210   return kTRUE;
3211 }
3212 //_____________________________________________________________________________
3213 Bool_t AliReconstruction::FillTriggerScalers(AliESDEvent*& esd)
3214 {
3215   //Scalers
3216   //fRunScalers->Print();
3217   if(fRunScalers && fRunScalers->CheckRunScalers()){
3218      AliTimeStamp* timestamp = new AliTimeStamp(esd->GetOrbitNumber(), esd->GetPeriodNumber(), esd->GetBunchCrossNumber());
3219      //AliTimeStamp* timestamp = new AliTimeStamp(10308000, 0, (ULong64_t)486238);
3220      AliESDHeader* esdheader = fesd->GetHeader();
3221      for(Int_t i=0;i<50;i++){
3222           if((1ull<<i) & esd->GetTriggerMask()){
3223           AliTriggerScalersESD* scalesd = fRunScalers->GetScalersForEventClass( timestamp, i+1);
3224           if(scalesd)esdheader->SetTriggerScalersRecord(scalesd);
3225         }
3226      }
3227      const AliTriggerScalersRecordESD* scalrecEvent = fRunScalers->GetScalersDeltaForEvent( timestamp);
3228      const AliTriggerScalersRecordESD* scalrecRun = fRunScalers->GetScalersDeltaForRun();
3229      if (scalrecEvent) esdheader->SetTriggerScalersDeltaEvent(scalrecEvent);
3230      if (scalrecRun) esdheader->SetTriggerScalersDeltaRun(scalrecRun);
3231   }
3232   return kTRUE;
3233 }
3234 //_____________________________________________________________________________
3235 Bool_t AliReconstruction::FillRawEventHeaderESD(AliESDEvent*& esd)
3236 {
3237   // 
3238   // Filling information from RawReader Header
3239   // 
3240
3241   if (!fRawReader) return kFALSE;
3242
3243   AliInfo("Filling information from RawReader Header");
3244
3245   esd->SetBunchCrossNumber(fRawReader->GetBCID());
3246   esd->SetOrbitNumber(fRawReader->GetOrbitID());
3247   esd->SetPeriodNumber(fRawReader->GetPeriod());
3248
3249   esd->SetTimeStamp(fRawReader->GetTimestamp());  
3250   esd->SetEventType(fRawReader->GetType());
3251
3252   return kTRUE;
3253 }
3254
3255
3256 //_____________________________________________________________________________
3257 Bool_t AliReconstruction::IsSelected(TString detName, TString& detectors) const
3258 {
3259 // check whether detName is contained in detectors
3260 // if yes, it is removed from detectors
3261
3262   // check if all detectors are selected
3263   if ((detectors.CompareTo("ALL") == 0) ||
3264       detectors.BeginsWith("ALL ") ||
3265       detectors.EndsWith(" ALL") ||
3266       detectors.Contains(" ALL ")) {
3267     detectors = "ALL";
3268     return kTRUE;
3269   }
3270
3271   // search for the given detector
3272   Bool_t result = kFALSE;
3273   if ((detectors.CompareTo(detName) == 0) ||
3274       detectors.BeginsWith(detName+" ") ||
3275       detectors.EndsWith(" "+detName) ||
3276       detectors.Contains(" "+detName+" ")) {
3277     detectors.ReplaceAll(detName, "");
3278     result = kTRUE;
3279   }
3280
3281   // clean up the detectors string
3282   while (detectors.Contains("  ")) detectors.ReplaceAll("  ", " ");
3283   while (detectors.BeginsWith(" ")) detectors.Remove(0, 1);
3284   while (detectors.EndsWith(" ")) detectors.Remove(detectors.Length()-1, 1);
3285
3286   return result;
3287 }
3288
3289 //_____________________________________________________________________________
3290 Bool_t AliReconstruction::InitRunLoader()
3291 {
3292 // get or create the run loader
3293
3294   if (gAlice) delete gAlice;
3295   gAlice = NULL;
3296
3297   TFile *gafile = TFile::Open(fGAliceFileName.Data());
3298   //  if (!gSystem->AccessPathName(fGAliceFileName.Data())) { // galice.root exists
3299   if (gafile) { // galice.root exists
3300     gafile->Close();
3301     delete gafile;
3302
3303     // load all base libraries to get the loader classes
3304     TString libs = gSystem->GetLibraries();
3305     for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
3306       TString detName = fgkDetectorName[iDet];
3307       if (detName == "HLT") continue;
3308       if (libs.Contains("lib" + detName + "base.so")) continue;
3309       gSystem->Load("lib" + detName + "base.so");
3310     }
3311     fRunLoader = AliRunLoader::Open(fGAliceFileName.Data());
3312     if (!fRunLoader) {
3313       AliError(Form("no run loader found in file %s", fGAliceFileName.Data()));
3314       CleanUp();
3315       return kFALSE;
3316     }
3317
3318     fRunLoader->CdGAFile();
3319     fRunLoader->LoadgAlice();
3320
3321     //PH This is a temporary fix to give access to the kinematics
3322     //PH that is needed for the labels of ITS clusters
3323     fRunLoader->LoadHeader();
3324     fRunLoader->LoadKinematics();
3325
3326   } else {               // galice.root does not exist
3327     if (!fRawReader) {
3328       AliError(Form("the file %s does not exist", fGAliceFileName.Data()));
3329     }
3330     fRunLoader = AliRunLoader::Open(fGAliceFileName.Data(),
3331                                     AliConfig::GetDefaultEventFolderName(),
3332                                     "recreate");
3333     if (!fRunLoader) {
3334       AliError(Form("could not create run loader in file %s", 
3335                     fGAliceFileName.Data()));
3336       CleanUp();
3337       return kFALSE;
3338     }
3339     fIsNewRunLoader = kTRUE;
3340     fRunLoader->MakeTree("E");
3341     fRunLoader->MakeTree("GG");
3342
3343     if (fNumberOfEventsPerFile > 0)
3344       fRunLoader->SetNumberOfEventsPerFile(fNumberOfEventsPerFile);
3345     else
3346       fRunLoader->SetNumberOfEventsPerFile((UInt_t)-1);
3347   }
3348
3349   return kTRUE;
3350 }
3351
3352 //_____________________________________________________________________________
3353 AliReconstructor* AliReconstruction::GetReconstructor(Int_t iDet)
3354 {
3355 // get the reconstructor object and the loader for a detector
3356
3357   if (fReconstructor[iDet]) {
3358     if (fRecoParam.GetDetRecoParamArray(iDet) && !AliReconstructor::GetRecoParam(iDet)) {
3359       const AliDetectorRecoParam *par = fRecoParam.GetDetRecoParam(iDet);
3360       fReconstructor[iDet]->SetRecoParam(par);
3361       fReconstructor[iDet]->SetRunInfo(fRunInfo);
3362     }
3363     return fReconstructor[iDet];
3364   }
3365
3366   // load the reconstructor object
3367   TPluginManager* pluginManager = gROOT->GetPluginManager();
3368   TString detName = fgkDetectorName[iDet];
3369   TString recName = "Ali" + detName + "Reconstructor";
3370
3371   if (!fIsNewRunLoader && !fRunLoader->GetLoader(detName+"Loader") && (detName != "HLT")) return NULL;
3372
3373   AliReconstructor* reconstructor = NULL;
3374   // first check if a plugin is defined for the reconstructor
3375   TPluginHandler* pluginHandler = 
3376     pluginManager->FindHandler("AliReconstructor", detName);
3377   // if not, add a plugin for it
3378   if (!pluginHandler) {
3379     AliDebug(1, Form("defining plugin for %s", recName.Data()));
3380     TString libs = gSystem->GetLibraries();
3381     if (libs.Contains("lib" + detName + "base.so") ||
3382         (gSystem->Load("lib" + detName + "base.so") >= 0)) {
3383       pluginManager->AddHandler("AliReconstructor", detName, 
3384                                 recName, detName + "rec", recName + "()");
3385     } else {
3386       pluginManager->AddHandler("AliReconstructor", detName, 
3387                                 recName, detName, recName + "()");
3388     }
3389     pluginHandler = pluginManager->FindHandler("AliReconstructor", detName);
3390   }
3391   if (pluginHandler && (pluginHandler->LoadPlugin() == 0)) {
3392     reconstructor = (AliReconstructor*) pluginHandler->ExecPlugin(0);
3393   }
3394
3395    // check if the upgrade reconstructor should be used instead of the standard one
3396   if(fUpgradeMask[iDet]) {
3397     if(reconstructor) delete reconstructor;
3398     TClass *cl = new TClass(Form("Ali%sUpgradeReconstructor",fgkDetectorName[iDet]));
3399     reconstructor = (AliReconstructor*)(cl->New());
3400    }
3401
3402   if (reconstructor) {
3403     TObject* obj = fOptions.FindObject(detName.Data());
3404     if (obj) reconstructor->SetOption(obj->GetTitle());
3405     reconstructor->SetRunInfo(fRunInfo);
3406     reconstructor->Init();
3407     fReconstructor[iDet] = reconstructor;
3408   }
3409
3410   // get or create the loader
3411   if (detName != "HLT") {
3412     fLoader[iDet] = fRunLoader->GetLoader(detName + "Loader");
3413     if (!fLoader[iDet]) {
3414       AliConfig::Instance()
3415         ->CreateDetectorFolders(fRunLoader->GetEventFolder(), 
3416                                 detName, detName);
3417       // first check if a plugin is defined for the loader
3418       pluginHandler = 
3419         pluginManager->FindHandler("AliLoader", detName);
3420       // if not, add a plugin for it
3421       if (!pluginHandler) {
3422         TString loaderName = "Ali" + detName + "Loader";
3423         AliDebug(1, Form("defining plugin for %s", loaderName.Data()));
3424         pluginManager->AddHandler("AliLoader", detName, 
3425                                   loaderName, detName + "base", 
3426                                   loaderName + "(const char*, TFolder*)");
3427         pluginHandler = pluginManager->FindHandler("AliLoader", detName);
3428       }
3429       if (pluginHandler && (pluginHandler->LoadPlugin() == 0)) {
3430         fLoader[iDet] = 
3431           (AliLoader*) pluginHandler->ExecPlugin(2, detName.Data(), 
3432                                                  fRunLoader->GetEventFolder());
3433       }
3434       if (!fLoader[iDet]) {   // use default loader
3435         fLoader[iDet] = new AliLoader(detName, fRunLoader->GetEventFolder());
3436       }
3437       if (!fLoader[iDet]) {
3438         AliWarning(Form("couldn't get loader for %s", detName.Data()));
3439         if (fStopOnError) return NULL;
3440       } else {
3441         fRunLoader->AddLoader(fLoader[iDet]);
3442         fRunLoader->CdGAFile();
3443         if (gFile && !gFile->IsWritable()) gFile->ReOpen("UPDATE");
3444         fRunLoader->Write(0, TObject::kOverwrite);
3445       }
3446     }
3447   }
3448       
3449   if (fRecoParam.GetDetRecoParamArray(iDet) && !AliReconstructor::GetRecoParam(iDet)) {
3450     const AliDetectorRecoParam *par = fRecoParam.GetDetRecoParam(iDet);
3451     if (reconstructor) {
3452       reconstructor->SetRecoParam(par);
3453       reconstructor->SetRunInfo(fRunInfo);
3454     }
3455   }
3456   return reconstructor;
3457 }
3458
3459 //_____________________________________________________________________________
3460 AliVertexer* AliReconstruction::CreateVertexer()
3461 {
3462 // create the vertexer
3463 // Please note that the caller is the owner of the
3464 // vertexer
3465
3466   AliVertexer* vertexer = NULL;
3467   AliReconstructor* itsReconstructor = GetReconstructor(0);
3468   if (itsReconstructor && ((fRunLocalReconstruction.Contains("ITS")) || 
3469                            fRunTracking.Contains("ITS") || fFillESD.Contains("ITS") )) {
3470     vertexer = itsReconstructor->CreateVertexer();
3471   }
3472   if (!vertexer) {
3473     AliWarning("couldn't create a vertexer for ITS");
3474   }
3475
3476   return vertexer;
3477 }
3478
3479 //_____________________________________________________________________________
3480 AliTrackleter* AliReconstruction::CreateMultFinder()
3481 {
3482 // create the ITS trackleter for mult. estimation
3483 // Please note that the caller is the owner of the
3484 // trackleter
3485
3486   AliTrackleter* trackleter = NULL;
3487   AliReconstructor* itsReconstructor = GetReconstructor(0);
3488   if (itsReconstructor && ((fRunLocalReconstruction.Contains("ITS")) || 
3489                            fRunTracking.Contains("ITS") || fFillESD.Contains("ITS") )) {
3490     trackleter = itsReconstructor->CreateMultFinder();
3491   }
3492   else {
3493     AliWarning("ITS is not in reconstruction, switching off RunMultFinder");
3494     fRunMultFinder = kFALSE;
3495   }
3496
3497   return trackleter;
3498 }
3499
3500 //_____________________________________________________________________________
3501 Bool_t AliReconstruction::CreateTrackers(const TString& detectors)
3502 {
3503 // create the trackers
3504         AliInfo("Creating trackers");
3505
3506   TString detStr = detectors;
3507   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
3508     if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
3509     AliReconstructor* reconstructor = GetReconstructor(iDet);
3510     if (!reconstructor) continue;
3511     TString detName = fgkDetectorName[iDet];
3512     if (detName == "HLT") {
3513       fRunHLTTracking = kTRUE;
3514       continue;
3515     }
3516     if (detName == "MUON") {
3517       fRunMuonTracking = kTRUE;
3518       continue;
3519     }
3520
3521     fTracker[iDet] = reconstructor->CreateTracker();
3522     if (!fTracker[iDet] && (iDet < 7)) {
3523       AliWarning(Form("couldn't create a tracker for %s", detName.Data()));
3524       if (fStopOnError) return kFALSE;
3525     }
3526     AliSysInfo::AddStamp(Form("LTracker%s",fgkDetectorName[iDet]), iDet,0);
3527   }
3528
3529   return kTRUE;
3530 }
3531
3532 //_____________________________________________________________________________
3533 void AliReconstruction::CleanUp()
3534 {
3535 // delete trackers and the run loader and close and delete the file
3536 /*
3537   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
3538     delete fReconstructor[iDet];
3539     fReconstructor[iDet] = NULL;
3540     fLoader[iDet] = NULL;
3541     delete fTracker[iDet];
3542     fTracker[iDet] = NULL;
3543   }
3544 */
3545
3546   delete fRunInfo;
3547   fRunInfo = NULL;
3548
3549   delete fSPDTrackleter;
3550   fSPDTrackleter = NULL;
3551
3552   delete ftVertexer;
3553   ftVertexer = NULL;
3554   
3555   delete fRunLoader;
3556   fRunLoader = NULL;
3557   delete fRawReader;
3558   fRawReader = NULL;
3559   delete fParentRawReader;
3560   fParentRawReader=NULL;
3561
3562   if (ffile) {
3563     ffile->Close();
3564     delete ffile;
3565     ffile = NULL;
3566   }
3567
3568   if (AliQAManager::QAManager())
3569     AliQAManager::QAManager()->ShowQA() ; 
3570   //  AliQAManager::Destroy() ;
3571   delete fAnalysis; 
3572   fAnalysis = NULL;
3573 }
3574
3575 void AliReconstruction::WriteAlignmentData(AliESDEvent* esd)
3576 {
3577   // Write space-points which are then used in the alignment procedures
3578   // For the moment only ITS, TPC, TRD and TOF
3579
3580   Int_t ntracks = esd->GetNumberOfTracks();
3581   for (Int_t itrack = 0; itrack < ntracks; itrack++)
3582     {
3583       AliESDtrack *track = esd->GetTrack(itrack);
3584       Int_t nsp = 0;
3585       Int_t idx[200];
3586       for (Int_t i=0; i<200; ++i) idx[i] = -1; //PH avoid uninitialized values
3587       for (Int_t iDet = 5; iDet >= 0; iDet--) {// TOF, TRD, TPC, ITS clusters
3588           nsp += (iDet==GetDetIndex("TRD")) ? track->GetTRDntracklets():track->GetNcls(iDet);
3589
3590           if (iDet==GetDetIndex("ITS")) { // ITS "extra" clusters
3591              track->GetClusters(iDet,idx);
3592              for (Int_t i=6; i<12; i++) if(idx[i] >= 0) nsp++;
3593           }  
3594       }
3595
3596       if (nsp) {
3597         AliTrackPointArray *sp = new AliTrackPointArray(nsp);
3598         track->SetTrackPointArray(sp);
3599         Int_t isptrack = 0;
3600         for (Int_t iDet = 5; iDet >= 0; iDet--) {
3601           AliTracker *tracker = fTracker[iDet];
3602           if (!tracker) continue;
3603           Int_t nspdet = (iDet==GetDetIndex("TRD")) ? track->GetTRDtracklets(idx):track->GetClusters(iDet,idx);
3604
3605           if (iDet==GetDetIndex("ITS")) // ITS "extra" clusters             
3606              for (Int_t i=6; i<12; i++) if(idx[i] >= 0) nspdet++;
3607
3608           if (nspdet <= 0) continue;
3609           AliTrackPoint p;
3610           Int_t isp = 0;
3611           Int_t isp2 = 0;
3612           while (isp2 < nspdet) {
3613             Bool_t isvalid=kTRUE;
3614
3615             Int_t index=idx[isp++];
3616             if (index < 0) continue;
3617
3618             TString dets = fgkDetectorName[iDet];
3619             if ((fUseTrackingErrorsForAlignment.CompareTo(dets) == 0) ||
3620             fUseTrackingErrorsForAlignment.BeginsWith(dets+" ") ||
3621             fUseTrackingErrorsForAlignment.EndsWith(" "+dets) ||
3622             fUseTrackingErrorsForAlignment.Contains(" "+dets+" ")) {
3623               isvalid = tracker->GetTrackPointTrackingError(index,p,track);
3624             } else {
3625               isvalid = tracker->GetTrackPoint(index,p); 
3626             } 
3627             isp2++;
3628             if (!isvalid) continue;
3629             if (iDet==GetDetIndex("ITS") && (isp-1)>=6) p.SetExtra();
3630             sp->AddPoint(isptrack,&p); isptrack++;
3631           }
3632         }       
3633       }
3634     }
3635 }
3636
3637 //_____________________________________________________________________________
3638 void AliReconstruction::FillRawDataErrorLog(Int_t iEvent, AliESDEvent* esd)
3639 {
3640   // The method reads the raw-data error log
3641   // accumulated within the rawReader.
3642   // It extracts the raw-data errors related to
3643   // the current event and stores them into
3644   // a TClonesArray inside the esd object.
3645
3646   if (!fRawReader) return;
3647
3648   for(Int_t i = 0; i < fRawReader->GetNumberOfErrorLogs(); i++) {
3649
3650     AliRawDataErrorLog *log = fRawReader->GetErrorLog(i);
3651     if (!log) continue;
3652     if (iEvent != log->GetEventNumber()) continue;
3653
3654     esd->AddRawDataErrorLog(log);
3655   }
3656
3657 }
3658
3659 //_____________________________________________________________________________
3660 // void AliReconstruction::CheckQA()
3661 // {
3662 // check the QA of SIM for this run and remove the detectors 
3663 // with status Fatal
3664   
3665 //      TString newRunLocalReconstruction ; 
3666 //      TString newRunTracking ;
3667 //      TString newFillESD ;
3668 //       
3669 //      for (Int_t iDet = 0; iDet < AliQAv1::kNDET; iDet++) {
3670 //              TString detName(AliQAv1::GetDetName(iDet)) ;
3671 //              AliQAv1 * qa = AliQAv1::Instance(AliQAv1::DETECTORINDEX_t(iDet)) ;       
3672 //      if ( qa->IsSet(AliQAv1::DETECTORINDEX_t(iDet), AliQAv1::kSIM, specie, AliQAv1::kFATAL)) {
3673 //        AliInfo(Form("QA status for %s %s in Hits and/or SDIGITS  and/or Digits was Fatal; No reconstruction performed", 
3674 //                   detName.Data(), AliRecoParam::GetEventSpecieName(es))) ;
3675 //                      } else {
3676 //                      if ( fRunLocalReconstruction.Contains(AliQAv1::GetDetName(iDet)) || 
3677 //                                      fRunLocalReconstruction.Contains("ALL") )  {
3678 //                              newRunLocalReconstruction += detName ; 
3679 //                              newRunLocalReconstruction += " " ;                      
3680 //                      }
3681 //                      if ( fRunTracking.Contains(AliQAv1::GetDetName(iDet)) || 
3682 //                                      fRunTracking.Contains("ALL") )  {
3683 //                              newRunTracking += detName ; 
3684 //                              newRunTracking += " " ;                         
3685 //                      }
3686 //                      if ( fFillESD.Contains(AliQAv1::GetDetName(iDet)) || 
3687 //                                      fFillESD.Contains("ALL") )  {
3688 //                              newFillESD += detName ; 
3689 //                              newFillESD += " " ;                     
3690 //                      }
3691 //              }
3692 //      }
3693 //      fRunLocalReconstruction = newRunLocalReconstruction ; 
3694 //      fRunTracking            = newRunTracking ; 
3695 //      fFillESD                = newFillESD ; 
3696 // }
3697
3698 //_____________________________________________________________________________
3699 Int_t AliReconstruction::GetDetIndex(const char* detector)
3700 {
3701   // return the detector index corresponding to detector
3702   Int_t index = -1 ; 
3703   for (index = 0; index < kNDetectors ; index++) {
3704     if ( strcmp(detector, fgkDetectorName[index]) == 0 )
3705         break ; 
3706   }     
3707   return index ; 
3708 }
3709 //_____________________________________________________________________________
3710 Bool_t AliReconstruction::FinishPlaneEff() {
3711  //
3712  // Here execute all the necessary operationis, at the end of the tracking phase,
3713  // in case that evaluation of PlaneEfficiencies was required for some detector.
3714  // E.g., write into a DataBase file the PlaneEfficiency which have been evaluated.
3715  //
3716  // This Preliminary version works only FOR ITS !!!!!
3717  // other detectors (TOF,TRD, etc. have to develop their specific codes)
3718  //
3719  //  Input: none
3720  //  Return: kTRUE if all operations have been done properly, kFALSE otherwise
3721  //
3722  Bool_t ret=kFALSE;
3723  TString detStr = fLoadCDB;
3724  //for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) {
3725  for (Int_t iDet = 0; iDet < 1; iDet++) { // for the time being only ITS
3726    if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
3727    if(fTracker[iDet] && fTracker[iDet]->GetPlaneEff()) {
3728       AliPlaneEff *planeeff=fTracker[iDet]->GetPlaneEff();
3729       TString name=planeeff->GetName();
3730       name+=".root";
3731       TFile* pefile = TFile::Open(name, "RECREATE");
3732       ret=(Bool_t)planeeff->Write();
3733       pefile->Close();
3734       if(planeeff->GetCreateHistos()) {
3735         TString hname=planeeff->GetName();
3736         hname+="Histo.root";
3737         ret*=planeeff->WriteHistosToFile(hname,"RECREATE");
3738       }
3739    }
3740    if(fSPDTrackleter) {
3741      AliPlaneEff *planeeff=fSPDTrackleter->GetPlaneEff();
3742       TString name="AliITSPlaneEffSPDtracklet.root";
3743       TFile* pefile = TFile::Open(name, "RECREATE");
3744       ret=(Bool_t)planeeff->Write();
3745       pefile->Close();
3746       AliESDEvent *dummy=NULL;
3747       ret=(Bool_t)fSPDTrackleter->PostProcess(dummy); // take care of writing other files
3748    }
3749  }
3750  return ret;
3751 }
3752 //_____________________________________________________________________________
3753 Bool_t AliReconstruction::InitPlaneEff() {
3754 //
3755  // Here execute all the necessary operations, before of the tracking phase,
3756  // for the evaluation of PlaneEfficiencies, in case required for some detectors.
3757  // E.g., read from a DataBase file a first evaluation of the PlaneEfficiency
3758  // which should be updated/recalculated.
3759  //
3760  // This Preliminary version will work only FOR ITS !!!!!
3761  // other detectors (TOF,TRD, etc. have to develop their specific codes)
3762  //
3763  //  Input: none
3764  //  Return: kTRUE if all operations have been done properly, kFALSE otherwise
3765  //
3766
3767   fSPDTrackleter = NULL;
3768   TString detStr = fLoadCDB;
3769   if (IsSelected(fgkDetectorName[0], detStr)) {
3770     AliReconstructor* itsReconstructor = GetReconstructor(0);
3771     if (itsReconstructor) {
3772       fSPDTrackleter = itsReconstructor->CreateTrackleter(); // this is NULL unless required in RecoParam
3773     }
3774     if (fSPDTrackleter) {
3775       AliInfo("Trackleter for SPD has been created");
3776     }
3777   }
3778  return kTRUE;
3779 }
3780
3781 //_____________________________________________________________________________
3782 Bool_t AliReconstruction::InitAliEVE()
3783 {
3784   // This method should be called only in case 
3785   // AliReconstruction is run
3786   // within the alieve environment.
3787   // It will initialize AliEVE in a way
3788   // so that it can visualize event processed
3789   // by AliReconstruction.
3790   // The return flag shows whenever the
3791   // AliEVE initialization was successful or not.
3792
3793   TString macroStr(gSystem->Getenv("ALIEVE_ONLINE_MACRO"));
3794
3795   if (macroStr.IsNull())
3796     macroStr.Form("%s/EVE/macros/alieve_online.C",gSystem->ExpandPathName("$ALICE_ROOT"));
3797
3798   AliInfo(Form("Loading AliEVE macro: %s",macroStr.Data()));
3799
3800   if (gROOT->LoadMacro(macroStr.Data()) != 0) return kFALSE;
3801
3802   gROOT->ProcessLine("if (!AliEveEventManager::GetMaster()){new AliEveEventManager();AliEveEventManager::GetMaster()->AddNewEventCommand(\"alieve_online_on_new_event()\");gEve->AddEvent(AliEveEventManager::GetMaster());};");
3803   gROOT->ProcessLine("alieve_online_init()");
3804
3805   return kTRUE;
3806 }
3807   
3808 //_____________________________________________________________________________
3809 void AliReconstruction::RunAliEVE()
3810 {
3811   // Runs AliEVE visualisation of
3812   // the current event.
3813   // Should be executed only after
3814   // successful initialization of AliEVE.
3815
3816   AliInfo("Running AliEVE...");
3817   gROOT->ProcessLine(Form("AliEveEventManager::GetMaster()->SetEvent((AliRunLoader*)%p,(AliRawReader*)%p,(AliESDEvent*)%p,(AliESDfriend*)%p);",fRunLoader,fRawReader,fesd,fesdf));
3818   gSystem->Run();
3819 }
3820
3821 //_____________________________________________________________________________
3822 Bool_t AliReconstruction::SetRunQA(TString detAndAction) 
3823 {
3824         // Allows to run QA for a selected set of detectors
3825         // and a selected set of tasks among RAWS, DIGITSR, RECPOINTS and ESDS
3826         // all selected detectors run the same selected tasks
3827         
3828         if (!detAndAction.Contains(":")) {
3829                 AliError( Form("%s is a wrong syntax, use \"DetectorList:ActionList\" \n", detAndAction.Data()) ) ;
3830                 fRunQA = kFALSE ;
3831                 return kFALSE ;                 
3832         }
3833         Int_t colon = detAndAction.Index(":") ; 
3834         fQADetectors = detAndAction(0, colon) ; 
3835         fQATasks   = detAndAction(colon+1, detAndAction.Sizeof() ) ; 
3836         if (fQATasks.Contains("ALL") ) {
3837                 fQATasks = Form("%d %d %d %d", AliQAv1::kRAWS, AliQAv1::kDIGITSR, AliQAv1::kRECPOINTS, AliQAv1::kESDS) ; 
3838         } else {
3839                 fQATasks.ToUpper() ; 
3840                 TString tempo("") ; 
3841                 if ( fQATasks.Contains("RAW") ) 
3842                         tempo = Form("%d ", AliQAv1::kRAWS) ; 
3843                 if ( fQATasks.Contains("DIGIT") ) 
3844                         tempo += Form("%d ", AliQAv1::kDIGITSR) ; 
3845                 if ( fQATasks.Contains("RECPOINT") ) 
3846                         tempo += Form("%d ", AliQAv1::kRECPOINTS) ; 
3847                 if ( fQATasks.Contains("ESD") ) 
3848                         tempo += Form("%d ", AliQAv1::kESDS) ; 
3849                 fQATasks = tempo ; 
3850                 if (fQATasks.IsNull()) {
3851                         AliInfo("No QA requested\n")  ;
3852                         fRunQA = kFALSE ;
3853                         return kTRUE ; 
3854                 }
3855         }       
3856         TString tempo(fQATasks) ; 
3857         tempo.ReplaceAll(Form("%d", AliQAv1::kRAWS), AliQAv1::GetTaskName(AliQAv1::kRAWS))      ;
3858         tempo.ReplaceAll(Form("%d", AliQAv1::kDIGITSR), AliQAv1::GetTaskName(AliQAv1::kDIGITSR)) ;      
3859         tempo.ReplaceAll(Form("%d", AliQAv1::kRECPOINTS), AliQAv1::GetTaskName(AliQAv1::kRECPOINTS)) ;  
3860         tempo.ReplaceAll(Form("%d", AliQAv1::kESDS), AliQAv1::GetTaskName(AliQAv1::kESDS)) ;    
3861         AliInfo( Form("QA will be done on \"%s\" for \"%s\"\n", fQADetectors.Data(), tempo.Data()) ) ;  
3862         fRunQA = kTRUE ;
3863         return kTRUE; 
3864
3865
3866 //_____________________________________________________________________________
3867 Bool_t AliReconstruction::InitRecoParams() 
3868 {
3869   // The method accesses OCDB and retrieves all
3870   // the available reco-param objects from there.
3871
3872   Bool_t isOK = kTRUE;
3873
3874   if (fRecoParam.GetDetRecoParamArray(kNDetectors)) {
3875     AliInfo("Using custom GRP reconstruction parameters");
3876   }
3877   else {
3878     AliInfo("Loading GRP reconstruction parameter objects");
3879
3880     AliCDBPath path("GRP","Calib","RecoParam");
3881     AliCDBEntry *entry=AliCDBManager::Instance()->Get(path.GetPath());
3882     if(!entry){ 
3883       AliWarning("Couldn't find GRP RecoParam entry in OCDB");
3884       isOK = kFALSE;
3885     }
3886     else {
3887       TObject *recoParamObj = entry->GetObject();
3888       if (dynamic_cast<TObjArray*>(recoParamObj)) {
3889         // GRP has a normal TobjArray of AliDetectorRecoParam objects
3890         // Registering them in AliRecoParam
3891         fRecoParam.AddDetRecoParamArray(kNDetectors,dynamic_cast<TObjArray*>(recoParamObj));
3892       }
3893       else if (dynamic_cast<AliDetectorRecoParam*>(recoParamObj)) {
3894         // GRP has only onse set of reco parameters
3895         // Registering it in AliRecoParam
3896         AliInfo("Single set of GRP reconstruction parameters found");
3897         dynamic_cast<AliDetectorRecoParam*>(recoParamObj)->SetAsDefault();
3898         fRecoParam.AddDetRecoParam(kNDetectors,dynamic_cast<AliDetectorRecoParam*>(recoParamObj));
3899       }
3900       else {
3901         AliError("No valid GRP RecoParam object found in the OCDB");
3902         isOK = kFALSE;
3903       }
3904       entry->SetOwner(0);
3905     }
3906   }
3907
3908   TString detStr = fLoadCDB;
3909   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
3910
3911     if (!IsSelected(fgkDetectorName[iDet], detStr)) continue;
3912
3913     if (fRecoParam.GetDetRecoParamArray(iDet)) {
3914       AliInfo(Form("Using custom reconstruction parameters for detector %s",fgkDetectorName[iDet]));
3915       continue;
3916     }
3917
3918     AliInfo(Form("Loading reconstruction parameter objects for detector %s",fgkDetectorName[iDet]));
3919   
3920     AliCDBPath path(fgkDetectorName[iDet],"Calib","RecoParam");
3921     AliCDBEntry *entry=AliCDBManager::Instance()->Get(path.GetPath());
3922     if(!entry){ 
3923       AliWarning(Form("Couldn't find RecoParam entry in OCDB for detector %s",fgkDetectorName[iDet]));
3924       isOK = kFALSE;
3925     }
3926     else {
3927       TObject *recoParamObj = entry->GetObject();
3928       if (dynamic_cast<TObjArray*>(recoParamObj)) {
3929         // The detector has a normal TobjArray of AliDetectorRecoParam objects
3930         // Registering them in AliRecoParam
3931         fRecoParam.AddDetRecoParamArray(iDet,dynamic_cast<TObjArray*>(recoParamObj));
3932       }
3933       else if (dynamic_cast<AliDetectorRecoParam*>(recoParamObj)) {
3934         // The detector has only onse set of reco parameters
3935         // Registering it in AliRecoParam
3936         AliInfo(Form("Single set of reconstruction parameters found for detector %s",fgkDetectorName[iDet]));
3937         dynamic_cast<AliDetectorRecoParam*>(recoParamObj)->SetAsDefault();
3938         fRecoParam.AddDetRecoParam(iDet,dynamic_cast<AliDetectorRecoParam*>(recoParamObj));
3939       }
3940       else {
3941         AliError(Form("No valid RecoParam object found in the OCDB for detector %s",fgkDetectorName[iDet]));
3942         isOK = kFALSE;
3943       }
3944       entry->SetOwner(0);
3945       //      FIX ME: We have to disable the unloading of reco-param CDB
3946       //      entries because QA framework is using them. Has to be fix in
3947       //      a way that the QA takes the objects already constructed in
3948       //      this method.
3949       //      AliCDBManager::Instance()->UnloadFromCache(path.GetPath());
3950     }
3951   }
3952
3953   if (AliDebugLevel() > 0) fRecoParam.Print();
3954
3955   return isOK;
3956 }
3957
3958 //_____________________________________________________________________________
3959 Bool_t AliReconstruction::GetEventInfo() 
3960 {
3961   // Fill the event info object
3962   // ...
3963   AliCodeTimerAuto("",0)
3964
3965   AliCentralTrigger *aCTP = NULL;
3966   if (fRawReader) {
3967     fEventInfo.SetEventType(fRawReader->GetType());
3968
3969     ULong64_t mask = fRawReader->GetClassMask();
3970     fEventInfo.SetTriggerMask(mask);
3971     UInt_t clmask = fRawReader->GetDetectorPattern()[0];
3972     fEventInfo.SetTriggerCluster(AliDAQ::ListOfTriggeredDetectors(clmask));
3973
3974     aCTP = new AliCentralTrigger();
3975     TString configstr("");
3976     if (!aCTP->LoadConfiguration(configstr)) { // Load CTP config from OCDB
3977       AliError("No trigger configuration found in OCDB! The trigger configuration information will not be used!");
3978       delete aCTP;
3979       return kFALSE;
3980     }
3981     aCTP->SetClassMask(mask);
3982     aCTP->SetClusterMask(clmask);
3983
3984     AliCentralTrigger* rlCTP = fRunLoader->GetTrigger();
3985     if (rlCTP) {
3986       rlCTP->SetClassMask(mask);
3987       rlCTP->SetClusterMask(clmask);
3988     }
3989   }
3990   else {
3991     fEventInfo.SetEventType(AliRawEventHeaderBase::kPhysicsEvent);
3992
3993     if (fRunLoader && (!fRunLoader->LoadTrigger())) {
3994       aCTP = fRunLoader->GetTrigger();
3995       fEventInfo.SetTriggerMask(aCTP->GetClassMask());
3996       // get inputs from actp - just get
3997       AliESDHeader* esdheader = fesd->GetHeader();
3998       esdheader->SetL0TriggerInputs(aCTP->GetL0TriggerInputs());
3999       esdheader->SetL1TriggerInputs(aCTP->GetL1TriggerInputs());
4000       esdheader->SetL2TriggerInputs(aCTP->GetL2TriggerInputs());
4001       fEventInfo.SetTriggerCluster(AliDAQ::ListOfTriggeredDetectors(aCTP->GetClusterMask()));
4002     }
4003     else {
4004       AliWarning("No trigger can be loaded! The trigger information will not be used!");
4005       return kFALSE;
4006     }
4007   }
4008
4009   AliTriggerConfiguration *config = aCTP->GetConfiguration();
4010   if (!config) {
4011     AliError("No trigger configuration has been found! The trigger configuration information will not be used!");
4012     if (fRawReader) delete aCTP;
4013     return kFALSE;
4014   }
4015
4016   UChar_t clustmask = 0;
4017   TString trclasses;
4018   ULong64_t trmask = fEventInfo.GetTriggerMask();
4019   const TObjArray& classesArray = config->GetClasses();
4020   Int_t nclasses = classesArray.GetEntriesFast();
4021   for( Int_t iclass=0; iclass < nclasses; iclass++ ) {
4022     AliTriggerClass* trclass = (AliTriggerClass*)classesArray.At(iclass);
4023     if (trclass && trclass->GetMask()>0) {
4024       Int_t trindex = TMath::Nint(TMath::Log2(trclass->GetMask()));
4025       fesd->SetTriggerClass(trclass->GetName(),trindex);
4026       if (fRawReader) fRawReader->LoadTriggerClass(trclass->GetName(),trindex);
4027       if (trmask & (1ull << trindex)) {
4028         trclasses += " ";
4029         trclasses += trclass->GetName();
4030         trclasses += " ";
4031         clustmask |= trclass->GetCluster()->GetClusterMask();
4032       }
4033     }
4034   }
4035   fEventInfo.SetTriggerClasses(trclasses);
4036   // Now put the declared trigger classes (not present in the run)
4037   // to 0/false in the event selection
4038   if (!fDeclTriggerClasses.IsNull()) {
4039     TObjArray *tokens = fDeclTriggerClasses.Tokenize(" ");
4040     Int_t ntokens = tokens->GetEntriesFast();
4041     for (Int_t itoken = 0; itoken < ntokens; ++itoken) {
4042       if (fRawReader) fRawReader->LoadTriggerClass((((TObjString*)tokens->At(itoken))->String()).Data(),-1);
4043     }
4044     delete tokens;
4045   }
4046
4047   // Write names of active trigger inputs in ESD Header
4048   const TObjArray& inputsArray = config->GetInputs(); 
4049   Int_t ninputs = inputsArray.GetEntriesFast();
4050   for( Int_t iinput=0; iinput < ninputs; iinput++ ) {
4051     AliTriggerInput* trginput = (AliTriggerInput*)inputsArray.At(iinput);
4052     if (trginput && trginput->GetMask()>0) {
4053       Int_t inputIndex = (Int_t)TMath::Nint(TMath::Log2(trginput->GetMask()));
4054       AliESDHeader* headeresd = fesd->GetHeader();
4055       Int_t trglevel = (Int_t)trginput->GetLevel();
4056       if (trglevel == 0) headeresd->SetActiveTriggerInputs(trginput->GetInputName(), inputIndex);
4057       if (trglevel == 1) headeresd->SetActiveTriggerInputs(trginput->GetInputName(), inputIndex+24);
4058       if (trglevel == 2) headeresd->SetActiveTriggerInputs(trginput->GetInputName(), inputIndex+48);
4059     }
4060   }
4061
4062   // Set the information in ESD
4063   fesd->SetTriggerMask(trmask);
4064   fesd->SetTriggerCluster(clustmask);
4065
4066   if (!aCTP->CheckTriggeredDetectors()) {
4067     if (fRawReader) delete aCTP;
4068     return kFALSE;
4069   }    
4070
4071   if (fRawReader) delete aCTP;
4072
4073   // We have to fill also the HLT decision here!!
4074   // ...
4075
4076   return kTRUE;
4077 }
4078
4079 const char *AliReconstruction::MatchDetectorList(const char *detectorList, UInt_t detectorMask)
4080 {
4081   // Match the detector list found in the rec.C or the default 'ALL'
4082   // to the list found in the GRP (stored there by the shuttle PP which
4083   // gets the information from ECS)
4084   static TString resultList;
4085   TString detList = detectorList;
4086
4087   resultList = "";
4088
4089   for(Int_t iDet = 0; iDet < (AliDAQ::kNDetectors-1); iDet++) {
4090     if ((detectorMask >> iDet) & 0x1) {
4091       TString det = AliDAQ::OfflineModuleName(iDet);
4092       if ((detList.CompareTo("ALL") == 0) ||
4093           ((detList.BeginsWith("ALL ") ||
4094             detList.EndsWith(" ALL") ||
4095             detList.Contains(" ALL ")) &&
4096            !(detList.BeginsWith("-"+det+" ") ||
4097              detList.EndsWith(" -"+det) ||
4098              detList.Contains(" -"+det+" "))) ||
4099           (detList.CompareTo(det) == 0) ||
4100           detList.BeginsWith(det+" ") ||
4101           detList.EndsWith(" "+det) ||
4102           detList.Contains( " "+det+" " )) {
4103         if (!resultList.EndsWith(det + " ")) {
4104           resultList += det;
4105           resultList += " ";
4106         }
4107       }        
4108     }
4109   }
4110
4111   // HLT
4112   if ((detectorMask >> AliDAQ::kHLTId) & 0x1) {
4113     TString hltDet = AliDAQ::OfflineModuleName(AliDAQ::kNDetectors-1);
4114     if ((detList.CompareTo("ALL") == 0) ||
4115         ((detList.BeginsWith("ALL ") ||
4116           detList.EndsWith(" ALL") ||
4117           detList.Contains(" ALL ")) &&
4118          !(detList.BeginsWith("-"+hltDet+" ") ||
4119            detList.EndsWith(" -"+hltDet) ||
4120            detList.Contains(" -"+hltDet+" "))) ||
4121         (detList.CompareTo(hltDet) == 0) ||
4122         detList.BeginsWith(hltDet+" ") ||
4123         detList.EndsWith(" "+hltDet) ||
4124         detList.Contains( " "+hltDet+" " )) {
4125       resultList += hltDet;
4126     }
4127   }
4128
4129   return resultList.Data();
4130
4131 }
4132
4133 //______________________________________________________________________________
4134 void AliReconstruction::Abort(const char *method, EAbort what)
4135 {
4136   // Abort processing. If what = kAbortProcess, the Process() loop will be
4137   // aborted. If what = kAbortFile, the current file in a chain will be
4138   // aborted and the processing will continue with the next file, if there
4139   // is no next file then Process() will be aborted. Abort() can also  be
4140   // called from Begin(), SlaveBegin(), Init() and Notify(). After abort
4141   // the SlaveTerminate() and Terminate() are always called. The abort flag
4142   // can be checked in these methods using GetAbort().
4143   //
4144   // The method is overwritten in AliReconstruction for better handling of
4145   // reco specific errors 
4146
4147   if (!fStopOnError) return;
4148
4149   CleanUp();
4150
4151   TString whyMess = method;
4152   whyMess += " failed! Aborting...";
4153
4154   AliError(whyMess.Data());
4155
4156   fAbort = what;
4157   TString mess = "Abort";
4158   if (fAbort == kAbortProcess)
4159     mess = "AbortProcess";
4160   else if (fAbort == kAbortFile)
4161     mess = "AbortFile";
4162
4163   Info(mess.Data(), "%s", whyMess.Data());
4164 }
4165
4166 //______________________________________________________________________________
4167 Bool_t AliReconstruction::ProcessEvent(void* event)
4168 {
4169   // Method that is used in case the event loop
4170   // is steered from outside, for example by AMORE
4171   // 'event' is a pointer to the DATE event in the memory
4172
4173   if (fRawReader) delete fRawReader;
4174   fRawReader = new AliRawReaderDate(event);
4175   fStatus = ProcessEvent(fRunLoader->GetNumberOfEvents());  
4176   delete fRawReader;
4177   fRawReader = NULL;
4178
4179   return fStatus;
4180 }
4181
4182 //______________________________________________________________________________
4183 Bool_t AliReconstruction::ParseOutput()
4184 {
4185   // The method parses the output file
4186   // location string in order to steer
4187   // properly the selector
4188
4189   TPMERegexp re1("(\\w+\\.zip#\\w+\\.root):([,*\\w+\\.root,*]+)@dataset://(\\w++)");
4190   TPMERegexp re2("(\\w+\\.root)?@?dataset://(\\w++)");
4191
4192   if (re1.Match(fESDOutput) == 4) {
4193     // root archive with output files stored and regustered
4194     // in proof dataset
4195     gProof->AddInput(new TNamed("PROOF_OUTPUTFILE",re1[1].Data()));
4196     gProof->AddInput(new TNamed("PROOF_OUTPUTFILE_LOCATION",re1[3].Data()));
4197     gProof->AddInput(new TNamed("PROOF_OUTPUTFILE_DATASET",""));
4198     gProof->AddInput(new TNamed("PROOF_OUTPUTFILE_ARCHIVE",re1[2].Data()));
4199     AliInfo(Form("%s files will be stored within %s in dataset %s",
4200                  re1[2].Data(),
4201                  re1[1].Data(),
4202                  re1[3].Data()));
4203   }
4204   else if (re2.Match(fESDOutput) == 3) {
4205     // output file stored and registered
4206     // in proof dataset
4207     gProof->AddInput(new TNamed("PROOF_OUTPUTFILE",(re2[1].IsNull()) ? "AliESDs.root" : re2[1].Data()));
4208     gProof->AddInput(new TNamed("PROOF_OUTPUTFILE_LOCATION",re2[2].Data()));
4209     gProof->AddInput(new TNamed("PROOF_OUTPUTFILE_DATASET",""));
4210     AliInfo(Form("%s will be stored in dataset %s",
4211                  (re2[1].IsNull()) ? "AliESDs.root" : re2[1].Data(),
4212                  re2[2].Data()));
4213   }
4214   else {
4215     if (fESDOutput.IsNull()) {
4216       // Output location not given.
4217       // Assuming xrootd has been already started and
4218       // the output file has to be sent back
4219       // to the client machine
4220       TString esdUrl(Form("root://%s/%s/",
4221                           TUrl(gSystem->HostName()).GetHostFQDN(),
4222                           gSystem->pwd()));
4223       gProof->AddInput(new TNamed("PROOF_OUTPUTFILE","AliESDs.root"));
4224       gProof->AddInput(new TNamed("PROOF_OUTPUTFILE_LOCATION",esdUrl.Data()));
4225       AliInfo(Form("AliESDs.root will be stored in %s",
4226                    esdUrl.Data()));
4227     }
4228     else {
4229       // User specified an output location.
4230       // Ones has just to parse it here
4231       TUrl outputUrl(fESDOutput.Data());
4232       TString outputFile(gSystem->BaseName(outputUrl.GetFile()));
4233       gProof->AddInput(new TNamed("PROOF_OUTPUTFILE",outputFile.IsNull() ? "AliESDs.root" : outputFile.Data()));
4234       TString outputLocation(outputUrl.GetUrl());
4235       outputLocation.ReplaceAll(outputFile.Data(),"");
4236       gProof->AddInput(new TNamed("PROOF_OUTPUTFILE_LOCATION",outputLocation.Data()));
4237       AliInfo(Form("%s will be stored in %s",
4238                    outputFile.IsNull() ? "AliESDs.root" : outputFile.Data(),
4239                    outputLocation.Data()));
4240     }
4241   }
4242
4243   return kTRUE;
4244 }
4245
4246 //______________________________________________________________________________
4247 Bool_t AliReconstruction::IsHighPt() const {
4248   // Selection of events containing "high" pT tracks
4249   // If at least one track is found within 1.5 and 100 GeV (pT)
4250   // that was reconstructed by both ITS and TPC, the event is accepted
4251
4252   // Track cuts
4253   const Double_t pTmin = 1.5;
4254   const Double_t pTmax = 100;
4255   ULong_t mask = 0;
4256   mask |= (AliESDtrack::kITSrefit);
4257   mask |= (AliESDtrack::kTPCrefit);
4258   const Double_t pTminCosmic = 5.;
4259   const Double_t pTmaxCosmic = 100;
4260   ULong_t maskCosmic = 0;
4261   Int_t cosmicCount=0;
4262   maskCosmic |= (AliESDtrack::kTPCrefit);
4263
4264   Bool_t isOK = kFALSE;
4265
4266   if (fesd && fesd->GetEventType()==AliRawEventHeaderBase::kPhysicsEvent) {
4267     // Check if this ia a physics event (code 7)
4268     Int_t ntrk = fesd->GetNumberOfTracks();
4269     for (Int_t itrk=0; itrk<ntrk; ++itrk) {
4270           
4271       AliESDtrack * trk = fesd->GetTrack(itrk);
4272       if (trk 
4273           && trk->Pt() > pTmin 
4274           && trk->Pt() < pTmax
4275           && (trk->GetStatus() & mask) == mask ) {
4276         
4277         isOK = kTRUE;
4278         break;
4279       }
4280       if (trk 
4281           && trk->GetInnerParam()
4282           && trk->GetInnerParam()->Pt() > pTminCosmic 
4283           && trk->GetInnerParam()->Pt() < pTmaxCosmic
4284           && (trk->GetStatus() & maskCosmic) == maskCosmic ) {
4285         
4286         cosmicCount++;
4287         break;
4288       }
4289     }
4290     if (cosmicCount>1) isOK=kTRUE;
4291   }
4292   return isOK;
4293 }
4294
4295 //______________________________________________________________________________
4296 Bool_t AliReconstruction::IsCosmicOrCalibSpecie() const {
4297   // Select cosmic or calibration events
4298
4299   Bool_t isOK = kFALSE;
4300
4301   if (fesd && fesd->GetEventType()==AliRawEventHeaderBase::kPhysicsEvent) {
4302       // Check if this ia a physics event (code 7)
4303       
4304       UInt_t specie = fesd->GetEventSpecie();
4305       if (specie==AliRecoParam::kCosmic || specie==AliRecoParam::kCalib) {
4306         isOK = kTRUE;
4307       }
4308   }
4309   return isOK;
4310 }
4311
4312 //______________________________________________________________________________
4313 void AliReconstruction::WriteESDfriend() {
4314   // Fill the ESD friend in the tree. The required fraction of ESD friends is stored
4315   // in fFractionFriends. We select events where we store the ESD friends according
4316   // to the following algorithm:
4317   // 1. Store all Cosmic or Calibration events within the required fraction
4318   // 2. Sample "high Pt" events within the remaining fraction after step 1.
4319   // 3. Sample randomly events if we still have remaining slot
4320
4321   fNall++;
4322   Bool_t isSelected = kFALSE;
4323   //
4324   // Store all friends for B field OFF 
4325   if (TMath::Abs(AliTrackerBase::GetBz())<0.5) isSelected=kTRUE;
4326
4327   if (IsCosmicOrCalibSpecie()) { // Selection of calib or cosmic events
4328     fNspecie++;
4329
4330     isSelected = kTRUE;
4331     fSspecie++;
4332   }
4333   
4334   Double_t remainingFraction = fFractionFriends;
4335   remainingFraction -= ((Double_t)(fSspecie)/(Double_t)(fNall));
4336   
4337   if (IsHighPt())  { // Selection of "high Pt" events
4338     fNhighPt++;
4339     Double_t curentHighPtFraction = ((Double_t)(fNhighPt+1))/((Double_t)(fNall+1));
4340     // "Bayesian" estimate supposing that without events all the events are of the required type
4341     
4342     if (!isSelected) {
4343       Double_t rnd = gRandom->Rndm()*curentHighPtFraction;
4344       if (rnd<remainingFraction) {
4345         isSelected = kTRUE;
4346         fShighPt++;
4347       }
4348     }
4349   }
4350   remainingFraction -= ((Double_t)(fShighPt)/(Double_t)(fNall));
4351   
4352   // Random selection to fill the remaining fraction (if any)
4353   if (!isSelected) {
4354     Double_t rnd = gRandom->Rndm();
4355     if (rnd<remainingFraction) {        
4356       isSelected = kTRUE;
4357     }
4358   }
4359   
4360   if (!isSelected) {
4361     fesdf->~AliESDfriend();
4362     new (fesdf) AliESDfriend(); // Reset...
4363     fesdf->SetSkipBit(kTRUE);
4364   }
4365   //
4366   ftreeF->Fill();
4367 }
4368
4369 //_________________________________________________________________
4370 void AliReconstruction::DeleteDigits(const TString& detectors)
4371 {
4372   // delete requested digit files produced at current event
4373   static int iEvent = 0;
4374   if (detectors.IsNull()) return;
4375   TString detStr = detectors;
4376   AliInfo(Form("Deleting Digits: %s",detectors.Data()));
4377
4378   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
4379     gSystem->Exec(Form("if [ -e %s.Digits.root ]; then\nrm %s.Digits.root\nfi",
4380                        fgkDetectorName[iDet],fgkDetectorName[iDet]));
4381   }
4382   AliSysInfo::AddStamp(Form("DelDigits_%d",iEvent), 0,0,iEvent);
4383   iEvent++;
4384 }
4385
4386 //_________________________________________________________________
4387 void AliReconstruction::DeleteRecPoints(const TString& detectors)
4388 {
4389   // delete requested recpoint files produced at current event
4390   static int iEvent = 0;
4391   if (detectors.IsNull()) return;
4392   TString detStr = detectors;
4393   AliInfo(Form("Deleting Recpoints: %s",detectors.Data()));
4394   //
4395   for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
4396     gSystem->Exec(Form("if [ -e %s.RecPoints.root ]; then\nrm %s.RecPoints.root\nfi",
4397                        fgkDetectorName[iDet],fgkDetectorName[iDet]));
4398   }
4399   AliSysInfo::AddStamp(Form("DelRecPoints_%d",iEvent), 0,0,iEvent);
4400   iEvent++;
4401 }
4402
4403 //_________________________________________________________________
4404 void AliReconstruction::SetStopOnResourcesExcess(Int_t vRSS,Int_t vVMEM)
4405 {
4406   // require checking the resources left and stopping on excess
4407   // if 0  : no check is done
4408   // if >0 : stop reconstruction if exceeds this value
4409   // if <0 : use as margin to system limits
4410   //
4411   const int kKB2MB = 1024;
4412   const int kInfMem = 9999999;
4413   //
4414   struct rlimit r;
4415   int pgSize = getpagesize();
4416   //
4417   if (vRSS>0) {
4418     fMaxRSS = vRSS;
4419     AliInfo(Form("Setting max. RSS usage to user value %d MB",fMaxRSS));
4420   }
4421   else if (vRSS<0) {
4422     getrlimit(RLIMIT_RSS,&r);
4423     fMaxRSS = r.rlim_max==RLIM_INFINITY ? kInfMem : int(r.rlim_max*pgSize/kKB2MB/kKB2MB) + vRSS;
4424     AliInfo(Form("Setting max. RSS usage to system hard limit %d%s MB (%d margin)",fMaxRSS,r.rlim_max==RLIM_INFINITY ? "(inf)":"",-vRSS));
4425   }
4426   else {AliInfo("No check on RSS memory usage will be applied");}
4427   //
4428   if (vVMEM>0) {
4429     fMaxVMEM = vVMEM;
4430     AliInfo(Form("Setting max. VMEM usage to user value %d MB",fMaxVMEM));
4431   }
4432   else if (vVMEM<0) {
4433     getrlimit(RLIMIT_AS,&r);
4434     fMaxVMEM = r.rlim_max==RLIM_INFINITY ? kInfMem : int(r.rlim_max*pgSize/kKB2MB/kKB2MB) + vVMEM;
4435     AliInfo(Form("Setting max. VMEM usage to system hard limit %d%s MB (%d margin)",fMaxVMEM,r.rlim_max==RLIM_INFINITY ? "(inf)":"",-vVMEM));
4436   }
4437   else {AliInfo("No check on RSS memory usage will be applied");}
4438   //  
4439 }
4440
4441 //_________________________________________________________________
4442 Bool_t AliReconstruction::HasEnoughResources(int ev)
4443 {
4444   // check if process consumed more than allowed resources
4445   const int kKB2MB = 1024;
4446   Bool_t res = kTRUE;
4447   if (!fMaxRSS && !fMaxVMEM) return res;
4448   //
4449   ProcInfo_t procInfo;
4450   gSystem->GetProcInfo(&procInfo);
4451   if (procInfo.fMemResident/kKB2MB > fMaxRSS)  res = kFALSE;
4452   if (procInfo.fMemVirtual/kKB2MB  > fMaxVMEM) res = kFALSE;  
4453   //
4454   if (!res) {
4455     AliInfo(Form("Job exceeded allowed limits: RSS:%d (%d) VMEM:%d (%d), will stop",
4456                  int(procInfo.fMemResident/kKB2MB),fMaxRSS,
4457                  int(procInfo.fMemVirtual/kKB2MB) ,fMaxVMEM));
4458     //
4459     gSystem->Exec(Form("if [ -e %s ]; then\nrm %s\nfi\necho %d > %s",fgkStopEvFName,fgkStopEvFName,ev,fgkStopEvFName));
4460     fStopped = kTRUE;
4461   }
4462   return res;
4463 }