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