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