]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - TOF/AliTOFDigitizer.cxx
Part of Reset() moved to base class.
[u/mrichter/AliRoot.git] / TOF / AliTOFDigitizer.cxx
index 38ad4437eb72cd5eadd0eb0363ff68b9066366b6..4dfb1bed856b3a183def5c2d6dac0d6eeb365697 100644 (file)
@@ -1,5 +1,5 @@
 /**************************************************************************
- * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
+ * Copyright(c) 1998-2000, ALICE Experiment at CERN, All rights reserved. *
  *                                                                        *
  * Author: The ALICE Off-line Project.                                    *
  * Contributors are mentioned in the code where appropriate.              *
  * provided "as is" without express or implied warranty.                  *
  **************************************************************************/
 
+//_________________________________________________________________________//
+//                                                                         //
+// This is a TTask that makes TOF-Digits out of TOF-SDigits.               //
+// The simulation of the detector is performed at sdigits level:           //
+// during digitization the unique task is the sum of all sdigits in the    //
+// same pad.                                                               //
+// Digits are written to TreeD in branch "TOF".                            //
+//                                                                         //
+// -- Author :  F. Pierella (Bologna University) pierella@bo.infn.it       //
+//                                                                         //
+//_________________________________________________________________________//
 
-//_________________________________________________________________________
-// This is a TTask that makes TOF-Digits out of TOF-Hits.
-// A TOF Digit is essentially a TOF hit with the smearing for strip 
-// time resolution and simulation of the ADC correlation signal. 
-// Digits are written to TreeD in branch "TOF".
-// AliTOFDigitizer with all current parameters used for digitization 
-// (time resolution and ADC parameter) is written 
-// to TreeD branch "AliTOFDigitizer".
-// Both branches have the same title. If necessary one can produce 
-// another set of Digits with different parameters. Two versions
-// can be distunguished using titles of the branches.
-// User case:
-//  root [0] AliTOFDigitizer * s = new AliTOFDigitizer("galice.root")
-//  Warning in <AliITSgeomSPD425Long::Default Creator>: Detector size may not be write.
-//  Warning in <TDatabasePDG::TDatabasePDG>: object already instantiated
-//  root [1] s->ExecuteTask()
-//             // Makes Digits for all events stored in galice.root
-//  root [2] s->SetTimeRes(100.)
-//             // One can change parameters of digitization
-//  root [3] s->SetDigitsBranch("Time Resolution 100. ps")
-//             // and write them into the new branch
-//  root [4] s->ExecuteTask("deb all tim")
-//             // available parameters:
-//             deb - print number of produced Digits
-//             deb all  - print number and list of produced Digits
-//             tim - print benchmarking information
-//
-// -- Author :  F. Pierella (Bologna University) pierella@bo.infn.it
-//////////////////////////////////////////////////////////////////////////////
+#include "Riostream.h"
 
 #include "TFile.h"
-#include "TTask.h"
+#include "TH1F.h"
 #include "TTree.h"
-#include "TSystem.h"
-#include "TROOT.h"
-#include "TFolder.h"
-#include "TBenchmark.h"
-#include "TObjString.h"
-
-#include <iomanip.h>
+#include "TRandom.h"
 
+#include "AliLoader.h"
+#include "AliLog.h"
+#include "AliRunDigitizer.h"
+#include "AliRunLoader.h"
 #include "AliRun.h"
-#include "AliTOF.h"
-#include "AliTOFdigit.h"
-#include "AliTOFhit.h"
+
+#include "AliTOFCal.h"
+#include "AliTOFcalib.h"
+#include "AliTOFChannel.h"
 #include "AliTOFDigitizer.h"
+#include "AliTOFdigit.h"
+#include "AliTOFHitMap.h"
+#include "AliTOFGeometryV5.h"
+#include "AliTOFSDigit.h"
+#include "AliTOF.h"
+
+extern TDirectory *gDirectory;
+extern TFile *gFile;
+extern TRandom *gRandom;
+
+extern AliRun *gAlice;
 
 
 ClassImp(AliTOFDigitizer)
 
-           
-//____________________________________________________________________________ 
-  AliTOFDigitizer::AliTOFDigitizer():TTask("AliTOFDigitizer","") 
+//___________________________________________
+  AliTOFDigitizer::AliTOFDigitizer()  :
+    AliDigitizer(),
+    fGeom(0x0),
+    fDigits(0x0),
+    fSDigitsArray(0x0),
+    fhitMap(0x0)
 {
-  // ctor
-  fTimeRes       = 100;  // ps
-  fChrgRes       = 100.; // pC
-  fNevents       = 0 ;      
-  fDigits        = 0 ;
-  fHits          = 0 ;
-  fIsInitialized = kFALSE ;
+  // Default ctor - don't use it
+}
+
+//___________________________________________
+AliTOFDigitizer::AliTOFDigitizer(AliRunDigitizer* manager): 
+  AliDigitizer(manager), 
+  fGeom(0x0),
+  fDigits(0x0),
+  fSDigitsArray(0x0),
+  fhitMap(0x0)
+{
+  //ctor with RunDigitizer
+}
+
+//------------------------------------------------------------------------
+AliTOFDigitizer::AliTOFDigitizer(const AliTOFDigitizer &source):
+  AliDigitizer(source),
+  fGeom(0x0), 
+  fDigits(0),
+  fSDigitsArray(0),
+  fhitMap(0)
+{
+  // copy constructor
+  this->fDigits=source.fDigits;
+  this->fSDigitsArray=source.fSDigitsArray;
+  this->fhitMap=source.fhitMap;
+  this->fGeom=source.fGeom; 
 
 }
 
-//____________________________________________________________________________ 
-AliTOFDigitizer::AliTOFDigitizer(const char* headerFile, const char *digitsTitle):TTask("AliTOFDigitizer","")
+//------------------------------------------------------------------------
+  AliTOFDigitizer& AliTOFDigitizer::operator=(const AliTOFDigitizer &source)
 {
-  // ctor
-  fTimeRes       = 100;  // ps
-  fChrgRes       = 100.; // pC
-  fNevents       = 0 ;      
-  fDigitsTitle   = digitsTitle ;
-  fHeadersFile   = headerFile ;
-  fIsInitialized = kFALSE ;
-  Init();
+  // ass. op.
+  this->fDigits=source.fDigits;
+  this->fSDigitsArray=source.fSDigitsArray;
+  this->fhitMap=source.fhitMap;
+  this->fGeom=source.fGeom; 
+  return *this;
+
 }
 
-//____________________________________________________________________________ 
+//------------------------------------------------------------------------
 AliTOFDigitizer::~AliTOFDigitizer()
 {
-  // dtor
-  if(fDigits)
-    delete fDigits ;
-  if(fHits)
-    delete fHits ;
+  // Destructor
 }
-//____________________________________________________________________________ 
-void AliTOFDigitizer::Init()
+
+//---------------------------------------------------------------------
+
+void AliTOFDigitizer::Exec(Option_t* /*option*/)
 {
-  // Initialization: open root-file, allocate arrays for hits and digits,
-  // attach task Digitizer to the list of TOF tasks
-  // 
-  // Initialization can not be done in the default constructor
+  //
+  // Perform digitization and merging.
+  // The algorithm is the following:
+  // - a hitmap is created to check if a pad is already activated;
+  // - an sdigits container is created to collect all sdigits from
+  //   different files;
+  // - sdigits are summed using the hitmap;
+  // - the sdigits container is used to create the array of AliTOFdigit.
+  //
 
-  if(!fIsInitialized){
+  AliDebug(1, "");
 
-    if(fHeadersFile.IsNull())
-      fHeadersFile="galice.root" ;
 
-    TFile * file = (TFile*) gROOT->GetFile(fHeadersFile.Data() ) ;
-    
-    //if file was not opened yet, read gAlice
-    if(file == 0){
-      if(fHeadersFile.Contains("rfio"))
-       file =  TFile::Open(fHeadersFile,"update") ;
-      else
-       file = new TFile(fHeadersFile.Data(),"update") ;
-      gAlice = (AliRun *) file->Get("gAlice") ;
-    }
-    fHits    = new TClonesArray("AliTOFhit"  , 405);
-    fDigits  = new TClonesArray("AliTOFdigit", 405);
-    
-    //add Task to //FPAlice/tasks/(S)Digitizer/TOF
-    TList * aList = gROOT->GetListOfBrowsables();
-    if (aList) {
-      TFolder * alice  = (TFolder*)aList->FindObject("FPAlice") ;
-      if (alice) {
-        TTask * aliceSD  = (TTask*)alice->FindObject("tasks/(S)Digitizer") ;
-        if (aliceSD) {
-          TTask * tofD   = (TTask*)aliceSD->GetListOfTasks()->FindObject("TOF") ;   
-          tofD->Add(this) ;
-        }
-      }
-    }
+  // get the ptr to TOF detector
+  AliTOF * tof = (AliTOF *) gAlice->GetDetector("TOF") ;
+
+  //Make branches
+  char branchname[20];
+  sprintf (branchname, "%s", tof->GetName ());
+
+  fDigits=new TClonesArray("AliTOFdigit",4000);
+  AliRunLoader* outrl = AliRunLoader::GetRunLoader(fManager->GetOutputFolderName());
+  if (outrl == 0x0)
+   {
+     AliError("Can not find Run Loader in output folder.");
+     return;
+   }
+   
+  outrl->CdGAFile();
+  TFile *in=(TFile*)gFile;
+  TDirectory *savedir=gDirectory;
 
-    fIsInitialized = kTRUE ;
+  if (!in->IsOpen()) {
+    AliWarning("Geometry file is not open default  TOF geometry will be used");
+    fGeom = new AliTOFGeometryV5();
   }
-}
-//____________________________________________________________________________
-void AliTOFDigitizer::Exec(Option_t *option) 
-{ 
-  Int_t    tracks[3];    // track info
-  Int_t    vol[5];       // dummy location for digit
-  Float_t  digit[2];     // TOF digit variables
-
-  // Collects all hits in the same active volume into digit
+  else {
+    in->cd();
+    fGeom = (AliTOFGeometry*)in->Get("TOFgeometry");
+  }
+
+  savedir->cd();
+
+  AliLoader* outgime = outrl->GetLoader("TOFLoader");
+  if (outgime == 0x0)
+   {
+     AliError("Can not get TOF Loader from Output Run Loader.");
+     return;
+   }
   
-  if(!fIsInitialized)
-    Init() ;
+  TTree* treeD = outgime->TreeD();
+  if (treeD == 0x0)
+   {
+     outgime->MakeTree("D");
+     treeD = outgime->TreeD();
+   }
+  //Make branch for digits (to be created in Init())
+  tof->MakeBranchInTree(treeD,branchname,&fDigits,4000);
 
-  if(strstr(option,"tim"))
-    gBenchmark->Start("TOFDigitizer");
+  // container for all summed sdigits (to be created in Init())
+  fSDigitsArray=new TClonesArray("AliTOFSDigit",1000);
   
-  fNevents = (Int_t) gAlice->TreeE()->GetEntries() ; 
+  // create hit map (to be created in Init())
+  fhitMap = new AliTOFHitMap(fSDigitsArray, fGeom);
   
-  Int_t ievent ;
-  // start loop on events
-  for(ievent = 0; ievent < fNevents; ievent++){
-    gAlice->GetEvent(ievent) ;
-    gAlice->SetEvent(ievent) ;
+  // Loop over files to digitize
+
+  for (Int_t inputFile=0; inputFile<fManager->GetNinputs();
+       inputFile++) {
+    ReadSDigit(inputFile);
+   }
+
+  // create digits
+  CreateDigits();
+
+  // free used memory for Hit Map in current event
+  delete fhitMap;
+  fSDigitsArray->Delete();
+  delete fSDigitsArray;
+
+  treeD->Fill();
+  outgime->WriteDigits("OVERWRITE");
+  outgime->UnloadDigits();
+  fDigits->Delete();
+  delete fDigits;
+
+}
+
+//---------------------------------------------------------------------
+
+void AliTOFDigitizer::CreateDigits()
+{
+  // loop on sdigits container to fill the AliTOFdigit TClonesArray
+  // start digitizing all the collected sdigits 
+
+  Int_t ndump=0; // dump the first ndump created digits for each event
+
+  // get the total number of collected sdigits
+  Int_t ndig = fSDigitsArray->GetEntriesFast();
+
+  for (Int_t k = 0; k < ndig; k++) {
     
-    if(gAlice->TreeH()==0){
-      cout << "AliTOFDigitizer: There is no Hit Tree" << endl;
-      return ;
-    }
+    Int_t  vol[5];  // location for a digit
+    for (Int_t i=0; i<5; i++) vol[i] = -1;
     
-    //set address of the hits 
-    TBranch * branch = gAlice->TreeH()->GetBranch("TOF");
-    if (branch) 
-      branch->SetAddress(&fHits);
-    else{
-      cout << "ERROR in AliTOFDigitizer: "<< endl ;
-      cout << "      no branch TOF in TreeH"<< endl ;
-      cout << "      do nothing " << endl ;
-      return ;
-    }
+    // Get the information for this digit
+    AliTOFSDigit *tofsdigit = (AliTOFSDigit *) fSDigitsArray->UncheckedAt(k);
     
-    fDigits->Clear();
-    Int_t ndigits = 0 ;
+    Int_t nslot=tofsdigit->GetNDigits(); // get the number of slots
+    // for current sdigit
     
-    //Now made Digits from hits, for TOF it is the same a part for the tof smearing
-    // and some missing MC variables     
-    Int_t itrack ;
-    for (itrack=0; itrack < gAlice->GetNtrack(); itrack++){
-
-      //=========== Get the TOF branch from Hits Tree for the Primary track itrack
-      branch->GetEntry(itrack,0);
-      
-      Int_t i;
-      for ( i = 0 ; i < fHits->GetEntries() ; i++ ) {
-
-       AliTOFhit * hit = (AliTOFhit*)fHits->At(i) ;
-
-        vol[0] = hit->GetSector();
-        vol[1] = hit->GetPlate();
-        vol[2] = hit->GetPadx();
-        vol[3] = hit->GetPadz();
-        vol[4] = hit->GetStrip();
-        // 95% of efficiency to be inserted here
-        // edge effect to be inserted here
-        // cross talk  to be inserted here
-        // simulation of the detector response
-        Float_t idealtime = hit->GetTof(); // unit s
-        idealtime *= 1.E+12;  // conversion from s to ps  
-                              // fTimeRes is given usually in ps
-        Float_t tdctime   = gRandom->Gaus(idealtime, fTimeRes);
-        digit[0] = tdctime;
-        // typical Landau Distribution to be inserted here
-        Float_t idealcharge = hit->GetEdep();
-        Float_t adccharge = gRandom->Gaus(idealcharge, fChrgRes);
-        digit[1] = adccharge;
-        // to be added a check for overlaps
-        new((*fDigits)[ndigits]) AliTOFdigit(tracks, vol, digit);
-       ndigits++ ;  
-      } 
-      
-    } // end loop over tracks
-
-    ndigits = fDigits->GetEntriesFast() ;
-    printf("AliTOFDigitizer: Total number of digits %d\n",ndigits);
-
-    if(gAlice->TreeD() == 0)
-      gAlice->MakeTree("D") ;
+    // TOF sdigit volumes (always the same for all slots)
+    Int_t sector    = tofsdigit->GetSector(); // range [0-17]
+    Int_t plate     = tofsdigit->GetPlate();  // range [0- 4]
+    Int_t strip     = tofsdigit->GetStrip();  // range [0-14/18/19]
+    Int_t padz      = tofsdigit->GetPadz();   // range [0- 1]
+    Int_t padx      = tofsdigit->GetPadx();   // range [0-47]
     
-    //check, if this branch already exits
-    TBranch * digitsBranch = 0;
-    TBranch * digitizerBranch = 0;
+    vol[0] = sector;
+    vol[1] = plate;
+    vol[2] = strip;
+    vol[3] = padx;
+    vol[4] = padz;
     
-    TObjArray * branches = gAlice->TreeD()->GetListOfBranches() ;
-    Int_t ibranch;
-    Bool_t tofNotFound = kTRUE ;
-    Bool_t digitizerNotFound = kTRUE ;
+    //--------------------- QA section ----------------------
+    // in the while, I perform QA
+    Bool_t isSDigitBad = (sector<0 || sector>17 || plate<0 || plate >4 || padz<0 || padz>1 || padx<0 || padx>47);
     
-    for(ibranch = 0;ibranch <branches->GetEntries();ibranch++){
-      
-      if(tofNotFound){
-       digitsBranch=(TBranch *) branches->At(ibranch) ;
-       if( (strcmp("TOF",digitsBranch->GetName())==0 ) &&
-           (fDigitsTitle.CompareTo(digitsBranch->GetTitle()) == 0) )
-         tofNotFound = kFALSE ;
-      }
-      if(digitizerNotFound){
-       digitizerBranch = (TBranch *) branches->At(ibranch) ;
-       if( (strcmp(digitizerBranch->GetName(),"AliTOFDigitizer") == 0)&&
-           (fDigitsTitle.CompareTo(digitizerBranch->GetTitle()) == 0) )
-         digitizerNotFound = kFALSE ;
-      }
-    }
-
-    if(!(digitizerNotFound && tofNotFound)){
-      cout << "AliTOFdigitizer error:" << endl ;
-      cout << "Can not overwrite existing branches: do not write" << endl ;
-      return ;
+    if (isSDigitBad) {
+      //AliFatal("strange sdigit found");
+      AliFatal(Form("strange sdigit found   %3i  %2i  %2i  %3i    %3i", sector, plate, padz, padx, strip));
     }
+    //-------------------------------------------------------
     
-    //Make (if necessary) branches    
-    char * file =0;
-    if(gSystem->Getenv("CONFIG_SPLIT_FILE")){ //generating file name
-      file = new char[strlen(gAlice->GetBaseFile())+20] ;
-      sprintf(file,"%s/TOF.Digits.root",gAlice->GetBaseFile()) ;
+    //------------------- Dump section ----------------------
+    if(k<ndump){
+      AliInfo(Form("%2i-th | Sector %2i | Plate %1i | Strip %2i | PadZ %1i | PadX %2i ", k, sector, plate, strip, padz, padx));
+      AliInfo(Form("%2i-th", k));
+      AliInfo("----------------------------------------------------");
     }
+    // ------------------------------------------------------
     
-    TDirectory *cwd = gDirectory;
-    
-    //First list of digits
-    Int_t bufferSize = 32000 ;    
-    digitsBranch = gAlice->TreeD()->Branch("TOF",&fDigits,bufferSize);
-    digitsBranch->SetTitle(fDigitsTitle.Data());
-    if (file) {
-      digitsBranch->SetFile(file);
-      TIter next( digitsBranch->GetListOfBranches());
-      TBranch * subbr;
-      while ((subbr=(TBranch*)next())) {
-       subbr->SetFile(file);
-      }   
-      cwd->cd();
-    } 
+    // start loop on number of slots for current sdigit
+    for (Int_t islot = 0; islot < nslot; islot++) {
+      Int_t  digit[4] = {-1,-1,-1,-1};     // TOF digit variables
+      Int_t tracknum[AliTOFSDigit::kMAXDIGITS];     // contributing tracks for the current slot
       
-    //second - Digitizer
-    Int_t splitlevel = 0 ;
-    AliTOFDigitizer * digtz = this ;
-    digitizerBranch = gAlice->TreeD()->Branch("AliTOFDigitizer","AliTOFDigitizer",
-                                              &digtz,bufferSize,splitlevel); 
-    digitizerBranch->SetTitle(fDigitsTitle.Data());
-    if (file) {
-      digitizerBranch->SetFile(file);
-      TIter next( digitizerBranch->GetListOfBranches());
-      TBranch * subbr ;
-      while ((subbr=(TBranch*)next())) {
-       subbr->SetFile(file);
-      }   
-      cwd->cd();
-      delete file;
-    }
+      Int_t tdc=tofsdigit->GetTdc(islot); digit[0]=tdc;
+      Int_t adc=tofsdigit->GetAdc(islot); digit[1]=adc;
+      
+      tracknum[0]=tofsdigit->GetTrack(islot,0);
+      tracknum[1]=tofsdigit->GetTrack(islot,1);
+      tracknum[2]=tofsdigit->GetTrack(islot,2);
+      
+      // new with placement must be used
+      // adding a TOF digit for each slot
+      TClonesArray &aDigits = *fDigits;
+      Int_t last=fDigits->GetEntriesFast();
+      new (aDigits[last]) AliTOFdigit(tracknum, vol, digit);
 
-    digitsBranch->Fill();
-    digitizerBranch->Fill();
-    gAlice->TreeD()->Write(0,TObject::kOverwrite) ;
-    
-    if(strstr(option,"deb"))
-      PrintDigits(option) ;
+    }
     
-  }
+  } // end loop on sdigits - end digitizing all collected sdigits
+
+  //Insert Decalibration 
+
+  AliTOFcalib * calib = new AliTOFcalib(fGeom);
+  InitDecalibration(calib);
+  DecalibrateTOFSignal(calib);
+  delete calib;
+}
+
+//---------------------------------------------------------------------
+
+void AliTOFDigitizer::ReadSDigit(Int_t inputFile )
+{
+  // Read sdigits for current event and inputFile; 
+  // store them into the sdigits container
+  // and update the hit map
+  // SDigits from different files are assumed to
+  // be created with the same simulation parameters.
   
-  if(strstr(option,"tim")){
-    gBenchmark->Stop("TOFDigitizer");
-    cout << "AliTOFDigitizer:" << endl ;
-    cout << "   took " << gBenchmark->GetCpuTime("TOFDigitizer") << " seconds for Digitizing " 
-        <<  gBenchmark->GetCpuTime("TOFDigitizer")/fNevents << " seconds per event " << endl ;
-    cout << endl ;
+  // get the treeS from manager
+  AliRunLoader* rl = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(inputFile));
+  if (rl == 0x0)
+   {
+     AliError(Form("Can not find Run Loader in input %d folder.",inputFile));
+     return;
+   }
+
+  AliLoader* gime = rl->GetLoader("TOFLoader");
+  if (gime == 0x0)
+   {
+     AliError(Form("Can not get TOF Loader from Input %d Run Loader.",inputFile));
+     return;
+   }
+
+  TTree* currentTreeS=gime->TreeS();
+  if (currentTreeS == 0x0)
+   {
+     Int_t retval = gime->LoadSDigits();
+     if (retval) 
+      {
+         AliError(Form("Error occured while loading S. Digits for Input %d",inputFile));
+         return;
+      }
+     currentTreeS=gime->TreeS();
+     if (currentTreeS == 0x0)
+      {
+         AliError(Form("Can not get S. Digits Tree for Input %d",inputFile));
+         return;
+      }
+   } 
+  // get the branch TOF inside the treeS
+  TClonesArray * sdigitsDummyContainer= new TClonesArray("AliTOFSDigit",  1000); 
+
+  // check if the branch exist
+  TBranch* tofBranch=currentTreeS->GetBranch("TOF");
+
+  if(!tofBranch){
+    AliFatal(Form("TOF branch not found for input %d",inputFile));
   }
   
+  tofBranch->SetAddress(&sdigitsDummyContainer);           
   
-}
-//__________________________________________________________________
-void AliTOFDigitizer::SetDigitsBranch(const char* title )
-{
-  // Setting title to branch Digits 
-  if(!fDigitsTitle.IsNull())
-    cout << "AliTOFdigitizer: changing Digits file from " <<fDigitsTitle.Data() << " to " << title << endl ;
-  fDigitsTitle=title ;
-}
-//__________________________________________________________________
-void AliTOFDigitizer::Print(Option_t* option)const
-{
-  // Prints parameters of Digitizer
-  cout << "------------------- "<< GetName() << " -------------" << endl ;
-  cout << "   Writing Digits to branch with title  " << fDigitsTitle.Data() << endl ;
-  cout << "   with digitization parameters Time resolution        = " << fTimeRes << endl ;
-  cout << "                                Adc smearing parameter = " << fChrgRes << endl ;
-  cout << "---------------------------------------------------"<<endl ;
+  Int_t nEntries = (Int_t)tofBranch->GetEntries();                                
+
+  // Loop through all entries in the tree
+  Int_t nbytes = 0;
   
+  for (Int_t iEntry = 0; iEntry < nEntries; iEntry++) {
+    
+    // Import the tree
+    nbytes += tofBranch->GetEvent(iEntry);
+    
+    // Get the number of sdigits
+    Int_t ndig = sdigitsDummyContainer->GetEntriesFast();
+    
+    for (Int_t k=0; k<ndig; k++) {
+      AliTOFSDigit *tofSdigit= (AliTOFSDigit*) sdigitsDummyContainer->UncheckedAt(k);
+      
+      Int_t  vol[5]; // location for a sdigit
+      for (Int_t i=0; i<5; i++) vol[i] = -1;
+
+      // check the sdigit volume
+      vol[0] = tofSdigit->GetSector();
+      vol[1] = tofSdigit->GetPlate();
+      vol[2] = tofSdigit->GetStrip();
+      vol[3] = tofSdigit->GetPadx();
+      vol[4] = tofSdigit->GetPadz();
+      
+      if (fhitMap->TestHit(vol) != kEmpty) {
+       AliTOFSDigit *sdig = static_cast<AliTOFSDigit*>(fhitMap->GetHit(vol));
+       sdig->Update(tofSdigit);
+
+      } else {
+
+       CollectSDigit(tofSdigit); // collect the current sdigit
+       fhitMap->SetHit(vol);     // update the hitmap for location vol
+
+      } // if (hitMap->TestHit(vol) != kEmpty)
+      
+    } // for (Int_t k=0; k<ndig; k++)
+    sdigitsDummyContainer->Delete();
+
+  } // end loop on entries
+
+  delete sdigitsDummyContainer;
+
 }
-//__________________________________________________________________
-Bool_t AliTOFDigitizer::operator==( AliTOFDigitizer const &digtz )const
+
+
+//_____________________________________________________________________________
+void AliTOFDigitizer::CollectSDigit(AliTOFSDigit * sdigit)
 {
-  // Equal operator.
-  // Dititizers are equal if their time resolution and Adc 
-  // smearing parameter are equal
-
-  if( (fTimeRes==digtz.fTimeRes)&&(fChrgRes==digtz.fChrgRes))
-    return kTRUE ;
-  else
-    return kFALSE ;
+  //
+  // Add a TOF sdigit in container
+  // new with placement must be used
+  TClonesArray &aSDigitsArray = *fSDigitsArray;
+  Int_t last=fSDigitsArray->GetEntriesFast();
+  // make a copy of the current sdigit and
+  // put it into tmp array
+  new (aSDigitsArray[last]) AliTOFSDigit(*sdigit);
 }
-//__________________________________________________________________
-void AliTOFDigitizer::PrintDigits(Option_t * option)
-{
-  // Prints list of digits produced in the current pass of AliTOFDigitizer
+
+//_____________________________________________________________________________
+void AliTOFDigitizer::InitDecalibration( AliTOFcalib *calib) const {
+  calib->ReadSimParFromCDB("TOF/Calib", -1); // use AliCDBManager's number
+}
+//---------------------------------------------------------------------
+void AliTOFDigitizer::DecalibrateTOFSignal( AliTOFcalib *calib){
+
+  // Read Calibration parameters from the CDB
+
+  AliTOFCal * cal= calib->GetTOFCalSimArray();
+
+  AliDebug(2,Form("Size of AliTOFCal = %i",cal->NPads()));
+
+  // Initialize Quantities to Simulate ToT Spectra
+
+  TH1F * hToT= calib->GetTOFSimToT();
+  Int_t nbins = hToT->GetNbinsX();
+  Float_t delta = hToT->GetBinWidth(1);
+  Float_t maxch = hToT->GetBinLowEdge(nbins)+delta;
+  Float_t minch = hToT->GetBinLowEdge(1);
+  Float_t max=0,min=0; //maximum and minimum value of the distribution
+  Int_t maxbin=0,minbin=0; //maximum and minimum bin of the distribution
+
+  for (Int_t ii=nbins; ii>0; ii--){
+    if (hToT->GetBinContent(ii)!= 0) {
+      max = maxch - (nbins-ii-1)*delta;
+      maxbin = ii; 
+      break;}
+  }
+  for (Int_t j=1; j<nbins; j++){
+    if (hToT->GetBinContent(j)!= 0) {
+      min = minch + (j-1)*delta;
+      minbin = j; 
+      break;}
+  }
+
+  Float_t maxToT=max;
+  Float_t minToT=min;
+  Float_t maxToTDistr=hToT->GetMaximum();
+
+  AliDebug (1, Form(" The minimum ToT = %f", minToT)); 
+  AliDebug (1, Form(" The maximum ToT = %f", maxToT)); 
+  AliDebug (1, Form(" The maximum peak in ToT = %f", maxToTDistr)); 
   
-  cout << "AliTOFDigitizer: " << endl ;
-  cout << "       Number of entries in Digits list  " << fDigits->GetEntriesFast() << endl ;
-  cout << endl ;
+  // Loop on TOF Digits
+
+  Bool_t isToTSimulated=kFALSE;
+  Bool_t misCalibPars=kFALSE;
+  if(hToT->GetEntries()>0)isToTSimulated=kTRUE;  
+  Int_t ndigits = fDigits->GetEntriesFast();    
+  for (Int_t i=0;i<ndigits;i++){
+    AliTOFdigit * dig = (AliTOFdigit*)fDigits->At(i);
+    Int_t detId[5];
+    detId[0] = dig->GetSector();
+    detId[1] = dig->GetPlate();
+    detId[2] = dig->GetStrip();
+    detId[3] = dig->GetPadz();
+    detId[4] = dig->GetPadx();
+    dig->SetTdcND(dig->GetTdc()); // save the non decalibrated time
+    if(isToTSimulated){  
+
+      //A realistic ToT Spectrum was found in input, 
+      //decalibrated TOF Digits likely to be simulated....
+      Int_t index = calib->GetIndex(detId); // The channel index    
+      AliTOFChannel *calChannel = cal->GetChannel(index); //retrieve the info
+      Float_t timedelay = calChannel->GetDelay(); //The global channel delay
+      Float_t par[6];  // time slewing parameters
   
-  if(strstr(option,"all")){// print all digits
-    
-    //loop over digits
-    AliTOFdigit * digit;
-    cout << "Digit # " << " Time of flight(ps) " << 
-            "  ADC(pC)"  <<  " Sector #" << " Plate #" << 
-            " Strip #" << " Pad # (x) " << " Pad # (z) " << endl;    
-    Int_t index ;
-    for (index = 0 ; index < fDigits->GetEntries() ; index++) {
-      digit = (AliTOFdigit * )  fDigits->At(index) ;
-
-      // set the width of the output with the setw(int width) manipulator
-
-      cout << setw(7)  <<  index << " " 
-           << setw(13) <<  digit->GetTdc()    << "  "  
-          << setw(13) <<  digit->GetAdc()    << "  "   
-          << setw(6)  <<  digit->GetSector() << "  "   
-          << setw(6)  <<  digit->GetPlate()  << "  "   
-          << setw(6)  <<  digit->GetStrip()  << "  "   
-          << setw(7)  <<  digit->GetPadx()   << "  "   
-          << setw(7)  <<  digit->GetPadz()   << "  " << endl;   
-      
-    } // end loop on digits
-    
-  } // close if "all" option selected
+      //check whether we actually ask for miscalibration
+
+      if(timedelay!=0)misCalibPars=kTRUE;
+      for (Int_t j = 0; j<6; j++){
+       par[j]=calChannel->GetSlewPar(j);
+       if(par[j]!=0)misCalibPars=kTRUE;
+      }
+      AliDebug(2,Form(" Calib Pars = %f, %f, %f, %f, %f, %f ",par[0],par[1],par[2],par[3],par[4],par[5]));
+      // Now generate Realistic ToT distribution from TestBeam Data. 
+      // Tot is in ns, assuming a Matching Window of 10 ns.
+
+      Float_t simToT = 0;
+      Float_t trix = 0;
+      Float_t triy = 0;
+      Double_t timeCorr;
+      Double_t tToT;
+      while (simToT <= triy){
+       trix = gRandom->Rndm(i);
+       triy = gRandom->Rndm(i);
+       trix = (maxToT-minToT)*trix + minToT; 
+       triy = maxToTDistr*triy;
+       Int_t binx=hToT->FindBin(trix);
+       simToT=hToT->GetBinContent(binx);
+      }
+      // the generated ToT (ns)
+      tToT= (Double_t) trix; // to apply slewing we start from ns..
+      // transform TOF signal in ns
+      AliDebug(2,Form(" The Initial Time (counts): %i: ",dig->GetTdc()));
+      AliDebug(2,Form(" Time before miscalibration (ps) %e: ",dig->GetTdc()*AliTOFGeometry::TdcBinWidth()));
+      // add slewing effect
+      timeCorr=par[0] + tToT*(par[1] +tToT*(par[2] +tToT*(par[3] +tToT*(par[4] +tToT*par[5])))); 
+      AliDebug(2,Form(" The Time slewing (ns): %f: ",timeCorr));
+      // add global time shift
+      timeCorr = timeCorr + timedelay;
+      AliDebug(2,Form(" The Time Slewing+ delay (ns): %f: ",timeCorr));
+      //convert to ps
+      timeCorr*=1E3;
+      Double_t timeMis = (Double_t)(dig->GetTdc())*AliTOFGeometry::TdcBinWidth();
+      timeMis = timeMis+timeCorr;
+      AliDebug(2,Form(" The Miscalibrated time (ps): %e: ",timeMis));
+
+      // now update the digit info
+      Int_t tdcCorr= (Int_t)(timeMis/AliTOFGeometry::TdcBinWidth());
+      AliDebug(2,Form(" Final Time (counts): %i: ",tdcCorr));
+      // Setting Decalibrated Time signal (TDC counts)    
+      dig->SetTdc(tdcCorr);   
+      // Setting realistic ToT signal (TDC counts) 
+      tToT*=1E3; //back to ps  
+      Int_t tot=(Int_t)(tToT/AliTOFGeometry::ToTBinWidth());//(factor 1E3 as input ToT is in ns)
+      dig->SetToT(tot); 
+      AliDebug(2,Form(" Final Time and ToT (counts): %i: ",dig->GetTdc(),dig->GetToT()));
+      if(tdcCorr<0){
+       AliWarning (Form(" The bad Slewed Time(TDC counts)= %i ", tdcCorr)); 
+       AliWarning(Form(" The bad ToT (TDC counts)= %i ", tot)); 
+      }
+    }
+    else{
+    // For Data with no Miscalibration, set ToT signal == Adc
+      dig->SetToT((Int_t)(dig->GetAdc()/AliTOFGeometry::ToTBinWidth())); //remove the factor 10^3 just to have a reasonable ToT range for raw data simulation even in the case of non-realistic ToT distribution (n.b. fAdc is practically an arbitrary quantity, and ToT has no impact on the TOF reco for non-miscalibrated digits)
+    }
+  }
+
+  if(!isToTSimulated){
+    AliDebug(1,"Standard Production, no miscalibrated digits");   
+  }else{
+    if(!misCalibPars){
+    AliDebug(1,"Standard Production, no miscalibrated digits");   
+    }
+    else {
+      AliDebug(1,"Simulating miscalibrated digits");   
+    } 
+  }
+  return;
 }
+