]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TOF/AliTOFcalib.cxx
09e2cd143256c1f6d4ce68632f59f79b5472f67b
[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   meantime/=ntracksTotal;
1166   AliDebug(2, Form("meantime = %f",meantime));
1167   
1168   for (Int_t j=1;j<=nusefulbins;j++) {
1169     AliDebug(2,Form(" summing channels from %i to %i, nusefulbins = %i, bin %i = %f",ichmin,ichmax,nusefulbins,j,binsProfile[j])); 
1170   }
1171
1172   TProfile* hSlewingProf = new TProfile("hSlewingProf", "hSlewingProf",nusefulbins, binsProfile, "G");  // CHECK THE BUILD OPTION, PLEASE!!!!!!
1173   TH2F * htimetot = new TH2F("htimetot","htimetot",nbinToT, minToT, maxToT,600,-5,10);
1174
1175   for (Int_t irun=0;irun<fNruns;irun++){
1176     Int_t ientry = -1;
1177     for (Int_t i=ichmin; i<ichmax; i++){
1178       ientry = i+irun*fNChannels;
1179       //fTree->GetEntry(ientry);
1180       fChain->GetEntry(ientry);
1181       ntracksRun=nentries/3;
1182       for (Int_t j=0;j<ntracksRun;j++){
1183         Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1184         Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1185         Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1186         Float_t tot = p[idxexToT];
1187         Float_t time = p[idxexTime]-p[idxexExTime];
1188         AliDebug (2, Form("track = %i, time = %f, tot = %f, time-meantime = %f",j,time, tot, time-meantime));
1189         hSlewingProf->Fill(tot,time);  // if meantime is not used, the fill may be moved in the loop above
1190         htimetot->Fill(tot,time-meantime);  // if meantime is not used, the fill may be moved in the loop above
1191       }
1192     }
1193   }
1194
1195   hSlewingProf->Fit("pol5",optionFit,"",0,4);
1196   TF1 * calibfunc = (TF1*)hSlewingProf->GetFunction("pol5");
1197   Float_t par[6];    
1198   for(Int_t kk=0;kk<6;kk++){
1199     par[kk]=calibfunc->GetParameter(kk);
1200     AliDebug(2,Form("parameter %i = %f",kk,par[kk]));
1201   }
1202
1203   if(strstr(optionSave,"save")){
1204     TFile * fileProf = new TFile("TOFCalibSave.root","recreate");
1205     fileProf->cd(); 
1206     TString profName=Form("Profile%06i_%06i",ichmin,ichmax);
1207     TString timeTotName=Form("TimeTot%06i_%06i",ichmin,ichmax);
1208     TString totName=Form("Tot%06i_%06i",ichmin,ichmax);
1209     TString deltaName=Form("Delta%06i_%06i",ichmin,ichmax);
1210     hSlewingProf->Write(profName);
1211     htimetot->Write(timeTotName);
1212     hToT->Write(totName);
1213     hdeltaTime->Write(deltaName);
1214     fileProf->Close();
1215     delete fileProf;
1216     fileProf=0x0;
1217   }
1218
1219   delete hToT;
1220   hToT=0x0;
1221   delete hSlewingProf;
1222   hSlewingProf=0x0;
1223   delete htimetot;
1224   htimetot=0x0;
1225   delete hdeltaTime;
1226   hdeltaTime=0x0;
1227
1228   AliTOFChannelOffline * calChannel = (AliTOFChannelOffline*)fTOFCalOffline->At(ichmin);
1229   calChannel->SetSlewPar(par);
1230   WriteParOfflineOnCDB("TOF/Calib","valid");
1231   return 0;
1232 }
1233 //----------------------------------------------------------------------------
1234 Int_t AliTOFcalib::Calibrate(Int_t i, Option_t *optionSave, Option_t *optionFit){
1235
1236   // computing calibration parameters for channel i
1237   // Returning codes:
1238   // 0 -> everything was ok
1239   // 1 -> no tree for calibration found
1240   // 2 -> not enough statistics to perform calibration
1241   // 3 -> problems with arrays
1242
1243   TH1::AddDirectory(0);
1244   
1245   AliInfo(Form("*** Calibrating Histograms (one channel) %s", GetName())) ; 
1246   AliInfo(Form("Option for Saving histos = %s",optionSave )) ; 
1247   AliInfo(Form("Option for Fitting Profile histos = %s",optionFit )) ; 
1248
1249   Float_t p[MAXCHENTRIESSMALL];
1250   Int_t nentries;
1251   //fTree->SetBranchAddress("nentries",&nentries);
1252   //fTree->SetBranchAddress("TOFentries",p);
1253   fChain->SetBranchAddress("nentries",&nentries);
1254   fChain->SetBranchAddress("TOFentries",p);
1255
1256   Float_t ntracksTotal =0;
1257   for (Int_t irun=0;irun<fNruns;irun++){
1258     Int_t ientry = -1;
1259     ientry = i+irun*fNChannels;
1260     //fTree->GetEntry(ientry);
1261     fChain->GetEntry(ientry);
1262     ntracksTotal+=nentries/3;    
1263   }
1264   
1265   if (ntracksTotal < MEANENTRIES) {  
1266     AliInfo(Form(" Too small mean number of entires per channel (mean number = %f) not calibrating and exiting.....",ntracksTotal));
1267     return 2;
1268   }
1269
1270   //filling ToT and Time arrays
1271
1272   Int_t nbinToT = 100;  // ToT bin width in Profile = 48.8 ps 
1273   Float_t minToT = 0;   // ns
1274   Float_t maxToT = 4.88;  // ns
1275
1276   TH1F *hToT = new TH1F("htot","htot",nbinToT, minToT, maxToT);
1277   TH1F *hdeltaTime = new TH1F("hdeltaTime","hdeltaTime",200,2,4);
1278   Int_t ntracksRun = 0;
1279   Double_t binsProfile[101]; // sized larger than necessary, the correct 
1280                              // dim being set in the booking of the profile
1281   Int_t nusefulbins=0;
1282   Float_t meantime=0;
1283   for (Int_t irun=0;irun<fNruns;irun++){
1284     Int_t ientry = -1;
1285     ientry = i+irun*fNChannels;
1286     //fTree->GetEntry(ientry);
1287     fChain->GetEntry(ientry);
1288     ntracksRun=nentries/3;
1289     AliDebug(2,Form("run %i, channel %i, nentries = %i, ntracksRun = %i",irun, i ,nentries, ntracksRun));
1290     for (Int_t j=0;j<ntracksRun;j++){
1291       Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1292       Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1293       Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1294       Float_t tot = p[idxexToT];
1295       meantime+=p[idxexTime]-p[idxexExTime];
1296       hdeltaTime->Fill(p[idxexTime]-p[idxexExTime]);
1297       hToT->Fill(tot);
1298     }
1299   }
1300
1301   nusefulbins = FindBins(hToT,&binsProfile[0]);
1302   meantime/=ntracksTotal;
1303   AliDebug(2,Form("meantime = %f",meantime));
1304   
1305   for (Int_t j=1;j<=nusefulbins;j++) {
1306     AliDebug(2,Form(" channel %i, nusefulbins = %i, bin %i = %f",i,nusefulbins,j,binsProfile[j])); 
1307   }
1308
1309   TProfile* hSlewingProf = new TProfile("hSlewingProf", "hSlewingProf",nusefulbins, binsProfile, "G");  // CHECK THE BUILD OPTION, PLEASE!!!!!!
1310   TH2F * htimetot = new TH2F("htimetot","htimetot",nbinToT, minToT, maxToT,600,-5,10);
1311   for (Int_t irun=0;irun<fNruns;irun++){
1312     Int_t ientry = -1;
1313     ientry = i+irun*fNChannels;
1314     //fTree->GetEntry(ientry);
1315     fChain->GetEntry(ientry);
1316     ntracksRun=nentries/3;
1317     for (Int_t j=0;j<ntracksRun;j++){
1318       Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1319       Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1320       Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1321       Float_t tot = p[idxexToT];
1322       Float_t time = p[idxexTime]-p[idxexExTime];
1323       AliDebug (2,Form("track = %i, time = %f, tot = %f, time-meantime = %f",j,time, tot, time-meantime));
1324       hSlewingProf->Fill(tot,time);  // if meantime is not used, the fill may be moved in the loop above
1325       htimetot->Fill(tot,time-meantime);  // if meantime is not used, the fill may be moved in the loop above
1326     }
1327   }
1328
1329   hSlewingProf->Fit("pol5",optionFit,"",0,4);
1330   TF1 * calibfunc = (TF1*)hSlewingProf->GetFunction("pol5");
1331   Float_t par[6];    
1332   for(Int_t kk=0;kk<6;kk++){
1333     par[kk]=calibfunc->GetParameter(kk);
1334     AliDebug(2,Form("parameter %i = %f",kk,par[kk]));
1335   }
1336
1337
1338   if(strstr(optionSave,"save")){
1339     TFile * fileProf = new TFile("TOFCalibSave.root","recreate");
1340     fileProf->cd();   
1341     TString profName=Form("Profile%06i",i);
1342     TString timeTotName=Form("TimeTot%06i",i);
1343     TString totName=Form("Tot%06i",i);
1344     TString deltaName=Form("Delta%06i",i);
1345     hSlewingProf->Write(profName);
1346     htimetot->Write(timeTotName);
1347     hToT->Write(totName);
1348     hdeltaTime->Write(deltaName);
1349     fileProf->Close();
1350     delete fileProf;
1351     fileProf=0x0;
1352   }
1353
1354   delete hToT;
1355   hToT=0x0; 
1356   delete hSlewingProf;
1357   hSlewingProf=0x0;
1358   delete htimetot;
1359   htimetot=0x0;
1360   delete hdeltaTime;
1361   hdeltaTime=0x0;
1362
1363   AliTOFChannelOffline * calChannel = (AliTOFChannelOffline*)fTOFCalOffline->At(i);
1364   calChannel->SetSlewPar(par);
1365   WriteParOfflineOnCDB("TOF/Calib","valid");
1366   return 0;
1367 }
1368 //----------------------------------------------------------------------------
1369 Int_t AliTOFcalib::Calibrate(Int_t nch, Int_t *ch, Option_t *optionSave, Option_t *optionFit){
1370
1371   // calibrating an array of channels
1372   // computing calibration parameters
1373   // Returning codes:
1374   // 0 -> everything was ok
1375   // 1 -> no tree for calibration found
1376   // 2 -> not enough statistics to perform calibration
1377   // 3 -> problems with arrays
1378   
1379   TH1::AddDirectory(0);
1380
1381   AliInfo(Form("*** Calibrating Histograms %s, number of channels = %i", GetName(),nch)) ; 
1382   AliInfo(Form("Option for Saving histos = %s",optionSave )) ; 
1383   AliInfo(Form("Option for Fitting Profile histos = %s",optionFit )) ; 
1384   for (Int_t ich=0; ich<nch; ich++){
1385     Int_t i = ch[ich];
1386     AliInfo(Form("Calibrating channel = %i",i )) ; 
1387   }
1388   Float_t p[MAXCHENTRIESSMALL];
1389   Int_t nentries;
1390   //fTree->SetBranchAddress("nentries",&nentries);
1391   //fTree->SetBranchAddress("TOFentries",p);
1392   fChain->SetBranchAddress("nentries",&nentries);
1393   fChain->SetBranchAddress("TOFentries",p);
1394
1395   Float_t ntracksTotalmean =0;
1396   for (Int_t ich=0; ich<nch; ich++){
1397     Int_t ientry = -1;
1398       Int_t i = ch[ich];
1399       for (Int_t irun=0;irun<fNruns;irun++){
1400       ientry = i+irun*fNChannels;
1401       //fTree->GetEntry(ientry);
1402       fChain->GetEntry(ientry);
1403       ntracksTotalmean+=nentries/3;
1404     }
1405   }
1406
1407   ntracksTotalmean/=nch;
1408   if (ntracksTotalmean < MEANENTRIES) { 
1409     AliInfo(Form(" Too small mean number of entires per channel (mean number = %f) not calibrating and exiting.....",ntracksTotalmean));
1410     return 2;
1411   }
1412
1413   //filling ToT and Time arrays
1414
1415   Int_t nbinToT = 100;  // ToT bin width in Profile = 48.8 ps 
1416   Float_t minToT = 0;   // ns
1417   Float_t maxToT = 4.88;  // ns
1418   TFile * fileProf=0x0;
1419   if(strstr(optionSave,"save")){
1420     fileProf = new TFile("TOFCalibSave.root","recreate");
1421   }
1422   for (Int_t ich=0; ich<nch; ich++) {
1423     TH1F *hToT = new TH1F("htot","htot",nbinToT, minToT, maxToT);
1424     TH1F *hdeltaTime = new TH1F("hdeltaTime","hdeltaTime",200,2,4);
1425     Double_t binsProfile[101]; // sized larger than necessary, the correct 
1426     // dim being set in the booking of the profile
1427     TH2F * htimetot = new TH2F("htimetot","htimetot",nbinToT, minToT, maxToT,600,-5,10);
1428     Int_t ntracksTotal = 0;
1429     Int_t ntracksRun = 0;
1430     Int_t nusefulbins=0;
1431     Float_t meantime=0;
1432     Int_t i=-1;
1433     for (Int_t irun=0;irun<fNruns;irun++){
1434       i = ch[ich]+irun*fNChannels;
1435       AliDebug(2,Form("Calibrating channel %i",i));
1436       //fTree->GetEntry(i);
1437       fChain->GetEntry(i);
1438       ntracksTotal+=nentries/3;
1439     }
1440     if (ntracksTotal < MEANENTRIES) {
1441       AliInfo(Form(" Too small mean number of entires in channel %i (number of tracks = %d), not calibrating channel and continuing.....",i,ntracksTotal));
1442       continue;
1443     }
1444   
1445     for (Int_t irun=0;irun<fNruns;irun++){
1446       i = ch[ich]+irun*fNChannels;
1447       //fTree->GetEntry(i);
1448       fChain->GetEntry(i);
1449       ntracksRun=nentries/3;
1450       for (Int_t j=0;j<ntracksRun;j++){
1451         Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1452         Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1453         Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1454         Float_t tot = p[idxexToT];
1455         hdeltaTime->Fill(p[idxexTime]-p[idxexExTime]);
1456         meantime+=p[idxexTime]-p[idxexExTime];
1457         hToT->Fill(tot);
1458       }
1459     }
1460
1461     nusefulbins = FindBins(hToT,&binsProfile[0]);
1462     meantime/=ntracksTotal;
1463     for (Int_t j=1;j<=nusefulbins;j++) {
1464       AliDebug(2,Form(" channel %i, nusefulbins = %i, bin %i = %f",i,nusefulbins,j,binsProfile[j])); 
1465     }
1466
1467     TProfile* hSlewingProf = new TProfile("hSlewingProf", "hSlewingProf",nusefulbins, binsProfile, "G");  // CHECK THE BUILD OPTION, PLEASE!!!!!!
1468     for (Int_t irun=0;irun<fNruns;irun++){
1469       i = ch[ich]+irun*fNChannels;
1470       //fTree->GetEntry(i);
1471       fChain->GetEntry(i);
1472       ntracksRun=nentries/3;
1473       for (Int_t j=0;j<ntracksRun;j++){
1474         Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1475         Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1476         Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1477         Float_t tot = p[idxexToT];
1478         Float_t time = p[idxexTime]-p[idxexExTime];
1479         AliDebug(2,Form("track = %i, time = %f, tot = %f, time-meantime = %f",j,time, tot, time-meantime));
1480         hSlewingProf->Fill(tot,time);  // if meantime is not used, the fill may be moved in the loop above
1481         htimetot->Fill(tot,time-meantime);  // if meantime is not used, the fill may be moved in the loop above
1482       }
1483     }
1484     
1485     hSlewingProf->Fit("pol5",optionFit,"",1,4);
1486     TF1 * calibfunc = (TF1*)hSlewingProf->GetFunction("pol5");
1487     Float_t par[6];    
1488     for(Int_t kk=0;kk<6;kk++){
1489       par[kk]=calibfunc->GetParameter(kk);
1490       AliDebug(2,Form("parameter %i = %f",kk,par[kk]));
1491     }
1492     
1493     if(strstr(optionSave,"save") && fileProf){
1494       TString profName=Form("Profile%06i",i);
1495       TString timeTotName=Form("TimeTot%06i",i);
1496       TString totName=Form("Tot%06i",i);
1497       TString deltaName=Form("Delta%06i",i);
1498       fileProf->cd();
1499       hSlewingProf->Write(profName);
1500       htimetot->Write(timeTotName);
1501       hToT->Write(totName);
1502       hdeltaTime->Write(deltaName);
1503     }
1504
1505     AliTOFChannelOffline * calChannel = (AliTOFChannelOffline*)fTOFCalOffline->At(i);
1506     calChannel->SetSlewPar(par);
1507     delete hToT;
1508     hToT=0x0;
1509     delete hSlewingProf;
1510     hSlewingProf=0x0;
1511     delete htimetot;
1512     htimetot=0x0;
1513     delete hdeltaTime;
1514     hdeltaTime=0x0;
1515   }
1516
1517   if(strstr(optionSave,"save") && fileProf){
1518     fileProf->Close();
1519     delete fileProf;
1520     fileProf=0x0;
1521   }
1522   WriteParOfflineOnCDB("TOF/Calib","valid");
1523
1524   return 0;
1525 }
1526 //----------------------------------------------------------------------------
1527 Int_t AliTOFcalib::CalibrateFromProfile(Int_t ich, Option_t *optionSave, Option_t *optionFit){
1528
1529   // computing calibration parameters using the old profiling algo
1530   // Returning codes:
1531   // 0 -> everything was ok
1532   // 1 -> no tree for calibration found
1533   // 2 -> not enough statistics to perform calibration
1534   // 3 -> problems with arrays
1535
1536   TH1::AddDirectory(0);
1537
1538   AliInfo(Form("*** Calibrating Histograms From Profile %s", GetName())) ; 
1539   AliInfo(Form("Option for Saving histos = %s",optionSave )) ; 
1540   AliInfo(Form("Option for Fitting Profile histos = %s",optionFit )) ; 
1541   Float_t p[MAXCHENTRIESSMALL];
1542   Int_t nentries;
1543   Int_t ntracksTotal=0;
1544   //fTree->SetBranchAddress("nentries",&nentries);
1545   //fTree->SetBranchAddress("TOFentries",p);
1546   fChain->SetBranchAddress("nentries",&nentries);
1547   fChain->SetBranchAddress("TOFentries",p);
1548
1549   for (Int_t irun=0;irun<fNruns;irun++){
1550     Int_t i = ich+irun*fNChannels;
1551     //fTree->GetEntry(i);
1552     fChain->GetEntry(i);
1553     ntracksTotal+=nentries/3;
1554   }
1555
1556   if (ntracksTotal < MEANENTRIES) {  
1557     AliInfo(Form(" Too small mean number of entires per channel (mean number = %d) not calibrating and exiting.....",ntracksTotal));
1558     return 2;
1559   }
1560
1561   TH1F * hProf = Profile(ich);
1562   hProf->Fit("pol5",optionFit,"",0,4);
1563   TF1 * calibfunc = (TF1*)hProf->GetFunction("pol5");
1564   Float_t par[6];    
1565   for(Int_t kk=0;kk<6;kk++){
1566     par[kk]=calibfunc->GetParameter(kk);
1567     AliDebug(2,Form("parameter %i = %f",kk,par[kk]));
1568   }
1569
1570   if(strstr(optionSave,"save")){
1571     TFile * fileProf = new TFile("TOFCalibSave.root","recreate");
1572     fileProf->cd(); 
1573     TString profName=Form("Profile%06i",ich);
1574     hProf->Write(profName);
1575     fileProf->Close();
1576     delete fileProf;
1577     fileProf=0x0;
1578   }
1579
1580   delete hProf;
1581   hProf=0x0;
1582   AliTOFChannelOffline * calChannel = (AliTOFChannelOffline*)fTOFCalOffline->At(ich);
1583   calChannel->SetSlewPar(par);
1584   WriteParOfflineOnCDB("TOF/Calib","valid");
1585   return 0;
1586 }
1587 //----------------------------------------------------------------------------
1588 Int_t AliTOFcalib::Calibrate(Option_t *optionSave, Option_t *optionFit){
1589
1590   // calibrating the whole TOF
1591   // computing calibration parameters
1592   // Returning codes:
1593   // 0 -> everything was ok
1594   // 1 -> no tree for calibration found
1595   // 2 -> not enough statistics to perform calibration
1596   // 3 -> problems with arrays
1597
1598   TH1::AddDirectory(0);
1599
1600   AliInfo(Form("*** Calibrating Histograms %s, all channels", GetName())) ; 
1601   AliInfo(Form("Option for Saving histos = %s",optionSave )) ; 
1602   AliInfo(Form("Option for Fitting Profile histos = %s",optionFit )) ; 
1603
1604   TFile * fileProf=0x0;
1605   if(strstr(optionSave,"save")){
1606     fileProf = new TFile("TOFCalibSave.root","recreate");
1607   }
1608
1609   Float_t p[MAXCHENTRIESSMALL];
1610   Int_t nentries;
1611   //fTree->SetBranchAddress("nentries",&nentries);
1612   //fTree->SetBranchAddress("TOFentries",p);
1613   fChain->SetBranchAddress("nentries",&nentries);
1614   fChain->SetBranchAddress("TOFentries",p);
1615
1616   Float_t ntracksTotalmean =0;
1617   for (Int_t ii=0; ii<fNChannels; ii++){
1618     for (Int_t irun=0;irun<fNruns;irun++){
1619       Int_t i = ii+irun*fNChannels;
1620       //fTree->GetEntry(i);
1621       fChain->GetEntry(i);
1622       ntracksTotalmean+=nentries/3;
1623     }
1624   }
1625
1626   ntracksTotalmean/=fNChannels;
1627   if (ntracksTotalmean < MEANENTRIES) {
1628     AliInfo(Form(" Too small mean number of entires per channel (mean number = %f) not calibrating and exiting.....",ntracksTotalmean));
1629     return 2;
1630   }
1631
1632   //filling ToT and Time arrays
1633
1634   Int_t nbinToT = 100;  // ToT bin width in Profile = 50.0 ps 
1635   Float_t minToT = 0;   // ns
1636   Float_t maxToT = 4.88;// ns
1637   for (Int_t ii=0; ii<fNChannels; ii++) {
1638     TH1F *hToT = new TH1F("htot","htot",nbinToT, minToT, maxToT);
1639     TH1F *hdeltaTime = new TH1F("hdeltaTime","hdeltaTime",200,2,4);
1640     TH2F * htimetot = new TH2F("htimetot","htimetot",nbinToT, minToT, maxToT,600,-5,10);
1641     if (ii%1000 == 0) AliDebug(1,Form("Calibrating channel %i ",ii));
1642     //Int_t i = 3;
1643     Int_t nusefulbins=0;
1644     Double_t binsProfile[101]; // sized larger than necessary, the correct 
1645                               // dim being set in the booking of the profile
1646     Int_t ntracksRun = 0;
1647     Int_t ntracksTotal = 0;
1648     for (Int_t irun=0;irun<fNruns;irun++){
1649       Int_t i = ii+irun*fNChannels;
1650       //fTree->GetEntry(i);
1651       fChain->GetEntry(i);
1652       ntracksTotal+=nentries/3;
1653     }
1654     if (ntracksTotal < MEANENTRIES) {
1655       AliInfo(Form(" Too small mean number of entires in channel %i (number of tracks = %d), not calibrating channel and continuing.....",ii,ntracksTotal));
1656       continue;
1657     }
1658     Float_t meantime=0;
1659     for (Int_t irun=0;irun<fNruns;irun++){
1660       Int_t i = ii+irun*fNChannels;
1661       //fTree->GetEntry(i);
1662       fChain->GetEntry(i);
1663       ntracksRun=nentries/3;
1664       for (Int_t j=0;j<ntracksRun;j++){
1665         Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1666         Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1667         Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1668         Float_t tot = p[idxexToT];
1669         hdeltaTime->Fill(p[idxexTime]-p[idxexExTime]);
1670         meantime+=p[idxexTime]-p[idxexExTime];
1671         hToT->Fill(tot);
1672       }
1673     }
1674     nusefulbins = FindBins(hToT,&binsProfile[0]);
1675     meantime/=ntracksTotal;
1676     for (Int_t j=0;j<nusefulbins;j++) {
1677       AliDebug(2,Form(" channel %i, usefulbin = %i, low edge = %f",ii,j,binsProfile[j])); 
1678     }
1679     TProfile* hSlewingProf = new TProfile("hSlewingProf", "hSlewingProf",nusefulbins, binsProfile, "G");  // CHECK THE BUILD OPTION, PLEASE!!!!!!
1680     for (Int_t irun=0;irun<fNruns;irun++){
1681       Int_t i = ii+irun*fNChannels;
1682       //fTree->GetEntry(i);
1683       fChain->GetEntry(i);
1684       ntracksRun=nentries/3;
1685       for (Int_t j=0;j<ntracksRun;j++){
1686         Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1687         Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1688         Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1689         Float_t tot = p[idxexToT];
1690         Float_t time = p[idxexTime]-p[idxexExTime];
1691         AliDebug (2,Form("track = %i, time = %f, tot = %f, time-meantime = %f",j,time, tot, time-meantime));
1692         hSlewingProf->Fill(tot,time);  // if meantime is not used, the fill may be moved in the loop above
1693         htimetot->Fill(tot,time-meantime);  // if meantime is not used, the fill may be moved in the loop above
1694       }
1695     }
1696     hSlewingProf->Fit("pol5",optionFit,"",1,4);
1697     TF1 * calibfunc = (TF1*)hSlewingProf->GetFunction("pol5");
1698     Float_t par[6];    
1699     for(Int_t kk=0;kk<6;kk++){
1700       par[kk]=calibfunc->GetParameter(kk);
1701       AliDebug(2,Form("parameter %i = %f",kk,par[kk]));
1702     }
1703
1704     if(strstr(optionSave,"save") && fileProf){
1705       TString profName=Form("Profile%06i",ii);
1706       TString timeTotName=Form("TimeTot%06i",ii);
1707       TString totName=Form("Tot%06i",ii);
1708       TString deltaName=Form("Delta%06i",ii);
1709       fileProf->cd();
1710       hSlewingProf->Write(profName);
1711       htimetot->Write(timeTotName);
1712       hToT->Write(totName);
1713       hdeltaTime->Write(deltaName);
1714     }
1715     AliTOFChannelOffline * calChannel = (AliTOFChannelOffline*)fTOFCalOffline->At(ii);
1716     calChannel->SetSlewPar(par);
1717
1718     delete hToT;
1719     hToT=0x0;
1720     delete hSlewingProf;
1721     hSlewingProf=0x0;
1722     delete htimetot;
1723     htimetot=0x0;
1724     delete hdeltaTime;
1725     hdeltaTime=0x0;
1726   }
1727
1728   if(strstr(optionSave,"save")){
1729     fileProf->Close();
1730     delete fileProf;
1731     fileProf=0x0;
1732   }
1733   WriteParOfflineOnCDB("TOF/Calib","valid");
1734   return 0;
1735 }
1736
1737 //-----------------------------------------------------------------------
1738 TH1F* AliTOFcalib::Profile(Int_t ich)
1739 {
1740   // profiling algo
1741
1742   Float_t p[MAXCHENTRIESSMALL];
1743   Int_t nentries;
1744   //fTree->SetBranchAddress("nentries",&nentries);
1745   //fTree->SetBranchAddress("TOFentries",p);
1746   fChain->SetBranchAddress("nentries",&nentries);
1747   fChain->SetBranchAddress("TOFentries",p);
1748
1749   //Prepare histograms for Slewing Correction
1750   const Int_t knbinToT = 100;
1751   Int_t nbinTime = 200;
1752   Float_t minTime = -5.5; //ns
1753   Float_t maxTime = 5.5; //ns
1754   Float_t minToT = 0; //ns
1755   Float_t maxToT = 5.; //ns
1756   Float_t deltaToT = (maxToT-minToT)/knbinToT;
1757   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];
1758   Int_t n[knbinToT+1], nentrx[knbinToT+1];
1759   Double_t sigmaToT[knbinToT+1];
1760   for (Int_t i = 0; i < knbinToT+1 ; i++){
1761     mTime[i]=0;
1762     mToT[i]=0;
1763     n[i]=0;
1764     meanTime[i]=0;
1765     meanTime2[i]=0;
1766     vToT[i]=0;
1767     vToT2[i]=0;
1768     meanToT[i]=0;
1769     meanToT2[i]=0;
1770     vTime[i]=0;
1771     vTime2[i]=0;
1772     xlow[i]=0;
1773     sigmaTime[i]=0;
1774     sigmaToT[i]=0;
1775     n[i]=0;
1776     nentrx[i]=0;
1777   }
1778   TH2F* hSlewing = new TH2F("hSlewing", "hSlewing", knbinToT, minToT, maxToT, nbinTime, minTime, maxTime);
1779   Int_t ntracksRun = 0;
1780   TH1F *histo = new TH1F("histo", "1D Time vs ToT", knbinToT, minToT, maxToT);
1781   for (Int_t irun=0;irun<fNruns;irun++){
1782     Int_t i = ich+irun*fNChannels;
1783     //fTree->GetEntry(i);
1784     fChain->GetEntry(i);
1785     ntracksRun=nentries/3;
1786     for (Int_t j=0;j<ntracksRun;j++){
1787       Int_t idxexToT = (j* NIDXSMALL)+DELTAIDXTOT; 
1788       Int_t idxexTime = (j* NIDXSMALL)+DELTAIDXTIME; 
1789       Int_t idxexExTime = (j* NIDXSMALL)+DELTAIDXPID; 
1790       Float_t tot = p[idxexToT];
1791       Float_t time = p[idxexTime]-p[idxexExTime];
1792       Int_t nx = (Int_t)((tot-minToT)/deltaToT)+1;
1793       if ((tot != 0) && ( time!= 0)){
1794         vTime[nx]+=time;
1795         vTime2[nx]+=time*time;
1796         vToT[nx]+=tot;
1797         vToT2[nx]+=tot*tot;
1798         nentrx[nx]++;
1799         hSlewing->Fill(tot,time);
1800       }
1801     }
1802   }
1803   Int_t nbinsToT=hSlewing->GetNbinsX();
1804   if (nbinsToT != knbinToT) {
1805     AliError("Profile :: incompatible numbers of bins");
1806     return 0x0;
1807   }
1808   
1809   Int_t usefulBins=0;
1810   for (Int_t i=1;i<=nbinsToT;i++){
1811     if (nentrx[i]!=0){
1812       n[usefulBins]+=nentrx[i];
1813       if (n[usefulBins]==0 && i == nbinsToT) {
1814         break;
1815       }
1816       meanTime[usefulBins]+=vTime[i];
1817       meanTime2[usefulBins]+=vTime2[i];
1818       meanToT[usefulBins]+=vToT[i];
1819       meanToT2[usefulBins]+=vToT2[i];
1820       if (n[usefulBins]<10 && i!=nbinsToT) continue; 
1821       mTime[usefulBins]=meanTime[usefulBins]/n[usefulBins];
1822       mToT[usefulBins]=meanToT[usefulBins]/n[usefulBins];
1823       sigmaTime[usefulBins]=TMath::Sqrt(1./n[usefulBins]/n[usefulBins]
1824                             *(meanTime2[usefulBins]-meanTime[usefulBins]
1825                             *meanTime[usefulBins]/n[usefulBins]));
1826       if ((1./n[usefulBins]/n[usefulBins]
1827            *(meanToT2[usefulBins]-meanToT[usefulBins]
1828              *meanToT[usefulBins]/n[usefulBins]))< 0) {
1829         AliError(" too small radical" );
1830         sigmaToT[usefulBins]=0;
1831       }
1832       else{       
1833         sigmaToT[usefulBins]=TMath::Sqrt(1./n[usefulBins]/n[usefulBins]
1834                              *(meanToT2[usefulBins]-meanToT[usefulBins]
1835                              *meanToT[usefulBins]/n[usefulBins]));
1836       }
1837       usefulBins++;
1838     }
1839   }
1840   for (Int_t i=0;i<usefulBins;i++){
1841     Int_t binN = (Int_t)((mToT[i]-minToT)/deltaToT)+1;
1842     histo->Fill(mToT[i],mTime[i]);
1843     histo->SetBinError(binN,sigmaTime[i]);
1844   } 
1845   delete hSlewing;
1846   hSlewing=0x0;
1847
1848   return histo;
1849 }
1850 //----------------------------------------------------------------------------
1851 Int_t AliTOFcalib::FindBins(TH1F* h, Double_t *binsProfile) const{
1852
1853   // to determine the bins for ToT histo
1854
1855   Int_t cont = 0;
1856   Int_t startBin = 1;
1857   Int_t nbin = h->GetNbinsX();
1858   Int_t nentries = (Int_t)h->GetEntries();
1859   Float_t max = h->GetBinLowEdge(nbin);
1860   Int_t nusefulbins=0;
1861   Int_t maxcont=0;
1862   // setting maxvalue of entries per bin
1863   if (nentries <= 60) maxcont = 2;
1864   else  if (nentries <= 100) maxcont = 5;
1865   else  if (nentries <= 500) maxcont = 10;
1866   else  maxcont = 20;
1867   for (Int_t j=1;j<=nbin;j++) {
1868     cont += (Int_t)h->GetBinContent(j);
1869     if (j<nbin){
1870       if (cont>=maxcont){
1871         nusefulbins++;
1872         binsProfile[nusefulbins-1]=h->GetBinLowEdge(startBin);
1873         cont=0;
1874         startBin=j+1;
1875         continue;
1876       }
1877     }
1878     else{
1879       if (cont>=maxcont){
1880         nusefulbins++;
1881         binsProfile[nusefulbins-1]=h->GetBinLowEdge(startBin);
1882         binsProfile[nusefulbins]=max;
1883       }
1884       else {
1885         binsProfile[nusefulbins]=h->GetBinLowEdge(startBin);
1886       }
1887     }
1888   }
1889   return nusefulbins;
1890 }
1891
1892
1893 //----------------------------------------------------------------------------
1894
1895 void
1896 AliTOFcalib::CreateDeltaBCOffset()
1897 {
1898   /*
1899    * create deltaBC offset
1900    */
1901
1902   if (fDeltaBCOffset) {
1903     AliWarning("DeltaBCOffset object already defined, cannot create a new one");
1904     return;
1905   }
1906   fDeltaBCOffset = new AliTOFDeltaBCOffset();
1907 }
1908   
1909 //----------------------------------------------------------------------------
1910
1911 void
1912 AliTOFcalib::CreateCTPLatency()
1913 {
1914   /*
1915    * create CTP latency
1916    */
1917
1918   if (fCTPLatency) {
1919     AliWarning("CTPLatency object already defined, cannot create a new one");
1920     return;
1921   }
1922   fCTPLatency = new AliTOFCTPLatency();
1923 }
1924   
1925 //----------------------------------------------------------------------------
1926
1927 void
1928 AliTOFcalib::CreateT0Fill()
1929 {
1930   /*
1931    * create event-time
1932    */
1933
1934   if (fT0Fill) {
1935     AliWarning("T0Fill object already defined, cannot create a new one");
1936     return;
1937   }
1938   fT0Fill = new AliTOFT0Fill();
1939 }
1940   
1941 //----------------------------------------------------------------------------
1942
1943 void
1944 AliTOFcalib::CreateRunParams()
1945 {
1946   /*
1947    * create run params
1948    */
1949
1950   if (fRunParams) {
1951     AliWarning("RunParams object already defined, cannot create a new one");
1952     return;
1953   }
1954   fRunParams = new AliTOFRunParams();
1955 }
1956   
1957 //----------------------------------------------------------------------------
1958
1959 void
1960 AliTOFcalib::WriteDeltaBCOffsetOnCDB(const Char_t *sel , Int_t minrun, Int_t maxrun)
1961 {
1962   /*
1963    * deltaBC offset on CDB 
1964    */
1965   
1966   if (!fDeltaBCOffset) return;
1967   AliCDBId id(Form("%s/DeltaBCOffset", sel), minrun, maxrun);
1968   AliCDBMetaData *md = new AliCDBMetaData();
1969   md->SetResponsible("Roberto Preghenella");
1970   AliCDBManager *man = AliCDBManager::Instance();
1971   man->Put(fDeltaBCOffset, id, md);
1972   AliDebug(2,Form("DeltaBCOffset written on CDB with run range [%i, %i] ",minrun ,maxrun));
1973   delete md;
1974 }
1975
1976 //----------------------------------------------------------------------------
1977
1978 void
1979 AliTOFcalib::WriteCTPLatencyOnCDB(const Char_t *sel , Int_t minrun, Int_t maxrun)
1980 {
1981   /*
1982    * write CTP latency on CDB 
1983    */
1984   
1985   if (!fCTPLatency) return;
1986   AliCDBId id(Form("%s/CTPLatency", sel), minrun, maxrun);
1987   AliCDBMetaData *md = new AliCDBMetaData();
1988   md->SetResponsible("Roberto Preghenella");
1989   AliCDBManager *man = AliCDBManager::Instance();
1990   man->Put(fCTPLatency, id, md);
1991   AliDebug(2,Form("CTPLatency written on CDB with run range [%i, %i] ",minrun ,maxrun));
1992   delete md;
1993 }
1994
1995 //----------------------------------------------------------------------------
1996
1997 void
1998 AliTOFcalib::WriteT0FillOnCDB(const Char_t *sel , Int_t minrun, Int_t maxrun)
1999 {
2000   /*
2001    * write event-time on CDB 
2002    */
2003   
2004   if (!fT0Fill) return;
2005   AliCDBId id(Form("%s/T0Fill", sel), minrun, maxrun);
2006   AliCDBMetaData *md = new AliCDBMetaData();
2007   md->SetResponsible("Roberto Preghenella");
2008   AliCDBManager *man = AliCDBManager::Instance();
2009   man->Put(fT0Fill, id, md);
2010   AliDebug(2,Form("T0Fill written on CDB with run range [%i, %i] ",minrun ,maxrun));
2011   delete md;
2012 }
2013
2014 //----------------------------------------------------------------------------
2015
2016 void
2017 AliTOFcalib::WriteRunParamsOnCDB(const Char_t *sel , Int_t minrun, Int_t maxrun)
2018 {
2019   /*
2020    * write run params on CDB 
2021    */
2022   
2023   if (!fRunParams) return;
2024   AliCDBId id(Form("%s/RunParams", sel), minrun, maxrun);
2025   AliCDBMetaData *md = new AliCDBMetaData();
2026   md->SetResponsible("Roberto Preghenella");
2027   AliCDBManager *man = AliCDBManager::Instance();
2028   man->Put(fRunParams, id, md);
2029   AliDebug(2,Form("RunParams written on CDB with run range [%i, %i] ",minrun ,maxrun));
2030   delete md;
2031 }
2032
2033 //----------------------------------------------------------------------------
2034
2035 void
2036 AliTOFcalib::WriteReadoutEfficiencyOnCDB(const Char_t *sel , Int_t minrun, Int_t maxrun)
2037 {
2038   /*
2039    * write readout efficiency on CDB 
2040    */
2041   
2042   if (!fReadoutEfficiency) return;
2043   AliCDBId id(Form("%s/ReadoutEfficiency", sel), minrun, maxrun);
2044   AliCDBMetaData *md = new AliCDBMetaData();
2045   md->SetResponsible("Roberto Preghenella");
2046   AliCDBManager *man = AliCDBManager::Instance();
2047   man->Put(fReadoutEfficiency, id, md);
2048   AliDebug(2,Form("ReadoutEfficiency written on CDB with run range [%i, %i] ",minrun ,maxrun));
2049   delete md;
2050 }
2051
2052 //----------------------------------------------------------------------------
2053
2054 void
2055 AliTOFcalib::WriteProblematicOnCDB(const Char_t *sel , Int_t minrun, Int_t maxrun)
2056 {
2057   /*
2058    * write problematic on CDB 
2059    */
2060   
2061   if (!fProblematic) return;
2062   AliCDBId id(Form("%s/Problematic", sel), minrun, maxrun);
2063   AliCDBMetaData *md = new AliCDBMetaData();
2064   md->SetResponsible("Roberto Preghenella");
2065   AliCDBManager *man = AliCDBManager::Instance();
2066   man->Put(fProblematic, id, md);
2067   AliDebug(2,Form("Problematic written on CDB with run range [%i, %i] ",minrun ,maxrun));
2068   delete md;
2069 }
2070
2071 //----------------------------------------------------------------------------
2072
2073 Bool_t
2074 AliTOFcalib::ReadDeltaBCOffsetFromCDB(const Char_t *sel , Int_t nrun)
2075 {
2076   /*
2077    * read deltaBC offset from CDB
2078    */
2079   
2080   AliCDBManager *man = AliCDBManager::Instance();
2081   AliCDBEntry *entry = man->Get(Form("%s/DeltaBCOffset", sel),nrun);
2082   if (!entry) { 
2083     AliFatal("No DeltaBCOffset entry found in CDB");
2084     exit(0);  
2085   }
2086   fDeltaBCOffset =(AliTOFDeltaBCOffset *)entry->GetObject();
2087   if(!fDeltaBCOffset){
2088     AliFatal("No DeltaBCOffset object found in CDB entry");
2089     exit(0);  
2090   }  
2091   return kTRUE; 
2092 }
2093
2094 //----------------------------------------------------------------------------
2095
2096 Bool_t
2097 AliTOFcalib::ReadCTPLatencyFromCDB(const Char_t *sel , Int_t nrun)
2098 {
2099   /*
2100    * read CTP latency from CDB
2101    */
2102   
2103   AliCDBManager *man = AliCDBManager::Instance();
2104   AliCDBEntry *entry = man->Get(Form("%s/CTPLatency", sel),nrun);
2105   if (!entry) { 
2106     AliFatal("No CTPLatency entry found in CDB");
2107     exit(0);  
2108   }
2109   fCTPLatency =(AliTOFCTPLatency *)entry->GetObject();
2110   if(!fCTPLatency){
2111     AliFatal("No CTPLatency object found in CDB entry");
2112     exit(0);  
2113   }  
2114   return kTRUE; 
2115 }
2116
2117 //----------------------------------------------------------------------------
2118
2119 Bool_t
2120 AliTOFcalib::ReadT0FillFromCDB(const Char_t *sel , Int_t nrun)
2121 {
2122   /*
2123    * read event-time from CDB
2124    */
2125   
2126   AliCDBManager *man = AliCDBManager::Instance();
2127   AliCDBEntry *entry = man->Get(Form("%s/T0Fill", sel),nrun);
2128   if (!entry) { 
2129     AliFatal("No T0Fill entry found in CDB");
2130     exit(0);  
2131   }
2132   fT0Fill =(AliTOFT0Fill *)entry->GetObject();
2133   if(!fT0Fill){
2134     AliFatal("No T0Fill object found in CDB entry");
2135     exit(0);  
2136   }  
2137   return kTRUE; 
2138 }
2139
2140 //----------------------------------------------------------------------------
2141
2142 Bool_t
2143 AliTOFcalib::ReadRunParamsFromCDB(const Char_t *sel , Int_t nrun)
2144 {
2145   /*
2146    * read run params from CDB
2147    */
2148   
2149   AliCDBManager *man = AliCDBManager::Instance();
2150   AliCDBEntry *entry = man->Get(Form("%s/RunParams", sel),nrun);
2151   if (!entry) { 
2152     AliFatal("No RunParams entry found in CDB");
2153     exit(0);  
2154   }
2155   fRunParams =(AliTOFRunParams *)entry->GetObject();
2156   if(!fRunParams){
2157     AliFatal("No RunParams object found in CDB entry");
2158     exit(0);  
2159   }  
2160   return kTRUE; 
2161 }
2162
2163 //----------------------------------------------------------------------------
2164
2165 Bool_t
2166 AliTOFcalib::ReadLHCClockPhaseFromCDB(const Char_t *sel , Int_t nrun)
2167 {
2168   /*
2169    * read LHC clock-phase from CDB
2170    */
2171   
2172   AliCDBManager *man = AliCDBManager::Instance();
2173   AliCDBEntry *entry = man->Get(Form("%s/LHCClockPhase", sel),nrun);
2174   if (!entry) { 
2175     AliFatal("No LHCClockPhase entry found in CDB");
2176     exit(0);  
2177   }
2178   fLHCClockPhase =(AliLHCClockPhase *)entry->GetObject();
2179   if(!fRunParams){
2180     AliFatal("No LHCClockPhase object found in CDB entry");
2181     exit(0);  
2182   }  
2183   return kTRUE; 
2184 }
2185
2186 //----------------------------------------------------------------------------
2187
2188 Bool_t
2189 AliTOFcalib::ReadReadoutEfficiencyFromCDB(const Char_t *sel , Int_t nrun)
2190 {
2191   /*
2192    * read readout efficiency from CDB
2193    */
2194   
2195   AliCDBManager *man = AliCDBManager::Instance();
2196   AliCDBEntry *entry = man->Get(Form("%s/ReadoutEfficiency", sel),nrun);
2197   if (!entry) { 
2198     AliFatal("No ReadoutEfficiency entry found in CDB");
2199     exit(0);  
2200   }
2201   fReadoutEfficiency = (TH1F *)entry->GetObject();
2202   if(!fReadoutEfficiency){
2203     AliFatal("No ReadoutEfficiency object found in CDB entry");
2204     exit(0);  
2205   }  
2206   return kTRUE; 
2207 }
2208
2209 //----------------------------------------------------------------------------
2210
2211 Bool_t
2212 AliTOFcalib::ReadProblematicFromCDB(const Char_t *sel , Int_t nrun)
2213 {
2214   /*
2215    * read problematic from CDB
2216    */
2217   
2218   AliCDBManager *man = AliCDBManager::Instance();
2219   AliCDBEntry *entry = man->Get(Form("%s/Problematic", sel),nrun);
2220   if (!entry) { 
2221     AliFatal("No Problematic entry found in CDB");
2222     exit(0);  
2223   }
2224   fProblematic = (TH1C *)entry->GetObject();
2225   if(!fProblematic){
2226     AliFatal("No Problematic object found in CDB entry");
2227     exit(0);  
2228   }  
2229   return kTRUE; 
2230 }
2231
2232 //----------------------------------------------------------------------------
2233
2234 Bool_t 
2235 AliTOFcalib::Init(Int_t run)
2236 {
2237   /*
2238    * init
2239    */
2240
2241   if (fInitFlag) {
2242     AliWarning("the class was already initialized, re-initialize it");
2243     fInitFlag = kFALSE;
2244   }
2245   
2246   /* read channel status array */
2247   if (!ReadParOnlineStatusFromCDB("TOF/Calib", run)) {
2248     AliError("cannot get \"Status\" object from OCDB");
2249     return kFALSE;
2250   }
2251   /* get par offline array */
2252   if (!ReadParOfflineFromCDB("TOF/Calib", run)) {
2253     AliError("cannot get \"ParOffline\" object from OCDB");
2254     return kFALSE;
2255   }
2256   /* get deltaBC offset obj */
2257   if (!ReadDeltaBCOffsetFromCDB("TOF/Calib", run)) {
2258     AliError("cannot get \"DeltaBCOffset\" object from OCDB");
2259     return kFALSE;
2260   }
2261   /* get CTP latency obj */
2262   if (!ReadCTPLatencyFromCDB("TOF/Calib", run)) {
2263     AliError("cannot get \"CTPLatency\" object from OCDB");
2264     return kFALSE;
2265   }
2266   /* get run params obj */
2267   if (!ReadRunParamsFromCDB("TOF/Calib", run)) {
2268     AliError("cannot get \"RunParams\" object from OCDB");
2269     return kFALSE;
2270   }
2271   /* get LHC clock-phase obj */
2272   if (!ReadLHCClockPhaseFromCDB("GRP/Calib", run)) {
2273     AliError("cannot get \"LHCClockPhase\" object from OCDB");
2274     return kFALSE;
2275   }
2276   /* get readout efficiency obj */
2277   if (!ReadReadoutEfficiencyFromCDB("TOF/Calib", run)) {
2278     AliError("cannot get \"ReadoutEfficiency\" object from OCDB");
2279     return kFALSE;
2280   }
2281   /* get readout efficiency obj */
2282   if (!ReadProblematicFromCDB("TOF/Calib", run)) {
2283     AliError("cannot get \"Problematic\" object from OCDB");
2284     return kFALSE;
2285   }
2286   /* get response params */
2287   TFile *responseFile = TFile::Open("$ALICE_ROOT/TOF/data/AliTOFresponsePar.root");
2288   if (!responseFile || !responseFile->IsOpen()) {
2289     AliError("cannot open \"ResponseParams\" local file");
2290     return kFALSE;
2291   }
2292   fResponseParams = (AliTOFResponseParams *)responseFile->Get("ResponseParams");
2293   if (!fResponseParams) {
2294     AliError("cannot get \"ResponseParams\" object from local file");
2295     return kFALSE;
2296   }
2297   responseFile->Close();
2298
2299   /* check whether to use the clock phase */
2300   if (fRunParams->GetUseLHCClockPhase())
2301     fUseLHCClockPhase = kTRUE;
2302  
2303   if (fUseLHCClockPhase)
2304     AliInfo("calibration using BPTX LHC clock-phase");
2305
2306   /* all done */
2307   fInitFlag = kTRUE;
2308   return kTRUE;
2309
2310 }
2311
2312 //----------------------------------------------------------------------------
2313
2314 Double_t
2315 AliTOFcalib::GetTimeCorrection(Int_t index, Double_t tot, Int_t deltaBC, Int_t l0l1, UInt_t timestamp)
2316 {
2317   /*
2318    * get time correction
2319    */
2320
2321   if (!fInitFlag) {
2322     AliError("class not yet initialized. Initialize it before.");
2323     return 0.;
2324   }
2325
2326   /* deal with L0-L1 orbit crossing (negative values) */
2327   if (l0l1 < 0) l0l1 += 3564;
2328
2329   /* get calibration params */
2330   AliTOFChannelOffline *parOffline = (AliTOFChannelOffline *)fTOFCalOffline->At(index);
2331   Int_t deltaBCOffset = fDeltaBCOffset->GetDeltaBCOffset();
2332   Float_t ctpLatency = fCTPLatency->GetCTPLatency();
2333   Float_t tdcLatencyWindow = fStatus->GetLatencyWindow(index) * 1.e3;
2334   Float_t timezero = fRunParams->EvalT0(timestamp);
2335   Float_t clockphase = fLHCClockPhase->GetPhase(timestamp);
2336   /* check whether to remove mean T0.
2337    * useful when one wants to compute mean T0 */
2338   if (!fRemoveMeanT0) timezero = 0.;
2339   /* check whether to use the clock phase */
2340   if (fUseLHCClockPhase) timezero -= 1.e3 * clockphase;
2341
2342   /* compute correction */
2343   Double_t corr = 0.;
2344   /* deltaBC correction */
2345   deltaBC = deltaBCOffset; /* inhibit deltaBC correction for the time being */
2346   corr += (deltaBC - deltaBCOffset) * AliTOFGeometry::BunchCrossingBinWidth();
2347   /* L0-L1 latency correction */
2348   corr -= l0l1 * AliTOFGeometry::BunchCrossingBinWidth();
2349   /* CTP latency correction */
2350   corr -= ctpLatency;
2351   /* TDC latency window correction */
2352   corr += tdcLatencyWindow;
2353   /* time-zero correction */
2354   corr += timezero;
2355   /* time calibration correction */
2356   if (tot < AliTOFGeometry::SlewTOTMin()) 
2357     tot = AliTOFGeometry::SlewTOTMin();
2358   if (tot > AliTOFGeometry::SlewTOTMax()) 
2359     tot = AliTOFGeometry::SlewTOTMax();
2360   for (Int_t islew = 0; islew < 6; islew++)
2361     corr += parOffline->GetSlewPar(islew) * TMath::Power(tot, islew) * 1.e3;
2362
2363   /* return correction */
2364   return corr;
2365 }
2366
2367 //----------------------------------------------------------------------------
2368
2369 void
2370 AliTOFcalib::CalibrateESD(AliESDEvent *event)
2371 {
2372   /*
2373    * calibrate ESD
2374    */
2375
2376   if (!fInitFlag) {
2377     AliError("class not yet initialized. Initialize it before.");
2378     return;
2379   }
2380
2381   /* loop over tracks */
2382   AliESDtrack *track = NULL;
2383   Int_t index, l0l1, deltaBC;
2384   Double_t time, tot, corr, texp[AliPID::kSPECIES];
2385   UInt_t timestamp = event->GetTimeStamp();
2386   for (Int_t itrk = 0; itrk < event->GetNumberOfTracks(); itrk++) {
2387
2388     /* get track */
2389     track = event->GetTrack(itrk);
2390     if (!track || !(track->GetStatus() & AliESDtrack::kTOFout)) continue;
2391
2392     /* calibrate TOF signal */
2393     if (fCalibrateTOFsignal) {
2394       /* get info */
2395       index = track->GetTOFCalChannel();
2396       time = track->GetTOFsignalRaw();
2397       tot = track->GetTOFsignalToT();
2398       l0l1 = track->GetTOFL0L1();
2399       deltaBC = track->GetTOFDeltaBC();
2400       /* get correction */
2401       corr = GetTimeCorrection(index, tot, deltaBC, l0l1, timestamp);
2402       /* apply correction */
2403       time -= corr;
2404       /* set new TOF signal */
2405       track->SetTOFsignal(time);
2406     }
2407
2408     /* correct expected time */
2409     if (fCorrectTExp) {
2410       /* get integrated times */
2411       track->GetIntegratedTimes(texp);
2412       /* loop over particle types and correct expected time */
2413       for (Int_t ipart = 0; ipart < AliPID::kSPECIES; ipart++)
2414         texp[ipart] += fResponseParams->EvalTExpCorr(ipart, track->P());
2415       /* set integrated times */
2416       track->SetIntegratedTimes(texp);
2417     }
2418
2419   }
2420
2421 }
2422
2423 //----------------------------------------------------------------------------
2424
2425 Bool_t
2426 AliTOFcalib::IsChannelEnabled(Int_t index, Bool_t checkEfficiency, Bool_t checkProblematic)
2427 {
2428   /*
2429    * is channel enabled
2430    */
2431
2432   if (!fInitFlag) {
2433     AliError("class not yet initialized. Initialize it before.");
2434     return kTRUE;
2435   }
2436
2437   /* check bad status */
2438   if (fStatus->GetPulserStatus(index) == AliTOFChannelOnlineStatusArray::kTOFPulserBad) return kFALSE;
2439   if (fStatus->GetNoiseStatus(index) == AliTOFChannelOnlineStatusArray::kTOFNoiseBad) return kFALSE;
2440   if (fStatus->GetHWStatus(index) == AliTOFChannelOnlineStatusArray::kTOFHWBad) return kFALSE;
2441   if (checkEfficiency && !IsChannelEfficient(index)) return kFALSE;
2442   if (checkProblematic && IsChannelProblematic(index)) return kFALSE;
2443   
2444   /* good status */
2445   return kTRUE;
2446
2447 }
2448
2449 //----------------------------------------------------------------------------
2450
2451 Bool_t
2452 AliTOFcalib::IsChannelEfficient(Int_t index)
2453 {
2454   /*
2455    * is channel efficient
2456    */
2457
2458   if (!fInitFlag) {
2459     AliError("class not yet initialized. Initialize it before.");
2460     return kTRUE;
2461   }
2462
2463   /* check efficiency */
2464   if (fReadoutEfficiency->GetBinContent(index + 1) < 0.95) return kFALSE;
2465   return kTRUE;
2466
2467 }
2468
2469 //----------------------------------------------------------------------------
2470
2471 Bool_t
2472 AliTOFcalib::IsChannelProblematic(Int_t index)
2473 {
2474   /*
2475    * is channel problematic
2476    */
2477
2478   if (!fInitFlag) {
2479     AliError("class not yet initialized. Initialize it before.");
2480     return kTRUE;
2481   }
2482
2483   /* check problematic */
2484   if (fProblematic->GetBinContent(index + 1) != 0) return kTRUE;
2485   return kFALSE;
2486
2487 }
2488
2489 //----------------------------------------------------------------------------
2490
2491 void
2492 AliTOFcalib::CalibrateTExp(AliESDEvent *event) const
2493 {
2494   /*
2495    * calibrate TExp
2496    */
2497
2498   if (!fInitFlag) {
2499     AliError("class not yet initialized. Initialize it before.");
2500     return;
2501   }
2502
2503   /* loop over tracks */
2504   AliESDtrack *track = NULL;
2505   Double_t texp[AliPID::kSPECIES];
2506   for (Int_t itrk = 0; itrk < event->GetNumberOfTracks(); itrk++) {
2507
2508     /* get track */
2509     track = event->GetTrack(itrk);
2510     if (!track || !(track->GetStatus() & AliESDtrack::kTOFout)) continue;
2511
2512     /* get integrated times */
2513     track->GetIntegratedTimes(texp);
2514     /* loop over particle types and correct expected time */
2515     for (Int_t ipart = 0; ipart < AliPID::kSPECIES; ipart++)
2516       texp[ipart] += fResponseParams->EvalTExpCorr(ipart, track->P());
2517     /* set integrated times */
2518     track->SetIntegratedTimes(texp);
2519
2520   }
2521
2522 }
2523
2524 //----------------------------------------------------------------------------
2525
2526 Double_t
2527 AliTOFcalib::TuneForMC(AliESDEvent *event, Double_t resolution)
2528 {
2529   /*
2530    * tune for MC
2531    */
2532
2533   /* get vertex spread and define T0-spread */
2534   Double_t diamond2 = TMath::Abs(event->GetSigma2DiamondZ());
2535   Double_t t0spread = TMath::Sqrt(diamond2) / 2.99792457999999984e-02;
2536   /* generate random startTime */
2537   Double_t startTime = gRandom->Gaus(0., t0spread);
2538   /* define extra smearing for resolution */
2539   Double_t defaultResolution = 80.;
2540   Double_t extraSmearing = 0.;
2541   if (resolution > defaultResolution)
2542     extraSmearing = TMath::Sqrt(resolution * resolution - defaultResolution * defaultResolution);
2543
2544   /* loop over tracks */
2545   AliESDtrack *track = NULL;
2546   Double_t time;
2547   for (Int_t itrk = 0; itrk < event->GetNumberOfTracks(); itrk++) {
2548     /* get track */
2549     track = event->GetTrack(itrk);
2550     if (!track) continue;
2551     /* check TOF match */
2552     if (!track->IsOn(AliESDtrack::kTOFout)) continue;
2553     /* check if channel is enabled */
2554     if (!IsChannelEnabled(track->GetTOFCalChannel())) {
2555       /* reset TOF status */
2556       track->ResetStatus(AliESDtrack::kTOFin);
2557       track->ResetStatus(AliESDtrack::kTOFout);
2558       track->ResetStatus(AliESDtrack::kTOFmismatch);
2559       track->ResetStatus(AliESDtrack::kTOFpid);
2560     }
2561     /* get original time and manipulate it */
2562     time = track->GetTOFsignal();
2563     time += startTime; /* add start time */
2564     time += gRandom->Gaus(0., extraSmearing); /* extra smearing */
2565     time -= 25.; /* remove 25 ps to center the signal */
2566     track->SetTOFsignal(time);
2567   }
2568
2569   return startTime;
2570 }