]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TOF/AliTOFcalib.cxx
o fix for coverity bug 19907
[u/mrichter/AliRoot.git] / TOF / AliTOFcalib.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 /*
17 $Log: AliTOFcalib.cxx,v $
18 Revision 1.21  2007/11/02 15:41:49  hristov
19 Provide return value if the function is not void
20
21 Revision 1.20  2007/10/26 15:13:50  zampolli
22 Using a TChain instead of a TTree
23
24 Revision 1.19  2007/10/23 15:27:38  zampolli
25 Rearrangement of Calibration objects for simulation
26
27 Revision 1.16  2007/10/08 10:13:26  zampolli
28 First Run and Last Run members added, infinite validity of calib obj implemented.
29
30 Revision 1.15  2007/10/04 13:23:28  zampolli
31 Updates to handle functionalities in TOF online/offline calibration according to the latest schema
32
33 Revision 1.14  2007/06/06 16:26:30  arcelli
34 remove fall-back call to local CDB storage
35
36 Revision 1.13  2007/04/20 13:59:40  arcelli
37 make protections agains failed retrieval of the CDB object in a proper way
38
39 Revision 1.12  2007/03/23 11:31:16  arcelli
40 CDB Entry for TOF Reconstruction Parameters
41
42 Revision 1.11  2007/02/28 18:08:26  arcelli
43 Add protection against failed retrieval of the CDB cal object
44
45 Revision 1.10  2006/08/22 13:30:49  arcelli
46 removal of effective c++ warnings (C.Zampolli)
47
48 Revision 1.9  2006/04/20 22:30:50  hristov
49 Coding conventions (Annalisa)
50
51 Revision 1.8  2006/04/16 22:29:05  hristov
52 Coding conventions (Annalisa)
53
54 Revision 1.7  2006/04/16 20:12:46  hristov
55 Removing memory leak in case of cached CDB entries
56
57 Revision 1.6  2006/04/11 15:28:32  hristov
58 Checks on cache status before deleting calibration objects (A.Colla)
59
60 Revision 1.5  2006/04/05 08:35:38  hristov
61 Coding conventions (S.Arcelli, C.Zampolli)
62
63 Revision 1.4  2006/03/31 11:26:46  arcelli
64  changing CDB Ids according to standard convention
65
66 Revision 1.3  2006/03/28 14:57:02  arcelli
67 updates to handle new V5 geometry & some re-arrangements
68
69 Revision 1.2  2006/02/13 17:22:26  arcelli
70 just Fixing Log info
71
72 Revision 1.1  2006/02/13 16:10:48  arcelli
73 Add classes for TOF Calibration (C.Zampolli)
74
75 author: Chiara Zampolli, zampolli@bo.infn.it
76 */  
77
78 ///////////////////////////////////////////////////////////////////////////////
79 //                                                                           //
80 // class for TOF calibration                                                 //
81 //                                                                           //
82 ///////////////////////////////////////////////////////////////////////////////
83
84 #include "TF1.h"
85 #include "TFile.h"
86 #include "TH1F.h"
87 #include "TH1C.h"
88 #include "TH2F.h"
89 //#include "TList.h"
90 //#include "TROOT.h"
91 //#include "TStyle.h"
92 #include "TTree.h"
93 #include "TChain.h"
94 #include "TProfile.h"
95 #include "TGrid.h"
96 #include "TMath.h"
97 #include "TMap.h"
98
99 #include "AliCDBEntry.h"
100 #include "AliCDBRunRange.h"
101 #include "AliCDBId.h"
102 #include "AliCDBManager.h"
103 #include "AliCDBStorage.h"
104 #include "AliCDBMetaData.h"
105 //#include "AliESDtrack.h"
106 //#include "AliESD.h"
107 #include "AliLog.h"
108
109 #include "AliTOFcalib.h"
110 #include "AliTOFChannelOnlineArray.h"
111 #include "AliTOFChannelOnline.h"
112 #include "AliTOFChannelOnlineStatus.h"
113 #include "AliTOFChannelOnlineStatusArray.h"
114 #include "AliTOFChannelOffline.h"
115 #include "AliTOFGeometry.h"
116 #include "AliTOFRecoParam.h"
117 #include "AliTOFDeltaBCOffset.h"
118 #include "AliTOFCTPLatency.h"
119 #include "AliTOFT0Fill.h"
120 #include "AliTOFRunParams.h"
121 #include "AliLHCClockPhase.h"
122 #include "AliTOFResponseParams.h"
123 #include "AliESDEvent.h"
124 #include "AliESDtrack.h"
125 #include "TRandom.h"
126
127 class TROOT;
128 class TStyle;
129
130 extern TROOT *gROOT;
131 extern TStyle *gStyle;
132
133 ClassImp(AliTOFcalib)
134
135 //_______________________________________________________________________
136 AliTOFcalib::AliTOFcalib():
137   TTask("AliTOFcalib",""),
138   fNChannels(-1),
139   fTOFCalOnline(0x0),
140   fTOFCalOnlinePulser(0x0),
141   fTOFCalOnlineNoise(0x0),
142   fTOFCalOnlineHW(0x0),
143   fTOFCalOffline(0x0),
144   fCal(0x0),
145   fStatus(0x0),
146   fTOFSimToT(0x0),
147   fkValidity(0x0),
148   fTree(0x0),
149   fChain(0x0),
150   fNruns(0),
151   fFirstRun(0),
152   fLastRun(AliCDBRunRange::Infinity()),
153   fConfigMap(new TMap),
154   fDeltaBCOffset(NULL),
155   fCTPLatency(NULL),
156   fT0Fill(NULL),
157   fRunParams(NULL),
158   fLHCClockPhase(NULL),
159   fResponseParams(NULL),
160   fReadoutEfficiency(NULL),
161   fProblematic(NULL),
162   fInitFlag(kFALSE),
163   fRemoveMeanT0(kTRUE),
164   fUseLHCClockPhase(kFALSE),
165   fCalibrateTOFsignal(kTRUE),
166   fCorrectTExp(kFALSE),
167   fRunParamsSpecificVersion(-1)
168
169   //TOF Calibration Class ctor
170   fNChannels = AliTOFGeometry::NSectors()*(2*(AliTOFGeometry::NStripC()+AliTOFGeometry::NStripB())+AliTOFGeometry::NStripA())*AliTOFGeometry::NpadZ()*AliTOFGeometry::NpadX();
171
172   gRandom->SetSeed(123456789);
173 }
174 //____________________________________________________________________________ 
175
176 AliTOFcalib::AliTOFcalib(const AliTOFcalib & calib):
177   TTask(calib),
178   fNChannels(calib.fNChannels),
179   fTOFCalOnline(0x0),
180   fTOFCalOnlinePulser(0x0),
181   fTOFCalOnlineNoise(0x0),
182   fTOFCalOnlineHW(0x0),
183   fTOFCalOffline(0x0),
184   fCal(calib.fCal),
185   fStatus(calib.fStatus),
186   fTOFSimToT(calib.fTOFSimToT),
187   fkValidity(calib.fkValidity),
188   fTree(calib.fTree),
189   fChain(calib.fChain),
190   fNruns(calib.fNruns),
191   fFirstRun(calib.fFirstRun),
192   fLastRun(calib.fLastRun),
193   fConfigMap(calib.fConfigMap),
194   fDeltaBCOffset(NULL),
195   fCTPLatency(NULL),
196   fT0Fill(NULL),
197   fRunParams(NULL),
198   fLHCClockPhase(NULL),
199   fResponseParams(NULL),
200   fReadoutEfficiency(NULL),
201   fProblematic(NULL),
202   fInitFlag(calib.fInitFlag),
203   fRemoveMeanT0(calib.fRemoveMeanT0),
204   fUseLHCClockPhase(calib.fUseLHCClockPhase),
205   fCalibrateTOFsignal(calib.fCalibrateTOFsignal),
206   fCorrectTExp(calib.fCorrectTExp),
207   fRunParamsSpecificVersion(calib.fRunParamsSpecificVersion)
208 {
209
210   fTOFCalOnline = new TObjArray(fNChannels);
211   fTOFCalOnlinePulser = new TObjArray(fNChannels);
212   fTOFCalOnlineNoise = new TObjArray(fNChannels);
213   fTOFCalOnlineHW = new TObjArray(fNChannels);
214   fTOFCalOffline = new TObjArray(fNChannels);
215   fTOFCalOnline->SetOwner();
216   fTOFCalOnlinePulser->SetOwner();
217   fTOFCalOnlineNoise->SetOwner();
218   fTOFCalOnlineHW->SetOwner();
219   fTOFCalOffline->SetOwner();
220
221   //TOF Calibration Class copy ctor
222   for (Int_t iarray = 0; iarray<fNChannels; iarray++){
223     AliTOFChannelOnline * calChOnline = (AliTOFChannelOnline*)calib.fTOFCalOnline->At(iarray);
224     AliTOFChannelOnlineStatus * calChOnlineStPulser = (AliTOFChannelOnlineStatus*)calib.fTOFCalOnlinePulser->At(iarray);
225     AliTOFChannelOnlineStatus * calChOnlineStNoise = (AliTOFChannelOnlineStatus*)calib.fTOFCalOnlineNoise->At(iarray);
226     AliTOFChannelOnlineStatus * calChOnlineStHW = (AliTOFChannelOnlineStatus*)calib.fTOFCalOnlineHW->At(iarray);
227     AliTOFChannelOffline * calChOffline = (AliTOFChannelOffline*)calib.fTOFCalOffline->At(iarray);
228     fTOFCalOnline->AddAt(calChOnline,iarray);
229     fTOFCalOnlinePulser->AddAt(calChOnlineStPulser,iarray);
230     fTOFCalOnlineNoise->AddAt(calChOnlineStNoise,iarray);
231     fTOFCalOnlineHW->AddAt(calChOnlineStHW,iarray);
232     fTOFCalOffline->AddAt(calChOffline,iarray);
233   }
234
235   if (calib.fDeltaBCOffset) fDeltaBCOffset = new AliTOFDeltaBCOffset(*calib.fDeltaBCOffset);
236   if (calib.fCTPLatency) fCTPLatency = new AliTOFCTPLatency(*calib.fCTPLatency);
237   if (calib.fT0Fill) fT0Fill = new AliTOFT0Fill(*calib.fT0Fill);
238   if (calib.fRunParams) fRunParams = new AliTOFRunParams(*calib.fRunParams);
239   if (calib.fResponseParams) fResponseParams = new AliTOFResponseParams(*calib.fResponseParams);
240   if (calib.fReadoutEfficiency) fReadoutEfficiency = new TH1F(*calib.fReadoutEfficiency);
241   if (calib.fProblematic) fProblematic = new TH1C(*calib.fProblematic);
242
243   gRandom->SetSeed(123456789);
244 }
245
246 //____________________________________________________________________________ 
247
248 AliTOFcalib& AliTOFcalib::operator=(const AliTOFcalib &calib)
249 {
250   //TOF Calibration Class assignment operator
251
252   if (this == &calib)
253     return *this;
254   
255   TTask::operator=(calib);
256   fNChannels = calib.fNChannels;
257   fCal = calib.fCal;
258   fStatus = calib.fStatus;
259   fTOFSimToT = calib.fTOFSimToT;
260   fkValidity = calib.fkValidity;
261   fTree = calib.fTree;
262   fChain = calib.fChain;
263   fNruns = calib.fNruns;
264   fFirstRun = calib.fFirstRun;
265   fLastRun = calib.fLastRun;
266   for (Int_t iarray = 0; iarray<fNChannels; iarray++){
267     AliTOFChannelOnline * calChOnline = (AliTOFChannelOnline*)calib.fTOFCalOnline->At(iarray);
268     AliTOFChannelOffline * calChOffline = (AliTOFChannelOffline*)calib.fTOFCalOffline->At(iarray);
269     AliTOFChannelOnlineStatus * calChOnlineStPulser = (AliTOFChannelOnlineStatus*)calib.fTOFCalOnlinePulser->At(iarray);
270     AliTOFChannelOnlineStatus * calChOnlineStNoise = (AliTOFChannelOnlineStatus*)calib.fTOFCalOnlineNoise->At(iarray);
271     AliTOFChannelOnlineStatus * calChOnlineStHW = (AliTOFChannelOnlineStatus*)calib.fTOFCalOnlineHW->At(iarray);
272     fTOFCalOnline->AddAt(calChOnline,iarray);
273     fTOFCalOnlinePulser->AddAt(calChOnlineStPulser,iarray);
274     fTOFCalOnlineNoise->AddAt(calChOnlineStNoise,iarray);
275     fTOFCalOnlineHW->AddAt(calChOnlineStHW,iarray);
276     fTOFCalOffline->AddAt(calChOffline,iarray);
277   }
278
279   if (calib.fDeltaBCOffset) {
280     if (fDeltaBCOffset) *fDeltaBCOffset = *calib.fDeltaBCOffset;
281     else fDeltaBCOffset = new AliTOFDeltaBCOffset(*calib.fDeltaBCOffset);
282   }
283
284   if (calib.fCTPLatency) {
285     if (fCTPLatency) *fCTPLatency = *calib.fCTPLatency;
286     else fCTPLatency = new AliTOFCTPLatency(*calib.fCTPLatency);
287   }
288
289   if (calib.fT0Fill) {
290     if (fT0Fill) *fT0Fill = *calib.fT0Fill;
291     else fT0Fill = new AliTOFT0Fill(*calib.fT0Fill);
292   }
293   if (calib.fRunParams) {
294     if (fRunParams) *fRunParams = *calib.fRunParams;
295     else fRunParams = new AliTOFRunParams(*calib.fRunParams);
296   }
297   if (calib.fResponseParams) {
298     if (fResponseParams) *fResponseParams = *calib.fResponseParams;
299     else fResponseParams = new AliTOFResponseParams(*calib.fResponseParams);
300   }
301   if (calib.fReadoutEfficiency) {
302     if (fReadoutEfficiency) *fReadoutEfficiency = *calib.fReadoutEfficiency;
303     else fReadoutEfficiency = new TH1F(*calib.fReadoutEfficiency);
304   }
305   if (calib.fProblematic) {
306     if (fProblematic) *fProblematic = *calib.fProblematic;
307     else fProblematic = new TH1C(*calib.fProblematic);
308   }
309   fInitFlag = calib.fInitFlag;
310   fRemoveMeanT0 = calib.fRemoveMeanT0;
311   fUseLHCClockPhase = calib.fUseLHCClockPhase;
312   fCalibrateTOFsignal = calib.fCalibrateTOFsignal;
313   fCorrectTExp = calib.fCorrectTExp;
314   fRunParamsSpecificVersion = calib.fRunParamsSpecificVersion;
315
316   return *this;
317 }
318
319 //____________________________________________________________________________ 
320
321 AliTOFcalib::~AliTOFcalib()
322 {
323   //TOF Calibration Class dtor
324   if(!(AliCDBManager::Instance()->GetCacheFlag())){ // CDB objects must NOT be deleted if cache is active!
325     if (fTOFCalOnline){
326       delete fTOFCalOnline;
327     }
328     if (fTOFCalOnlinePulser){
329       delete fTOFCalOnlinePulser;
330     }
331     if (fTOFCalOnlineNoise){
332       delete fTOFCalOnlineNoise;
333     }
334     if (fTOFCalOnlineHW){
335       delete fTOFCalOnlineHW;
336     }
337     if (fTOFCalOffline){
338       delete fTOFCalOffline;
339     }
340     if (fCal){
341       delete fCal;
342     }
343     if (fStatus){
344       delete fStatus;
345     }
346     if (fConfigMap){
347       delete fConfigMap;
348     }
349     if (fDeltaBCOffset) delete fDeltaBCOffset;
350     if (fCTPLatency) delete fCTPLatency;
351     if (fT0Fill) delete fT0Fill;
352     if (fRunParams) delete fRunParams;
353     if (fResponseParams) delete fResponseParams;
354     if (fReadoutEfficiency) delete fReadoutEfficiency;
355     if (fProblematic) delete fProblematic;
356   }
357   if (fTree!=0x0) delete fTree;
358   if (fChain!=0x0) delete fChain;
359
360 }
361 //_____________________________________________________________________________
362 void AliTOFcalib::CreateCalArrays(){
363
364   // creating arrays for online/offline calibration objs
365
366   fTOFCalOnline = new TObjArray(fNChannels);
367   fTOFCalOnlinePulser = new TObjArray(fNChannels);
368   fTOFCalOnlineNoise = new TObjArray(fNChannels);
369   fTOFCalOnlineHW = new TObjArray(fNChannels);
370   fTOFCalOffline = new TObjArray(fNChannels);
371   fTOFCalOnline->SetOwner();
372   fTOFCalOnlinePulser->SetOwner();
373   fTOFCalOnlineNoise->SetOwner();
374   fTOFCalOnlineHW->SetOwner();
375   fTOFCalOffline->SetOwner();
376   for (Int_t iarray = 0; iarray<fNChannels; iarray++){
377     AliTOFChannelOnline * calChOnline = new AliTOFChannelOnline();
378     AliTOFChannelOnlineStatus * calChOnlineStPulser = new AliTOFChannelOnlineStatus();
379     AliTOFChannelOnlineStatus * calChOnlineStNoise = new AliTOFChannelOnlineStatus();
380     AliTOFChannelOnlineStatus * calChOnlineStHW = new AliTOFChannelOnlineStatus();
381     AliTOFChannelOffline * calChOffline = new AliTOFChannelOffline();
382     fTOFCalOnline->AddAt(calChOnline,iarray);
383     fTOFCalOnlinePulser->AddAt(calChOnlineStPulser,iarray);
384     fTOFCalOnlineNoise->AddAt(calChOnlineStNoise,iarray);
385     fTOFCalOnlineHW->AddAt(calChOnlineStHW,iarray);
386     fTOFCalOffline->AddAt(calChOffline,iarray);
387   }
388   fCal = new AliTOFChannelOnlineArray(fNChannels);
389   fStatus = new AliTOFChannelOnlineStatusArray(fNChannels);
390 }
391 //_____________________________________________________________________________
392 void AliTOFcalib::CreateCalObjects(){
393
394   // creating arrays for online/offline calibration objs
395
396   fTOFCalOffline = new TObjArray(fNChannels);
397   fTOFCalOffline->SetOwner();
398   for (Int_t iarray = 0; iarray<fNChannels; iarray++){
399     AliTOFChannelOffline * calChOffline = new AliTOFChannelOffline();
400     fTOFCalOffline->AddAt(calChOffline,iarray);
401   }
402   fCal = new AliTOFChannelOnlineArray(fNChannels);
403   fStatus = new AliTOFChannelOnlineStatusArray(fNChannels);
404 }
405 //_____________________________________________________________________________
406 void AliTOFcalib::WriteConfigMapOnCDB(const Char_t *sel, Int_t minrun, Int_t maxrun)
407 {
408   //Write calibration parameters to the CDB
409   SetFirstRun(minrun);
410   SetLastRun(maxrun);
411   AliCDBManager *man = AliCDBManager::Instance();
412   const Char_t *sel1 = "Config" ;  // to be consistent with TOFPreprocessor
413   TString out(Form("%s/%s",sel,sel1));
414   AliDebug(2,Form("Writing TOF configuration map for online calib on CDB with run range [%i, %i] ",fFirstRun,fLastRun));
415   AliCDBId id(out,fFirstRun,fLastRun);
416   AliCDBMetaData *md = new AliCDBMetaData();
417   md->SetResponsible("Chiara Zampolli");
418   if (!fConfigMap) {
419     // deve uscire!!
420   }
421   man->Put(fConfigMap,id,md);
422   delete md;
423 }
424 //_____________________________________________________________________________
425
426 void AliTOFcalib::WriteConfigMapOnCDB(const Char_t *sel)
427 {
428   //Write calibration parameters to the CDB with infinite validity
429   AliCDBManager *man = AliCDBManager::Instance();
430   const Char_t *sel1 = "Config" ;  // to be consistent with TOFPreprocessor
431   TString out(Form("%s/%s",sel,sel1));
432   AliCDBRunRange runrange(fFirstRun,fLastRun);
433   AliDebug(2,Form("Writing TOF config map for online calib on CDB with run range [%i, %i] ",runrange.GetFirstRun(),runrange.GetLastRun()));
434   AliCDBId id(out,runrange);
435   AliCDBMetaData *md = new AliCDBMetaData();
436   md->SetResponsible("Chiara Zampolli");
437   if (!fConfigMap) {
438     // deve uscire!!
439   }
440   man->Put(fConfigMap,id,md);
441   delete md;
442 }
443 //_____________________________________________________________________________
444 void AliTOFcalib::WriteParOnlineDelayOnCDB(const Char_t *sel, Int_t minrun, Int_t maxrun)
445 {
446   //Write calibration parameters to the CDB -------> new calib objs!!!!!
447   SetFirstRun(minrun);
448   SetLastRun(maxrun);
449   AliCDBManager *man = AliCDBManager::Instance();
450   const Char_t *sel1 = "ParOnlineDelay" ;  // to be consistent with TOFPreprocessor
451   TString out(Form("%s/%s",sel,sel1));
452   AliDebug(2,Form("Writing TOF online calib obj on CDB with run range [%i, %i] ",fFirstRun,fLastRun));
453   AliCDBId id(out,fFirstRun,fLastRun);
454   AliCDBMetaData *md = new AliCDBMetaData();
455   md->SetResponsible("Chiara Zampolli");
456   if (!fCal) {
457     // deve uscire!!
458   }
459   man->Put(fCal,id,md);
460   delete md;
461 }
462 //_____________________________________________________________________________
463 void AliTOFcalib::WriteParOnlineStatusOnCDB(const Char_t *sel, Int_t minrun, Int_t maxrun)
464 {
465   //Write calibration parameters to the CDB -------> new calib objs!!!!!
466   SetFirstRun(minrun);
467   SetLastRun(maxrun);
468   AliCDBManager *man = AliCDBManager::Instance();
469   const Char_t *sel1 = "Status" ;  // to be consistent with TOFPreprocessor
470   TString out(Form("%s/%s",sel,sel1));
471   AliDebug(2,Form("Writing TOF online status calib obj on CDB with run range [%i, %i] ",fFirstRun,fLastRun));
472   AliCDBId id(out,fFirstRun,fLastRun);
473   AliCDBMetaData *md = new AliCDBMetaData();
474   md->SetResponsible("Chiara Zampolli");
475   if (!fStatus) {
476     // deve uscire!!
477   }
478   man->Put(fStatus,id,md);
479   delete md;
480 }
481 //_____________________________________________________________________________
482
483 void AliTOFcalib::WriteParOnlineDelayOnCDB(const Char_t *sel)
484 {
485   //Write calibration parameters to the CDB with infinite validity -------> new calib objs!!!!!
486   AliCDBManager *man = AliCDBManager::Instance();
487   const Char_t *sel1 = "ParOnlineDelay" ;  // to be consistent with TOFPreprocessor
488   TString out(Form("%s/%s",sel,sel1));
489   AliCDBRunRange runrange(fFirstRun,fLastRun);
490   AliDebug(2,Form("Writing TOF online calib obj on CDB with run range [%i, %i] ",runrange.GetFirstRun(),runrange.GetLastRun()));
491   AliCDBId id(out,runrange);
492   AliCDBMetaData *md = new AliCDBMetaData();
493   md->SetResponsible("Chiara Zampolli");
494   if (!fCal) {
495     // deve uscire!!
496   }
497   man->Put(fCal,id,md);
498   delete md;
499 }
500 //_____________________________________________________________________________
501
502 void AliTOFcalib::WriteParOnlineStatusOnCDB(const Char_t *sel)
503 {
504   //Write calibration parameters to the CDB with infinite validity -------> new calib objs!!!!!
505   AliCDBManager *man = AliCDBManager::Instance();
506   const Char_t *sel1 = "Status" ;  // to be consistent with TOFPreprocessor
507   TString out(Form("%s/%s",sel,sel1));
508   AliCDBRunRange runrange(fFirstRun,fLastRun);
509   AliDebug(2,Form("Writing TOF online status calib obj on CDB with run range [%i, %i] ",runrange.GetFirstRun(),runrange.GetLastRun()));
510   AliCDBId id(out,runrange);
511   AliCDBMetaData *md = new AliCDBMetaData();
512   md->SetResponsible("Chiara Zampolli");
513   if (!fStatus) {
514     // deve uscire!!
515   }
516   man->Put(fStatus,id,md);
517   delete md;
518 }
519 //_____________________________________________________________________________
520 void AliTOFcalib::WriteParOnlineOnCDB(const Char_t *sel, Int_t minrun, Int_t maxrun)
521 {
522   //Write calibration parameters to the CDB
523   SetFirstRun(minrun);
524   SetLastRun(maxrun);
525   AliCDBManager *man = AliCDBManager::Instance();
526   const Char_t *sel1 = "ParOnline" ;  // to be consistent with TOFPreprocessor
527   TString out(Form("%s/%s",sel,sel1));
528   AliDebug(2,Form("Writing TOF online calib obj on CDB with run range [%i, %i] ",fFirstRun,fLastRun));
529   AliCDBId id(out,fFirstRun,fLastRun);
530   AliCDBMetaData *md = new AliCDBMetaData();
531   md->SetResponsible("Chiara Zampolli");
532   if (!fTOFCalOnline) {
533     // deve uscire!!
534   }
535   man->Put(fTOFCalOnline,id,md);
536   delete md;
537 }
538 //_____________________________________________________________________________
539 void AliTOFcalib::WriteParOnlinePulserOnCDB(const Char_t *sel, Int_t minrun, Int_t maxrun)
540 {
541   //Write calibration parameters from pulser to the CDB
542   SetFirstRun(minrun);
543   SetLastRun(maxrun);
544   AliCDBManager *man = AliCDBManager::Instance();
545   const Char_t *sel1 = "Pulser" ;  // to be consistent with TOFPreprocessor
546   TString out(Form("%s/%s",sel,sel1));
547   AliDebug(2,Form("Writing TOF online calib obj from pulser on CDB with run range [%i, %i] ",fFirstRun,fLastRun));
548   AliCDBId id(out,fFirstRun,fLastRun);
549   AliCDBMetaData *md = new AliCDBMetaData();
550   md->SetResponsible("Chiara Zampolli");
551   if (!fTOFCalOnlinePulser) {
552     // deve uscire!!
553   }
554   man->Put(fTOFCalOnlinePulser,id,md);
555   delete md;
556 }
557 //_____________________________________________________________________________
558 void AliTOFcalib::WriteParOnlineNoiseOnCDB(const Char_t *sel, Int_t minrun, Int_t maxrun)
559 {
560   //Write calibration parameters from noise to the CDB
561   SetFirstRun(minrun);
562   SetLastRun(maxrun);
563   AliCDBManager *man = AliCDBManager::Instance();
564   const Char_t *sel1 = "Noise" ;  // to be consistent with TOFPreprocessor
565   TString out(Form("%s/%s",sel,sel1));
566   AliDebug(2,Form("Writing TOF online calib obj from noise on CDB with run range [%i, %i] ",fFirstRun,fLastRun));
567   AliCDBId id(out,fFirstRun,fLastRun);
568   AliCDBMetaData *md = new AliCDBMetaData();
569   md->SetResponsible("Chiara Zampolli");
570   if (!fTOFCalOnlineNoise) {
571     // deve uscire!!
572   }
573   man->Put(fTOFCalOnlineNoise,id,md);
574   delete md;
575 }
576 //_____________________________________________________________________________
577 void AliTOFcalib::WriteParOnlineHWOnCDB(const Char_t *sel, Int_t minrun, Int_t maxrun)
578 {
579   //Write calibration parameters from hardware to the CDB
580   SetFirstRun(minrun);
581   SetLastRun(maxrun);
582   AliCDBManager *man = AliCDBManager::Instance();
583   const Char_t *sel1 = "HW" ;  // to be consistent with TOFPreprocessor
584   TString out(Form("%s/%s",sel,sel1));
585   AliDebug(2,Form("Writing TOF online calib obj from hardware on CDB with run range [%i, %i] ",fFirstRun,fLastRun));
586   AliCDBId id(out,fFirstRun,fLastRun);
587   AliCDBMetaData *md = new AliCDBMetaData();
588   md->SetResponsible("Chiara Zampolli");
589   if (!fTOFCalOnlineHW) {
590     // deve uscire!!
591   }
592   man->Put(fTOFCalOnlineHW,id,md);
593   delete md;
594 }
595 //_____________________________________________________________________________
596
597 void AliTOFcalib::WriteParOnlineOnCDB(const Char_t *sel)
598 {
599   //Write calibration parameters to the CDB with infinite validity
600   AliCDBManager *man = AliCDBManager::Instance();
601   const Char_t *sel1 = "ParOnline" ;  // to be consistent with TOFPreprocessor
602   TString out(Form("%s/%s",sel,sel1));
603   AliCDBRunRange runrange(fFirstRun,fLastRun);
604   AliDebug(2,Form("Writing TOF online calib obj on CDB with run range [%i, %i] ",runrange.GetFirstRun(),runrange.GetLastRun()));
605   AliCDBId id(out,runrange);
606   AliCDBMetaData *md = new AliCDBMetaData();
607   md->SetResponsible("Chiara Zampolli");
608   if (!fTOFCalOnline) {
609     // deve uscire!!
610   }
611   man->Put(fTOFCalOnline,id,md);
612   delete md;
613 }
614 //_____________________________________________________________________________
615
616 void AliTOFcalib::WriteParOnlinePulserOnCDB(const Char_t *sel)
617 {
618   //Write calibration parameters from pulser to the CDB with infinite validity
619   AliCDBManager *man = AliCDBManager::Instance();
620   const Char_t *sel1 = "Pulser" ;  // to be consistent with TOFPreprocessor
621   TString out(Form("%s/%s",sel,sel1));
622   AliCDBRunRange runrange(fFirstRun,fLastRun);
623   AliDebug(2,Form("Writing TOF online calib obj from pulser on CDB with run range [%i, %i] ",runrange.GetFirstRun(),runrange.GetLastRun()));
624   AliCDBId id(out,runrange);
625   AliCDBMetaData *md = new AliCDBMetaData();
626   md->SetResponsible("Chiara Zampolli");
627   if (!fTOFCalOnlinePulser) {
628     // deve uscire!!
629   }
630   man->Put(fTOFCalOnlinePulser,id,md);
631   delete md;
632 }
633 //_____________________________________________________________________________
634
635 void AliTOFcalib::WriteParOnlineNoiseOnCDB(const Char_t *sel)
636 {
637   //Write calibration parameters from noise to the CDB with infinite validity
638   AliCDBManager *man = AliCDBManager::Instance();
639   const Char_t *sel1 = "Noise" ;  // to be consistent with TOFPreprocessor
640   TString out(Form("%s/%s",sel,sel1));
641   AliCDBRunRange runrange(fFirstRun,fLastRun);
642   AliDebug(2,Form("Writing TOF online calib obj from noise on CDB with run range [%i, %i] ",runrange.GetFirstRun(),runrange.GetLastRun()));
643   AliCDBId id(out,runrange);
644   AliCDBMetaData *md = new AliCDBMetaData();
645   md->SetResponsible("Chiara Zampolli");
646   if (!fTOFCalOnlineNoise) {
647     // deve uscire!!
648   }
649   man->Put(fTOFCalOnlineNoise,id,md);
650   delete md;
651 }
652 //_____________________________________________________________________________
653
654 void AliTOFcalib::WriteParOnlineHWOnCDB(const Char_t *sel)
655 {
656   //Write calibration parameters from hardware to the CDB with infinite validity
657   AliCDBManager *man = AliCDBManager::Instance();
658   const Char_t *sel1 = "HW" ;  // to be consistent with TOFPreprocessor
659   TString out(Form("%s/%s",sel,sel1));
660   AliCDBRunRange runrange(fFirstRun,fLastRun);
661   AliDebug(2,Form("Writing TOF online calib obj from harware on CDB with run range [%i, %i] ",runrange.GetFirstRun(),runrange.GetLastRun()));
662   AliCDBId id(out,runrange);
663   AliCDBMetaData *md = new AliCDBMetaData();
664   md->SetResponsible("Chiara Zampolli");
665   if (!fTOFCalOnlineHW) {
666     // deve uscire!!
667   }
668   man->Put(fTOFCalOnlineHW,id,md);
669   delete md;
670 }
671 //_____________________________________________________________________________
672
673 void AliTOFcalib::WriteParOfflineOnCDB(const Char_t *sel, const Char_t *validity, Int_t minrun, Int_t maxrun)
674 {
675   //Write calibration parameters to the CDB
676   SetFirstRun(minrun);
677   SetLastRun(maxrun);
678   AliCDBManager *man = AliCDBManager::Instance();
679   const Char_t *sel1 = "ParOffline" ;
680   TString out(Form("%s/%s",sel,sel1));
681   AliDebug(2,Form("Writing TOF offline calib obj on CDB with run range [%i, %i] ",fFirstRun,fLastRun));
682   AliCDBId id(out,fFirstRun,fLastRun);
683   AliCDBMetaData *md = new AliCDBMetaData();
684   md->SetResponsible("Chiara Zampolli");
685   md->SetComment(validity);
686   man->Put(fTOFCalOffline,id,md);
687   delete md;
688 }
689 //_____________________________________________________________________________
690
691 void AliTOFcalib::WriteParOfflineOnCDB(const Char_t *sel, const Char_t *validity)
692 {
693   //Write calibration parameters to the CDB with infinite validity
694   AliCDBManager *man = AliCDBManager::Instance();
695   const Char_t *sel1 = "ParOffline" ;
696   TString out(Form("%s/%s",sel,sel1));
697   AliCDBRunRange runrange(fFirstRun,fLastRun);
698   AliDebug(2,Form("Writing TOF offline calib obj on CDB with run range [%i, %i] ",runrange.GetFirstRun(),runrange.GetLastRun()));
699   AliCDBId id(out,runrange);
700   AliCDBMetaData *md = new AliCDBMetaData();
701   md->SetResponsible("Chiara Zampolli");
702   md->SetComment(validity);
703   man->Put(fTOFCalOffline,id,md);
704   delete md;
705 }
706 //_____________________________________________________________________________
707
708 Bool_t AliTOFcalib::ReadConfigMapFromCDB(const Char_t *sel, Int_t nrun)
709 {
710   //Read calibration parameters from the CDB
711   AliCDBManager *man = AliCDBManager::Instance();
712   const Char_t *sel1 = "Config" ;
713   TString out(Form("%s/%s",sel,sel1));
714   AliCDBEntry *entry = man->Get(out,nrun);
715   if (!entry) { 
716     AliFatal("Exiting, no CDB object (ConfigMap) found!!!");
717     exit(0);  
718   }
719   if(!entry->GetObject()){
720     AliFatal("Exiting, no CDB object (ConfigMap) found!!!");
721     exit(0);  
722   }  
723   
724   fConfigMap =(TMap*)entry->GetObject();
725
726   return kTRUE; 
727    
728 }
729 //_____________________________________________________________________________
730
731 Bool_t AliTOFcalib::ReadParOnlineDelayFromCDB(const Char_t *sel, Int_t nrun)
732 {
733   //Read calibration parameters from the CDB -------> new calib objs!!!!!
734   AliCDBManager *man = AliCDBManager::Instance();
735   const Char_t *sel1 = "ParOnlineDelay" ;
736   TString out(Form("%s/%s",sel,sel1));
737   AliCDBEntry *entry = man->Get(out,nrun);
738   if (!entry) { 
739     AliFatal("Exiting, no CDB object (ParOnlineDelay) found!!!");
740     exit(0);  
741   }
742   if(!entry->GetObject()){
743     AliFatal("Exiting, no CDB object (ParOnlineDelay) found!!!");
744     exit(0);  
745   }  
746   
747   fCal =(AliTOFChannelOnlineArray*)entry->GetObject();
748
749   return kTRUE; 
750    
751 }
752 //_____________________________________________________________________________
753
754 Bool_t AliTOFcalib::ReadParOnlineStatusFromCDB(const Char_t *sel, Int_t nrun)
755 {
756   //Read calibration parameters from the CDB -------> new calib objs!!!!!
757   AliCDBManager *man = AliCDBManager::Instance();
758   const Char_t *sel1 = "Status" ;
759   TString out(Form("%s/%s",sel,sel1));
760   AliCDBEntry *entry = man->Get(out,nrun);
761   if (!entry) { 
762     AliFatal("Exiting, no CDB object (Status) found!!!");
763     exit(0);  
764   }
765   if(!entry->GetObject()){
766     AliFatal("Exiting, no CDB object (Status) found!!!");
767     exit(0);  
768   }  
769   
770   fStatus =(AliTOFChannelOnlineStatusArray*)entry->GetObject();
771
772   return kTRUE; 
773    
774 }
775 //_____________________________________________________________________________
776
777 Bool_t AliTOFcalib::ReadParOnlineFromCDB(const Char_t *sel, Int_t nrun)
778 {
779   //Read calibration parameters from the CDB
780   AliCDBManager *man = AliCDBManager::Instance();
781   const Char_t *sel1 = "ParOnline" ;
782   TString out(Form("%s/%s",sel,sel1));
783   AliCDBEntry *entry = man->Get(out,nrun);
784   if (!entry) { 
785     AliFatal("Exiting, no CDB object (ParOnline) found!!!");
786     exit(0);  
787   }
788   if(!entry->GetObject()){
789     AliFatal("Exiting, no CDB object (ParOnline) found!!!");
790     exit(0);  
791   }  
792   
793   fTOFCalOnline =(TObjArray*)entry->GetObject();
794
795   return kTRUE; 
796    
797 }
798 //_____________________________________________________________________________
799
800 Bool_t AliTOFcalib::ReadParOnlinePulserFromCDB(const Char_t *sel, Int_t nrun)
801 {
802   //Read calibration parameters from pulser from the CDB
803   AliCDBManager *man = AliCDBManager::Instance();
804   const Char_t *sel1 = "Pulser" ;
805   TString out(Form("%s/%s",sel,sel1));
806   AliCDBEntry *entry = man->Get(out,nrun);
807   if (!entry) { 
808     AliFatal("Exiting, no CDB object (Pulser) found!!!");
809     exit(0);  
810   }
811   if(!entry->GetObject()){
812     AliFatal("Exiting, no CDB object (Pulser) found!!!");
813     exit(0);  
814   }  
815   
816   fTOFCalOnlinePulser =(TObjArray*)entry->GetObject();
817
818   return kTRUE; 
819    
820 }
821 //_____________________________________________________________________________
822
823 Bool_t AliTOFcalib::ReadParOnlineNoiseFromCDB(const Char_t *sel, Int_t nrun)
824 {
825   //Read calibration parameters from noise from the CDB
826   AliCDBManager *man = AliCDBManager::Instance();
827   const Char_t *sel1 = "Noise" ;
828   TString out(Form("%s/%s",sel,sel1));
829   AliCDBEntry *entry = man->Get(out,nrun);
830   if (!entry) { 
831     AliFatal("Exiting, no CDB object (Noise) found!!!");
832     exit(0);  
833   }
834   if(!entry->GetObject()){
835     AliFatal("Exiting, no CDB object (Noise) found!!!");
836     exit(0);  
837   }  
838   
839   fTOFCalOnlineNoise =(TObjArray*)entry->GetObject();
840
841   return kTRUE; 
842    
843 }
844 //_____________________________________________________________________________
845
846 Bool_t AliTOFcalib::ReadParOnlineHWFromCDB(const Char_t *sel, Int_t nrun)
847 {
848   //Read calibration parameters from hardware from the CDB
849   AliCDBManager *man = AliCDBManager::Instance();
850   const Char_t *sel1 = "HW" ;
851   TString out(Form("%s/%s",sel,sel1));
852   AliCDBEntry *entry = man->Get(out,nrun);
853   if (!entry) { 
854     AliFatal("Exiting, no CDB object (HW map) found!!!");
855     exit(0);  
856   }
857   if(!entry->GetObject()){
858     AliFatal("Exiting, no CDB object (HW map) found!!!");
859     exit(0);  
860   }  
861   
862   fTOFCalOnlineHW =(TObjArray*)entry->GetObject();
863
864   return kTRUE; 
865    
866 }
867 //_____________________________________________________________________________
868
869 Bool_t AliTOFcalib::ReadParOfflineFromCDB(const Char_t *sel, Int_t nrun)
870 {
871   //Read calibration parameters from the CDB
872   AliCDBManager *man = AliCDBManager::Instance();
873   const Char_t *sel1 = "ParOffline" ;
874   TString out(Form("%s/%s",sel,sel1));
875   AliCDBEntry *entry = man->Get(out,nrun);
876   if (!entry) { 
877     AliFatal("Exiting, no CDB object (ParOffline) found!!!");
878     exit(0);  
879   }
880   if(!entry->GetObject()){
881     AliFatal("Exiting, no CDB object (ParOffline) found!!!");
882     exit(0);  
883   }  
884   AliCDBMetaData * md = entry->GetMetaData();
885   fkValidity = md->GetComment();  
886   fTOFCalOffline =(TObjArray*)entry->GetObject();
887
888   return kTRUE; 
889    
890 }
891 //_____________________________________________________________________________
892 void AliTOFcalib::WriteSimHistoOnCDB(const Char_t *sel, Int_t minrun, Int_t maxrun, TH1F *histo){
893   //Write Sim miscalibration parameters to the CDB
894
895   fTOFSimToT=histo;
896   AliCDBManager *man = AliCDBManager::Instance();
897   const Char_t *sel1 = "SimHisto" ;
898   TString out(Form("%s/%s",sel,sel1));
899   AliCDBMetaData *mdhisto = new AliCDBMetaData();
900   mdhisto->SetResponsible("Chiara Zampolli");
901   AliCDBId id(out,minrun,maxrun);
902   man->Put(fTOFSimToT,id,mdhisto);
903   delete mdhisto;
904 }
905 //_____________________________________________________________________________
906 Bool_t AliTOFcalib::ReadSimHistoFromCDB(const Char_t *sel, Int_t nrun)
907 {
908   //Read miscalibration parameters from the CDB
909   AliCDBManager *man = AliCDBManager::Instance();
910
911   // The Tot Histo
912
913   const Char_t *sel1 = "SimHisto" ;
914   TString out(Form("%s/%s",sel,sel1));
915   AliCDBEntry *entry = man->Get(out,nrun);
916   if (!entry) { 
917     AliFatal("Exiting, no CDB object (SimHisto) found!!!");
918     exit(0);  
919   }
920   if(!entry->GetObject()){
921     AliFatal("Exiting, no CDB object (SimHisto) found!!!");
922     exit(0);  
923   }  
924   TH1F *histo =(TH1F*)entry->GetObject();
925   fTOFSimToT=histo;
926   return kTRUE;
927 }
928 //_____________________________________________________________________________
929 void AliTOFcalib::WriteRecParOnCDB(const Char_t *sel, Int_t minrun, Int_t maxrun, AliTOFRecoParam *param){
930   //Write reconstruction parameters to the CDB
931
932   AliCDBManager *man = AliCDBManager::Instance();
933   AliCDBMetaData *md = new AliCDBMetaData();
934   md->SetResponsible("Silvia Arcelli");
935   const Char_t *sel1 = "RecoParam" ;
936   TString out(Form("%s/%s",sel,sel1));
937   AliCDBId id(out,minrun,maxrun);
938
939   TObjArray *arr=new TObjArray(1);
940   arr->AddLast(param);
941   man->Put(arr,id,md);
942   //man->Put(param,id,md);
943   delete md;
944 }
945 //_____________________________________________________________________________
946 void AliTOFcalib::WriteRecParOnCDB(const Char_t *sel, Int_t minrun, Int_t maxrun, TObjArray *arr){
947   //Write reconstruction parameters to the CDB
948
949   AliCDBManager *man = AliCDBManager::Instance();
950   AliCDBMetaData *md = new AliCDBMetaData();
951   md->SetResponsible("Silvia Arcelli");
952   const Char_t *sel1 = "RecoParam" ;
953   TString out(Form("%s/%s",sel,sel1));
954   AliCDBId id(out,minrun,maxrun);
955   man->Put(arr,id,md);
956   delete md;
957 }
958 //_____________________________________________________________________________
959 AliTOFRecoParam * AliTOFcalib::ReadRecParFromCDB(const Char_t *sel, Int_t nrun, Int_t eventType)
960 {
961   //Read reconstruction parameters from the CDB
962   AliCDBManager *man = AliCDBManager::Instance();
963   const Char_t *sel1 = "RecoParam" ;
964   TString out(Form("%s/%s",sel,sel1));
965   AliCDBEntry *entry = man->Get(out,nrun);
966   if (!entry) { 
967     AliFatal("Exiting, no CDB object (RecoParam) found!!!");
968     exit(0);  
969   }  
970   if(!entry->GetObject()){
971     AliFatal("Exiting, no CDB object (RecoParam) found!!!");
972     exit(0);  
973   }  
974
975   TObjArray *array = (TObjArray*)entry->GetObject();
976   AliTOFRecoParam *param=0x0;
977   if (eventType>=0 || eventType<array->GetEntries())
978     param=(AliTOFRecoParam*)array->At(eventType);
979   return param;
980
981 }
982 //-----------------------------------------------------------------------------
983 // Calibration methods
984 //-----------------------------------------------------------------------------
985 void AliTOFcalib::CreateTreeFromCDB(Int_t minrun, Int_t maxrun){
986
987   // creating the chain with the trees for calibration
988   // collecting them from reference data 
989   // from minrun to maxrun
990
991   Float_t p[CHENTRIESSMALL];
992   Int_t nentries;
993   fTree = new TTree("TOFCalib","Tree for TOF Calibration");
994   fTree->Branch("nentries",&nentries,"nentries/I");
995   fTree->Branch("TOFentries",p,"TOFentries[nentries]/F");
996   AliCDBManager *man = AliCDBManager::Instance();
997   AliCDBStorage *aStorage = man->GetStorage("local://$ALICE_ROOT/OCDB");
998   for (Int_t irun = minrun;irun<=maxrun;irun++){
999     AliCDBEntry *entry = aStorage->Get("TOF/RefData/TreeForCalib",irun);
1000     if (!entry){
1001       AliInfo(Form("No entry found for run %i",irun));
1002     }
1003     else{
1004       TTree *tree = (TTree*)entry->GetObject();
1005       tree->SetBranchAddress("nentries",&nentries);
1006       tree->SetBranchAddress("TOFentries",p);      
1007       fTree->CopyEntries(tree);
1008       fNruns++;
1009     }
1010   }
1011   AliInfo(Form("Number of runs being analyzed %i",fNruns));
1012 }
1013 //-----------------------------------------------------------------------------
1014 void AliTOFcalib::CreateTreeFromGrid(Int_t minrun, Int_t maxrun){
1015
1016   // creating the chain with the trees for calibration
1017   // collecting them from the Grid 
1018   // from minrun to maxrun
1019
1020   Float_t p[CHENTRIESSMALL];
1021   Int_t nentries;
1022   fTree = new TTree("TOFCalib","Tree for TOF Calibration");
1023   fTree->SetDirectory(0);
1024   fTree->Branch("nentries",&nentries,"nentries/I");
1025   fTree->Branch("TOFentries",p,"TOFentries[nentries]/F");
1026   AliInfo("connected to alien");
1027   TGrid::Connect("alien://");
1028   
1029   TString filename;
1030   for (Int_t irun = minrun;irun<=maxrun;irun++){
1031     filename = Form("alien:///alice/cern.ch/user/c/czampolli/TOFCalibReference_%i.root",irun);
1032     TFile *filegrid = TFile::Open(filename.Data(),"READ");
1033     TTree *tree = (TTree*)filegrid->Get("T");
1034     tree->SetBranchAddress("nentries",&nentries);
1035     tree->SetBranchAddress("TOFentries",p);      
1036     fTree->CopyEntries(tree);
1037     delete tree;
1038     fNruns++;    
1039   }
1040   
1041   AliInfo(Form("Number of runs being analyzed %i",fNruns));
1042 }
1043 //-----------------------------------------------------------------------------
1044 void AliTOFcalib::CreateTreeFromFile(Int_t minrun, Int_t maxrun){
1045
1046   // creating the tree with the trees for calibration
1047   // collecting them from reference data (from file)
1048   // from minrun to maxrun
1049
1050   Float_t p[CHENTRIESSMALL];
1051   Int_t nentries;
1052   fTree = new TTree("TOFCalib","Tree for TOF Calibration");
1053   fTree->SetDirectory(0);
1054   fTree->Branch("nentries",&nentries,"nentries/I");
1055   fTree->Branch("TOFentries",p,"TOFentries[nentries]/F");
1056   TString filename;
1057   for (Int_t irun = minrun;irun<=maxrun;irun++){
1058     filename = Form("$ALICE_ROOT/TOF/RefData/TreeForCalib/fileout_%i.root",irun);
1059     TFile *file = new TFile(filename.Data(),"READ");
1060     TTree *tree = (TTree*)file->Get("T");
1061     tree->SetBranchAddress("nentries",&nentries);
1062     tree->SetBranchAddress("TOFentries",p);      
1063     fTree->CopyEntries(tree);
1064     delete tree;
1065     delete file;
1066     file = 0x0;
1067     fNruns++;
1068   }
1069
1070   AliInfo(Form("Number of runs being analyzed %i",fNruns));
1071 }
1072 //-----------------------------------------------------------------------------
1073 void AliTOFcalib::CreateChainFromGrid(Int_t minrun, Int_t maxrun){
1074
1075   // creating the chain with the trees for calibration
1076   // collecting them from the Grid 
1077   // from minrun to maxrun
1078
1079   fChain = new TChain("T");
1080   AliInfo("connected to alien");
1081   TGrid::Connect("alien://");
1082   
1083   TString filename;
1084   for (Int_t irun = minrun;irun<=maxrun;irun++){
1085     filename = Form("alien:///alice/cern.ch/user/c/czampolli/TOFCalibReference_%i.root",irun);
1086     fChain->Add(filename.Data());
1087     fNruns++;    
1088   }
1089   
1090   AliInfo(Form("Number of runs being analyzed %i",fNruns));
1091 }
1092 //-----------------------------------------------------------------------------
1093 Int_t AliTOFcalib::Calibrate(Int_t ichmin, Int_t ichmax, Option_t *optionSave, Option_t *optionFit){
1094
1095   // calibrating summing more than one channels
1096   // computing calibration parameters
1097   // Returning codes:
1098   // 0 -> everything was ok
1099   // 1 -> no tree for calibration found
1100   // 2 -> not enough statistics to perform calibration
1101   // 3 -> problems with arrays
1102   
1103   TH1::AddDirectory(0);
1104
1105   AliInfo(Form("*** Calibrating Histograms %s, summing more channels, from channel %i, to channel %i, storing Calib Pars in channel %i", GetName(),ichmin,ichmax,ichmin)) ; 
1106   AliInfo(Form("Option for Saving histos = %s",optionSave )) ; 
1107   AliInfo(Form("Option for Fitting Profile histos = %s",optionFit )) ; 
1108
1109   Float_t p[CHENTRIESSMALL];
1110   Int_t nentries;
1111   //fTree->SetBranchAddress("nentries",&nentries);
1112   //fTree->SetBranchAddress("TOFentries",p);
1113   fChain->SetBranchAddress("nentries",&nentries);
1114   fChain->SetBranchAddress("TOFentries",p);
1115
1116   Float_t ntracksTotalmean =0;
1117   for (Int_t i=ichmin; i<ichmax; i++){
1118     Int_t ientry = -1;
1119     for (Int_t irun=0;irun<fNruns;irun++){
1120       ientry = i+irun*fNChannels;
1121       //fTree->GetEntry(ientry);
1122       fChain->GetEntry(ientry);
1123       Int_t ntracksRun=nentries/3;
1124       ntracksTotalmean+=ntracksRun;
1125     }
1126   }
1127   
1128   if (ntracksTotalmean < MEANENTRIES) {
1129     AliInfo(Form(" Too small mean number of entires per channel (mean number = %f) not calibrating and exiting.....",ntracksTotalmean));
1130     return 2;
1131   }
1132
1133   //filling ToT and Time arrays
1134
1135   Int_t nbinToT = 100;  // ToT bin width in Profile = 48.8 ps 
1136   Float_t minToT = 0;   // ns
1137   Float_t maxToT = 4.88;  // ns
1138
1139   TH1F *hToT = new TH1F("htot","htot",nbinToT, minToT, maxToT);
1140   TH1F *hdeltaTime = new TH1F("hdeltaTime","hdeltaTime",200,2,4);
1141   Int_t ntracksTotal = 0;
1142   Int_t ntracksRun = 0;
1143   Double_t binsProfile[101]; // sized larger than necessary, the correct 
1144                              // dim being set in the booking of the profile
1145   Int_t nusefulbins=0;
1146   Float_t meantime=0;
1147   for (Int_t i = ichmin;i<ichmax;i++){
1148     Int_t ientry = -1;
1149     for (Int_t irun=0;irun<fNruns;irun++){
1150       ientry = i+irun*fNChannels;
1151       //fTree->GetEntry(ientry);
1152       fChain->GetEntry(ientry);
1153       ntracksTotal+=nentries/3;
1154       ntracksRun=nentries/3;
1155       AliDebug(2,Form("run %i, channel %i, nentries = %i, ntracks = %i",irun,i,nentries, ntracksRun));
1156       for (Int_t j=0;j<ntracksRun;j++){
1157         Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1158         Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1159         Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1160         Float_t tot = p[idxexToT];
1161         hdeltaTime->Fill(p[idxexTime]-p[idxexExTime]);
1162         meantime+=p[idxexTime]-p[idxexExTime];
1163         hToT->Fill(tot);
1164       }
1165     }
1166   }
1167   nusefulbins = FindBins(hToT,&binsProfile[0]);
1168   if (ntracksTotal != 0){
1169           meantime/=ntracksTotal;
1170   }
1171   AliDebug(2, Form("meantime = %f",meantime));
1172   
1173   for (Int_t j=1;j<=nusefulbins;j++) {
1174     AliDebug(2,Form(" summing channels from %i to %i, nusefulbins = %i, bin %i = %f",ichmin,ichmax,nusefulbins,j,binsProfile[j])); 
1175   }
1176
1177   TProfile* hSlewingProf = new TProfile("hSlewingProf", "hSlewingProf",nusefulbins, binsProfile, "G");  // CHECK THE BUILD OPTION, PLEASE!!!!!!
1178   TH2F * htimetot = new TH2F("htimetot","htimetot",nbinToT, minToT, maxToT,600,-5,10);
1179
1180   for (Int_t irun=0;irun<fNruns;irun++){
1181     Int_t ientry = -1;
1182     for (Int_t i=ichmin; i<ichmax; i++){
1183       ientry = i+irun*fNChannels;
1184       //fTree->GetEntry(ientry);
1185       fChain->GetEntry(ientry);
1186       ntracksRun=nentries/3;
1187       for (Int_t j=0;j<ntracksRun;j++){
1188         Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1189         Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1190         Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1191         Float_t tot = p[idxexToT];
1192         Float_t time = p[idxexTime]-p[idxexExTime];
1193         AliDebug (2, Form("track = %i, time = %f, tot = %f, time-meantime = %f",j,time, tot, time-meantime));
1194         hSlewingProf->Fill(tot,time);  // if meantime is not used, the fill may be moved in the loop above
1195         htimetot->Fill(tot,time-meantime);  // if meantime is not used, the fill may be moved in the loop above
1196       }
1197     }
1198   }
1199
1200   hSlewingProf->Fit("pol5",optionFit,"",0,4);
1201   TF1 * calibfunc = (TF1*)hSlewingProf->GetFunction("pol5");
1202   Float_t par[6];    
1203   for(Int_t kk=0;kk<6;kk++){
1204     par[kk]=calibfunc->GetParameter(kk);
1205     AliDebug(2,Form("parameter %i = %f",kk,par[kk]));
1206   }
1207
1208   if(strstr(optionSave,"save")){
1209     TFile * fileProf = new TFile("TOFCalibSave.root","recreate");
1210     fileProf->cd(); 
1211     TString profName=Form("Profile%06i_%06i",ichmin,ichmax);
1212     TString timeTotName=Form("TimeTot%06i_%06i",ichmin,ichmax);
1213     TString totName=Form("Tot%06i_%06i",ichmin,ichmax);
1214     TString deltaName=Form("Delta%06i_%06i",ichmin,ichmax);
1215     hSlewingProf->Write(profName);
1216     htimetot->Write(timeTotName);
1217     hToT->Write(totName);
1218     hdeltaTime->Write(deltaName);
1219     fileProf->Close();
1220     delete fileProf;
1221     fileProf=0x0;
1222   }
1223
1224   delete hToT;
1225   hToT=0x0;
1226   delete hSlewingProf;
1227   hSlewingProf=0x0;
1228   delete htimetot;
1229   htimetot=0x0;
1230   delete hdeltaTime;
1231   hdeltaTime=0x0;
1232
1233   AliTOFChannelOffline * calChannel = (AliTOFChannelOffline*)fTOFCalOffline->At(ichmin);
1234   calChannel->SetSlewPar(par);
1235   WriteParOfflineOnCDB("TOF/Calib","valid");
1236   return 0;
1237 }
1238 //----------------------------------------------------------------------------
1239 Int_t AliTOFcalib::Calibrate(Int_t i, Option_t *optionSave, Option_t *optionFit){
1240
1241   // computing calibration parameters for channel i
1242   // Returning codes:
1243   // 0 -> everything was ok
1244   // 1 -> no tree for calibration found
1245   // 2 -> not enough statistics to perform calibration
1246   // 3 -> problems with arrays
1247
1248   TH1::AddDirectory(0);
1249   
1250   AliInfo(Form("*** Calibrating Histograms (one channel) %s", GetName())) ; 
1251   AliInfo(Form("Option for Saving histos = %s",optionSave )) ; 
1252   AliInfo(Form("Option for Fitting Profile histos = %s",optionFit )) ; 
1253
1254   Float_t p[MAXCHENTRIESSMALL];
1255   Int_t nentries;
1256   //fTree->SetBranchAddress("nentries",&nentries);
1257   //fTree->SetBranchAddress("TOFentries",p);
1258   fChain->SetBranchAddress("nentries",&nentries);
1259   fChain->SetBranchAddress("TOFentries",p);
1260
1261   Float_t ntracksTotal =0;
1262   for (Int_t irun=0;irun<fNruns;irun++){
1263     Int_t ientry = -1;
1264     ientry = i+irun*fNChannels;
1265     //fTree->GetEntry(ientry);
1266     fChain->GetEntry(ientry);
1267     ntracksTotal+=nentries/3;    
1268   }
1269   
1270   if (ntracksTotal < MEANENTRIES) {  
1271     AliInfo(Form(" Too small mean number of entires per channel (mean number = %f) not calibrating and exiting.....",ntracksTotal));
1272     return 2;
1273   }
1274
1275   //filling ToT and Time arrays
1276
1277   Int_t nbinToT = 100;  // ToT bin width in Profile = 48.8 ps 
1278   Float_t minToT = 0;   // ns
1279   Float_t maxToT = 4.88;  // ns
1280
1281   TH1F *hToT = new TH1F("htot","htot",nbinToT, minToT, maxToT);
1282   TH1F *hdeltaTime = new TH1F("hdeltaTime","hdeltaTime",200,2,4);
1283   Int_t ntracksRun = 0;
1284   Double_t binsProfile[101]; // sized larger than necessary, the correct 
1285                              // dim being set in the booking of the profile
1286   Int_t nusefulbins=0;
1287   Float_t meantime=0;
1288   for (Int_t irun=0;irun<fNruns;irun++){
1289     Int_t ientry = -1;
1290     ientry = i+irun*fNChannels;
1291     //fTree->GetEntry(ientry);
1292     fChain->GetEntry(ientry);
1293     ntracksRun=nentries/3;
1294     AliDebug(2,Form("run %i, channel %i, nentries = %i, ntracksRun = %i",irun, i ,nentries, ntracksRun));
1295     for (Int_t j=0;j<ntracksRun;j++){
1296       Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1297       Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1298       Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1299       Float_t tot = p[idxexToT];
1300       meantime+=p[idxexTime]-p[idxexExTime];
1301       hdeltaTime->Fill(p[idxexTime]-p[idxexExTime]);
1302       hToT->Fill(tot);
1303     }
1304   }
1305
1306   nusefulbins = FindBins(hToT,&binsProfile[0]);
1307   meantime/=ntracksTotal;
1308   AliDebug(2,Form("meantime = %f",meantime));
1309   
1310   for (Int_t j=1;j<=nusefulbins;j++) {
1311     AliDebug(2,Form(" channel %i, nusefulbins = %i, bin %i = %f",i,nusefulbins,j,binsProfile[j])); 
1312   }
1313
1314   TProfile* hSlewingProf = new TProfile("hSlewingProf", "hSlewingProf",nusefulbins, binsProfile, "G");  // CHECK THE BUILD OPTION, PLEASE!!!!!!
1315   TH2F * htimetot = new TH2F("htimetot","htimetot",nbinToT, minToT, maxToT,600,-5,10);
1316   for (Int_t irun=0;irun<fNruns;irun++){
1317     Int_t ientry = -1;
1318     ientry = i+irun*fNChannels;
1319     //fTree->GetEntry(ientry);
1320     fChain->GetEntry(ientry);
1321     ntracksRun=nentries/3;
1322     for (Int_t j=0;j<ntracksRun;j++){
1323       Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1324       Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1325       Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1326       Float_t tot = p[idxexToT];
1327       Float_t time = p[idxexTime]-p[idxexExTime];
1328       AliDebug (2,Form("track = %i, time = %f, tot = %f, time-meantime = %f",j,time, tot, time-meantime));
1329       hSlewingProf->Fill(tot,time);  // if meantime is not used, the fill may be moved in the loop above
1330       htimetot->Fill(tot,time-meantime);  // if meantime is not used, the fill may be moved in the loop above
1331     }
1332   }
1333
1334   hSlewingProf->Fit("pol5",optionFit,"",0,4);
1335   TF1 * calibfunc = (TF1*)hSlewingProf->GetFunction("pol5");
1336   Float_t par[6];    
1337   for(Int_t kk=0;kk<6;kk++){
1338     par[kk]=calibfunc->GetParameter(kk);
1339     AliDebug(2,Form("parameter %i = %f",kk,par[kk]));
1340   }
1341
1342
1343   if(strstr(optionSave,"save")){
1344     TFile * fileProf = new TFile("TOFCalibSave.root","recreate");
1345     fileProf->cd();   
1346     TString profName=Form("Profile%06i",i);
1347     TString timeTotName=Form("TimeTot%06i",i);
1348     TString totName=Form("Tot%06i",i);
1349     TString deltaName=Form("Delta%06i",i);
1350     hSlewingProf->Write(profName);
1351     htimetot->Write(timeTotName);
1352     hToT->Write(totName);
1353     hdeltaTime->Write(deltaName);
1354     fileProf->Close();
1355     delete fileProf;
1356     fileProf=0x0;
1357   }
1358
1359   delete hToT;
1360   hToT=0x0; 
1361   delete hSlewingProf;
1362   hSlewingProf=0x0;
1363   delete htimetot;
1364   htimetot=0x0;
1365   delete hdeltaTime;
1366   hdeltaTime=0x0;
1367
1368   AliTOFChannelOffline * calChannel = (AliTOFChannelOffline*)fTOFCalOffline->At(i);
1369   calChannel->SetSlewPar(par);
1370   WriteParOfflineOnCDB("TOF/Calib","valid");
1371   return 0;
1372 }
1373 //----------------------------------------------------------------------------
1374 Int_t AliTOFcalib::Calibrate(Int_t nch, Int_t *ch, Option_t *optionSave, Option_t *optionFit){
1375
1376   // calibrating an array of channels
1377   // computing calibration parameters
1378   // Returning codes:
1379   // 0 -> everything was ok
1380   // 1 -> no tree for calibration found
1381   // 2 -> not enough statistics to perform calibration
1382   // 3 -> problems with arrays
1383   
1384   TH1::AddDirectory(0);
1385
1386   AliInfo(Form("*** Calibrating Histograms %s, number of channels = %i", GetName(),nch)) ; 
1387   AliInfo(Form("Option for Saving histos = %s",optionSave )) ; 
1388   AliInfo(Form("Option for Fitting Profile histos = %s",optionFit )) ; 
1389   for (Int_t ich=0; ich<nch; ich++){
1390     Int_t i = ch[ich];
1391     AliInfo(Form("Calibrating channel = %i",i )) ; 
1392   }
1393   Float_t p[MAXCHENTRIESSMALL];
1394   Int_t nentries;
1395   //fTree->SetBranchAddress("nentries",&nentries);
1396   //fTree->SetBranchAddress("TOFentries",p);
1397   fChain->SetBranchAddress("nentries",&nentries);
1398   fChain->SetBranchAddress("TOFentries",p);
1399
1400   Float_t ntracksTotalmean =0;
1401   for (Int_t ich=0; ich<nch; ich++){
1402     Int_t ientry = -1;
1403       Int_t i = ch[ich];
1404       for (Int_t irun=0;irun<fNruns;irun++){
1405       ientry = i+irun*fNChannels;
1406       //fTree->GetEntry(ientry);
1407       fChain->GetEntry(ientry);
1408       ntracksTotalmean+=nentries/3;
1409     }
1410   }
1411
1412   ntracksTotalmean/=nch;
1413   if (ntracksTotalmean < MEANENTRIES) { 
1414     AliInfo(Form(" Too small mean number of entires per channel (mean number = %f) not calibrating and exiting.....",ntracksTotalmean));
1415     return 2;
1416   }
1417
1418   //filling ToT and Time arrays
1419
1420   Int_t nbinToT = 100;  // ToT bin width in Profile = 48.8 ps 
1421   Float_t minToT = 0;   // ns
1422   Float_t maxToT = 4.88;  // ns
1423   TFile * fileProf=0x0;
1424   if(strstr(optionSave,"save")){
1425     fileProf = new TFile("TOFCalibSave.root","recreate");
1426   }
1427   for (Int_t ich=0; ich<nch; ich++) {
1428     TH1F *hToT = new TH1F("htot","htot",nbinToT, minToT, maxToT);
1429     TH1F *hdeltaTime = new TH1F("hdeltaTime","hdeltaTime",200,2,4);
1430     Double_t binsProfile[101]; // sized larger than necessary, the correct 
1431     // dim being set in the booking of the profile
1432     TH2F * htimetot = new TH2F("htimetot","htimetot",nbinToT, minToT, maxToT,600,-5,10);
1433     Int_t ntracksTotal = 0;
1434     Int_t ntracksRun = 0;
1435     Int_t nusefulbins=0;
1436     Float_t meantime=0;
1437     Int_t i=-1;
1438     for (Int_t irun=0;irun<fNruns;irun++){
1439       i = ch[ich]+irun*fNChannels;
1440       AliDebug(2,Form("Calibrating channel %i",i));
1441       //fTree->GetEntry(i);
1442       fChain->GetEntry(i);
1443       ntracksTotal+=nentries/3;
1444     }
1445     if (ntracksTotal < MEANENTRIES) {
1446       AliInfo(Form(" Too small mean number of entires in channel %i (number of tracks = %d), not calibrating channel and continuing.....",i,ntracksTotal));
1447       continue;
1448     }
1449   
1450     for (Int_t irun=0;irun<fNruns;irun++){
1451       i = ch[ich]+irun*fNChannels;
1452       //fTree->GetEntry(i);
1453       fChain->GetEntry(i);
1454       ntracksRun=nentries/3;
1455       for (Int_t j=0;j<ntracksRun;j++){
1456         Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1457         Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1458         Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1459         Float_t tot = p[idxexToT];
1460         hdeltaTime->Fill(p[idxexTime]-p[idxexExTime]);
1461         meantime+=p[idxexTime]-p[idxexExTime];
1462         hToT->Fill(tot);
1463       }
1464     }
1465
1466     nusefulbins = FindBins(hToT,&binsProfile[0]);
1467     meantime/=ntracksTotal;
1468     for (Int_t j=1;j<=nusefulbins;j++) {
1469       AliDebug(2,Form(" channel %i, nusefulbins = %i, bin %i = %f",i,nusefulbins,j,binsProfile[j])); 
1470     }
1471
1472     TProfile* hSlewingProf = new TProfile("hSlewingProf", "hSlewingProf",nusefulbins, binsProfile, "G");  // CHECK THE BUILD OPTION, PLEASE!!!!!!
1473     for (Int_t irun=0;irun<fNruns;irun++){
1474       i = ch[ich]+irun*fNChannels;
1475       //fTree->GetEntry(i);
1476       fChain->GetEntry(i);
1477       ntracksRun=nentries/3;
1478       for (Int_t j=0;j<ntracksRun;j++){
1479         Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1480         Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1481         Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1482         Float_t tot = p[idxexToT];
1483         Float_t time = p[idxexTime]-p[idxexExTime];
1484         AliDebug(2,Form("track = %i, time = %f, tot = %f, time-meantime = %f",j,time, tot, time-meantime));
1485         hSlewingProf->Fill(tot,time);  // if meantime is not used, the fill may be moved in the loop above
1486         htimetot->Fill(tot,time-meantime);  // if meantime is not used, the fill may be moved in the loop above
1487       }
1488     }
1489     
1490     hSlewingProf->Fit("pol5",optionFit,"",1,4);
1491     TF1 * calibfunc = (TF1*)hSlewingProf->GetFunction("pol5");
1492     Float_t par[6];    
1493     for(Int_t kk=0;kk<6;kk++){
1494       par[kk]=calibfunc->GetParameter(kk);
1495       AliDebug(2,Form("parameter %i = %f",kk,par[kk]));
1496     }
1497     
1498     if(strstr(optionSave,"save") && fileProf){
1499       TString profName=Form("Profile%06i",i);
1500       TString timeTotName=Form("TimeTot%06i",i);
1501       TString totName=Form("Tot%06i",i);
1502       TString deltaName=Form("Delta%06i",i);
1503       fileProf->cd();
1504       hSlewingProf->Write(profName);
1505       htimetot->Write(timeTotName);
1506       hToT->Write(totName);
1507       hdeltaTime->Write(deltaName);
1508     }
1509
1510     AliTOFChannelOffline * calChannel = (AliTOFChannelOffline*)fTOFCalOffline->At(i);
1511     calChannel->SetSlewPar(par);
1512     delete hToT;
1513     hToT=0x0;
1514     delete hSlewingProf;
1515     hSlewingProf=0x0;
1516     delete htimetot;
1517     htimetot=0x0;
1518     delete hdeltaTime;
1519     hdeltaTime=0x0;
1520   }
1521
1522   if(strstr(optionSave,"save") && fileProf){
1523     fileProf->Close();
1524     delete fileProf;
1525     fileProf=0x0;
1526   }
1527   WriteParOfflineOnCDB("TOF/Calib","valid");
1528
1529   return 0;
1530 }
1531 //----------------------------------------------------------------------------
1532 Int_t AliTOFcalib::CalibrateFromProfile(Int_t ich, Option_t *optionSave, Option_t *optionFit){
1533
1534   // computing calibration parameters using the old profiling algo
1535   // Returning codes:
1536   // 0 -> everything was ok
1537   // 1 -> no tree for calibration found
1538   // 2 -> not enough statistics to perform calibration
1539   // 3 -> problems with arrays
1540
1541   TH1::AddDirectory(0);
1542
1543   AliInfo(Form("*** Calibrating Histograms From Profile %s", GetName())) ; 
1544   AliInfo(Form("Option for Saving histos = %s",optionSave )) ; 
1545   AliInfo(Form("Option for Fitting Profile histos = %s",optionFit )) ; 
1546   Float_t p[MAXCHENTRIESSMALL];
1547   Int_t nentries;
1548   Int_t ntracksTotal=0;
1549   //fTree->SetBranchAddress("nentries",&nentries);
1550   //fTree->SetBranchAddress("TOFentries",p);
1551   fChain->SetBranchAddress("nentries",&nentries);
1552   fChain->SetBranchAddress("TOFentries",p);
1553
1554   for (Int_t irun=0;irun<fNruns;irun++){
1555     Int_t i = ich+irun*fNChannels;
1556     //fTree->GetEntry(i);
1557     fChain->GetEntry(i);
1558     ntracksTotal+=nentries/3;
1559   }
1560
1561   if (ntracksTotal < MEANENTRIES) {  
1562     AliInfo(Form(" Too small mean number of entires per channel (mean number = %d) not calibrating and exiting.....",ntracksTotal));
1563     return 2;
1564   }
1565
1566   TH1F * hProf = Profile(ich);
1567   hProf->Fit("pol5",optionFit,"",0,4);
1568   TF1 * calibfunc = (TF1*)hProf->GetFunction("pol5");
1569   Float_t par[6];    
1570   for(Int_t kk=0;kk<6;kk++){
1571     par[kk]=calibfunc->GetParameter(kk);
1572     AliDebug(2,Form("parameter %i = %f",kk,par[kk]));
1573   }
1574
1575   if(strstr(optionSave,"save")){
1576     TFile * fileProf = new TFile("TOFCalibSave.root","recreate");
1577     fileProf->cd(); 
1578     TString profName=Form("Profile%06i",ich);
1579     hProf->Write(profName);
1580     fileProf->Close();
1581     delete fileProf;
1582     fileProf=0x0;
1583   }
1584
1585   delete hProf;
1586   hProf=0x0;
1587   AliTOFChannelOffline * calChannel = (AliTOFChannelOffline*)fTOFCalOffline->At(ich);
1588   calChannel->SetSlewPar(par);
1589   WriteParOfflineOnCDB("TOF/Calib","valid");
1590   return 0;
1591 }
1592 //----------------------------------------------------------------------------
1593 Int_t AliTOFcalib::Calibrate(Option_t *optionSave, Option_t *optionFit){
1594
1595   // calibrating the whole TOF
1596   // computing calibration parameters
1597   // Returning codes:
1598   // 0 -> everything was ok
1599   // 1 -> no tree for calibration found
1600   // 2 -> not enough statistics to perform calibration
1601   // 3 -> problems with arrays
1602
1603   TH1::AddDirectory(0);
1604
1605   AliInfo(Form("*** Calibrating Histograms %s, all channels", GetName())) ; 
1606   AliInfo(Form("Option for Saving histos = %s",optionSave )) ; 
1607   AliInfo(Form("Option for Fitting Profile histos = %s",optionFit )) ; 
1608
1609   TFile * fileProf=0x0;
1610   if(strstr(optionSave,"save")){
1611     fileProf = new TFile("TOFCalibSave.root","recreate");
1612   }
1613
1614   Float_t p[MAXCHENTRIESSMALL];
1615   Int_t nentries;
1616   //fTree->SetBranchAddress("nentries",&nentries);
1617   //fTree->SetBranchAddress("TOFentries",p);
1618   fChain->SetBranchAddress("nentries",&nentries);
1619   fChain->SetBranchAddress("TOFentries",p);
1620
1621   Float_t ntracksTotalmean =0;
1622   for (Int_t ii=0; ii<fNChannels; ii++){
1623     for (Int_t irun=0;irun<fNruns;irun++){
1624       Int_t i = ii+irun*fNChannels;
1625       //fTree->GetEntry(i);
1626       fChain->GetEntry(i);
1627       ntracksTotalmean+=nentries/3;
1628     }
1629   }
1630
1631   ntracksTotalmean/=fNChannels;
1632   if (ntracksTotalmean < MEANENTRIES) {
1633     AliInfo(Form(" Too small mean number of entires per channel (mean number = %f) not calibrating and exiting.....",ntracksTotalmean));
1634     return 2;
1635   }
1636
1637   //filling ToT and Time arrays
1638
1639   Int_t nbinToT = 100;  // ToT bin width in Profile = 50.0 ps 
1640   Float_t minToT = 0;   // ns
1641   Float_t maxToT = 4.88;// ns
1642   for (Int_t ii=0; ii<fNChannels; ii++) {
1643     TH1F *hToT = new TH1F("htot","htot",nbinToT, minToT, maxToT);
1644     TH1F *hdeltaTime = new TH1F("hdeltaTime","hdeltaTime",200,2,4);
1645     TH2F * htimetot = new TH2F("htimetot","htimetot",nbinToT, minToT, maxToT,600,-5,10);
1646     if (ii%1000 == 0) AliDebug(1,Form("Calibrating channel %i ",ii));
1647     //Int_t i = 3;
1648     Int_t nusefulbins=0;
1649     Double_t binsProfile[101]; // sized larger than necessary, the correct 
1650                               // dim being set in the booking of the profile
1651     Int_t ntracksRun = 0;
1652     Int_t ntracksTotal = 0;
1653     for (Int_t irun=0;irun<fNruns;irun++){
1654       Int_t i = ii+irun*fNChannels;
1655       //fTree->GetEntry(i);
1656       fChain->GetEntry(i);
1657       ntracksTotal+=nentries/3;
1658     }
1659     if (ntracksTotal < MEANENTRIES) {
1660       AliInfo(Form(" Too small mean number of entires in channel %i (number of tracks = %d), not calibrating channel and continuing.....",ii,ntracksTotal));
1661       continue;
1662     }
1663     Float_t meantime=0;
1664     for (Int_t irun=0;irun<fNruns;irun++){
1665       Int_t i = ii+irun*fNChannels;
1666       //fTree->GetEntry(i);
1667       fChain->GetEntry(i);
1668       ntracksRun=nentries/3;
1669       for (Int_t j=0;j<ntracksRun;j++){
1670         Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1671         Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1672         Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1673         Float_t tot = p[idxexToT];
1674         hdeltaTime->Fill(p[idxexTime]-p[idxexExTime]);
1675         meantime+=p[idxexTime]-p[idxexExTime];
1676         hToT->Fill(tot);
1677       }
1678     }
1679     nusefulbins = FindBins(hToT,&binsProfile[0]);
1680     meantime/=ntracksTotal;
1681     for (Int_t j=0;j<nusefulbins;j++) {
1682       AliDebug(2,Form(" channel %i, usefulbin = %i, low edge = %f",ii,j,binsProfile[j])); 
1683     }
1684     TProfile* hSlewingProf = new TProfile("hSlewingProf", "hSlewingProf",nusefulbins, binsProfile, "G");  // CHECK THE BUILD OPTION, PLEASE!!!!!!
1685     for (Int_t irun=0;irun<fNruns;irun++){
1686       Int_t i = ii+irun*fNChannels;
1687       //fTree->GetEntry(i);
1688       fChain->GetEntry(i);
1689       ntracksRun=nentries/3;
1690       for (Int_t j=0;j<ntracksRun;j++){
1691         Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1692         Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1693         Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1694         Float_t tot = p[idxexToT];
1695         Float_t time = p[idxexTime]-p[idxexExTime];
1696         AliDebug (2,Form("track = %i, time = %f, tot = %f, time-meantime = %f",j,time, tot, time-meantime));
1697         hSlewingProf->Fill(tot,time);  // if meantime is not used, the fill may be moved in the loop above
1698         htimetot->Fill(tot,time-meantime);  // if meantime is not used, the fill may be moved in the loop above
1699       }
1700     }
1701     hSlewingProf->Fit("pol5",optionFit,"",1,4);
1702     TF1 * calibfunc = (TF1*)hSlewingProf->GetFunction("pol5");
1703     Float_t par[6];    
1704     for(Int_t kk=0;kk<6;kk++){
1705       par[kk]=calibfunc->GetParameter(kk);
1706       AliDebug(2,Form("parameter %i = %f",kk,par[kk]));
1707     }
1708
1709     if(strstr(optionSave,"save") && fileProf){
1710       TString profName=Form("Profile%06i",ii);
1711       TString timeTotName=Form("TimeTot%06i",ii);
1712       TString totName=Form("Tot%06i",ii);
1713       TString deltaName=Form("Delta%06i",ii);
1714       fileProf->cd();
1715       hSlewingProf->Write(profName);
1716       htimetot->Write(timeTotName);
1717       hToT->Write(totName);
1718       hdeltaTime->Write(deltaName);
1719     }
1720     AliTOFChannelOffline * calChannel = (AliTOFChannelOffline*)fTOFCalOffline->At(ii);
1721     calChannel->SetSlewPar(par);
1722
1723     delete hToT;
1724     hToT=0x0;
1725     delete hSlewingProf;
1726     hSlewingProf=0x0;
1727     delete htimetot;
1728     htimetot=0x0;
1729     delete hdeltaTime;
1730     hdeltaTime=0x0;
1731   }
1732
1733   if(strstr(optionSave,"save")){
1734     fileProf->Close();
1735     delete fileProf;
1736     fileProf=0x0;
1737   }
1738   WriteParOfflineOnCDB("TOF/Calib","valid");
1739   return 0;
1740 }
1741
1742 //-----------------------------------------------------------------------
1743 TH1F* AliTOFcalib::Profile(Int_t ich)
1744 {
1745   // profiling algo
1746
1747   Float_t p[MAXCHENTRIESSMALL];
1748   Int_t nentries;
1749   //fTree->SetBranchAddress("nentries",&nentries);
1750   //fTree->SetBranchAddress("TOFentries",p);
1751   fChain->SetBranchAddress("nentries",&nentries);
1752   fChain->SetBranchAddress("TOFentries",p);
1753
1754   //Prepare histograms for Slewing Correction
1755   const Int_t knbinToT = 100;
1756   Int_t nbinTime = 200;
1757   Float_t minTime = -5.5; //ns
1758   Float_t maxTime = 5.5; //ns
1759   Float_t minToT = 0; //ns
1760   Float_t maxToT = 5.; //ns
1761   Float_t deltaToT = (maxToT-minToT)/knbinToT;
1762   Double_t mTime[knbinToT+1],mToT[knbinToT+1],meanTime[knbinToT+1], meanTime2[knbinToT+1],vToT[knbinToT+1], vToT2[knbinToT+1],meanToT[knbinToT+1],meanToT2[knbinToT+1],vTime[knbinToT+1],vTime2[knbinToT+1],xlow[knbinToT+1],sigmaTime[knbinToT+1];
1763   Int_t n[knbinToT+1], nentrx[knbinToT+1];
1764   Double_t sigmaToT[knbinToT+1];
1765   for (Int_t i = 0; i < knbinToT+1 ; i++){
1766     mTime[i]=0;
1767     mToT[i]=0;
1768     n[i]=0;
1769     meanTime[i]=0;
1770     meanTime2[i]=0;
1771     vToT[i]=0;
1772     vToT2[i]=0;
1773     meanToT[i]=0;
1774     meanToT2[i]=0;
1775     vTime[i]=0;
1776     vTime2[i]=0;
1777     xlow[i]=0;
1778     sigmaTime[i]=0;
1779     sigmaToT[i]=0;
1780     n[i]=0;
1781     nentrx[i]=0;
1782   }
1783   TH2F* hSlewing = new TH2F("hSlewing", "hSlewing", knbinToT, minToT, maxToT, nbinTime, minTime, maxTime);
1784   Int_t ntracksRun = 0;
1785   TH1F *histo = new TH1F("histo", "1D Time vs ToT", knbinToT, minToT, maxToT);
1786   for (Int_t irun=0;irun<fNruns;irun++){
1787     Int_t i = ich+irun*fNChannels;
1788     //fTree->GetEntry(i);
1789     fChain->GetEntry(i);
1790     ntracksRun=nentries/3;
1791     for (Int_t j=0;j<ntracksRun;j++){
1792       Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1793       Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1794       Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1795       Float_t tot = p[idxexToT];
1796       Float_t time = p[idxexTime]-p[idxexExTime];
1797       Int_t nx = (Int_t)((tot-minToT)/deltaToT)+1;
1798       if ((tot != 0) && ( time!= 0)){
1799         vTime[nx]+=time;
1800         vTime2[nx]+=time*time;
1801         vToT[nx]+=tot;
1802         vToT2[nx]+=tot*tot;
1803         nentrx[nx]++;
1804         hSlewing->Fill(tot,time);
1805       }
1806     }
1807   }
1808   Int_t nbinsToT=hSlewing->GetNbinsX();
1809   if (nbinsToT != knbinToT) {
1810     AliError("Profile :: incompatible numbers of bins");
1811     return 0x0;
1812   }
1813   
1814   Int_t usefulBins=0;
1815   for (Int_t i=1;i<=nbinsToT;i++){
1816     if (nentrx[i]!=0){
1817       n[usefulBins]+=nentrx[i];
1818       if (n[usefulBins]==0 && i == nbinsToT) {
1819         break;
1820       }
1821       meanTime[usefulBins]+=vTime[i];
1822       meanTime2[usefulBins]+=vTime2[i];
1823       meanToT[usefulBins]+=vToT[i];
1824       meanToT2[usefulBins]+=vToT2[i];
1825       if (n[usefulBins]<10 && i!=nbinsToT) continue; 
1826       mTime[usefulBins]=meanTime[usefulBins]/n[usefulBins];
1827       mToT[usefulBins]=meanToT[usefulBins]/n[usefulBins];
1828       sigmaTime[usefulBins]=TMath::Sqrt(1./n[usefulBins]/n[usefulBins]
1829                             *(meanTime2[usefulBins]-meanTime[usefulBins]
1830                             *meanTime[usefulBins]/n[usefulBins]));
1831       if ((1./n[usefulBins]/n[usefulBins]
1832            *(meanToT2[usefulBins]-meanToT[usefulBins]
1833              *meanToT[usefulBins]/n[usefulBins]))< 0) {
1834         AliError(" too small radical" );
1835         sigmaToT[usefulBins]=0;
1836       }
1837       else{       
1838         sigmaToT[usefulBins]=TMath::Sqrt(1./n[usefulBins]/n[usefulBins]
1839                              *(meanToT2[usefulBins]-meanToT[usefulBins]
1840                              *meanToT[usefulBins]/n[usefulBins]));
1841       }
1842       usefulBins++;
1843     }
1844   }
1845   for (Int_t i=0;i<usefulBins;i++){
1846     Int_t binN = (Int_t)((mToT[i]-minToT)/deltaToT)+1;
1847     histo->Fill(mToT[i],mTime[i]);
1848     histo->SetBinError(binN,sigmaTime[i]);
1849   } 
1850   delete hSlewing;
1851   hSlewing=0x0;
1852
1853   return histo;
1854 }
1855 //----------------------------------------------------------------------------
1856 Int_t AliTOFcalib::FindBins(TH1F* h, Double_t *binsProfile) const{
1857
1858   // to determine the bins for ToT histo
1859
1860   Int_t cont = 0;
1861   Int_t startBin = 1;
1862   Int_t nbin = h->GetNbinsX();
1863   Int_t nentries = (Int_t)h->GetEntries();
1864   Float_t max = h->GetBinLowEdge(nbin);
1865   Int_t nusefulbins=0;
1866   Int_t maxcont=0;
1867   // setting maxvalue of entries per bin
1868   if (nentries <= 60) maxcont = 2;
1869   else  if (nentries <= 100) maxcont = 5;
1870   else  if (nentries <= 500) maxcont = 10;
1871   else  maxcont = 20;
1872   for (Int_t j=1;j<=nbin;j++) {
1873     cont += (Int_t)h->GetBinContent(j);
1874     if (j<nbin){
1875       if (cont>=maxcont){
1876         nusefulbins++;
1877         binsProfile[nusefulbins-1]=h->GetBinLowEdge(startBin);
1878         cont=0;
1879         startBin=j+1;
1880         continue;
1881       }
1882     }
1883     else{
1884       if (cont>=maxcont){
1885         nusefulbins++;
1886         binsProfile[nusefulbins-1]=h->GetBinLowEdge(startBin);
1887         binsProfile[nusefulbins]=max;
1888       }
1889       else {
1890         binsProfile[nusefulbins]=h->GetBinLowEdge(startBin);
1891       }
1892     }
1893   }
1894   return nusefulbins;
1895 }
1896
1897
1898 //----------------------------------------------------------------------------
1899
1900 void
1901 AliTOFcalib::CreateDeltaBCOffset()
1902 {
1903   /*
1904    * create deltaBC offset
1905    */
1906
1907   if (fDeltaBCOffset) {
1908     AliWarning("DeltaBCOffset object already defined, cannot create a new one");
1909     return;
1910   }
1911   fDeltaBCOffset = new AliTOFDeltaBCOffset();
1912 }
1913   
1914 //----------------------------------------------------------------------------
1915
1916 void
1917 AliTOFcalib::CreateCTPLatency()
1918 {
1919   /*
1920    * create CTP latency
1921    */
1922
1923   if (fCTPLatency) {
1924     AliWarning("CTPLatency object already defined, cannot create a new one");
1925     return;
1926   }
1927   fCTPLatency = new AliTOFCTPLatency();
1928 }
1929   
1930 //----------------------------------------------------------------------------
1931
1932 void
1933 AliTOFcalib::CreateT0Fill()
1934 {
1935   /*
1936    * create event-time
1937    */
1938
1939   if (fT0Fill) {
1940     AliWarning("T0Fill object already defined, cannot create a new one");
1941     return;
1942   }
1943   fT0Fill = new AliTOFT0Fill();
1944 }
1945   
1946 //----------------------------------------------------------------------------
1947
1948 void
1949 AliTOFcalib::CreateRunParams()
1950 {
1951   /*
1952    * create run params
1953    */
1954
1955   if (fRunParams) {
1956     AliWarning("RunParams object already defined, cannot create a new one");
1957     return;
1958   }
1959   fRunParams = new AliTOFRunParams();
1960 }
1961   
1962 //----------------------------------------------------------------------------
1963
1964 void
1965 AliTOFcalib::WriteDeltaBCOffsetOnCDB(const Char_t *sel , Int_t minrun, Int_t maxrun)
1966 {
1967   /*
1968    * deltaBC offset on CDB 
1969    */
1970   
1971   if (!fDeltaBCOffset) return;
1972   AliCDBId id(Form("%s/DeltaBCOffset", sel), minrun, maxrun);
1973   AliCDBMetaData *md = new AliCDBMetaData();
1974   md->SetResponsible("Roberto Preghenella");
1975   AliCDBManager *man = AliCDBManager::Instance();
1976   man->Put(fDeltaBCOffset, id, md);
1977   AliDebug(2,Form("DeltaBCOffset written on CDB with run range [%i, %i] ",minrun ,maxrun));
1978   delete md;
1979 }
1980
1981 //----------------------------------------------------------------------------
1982
1983 void
1984 AliTOFcalib::WriteCTPLatencyOnCDB(const Char_t *sel , Int_t minrun, Int_t maxrun)
1985 {
1986   /*
1987    * write CTP latency on CDB 
1988    */
1989   
1990   if (!fCTPLatency) return;
1991   AliCDBId id(Form("%s/CTPLatency", sel), minrun, maxrun);
1992   AliCDBMetaData *md = new AliCDBMetaData();
1993   md->SetResponsible("Roberto Preghenella");
1994   AliCDBManager *man = AliCDBManager::Instance();
1995   man->Put(fCTPLatency, id, md);
1996   AliDebug(2,Form("CTPLatency written on CDB with run range [%i, %i] ",minrun ,maxrun));
1997   delete md;
1998 }
1999
2000 //----------------------------------------------------------------------------
2001
2002 void
2003 AliTOFcalib::WriteT0FillOnCDB(const Char_t *sel , Int_t minrun, Int_t maxrun)
2004 {
2005   /*
2006    * write event-time on CDB 
2007    */
2008   
2009   if (!fT0Fill) return;
2010   AliCDBId id(Form("%s/T0Fill", sel), minrun, maxrun);
2011   AliCDBMetaData *md = new AliCDBMetaData();
2012   md->SetResponsible("Roberto Preghenella");
2013   AliCDBManager *man = AliCDBManager::Instance();
2014   man->Put(fT0Fill, id, md);
2015   AliDebug(2,Form("T0Fill written on CDB with run range [%i, %i] ",minrun ,maxrun));
2016   delete md;
2017 }
2018
2019 //----------------------------------------------------------------------------
2020
2021 void
2022 AliTOFcalib::WriteRunParamsOnCDB(const Char_t *sel , Int_t minrun, Int_t maxrun)
2023 {
2024   /*
2025    * write run params on CDB 
2026    */
2027   
2028   if (!fRunParams) return;
2029   AliCDBId id(Form("%s/RunParams", sel), minrun, maxrun);
2030   AliCDBMetaData *md = new AliCDBMetaData();
2031   md->SetResponsible("Roberto Preghenella");
2032   AliCDBManager *man = AliCDBManager::Instance();
2033   man->Put(fRunParams, id, md);
2034   AliDebug(2,Form("RunParams written on CDB with run range [%i, %i] ",minrun ,maxrun));
2035   delete md;
2036 }
2037
2038 //----------------------------------------------------------------------------
2039
2040 void
2041 AliTOFcalib::WriteReadoutEfficiencyOnCDB(const Char_t *sel , Int_t minrun, Int_t maxrun)
2042 {
2043   /*
2044    * write readout efficiency on CDB 
2045    */
2046   
2047   if (!fReadoutEfficiency) return;
2048   AliCDBId id(Form("%s/ReadoutEfficiency", sel), minrun, maxrun);
2049   AliCDBMetaData *md = new AliCDBMetaData();
2050   md->SetResponsible("Roberto Preghenella");
2051   AliCDBManager *man = AliCDBManager::Instance();
2052   man->Put(fReadoutEfficiency, id, md);
2053   AliDebug(2,Form("ReadoutEfficiency written on CDB with run range [%i, %i] ",minrun ,maxrun));
2054   delete md;
2055 }
2056
2057 //----------------------------------------------------------------------------
2058
2059 void
2060 AliTOFcalib::WriteProblematicOnCDB(const Char_t *sel , Int_t minrun, Int_t maxrun)
2061 {
2062   /*
2063    * write problematic on CDB 
2064    */
2065   
2066   if (!fProblematic) return;
2067   AliCDBId id(Form("%s/Problematic", sel), minrun, maxrun);
2068   AliCDBMetaData *md = new AliCDBMetaData();
2069   md->SetResponsible("Roberto Preghenella");
2070   AliCDBManager *man = AliCDBManager::Instance();
2071   man->Put(fProblematic, id, md);
2072   AliDebug(2,Form("Problematic written on CDB with run range [%i, %i] ",minrun ,maxrun));
2073   delete md;
2074 }
2075
2076 //----------------------------------------------------------------------------
2077
2078 Bool_t
2079 AliTOFcalib::ReadDeltaBCOffsetFromCDB(const Char_t *sel , Int_t nrun)
2080 {
2081   /*
2082    * read deltaBC offset from CDB
2083    */
2084   
2085   AliCDBManager *man = AliCDBManager::Instance();
2086   AliCDBEntry *entry = man->Get(Form("%s/DeltaBCOffset", sel),nrun);
2087   if (!entry) { 
2088     AliFatal("No DeltaBCOffset entry found in CDB");
2089     exit(0);  
2090   }
2091   fDeltaBCOffset =(AliTOFDeltaBCOffset *)entry->GetObject();
2092   if(!fDeltaBCOffset){
2093     AliFatal("No DeltaBCOffset object found in CDB entry");
2094     exit(0);  
2095   }  
2096   return kTRUE; 
2097 }
2098
2099 //----------------------------------------------------------------------------
2100
2101 Bool_t
2102 AliTOFcalib::ReadCTPLatencyFromCDB(const Char_t *sel , Int_t nrun)
2103 {
2104   /*
2105    * read CTP latency from CDB
2106    */
2107   
2108   AliCDBManager *man = AliCDBManager::Instance();
2109   AliCDBEntry *entry = man->Get(Form("%s/CTPLatency", sel),nrun);
2110   if (!entry) { 
2111     AliFatal("No CTPLatency entry found in CDB");
2112     exit(0);  
2113   }
2114   fCTPLatency =(AliTOFCTPLatency *)entry->GetObject();
2115   if(!fCTPLatency){
2116     AliFatal("No CTPLatency object found in CDB entry");
2117     exit(0);  
2118   }  
2119   return kTRUE; 
2120 }
2121
2122 //----------------------------------------------------------------------------
2123
2124 Bool_t
2125 AliTOFcalib::ReadT0FillFromCDB(const Char_t *sel , Int_t nrun)
2126 {
2127   /*
2128    * read event-time from CDB
2129    */
2130   
2131   AliCDBManager *man = AliCDBManager::Instance();
2132   AliCDBEntry *entry = man->Get(Form("%s/T0Fill", sel),nrun);
2133   if (!entry) { 
2134     AliFatal("No T0Fill entry found in CDB");
2135     exit(0);  
2136   }
2137   fT0Fill =(AliTOFT0Fill *)entry->GetObject();
2138   if(!fT0Fill){
2139     AliFatal("No T0Fill object found in CDB entry");
2140     exit(0);  
2141   }  
2142   return kTRUE; 
2143 }
2144
2145 //----------------------------------------------------------------------------
2146
2147 Bool_t
2148 AliTOFcalib::ReadRunParamsFromCDB(const Char_t *sel , Int_t nrun)
2149 {
2150   /*
2151    * read run params from CDB
2152    */
2153   
2154   AliCDBManager *man = AliCDBManager::Instance();
2155   AliCDBEntry *entry = man->Get(Form("%s/RunParams", sel),nrun, fRunParamsSpecificVersion);
2156   if (!entry) { 
2157     AliFatal("No RunParams entry found in CDB");
2158     exit(0);  
2159   }
2160   fRunParams =(AliTOFRunParams *)entry->GetObject();
2161   if(!fRunParams){
2162     AliFatal("No RunParams object found in CDB entry");
2163     exit(0);  
2164   }  
2165   return kTRUE; 
2166 }
2167
2168 //----------------------------------------------------------------------------
2169
2170 Bool_t
2171 AliTOFcalib::ReadLHCClockPhaseFromCDB(const Char_t *sel , Int_t nrun)
2172 {
2173   /*
2174    * read LHC clock-phase from CDB
2175    */
2176   
2177   AliCDBManager *man = AliCDBManager::Instance();
2178   AliCDBEntry *entry = man->Get(Form("%s/LHCClockPhase", sel),nrun);
2179   if (!entry) { 
2180     AliFatal("No LHCClockPhase entry found in CDB");
2181     exit(0);  
2182   }
2183   fLHCClockPhase =(AliLHCClockPhase *)entry->GetObject();
2184   if(!fRunParams){
2185     AliFatal("No LHCClockPhase object found in CDB entry");
2186     exit(0);  
2187   }  
2188   return kTRUE; 
2189 }
2190
2191 //----------------------------------------------------------------------------
2192
2193 Bool_t
2194 AliTOFcalib::ReadReadoutEfficiencyFromCDB(const Char_t *sel , Int_t nrun)
2195 {
2196   /*
2197    * read readout efficiency from CDB
2198    */
2199   
2200   AliCDBManager *man = AliCDBManager::Instance();
2201   AliCDBEntry *entry = man->Get(Form("%s/ReadoutEfficiency", sel),nrun);
2202   if (!entry) { 
2203     AliFatal("No ReadoutEfficiency entry found in CDB");
2204     exit(0);  
2205   }
2206   fReadoutEfficiency = (TH1F *)entry->GetObject();
2207   if(!fReadoutEfficiency){
2208     AliFatal("No ReadoutEfficiency object found in CDB entry");
2209     exit(0);  
2210   }  
2211   return kTRUE; 
2212 }
2213
2214 //----------------------------------------------------------------------------
2215
2216 Bool_t
2217 AliTOFcalib::ReadProblematicFromCDB(const Char_t *sel , Int_t nrun)
2218 {
2219   /*
2220    * read problematic from CDB
2221    */
2222   
2223   AliCDBManager *man = AliCDBManager::Instance();
2224   AliCDBEntry *entry = man->Get(Form("%s/Problematic", sel),nrun);
2225   if (!entry) { 
2226     AliFatal("No Problematic entry found in CDB");
2227     exit(0);  
2228   }
2229   fProblematic = (TH1C *)entry->GetObject();
2230   if(!fProblematic){
2231     AliFatal("No Problematic object found in CDB entry");
2232     exit(0);  
2233   }  
2234   return kTRUE; 
2235 }
2236
2237 //----------------------------------------------------------------------------
2238
2239 Bool_t 
2240 AliTOFcalib::Init(Int_t run)
2241 {
2242   /*
2243    * init
2244    */
2245
2246   if (fInitFlag) {
2247     AliWarning("the class was already initialized, re-initialize it");
2248     fInitFlag = kFALSE;
2249   }
2250   
2251   /* read channel status array */
2252   if (!ReadParOnlineStatusFromCDB("TOF/Calib", run)) {
2253     AliError("cannot get \"Status\" object from OCDB");
2254     return kFALSE;
2255   }
2256   /* get par offline array */
2257   if (!ReadParOfflineFromCDB("TOF/Calib", run)) {
2258     AliError("cannot get \"ParOffline\" object from OCDB");
2259     return kFALSE;
2260   }
2261   /* get deltaBC offset obj */
2262   if (!ReadDeltaBCOffsetFromCDB("TOF/Calib", run)) {
2263     AliError("cannot get \"DeltaBCOffset\" object from OCDB");
2264     return kFALSE;
2265   }
2266   /* get CTP latency obj */
2267   if (!ReadCTPLatencyFromCDB("TOF/Calib", run)) {
2268     AliError("cannot get \"CTPLatency\" object from OCDB");
2269     return kFALSE;
2270   }
2271   /* get run params obj */
2272   if (!ReadRunParamsFromCDB("TOF/Calib", run)) {
2273     AliError("cannot get \"RunParams\" object from OCDB");
2274     return kFALSE;
2275   }
2276   /* get LHC clock-phase obj */
2277   if (!ReadLHCClockPhaseFromCDB("GRP/Calib", run)) {
2278     AliError("cannot get \"LHCClockPhase\" object from OCDB");
2279     return kFALSE;
2280   }
2281   /* get readout efficiency obj */
2282   if (!ReadReadoutEfficiencyFromCDB("TOF/Calib", run)) {
2283     AliError("cannot get \"ReadoutEfficiency\" object from OCDB");
2284     return kFALSE;
2285   }
2286   /* get readout efficiency obj */
2287   if (!ReadProblematicFromCDB("TOF/Calib", run)) {
2288     AliError("cannot get \"Problematic\" object from OCDB");
2289     return kFALSE;
2290   }
2291   /* get response params */
2292   TFile *responseFile = TFile::Open("$ALICE_ROOT/TOF/data/AliTOFresponsePar.root");
2293   if (!responseFile || !responseFile->IsOpen()) {
2294     AliError("cannot open \"ResponseParams\" local file");
2295     return kFALSE;
2296   }
2297   fResponseParams = (AliTOFResponseParams *)responseFile->Get("ResponseParams");
2298   if (!fResponseParams) {
2299     AliError("cannot get \"ResponseParams\" object from local file");
2300     return kFALSE;
2301   }
2302   responseFile->Close();
2303
2304   /* check whether to use the clock phase */
2305   if (fRunParams->GetUseLHCClockPhase())
2306     fUseLHCClockPhase = kTRUE;
2307  
2308   if (fUseLHCClockPhase)
2309     AliInfo("calibration using BPTX LHC clock-phase");
2310
2311   /* all done */
2312   fInitFlag = kTRUE;
2313   return kTRUE;
2314
2315 }
2316
2317 //----------------------------------------------------------------------------
2318
2319 Double_t
2320 AliTOFcalib::GetTimeCorrection(Int_t index, Double_t tot, Int_t deltaBC, Int_t l0l1, UInt_t timestamp)
2321 {
2322   /*
2323    * get time correction
2324    */
2325
2326   if (!fInitFlag) {
2327     AliError("class not yet initialized. Initialize it before.");
2328     return 0.;
2329   }
2330
2331   /* deal with L0-L1 orbit crossing (negative values) */
2332   if (l0l1 < 0) l0l1 += 3564;
2333
2334   /* get calibration params */
2335   AliTOFChannelOffline *parOffline = (AliTOFChannelOffline *)fTOFCalOffline->At(index);
2336   Int_t deltaBCOffset = fDeltaBCOffset->GetDeltaBCOffset();
2337   Float_t ctpLatency = fCTPLatency->GetCTPLatency();
2338   Float_t tdcLatencyWindow = fStatus->GetLatencyWindow(index) * 1.e3;
2339   Float_t timezero = fRunParams->EvalT0(timestamp);
2340   Float_t clockphase = fLHCClockPhase->GetPhase(timestamp);
2341   /* check whether to remove mean T0.
2342    * useful when one wants to compute mean T0 */
2343   if (!fRemoveMeanT0) timezero = 0.;
2344   /* check whether to use the clock phase */
2345   if (fUseLHCClockPhase) timezero -= 1.e3 * clockphase;
2346
2347   /* compute correction */
2348   Double_t corr = 0.;
2349   /* deltaBC correction */
2350   deltaBC = deltaBCOffset; /* inhibit deltaBC correction for the time being */
2351   corr += (deltaBC - deltaBCOffset) * AliTOFGeometry::BunchCrossingBinWidth();
2352   /* L0-L1 latency correction */
2353   corr -= l0l1 * AliTOFGeometry::BunchCrossingBinWidth();
2354   /* CTP latency correction */
2355   corr -= ctpLatency;
2356   /* TDC latency window correction */
2357   corr += tdcLatencyWindow;
2358   /* time-zero correction */
2359   corr += timezero;
2360   /* time calibration correction */
2361   if (tot < AliTOFGeometry::SlewTOTMin()) 
2362     tot = AliTOFGeometry::SlewTOTMin();
2363   if (tot > AliTOFGeometry::SlewTOTMax()) 
2364     tot = AliTOFGeometry::SlewTOTMax();
2365   for (Int_t islew = 0; islew < 6; islew++)
2366     corr += parOffline->GetSlewPar(islew) * TMath::Power(tot, islew) * 1.e3;
2367
2368   /* return correction */
2369   return corr;
2370 }
2371
2372 //----------------------------------------------------------------------------
2373
2374 void
2375 AliTOFcalib::CalibrateESD(AliESDEvent *event)
2376 {
2377   /*
2378    * calibrate ESD
2379    */
2380
2381   if (!fInitFlag) {
2382     AliError("class not yet initialized. Initialize it before.");
2383     return;
2384   }
2385
2386   /* loop over tracks */
2387   AliESDtrack *track = NULL;
2388   Int_t index, l0l1, deltaBC;
2389   Double_t time, tot, corr, texp[AliPID::kSPECIES];
2390   UInt_t timestamp = event->GetTimeStamp();
2391   for (Int_t itrk = 0; itrk < event->GetNumberOfTracks(); itrk++) {
2392
2393     /* get track */
2394     track = event->GetTrack(itrk);
2395     if (!track || !(track->GetStatus() & AliESDtrack::kTOFout)) continue;
2396
2397     /* calibrate TOF signal */
2398     if (fCalibrateTOFsignal) {
2399       /* get info */
2400       index = track->GetTOFCalChannel();
2401       time = track->GetTOFsignalRaw();
2402       tot = track->GetTOFsignalToT();
2403       l0l1 = track->GetTOFL0L1();
2404       deltaBC = track->GetTOFDeltaBC();
2405       /* get correction */
2406       corr = GetTimeCorrection(index, tot, deltaBC, l0l1, timestamp);
2407       /* apply correction */
2408       time -= corr;
2409       /* set new TOF signal */
2410       track->SetTOFsignal(time);
2411     }
2412
2413     /* correct expected time */
2414     if (fCorrectTExp) {
2415       /* get integrated times */
2416       track->GetIntegratedTimes(texp);
2417       /* loop over particle types and correct expected time */
2418       for (Int_t ipart = 0; ipart < AliPID::kSPECIES; ipart++)
2419         texp[ipart] += fResponseParams->EvalTExpCorr(ipart, track->P());
2420       /* set integrated times */
2421       track->SetIntegratedTimes(texp);
2422     }
2423
2424   }
2425
2426 }
2427
2428 //----------------------------------------------------------------------------
2429
2430 Bool_t
2431 AliTOFcalib::IsChannelEnabled(Int_t index, Bool_t checkEfficiency, Bool_t checkProblematic)
2432 {
2433   /*
2434    * is channel enabled
2435    */
2436
2437   if (!fInitFlag) {
2438     AliError("class not yet initialized. Initialize it before.");
2439     return kTRUE;
2440   }
2441
2442   /* check bad status */
2443   if (fStatus->GetPulserStatus(index) == AliTOFChannelOnlineStatusArray::kTOFPulserBad) return kFALSE;
2444   if (fStatus->GetNoiseStatus(index) == AliTOFChannelOnlineStatusArray::kTOFNoiseBad) return kFALSE;
2445   if (fStatus->GetHWStatus(index) == AliTOFChannelOnlineStatusArray::kTOFHWBad) return kFALSE;
2446   if (checkEfficiency && !IsChannelEfficient(index)) return kFALSE;
2447   if (checkProblematic && IsChannelProblematic(index)) return kFALSE;
2448   
2449   /* good status */
2450   return kTRUE;
2451
2452 }
2453
2454 //----------------------------------------------------------------------------
2455
2456 Bool_t
2457 AliTOFcalib::IsChannelEfficient(Int_t index)
2458 {
2459   /*
2460    * is channel efficient
2461    */
2462
2463   if (!fInitFlag) {
2464     AliError("class not yet initialized. Initialize it before.");
2465     return kTRUE;
2466   }
2467
2468   /* check efficiency */
2469   if (fReadoutEfficiency->GetBinContent(index + 1) < 0.95) return kFALSE;
2470   return kTRUE;
2471
2472 }
2473
2474 //----------------------------------------------------------------------------
2475
2476 Bool_t
2477 AliTOFcalib::IsChannelProblematic(Int_t index)
2478 {
2479   /*
2480    * is channel problematic
2481    */
2482
2483   if (!fInitFlag) {
2484     AliError("class not yet initialized. Initialize it before.");
2485     return kTRUE;
2486   }
2487
2488   /* check problematic */
2489   if (fProblematic->GetBinContent(index + 1) != 0) return kTRUE;
2490   return kFALSE;
2491
2492 }
2493
2494 //----------------------------------------------------------------------------
2495
2496 void
2497 AliTOFcalib::CalibrateTExp(AliESDEvent *event) const
2498 {
2499   /*
2500    * calibrate TExp
2501    */
2502
2503   if (!fInitFlag) {
2504     AliError("class not yet initialized. Initialize it before.");
2505     return;
2506   }
2507
2508   /* loop over tracks */
2509   AliESDtrack *track = NULL;
2510   Double_t texp[AliPID::kSPECIES];
2511   for (Int_t itrk = 0; itrk < event->GetNumberOfTracks(); itrk++) {
2512
2513     /* get track */
2514     track = event->GetTrack(itrk);
2515     if (!track || !(track->GetStatus() & AliESDtrack::kTOFout)) continue;
2516
2517     /* get integrated times */
2518     track->GetIntegratedTimes(texp);
2519     /* loop over particle types and correct expected time */
2520     for (Int_t ipart = 0; ipart < AliPID::kSPECIES; ipart++)
2521       texp[ipart] += fResponseParams->EvalTExpCorr(ipart, track->P());
2522     /* set integrated times */
2523     track->SetIntegratedTimes(texp);
2524
2525   }
2526
2527 }
2528
2529 //----------------------------------------------------------------------------
2530
2531 Double_t
2532 AliTOFcalib::TuneForMC(AliESDEvent *event, Double_t resolution)
2533 {
2534   /*
2535    * tune for MC
2536    */
2537
2538   /* get vertex spread and define T0-spread */
2539   Double_t diamond2 = TMath::Abs(event->GetSigma2DiamondZ());
2540   Double_t t0spread = TMath::Sqrt(diamond2) / 2.99792457999999984e-02;
2541   /* generate random startTime */
2542   Double_t startTime = gRandom->Gaus(0., t0spread);
2543   /* define extra smearing for resolution */
2544   Double_t defaultResolution = 80.;
2545   Double_t extraSmearing = 0.;
2546   if (resolution > defaultResolution)
2547     extraSmearing = TMath::Sqrt(resolution * resolution - defaultResolution * defaultResolution);
2548
2549   /* loop over tracks */
2550   AliESDtrack *track = NULL;
2551   Double_t time;
2552   for (Int_t itrk = 0; itrk < event->GetNumberOfTracks(); itrk++) {
2553     /* get track */
2554     track = event->GetTrack(itrk);
2555     if (!track) continue;
2556     /* check TOF match */
2557     if (!track->IsOn(AliESDtrack::kTOFout)) continue;
2558     /* check if channel is enabled */
2559     if (!IsChannelEnabled(track->GetTOFCalChannel())) {
2560       /* reset TOF status */
2561       track->ResetStatus(AliESDtrack::kTOFin);
2562       track->ResetStatus(AliESDtrack::kTOFout);
2563       track->ResetStatus(AliESDtrack::kTOFmismatch);
2564       track->ResetStatus(AliESDtrack::kTOFpid);
2565     }
2566     /* get original time and manipulate it */
2567     time = track->GetTOFsignal();
2568     time += startTime; /* add start time */
2569     time += gRandom->Gaus(0., extraSmearing); /* extra smearing */
2570     time -= 25.; /* remove 25 ps to center the signal */
2571     track->SetTOFsignal(time);
2572   }
2573
2574   return startTime;
2575 }