]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - TRD/AliTRDdigitizer.cxx
Classes moved to STEERBase.
[u/mrichter/AliRoot.git] / TRD / AliTRDdigitizer.cxx
index 9268e8f52c633fa804b6691df02dab2353b230ff..a3438eb3e115dab6237873cfefd6124808d41d94 100644 (file)
@@ -18,7 +18,9 @@
 ///////////////////////////////////////////////////////////////////////////////
 //                                                                           //
 //  Creates and handles digits from TRD hits                                 //
-//  Author: C. Blume (C.Blume@gsi.de)                                        //
+//  Authors: C. Blume (blume@ikf.uni-frankfurt.de)                           //
+//           C. Lippmann                                                     //
+//           B. Vulpescu                                                     //
 //                                                                           //
 //  The following effects are included:                                      //
 //      - Diffusion                                                          //
 //  The corresponding parameter can be adjusted via the various              //
 //  Set-functions. If these parameters are not explicitly set, default       //
 //  values are used (see Init-function).                                     //
-//  As an example on how to use this class to produce digits from hits       //
-//  have a look at the macro hits2digits.C                                   //
-//  The production of summable digits is demonstrated in hits2sdigits.C      //
-//  and the subsequent conversion of the s-digits into normal digits is      //
-//  explained in sdigits2digits.C.                                           //
 //                                                                           //
 ///////////////////////////////////////////////////////////////////////////////
 
@@ -62,6 +59,7 @@
 #include "AliRunDigitizer.h"
 #include "AliRunLoader.h"
 #include "AliLoader.h"
+#include "AliLog.h"
 
 #include "AliTRD.h"
 #include "AliTRDhit.h"
 #include "AliTRDsegmentArray.h"
 #include "AliTRDdigitsManager.h"
 #include "AliTRDgeometry.h"
-#include "AliTRDparameter.h"
 #include "AliTRDpadPlane.h"
 #include "AliTRDcalibDB.h"
 #include "AliTRDSimParam.h"
 #include "AliTRDCommonParam.h"
 
+#include "Cal/AliTRDCalROC.h"
+#include "Cal/AliTRDCalDet.h"
+
 ClassImp(AliTRDdigitizer)
 
 //_____________________________________________________________________________
 AliTRDdigitizer::AliTRDdigitizer()
+  :AliDigitizer()
+  ,fRunLoader(0)
+  ,fDigitsManager(0)
+  ,fSDigitsManager(0)
+  ,fSDigitsManagerList(0)
+  ,fTRD(0)
+  ,fGeo(0)
+  ,fEvent(0)
+  ,fMasks(0)
+  ,fCompress(kTRUE)
+  ,fSDigits(kFALSE)
+  ,fSDigitsScale(0.0)
+  ,fMergeSignalOnly(kFALSE)
+  ,fDiffLastVdrift(0)
+  ,fDiffusionT(0.0)
+  ,fDiffusionL(0.0)
+  ,fOmegaTau(0.0)
+  ,fLorentzFactor(0.0)
+  ,fTimeLastVdrift(0)
+  ,fTimeStruct1(0)
+  ,fTimeStruct2(0)
+  ,fVDlo(0)
+  ,fVDhi(0)
 {
   //
   // AliTRDdigitizer default constructor
   //
-
-  fRunLoader          = 0;
-  fDigitsManager      = 0;
-  fSDigitsManager     = 0;
-  fSDigitsManagerList = 0;
-  fTRD                = 0;
-  fGeo                = 0;
-  fPar                = 0;
-  fEvent              = 0;
-  fMasks              = 0;
-  fCompress           = kTRUE;
-  fDebug              = 0;
-  fSDigits            = kFALSE;
-  fSDigitsScale       = 0.0;
-  fMergeSignalOnly    = kFALSE;
-  fFixedGeometry      = kFALSE;
-  fTimeStructInfo.fLastVdrift   = 0;
-  fTimeStructInfo.fTimeStruct1  = 0;
-  fTimeStructInfo.fTimeStruct2  = 0;
-  fTimeStructInfo.fVDlo         = 0;
-  fTimeStructInfo.fVDhi         = 0;
-  
-  fDiffusionInfo.fLastVdrift    = 0;
-  fDiffusionInfo.fDiffusionT    = 0.0;
-  fDiffusionInfo.fDiffusionL    = 0.0;
-  fDiffusionInfo.fLorentzFactor = 0.0;
   
   Init();
 
 }
 
 //_____________________________________________________________________________
-AliTRDdigitizer::AliTRDdigitizer(const Text_t *name, const Text_t *title)
-                :AliDigitizer(name,title)
+AliTRDdigitizer::AliTRDdigitizer(const Text_t *name, const Text_t *title)              
+  :AliDigitizer(name,title)
+  ,fRunLoader(0)
+  ,fDigitsManager(0)
+  ,fSDigitsManager(0)
+  ,fSDigitsManagerList(0)
+  ,fTRD(0)
+  ,fGeo(0)
+  ,fEvent(0)
+  ,fMasks(0)
+  ,fCompress(kTRUE)
+  ,fSDigits(kFALSE)
+  ,fSDigitsScale(0.0)
+  ,fMergeSignalOnly(kFALSE)
+  ,fDiffLastVdrift(0)
+  ,fDiffusionT(0.0)
+  ,fDiffusionL(0.0)
+  ,fOmegaTau(0.0)
+  ,fLorentzFactor(0.0)
+  ,fTimeLastVdrift(0)
+  ,fTimeStruct1(0)
+  ,fTimeStruct2(0)
+  ,fVDlo(0)
+  ,fVDhi(0)
 {
   //
   // AliTRDdigitizer constructor
@@ -131,8 +149,30 @@ AliTRDdigitizer::AliTRDdigitizer(const Text_t *name, const Text_t *title)
 
 //_____________________________________________________________________________
 AliTRDdigitizer::AliTRDdigitizer(AliRunDigitizer *manager
-                                , const Text_t *name, const Text_t *title)
-                :AliDigitizer(manager,name,title)
+                               , const Text_t *name, const Text_t *title)
+  :AliDigitizer(manager,name,title)
+  ,fRunLoader(0)
+  ,fDigitsManager(0)
+  ,fSDigitsManager(0)
+  ,fSDigitsManagerList(0)
+  ,fTRD(0)
+  ,fGeo(0)
+  ,fEvent(0)
+  ,fMasks(0)
+  ,fCompress(kTRUE)
+  ,fSDigits(kFALSE)
+  ,fSDigitsScale(0.0)
+  ,fMergeSignalOnly(kFALSE)
+  ,fDiffLastVdrift(0)
+  ,fDiffusionT(0.0)
+  ,fDiffusionL(0.0)
+  ,fOmegaTau(0.0)
+  ,fLorentzFactor(0.0)
+  ,fTimeLastVdrift(0)
+  ,fTimeStruct1(0)
+  ,fTimeStruct2(0)
+  ,fVDlo(0)
+  ,fVDhi(0)
 {
   //
   // AliTRDdigitizer constructor
@@ -144,7 +184,29 @@ AliTRDdigitizer::AliTRDdigitizer(AliRunDigitizer *manager
 
 //_____________________________________________________________________________
 AliTRDdigitizer::AliTRDdigitizer(AliRunDigitizer *manager)
-                :AliDigitizer(manager,"AliTRDdigitizer","TRD digitizer")
+  :AliDigitizer(manager,"AliTRDdigitizer","TRD digitizer")
+  ,fRunLoader(0)
+  ,fDigitsManager(0)
+  ,fSDigitsManager(0)
+  ,fSDigitsManagerList(0)
+  ,fTRD(0)
+  ,fGeo(0)
+  ,fEvent(0)
+  ,fMasks(0)
+  ,fCompress(kTRUE)
+  ,fSDigits(kFALSE)
+  ,fSDigitsScale(0.0)
+  ,fMergeSignalOnly(kFALSE)
+  ,fDiffLastVdrift(0)
+  ,fDiffusionT(0.0)
+  ,fDiffusionL(0.0)
+  ,fOmegaTau(0.0)
+  ,fLorentzFactor(0.0)
+  ,fTimeLastVdrift(0)
+  ,fTimeStruct1(0)
+  ,fTimeStruct2(0)
+  ,fVDlo(0)
+  ,fVDhi(0)
 {
   //
   // AliTRDdigitizer constructor
@@ -162,48 +224,74 @@ Bool_t AliTRDdigitizer::Init()
   //
 
   fRunLoader          = 0;
-
-  //NewIO: These data members probably are not needed anymore
   fDigitsManager      = 0;
   fSDigitsManager     = 0;
   fSDigitsManagerList = 0;
   fTRD                = 0;
   fGeo                = 0;
-  fPar                = 0;  
-  //End NewIO comment
 
   fEvent              = 0;
   fMasks              = 0;
   fCompress           = kTRUE;
-  fDebug              = 0;
   fSDigits            = kFALSE;
-  fSDigitsScale       = 100.; // For the summable digits
+  fSDigitsScale       = 100.0;
   fMergeSignalOnly    = kFALSE;
-  fFixedGeometry      = kFALSE;
  
-  fTimeStructInfo.fLastVdrift   = -1;
-  fTimeStructInfo.fTimeStruct1  = 0;
-  fTimeStructInfo.fTimeStruct2  = 0;
-  fTimeStructInfo.fVDlo         = 0;
-  fTimeStructInfo.fVDhi         = 0;
+  fTimeLastVdrift     = -1;
+  fTimeStruct1        =  0;
+  fTimeStruct2        =  0;
+  fVDlo               =  0;
+  fVDhi               =  0;
   
-  fDiffusionInfo.fLastVdrift    = -1;
-  fDiffusionInfo.fDiffusionT    = 0.0;
-  fDiffusionInfo.fDiffusionL    = 0.0;
-  fDiffusionInfo.fLorentzFactor = 0.0;
+  fDiffLastVdrift     = -1;
+  fDiffusionT         =  0.0;
+  fDiffusionL         =  0.0;
+  fLorentzFactor      =  0.0;
 
   return AliDigitizer::Init();
 
 }
 
 //_____________________________________________________________________________
-AliTRDdigitizer::AliTRDdigitizer(const AliTRDdigitizer &d):AliDigitizer(d)
+AliTRDdigitizer::AliTRDdigitizer(const AliTRDdigitizer &d)
+  :AliDigitizer(d)
+  ,fRunLoader(0)
+  ,fDigitsManager(0)
+  ,fSDigitsManager(0)
+  ,fSDigitsManagerList(0)
+  ,fTRD(0)
+  ,fGeo(0)
+  ,fEvent(0)
+  ,fMasks(0)
+  ,fCompress(d.fCompress)
+  ,fSDigits(d.fSDigits)
+  ,fSDigitsScale(d.fSDigitsScale)
+  ,fMergeSignalOnly(d.fMergeSignalOnly)
+  ,fDiffLastVdrift(-1)
+  ,fDiffusionT(0.0)
+  ,fDiffusionL(0.0)
+  ,fOmegaTau(0.0)
+  ,fLorentzFactor(0.0)
+  ,fTimeLastVdrift(-1)
+  ,fTimeStruct1(0)
+  ,fTimeStruct2(0)
+  ,fVDlo(0)
+  ,fVDhi(0)
 {
   //
   // AliTRDdigitizer copy constructor
   //
 
-  ((AliTRDdigitizer &) d).Copy(*this);
+  // Do not copy timestructs, just invalidate lastvdrift.
+  // Next time they are requested, they get recalculated
+  if (((AliTRDdigitizer &) d).fTimeStruct1) {
+    delete [] ((AliTRDdigitizer &) d).fTimeStruct1;
+    ((AliTRDdigitizer &) d).fTimeStruct1 = 0;
+  }
+  if (((AliTRDdigitizer &) d).fTimeStruct2) {
+    delete [] ((AliTRDdigitizer &) d).fTimeStruct2;
+    ((AliTRDdigitizer &) d).fTimeStruct2 = 0;
+  }
 
 }
 
@@ -216,10 +304,13 @@ AliTRDdigitizer::~AliTRDdigitizer()
 
   if (fDigitsManager) {
     delete fDigitsManager;
-    fDigitsManager = 0;
+    fDigitsManager      = 0;
   }
 
-  fSDigitsManager = 0;
+  if (fDigitsManager) {
+    delete fSDigitsManager;
+    fSDigitsManager     = 0;
+  }
 
   if (fSDigitsManagerList) {
     fSDigitsManagerList->Delete();
@@ -229,19 +320,22 @@ AliTRDdigitizer::~AliTRDdigitizer()
 
   if (fMasks) {
     delete [] fMasks;
-    fMasks = 0;
+    fMasks       = 0;
+  }
+
+  if (fTimeStruct1) {
+    delete [] fTimeStruct1;
+    fTimeStruct1 = 0;
   }
 
-  if (fTimeStructInfo.fTimeStruct1)
-  {
-    delete [] fTimeStructInfo.fTimeStruct1;
-    fTimeStructInfo.fTimeStruct1 = 0;
+  if (fTimeStruct2) {
+    delete [] fTimeStruct2;
+    fTimeStruct2 = 0;
   }
 
-  if (fTimeStructInfo.fTimeStruct2) 
-  {
-    delete [] fTimeStructInfo.fTimeStruct2;
-    fTimeStructInfo.fTimeStruct2 = 0;
+  if (fGeo) {
+    delete fGeo;
+    fGeo = 0;
   }
 
 }
@@ -254,6 +348,7 @@ AliTRDdigitizer &AliTRDdigitizer::operator=(const AliTRDdigitizer &d)
   //
 
   if (this != &d) ((AliTRDdigitizer &) d).Copy(*this);
+
   return *this;
 
 }
@@ -271,38 +366,31 @@ void AliTRDdigitizer::Copy(TObject &d) const
   ((AliTRDdigitizer &) d).fSDigitsManagerList = 0;
   ((AliTRDdigitizer &) d).fTRD                = 0;
   ((AliTRDdigitizer &) d).fGeo                = 0;
-  ((AliTRDdigitizer &) d).fPar                = 0;
   ((AliTRDdigitizer &) d).fEvent              = 0;
   ((AliTRDdigitizer &) d).fMasks              = 0;
   ((AliTRDdigitizer &) d).fCompress           = fCompress;
-  ((AliTRDdigitizer &) d).fDebug              = fDebug  ;
   ((AliTRDdigitizer &) d).fSDigits            = fSDigits;
   ((AliTRDdigitizer &) d).fSDigitsScale       = fSDigitsScale;
   ((AliTRDdigitizer &) d).fMergeSignalOnly    = fMergeSignalOnly;
-  ((AliTRDdigitizer &) d).fFixedGeometry      = fFixedGeometry;
                                        
   AliTRDdigitizer& target = (AliTRDdigitizer &) d;
   
-  target.fDiffusionInfo = fDiffusionInfo;
-  
   // Do not copy timestructs, just invalidate lastvdrift.
   // Next time they are requested, they get recalculated
-  if (target.fTimeStructInfo.fTimeStruct1)
-  {
-    delete[] target.fTimeStructInfo.fTimeStruct1;
-    target.fTimeStructInfo.fTimeStruct1 = 0;
-  }
-  if (target.fTimeStructInfo.fTimeStruct2)
-  {
-    delete[] target.fTimeStructInfo.fTimeStruct2;
-    target.fTimeStructInfo.fTimeStruct2 = 0;
+  if (target.fTimeStruct1) {
+    delete [] target.fTimeStruct1;
+    target.fTimeStruct1 = 0;
+  }
+  if (target.fTimeStruct2) {
+    delete [] target.fTimeStruct2;
+    target.fTimeStruct2 = 0;
   }  
-  target.fTimeStructInfo.fLastVdrift = -1;
+  target.fTimeLastVdrift = -1;
 
 }
 
 //_____________________________________________________________________________
-void AliTRDdigitizer::Exec(Option_toption)
+void AliTRDdigitizer::Exec(Option_t *option)
 {
   //
   // Executes the merging
@@ -314,107 +402,95 @@ void AliTRDdigitizer::Exec(Option_t* option)
 
   TString optionString = option;
   if (optionString.Contains("deb")) {
-    fDebug = 1;
-    if (optionString.Contains("2")) {
-      fDebug = 2;
-    }
-    printf("<AliTRDdigitizer::Exec> ");
-    printf("Called with debug option %d\n",fDebug);
+    AliLog::SetClassDebugLevel("AliTRDdigitizer",1);
+    AliInfo("Called with debug option");
   }
 
   // The AliRoot file is already connected by the manager
-  AliRunLoaderinrl;
+  AliRunLoader *inrl;
   
-  if (gAlice) 
-   {
-    if (fDebug > 0) {
-      printf("<AliTRDdigitizer::Exec> ");
-      printf("AliRun object found on file.\n");
-    }
-   }
+  if (gAlice) {
+    AliDebug(1,"AliRun object found on file.");
+  }
   else {
     inrl = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(0));
     inrl->LoadgAlice();
     gAlice = inrl->GetAliRun();
-    if (!gAlice)
-     {
-       printf("<AliTRDdigitizer::Exec> ");
-       printf("Could not find AliRun object.\n");
-       return;
-     }
+    if (!gAlice) {
+      AliError("Could not find AliRun object.")
+      return;
+    }
   }
                                                                            
   Int_t nInput = fManager->GetNinputs();
-  fMasks = new Int_t[nInput];
+  fMasks       = new Int_t[nInput];
   for (iInput = 0; iInput < nInput; iInput++) {
     fMasks[iInput] = fManager->GetMask(iInput);
   }
 
+  //
   // Initialization
+  //
+
+  AliRunLoader *orl = AliRunLoader::GetRunLoader(fManager->GetOutputFolderName());
 
-  AliRunLoader* orl = AliRunLoader::GetRunLoader(fManager->GetOutputFolderName());
   if (InitDetector()) {
-    AliLoader* ogime = orl->GetLoader("TRDLoader");
 
-    TTree* tree = 0;
-    if (fSDigits)
-      { 
-       //if we produce SDigits
+    AliLoader *ogime = orl->GetLoader("TRDLoader");
+
+    TTree *tree = 0;
+    if (fSDigits) { 
+      // If we produce SDigits
+      tree = ogime->TreeS();
+      if (!tree) {
+       ogime->MakeTree("S");
        tree = ogime->TreeS();
-       if (!tree)
-         {
-           ogime->MakeTree("S");
-           tree = ogime->TreeS();
-         }
       }
-    else
-      {//if we produce Digits
-       tree = ogime->TreeD();
-       if (!tree)
-         {
-           ogime->MakeTree("D");
-           tree = ogime->TreeD();
-         }
+    }
+    else {
+      // If we produce Digits
+      tree = ogime->TreeD();
+      if (!tree) {
+       ogime->MakeTree("D");
+        tree = ogime->TreeD();
       }
+    }
+
     MakeBranch(tree);
+
   }
  
   for (iInput = 0; iInput < nInput; iInput++) {
 
-    if (fDebug > 0) {
-      printf("<AliTRDdigitizer::Exec> ");
-      printf("Add input stream %d\n",iInput);
-    }
+    AliDebug(1,Form("Add input stream %d",iInput));
 
-    // check if the input tree exists
+    // Check if the input tree exists
     inrl = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(iInput));
-    AliLoader* gime = inrl->GetLoader("TRDLoader");
-
-    TTree * treees =  gime->TreeS();
-    if (treees == 0x0) 
-     {
-      if (gime->LoadSDigits())
-       {
-         Error("Exec","Error Occured while loading S. Digits for input %d.",iInput);
-         return;
-       }
-      treees =  gime->TreeS();
-     }
+    AliLoader *gime = inrl->GetLoader("TRDLoader");
+
+    TTree *treees = gime->TreeS();
+    if (treees == 0x0) {
+      if (gime->LoadSDigits()) {
+        AliError(Form("Error Occured while loading S. Digits for input %d.",iInput));
+        return;
+      }
+      treees = gime->TreeS();
+    }
     
     if (treees == 0x0) {
-      printf("<AliTRDdigitizer::Exec> ");
-      printf("Input stream %d does not exist\n",iInput);
+      AliError(Form("Input stream %d does not exist",iInput));
       return;
     } 
 
     // Read the s-digits via digits manager
     sdigitsManager = new AliTRDdigitsManager();
-    sdigitsManager->SetDebug(fDebug);
     sdigitsManager->SetSDigits(kTRUE);
     
-    AliRunLoader* rl = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(iInput));
-    AliLoader* gimme = rl->GetLoader("TRDLoader");
-    if (!gimme->TreeS()) gimme->LoadSDigits();
+    AliRunLoader *rl = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(iInput));
+    AliLoader *gimme = rl->GetLoader("TRDLoader");
+    if (!gimme->TreeS()) {
+      gimme->LoadSDigits();
+    }
     sdigitsManager->ReadDigits(gimme->TreeS());
 
     // Add the s-digits to the input list 
@@ -423,28 +499,17 @@ void AliTRDdigitizer::Exec(Option_t* option)
   }
 
   // Convert the s-digits to normal digits
-  if (fDebug > 0) {
-    printf("<AliTRDdigitizer::Exec> ");
-    printf("Do the conversion\n");
-  }
+  AliDebug(1,"Do the conversion");
   SDigits2Digits();
 
   // Store the digits
-  if (fDebug > 0) {
-    printf("<AliTRDdigitizer::Exec> ");
-    printf("Write the digits\n");
-  }
-  
+  AliDebug(1,"Write the digits");
   fDigitsManager->WriteDigits();
 
-  //Write parameters
+  // Write parameters
   orl->CdGAFile();
-  if (!gFile->Get("TRDparameter")) GetParameter()->Write();
 
-  if (fDebug > 0) {
-    printf("<AliTRDdigitizer::Exec> ");
-    printf("Done\n");
-  }
+  AliDebug(1,"Done");
 
   DeleteSDigitsManager();
 
@@ -460,64 +525,117 @@ Bool_t AliTRDdigitizer::Open(const Char_t *file, Int_t nEvent)
   //  
 
   TString evfoldname = AliConfig::GetDefaultEventFolderName();
+
   fRunLoader = AliRunLoader::GetRunLoader(evfoldname);
-  if (!fRunLoader)
-    fRunLoader = AliRunLoader::Open(file,AliConfig::GetDefaultEventFolderName(),
-                                   "UPDATE");
-  
-  if (!fRunLoader)
-   {
-     Error("Open","Can not open session for file %s.",file);
-     return kFALSE;
-   }
+  if (!fRunLoader) {
+    fRunLoader = AliRunLoader::Open(file,evfoldname,"UPDATE");
+  }  
+  if (!fRunLoader) {
+    AliError(Form("Can not open session for file %s.",file));
+    return kFALSE;
+  }
    
-  if (!fRunLoader->GetAliRun()) fRunLoader->LoadgAlice();
+  if (!fRunLoader->GetAliRun()) {
+    fRunLoader->LoadgAlice();
+  }
   gAlice = fRunLoader->GetAliRun();
   
   if (gAlice) {
-    if (fDebug > 0) {
-      printf("<AliTRDdigitizer::Open> ");
-      printf("AliRun object found on file.\n");
-    }
+    AliDebug(1,"AliRun object found on file.");
   }
   else {
-    printf("<AliTRDdigitizer::Open> ");
-    printf("Could not find AliRun object.\n");
+    AliError("Could not find AliRun object.");
     return kFALSE;
   }
 
   fEvent = nEvent;
 
-  // Import the Trees for the event nEvent in the file
-  fRunLoader->GetEvent(fEvent);
+  AliLoader *loader = fRunLoader->GetLoader("TRDLoader");
+  if (!loader) {
+    AliError("Can not get TRD loader from Run Loader");
+    return kFALSE;
+  }
+  
+  if (InitDetector()) {
+    TTree *tree = 0;
+    if (fSDigits) { 
+      // If we produce SDigits
+      tree = loader->TreeS();
+      if (!tree) {
+        loader->MakeTree("S");
+        tree = loader->TreeS();
+      }
+    }
+    else {
+      // If we produce Digits
+      tree = loader->TreeD();
+      if (!tree) {
+        loader->MakeTree("D");
+        tree = loader->TreeD();
+      }
+    }
+    return MakeBranch(tree);
+  }
+  else {
+    return kFALSE;
+  }
+
+}
+
+//_____________________________________________________________________________
+Bool_t AliTRDdigitizer::Open(AliRunLoader *runLoader, Int_t nEvent)
+{
+  //
+  // Opens a ROOT-file with TRD-hits and reads in the hit-tree
+  //
+  // Connect the AliRoot file containing Geometry, Kine, and Hits
+  //  
+
+  fRunLoader = runLoader;
+  if (!fRunLoader) {
+    AliError("RunLoader does not exist");
+    return kFALSE;
+  }
+   
+  if (!fRunLoader->GetAliRun()) {
+    fRunLoader->LoadgAlice();
+  }
+  gAlice = fRunLoader->GetAliRun();
   
-  AliLoader* loader = fRunLoader->GetLoader("TRDLoader");
-  if (!loader)
-   {
-     Error("Open","Can not get TRD loader from Run Loader");
-     return kFALSE;
-   }
+  if (gAlice) {
+    AliDebug(1,"AliRun object found on file.");
+  }
+  else {
+    AliError("Could not find AliRun object.");
+    return kFALSE;
+  }
+
+  fEvent = nEvent;
+
+  AliLoader *loader = fRunLoader->GetLoader("TRDLoader");
+  if (!loader) {
+    AliError("Can not get TRD loader from Run Loader");
+    return kFALSE;
+  }
   
   if (InitDetector()) {
-    TTree* tree = 0;
-    if (fSDigits)
-     { 
-     //if we produce SDigits
-       tree = loader->TreeS();
-       if (!tree)
-        {
-         loader->MakeTree("S");
-         tree = loader->TreeS();
-        }
-     }
-    else
-     {//if we produce Digits
-       if (!tree)
-        {
-         loader->MakeTree("D");
-         tree = loader->TreeD();
-        }
-     }
+    TTree *tree = 0;
+    if (fSDigits) { 
+      // If we produce SDigits
+      tree = loader->TreeS();
+      if (!tree) {
+        loader->MakeTree("S");
+        tree = loader->TreeS();
+      }
+    }
+    else {
+      // If we produce Digits
+      tree = loader->TreeD();
+      if (!tree) {
+        loader->MakeTree("D");
+        tree = loader->TreeD();
+      }
+    }
     return MakeBranch(tree);
   }
   else {
@@ -536,22 +654,16 @@ Bool_t AliTRDdigitizer::InitDetector()
   // Get the pointer to the detector class and check for version 1
   fTRD = (AliTRD *) gAlice->GetDetector("TRD");
   if (!fTRD) {
-    printf("<AliTRDdigitizer::InitDetector> ");
-    printf("No TRD module found\n");
+    AliFatal("No TRD module found");
     exit(1);
   }
   if (fTRD->IsVersion() != 1) {
-    printf("<AliTRDdigitizer::InitDetector> ");
-    printf("TRD must be version 1 (slow simulator).\n");
+    AliFatal("TRD must be version 1 (slow simulator)");
     exit(1);
   }
 
   // Get the geometry
-  fGeo = fTRD->GetGeometry();
-  if (fDebug > 0) {
-    printf("<AliTRDdigitizer::InitDetector> ");
-    printf("Geometry version %d\n",fGeo->IsVersion());
-  }
+  fGeo = new AliTRDgeometry();
 
   // Create a digits manager
   delete fDigitsManager;
@@ -559,7 +671,6 @@ Bool_t AliTRDdigitizer::InitDetector()
   fDigitsManager->SetSDigits(fSDigits);
   fDigitsManager->CreateArrays();
   fDigitsManager->SetEvent(fEvent);
-  fDigitsManager->SetDebug(fDebug);
 
   // The list for the input s-digits manager to be merged
   if (fSDigitsManagerList) {
@@ -574,7 +685,7 @@ Bool_t AliTRDdigitizer::InitDetector()
 }
 
 //_____________________________________________________________________________
-Bool_t AliTRDdigitizer::MakeBranch(TTreetree) const
+Bool_t AliTRDdigitizer::MakeBranch(TTree *tree) const
 {
   // 
   // Create the branches for the digits array
@@ -596,7 +707,7 @@ Bool_t AliTRDdigitizer::MakeDigits()
   ///////////////////////////////////////////////////////////////
 
   // Converts number of electrons to fC
-  const Double_t kEl2fC  = 1.602E-19 * 1.0E15; 
+  const Double_t kEl2fC  = 1.602e-19 * 1.0e15; 
 
   ///////////////////////////////////////////////////////////////
 
@@ -606,12 +717,18 @@ Bool_t AliTRDdigitizer::MakeDigits()
   // Number of track dictionary arrays
   const Int_t kNDict     = AliTRDdigitsManager::kNDict;
 
-  // Half the width of the amplification region
-  const Float_t kAmWidth = AliTRDgeometry::AmThick() / 2.;
+  // Width of the amplification region
+  const Float_t kAmWidth = AliTRDgeometry::AmThick();
   // Width of the drift region
   const Float_t kDrWidth = AliTRDgeometry::DrThick();
+  // Drift + amplification region 
+  const Float_t kDrMin   =          - 0.5 * kAmWidth;
+  const Float_t kDrMax   = kDrWidth + 0.5 * kAmWidth;
   
-  Int_t    iRow, iCol, iTime, iPad;
+  Int_t    iRow;
+  Int_t    iCol;
+  Int_t    iTime;
+  Int_t    iPad;
   Int_t    iDict  = 0;
   Int_t    nBytes = 0;
 
@@ -623,8 +740,7 @@ Bool_t AliTRDdigitizer::MakeDigits()
   Int_t    timeBinTRFend   = 1;
 
   Double_t pos[3];
-  Double_t rot[3];
-  Double_t xyz[3];
+  Double_t loc[3];
   Double_t padSignal[kNpad];
   Double_t signalOld[kNpad];
 
@@ -634,105 +750,88 @@ Bool_t AliTRDdigitizer::MakeDigits()
 
   AliTRDpadPlane   *padPlane = 0;
 
-  TGeoManager::Import("geometry.root");
+  AliTRDCalROC     *calVdriftROC          = 0;
+  Float_t           calVdriftDetValue     = 0.0;
+  AliTRDCalROC     *calT0ROC              = 0;
+  Float_t           calT0DetValue         = 0.0;
+  AliTRDCalROC     *calGainFactorROC      = 0;
+  Float_t           calGainFactorDetValue = 0.0;
 
-  // Create a default parameter class if none is defined
-  if (!fPar) {
-    fPar = new AliTRDparameter("TRDparameter","Standard TRD parameter");
-    if (fDebug > 0) {
-      printf("<AliTRDdigitizer::MakeDigits> ");
-      printf("Create the default parameter object\n");
-    }
+  if (!gGeoManager) {
+    AliFatal("No geometry manager!");
   }
-  
-  AliTRDSimParam* simParam = AliTRDSimParam::Instance();
+
+  if (!fGeo) {
+    AliError("No geometry defined");
+    return kFALSE;
+  }
+  fGeo->ReadGeoMatrices();
+
+  AliTRDSimParam    *simParam    = AliTRDSimParam::Instance();
   if (!simParam) {
-    printf("<AliTRDdigitizer::MakeDigits> ");
-    printf("Could not get simulation params\n");
+    AliFatal("Could not get simulation parameters");
     return kFALSE;
   }
   
-  AliTRDCommonParamcommonParam = AliTRDCommonParam::Instance();
+  AliTRDCommonParam *commonParam = AliTRDCommonParam::Instance();
   if (!commonParam) {
-    printf("<AliTRDdigitizer::MakeDigits> ");
-    printf("Could not get common params\n");
+    AliFatal("Could not get common parameterss");
     return kFALSE;
   }
-  
-  // Create a container for the amplitudes
-  AliTRDsegmentArray *signalsArray 
-                     = new AliTRDsegmentArray("AliTRDdataArrayF"
-                                             ,AliTRDgeometry::Ndet());
 
-  AliTRDcalibDBcalibration = AliTRDcalibDB::Instance();
+  AliTRDcalibDB     *calibration = AliTRDcalibDB::Instance();
   if (!calibration) {
-    printf("<AliTRDdigitizer::MakeDigits> ");
-    printf("Could not get calibration object\n");
+    AliFatal("Could not get calibration object");  
     return kFALSE;
   }
 
-  if (!gGeoManager) {
-    printf("<AliTRDdigitizer::MakeDigits> ");
-    printf("No TGeoManager available. Switch to fixed geometry.\n");
-    fFixedGeometry = kTRUE;
-  }
-
-  if (simParam->TRFOn()) {
-    timeBinTRFend = ((Int_t) ( simParam->GetTRFhi() * calibration->GetSamplingFrequency())) - 1;
-    if (fDebug > 0) {
-      printf("<AliTRDdigitizer::MakeDigits> ");
-      printf("Sample the TRF up to bin %d\n",timeBinTRFend);
-    }
-  }
-
-  Float_t elAttachProp = simParam->GetElAttachProp() / 100.; 
-
-  if (!fGeo) {
-    printf("<AliTRDdigitizer::MakeDigits> ");
-    printf("No geometry defined\n");
-    return kFALSE;
-  }
+  AliDebug(1,"Start creating digits");
+  
+  // Create a container for the amplitudes
+  AliTRDsegmentArray *signalsArray = new AliTRDsegmentArray("AliTRDdataArrayF"
+                                                           ,AliTRDgeometry::Ndet());
 
-  if (fDebug > 0) {
-    printf("<AliTRDdigitizer::MakeDigits> ");
-    printf("Start creating digits.\n");
+  AliLoader *gimme = fRunLoader->GetLoader("TRDLoader");
+  if (!gimme->TreeH()) {
+    gimme->LoadHits();
   }
-
-  AliLoader* gimme = fRunLoader->GetLoader("TRDLoader");
-  if (!gimme->TreeH()) gimme->LoadHits();
-  TTree* hitTree = gimme->TreeH();
+  TTree *hitTree = gimme->TreeH();
   if (hitTree == 0x0) {
-      Error("MakeDigits","Can not get TreeH");
-      return kFALSE;
+    AliError("Can not get TreeH");
+    return kFALSE;
   }
   fTRD->SetTreeAddress();
-  
+
   // Get the number of entries in the hit tree
   // (Number of primary particles creating a hit somewhere)
   Int_t nTrack = (Int_t) hitTree->GetEntries();
-  if (fDebug > 0) {
-    printf("<AliTRDdigitizer::MakeDigits> ");
-    printf("Found %d primary particles\n",nTrack);
-  }
-
-  Int_t detectorOld = -1;
-  Int_t countHits   =  0; 
-
-  if (fDebug > 0) {
-    printf("<AliTRDdigitizer::MakeDigits> Sampling = %.0fMHz\n", calibration->GetSamplingFrequency());
-    printf("<AliTRDdigitizer::MakeDigits> Gain = %d\n",(Int_t)simParam->GetGasGain());
-    printf("<AliTRDdigitizer::MakeDigits> Noise = %d\n",(Int_t)simParam->GetNoise());
-    if (simParam->TimeStructOn()) {
-      printf("<AliTRDdigitizer::MakeDigits> ");
-      printf("Time Structure of drift cells implemented.\n");
-    } else {
-      printf("<AliTRDdigitizer::MakeDigits> ");
-      printf("Constant drift velocity in drift cells.\n");      
-    }
+  AliDebug(1,Form("Found %d primary particles",nTrack));
+  AliDebug(1,Form("Sampling = %.0fMHz"        ,commonParam->GetSamplingFrequency()));
+  AliDebug(1,Form("Gain     = %d"             ,((Int_t) simParam->GetGasGain())));
+  AliDebug(1,Form("Noise    = %d"             ,((Int_t) simParam->GetNoise())));
+  if (simParam->TimeStructOn()) {
+    AliDebug(1,"Time Structure of drift cells implemented.");
+  } 
+  else {
+    AliDebug(1,"Constant drift velocity in drift cells.");
   }
-  
+  if (simParam->TRFOn()) {
+    timeBinTRFend = ((Int_t) (simParam->GetTRFhi() 
+                  * commonParam->GetSamplingFrequency())) - 1;
+    AliDebug(1,Form("Sample the TRF up to bin %d",timeBinTRFend));
+  }
+
+  // Get the detector wise calibration objects
+  const AliTRDCalDet *calVdriftDet     = calibration->GetVdriftDet();  
+  const AliTRDCalDet *calT0Det         = calibration->GetT0Det();  
+  const AliTRDCalDet *calGainFactorDet = calibration->GetGainFactorDet();  
+
+  Int_t   detectorOld  = -1;
+  Int_t   countHits    =  0;
   Int_t   nTimeTotal   = calibration->GetNumberOfTimeBins();
-  Float_t samplingRate = calibration->GetSamplingFrequency();
+  Float_t samplingRate = commonParam->GetSamplingFrequency();
+  Float_t elAttachProp = simParam->GetElAttachProp() / 100.0; 
 
   // Loop through all entries in the tree
   for (Int_t iTrack = 0; iTrack < nTrack; iTrack++) {
@@ -748,324 +847,301 @@ Bool_t AliTRDdigitizer::MakeDigits()
       countHits++;
       iHit++;
 
-              pos[0]        = hit->X();
-              pos[1]        = hit->Y();
-              pos[2]        = hit->Z();
-      Float_t q             = hit->GetCharge();
-      Int_t   track         = hit->Track();
-      Int_t   detector      = hit->GetDetector();
-      Int_t   plane         = fGeo->GetPlane(detector);
-      Int_t   sector        = fGeo->GetSector(detector);
-      Int_t   chamber       = fGeo->GetChamber(detector);
-      Float_t time0         = AliTRDgeometry::GetTime0(plane);
-
-      padPlane              = commonParam->GetPadPlane(plane,chamber);
-      Float_t row0          = padPlane->GetRow0();
-      Float_t col0          = padPlane->GetCol0();
-      Int_t   nRowMax       = padPlane->GetNrows();
-      Int_t   nColMax       = padPlane->GetNcols();
-
-      Int_t   inDrift       = 1;
-      if (!fFixedGeometry) {
-        gGeoManager->SetCurrentPoint(pos);
-        gGeoManager->FindNode();
-        if (strstr(gGeoManager->GetPath(),"/UK")) {
-          inDrift = 0;
-       }
+      Float_t q        = hit->GetCharge();
+      // Don't analyze test hits
+      if (((Int_t) q) == 0) {
+        hit = (AliTRDhit *) fTRD->NextHit();   
+        continue;
       }
 
-      if (fDebug > 1) {
-        printf("Analyze hit no. %d ",iHit);
-        printf("-----------------------------------------------------------\n");
-        hit->Dump();
-        printf("plane = %d, sector = %d, chamber = %d\n"
-              ,plane,sector,chamber);
-        printf("nRowMax = %d, nColMax = %d\n" 
-              ,nRowMax,nColMax);
-        printf("nTimeTotal = %d\n"
-             ,nTimeTotal);
-        printf("row0 = %f, col0 = %f, time0 = %f\n"
-              ,row0,col0,time0);
-        printf("samplingRate = %f\n"
-              ,samplingRate); 
+      pos[0]           = hit->X();
+      pos[1]           = hit->Y();
+      pos[2]           = hit->Z();
+      Int_t   track    = hit->Track();
+      Int_t   detector = hit->GetDetector();
+      Float_t hittime  = hit->GetTime();
+      Int_t   plane    = fGeo->GetPlane(detector);
+      Int_t   chamber  = fGeo->GetChamber(detector);
+      padPlane         = fGeo->GetPadPlane(plane,chamber);
+      Float_t row0     = padPlane->GetRow0ROC();
+      Int_t   nRowMax  = padPlane->GetNrows();
+      Int_t   nColMax  = padPlane->GetNcols();
+      Int_t   inDrift  = 1;
+
+      // Find the current volume with the geo manager
+      gGeoManager->SetCurrentPoint(pos);
+      gGeoManager->FindNode();
+      if (strstr(gGeoManager->GetPath(),"/UK")) {
+       inDrift = 0;
       }
-       
-      // Don't analyze test hits and switched off detectors
-      if ((CheckDetector(plane,chamber,sector)) &&
-          (((Int_t) q) != 0)) {
 
-        if (detector != detectorOld) {
+      if (detector != detectorOld) {
 
-          if (fDebug > 1) {
-            printf("<AliTRDdigitizer::MakeDigits> ");
-            printf("Get new container. New det = %d, Old det = %d\n"
-                  ,detector,detectorOld);
-         }
-          // Compress the old one if enabled
-          if ((fCompress) && (detectorOld > -1)) {
-            if (fDebug > 1) {
-              printf("<AliTRDdigitizer::MakeDigits> ");
-              printf("Compress the old container ...");
-           }
-            signals->Compress(1,0);
-            for (iDict = 0; iDict < kNDict; iDict++) {
-              dictionary[iDict]->Compress(1,0);
-           }
-            if (fDebug > 1) printf("done\n");
-         }
-         // Get the new container
-          signals = (AliTRDdataArrayF *) signalsArray->At(detector);
-          if (signals->GetNtime() == 0) {
-            // Allocate a new one if not yet existing
-            if (fDebug > 1) {
-              printf("<AliTRDdigitizer::MakeDigits> ");
-              printf("Allocate a new container ... ");
-           }
-            signals->Allocate(nRowMax,nColMax,nTimeTotal);
-         }
-          else {
-           // Expand an existing one
-            if (fCompress) {
-              if (fDebug > 1) {
-                printf("<AliTRDdigitizer::MakeDigits> ");
-                printf("Expand an existing container ... ");
-             }
-              signals->Expand();
-           }
-         }
-         // The same for the dictionary
-          for (iDict = 0; iDict < kNDict; iDict++) {       
-            dictionary[iDict] = fDigitsManager->GetDictionary(detector,iDict);
-            if (dictionary[iDict]->GetNtime() == 0) {
-              dictionary[iDict]->Allocate(nRowMax,nColMax,nTimeTotal);
-           }
-            else {
-              if (fCompress) dictionary[iDict]->Expand();
-            }
-          }      
-          if (fDebug > 1) printf("done\n");
-          detectorOld = detector;
+        // Compress the old one if enabled
+        if ((fCompress) && (detectorOld > -1)) {
+          signals->Compress(1,0);
+          for (iDict = 0; iDict < kNDict; iDict++) {
+            dictionary[iDict]->Compress(1,0);
+          }
         }
-
-        if (fFixedGeometry) {
-          // Rotate the sectors on top of each other       
-          fGeo->Rotate(detector,pos,rot);
+       // Get the new container
+        signals = (AliTRDdataArrayF *) signalsArray->At(detector);
+        if (signals->GetNtime() == 0) {
+          // Allocate a new one if not yet existing
+          signals->Allocate(nRowMax,nColMax,nTimeTotal);
        }
         else {
-         // Use the geoManager
-          Double_t aaa[3];
-          gGeoManager->MasterToLocal(pos,aaa);
-          if (inDrift) {
-            aaa[2] = time0 - (kDrWidth / 2.0 + kAmWidth) + aaa[2];
-         } 
-          else {
-            aaa[2] = time0 + aaa[2];
+         // Expand an existing one
+          if (fCompress) {
+            signals->Expand();
          }
-          aaa[1] = row0 + padPlane->GetLengthRim() + fGeo->RpadW() 
-                 - 0.5 * fGeo->GetChamberLength(plane,chamber) 
-                + aaa[1];
-          rot[0] = aaa[2];
-          rot[1] = aaa[0];
-          rot[2] = aaa[1];
-       }
-
-        // The driftlength. It is negative if the hit is between pad plane and anode wires.
-        Double_t driftlength = time0 - rot[0];
-
-        // Loop over all electrons of this hit
-        // TR photons produce hits with negative charge
-        Int_t nEl = ((Int_t) TMath::Abs(q));
-        for (Int_t iEl = 0; iEl < nEl; iEl++) {
-
-          xyz[0] = rot[0];
-          xyz[1] = rot[1];
-          xyz[2] = rot[2];
-
-         // Stupid patch to take care of TR photons that are absorbed
-         // outside the chamber volume. A real fix would actually need
-         // a more clever implementation of the TR hit generation
-          if (q < 0.0) {
-           if ((xyz[2] < padPlane->GetRowEnd()) ||
-                (xyz[2] > padPlane->GetRow0())) {
-              if (iEl == 0) {
-                printf("<AliTRDdigitizer::MakeDigits> ");
-                printf("Hit outside of sensitive volume, row (z=%f, row0=%f, rowE=%f)\n"
-                      ,xyz[2],padPlane->GetRow0(),padPlane->GetRowEnd());
-             }
-              continue;
-           }
-            Float_t tt = driftlength + kAmWidth;
-            if (tt < 0.0 || tt > kDrWidth + 2.*kAmWidth) {
-              if (iEl == 0) {
-                printf("<AliTRDdigitizer::MakeDigits> ");
-                printf("Hit outside of sensitive volume, time (Q = %d)\n",((Int_t) q));
-             }
-              continue;
-           }
+        }
+       // The same for the dictionary
+        for (iDict = 0; iDict < kNDict; iDict++) {       
+          dictionary[iDict] = fDigitsManager->GetDictionary(detector,iDict);
+          if (dictionary[iDict]->GetNtime() == 0) {
+            dictionary[iDict]->Allocate(nRowMax,nColMax,nTimeTotal);
          }
+          else {
+            if (fCompress) dictionary[iDict]->Expand();
+          }
+        }      
 
-          // Get row and col of unsmeared electron to retrieve drift velocity
-          // The pad row (z-direction)
-          Int_t    rowE      = padPlane->GetPadRowNumber(xyz[2]);
-          if (rowE < 0) continue;
-          Double_t rowOffset = padPlane->GetPadRowOffset(rowE,xyz[2]);
+       // Get the calibration objects
+       calVdriftROC      = calibration->GetVdriftROC(detector);
+        calVdriftDetValue = calVdriftDet->GetValue(detector);
+       calT0ROC          = calibration->GetT0ROC(detector);
+        calT0DetValue     = calT0Det->GetValue(detector);
 
-          // The pad column (rphi-direction)
-         Float_t offsetTilt     = padPlane->GetTiltOffset(rowOffset);   // MI change
-          Int_t    colE      = padPlane->GetPadColNumber(xyz[1]+offsetTilt,rowOffset);
-          if (colE < 0) continue;        
-          Double_t colOffset = padPlane->GetPadColOffset(colE,xyz[1]+offsetTilt);
+        detectorOld = detector;
 
-          Float_t driftvelocity = calibration->GetVdrift(detector, colE, rowE);
-                    
-          // Normalised drift length
-          Double_t absdriftlength = TMath::Abs(driftlength);
-          if (commonParam->ExBOn()) 
-            absdriftlength /= TMath::Sqrt(GetLorentzFactor(driftvelocity));
-
-          // Electron attachment
-          if (simParam->ElAttachOn()) {
-            if (gRandom->Rndm() < (absdriftlength * elAttachProp)) continue;
-          }
-          
-          // Apply the diffusion smearing
-          if (simParam->DiffusionOn()) {
-            if (!(Diffusion(driftvelocity, absdriftlength,xyz))) continue;
-          }
+      }
 
-          // Apply E x B effects (depends on drift direction)
-          if (commonParam->ExBOn()) { 
-            if (!(ExB(driftvelocity, driftlength,xyz))) continue;
-          }
+      // Go to the local coordinate system:
+      // loc[0] - col  direction in amplification or driftvolume
+      // loc[1] - row  direction in amplification or driftvolume
+      // loc[2] - time direction in amplification or driftvolume
+      gGeoManager->MasterToLocal(pos,loc);
+      if (inDrift) {
+       // Relative to middle of amplification region
+        loc[2] = loc[2] - kDrWidth/2.0 - kAmWidth/2.0;
+      } 
 
-          // The electron position after diffusion and ExB in pad coordinates.
-          // The pad row (z-direction)
-          rowE       = padPlane->GetPadRowNumber(xyz[2]);
-          if (rowE < 0) continue;
-          rowOffset  = padPlane->GetPadRowOffset(rowE,xyz[2]);
-
-          // The pad column (rphi-direction)
-          offsetTilt = padPlane->GetTiltOffset(rowOffset);   // MI change
-          colE       = padPlane->GetPadColNumber(xyz[1]+offsetTilt,rowOffset);
-          if (colE < 0) continue;         
-          colOffset  = padPlane->GetPadColOffset(colE,xyz[1]+offsetTilt);
-         
-          // Also re-retrieve drift velocity because col and row may have changed
-          driftvelocity = calibration->GetVdrift(detector, colE, rowE);
-          Float_t t0 = calibration->GetT0(detector, colE, rowE);
+      // The driftlength [cm] (w/o diffusion yet !).
+      // It is negative if the hit is between pad plane and anode wires.
+      Double_t driftlength = -1.0 * loc[2];
+
+      // Stupid patch to take care of TR photons that are absorbed
+      // outside the chamber volume. A real fix would actually need
+      // a more clever implementation of the TR hit generation
+      if (q < 0.0) {
+       if ((loc[1] < padPlane->GetRowEndROC()) ||
+            (loc[1] > padPlane->GetRow0ROC())) {
+          hit = (AliTRDhit *) fTRD->NextHit();   
+          continue;
+       }
+        if ((driftlength < kDrMin) ||
+            (driftlength > kDrMax)) {
+          hit = (AliTRDhit *) fTRD->NextHit();   
+          continue;
+        }
+      }
+
+      // Get row and col of unsmeared electron to retrieve drift velocity
+      // The pad row (z-direction)
+      Int_t    rowE         = padPlane->GetPadRowNumberROC(loc[1]);
+      if (rowE < 0) {
+        hit = (AliTRDhit *) fTRD->NextHit();   
+        continue;
+      }
+      Double_t rowOffset    = padPlane->GetPadRowOffsetROC(rowE,loc[1]);
+
+      // The pad column (rphi-direction)
+      Double_t offsetTilt   = padPlane->GetTiltOffset(rowOffset);
+      Int_t    colE         = padPlane->GetPadColNumber(loc[0]+offsetTilt);
+      if (colE < 0) {
+        hit = (AliTRDhit *) fTRD->NextHit();   
+        continue;        
+      }
+      Double_t colOffset    = padPlane->GetPadColOffset(colE,loc[0]+offsetTilt);
+
+      Float_t driftvelocity = calVdriftDetValue * calVdriftROC->GetValue(colE,rowE);
+                    
+      // Normalized drift length
+      Double_t absdriftlength = TMath::Abs(driftlength);
+      if (commonParam->ExBOn()) {
+        absdriftlength /= TMath::Sqrt(GetLorentzFactor(driftvelocity));
+      }
+
+      // Loop over all electrons of this hit
+      // TR photons produce hits with negative charge
+      Int_t nEl = ((Int_t) TMath::Abs(q));
+      for (Int_t iEl = 0; iEl < nEl; iEl++) {
+
+        // Now the real local coordinate system of the ROC
+        // column direction: locC
+        // row direction:    locR 
+        // time direction:   locT
+        // locR and locC are identical to the coordinates of the corresponding
+        // volumina of the drift or amplification region.
+        // locT is defined relative to the wire plane (i.e. middle of amplification
+        // region), meaming locT = 0, and is negative for hits coming from the
+        // drift region. 
+        Double_t locC = loc[0];
+        Double_t locR = loc[1];
+        Double_t locT = loc[2];
+
+        // Electron attachment
+        if (simParam->ElAttachOn()) {
+          if (gRandom->Rndm() < (absdriftlength * elAttachProp)) {
+            continue;
+         }
+        }
           
-          // Convert the position to drift time, using either constant drift velocity or
-          // time structure of drift cells (non-isochronity, GARFIELD calculation).
-         Double_t drifttime;
-          if (simParam->TimeStructOn()) {
-           // Get z-position with respect to anode wire:
-           //Double_t Z  =  xyz[2] - row0 + simParam->GetAnodeWireOffset();
-            Double_t Z  =  row0 - xyz[2] + simParam->GetAnodeWireOffset();
-           Z -= ((Int_t)(2*Z))/2.;
-           if (Z>0.25)   Z  = 0.5-Z;
-           // use drift time map (GARFIELD)
-            drifttime = TimeStruct(driftvelocity, time0 - xyz[0] + kAmWidth, Z);
-         } 
-          else {
-           // use constant drift velocity
-            drifttime = TMath::Abs(time0 - xyz[0]) / driftvelocity;
+        // Apply the diffusion smearing
+        if (simParam->DiffusionOn()) {
+          if (!(Diffusion(driftvelocity,absdriftlength,locR,locC,locT))) {
+            continue;
          }
+        }
 
-          // Apply the gas gain including fluctuations
-          Double_t ggRndm = 0.0;
-          do {
-            ggRndm = gRandom->Rndm();
-         } while (ggRndm <= 0);
-          Int_t signal = (Int_t) (-(simParam->GetGasGain()) * TMath::Log(ggRndm));
-
-          // Apply the pad response 
-          if (simParam->PRFOn()) {
-           // The distance of the electron to the center of the pad 
-           // in units of pad width
-            //Double_t dist = - colOffset / padPlane->GetColSize(colE);
-           Double_t dist = (colOffset - 0.5*padPlane->GetColSize(colE))
-                          / padPlane->GetColSize(colE);
-
-            if (!(calibration->PadResponse(signal,dist,plane,padSignal))) continue;
-         }
-         else {
-            padSignal[0] = 0.0;
-            padSignal[1] = signal;
-            padSignal[2] = 0.0;
+        // Apply E x B effects (depends on drift direction)
+        if (commonParam->ExBOn()) { 
+          if (!(ExB(driftvelocity,driftlength,locC))) {
+            continue;
          }
+        }
 
-          // The time bin (always positive), with t0 correction
-          Double_t timeBinIdeal = drifttime * samplingRate + t0;
-         // Protection according to MI
-          if (TMath::Abs(timeBinIdeal) > 2*nTimeTotal) {
-            timeBinIdeal = 2 * nTimeTotal;
+        // The electron position after diffusion and ExB in pad coordinates.
+        // The pad row (z-direction)
+        rowE       = padPlane->GetPadRowNumberROC(locR);
+        if (rowE < 0) continue;
+        rowOffset  = padPlane->GetPadRowOffsetROC(rowE,locR);
+
+        // The pad column (rphi-direction)
+        offsetTilt = padPlane->GetTiltOffset(rowOffset);
+        colE       = padPlane->GetPadColNumber(locC+offsetTilt);
+        if (colE < 0) continue;         
+        colOffset  = padPlane->GetPadColOffset(colE,locC+offsetTilt);
+         
+        // Also re-retrieve drift velocity because col and row may have changed
+        driftvelocity = calVdriftDetValue * calVdriftROC->GetValue(colE,rowE);
+        Float_t t0    = calT0DetValue     + calT0ROC->GetValue(colE,rowE);
+
+        // Convert the position to drift time [mus], using either constant drift velocity or
+        // time structure of drift cells (non-isochronity, GARFIELD calculation).
+       // Also add absolute time of hits to take pile-up events into account properly
+       Double_t drifttime;
+        if (simParam->TimeStructOn()) {
+         // Get z-position with respect to anode wire
+          Double_t zz  =  row0 - locR + simParam->GetAnodeWireOffset();
+         zz -= ((Int_t)(2 * zz)) / 2.0;
+         if (zz > 0.25) {
+            zz  = 0.5 - zz;
          }
-          Int_t    timeBinTruncated = (Int_t) timeBinIdeal;
-          // The distance of the position to the middle of the timebin
-          Double_t timeOffset = ((Float_t) timeBinTruncated + 0.5 - timeBinIdeal) / samplingRate;
+         // Use drift time map (GARFIELD)
+          drifttime = TimeStruct(driftvelocity,0.5*kAmWidth-1.0*locT,zz)
+                    + hittime;
+        } 
+        else {
+         // Use constant drift velocity
+          drifttime = -1.0 * locT / driftvelocity
+                    + hittime;
+        }
+
+        // Apply the gas gain including fluctuations
+        Double_t ggRndm = 0.0;
+        do {
+          ggRndm = gRandom->Rndm();
+       } while (ggRndm <= 0);
+        Int_t signal = (Int_t) (-(simParam->GetGasGain()) * TMath::Log(ggRndm));
+
+        // Apply the pad response 
+        if (simParam->PRFOn()) {
+         // The distance of the electron to the center of the pad 
+         // in units of pad width
+         Double_t dist = (colOffset - 0.5*padPlane->GetColSize(colE))
+                        / padPlane->GetColSize(colE);
+         // This is still the fixed parametrization, i.e. not dependent on
+         // calibration values !!!!
+          if (!(calibration->PadResponse(signal,dist,plane,padSignal))) continue;
+       }
+        else {
+          padSignal[0] = 0.0;
+          padSignal[1] = signal;
+          padSignal[2] = 0.0;
+        }
+
+        // The time bin (always positive), with t0 distortion
+        Double_t timeBinIdeal = drifttime * samplingRate + t0;
+        // Protection 
+        if (TMath::Abs(timeBinIdeal) > 2*nTimeTotal) {
+          timeBinIdeal = 2 * nTimeTotal;
+       }
+        Int_t    timeBinTruncated = (Int_t) timeBinIdeal;
+        // The distance of the position to the middle of the timebin
+        Double_t timeOffset       = ((Float_t) timeBinTruncated 
+                                  + 0.5 - timeBinIdeal) / samplingRate;
           
-         // Sample the time response inside the drift region
-         // + additional time bins before and after.
-          // The sampling is done always in the middle of the time bin
-          for (Int_t iTimeBin = TMath::Max(timeBinTruncated, 0);
-               iTimeBin < TMath::Min(timeBinTruncated+timeBinTRFend,nTimeTotal);
-              iTimeBin++) {
-
-           // Apply the time response
-            Double_t timeResponse = 1.0;
-            Double_t crossTalk    = 0.0;
-            Double_t time         = (iTimeBin - timeBinTruncated) / samplingRate + timeOffset;
-            if (simParam->TRFOn()) {
-              timeResponse = simParam->TimeResponse(time);
-            }
-      
-            if (simParam->CTOn()) {
-              crossTalk    = simParam->CrossTalk(time);
-            }
+       // Sample the time response inside the drift region
+       // + additional time bins before and after.
+        // The sampling is done always in the middle of the time bin
+        for (Int_t iTimeBin = TMath::Max(timeBinTruncated,0)
+            ;iTimeBin < TMath::Min(timeBinTruncated+timeBinTRFend,nTimeTotal)
+           ;iTimeBin++) {
+
+         // Apply the time response
+          Double_t timeResponse = 1.0;
+          Double_t crossTalk    = 0.0;
+          Double_t time         = (iTimeBin - timeBinTruncated) / samplingRate + timeOffset;
+          if (simParam->TRFOn()) {
+            timeResponse = simParam->TimeResponse(time);
+          }
+          if (simParam->CTOn()) {
+            crossTalk    = simParam->CrossTalk(time);
+          }
 
-            signalOld[0] = 0.0;
-            signalOld[1] = 0.0;
-            signalOld[2] = 0.0;
+          signalOld[0] = 0.0;
+          signalOld[1] = 0.0;
+          signalOld[2] = 0.0;
 
-            for (iPad = 0; iPad < kNpad; iPad++) {
+          for (iPad = 0; iPad < kNpad; iPad++) {
 
-              Int_t colPos = colE + iPad - 1;
-              if (colPos <        0) continue;
-              if (colPos >= nColMax) break;
+            Int_t colPos = colE + iPad - 1;
+            if (colPos <        0) continue;
+            if (colPos >= nColMax) break;
 
-              // Add the signals
-              Int_t iCurrentTimeBin = iTimeBin;
-              signalOld[iPad]  = signals->GetDataUnchecked(rowE,colPos,iCurrentTimeBin);
-              if( colPos != colE ) {
-                signalOld[iPad] += padSignal[iPad] * (timeResponse + crossTalk);
-              } 
-              else {
-                signalOld[iPad] += padSignal[iPad] * timeResponse;
-              }
-              signals->SetDataUnchecked(rowE,colPos,iCurrentTimeBin,signalOld[iPad]);
-
-              // Store the track index in the dictionary
-              // Note: We store index+1 in order to allow the array to be compressed
-              if (signalOld[iPad] > 0) { 
-                for (iDict = 0; iDict < kNDict; iDict++) {
-                  Int_t oldTrack = dictionary[iDict]->GetDataUnchecked(rowE
-                                                                      ,colPos
-                                                                      ,iCurrentTimeBin);
-                  if (oldTrack == track+1) break;
-                  if (oldTrack ==       0) {
-                    dictionary[iDict]->SetDataUnchecked(rowE,colPos,iCurrentTimeBin,track+1);
-                    break;
-                  }
+            // Add the signals
+            Int_t iCurrentTimeBin = iTimeBin;
+            signalOld[iPad]  = signals->GetDataUnchecked(rowE,colPos,iCurrentTimeBin);
+            if (colPos != colE) {
+              signalOld[iPad] += padSignal[iPad] * (timeResponse + crossTalk);
+            } 
+            else {
+              signalOld[iPad] += padSignal[iPad] * timeResponse;
+            }
+            signals->SetDataUnchecked(rowE,colPos,iCurrentTimeBin,signalOld[iPad]);
+
+            // Store the track index in the dictionary
+            // Note: We store index+1 in order to allow the array to be compressed
+            if (signalOld[iPad] > 0) { 
+              for (iDict = 0; iDict < kNDict; iDict++) {
+                Int_t oldTrack = dictionary[iDict]->GetDataUnchecked(rowE
+                                                                    ,colPos
+                                                                    ,iCurrentTimeBin);
+                if (oldTrack == track+1) break;
+                if (oldTrack ==       0) {
+                  dictionary[iDict]->SetDataUnchecked(rowE,colPos,iCurrentTimeBin,track+1);
+                  break;
                 }
               }
+            }
 
-           } // Loop: pads
-
-         } // Loop: time bins
+         } // Loop: pads
 
-        } // Loop: electrons of a single hit
+       } // Loop: time bins
 
-      } // If: detector and test hit
+      } // Loop: electrons of a single hit
 
       hit = (AliTRDhit *) fTRD->NextHit();   
 
@@ -1073,38 +1149,36 @@ Bool_t AliTRDdigitizer::MakeDigits()
 
   } // Loop: primary tracks
 
-  if (fDebug > 0) {
-    printf("<AliTRDdigitizer::MakeDigits> ");
-    printf("Finished analyzing %d hits\n",countHits);
-  }
+  AliDebug(1,Form("Finished analyzing %d hits",countHits));
+
+  //____________________________________________________________________
+  //
+  // Create (s)digits
+  //____________________________________________________________________
+  //
 
   // The coupling factor
   Double_t coupling = simParam->GetPadCoupling() 
-      * simParam->GetTimeCoupling();
+                    * simParam->GetTimeCoupling();
 
   // The conversion factor
-  Double_t convert  = kEl2fC
-      * simParam->GetChipGain();
+  Double_t convert  = kEl2fC 
+                    * simParam->GetChipGain();
 
   // Loop through all chambers to finalize the digits
   Int_t iDetBeg = 0;
   Int_t iDetEnd = AliTRDgeometry::Ndet();
   for (Int_t iDet = iDetBeg; iDet < iDetEnd; iDet++) {
 
-    Int_t plane       = fGeo->GetPlane(iDet);
-    Int_t sector      = fGeo->GetSector(iDet);
-    Int_t chamber     = fGeo->GetChamber(iDet);
-    Int_t nRowMax     = commonParam->GetRowMax(plane,chamber,sector);
-    Int_t nColMax     = commonParam->GetColMax(plane);
+    Int_t plane      = fGeo->GetPlane(iDet);
+    Int_t sector     = fGeo->GetSector(iDet);
+    Int_t chamber    = fGeo->GetChamber(iDet);
+    Int_t nRowMax    = fGeo->GetRowMax(plane,chamber,sector);
+    Int_t nColMax    = fGeo->GetColMax(plane);
 
     Double_t *inADC  = new Double_t[nTimeTotal];
     Double_t *outADC = new Double_t[nTimeTotal];
 
-    if (fDebug > 0) {
-      printf("<AliTRDdigitizer::MakeDigits> ");
-      printf("Digitization for chamber %d\n",iDet);
-    }
-
     // Add a container for the digits of this detector
     digits = fDigitsManager->GetDigits(iDet);        
     // Allocate memory space for the digits buffer
@@ -1132,13 +1206,25 @@ Bool_t AliTRDdigitizer::MakeDigits()
 
     Int_t nDigits = 0;
 
-    // Don't create noise in detectors that are switched off
-    if (CheckDetector(plane,chamber,sector)) {
+    // Don't create noise in detectors that are switched off / not installed, etc.
+    if (( calibration->IsChamberInstalled(iDet)) &&
+        (!calibration->IsChamberMasked(iDet))    &&
+        ( fGeo->GetSMstatus(sector))) {
+
+      // Get the calibration objects
+      calGainFactorROC      = calibration->GetGainFactorROC(iDet);
+      calGainFactorDetValue = calGainFactorDet->GetValue(iDet);
 
       // Create the digits for this chamber
       for (iRow  = 0; iRow  <  nRowMax;   iRow++ ) {
         for (iCol  = 0; iCol  <  nColMax;   iCol++ ) {
 
+          // Check whether pad is masked
+         // Bridged pads are not considered yet!!!
+          if (calibration->IsPadMasked(iDet,iCol,iRow)) {
+            continue;
+         }
+
          // Create summable digits
           if (fSDigits) {
 
@@ -1155,44 +1241,51 @@ Bool_t AliTRDdigitizer::MakeDigits()
          // Create normal digits
           else {
 
+            Float_t padgain = calGainFactorDetValue 
+                            * calGainFactorROC->GetValue(iCol,iRow);
+            if (padgain <= 0) {
+              AliError(Form("Not a valid gain %f, %d %d %d",padgain,iDet,iCol,iRow));
+            }
+
             for (iTime = 0; iTime < nTimeTotal; iTime++) {         
+
               Float_t signalAmp = signals->GetDataUnchecked(iRow,iCol,iTime);
+
               // Pad and time coupling
               signalAmp *= coupling;
-             Float_t padgain = calibration->GetGainFactor(iDet, iCol, iRow);
+             // Gain factors
              signalAmp *= padgain;
+
               // Add the noise, starting from minus ADC baseline in electrons
-              Double_t baselineEl = simParam->GetADCbaseline() * (simParam->GetADCinRange()
-                                                           / simParam->GetADCoutRange()) 
-                                                           / convert;
+              Double_t baselineEl = simParam->GetADCbaseline() 
+                                  * (simParam->GetADCinRange() / simParam->GetADCoutRange())
+                                  / convert;
               signalAmp  = TMath::Max((Double_t) gRandom->Gaus(signalAmp,simParam->GetNoise())
                                      ,-baselineEl);
               // Convert to mV
               signalAmp *= convert;
               // Add ADC baseline in mV
-              signalAmp += simParam->GetADCbaseline() * (simParam->GetADCinRange()
-                                                   / simParam->GetADCoutRange());
-             // Convert to ADC counts. Set the overflow-bit fADCoutRange if the 
+              signalAmp += simParam->GetADCbaseline() 
+                         * (simParam->GetADCinRange() / simParam->GetADCoutRange());
+             // Convert to ADC counts. Set the overflow-bit fADCoutRange if the
              // signal is larger than fADCinRange
               Int_t adc  = 0;
               if (signalAmp >= simParam->GetADCinRange()) {
                 adc = ((Int_t) simParam->GetADCoutRange());
              }
               else {
-                adc = ((Int_t) (signalAmp * (simParam->GetADCoutRange() 
-                                           / simParam->GetADCinRange())));
+                adc = TMath::Nint(signalAmp * (simParam->GetADCoutRange()
+                                            / simParam->GetADCinRange()));
              }
+
               inADC[iTime]  = adc;
               outADC[iTime] = adc;
+
            }
 
             for (iTime = 0; iTime < nTimeTotal; iTime++) {   
               // Store the amplitude of the digit if above threshold
-              if (outADC[iTime] > simParam->GetADCthreshold()) {
-                if (fDebug > 2) {
-                  printf("  iRow = %d, iCol = %d, iTime = %d, adc = %f\n"
-                        ,iRow,iCol,iTime,outADC[iTime]);
-               }
+              if (outADC[iTime] > (simParam->GetADCbaseline() + simParam->GetADCthreshold())) {
                 nDigits++;
                 digits->SetDataUnchecked(iRow,iCol,iTime,((Int_t) outADC[iTime]));
              }
@@ -1216,15 +1309,16 @@ Bool_t AliTRDdigitizer::MakeDigits()
     totalSizeDict1  += dictionary[1]->GetSize();
     totalSizeDict2  += dictionary[2]->GetSize();
 
-    Float_t nPixel = nRowMax * nColMax * nTimeTotal;
-    if (fDebug > 0) {
-      printf("<AliTRDdigitizer::MakeDigits> ");
-      printf("Found %d digits in detector %d (%3.0f).\n"
-            ,nDigits,iDet
-            ,100.0 * ((Float_t) nDigits) / nPixel);
-    } 
+    if (nDigits > 0) {
+      Float_t nPixel = nRowMax * nColMax * nTimeTotal;
+      AliDebug(1,Form("Found %d digits in detector %d (%3.0f)."
+                     ,nDigits,iDet
+                     ,100.0 * ((Float_t) nDigits) / nPixel));
+    }
 
-    if (fCompress) signals->Compress(1,0);
+    if (fCompress) {
+      signals->Compress(1,0);
+    }
 
     delete [] inADC;
     delete [] outADC;
@@ -1236,15 +1330,11 @@ Bool_t AliTRDdigitizer::MakeDigits()
     signalsArray = 0;
   }
 
-  if (fDebug > 0) {
-    printf("<AliTRDdigitizer::MakeDigits> ");
-    printf("Total number of analyzed hits = %d\n",countHits);
-    printf("<AliTRDdigitizer::MakeDigits> ");
-    printf("Total digits data size = %d, %d, %d, %d\n",totalSizeDigits
-                                                      ,totalSizeDict0
-                                                      ,totalSizeDict1
-                                                      ,totalSizeDict2);        
-  }
+  AliDebug(1,Form("Total number of analyzed hits = %d",countHits));
+  AliDebug(1,Form("Total digits data size = %d, %d, %d, %d",totalSizeDigits
+                                                           ,totalSizeDict0
+                                                           ,totalSizeDict1
+                                                           ,totalSizeDict2));
 
   return kTRUE;
 
@@ -1283,43 +1373,25 @@ Bool_t AliTRDdigitizer::ConvertSDigits()
   const Int_t    kNDict = AliTRDdigitsManager::kNDict;
 
   // Converts number of electrons to fC
-  const Double_t kEl2fC = 1.602E-19 * 1.0E15; 
+  const Double_t kEl2fC = 1.602e-19 * 1.0e15; 
 
   Int_t iDict = 0;
   Int_t iRow;
   Int_t iCol;
   Int_t iTime;
 
-  if (!fPar) {    
-    fPar = new AliTRDparameter("TRDparameter","Standard parameter");
-    if (fDebug > 0) {
-      printf("<AliTRDdigitizer::ConvertSDigits> ");
-      printf("Create the default parameter object\n");
-    }
-  }
+  AliTRDCalROC *calGainFactorROC      = 0;
+  Float_t       calGainFactorDetValue = 0.0;
 
-  AliTRDSimParam* simParam = AliTRDSimParam::Instance();
-  if (!simParam)
-  {
-    printf("<AliTRDdigitizer::ConvertSDigits> ");
-    printf("Could not get simulation params\n");
-    return kFALSE;
-  }
-  
-  AliTRDCommonParam* commonParam = AliTRDCommonParam::Instance();
-  if (!commonParam)
-  {
-    printf("<AliTRDdigitizer::ConvertSDigits> ");
-    printf("Could not get common params\n");
+  AliTRDSimParam    *simParam    = AliTRDSimParam::Instance();
+  if (!simParam) {
+    AliFatal("Could not get simulation parameters");
     return kFALSE;
   }
   
-  
-  AliTRDcalibDB* calibration = AliTRDcalibDB::Instance();
-  if (!calibration)
-  {
-    printf("<AliTRDdigitizer::ConvertSDigits> ");
-    printf("Could not get calibration object\n");
+  AliTRDcalibDB     *calibration = AliTRDcalibDB::Instance();
+  if (!calibration) {
+    AliFatal("Could not get calibration object");
     return kFALSE;
   }
     
@@ -1334,27 +1406,24 @@ Bool_t AliTRDdigitizer::ConvertSDigits()
   Double_t adcOutRange  = simParam->GetADCoutRange();
   Int_t    adcThreshold = simParam->GetADCthreshold();
   Int_t    adcBaseline  = simParam->GetADCbaseline();   
+  Int_t    nTimeTotal   = calibration->GetNumberOfTimeBins();
 
   AliTRDdataArrayI *digitsIn;
   AliTRDdataArrayI *digitsOut;
   AliTRDdataArrayI *dictionaryIn[kNDict];
   AliTRDdataArrayI *dictionaryOut[kNDict];
 
-  Int_t nTimeTotal = calibration->GetNumberOfTimeBins();
+  // Get the detector wise calibration objects
+  const AliTRDCalDet *calGainFactorDet = calibration->GetGainFactorDet();  
   
   // Loop through the detectors
   for (Int_t iDet = 0; iDet < AliTRDgeometry::Ndet(); iDet++) {
 
-    if (fDebug > 0) {
-      printf("<AliTRDdigitizer::ConvertSDigits> ");
-      printf("Convert detector %d to digits.\n",iDet);
-    }
-
     Int_t plane      = fGeo->GetPlane(iDet);
     Int_t sector     = fGeo->GetSector(iDet);
     Int_t chamber    = fGeo->GetChamber(iDet);
-    Int_t nRowMax    = commonParam->GetRowMax(plane,chamber,sector);
-    Int_t nColMax    = commonParam->GetColMax(plane);
+    Int_t nRowMax    = fGeo->GetRowMax(plane,chamber,sector);
+    Int_t nColMax    = fGeo->GetColMax(plane);
 
     Double_t *inADC  = new Double_t[nTimeTotal];
     Double_t *outADC = new Double_t[nTimeTotal];
@@ -1370,47 +1439,75 @@ Bool_t AliTRDdigitizer::ConvertSDigits()
       dictionaryOut[iDict]->Allocate(nRowMax,nColMax,nTimeTotal);
     }
 
-    for (iRow  = 0; iRow  <  nRowMax;   iRow++ ) {
-      for (iCol  = 0; iCol  <  nColMax;   iCol++ ) {
-
-        for (iTime = 0; iTime < nTimeTotal; iTime++) {         
-          Double_t signal = (Double_t) digitsIn->GetDataUnchecked(iRow,iCol,iTime);
-          signal *= sDigitsScale;
-          // Pad and time coupling
-          signal *= coupling;
-          // Add the noise, starting from minus ADC baseline in electrons
-          Double_t baselineEl = adcBaseline * (adcInRange / adcOutRange) / convert;
-          signal  = TMath::Max((Double_t) gRandom->Gaus(signal,noise),-baselineEl);
-          // Convert to mV
-          signal *= convert;
-          // add ADC baseline in mV
-          signal += adcBaseline * (adcInRange / adcOutRange);
-         // Convert to ADC counts. Set the overflow-bit adcOutRange if the 
-         // signal is larger than adcInRange
-          Int_t adc  = 0;
-          if (signal >= adcInRange) {
-            adc = ((Int_t) adcOutRange);
+    // Don't create noise in detectors that are switched off / not installed, etc.
+    if (( calibration->IsChamberInstalled(iDet)) &&
+        (!calibration->IsChamberMasked(iDet))    &&
+        ( fGeo->GetSMstatus(sector))) {
+
+      // Get the calibration objects
+      calGainFactorROC      = calibration->GetGainFactorROC(iDet);
+      calGainFactorDetValue = calGainFactorDet->GetValue(iDet);
+
+      for (iRow  = 0; iRow  <  nRowMax;   iRow++ ) {
+        for (iCol  = 0; iCol  <  nColMax;   iCol++ ) {
+
+          // Check whether pad is masked
+         // Bridged pads are not considered yet!!!
+          if (calibration->IsPadMasked(iDet,iCol,iRow)) {
+            continue;
          }
-          else {
-            adc = ((Int_t) (signal * (adcOutRange / adcInRange)));
+
+          Float_t padgain = calGainFactorDetValue 
+                          * calGainFactorROC->GetValue(iCol,iRow);
+          if (padgain <= 0) {
+            AliError(Form("Not a valid gain %f, %d %d %d",padgain,iDet,iCol,iRow));
+          }
+
+          for (iTime = 0; iTime < nTimeTotal; iTime++) {
+
+           // Scale s-digits to normal digits
+            Double_t signal = (Double_t) digitsIn->GetDataUnchecked(iRow,iCol,iTime);
+            signal         *= sDigitsScale;
+            // Pad and time coupling
+            signal *= coupling;
+           // Gain factors
+            signal *= padgain;
+            // Add the noise, starting from minus ADC baseline in electrons
+            Double_t baselineEl = adcBaseline * (adcInRange / adcOutRange) / convert;
+            signal  = TMath::Max((Double_t) gRandom->Gaus(signal,noise),-baselineEl);
+            // Convert to mV
+            signal *= convert;
+            // add ADC baseline in mV
+            signal += adcBaseline * (adcInRange / adcOutRange);
+           // Convert to ADC counts. Set the overflow-bit adcOutRange if the
+           // signal is larger than adcInRange
+            Int_t adc  = 0;
+            if (signal >= adcInRange) {
+              adc = ((Int_t) adcOutRange);
+           }
+            else {
+              adc = TMath::Nint(signal * (adcOutRange / adcInRange));
+           }
+            inADC[iTime]  = adc;
+            outADC[iTime] = adc;
+
          }
-          inADC[iTime]  = adc;
-          outADC[iTime] = adc;
-       }
 
-        for (iTime = 0; iTime < nTimeTotal; iTime++) {   
-          // Store the amplitude of the digit if above threshold
-          if (outADC[iTime] > adcThreshold) {
-            digitsOut->SetDataUnchecked(iRow,iCol,iTime,((Int_t) outADC[iTime]));
-           // Copy the dictionary
-            for (iDict = 0; iDict < kNDict; iDict++) { 
-              Int_t track = dictionaryIn[iDict]->GetDataUnchecked(iRow,iCol,iTime);
-              dictionaryOut[iDict]->SetDataUnchecked(iRow,iCol,iTime,track);
+          for (iTime = 0; iTime < nTimeTotal; iTime++) {
+            // Store the amplitude of the digit if above threshold
+            if (outADC[iTime] > (adcBaseline + adcThreshold)) {
+              digitsOut->SetDataUnchecked(iRow,iCol,iTime,((Int_t) outADC[iTime]));
+             // Copy the dictionary
+              for (iDict = 0; iDict < kNDict; iDict++) { 
+                Int_t track = dictionaryIn[iDict]->GetDataUnchecked(iRow,iCol,iTime);
+                dictionaryOut[iDict]->SetDataUnchecked(iRow,iCol,iTime,track);
+             }
            }
          }
-       }
 
+        }
       }
+
     }
 
     if (fCompress) {
@@ -1444,35 +1541,15 @@ Bool_t AliTRDdigitizer::MergeSDigits()
   // Number of track dictionary arrays
   const Int_t kNDict = AliTRDdigitsManager::kNDict;
 
-  if (!fPar) {
-    fPar = new AliTRDparameter("TRDparameter","Standard parameter");
-    if (fDebug > 0) {
-      printf("<AliTRDdigitizer::MergeSDigits> ");
-      printf("Create the default parameter object\n");
-    }
-  }
-
-  AliTRDSimParam* simParam = AliTRDSimParam::Instance();
-  if (!simParam)
-  {
-    printf("<AliTRDdigitizer::MergeSDigits> ");
-    printf("Could not get simulation params\n");
-    return kFALSE;
-  }
-  
-  AliTRDCommonParam* commonParam = AliTRDCommonParam::Instance();
-  if (!commonParam)
-  {
-    printf("<AliTRDdigitizer::MergeSDigits> ");
-    printf("Could not get common params\n");
+  AliTRDSimParam    *simParam    = AliTRDSimParam::Instance();
+  if (!simParam) {
+    AliFatal("Could not get simulation parameters");
     return kFALSE;
   }
   
-  AliTRDcalibDB* calibration = AliTRDcalibDB::Instance();
-  if (!calibration)
-  {
-    printf("<AliTRDdigitizer::MergeSDigits> ");
-    printf("Could not get calibration object\n");
+  AliTRDcalibDB     *calibration = AliTRDcalibDB::Instance();
+  if (!calibration) {
+    AliFatal("Could not get calibration object");
     return kFALSE;
   }
   
@@ -1486,22 +1563,21 @@ Bool_t AliTRDdigitizer::MergeSDigits()
 
   // Get the first s-digits
   fSDigitsManager = (AliTRDdigitsManager *) fSDigitsManagerList->First();
-  if (!fSDigitsManager) return kFALSE;
+  if (!fSDigitsManager) { 
+    AliError("No SDigits manager");
+    return kFALSE;
+  }
 
   // Loop through the other sets of s-digits
   AliTRDdigitsManager *mergeSDigitsManager;
   mergeSDigitsManager = (AliTRDdigitsManager *) 
                         fSDigitsManagerList->After(fSDigitsManager);
 
-  if (fDebug > 0) {
-    if (mergeSDigitsManager) {
-      printf("<AliTRDdigitizer::MergeSDigits> ");
-      printf("Merge %d input files.\n",fSDigitsManagerList->GetSize());
-    }
-    else {
-      printf("<AliTRDdigitizer::MergeSDigits> ");
-      printf("Only one input file.\n");
-    }
+  if (mergeSDigitsManager) {
+    AliDebug(1,Form("Merge %d input files.",fSDigitsManagerList->GetSize()));
+  }
+  else {
+    AliDebug(1,"Only one input file.");
   }
 
   Int_t nTimeTotal = calibration->GetNumberOfTimeBins();
@@ -1514,11 +1590,11 @@ Bool_t AliTRDdigitizer::MergeSDigits()
     // Loop through the detectors
     for (Int_t iDet = 0; iDet < AliTRDgeometry::Ndet(); iDet++) {
 
-      Int_t plane      = fGeo->GetPlane(iDet);
-      Int_t sector     = fGeo->GetSector(iDet);
-      Int_t chamber    = fGeo->GetChamber(iDet);
-      Int_t nRowMax    = commonParam->GetRowMax(plane,chamber,sector);
-      Int_t nColMax    = commonParam->GetColMax(plane);
+      Int_t plane   = fGeo->GetPlane(iDet);
+      Int_t sector  = fGeo->GetSector(iDet);
+      Int_t chamber = fGeo->GetChamber(iDet);
+      Int_t nRowMax = fGeo->GetRowMax(plane,chamber,sector);
+      Int_t nColMax = fGeo->GetColMax(plane);
 
       // Loop through the pixels of one detector and add the signals
       digitsA = fSDigitsManager->GetDigits(iDet);
@@ -1542,10 +1618,7 @@ Bool_t AliTRDdigitizer::MergeSDigits()
 
       if (doMerge) {
 
-        if (fDebug > 0) {
-          printf("<AliTRDdigitizer::MergeSDigits> ");
-          printf("Merge detector %d of input no.%d\n",iDet,iMerge+1);
-        }
+        AliDebug(1,Form("Merge detector %d of input no.%d",iDet,iMerge+1));
 
         for (Int_t iRow  = 0; iRow  <  nRowMax;   iRow++ ) {
           for (Int_t iCol  = 0; iCol  <  nColMax;   iCol++ ) {
@@ -1557,7 +1630,7 @@ Bool_t AliTRDdigitizer::MergeSDigits()
               ampA += ampB;
               digitsA->SetDataUnchecked(iRow,iCol,iTime,ampA);
 
-            // Add the mask to the track id if defined.
+             // Add the mask to the track id if defined.
               for (iDict = 0; iDict < kNDict; iDict++) {
                 Int_t trackB = dictionaryB[iDict]->GetDataUnchecked(iRow,iCol,iTime);
                 if ((fMasks) && (trackB > 0)) {
@@ -1605,37 +1678,11 @@ Bool_t AliTRDdigitizer::SDigits2Digits()
   // Merges the input s-digits and converts them to normal digits
   //
 
-  if (!MergeSDigits()) return kFALSE;
-
-  return ConvertSDigits();
-
-}
-
-//_____________________________________________________________________________
-Bool_t AliTRDdigitizer::CheckDetector(Int_t plane, Int_t chamber, Int_t sector)
-{
-  //
-  // Checks whether a detector is enabled
-  //
-
-  if ((fTRD->GetSensChamber() >=       0) &&
-      (fTRD->GetSensChamber() != chamber)) return kFALSE;
-  if ((fTRD->GetSensPlane()   >=       0) &&
-      (fTRD->GetSensPlane()   !=   plane)) return kFALSE;
-  if ( fTRD->GetSensSector()  >=       0) {
-    Int_t sens1 = fTRD->GetSensSector();
-    Int_t sens2 = sens1 + fTRD->GetSensSectorRange();
-    sens2 -= ((Int_t) (sens2 / AliTRDgeometry::Nsect())) 
-           * AliTRDgeometry::Nsect();
-    if (sens1 < sens2) {
-      if ((sector < sens1) || (sector >= sens2)) return kFALSE;
-    }
-    else {
-      if ((sector < sens1) && (sector >= sens2)) return kFALSE;
-    }
+  if (!MergeSDigits()) {
+    return kFALSE;
   }
 
-  return kTRUE;
+  return ConvertSDigits();
 
 }
 
@@ -1646,9 +1693,8 @@ Bool_t AliTRDdigitizer::WriteDigits() const
   // Writes out the TRD-digits and the dictionaries
   //
 
-  //Write parameters
+  // Write parameters
   fRunLoader->CdGAFile();
-  if (!gFile->Get("TRDparameter")) GetParameter()->Write();
 
   // Store the digits and the dictionary in the tree
   return fDigitsManager->WriteDigits();
@@ -1664,39 +1710,36 @@ void AliTRDdigitizer::InitOutput(Int_t iEvent)
 
   fEvent = iEvent;
    
-  if (!fRunLoader)
-   {
-     Error("InitOutput","Run Loader is NULL");
-     return;  
-   }
-  AliLoader* loader = fRunLoader->GetLoader("TRDLoader");
-  if (!loader)
-   {
-     Error("Open","Can not get TRD loader from Run Loader");
-     return;
-   }
-
-  TTree* tree = 0;
+  if (!fRunLoader) {
+    AliError("Run Loader is NULL");
+    return;  
+  }
+
+  AliLoader *loader = fRunLoader->GetLoader("TRDLoader");
+  if (!loader) {
+    AliError("Can not get TRD loader from Run Loader");
+    return;
+  }
+
+  TTree *tree = 0;
   
-  if (fSDigits)
-   { 
-   //if we produce SDigits
+  if (fSDigits) { 
+    // If we produce SDigits
     tree = loader->TreeS();
-    if (!tree)
-     {
+    if (!tree) {
       loader->MakeTree("S");
       tree = loader->TreeS();
-     }
-   }
-  else
-   {//if we produce Digits
-     tree = loader->TreeD();
-     if (!tree)
-      {
-       loader->MakeTree("D");
-       tree = loader->TreeD();
-      }
-   }
+    }
+  }
+  else {
+    // If we produce Digits
+    tree = loader->TreeD();
+    if (!tree) {
+      loader->MakeTree("D");
+      tree = loader->TreeD();
+    }
+  }
+
   fDigitsManager->SetEvent(iEvent);
   fDigitsManager->MakeBranch(tree);
 
@@ -1725,54 +1768,70 @@ Double_t AliTRDdigitizer::TimeStruct(Float_t vdrift, Double_t dist, Double_t z)
 
   SampleTimeStruct(vdrift);
   
-  // indices:
-  Int_t r1 = (Int_t)(10*dist);
-  Int_t r2 = r1+1;
-  if (r1<0)  r1 = 0;
-  if (r1>37) r1 = 37;
-  const Int_t kz1 = (Int_t)(100*z/2.5);
-  const Int_t kz2 = kz1+1;
-
-  if (r1<0 || r1>37 || kz1<0 || kz1>10) {
-    printf("<AliTRDparameter::TimeStruct> Warning. Indices out of range: ");
-    printf("dist=%.2f, z=%.2f, r1=%d, kz1=%d\n",dist,z,r1,kz1);
+  // Indices:
+  Int_t r1 = (Int_t)(10 * dist);
+  if (r1 <  0) r1 =  0;
+  if (r1 > 37) r1 = 37;
+  Int_t r2 = r1 + 1;
+  if (r2 <  0) r2 =  0;
+  if (r2 > 37) r2 = 37;
+  const Int_t kz1 = ((Int_t)(100 * z / 2.5));
+  const Int_t kz2 = kz1 + 1;
+
+  if ((r1  <  0) || 
+      (r1  > 37) || 
+      (kz1 <  0) || 
+      (kz1 > 10)) {
+    AliWarning(Form("Indices out of range: dist=%.2f, z=%.2f, r1=%d, kz1=%d"
+                   ,dist,z,r1,kz1));
   }
 
-  const Float_t ky111 = fTimeStructInfo.fTimeStruct1[r1+38*kz1];
-  const Float_t ky221 = (r2 <= 37 && kz2 <= 10) ? fTimeStructInfo.fTimeStruct1[r2+38*kz2] : fTimeStructInfo.fTimeStruct1[37+38*10];
-  const Float_t ky121 = (kz2 <= 10)             ? fTimeStructInfo.fTimeStruct1[r1+38*kz2] : fTimeStructInfo.fTimeStruct1[r1+38*10];
-  const Float_t ky211 = (r2 <= 37)             ? fTimeStructInfo.fTimeStruct1[r2+38*kz1] : fTimeStructInfo.fTimeStruct1[37+38*kz1];
+  const Float_t ky111 = fTimeStruct1[r1+38*kz1];
+  const Float_t ky221 = ((r2 <= 37) && (kz2 <= 10)) 
+                      ? fTimeStruct1[r2+38*kz2] 
+                      : fTimeStruct1[37+38*10];
+  const Float_t ky121 = (kz2 <= 10)             
+                      ? fTimeStruct1[r1+38*kz2] 
+                      : fTimeStruct1[r1+38*10];
+  const Float_t ky211 = (r2 <= 37)              
+                      ? fTimeStruct1[r2+38*kz1] 
+                      : fTimeStruct1[37+38*kz1];
 
   // 2D Interpolation, lower drift time map
   const Float_t ky11  = (ky211-ky111)*10*dist + ky111 - (ky211-ky111)*r1;
   const Float_t ky21  = (ky221-ky121)*10*dist + ky121 - (ky221-ky121)*r1;
 
-  const Float_t ky112 = fTimeStructInfo.fTimeStruct2[r1+38*kz1];
-  const Float_t ky222 = (r2 <= 37 && kz2 <= 10) ? fTimeStructInfo.fTimeStruct2[r2+38*kz2] : fTimeStructInfo.fTimeStruct2[37+38*10];
-  const Float_t ky122 = (kz2 <= 10)             ? fTimeStructInfo.fTimeStruct2[r1+38*kz2] : fTimeStructInfo.fTimeStruct2[r1+38*10];
-  const Float_t ky212 = (r2 <= 37)             ? fTimeStructInfo.fTimeStruct2[r2+38*kz1] : fTimeStructInfo.fTimeStruct2[37+38*kz1];
+  const Float_t ky112 = fTimeStruct2[r1+38*kz1];
+  const Float_t ky222 = ((r2 <= 37) && (kz2 <= 10)) 
+                      ? fTimeStruct2[r2+38*kz2] 
+                      : fTimeStruct2[37+38*10];
+  const Float_t ky122 = (kz2 <= 10)             
+                      ? fTimeStruct2[r1+38*kz2] 
+                      : fTimeStruct2[r1+38*10];
+  const Float_t ky212 = (r2 <= 37)              
+                      ? fTimeStruct2[r2+38*kz1] 
+                      : fTimeStruct2[37+38*kz1];
 
   // 2D Interpolation, larger drift time map
   const Float_t ky12  = (ky212-ky112)*10*dist + ky112 - (ky212-ky112)*r1;
   const Float_t ky22  = (ky222-ky122)*10*dist + ky122 - (ky222-ky122)*r1;
 
-  // dist now is the drift distance to the anode wires (negative if electrons are
+  // Dist now is the drift distance to the anode wires (negative if electrons are
   // between anode wire plane and cathode pad plane)
-  dist -= AliTRDgeometry::AmThick()/2.0;
+  dist -= AliTRDgeometry::AmThick() / 2.0;
 
   // Get the drift times for the drift velocities fVDlo and fVDhi
-  const Float_t ktdrift1 =
-      ( TMath::Abs(dist)>0.005 || z>0.005 ) ? (ky21-ky11)*100*z/2.5+ky11-(ky21-ky11)*kz1 : 0.0;
-  const Float_t ktdrift2 =
-      ( TMath::Abs(dist)>0.005 || z>0.005 ) ? (ky22-ky12)*100*z/2.5+ky12-(ky22-ky12)*kz1 : 0.0;
+  const Float_t ktdrift1 = ((TMath::Abs(dist) > 0.005) || (z > 0.005)) 
+                         ? (ky21 - ky11) * 100 * z / 2.5 + ky11 - (ky21 - ky11) * kz1 
+                         : 0.0;
+  const Float_t ktdrift2 = ((TMath::Abs(dist) > 0.005) || (z > 0.005)) 
+                         ? (ky22 - ky12) * 100 * z / 2.5 + ky12 - (ky22 - ky12) * kz1 
+                         : 0.0;
 
   // 1D Interpolation between the values at fVDlo and fVDhi
-  Float_t a = (ktdrift2 - ktdrift1) / (fTimeStructInfo.fVDhi - fTimeStructInfo.fVDlo);
-  Float_t b = ktdrift2 - a * fTimeStructInfo.fVDhi;
-
-
-  //printf("(%.2f, %.2f): %f, %f -> %f\n",
-  //     dist+AliTRDgeometry::AmThick()/2.0, z, ktdrift1, ktdrift2, a*fDriftVelocity+b);
+  Float_t a = (ktdrift2 - ktdrift1) 
+            / (fVDhi - fVDlo);
+  Float_t b = ktdrift2 - a * fVDhi;
 
   return a * vdrift + b;
 
@@ -1786,14 +1845,13 @@ void AliTRDdigitizer::SampleTimeStruct(Float_t vdrift)
   // Drift Time data calculated with Garfield (by C.Lippmann)
   //
   
-  //TODO make caching proper, if same timing structure is selected: do not update timestructs!
-  
-  if (vdrift == fTimeStructInfo.fLastVdrift)
+  // Nothing to do
+  if (vdrift == fTimeLastVdrift) {
     return;
-
-  fTimeStructInfo.fLastVdrift = vdrift;
+  }
+  fTimeLastVdrift = vdrift;
   
-  // drift time maps are saved for some drift velocity values (in drift region):
+  // Drift time maps are saved for some drift velocity values (in drift region):
   Float_t  fVDsmp[8];
   fVDsmp[0] = 1.032;
   fVDsmp[1] = 1.158;
@@ -1804,22 +1862,17 @@ void AliTRDdigitizer::SampleTimeStruct(Float_t vdrift)
   fVDsmp[6] = 1.959;
   fVDsmp[7] = 2.134;
 
-  if ( vdrift < fVDsmp[0] ) {
-    printf("<AliTRDparameter::SampleTimeStruct> !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
-    printf("<AliTRDparameter::SampleTimeStruct> Drift Velocity too small (%.3f<%.3f)\n"
-          , vdrift, fVDsmp[0]);
-    printf("<AliTRDparameter::SampleTimeStruct> !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
+  if      (vdrift < fVDsmp[0]) {
+    AliWarning(Form("Drift Velocity too small (%.3f<%.3f)",vdrift,fVDsmp[0]));
     vdrift = fVDsmp[0];
-  } else if ( vdrift > fVDsmp[7] ) {
-    printf("<AliTRDparameter::SampleTimeStruct> !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
-    printf("<AliTRDparameter::SampleTimeStruct> Drift Velocity too large (%.3f>%.3f)\n"
-          , vdrift,fVDsmp[6]);
-    printf("<AliTRDparameter::SampleTimeStruct> !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
+  } 
+  else if (vdrift > fVDsmp[7]) {
+    AliWarning(Form("Drift Velocity too large (%.3f>%.3f)",vdrift,fVDsmp[6]));
     vdrift = fVDsmp[7];
   }
 
   const Int_t ktimebin  = 38;
-  const Int_t kZbin = 11;
+  const Int_t kZbin     = 11;
 
   // Garfield simulation at UD = -1500V; vd = 1.032cm/microsec, <driftfield> = 525V/cm
   Float_t time1500[ktimebin][kZbin] =
@@ -2453,143 +2506,148 @@ void AliTRDdigitizer::SampleTimeStruct(Float_t vdrift)
        {1.48122, 1.48219, 1.48482, 1.48991, 1.50030, 1.53991,
         1.52898, 1.52653, 1.53653, 1.57282, 1.82386}};
 
-  if (fTimeStructInfo.fTimeStruct1)  delete [] fTimeStructInfo.fTimeStruct1;
-  fTimeStructInfo.fTimeStruct1  = new Float_t[ktimebin*kZbin];
-
-  if (fTimeStructInfo.fTimeStruct2)  delete [] fTimeStructInfo.fTimeStruct2;
-  fTimeStructInfo.fTimeStruct2  = new Float_t[ktimebin*kZbin];
-
-  for (Int_t ctrt = 0; ctrt<ktimebin; ctrt++) {
-    for (Int_t ctrz = 0; ctrz<kZbin; ctrz++) {
-      if ( vdrift > fVDsmp[6] ) {
-        fTimeStructInfo.fTimeStruct1[ctrt+ctrz*ktimebin] = time2100[ctrt][ctrz];
-        fTimeStructInfo.fTimeStruct2[ctrt+ctrz*ktimebin] = time2200[ctrt][ctrz];            
-        fTimeStructInfo.fVDlo = fVDsmp[6];
-        fTimeStructInfo.fVDhi = fVDsmp[7];
-      } else if ( vdrift > fVDsmp[5] ) {
-        fTimeStructInfo.fTimeStruct1[ctrt+ctrz*ktimebin] = time2000[ctrt][ctrz];
-        fTimeStructInfo.fTimeStruct2[ctrt+ctrz*ktimebin] = time2100[ctrt][ctrz];            
-        fTimeStructInfo.fVDlo = fVDsmp[5];
-        fTimeStructInfo.fVDhi = fVDsmp[6];
-      } else if ( vdrift > fVDsmp[4] ) {
-        fTimeStructInfo.fTimeStruct1[ctrt+ctrz*ktimebin] = time1900[ctrt][ctrz];
-        fTimeStructInfo.fTimeStruct2[ctrt+ctrz*ktimebin] = time2000[ctrt][ctrz];            
-        fTimeStructInfo.fVDlo = fVDsmp[4];
-        fTimeStructInfo.fVDhi = fVDsmp[5];
-      } else if ( vdrift > fVDsmp[3] ) {
-        fTimeStructInfo.fTimeStruct1[ctrt+ctrz*ktimebin] = time1800[ctrt][ctrz];
-        fTimeStructInfo.fTimeStruct2[ctrt+ctrz*ktimebin] = time1900[ctrt][ctrz];            
-        fTimeStructInfo.fVDlo = fVDsmp[3];
-        fTimeStructInfo.fVDhi = fVDsmp[4];
-      } else if ( vdrift > fVDsmp[2] ) {
-        fTimeStructInfo.fTimeStruct1[ctrt+ctrz*ktimebin] = time1700[ctrt][ctrz];
-        fTimeStructInfo.fTimeStruct2[ctrt+ctrz*ktimebin] = time1800[ctrt][ctrz];            
-        fTimeStructInfo.fVDlo = fVDsmp[2];
-        fTimeStructInfo.fVDhi = fVDsmp[3];
-      } else if ( vdrift > fVDsmp[1] ) {
-        fTimeStructInfo.fTimeStruct1[ctrt+ctrz*ktimebin] = time1600[ctrt][ctrz];
-        fTimeStructInfo.fTimeStruct2[ctrt+ctrz*ktimebin] = time1700[ctrt][ctrz];            
-        fTimeStructInfo.fVDlo = fVDsmp[1];
-        fTimeStructInfo.fVDhi = fVDsmp[2];
-      } else if ( vdrift > (fVDsmp[0] - 1.e-5) ) {
-        fTimeStructInfo.fTimeStruct1[ctrt+ctrz*ktimebin] = time1500[ctrt][ctrz];
-        fTimeStructInfo.fTimeStruct2[ctrt+ctrz*ktimebin] = time1600[ctrt][ctrz];            
-        fTimeStructInfo.fVDlo = fVDsmp[0];
-        fTimeStructInfo.fVDhi = fVDsmp[1];
+  if (fTimeStruct1) {
+    delete [] fTimeStruct1;
+  }
+  fTimeStruct1 = new Float_t[ktimebin*kZbin];
+
+  if (fTimeStruct2) {
+    delete [] fTimeStruct2;
+  }
+  fTimeStruct2 = new Float_t[ktimebin*kZbin];
+
+  for (Int_t ctrt = 0; ctrt < ktimebin; ctrt++) {
+    for (Int_t ctrz = 0; ctrz <    kZbin; ctrz++) {
+      if      (vdrift > fVDsmp[6]) {
+        fTimeStruct1[ctrt+ctrz*ktimebin] = time2100[ctrt][ctrz];
+        fTimeStruct2[ctrt+ctrz*ktimebin] = time2200[ctrt][ctrz];            
+        fVDlo = fVDsmp[6];
+        fVDhi = fVDsmp[7];
+      } 
+      else if (vdrift > fVDsmp[5]) {
+        fTimeStruct1[ctrt+ctrz*ktimebin] = time2000[ctrt][ctrz];
+        fTimeStruct2[ctrt+ctrz*ktimebin] = time2100[ctrt][ctrz];            
+        fVDlo = fVDsmp[5];
+        fVDhi = fVDsmp[6];
+      } 
+      else if (vdrift > fVDsmp[4]) {
+        fTimeStruct1[ctrt+ctrz*ktimebin] = time1900[ctrt][ctrz];
+        fTimeStruct2[ctrt+ctrz*ktimebin] = time2000[ctrt][ctrz];            
+        fVDlo = fVDsmp[4];
+        fVDhi = fVDsmp[5];
+      } 
+      else if (vdrift > fVDsmp[3]) {
+        fTimeStruct1[ctrt+ctrz*ktimebin] = time1800[ctrt][ctrz];
+        fTimeStruct2[ctrt+ctrz*ktimebin] = time1900[ctrt][ctrz];            
+        fVDlo = fVDsmp[3];
+        fVDhi = fVDsmp[4];
+      } 
+      else if (vdrift > fVDsmp[2]) {
+        fTimeStruct1[ctrt+ctrz*ktimebin] = time1700[ctrt][ctrz];
+        fTimeStruct2[ctrt+ctrz*ktimebin] = time1800[ctrt][ctrz];            
+        fVDlo = fVDsmp[2];
+        fVDhi = fVDsmp[3];
+      } 
+      else if (vdrift > fVDsmp[1]) {
+        fTimeStruct1[ctrt+ctrz*ktimebin] = time1600[ctrt][ctrz];
+        fTimeStruct2[ctrt+ctrz*ktimebin] = time1700[ctrt][ctrz];            
+        fVDlo = fVDsmp[1];
+        fVDhi = fVDsmp[2];
+      } 
+      else if (vdrift > (fVDsmp[0] - 1.0e-5)) {
+        fTimeStruct1[ctrt+ctrz*ktimebin] = time1500[ctrt][ctrz];
+        fTimeStruct2[ctrt+ctrz*ktimebin] = time1600[ctrt][ctrz];            
+        fVDlo = fVDsmp[0];
+        fVDhi = fVDsmp[1];
       }
     }
   }
+
 }
 
 //_____________________________________________________________________________
 void AliTRDdigitizer::RecalcDiffusion(Float_t vdrift)
 {
-  if (vdrift == fDiffusionInfo.fLastVdrift)
+  //
+  // Recalculates the diffusion parameters
+  //
+  // The B=0 case is not really included here.
+  // Should be revisited!
+  //
+
+  if (vdrift == fDiffLastVdrift) {
     return;
-  
-  if (!fPar) {
-    fPar = new AliTRDparameter("TRDparameter","Standard TRD parameter");
-    if (fDebug > 0) {
-      printf("<AliTRDdigitizer::RecalcDiffusion> ");
-      printf("Create the default parameter object\n");
-    }
   }
-  
-  AliTRDSimParam* simParam = AliTRDSimParam::Instance();
-  if (!simParam)
-  {
-    printf("<AliTRDdigitizer::RecalcDiffusion> ");
-    printf("Could not get simulation params\n");
+
+  AliTRDSimParam    *simParam    = AliTRDSimParam::Instance();
+  if (!simParam) {
+    AliFatal("Could not get simulation parameters");
     return;
   }
   
-  AliTRDCommonParam* commonParam = AliTRDCommonParam::Instance();
-  if (!commonParam)
-  {
-    printf("<AliTRDdigitizer::RecalcDiffusion> ");
-    printf("Could not get common params\n");
+  AliTRDCommonParam *commonParam = AliTRDCommonParam::Instance();
+  if (!commonParam) {
+    AliFatal("Could not get common parameters");
     return;
   }
   
-  AliTRDcalibDB* calibration = AliTRDcalibDB::Instance();
-  if (!calibration)
-  {
-    printf("<AliTRDdigitizer::RecalcDiffusion> ");
-    printf("Could not get calibration object\n");
+  AliTRDcalibDB     *calibration = AliTRDcalibDB::Instance();
+  if (!calibration) {
+    AliFatal("Could not get calibration object");
     return;
   }
   
-  Float_t field = commonParam->GetField();
-  fDiffusionInfo.fLastVdrift = vdrift;
-  
-  //DiffusionL
-  {
-    const Int_t kNb = 5;
-    Float_t p0[kNb] = {  0.007440,  0.007493,  0.007513,  0.007672,  0.007831 };
-    Float_t p1[kNb] = {  0.019252,  0.018912,  0.018636,  0.018012,  0.017343 };
-    Float_t p2[kNb] = { -0.005042, -0.004926, -0.004867, -0.004650, -0.004424 };
-    Float_t p3[kNb] = {  0.000195,  0.000189,  0.000195,  0.000182,  0.000169 };
-
-    Int_t ib = ((Int_t) (10 * (field - 0.15)));
-    ib       = TMath::Max(  0,ib);
-    ib       = TMath::Min(kNb,ib);
-
-    fDiffusionInfo.fDiffusionL = p0[ib] 
-        + p1[ib] * vdrift
-        + p2[ib] * vdrift*vdrift
-        + p3[ib] * vdrift*vdrift*vdrift;
-  }
-  
-  //DiffusionT
-  {
-    const Int_t kNb = 5;
-    Float_t p0[kNb] = {  0.009550,  0.009599,  0.009674,  0.009757,  0.009850 };
-    Float_t p1[kNb] = {  0.006667,  0.006539,  0.006359,  0.006153,  0.005925 };
-    Float_t p2[kNb] = { -0.000853, -0.000798, -0.000721, -0.000635, -0.000541 };
-    Float_t p3[kNb] = {  0.000131,  0.000122,  0.000111,  0.000098,  0.000085 };
-
-    Int_t ib = ((Int_t) (10 * (field - 0.15)));
-    ib       = TMath::Max(  0,ib);
-    ib       = TMath::Min(kNb,ib);
-
-    fDiffusionInfo.fDiffusionT = p0[ib] 
-        + p1[ib] * vdrift
-        + p2[ib] * vdrift*vdrift
-        + p3[ib] * vdrift*vdrift*vdrift;
-  }    
+  // The magnetic field strength
+  Double_t x[3] = { 0.0, 0.0, 0.0 };
+  Double_t b[3];        
+  gAlice->Field(x,b);         // b[] is in kilo Gauss   
+  Float_t field = b[2] * 0.1; // Tesla
 
-  //OmegaTau
-  fDiffusionInfo.fOmegaTau = calibration->GetOmegaTau(vdrift);
+  fDiffLastVdrift = vdrift;
   
-  //Lorentzfactor
-  {
-    if (commonParam->ExBOn()) {
-      fDiffusionInfo.fLorentzFactor = 1.0 / (1.0 + fDiffusionInfo.fOmegaTau*fDiffusionInfo.fOmegaTau);
-    }
-    else {
-      fDiffusionInfo.fLorentzFactor = 1.0;
-    }
+  // DiffusionL
+  const Int_t kNbL = 5;
+  Float_t p0L[kNbL] = {  0.007440,  0.007493,  0.007513,  0.007672,  0.007831 };
+  Float_t p1L[kNbL] = {  0.019252,  0.018912,  0.018636,  0.018012,  0.017343 };
+  Float_t p2L[kNbL] = { -0.005042, -0.004926, -0.004867, -0.004650, -0.004424 };
+  Float_t p3L[kNbL] = {  0.000195,  0.000189,  0.000195,  0.000182,  0.000169 };
+
+  Int_t ibL = ((Int_t) (10 * (field - 0.15)));
+  ibL       = TMath::Max(   0,ibL);
+  ibL       = TMath::Min(kNbL,ibL);
+
+  fDiffusionL = p0L[ibL] 
+              + p1L[ibL] * vdrift
+              + p2L[ibL] * vdrift*vdrift
+              + p3L[ibL] * vdrift*vdrift*vdrift;
+  
+  // DiffusionT
+  const Int_t kNbT = 5;
+  Float_t p0T[kNbT] = {  0.009550,  0.009599,  0.009674,  0.009757,  0.009850 };
+  Float_t p1T[kNbT] = {  0.006667,  0.006539,  0.006359,  0.006153,  0.005925 };
+  Float_t p2T[kNbT] = { -0.000853, -0.000798, -0.000721, -0.000635, -0.000541 };
+  Float_t p3T[kNbT] = {  0.000131,  0.000122,  0.000111,  0.000098,  0.000085 };
+
+  Int_t ibT= ((Int_t) (10 * (field - 0.15)));
+  ibT      = TMath::Max(   0,ibT);
+  ibT      = TMath::Min(kNbT,ibT);
+
+  fDiffusionT = p0T[ibT] 
+              + p1T[ibT] * vdrift
+              + p2T[ibT] * vdrift*vdrift
+              + p3T[ibT] * vdrift*vdrift*vdrift;
+
+  // OmegaTau
+  fOmegaTau = calibration->GetOmegaTau(vdrift,field);
+
+  // Lorentzfactor
+  if (commonParam->ExBOn()) {
+    fLorentzFactor = 1.0 / (1.0 + fOmegaTau*fOmegaTau);
+  }
+  else {
+    fLorentzFactor = 1.0;
   }
+
 }
   
 //_____________________________________________________________________________
@@ -2602,7 +2660,9 @@ Float_t AliTRDdigitizer::GetDiffusionL(Float_t vdrift)
   //
 
   RecalcDiffusion(vdrift);
-  return fDiffusionInfo.fDiffusionL;
+
+  return fDiffusionL;
+
 }
 
 //_____________________________________________________________________________
@@ -2615,47 +2675,58 @@ Float_t AliTRDdigitizer::GetDiffusionT(Float_t vdrift)
   //
 
   RecalcDiffusion(vdrift);
-  return fDiffusionInfo.fDiffusionT;
+
+  return fDiffusionT;
+
 }
 
 //_____________________________________________________________________________
-Int_t AliTRDdigitizer::Diffusion(Float_t vdrift, Double_t driftlength, Double_t *xyz)
+Int_t AliTRDdigitizer::Diffusion(Float_t vdrift, Double_t absdriftlength
+                               , Double_t &lRow, Double_t &lCol, Double_t &lTime)
 {
   //
-  // Applies the diffusion smearing to the position of a single electron
+  // Applies the diffusion smearing to the position of a single electron.
+  // Depends on absolute drift length.
   //
   
   RecalcDiffusion(vdrift);
 
-  Float_t driftSqrt = TMath::Sqrt(driftlength);
-  Float_t sigmaT = driftSqrt * fDiffusionInfo.fDiffusionT;
-  Float_t sigmaL = driftSqrt * fDiffusionInfo.fDiffusionL;
-  xyz[0] = gRandom->Gaus(xyz[0], sigmaL * GetLorentzFactor(vdrift));
-  xyz[1] = gRandom->Gaus(xyz[1], sigmaT * GetLorentzFactor(vdrift));
-  xyz[2] = gRandom->Gaus(xyz[2], sigmaT);
+  Float_t driftSqrt = TMath::Sqrt(absdriftlength);
+  Float_t sigmaT    = driftSqrt * fDiffusionT;
+  Float_t sigmaL    = driftSqrt * fDiffusionL;
+  lRow  = gRandom->Gaus(lRow ,sigmaT);
+  lCol  = gRandom->Gaus(lCol ,sigmaT * GetLorentzFactor(vdrift));
+  lTime = gRandom->Gaus(lTime,sigmaL * GetLorentzFactor(vdrift));
 
   return 1;
+
 }
 
 //_____________________________________________________________________________
 Float_t AliTRDdigitizer::GetLorentzFactor(Float_t vd)
 {
+  //
+  // Returns the recalculated Lorentz factor
+  //
+
   RecalcDiffusion(vd);
-  return fDiffusionInfo.fLorentzFactor;
+
+  return fLorentzFactor;
+
 }
   
 //_____________________________________________________________________________
-Int_t AliTRDdigitizer::ExB(Float_t vdrift, Double_t driftlength, Double_t *xyz)
+Int_t AliTRDdigitizer::ExB(Float_t vdrift, Double_t driftlength, Double_t &lCol)
 {
   //
-  // Applies E x B effects to the position of a single electron
+  // Applies E x B effects to the position of a single electron.
+  // Depends on signed drift length.
   //
   
   RecalcDiffusion(vdrift);
-  
-  xyz[0] = xyz[0];
-  xyz[1] = xyz[1] + fDiffusionInfo.fOmegaTau * driftlength;
-  xyz[2] = xyz[2];
+
+  lCol = lCol + fOmegaTau * driftlength;
 
   return 1;
+
 }