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