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