]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - TRD/AliTRDdigitizer.cxx
Restored compilation with CMake. The administrators of the modules have to mantain...
[u/mrichter/AliRoot.git] / TRD / AliTRDdigitizer.cxx
index 1bfa27f8724d7a8c05c9ba3918655686f0ed5983..dd75f254b69955c6b740c499e782f839aaf664c4 100644 (file)
  * provided "as is" without express or implied warranty.                  *
  **************************************************************************/
 
-/*
-$Log$
-Revision 1.17  2000/12/08 12:53:27  cblume
-Change in Copy() function for HP-compiler
-
-Revision 1.16  2000/12/07 12:20:46  cblume
-Go back to array compression. Use sampled PRF to speed up digitization
-
-Revision 1.15  2000/11/23 14:34:08  cblume
-Fixed bug in expansion routine of arrays (initialize buffers properly)
-
-Revision 1.14  2000/11/20 08:54:44  cblume
-Switch off compression as default
-
-Revision 1.13  2000/11/10 14:57:52  cblume
-Changes in the geometry constants for the DEC compiler
-
-Revision 1.12  2000/11/01 14:53:20  cblume
-Merge with TRD-develop
-
-Revision 1.1.4.9  2000/10/26 17:00:22  cblume
-Fixed bug in CheckDetector()
-
-Revision 1.1.4.8  2000/10/23 13:41:35  cblume
-Added protection against Log(0) in the gas gain calulation
-
-Revision 1.1.4.7  2000/10/17 02:27:34  cblume
-Get rid of global constants
-
-Revision 1.1.4.6  2000/10/16 01:16:53  cblume
-Changed timebin 0 to be the one closest to the readout
-
-Revision 1.1.4.5  2000/10/15 23:34:29  cblume
-Faster version of the digitizer
-
-Revision 1.1.4.4  2000/10/06 16:49:46  cblume
-Made Getters const
-
-Revision 1.1.4.3  2000/10/04 16:34:58  cblume
-Replace include files by forward declarations
-
-Revision 1.1.4.2  2000/09/22 14:41:10  cblume
-Bug fix in PRF. Included time response. New structure
-
-Revision 1.10  2000/10/05 07:27:53  cblume
-Changes in the header-files by FCA
-
-Revision 1.9  2000/10/02 21:28:19  fca
-Removal of useless dependecies via forward declarations
-
-Revision 1.8  2000/06/09 11:10:07  cblume
-Compiler warnings and coding conventions, next round
-
-Revision 1.7  2000/06/08 18:32:58  cblume
-Make code compliant to coding conventions
-
-Revision 1.6  2000/06/07 16:27:32  cblume
-Try to remove compiler warnings on Sun and HP
-
-Revision 1.5  2000/05/09 16:38:57  cblume
-Removed PadResponse(). Merge problem
-
-Revision 1.4  2000/05/08 15:53:45  cblume
-Resolved merge conflict
-
-Revision 1.3  2000/04/28 14:49:27  cblume
-Only one declaration of iDict in MakeDigits()
-
-Revision 1.1.4.1  2000/05/08 14:42:04  cblume
-Introduced AliTRDdigitsManager
-
-Revision 1.1  2000/02/28 19:00:13  cblume
-Add new TRD classes
-
-*/
-
-///////////////////////////////////////////////////////////////////////////////
-//                                                                           //
-//  Creates and handles digits from TRD hits                                 //
-//                                                                           //
-//  The following effects are included:                                      //
-//      - Diffusion                                                          //
-//      - ExB effects                                                        //
-//      - Gas gain including fluctuations                                    //
-//      - Pad-response (simple Gaussian approximation)                       //
-//      - Electronics noise                                                  //
-//      - Electronics gain                                                   //
-//      - Digitization                                                       //
-//      - ADC threshold                                                      //
-//  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).                                     //
-//  To produce digits from a root-file with TRD-hits use the                 //
-//  slowDigitsCreate.C macro.                                                //
-//                                                                           //
-///////////////////////////////////////////////////////////////////////////////
-
-#include <stdlib.h>
+/* $Id$ */
+
+////////////////////////////////////////////////////////////////////////////
+//                                                                        //
+//  Creates and handles digits from TRD hits                              //
+//                                                                        //
+//  Authors: C. Blume (blume@ikf.uni-frankfurt.de)                        //
+//           C. Lippmann                                                  //
+//           B. Vulpescu                                                  //
+//                                                                        //
+//  The following effects are included:                                   //
+//      - Diffusion                                                       //
+//      - ExB effects                                                     //
+//      - Gas gain including fluctuations                                 //
+//      - Pad-response (simple Gaussian approximation)                    //
+//      - Time-response                                                   //
+//      - Electronics noise                                               //
+//      - Electronics gain                                                //
+//      - Digitization                                                    //
+//      - Zero suppression                                                //
+//                                                                        //
+////////////////////////////////////////////////////////////////////////////
 
+#include <TF1.h>
+#include <TFile.h>
+#include <TGeoGlobalMagField.h>
+#include <TGeoManager.h>
+#include <TList.h>
 #include <TMath.h>
-#include <TVector.h>
-#include <TRandom.h>
 #include <TROOT.h>
+#include <TRandom.h>
+#include <TTask.h>
 #include <TTree.h>
-#include <TFile.h>
-#include <TF1.h>
+#include <TVector.h>
 
 #include "AliRun.h"
-
+#include "AliMC.h"
+#include "AliRunLoader.h"
+#include "AliLoader.h"
+#include "AliConfig.h"
+#include "AliMagF.h"
+#include "AliRunDigitizer.h"
+#include "AliRunLoader.h"
+#include "AliLoader.h"
+#include "AliLog.h"
 #include "AliTRD.h"
 #include "AliTRDhit.h"
 #include "AliTRDdigitizer.h"
-#include "AliTRDdataArrayI.h"
-#include "AliTRDdataArrayF.h"
-#include "AliTRDsegmentArray.h"
+
+#include "AliTRDarrayDictionary.h"
+#include "AliTRDarrayADC.h"
+#include "AliTRDarraySignal.h"
 #include "AliTRDdigitsManager.h"
 #include "AliTRDgeometry.h"
+#include "AliTRDpadPlane.h"
+#include "AliTRDcalibDB.h"
+#include "AliTRDSimParam.h"
+#include "AliTRDCommonParam.h"
+#include "AliTRDfeeParam.h"
+#include "AliTRDmcmSim.h"
+#include "Cal/AliTRDCalROC.h"
+#include "Cal/AliTRDCalDet.h"
 
 ClassImp(AliTRDdigitizer)
 
 //_____________________________________________________________________________
-AliTRDdigitizer::AliTRDdigitizer():TNamed()
+AliTRDdigitizer::AliTRDdigitizer()
+  :AliDigitizer()
+  ,fRunLoader(0)
+  ,fDigitsManager(0)
+  ,fSDigitsManager(0)
+  ,fSDigitsManagerList(0)
+  ,fTRD(0)
+  ,fGeo(0)
+  ,fEvent(0)
+  ,fMasks(0)
+  ,fCompress(kTRUE)
+  ,fSDigits(kFALSE)
+  ,fMergeSignalOnly(kFALSE)
 {
   //
   // AliTRDdigitizer default constructor
   //
+  
+  Init();
+
+}
+
+//_____________________________________________________________________________
+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)
+  ,fMergeSignalOnly(kFALSE)
+{
+  //
+  // AliTRDdigitizer constructor
+  //
 
-  fInputFile     = NULL;
-  fDigits        = NULL;
-  fTRD           = NULL;
-  fGeo           = NULL;
-  fPRF           = NULL;
-  fPRFsmp        = NULL;
-  fTRF           = NULL;
-  fTRFint        = NULL;
-
-  fEvent         = 0;
-  fGasGain       = 0.0;
-  fNoise         = 0.0;
-  fChipGain      = 0.0;
-  fADCoutRange   = 0.0;
-  fADCinRange    = 0.0;
-  fADCthreshold  = 0;
-  fDiffusionOn   = 0;
-  fDiffusionT    = 0.0;
-  fDiffusionL    = 0.0;
-  fElAttachOn    = 0;
-  fElAttachProp  = 0.0;
-  fExBOn         = 0;
-  fOmegaTau      = 0.0;
-  fPRFOn         = 0;
-  fTRFOn         = 0;
-  fDriftVelocity = 0.0;
-
-  fPRFbin        = 0;
-  fPRFlo         = 0.0;
-  fPRFhi         = 0.0;
-  fPRFwid        = 0.0;
-  fPRFpad        = 0;
-  fTRFbin        = 0;
-  fTRFlo         = 0.0;
-  fTRFhi         = 0.0;
-  fTRFwid        = 0.0;
-
-  fCompress      = kTRUE;
-  fVerbose       = 1;
+  Init();
 
 }
 
 //_____________________________________________________________________________
-AliTRDdigitizer::AliTRDdigitizer(const Text_t *name, const Text_t *title)
-                :TNamed(name,title)
+AliTRDdigitizer::AliTRDdigitizer(AliRunDigitizer *manager
+                               , 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)
+  ,fMergeSignalOnly(kFALSE)
 {
   //
-  // AliTRDdigitizer default constructor
+  // AliTRDdigitizer constructor
   //
 
-  fInputFile     = NULL;
-  fDigits        = NULL;
-  fTRD           = NULL;
-  fGeo           = NULL;
-  fPRF           = NULL;
-  fPRFsmp        = NULL;
-  fTRF           = NULL;
-  fTRFint        = NULL;
+  Init();
 
-  fEvent         = 0;
+}
 
-  fCompress      = kTRUE;
-  fVerbose       = 1;
+//_____________________________________________________________________________
+AliTRDdigitizer::AliTRDdigitizer(AliRunDigitizer *manager)
+  :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)
+  ,fMergeSignalOnly(kFALSE)
+{
+  //
+  // AliTRDdigitizer constructor
+  //
 
   Init();
 
 }
 
+//_____________________________________________________________________________
+Bool_t AliTRDdigitizer::Init()
+{
+  //
+  // Initialize the digitizer with default values
+  //
+
+  fRunLoader          = 0;
+  fDigitsManager      = 0;
+  fSDigitsManager     = 0;
+  fSDigitsManagerList = 0;
+  fTRD                = 0;
+  fGeo                = 0;
+
+  fEvent              = 0;
+  fMasks              = 0;
+  fCompress           = kTRUE;
+  fSDigits            = kFALSE;
+  fMergeSignalOnly    = kFALSE;
+  
+  return AliDigitizer::Init();
+
+}
+
 //_____________________________________________________________________________
 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)
+  ,fMergeSignalOnly(d.fMergeSignalOnly)
 {
   //
   // AliTRDdigitizer copy constructor
   //
 
-  ((AliTRDdigitizer &) d).Copy(*this);
-
 }
 
 //_____________________________________________________________________________
@@ -226,17 +223,31 @@ AliTRDdigitizer::~AliTRDdigitizer()
   // AliTRDdigitizer destructor
   //
 
-  if (fInputFile) {
-    fInputFile->Close();
-    delete fInputFile;
+  if (fDigitsManager) {
+    delete fDigitsManager;
+    fDigitsManager      = 0;
   }
 
-  if (fDigits) {
-    delete fDigits;
+  if (fDigitsManager) {              //typo? fSDigitsManager?
+    delete fSDigitsManager;
+    fSDigitsManager     = 0;
   }
 
-  if (fPRF) delete fPRF;
-  if (fTRF) delete fTRF;
+  if (fSDigitsManagerList) {
+    fSDigitsManagerList->Delete();
+    delete fSDigitsManagerList;
+    fSDigitsManagerList = 0;
+  }
+
+  if (fMasks) {
+    delete [] fMasks;
+    fMasks       = 0;
+  }
+
+  if (fGeo) {
+    delete fGeo;
+    fGeo = 0;
+  }
 
 }
 
@@ -247,861 +258,1550 @@ AliTRDdigitizer &AliTRDdigitizer::operator=(const AliTRDdigitizer &d)
   // Assignment operator
   //
 
-  if (this != &d) ((AliTRDdigitizer &) d).Copy(*this);
+  if (this != &d) {
+    ((AliTRDdigitizer &) d).Copy(*this);
+  }
+
   return *this;
 
 }
 
 //_____________________________________________________________________________
-void AliTRDdigitizer::Copy(TObject &d)
+void AliTRDdigitizer::Copy(TObject &d) const
 {
   //
   // Copy function
   //
 
-  Int_t iBin;
-
-  ((AliTRDdigitizer &) d).fInputFile     = NULL;
-  ((AliTRDdigitizer &) d).fDigits        = NULL;
-  ((AliTRDdigitizer &) d).fTRD           = NULL;
-  ((AliTRDdigitizer &) d).fGeo           = NULL;
-
-  ((AliTRDdigitizer &) d).fEvent         = 0;
-
-  ((AliTRDdigitizer &) d).fGasGain       = fGasGain;
-  ((AliTRDdigitizer &) d).fNoise         = fNoise;
-  ((AliTRDdigitizer &) d).fChipGain      = fChipGain;
-  ((AliTRDdigitizer &) d).fADCoutRange   = fADCoutRange;
-  ((AliTRDdigitizer &) d).fADCinRange    = fADCinRange;
-  ((AliTRDdigitizer &) d).fADCthreshold  = fADCthreshold;
-  ((AliTRDdigitizer &) d).fDiffusionOn   = fDiffusionOn; 
-  ((AliTRDdigitizer &) d).fDiffusionT    = fDiffusionT;
-  ((AliTRDdigitizer &) d).fDiffusionL    = fDiffusionL;
-  ((AliTRDdigitizer &) d).fElAttachOn    = fElAttachOn;
-  ((AliTRDdigitizer &) d).fElAttachProp  = fElAttachProp;
-  ((AliTRDdigitizer &) d).fExBOn         = fExBOn;
-  ((AliTRDdigitizer &) d).fOmegaTau      = fOmegaTau;
-  ((AliTRDdigitizer &) d).fLorentzFactor = fLorentzFactor;
-  ((AliTRDdigitizer &) d).fPRFOn         = fPRFOn;
-  ((AliTRDdigitizer &) d).fTRFOn         = fTRFOn;
-
-  ((AliTRDdigitizer &) d).fCompress      = fCompress;
-  ((AliTRDdigitizer &) d).fVerbose       = fVerbose;
-
-  fPRF->Copy(*((AliTRDdigitizer &) d).fPRF);
-  fTRF->Copy(*((AliTRDdigitizer &) d).fTRF);
-
-  ((AliTRDdigitizer &) d).fPRFbin        = fPRFbin;
-  ((AliTRDdigitizer &) d).fPRFlo         = fPRFlo;
-  ((AliTRDdigitizer &) d).fPRFhi         = fPRFhi;
-  ((AliTRDdigitizer &) d).fPRFwid        = fPRFwid;
-  ((AliTRDdigitizer &) d).fPRFpad        = fPRFpad;
-  if (((AliTRDdigitizer &) d).fPRFsmp) delete ((AliTRDdigitizer &) d).fPRFsmp;
-  ((AliTRDdigitizer &) d).fPRFsmp = new Float_t[fPRFbin];
-  for (iBin = 0; iBin < fPRFbin; iBin++) {
-    ((AliTRDdigitizer &) d).fPRFsmp[iBin] = fPRFsmp[iBin];
-  }                                                                             
-  ((AliTRDdigitizer &) d).fTRFbin        = fTRFbin;
-  ((AliTRDdigitizer &) d).fTRFlo         = fTRFlo;
-  ((AliTRDdigitizer &) d).fTRFhi         = fTRFhi;
-  ((AliTRDdigitizer &) d).fTRFwid        = fTRFwid;
-  if (((AliTRDdigitizer &) d).fTRFint) delete ((AliTRDdigitizer &) d).fTRFint;
-  ((AliTRDdigitizer &) d).fTRFint = new Float_t[fTRFbin];
-  for (iBin = 0; iBin < fTRFbin; iBin++) {
-    ((AliTRDdigitizer &) d).fTRFint[iBin] = fTRFint[iBin];
-  }                                                                             
+  ((AliTRDdigitizer &) d).fRunLoader          = 0;
+  ((AliTRDdigitizer &) d).fDigitsManager      = 0;
+  ((AliTRDdigitizer &) d).fSDigitsManager     = 0;
+  ((AliTRDdigitizer &) d).fSDigitsManagerList = 0;
+  ((AliTRDdigitizer &) d).fTRD                = 0;
+  ((AliTRDdigitizer &) d).fGeo                = 0;
+  ((AliTRDdigitizer &) d).fEvent              = 0;
+  ((AliTRDdigitizer &) d).fMasks              = 0;
+  ((AliTRDdigitizer &) d).fCompress           = fCompress;
+  ((AliTRDdigitizer &) d).fSDigits            = fSDigits;
+  ((AliTRDdigitizer &) d).fMergeSignalOnly    = fMergeSignalOnly;
 
 }
 
 //_____________________________________________________________________________
-Int_t AliTRDdigitizer::Diffusion(Float_t driftlength, Float_t *xyz)
+void AliTRDdigitizer::Exec(Option_t *option)
 {
   //
-  // Applies the diffusion smearing to the position of a single electron
+  // Executes the merging
   //
 
-  Float_t driftSqrt = TMath::Sqrt(driftlength);
-  Float_t sigmaT = driftSqrt * fDiffusionT;
-  Float_t sigmaL = driftSqrt * fDiffusionL;
-  xyz[0] = gRandom->Gaus(xyz[0], sigmaL * fLorentzFactor);
-  xyz[1] = gRandom->Gaus(xyz[1], sigmaT * fLorentzFactor);
-  xyz[2] = gRandom->Gaus(xyz[2], sigmaT);
+  Int_t iInput;
 
-  return 1;
+  AliTRDdigitsManager *sdigitsManager;
 
-}
+  TString optionString = option;
+  if (optionString.Contains("deb")) {
+    AliLog::SetClassDebugLevel("AliTRDdigitizer",1);
+    AliInfo("Called with debug option");
+  }
+
+  // The AliRoot file is already connected by the manager
+  AliRunLoader *inrl = 0x0;
+  
+  if (gAlice) {
+    AliDebug(1,"AliRun object found on file.");
+  }
+  else {
+    inrl = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(0));
+    inrl->LoadgAlice();
+    gAlice = inrl->GetAliRun();
+    if (!gAlice) {
+      AliError("Could not find AliRun object.")
+      return;
+    }
+  }
+                                                                           
+  Int_t nInput = fManager->GetNinputs();
+  fMasks       = new Int_t[nInput];
+  for (iInput = 0; iInput < nInput; iInput++) {
+    fMasks[iInput] = fManager->GetMask(iInput);
+  }
 
-//_____________________________________________________________________________
-Int_t AliTRDdigitizer::ExB(Float_t driftlength, Float_t *xyz)
-{
   //
-  // Applies E x B effects to the position of a single electron
+  // Initialization
   //
 
-  xyz[0] = xyz[0];
-  xyz[1] = xyz[1] + fOmegaTau * driftlength;
-  xyz[2] = xyz[2];
+  AliRunLoader *orl = AliRunLoader::GetRunLoader(fManager->GetOutputFolderName());
 
-  return 1;
+  if (InitDetector()) {
+
+    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();
+      }
+    }
+    else {
+      // If we produce Digits
+      tree = ogime->TreeD();
+      if (!tree) {
+       ogime->MakeTree("D");
+        tree = ogime->TreeD();
+      }
+    }
+
+    MakeBranch(tree);
+
+  }
+  for (iInput = 0; iInput < nInput; iInput++) {
+
+    AliDebug(1,Form("Add input stream %d",iInput));
+
+    // 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()) {
+        AliError(Form("Error Occured while loading S. Digits for input %d.",iInput));
+        return;
+      }
+      treees = gime->TreeS();
+    }
+    
+    if (treees == 0x0) {
+      AliError(Form("Input stream %d does not exist",iInput));
+      return;
+    } 
+
+    // Read the s-digits via digits manager
+    sdigitsManager = new AliTRDdigitsManager();
+    sdigitsManager->SetSDigits(kTRUE);
+    
+    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 
+    AddSDigitsManager(sdigitsManager);
+
+  }
+
+  // Convert the s-digits to normal digits
+  AliDebug(1,"Do the conversion");
+  SDigits2Digits();
+
+  // Store the digits
+  AliDebug(1,"Write the digits");
+  fDigitsManager->WriteDigits();
+
+  // Write parameters
+  orl->CdGAFile();
+
+  // Clean up
+  DeleteSDigitsManager();
+
+  AliDebug(1,"Done");
 
 }
 
 //_____________________________________________________________________________
-Int_t AliTRDdigitizer::PadResponse(Float_t signal, Float_t dist, Float_t *pad)
+Bool_t AliTRDdigitizer::Open(const Char_t *file, Int_t nEvent)
 {
   //
-  // Applies the pad response
+  // Opens a ROOT-file with TRD-hits and reads in the hit-tree
   //
+  // Connect the AliRoot file containing Geometry, Kine, and Hits
+  //  
 
-  Int_t iBin =  ((Int_t) (( - dist - fPRFlo) / fPRFwid));
+  TString evfoldname = AliConfig::GetDefaultEventFolderName();
 
-  Int_t iBin0 = iBin - fPRFpad;
-  Int_t iBin1 = iBin;
-  Int_t iBin2 = iBin + fPRFpad;
+  fRunLoader = AliRunLoader::GetRunLoader(evfoldname);
+  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();
+  }
+  gAlice = fRunLoader->GetAliRun();
+  
+  if (gAlice) {
+    AliDebug(1,"AliRun object found on file.");
+  }
+  else {
+    AliError("Could not find AliRun object.");
+    return kFALSE;
+  }
 
-  if ((iBin0 >= 0) && (iBin2 < fPRFbin)) {
+  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
+      tree = loader->TreeD();
+      if (!tree) {
+        loader->MakeTree("D");
+        tree = loader->TreeD();
+      }
+    }
+    return MakeBranch(tree);
+  }
+  else {
+    return kFALSE;
+  }
 
-    pad[0] = signal * fPRFsmp[iBin0];
-    pad[1] = signal * fPRFsmp[iBin1];
-    pad[2] = signal * fPRFsmp[iBin2];
+}
 
-    return 1;
+//_____________________________________________________________________________
+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();
+  
+  if (gAlice) {
+    AliDebug(1,"AliRun object found on file.");
   }
   else {
+    AliError("Could not find AliRun object.");
+    return kFALSE;
+  }
 
-    return 0;
+  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
+      tree = loader->TreeD();
+      if (!tree) {
+        loader->MakeTree("D");
+        tree = loader->TreeD();
+      }
+    }
+    return MakeBranch(tree);
+  }
+  else {
+    return kFALSE;
   }
 
 }
 
 //_____________________________________________________________________________
-Float_t AliTRDdigitizer::TimeResponse(Float_t time)
+Bool_t AliTRDdigitizer::InitDetector()
 {
   //
-  // Applies the preamp shaper time response
+  // Sets the pointer to the TRD detector and the geometry
   //
 
-  Int_t iBin = ((Int_t) ((time - fTRFlo) / fTRFwid)); 
-  if ((iBin >= 0) && (iBin < fTRFbin)) {
-    return fTRFint[iBin];
+  // Get the pointer to the detector class and check for version 1
+  fTRD = (AliTRD *) gAlice->GetDetector("TRD");
+  if (!fTRD) {
+    AliFatal("No TRD module found");
+    exit(1);
+  }
+  if (fTRD->IsVersion() != 1) {
+    AliFatal("TRD must be version 1 (slow simulator)");
+    exit(1);
+  }
+
+  // Get the geometry
+  fGeo = new AliTRDgeometry();
+
+  // Create a digits manager
+  if (fDigitsManager) {
+    delete fDigitsManager;
   }
+  fDigitsManager = new AliTRDdigitsManager();
+  fDigitsManager->SetSDigits(fSDigits);
+  fDigitsManager->CreateArrays();
+  fDigitsManager->SetEvent(fEvent);
+
+  // The list for the input s-digits manager to be merged
+  if (fSDigitsManagerList) {
+    fSDigitsManagerList->Delete();
+  } 
   else {
-    return 0.0;
-  }    
+    fSDigitsManagerList = new TList();
+  }
 
-}
+  return kTRUE;
 
+}
 //_____________________________________________________________________________
-void AliTRDdigitizer::Init()
+Bool_t AliTRDdigitizer::MakeBranch(TTree *tree) const
 {
+  // 
+  // Create the branches for the digits array
   //
-  // Initializes the digitization procedure with standard values
-  //
-
-  // The default parameter for the digitization
-  fGasGain       = 8.0E3;
-  fNoise         = 3000.;
-  fChipGain      = 10.;
-  fADCoutRange   = 255.;
-  fADCinRange    = 2000.;
-  fADCthreshold  = 1;
-
-  // Transverse and longitudinal diffusion coefficients (Xe/Isobutane)
-  fDiffusionOn   = 1;
-  fDiffusionT    = 0.060;
-  fDiffusionL    = 0.017;
-
-  // Propability for electron attachment
-  fElAttachOn    = 0;
-  fElAttachProp  = 0.0;
-
-  // E x B effects
-  fExBOn         = 0;
-  // omega * tau. (tau ~ 12 * 10^-12, B = 0.2T)
-  fOmegaTau      = 17.6 * 12.0 * 0.2 * 0.01;
-
-  // The pad response function
-  fPRFOn         =  1;
-  fPRFlo         = -3.0;
-  fPRFhi         =  3.0;
-  fPRFbin        = 1200;
-  fPRFwid        = (fPRFhi - fPRFlo) / ((Float_t) fPRFbin);
-  fPRFpad        = ((Int_t) (1.0 / fPRFwid));
-  fPRF           = new TF1("PRF","[0]*([1]+exp(-x*x/(2.0*[2])))",fPRFlo,fPRFhi);
-  fPRF->SetParameter(0, 0.8872);
-  fPRF->SetParameter(1,-0.00573);
-  fPRF->SetParameter(2, 0.454 * 0.454);
-
-  // The drift velocity (cm / mus)
-  fDriftVelocity = 1.0;
-
-  // The time response function
-  fTRFOn         = 1;
-  Float_t loTRF  = -200.0;
-  Float_t hiTRF  = 1000.0;
-  fTRF           = new TF1("TRF",TRFlandau,loTRF,hiTRF,3);
-  fTRF->SetParameter(0,  1.0 / 24.24249);
-  fTRF->SetParameter(1,  0.0);
-  fTRF->SetParameter(2, 25.0);
-  fTRFbin        = 1200;
-  fTRFlo         = loTRF * fDriftVelocity / 1000.0;
-  fTRFhi         = hiTRF * fDriftVelocity / 1000.0;
-  fTRFwid        = (fTRFhi - fTRFlo) / ((Float_t) fTRFbin);
+
+  return fDigitsManager->MakeBranch(tree);
 
 }
 
 //_____________________________________________________________________________
-void AliTRDdigitizer::IntegrateTRF()
+void AliTRDdigitizer::AddSDigitsManager(AliTRDdigitsManager *man)
 {
   //
-  // Integrates the time response function over the time bin size
+  // Add a digits manager for s-digits to the input list.
   //
 
-  if (fTRFint) delete fTRFint;
-  fTRFint = new Float_t[fTRFbin];
-  Float_t hiTRF   = fTRFhi                 / fDriftVelocity * 1000.0;
-  Float_t loTRF   = fTRFlo                 / fDriftVelocity * 1000.0;
-  Float_t timeBin = fGeo->GetTimeBinSize() / fDriftVelocity * 1000.0;
-  Float_t binWidth = (hiTRF - loTRF) / ((Float_t) fTRFbin);
-  for (Int_t iBin = 0; iBin < fTRFbin; iBin++) {
-    Float_t bin = iBin * binWidth + loTRF - 0.5 * timeBin;
-    fTRFint[iBin] = fTRF->Integral(bin,bin + timeBin);
-  }
+  fSDigitsManagerList->Add(man);
 
 }
 
 //_____________________________________________________________________________
-void AliTRDdigitizer::SamplePRF()
+void AliTRDdigitizer::DeleteSDigitsManager()
 {
   //
-  // Samples the pad response function
+  // Removes digits manager from the input list.
   //
 
-  if (fPRFsmp) delete fPRFsmp;
-  fPRFsmp = new Float_t[fPRFbin];
-  for (Int_t iBin = 0; iBin < fPRFbin; iBin++) {
-    Float_t bin = (((Float_t ) iBin) + 0.5) * fPRFwid + fPRFlo;
-    fPRFsmp[iBin] = TMath::Max(fPRF->Eval(bin),0.0);
-  }
+  fSDigitsManagerList->Delete();
 
 }
 
 //_____________________________________________________________________________
-Bool_t AliTRDdigitizer::Open(const Char_t *name, Int_t nEvent)
+Bool_t AliTRDdigitizer::MakeDigits()
 {
   //
-  // Opens a ROOT-file with TRD-hits and reads in the hit-tree
+  // Creates digits.
   //
 
-  // Connect the AliRoot file containing Geometry, Kine, and Hits
-  fInputFile = (TFile*) gROOT->GetListOfFiles()->FindObject(name);
-  if (!fInputFile) {
-    printf("AliTRDdigitizer::Open -- ");
-    printf("Open the ALIROOT-file %s.\n",name);
-    fInputFile = new TFile(name,"UPDATE");
-  }
-  else {
-    printf("AliTRDdigitizer::Open -- ");
-    printf("%s is already open.\n",name);
-  }
+  AliDebug(1,"Start creating digits");
 
-  gAlice = (AliRun*) fInputFile->Get("gAlice");
-  if (gAlice) {
-    printf("AliTRDdigitizer::Open -- ");
-    printf("AliRun object found on file.\n");
+  if (!fGeo) {
+    AliError("No geometry defined");
+    return kFALSE;
   }
-  else {
-    printf("AliTRDdigitizer::Open -- ");
-    printf("Could not find AliRun object.\n");
+
+  AliTRDcalibDB *calibration = AliTRDcalibDB::Instance();
+  if (!calibration) {
+    AliFatal("Could not get calibration object");
     return kFALSE;
   }
 
-  fEvent = nEvent;
+  const Int_t kNdet  = AliTRDgeometry::Ndet();
 
-  // Import the Trees for the event nEvent in the file
-  Int_t nparticles = gAlice->GetEvent(fEvent);
-  if (nparticles <= 0) {
-    printf("AliTRDdigitizer::Open -- ");
-    printf("No entries in the trees for event %d.\n",fEvent);
+  Float_t **hits = new Float_t*[kNdet];
+  Int_t    *nhit = new Int_t[kNdet];
+
+  AliTRDarraySignal *signals = 0x0;
+  // Sort all hits according to detector number
+  if (!SortHits(hits,nhit)) {
+    AliError("Sorting hits failed");
     return kFALSE;
   }
 
-  return InitDetector();
+  // Loop through all detectors
+  for (Int_t det = 0; det < kNdet; det++) {
+
+    // Detectors that are switched off, not installed, etc.
+    if (( calibration->IsChamberInstalled(det)) &&
+       (!calibration->IsChamberMasked(det))    &&
+        ( fGeo->ChamberInGeometry(det))         &&
+        (nhit[det] > 0)) {
+
+      signals = new AliTRDarraySignal();
+         
+      // Convert the hits of the current detector to detector signals
+      if (!ConvertHits(det,hits[det],nhit[det],signals)) {
+       AliError(Form("Conversion of hits failed for detector=%d",det));
+        return kFALSE;
+      }
+      // Convert the detector signals to digits or s-digits
+      if (!ConvertSignals(det,signals)) {
+       AliError(Form("Conversion of signals failed for detector=%d",det));
+       return kFALSE;
+      }
 
-}
+      // Delete the signals array
+      delete signals;
+      signals = 0x0;
 
-//_____________________________________________________________________________
-Bool_t AliTRDdigitizer::InitDetector()
-{
-  //
-  // Sets the pointer to the TRD detector and the geometry
-  //
+    } // if: detector status
 
-  // Get the pointer to the detector class and check for version 1
-  fTRD = (AliTRD*) gAlice->GetDetector("TRD");
-  if (fTRD->IsVersion() != 1) {
-    printf("AliTRDdigitizer::Open -- ");
-    printf("TRD must be version 1 (slow simulator).\n");
-    exit(1);
-  }
+    delete [] hits[det];
 
-  // Get the geometry
-  fGeo = fTRD->GetGeometry();
-  printf("AliTRDdigitizer::Open -- ");
-  printf("Geometry version %d\n",fGeo->IsVersion());
+  } // for: detector
+
+  delete [] hits;
+  delete [] nhit;
 
   return kTRUE;
 
 }
 
 //_____________________________________________________________________________
-Bool_t AliTRDdigitizer::MakeDigits()
+Bool_t AliTRDdigitizer::SortHits(Float_t **hits, Int_t *nhit)
 {
   //
-  // Loops through the TRD-hits and creates the digits.
+  // Read all the hits and sorts them according to detector number
+  // in the output array <hits>.
   //
 
-  ///////////////////////////////////////////////////////////////
-  // Parameter 
-  ///////////////////////////////////////////////////////////////
+  AliDebug(1,"Start sorting hits");
 
-  // Converts number of electrons to fC
-  const Float_t kEl2fC  = 1.602E-19 * 1.0E15; 
+  const Int_t kNdet = AliTRDgeometry::Ndet();
+  // Size of the hit vector
+  const Int_t kNhit = 6;
 
-  ///////////////////////////////////////////////////////////////
+  Float_t *xyz      = 0;
+  Int_t    nhitTrk  = 0;
 
-  // Number of pads included in the pad response
-  const Int_t kNpad  = 3;
+  Int_t   *lhit     = new Int_t[kNdet];
 
-  // Number of track dictionary arrays
-  const Int_t kNDict = AliTRDdigitsManager::kNDict;
+  for (Int_t det = 0; det < kNdet; det++) {
+    lhit[det] = 0;
+    nhit[det] = 0;
+    hits[det] = 0;
+  }
 
-  Int_t   iRow, iCol, iTime;
-  Int_t   iDict;
-  Int_t   nBytes = 0;
+  AliLoader *gimme = fRunLoader->GetLoader("TRDLoader");
+  if (!gimme->TreeH()) {
+    gimme->LoadHits();
+  }
+  TTree *hitTree = gimme->TreeH();
+  if (hitTree == 0x0) {
+    AliError("Can not get TreeH");
+    return kFALSE;
+  }
+  fTRD->SetTreeAddress();
 
-  Int_t   totalSizeDigits = 0;
-  Int_t   totalSizeDict0  = 0;
-  Int_t   totalSizeDict1  = 0;
-  Int_t   totalSizeDict2  = 0;
+  // Get the number of entries in the hit tree
+  // (Number of primary particles creating a hit somewhere)
+  Int_t nTrk = (Int_t) hitTree->GetEntries();
+  AliDebug(1,Form("Found %d tracks",nTrk));
 
-  AliTRDdataArrayF *signals = 0;
-  AliTRDdataArrayI *digits  = 0;
-  AliTRDdataArrayI *dictionary[kNDict];
+  // Loop through all the tracks in the tree
+  for (Int_t iTrk = 0; iTrk < nTrk; iTrk++) {
 
-  // Create a digits manager
-  fDigits = new AliTRDdigitsManager();
+    gAlice->GetMCApp()->ResetHits();
+    hitTree->GetEvent(iTrk);
 
-  // Create a container for the amplitudes
-  AliTRDsegmentArray *signalsArray 
-                     = new AliTRDsegmentArray("AliTRDdataArrayF",AliTRDgeometry::Ndet());
+    if (!fTRD->Hits()) {
+      AliError(Form("No hits array for track = %d",iTrk));
+      continue;
+    }
 
-  if (!fGeo) {
-    printf("AliTRDdigitizer::MakeDigits -- ");
-    printf("No geometry defined\n");
-    return kFALSE;
-  }
+    // Number of hits for this track
+    nhitTrk = fTRD->Hits()->GetEntriesFast();
+
+    Int_t hitCnt = 0;
+    // Loop through the TRD hits
+    AliTRDhit *hit = (AliTRDhit *) fTRD->FirstHit(-1);
+    while (hit) {
+
+      hitCnt++;
+
+      // Don't analyze test hits
+      if (((Int_t) hit->GetCharge()) != 0) {
+
+        Int_t   trk  = hit->Track();
+        Int_t   det  = hit->GetDetector();
+        Int_t   q    = hit->GetCharge();
+        Float_t x    = hit->X();
+        Float_t y    = hit->Y();
+        Float_t z    = hit->Z();
+        Float_t time = hit->GetTime();
+
+        if (nhit[det] == lhit[det]) {
+          // Inititialization of new detector
+          xyz        = new Float_t[kNhit*(nhitTrk+lhit[det])];
+          if (hits[det]) {
+            memcpy(xyz,hits[det],sizeof(Float_t)*kNhit*lhit[det]);
+            delete [] hits[det];
+         }
+          lhit[det] += nhitTrk;
+          hits[det]  = xyz;
+       }
+        else {
+          xyz        = hits[det];
+       }
+        xyz[nhit[det]*kNhit+0] = x;
+        xyz[nhit[det]*kNhit+1] = y;
+        xyz[nhit[det]*kNhit+2] = z;
+        xyz[nhit[det]*kNhit+3] = q;
+        xyz[nhit[det]*kNhit+4] = trk;
+        xyz[nhit[det]*kNhit+5] = time;
+        nhit[det]++;
 
-  printf("AliTRDdigitizer::MakeDigits -- ");
-  printf("Start creating digits.\n");
-  if (fVerbose > 0) this->Dump();
+      } // if: charge != 0
 
-  // The Lorentz factor
-  if (fExBOn) {
-    fLorentzFactor = 1.0 / (1.0 + fOmegaTau*fOmegaTau);
-  }
-  else {
-    fLorentzFactor = 1.0;
-  }
+      hit = (AliTRDhit *) fTRD->NextHit();   
 
-  // Create the sampled PRF
-  SamplePRF();
+    } // for: hits of one track
 
-  // Create the integrated TRF
-  IntegrateTRF();
+  } // for: tracks
 
-  // Get the pointer to the hit tree
-  TTree *HitTree = gAlice->TreeH();
+  delete [] lhit;
 
-  // 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 (fVerbose > 0) {
-    printf("AliTRDdigitizer::MakeDigits -- ");
-    printf("Found %d primary particles\n",nTrack);
-  } 
+  return kTRUE;
 
-  Int_t detectorOld = -1;
-  Int_t countHits   =  0; 
+}
+
+//_____________________________________________________________________________
+Bool_t AliTRDdigitizer::ConvertHits(Int_t det, Float_t *hits, Int_t nhit
+                                  , AliTRDarraySignal *signals)
+{
+  //
+  // Converts the detectorwise sorted hits to detector signals
+  //
 
-  // Loop through all entries in the tree
-  for (Int_t iTrack = 0; iTrack < nTrack; iTrack++) {
+  AliDebug(1,Form("Start converting hits for detector=%d (nhits=%d)",det,nhit));
 
-    gAlice->ResetHits();
-    nBytes += HitTree->GetEvent(iTrack);
+  // Number of pads included in the pad response
+  const Int_t kNpad      = 3;
+  // Number of track dictionary arrays
+  const Int_t kNdict     = AliTRDdigitsManager::kNDict;
+  // Size of the hit vector
+  const Int_t kNhit      = 6;
+
+  // 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    iPad          = 0;
+  Int_t    dict          = 0;
+  Int_t    timeBinTRFend = 1;
+
+  Double_t pos[3];
+  Double_t loc[3];
+  Double_t padSignal[kNpad];
+  Double_t signalOld[kNpad];
+
+  AliTRDarrayDictionary *dictionary[kNdict];
+
+  AliTRDSimParam    *simParam    = AliTRDSimParam::Instance();
+  AliTRDCommonParam *commonParam = AliTRDCommonParam::Instance();
+  AliTRDcalibDB     *calibration = AliTRDcalibDB::Instance();
+
+  if (!commonParam) {
+    AliFatal("Could not get common parameterss");
+    return kFALSE;
+  }
+  if (!simParam) {
+    AliFatal("Could not get simulation parameters");
+    return kFALSE;
+  }  
+  if (!calibration) {
+    AliFatal("Could not get calibration object");  
+    return kFALSE;
+  }
+
+  // Get the detector wise calibration objects
+  AliTRDCalROC       *calVdriftROC      = 0;
+  Float_t             calVdriftDetValue = 0.0;
+  const AliTRDCalDet *calVdriftDet      = calibration->GetVdriftDet();  
+  AliTRDCalROC       *calT0ROC          = 0;
+  Float_t             calT0DetValue     = 0.0;
+  const AliTRDCalDet *calT0Det          = calibration->GetT0Det();  
+
+  if (simParam->TRFOn()) {
+    timeBinTRFend = ((Int_t) (simParam->GetTRFhi() 
+                  * commonParam->GetSamplingFrequency())) - 1;
+  }
 
-    // Get the number of hits in the TRD created by this particle
-    Int_t nHit = fTRD->Hits()->GetEntriesFast();
-    if (fVerbose > 0) {
-      printf("AliTRDdigitizer::MakeDigits -- ");
-      printf("Found %d hits for primary particle %d\n",nHit,iTrack);
+  Int_t   nTimeTotal   = calibration->GetNumberOfTimeBins();
+  Float_t samplingRate = commonParam->GetSamplingFrequency();
+  Float_t elAttachProp = simParam->GetElAttachProp() / 100.0; 
+
+  AliTRDpadPlane *padPlane = fGeo->GetPadPlane(det);
+  Int_t   layer   = fGeo->GetLayer(det);         //update
+  Float_t row0    = padPlane->GetRow0ROC();
+  Int_t   nRowMax = padPlane->GetNrows();
+  Int_t   nColMax = padPlane->GetNcols();
+
+  // Create a new array for the signals
+  signals->Allocate(nRowMax,nColMax,nTimeTotal);
+
+  // Create a new array for the dictionary
+  for (dict = 0; dict < kNdict; dict++) {       
+    dictionary[dict] = (AliTRDarrayDictionary *) fDigitsManager->GetDictionary(det,dict);
+    dictionary[dict]->Allocate(nRowMax,nColMax,nTimeTotal);
+  }      
+
+  // Loop through the hits in this detector
+  for (Int_t hit = 0; hit < nhit; hit++) {
+
+    pos[0]          = hits[hit*kNhit+0];
+    pos[1]          = hits[hit*kNhit+1];
+    pos[2]          = hits[hit*kNhit+2];
+    Float_t q       = hits[hit*kNhit+3];
+    Float_t hittime = hits[hit*kNhit+5];
+    Int_t   track   = ((Int_t) hits[hit*kNhit+4]);
+
+    Int_t   inDrift = 1;
+
+    // Find the current volume with the geo manager
+    gGeoManager->SetCurrentPoint(pos);
+    gGeoManager->FindNode();      
+    if (strstr(gGeoManager->GetPath(),"/UK")) {
+      inDrift = 0;
     }
 
-    // Loop through the TRD hits  
-    for (Int_t iHit = 0; iHit < nHit; iHit++) {
-
-      countHits++;
-
-      AliTRDhit *hit = (AliTRDhit *) fTRD->Hits()->UncheckedAt(iHit);
-      Float_t pos[3];
-              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);
-
-      if (!(CheckDetector(plane,chamber,sector))) continue;
-
-      Int_t   nRowMax     = fGeo->GetRowMax(plane,chamber,sector);
-      Int_t   nColMax     = fGeo->GetColMax(plane);
-      Int_t   nTimeMax    = fGeo->GetTimeMax();
-      Float_t row0        = fGeo->GetRow0(plane,chamber,sector);
-      Float_t col0        = fGeo->GetCol0(plane);
-      Float_t time0       = fGeo->GetTime0(plane);
-      Float_t rowPadSize  = fGeo->GetRowPadSize();
-      Float_t colPadSize  = fGeo->GetColPadSize();
-      Float_t timeBinSize = fGeo->GetTimeBinSize();
-
-      if (fVerbose > 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, nTimeMax = %d\n" 
-              ,nRowMax,nColMax,nTimeMax);
-        printf("row0 = %f, col0 = %f, time0 = %f\n"
-              ,row0,col0,time0);
-        printf("rowPadSize = %f, colPadSize = %f, timeBinSize = %f\n"
-              ,rowPadSize,colPadSize,timeBinSize); 
+    // Get the calibration objects
+    calVdriftROC      = calibration->GetVdriftROC(det);
+    calVdriftDetValue = calVdriftDet->GetValue(det);
+    calT0ROC          = calibration->GetT0ROC(det);
+    calT0DetValue     = calT0Det->GetValue(det);
+
+    // 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 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())) {
+        continue;
       }
-       
-      // Don't analyze test hits with amplitude 0.
-      if (((Int_t) q) == 0) continue;
+      if ((driftlength < kDrMin) ||
+          (driftlength > kDrMax)) {
+        continue;
+      }
+    }
 
-      if (detector != detectorOld) {
+    // 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) {
+      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) {
+      continue;          
+    }
+    Double_t colOffset    = 0.0;
 
-        if (fVerbose > 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 (fVerbose > 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 (fVerbose > 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 (fVerbose > 1) {
-            printf("AliTRDdigitizer::MakeDigits -- ");
-            printf("Allocate a new container ... ");
-         }
-          signals->Allocate(nRowMax,nColMax,nTimeMax);
-       }
-        else {
-         // Expand an existing one
-          if (fCompress) {
-            if (fVerbose > 1) {
-              printf("AliTRDdigitizer::MakeDigits -- ");
-              printf("Expand an existing container ... ");
-           }
-            signals->Expand();
-         }
+    // Normalized drift length
+    Float_t  driftvelocity  = calVdriftDetValue * calVdriftROC->GetValue(colE,rowE);
+    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), meaning 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;
+        }
+      }
+          
+      // Apply the diffusion smearing
+      if (simParam->DiffusionOn()) {
+        if (!(Diffusion(driftvelocity,absdriftlength,locR,locC,locT))) {
+          continue;
        }
-       // The same for the dictionary
-        for (iDict = 0; iDict < kNDict; iDict++) {       
-          dictionary[iDict] = fDigits->GetDictionary(detector,iDict);
-          if (dictionary[iDict]->GetNtime() == 0) {
-            dictionary[iDict]->Allocate(nRowMax,nColMax,nTimeMax);
-         }
-          else {
-            if (fCompress) dictionary[iDict]->Expand();
-         }
-        }      
-        if (fVerbose > 1) printf("done\n");
-        detectorOld = detector;
       }
 
-      // Rotate the sectors on top of each other
-      Float_t rot[3];
-      fGeo->Rotate(detector,pos,rot);
-
-      // The driftlength
-      Float_t driftlength = time0 - rot[0];
-      if ((driftlength < 0) || 
-          (driftlength > AliTRDgeometry::DrThick())) continue;
-      Float_t driftlengthL = driftlength;
-      if (fExBOn) driftlengthL /= TMath::Sqrt(fLorentzFactor);
+      // Apply E x B effects (depends on drift direction)
+      if (commonParam->ExBOn()) { 
+        if (!(ExB(driftvelocity,driftlength,locC))) {
+          continue;
+       }
+      }
 
-      // The hit position in pad coordinates (center pad)
+      // The electron position after diffusion and ExB in pad coordinates.
       // The pad row (z-direction)
-      Int_t  rowH = (Int_t) ((rot[2] -  row0) /  rowPadSize);
-      // The pad column (rphi-direction)  
-      Int_t  colH = (Int_t) ((rot[1] -  col0) /  colPadSize);
-      // The time bucket
-      Int_t timeH = (Int_t) (driftlength      / timeBinSize);
-      if (fVerbose > 1) {
-        printf("rowH = %d, colH = %d, timeH = %d\n"
-              ,rowH,colH,timeH);
+      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 + padPlane->GetAnodeWireOffset();
+       zz -= ((Int_t)(2 * zz)) / 2.0;
+        if (zz > 0.25) {
+          zz  = 0.5 - zz;
+        }
+        // Use drift time map (GARFIELD)
+        drifttime = commonParam->TimeStruct(driftvelocity,0.5*kAmWidth-1.0*locT,zz)
+                  + hittime;
+      } 
+      else {
+       // Use constant drift velocity
+        drifttime = TMath::Abs(locT) / driftvelocity
+                  + hittime;
       }
 
-      // 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++) {
-
-        Float_t xyz[3];
-        xyz[0] = rot[0];
-        xyz[1] = rot[1];
-        xyz[2] = rot[2];
+      // Apply the gas gain including fluctuations
+      Double_t ggRndm = 0.0;
+      do {
+        ggRndm = gRandom->Rndm();
+      } while (ggRndm <= 0);
+      Double_t signal = -(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 a fixed parametrization, i.e. not dependent on
+        // calibration values !
+        if (!(calibration->PadResponse(signal,dist,layer,padSignal))) continue;
+      }
+      else {
+        padSignal[0] = 0.0;
+        padSignal[1] = signal;
+        padSignal[2] = 0.0;
+      }
 
-        // Electron attachment
-        if (fElAttachOn) {
-          if (gRandom->Rndm() < (driftlengthL * fElAttachProp / 100.)) 
-            continue;
+      // 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);
         }
 
-        // Apply the diffusion smearing
-        if (fDiffusionOn) {
-          if (!(Diffusion(driftlengthL,xyz))) continue;
-       }
+        signalOld[0] = 0.0;
+        signalOld[1] = 0.0;
+        signalOld[2] = 0.0;
 
-        // Apply E x B effects
-        if (fExBOn) { 
-          if (!(ExB(driftlength,xyz))) continue;   
-       }
+        for (iPad = 0; iPad < kNpad; iPad++) {
 
-        // The electron position 
-        // The pad row (z-direction)
-        Int_t  rowE = (Int_t) ((xyz[2] -  row0) /  rowPadSize);
-        // The pad column (rphi-direction)
-        Int_t  colE = (Int_t) ((xyz[1] -  col0) /  colPadSize);
-        // The time bucket
-        Int_t timeE = (Int_t) ((time0 - xyz[0]) / timeBinSize);
-
-        if (( rowE < 0) || ( rowE >=  nRowMax)) continue;
-        if (( colE < 0) || ( colE >=  nColMax)) continue;
-        if ((timeE < 0) || (timeE >= nTimeMax)) continue;
-
-        // Apply the gas gain including fluctuations
-        Float_t ggRndm = 0.0;
-        do {
-          ggRndm = gRandom->Rndm();
-       } while (ggRndm <= 0);
-        Int_t signal = (Int_t) (-fGasGain * TMath::Log(ggRndm));
-
-        if (fVerbose > 2) {
-          printf("  electron no. %d, signal = %d\n",iEl,signal);
-          printf("  rowE = %d, colE = %d, timeE = %d\n"
-               ,rowE,colE,timeE);
-       }
+          Int_t colPos = colE + iPad - 1;
+          if (colPos <        0) continue;
+          if (colPos >= nColMax) break;
 
-        // Apply the pad response 
-        Float_t padSignal[kNpad];
-        if (fPRFOn) {
-         // The distance of the electron to the center of the pad 
-         // in units of pad width
-          Float_t dist = (xyz[1] - col0 - (colE + 0.5) * colPadSize) 
-                       / colPadSize;
-          if (!(PadResponse(signal,dist,padSignal))) continue;
-       }
-       else {
-          padSignal[0] = 0.0;
-          padSignal[1] = signal;
-          padSignal[2] = 0.0;
-       }
+          // Add the signals
+          signalOld[iPad] = signals->GetData(rowE,colPos,iTimeBin);
 
-        // The distance of the position to the beginning of the timebin
-        Float_t timeOffset = (time0 - timeE * timeBinSize) - xyz[0];
-        Int_t timeTRDbeg = 0;
-        Int_t timeTRDend = 1;
-        if (fTRFOn) {
-          timeTRDbeg =  2;
-          timeTRDend = 11;
-       }
-        for (Int_t iTimeBin = TMath::Max(timeE - timeTRDbeg,       0)
-                ; iTimeBin < TMath::Min(timeE + timeTRDend,nTimeMax) 
-                ; iTimeBin++) {
-
-         // Apply the time response
-          Float_t timeResponse = 1.0;
-          if (fTRFOn) {
-            Float_t time = (iTimeBin - timeE) * timeBinSize + timeOffset;
-            timeResponse = TimeResponse(time);
-         }
+          if (colPos != colE) {
+           // Cross talk added to non-central pads
+            signalOld[iPad] += padSignal[iPad] 
+                            * (timeResponse + crossTalk);
+          } 
+          else {
+           // W/o cross talk at central pad
+            signalOld[iPad] += padSignal[iPad] 
+                            * timeResponse;
+          }
 
-          // Add the signals
-          Float_t signalOld[kNpad] = { 0.0, 0.0, 0.0 };
-          for (Int_t iPad = 0; iPad < kNpad; iPad++) {
-            Int_t colPos = colE + iPad - 1;
-            if (colPos <        0) continue;
-            if (colPos >= nColMax) break;
-            signalOld[iPad]  = signals->GetData(rowE,colPos,iTimeBin);
-            signalOld[iPad] += padSignal[iPad] * timeResponse;
-            signals->SetData(rowE,colPos,iTimeBin,signalOld[iPad]);
-         }
-          if (fVerbose > 3) {
-            printf("    iTimeBin = %d, timeResponse = %f\n"
-                  ,iTimeBin,timeResponse);
-            printf("    pad-signal = %f, %f, %f\n"
-                  ,signalOld[0],signalOld[1],signalOld[2]);
-         }
+          signals->SetData(rowE,colPos,iTimeBin,signalOld[iPad]);
 
           // Store the track index in the dictionary
           // Note: We store index+1 in order to allow the array to be compressed
-          for (iDict = 0; iDict < kNDict; iDict++) {
-            Int_t oldTrack = dictionary[iDict]->GetData(rowE,colE,timeE);
-            if (oldTrack == track+1) break;
-            //if (oldTrack ==      -1) break;
-            if (oldTrack ==       0) {
-              dictionary[iDict]->SetData(rowE,colE,timeE,track+1);
-              if (fVerbose > 3) {
-                printf("    track index = %d\n",track); 
+         // Note2: Taking out the +1 in track
+          if (signalOld[iPad] > 0.0) { 
+            for (dict = 0; dict < kNdict; dict++) {
+             Int_t oldTrack = dictionary[dict]->GetData(rowE,colPos,iTimeBin); 
+             if (oldTrack == track) break;
+             if (oldTrack ==  -1 ) {
+               dictionary[dict]->SetData(rowE,colPos,iTimeBin,track);
+               break;
              }
-              break;
             }
           }
-          if ((fVerbose > 1) && (iDict == kNDict)) {
-            printf("AliTRDdigitizer::MakeDigits -- ");
-            printf("More than three tracks for one digit!\n");
-          }
 
-       }
+       } // Loop: pads
 
-      }
+      } // Loop: time bins
 
-    }
+    } // Loop: electrons of a single hit
 
-  } // All hits finished
+  } // Loop: hits
 
-  printf("AliTRDdigitizer::MakeDigits -- ");
-  printf("Finished analyzing %d hits\n",countHits);
+  AliDebug(2,Form("Finished analyzing %d hits",nhit));
 
-  // Loop through all chambers to finalize the digits
-  for (Int_t iDet = 0; iDet < AliTRDgeometry::Ndet(); iDet++) {
+  return kTRUE;
 
-    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);
-    Int_t nTimeMax = fGeo->GetTimeMax();
+}
 
-    //if (!(CheckDetector(plane,chamber,sector))) continue;
-    if (fVerbose > 0) {
-      printf("AliTRDdigitizer::MakeDigits -- ");
-      printf("Digitization for chamber %d\n",iDet);
-    }
+//_____________________________________________________________________________
+Bool_t AliTRDdigitizer::ConvertSignals(Int_t det, AliTRDarraySignal *signals)
+{
+  //
+  // Convert signals to digits
+  //
 
-    // Add a container for the digits of this detector
-    digits = fDigits->GetDigits(iDet);        
-    // Allocate memory space for the digits buffer
-    digits->Allocate(nRowMax,nColMax,nTimeMax);
+  AliDebug(1,Form("Start converting the signals for detector %d",det));
 
-    // Get the signal container
-    signals = (AliTRDdataArrayF *) signalsArray->At(iDet);
-    if (signals->GetNtime() == 0) {
-      // Create missing containers
-      signals->Allocate(nRowMax,nColMax,nTimeMax);      
+  if (fSDigits) {
+    // Convert the signal array to s-digits
+    if (!Signal2SDigits(det,signals)) {
+      return kFALSE;
     }
-    else {
-      // Expand the container if neccessary
-      if (fCompress) signals->Expand();
+  }
+  else {
+    // Convert the signal array to digits
+    if (!Signal2ADC(det,signals)) {
+      return kFALSE;
     }
-    // Create the missing dictionary containers
-    for (iDict = 0; iDict < kNDict; iDict++) {       
-      dictionary[iDict] = fDigits->GetDictionary(iDet,iDict);
-      if (dictionary[iDict]->GetNtime() == 0) {
-        dictionary[iDict]->Allocate(nRowMax,nColMax,nTimeMax);
+  }
+
+  // Compress the arrays
+  CompressOutputArrays(det);   
+
+  return kTRUE;
+
+}
+
+//_____________________________________________________________________________
+Bool_t AliTRDdigitizer::Signal2ADC(Int_t det, AliTRDarraySignal *signals)
+{
+  //
+  // Converts the sampled electron signals to ADC values for a given chamber
+  //
+
+  AliDebug(1,Form("Start converting signals to ADC values for detector=%d",det));
+
+  AliTRDcalibDB     *calibration = AliTRDcalibDB::Instance();
+  if (!calibration) {
+    AliFatal("Could not get calibration object");
+    return kFALSE;
+  }
+
+  AliTRDSimParam    *simParam    = AliTRDSimParam::Instance();
+  if (!simParam) {
+    AliFatal("Could not get simulation parameters");
+    return kFALSE;
+  }  
+
+  // Converts number of electrons to fC
+  const Double_t kEl2fC = 1.602e-19 * 1.0e15; 
+
+  // Coupling factor
+  Double_t coupling     = simParam->GetPadCoupling() 
+                        * simParam->GetTimeCoupling();
+  // Electronics conversion factor
+  Double_t convert      = kEl2fC 
+                        * simParam->GetChipGain();
+  // ADC conversion factor
+  Double_t adcConvert   = simParam->GetADCoutRange()
+                        / simParam->GetADCinRange();
+  // The electronics baseline in mV
+  Double_t baseline     = simParam->GetADCbaseline() 
+                        / adcConvert;
+  // The electronics baseline in electrons
+  Double_t baselineEl   = baseline
+                        / convert;
+
+  Int_t row  = 0;
+  Int_t col  = 0;
+  Int_t time = 0;
+
+  Int_t nRowMax    = fGeo->GetPadPlane(det)->GetNrows();
+  Int_t nColMax    = fGeo->GetPadPlane(det)->GetNcols();
+  Int_t nTimeTotal = calibration->GetNumberOfTimeBins();
+
+  // The gainfactor calibration objects
+  const AliTRDCalDet *calGainFactorDet      = calibration->GetGainFactorDet();  
+  AliTRDCalROC       *calGainFactorROC      = 0;
+  Float_t             calGainFactorDetValue = 0.0;
+
+  AliTRDarrayADC     *digits = 0x0;
+
+  if (!signals) {
+    AliError(Form("Signals array for detector %d does not exist\n",det));
+    return kFALSE;
+  }
+  if (signals->HasData()) {
+    // Expand the container if neccessary
+    signals->Expand();   
+  }
+  else {
+    // Create missing containers
+    signals->Allocate(nRowMax,nColMax,nTimeTotal);      
+  }
+
+  // Get the container for the digits of this detector
+  if (fDigitsManager->HasSDigits()) {
+    AliError("Digits manager has s-digits");
+    return kFALSE;
+  }
+
+  digits = (AliTRDarrayADC *) fDigitsManager->GetDigits(det);
+  // Allocate memory space for the digits buffer
+  if (!digits->HasData()) {
+    digits->Allocate(nRowMax,nColMax,nTimeTotal);
+  }
+
+  // Get the calibration objects
+  calGainFactorROC      = calibration->GetGainFactorROC(det);
+  calGainFactorDetValue = calGainFactorDet->GetValue(det);
+
+  // Create the digits for this chamber
+  for (row  = 0; row  <  nRowMax; row++ ) {
+    for (col  = 0; col  <  nColMax; col++ ) {
+
+      // Check whether pad is masked
+      // Bridged pads are not considered yet!!!
+      if (calibration->IsPadMasked(det,col,row)) {
+        continue;
       }
-    }
 
-    Int_t nDigits = 0;
-
-    // Create the digits for this chamber
-    for (iRow  = 0; iRow  <  nRowMax; iRow++ ) {
-      for (iCol  = 0; iCol  <  nColMax; iCol++ ) {
-        for (iTime = 0; iTime < nTimeMax; iTime++) {         
-
-          Float_t signalAmp = signals->GetData(iRow,iCol,iTime);
-
-          // Add the noise
-          signalAmp  = TMath::Max((Double_t) gRandom->Gaus(signalAmp,fNoise),0.0);
-         // Convert to fC
-          signalAmp *= kEl2fC;
-          // Convert to mV
-          signalAmp *= fChipGain;
-         // Convert to ADC counts. Set the overflow-bit fADCoutRange if the 
-         // signal is larger than fADCinRange
-          Int_t adc  = 0;
-          if (signalAmp >= fADCinRange) {
-            adc = ((Int_t) fADCoutRange);
-         }
-          else {
-            adc = ((Int_t) (signalAmp * (fADCoutRange / fADCinRange)));
-         }
+      // The gain factors
+      Float_t padgain = calGainFactorDetValue 
+                      * calGainFactorROC->GetValue(col,row);
+      if (padgain <= 0) {
+        AliError(Form("Not a valid gain %f, %d %d %d",padgain,det,col,row));
+      }
 
-          // Store the amplitude of the digit if above threshold
-          if (adc > fADCthreshold) {
-            if (fVerbose > 2) {
-              printf("  iRow = %d, iCol = %d, iTime = %d\n"
-                    ,iRow,iCol,iTime);
-              printf("  signal = %f, adc = %d\n",signalAmp,adc);
-           }
-            nDigits++;
-            digits->SetData(iRow,iCol,iTime,adc);
-         }
+      for (time = 0; time < nTimeTotal; time++) {
+
+       // Get the signal amplitude
+        Float_t signalAmp = signals->GetData(row,col,time);
+        // Pad and time coupling
+        signalAmp *= coupling;
+       // Gain factors
+       signalAmp *= padgain;
+
+        // Add the noise, starting from minus ADC baseline in electrons
+        signalAmp  = TMath::Max((Double_t) gRandom->Gaus(signalAmp,simParam->GetNoise())
+                               ,-baselineEl);
+
+        // Convert to mV
+        signalAmp *= convert;
+        // Add ADC baseline in mV
+        signalAmp += baseline;
+
+       // Convert to ADC counts. Set the overflow-bit fADCoutRange if the
+       // signal is larger than fADCinRange
+        Short_t adc  = 0;
+        if (signalAmp >= simParam->GetADCinRange()) {
+          adc = ((Short_t) simParam->GetADCoutRange());
+       }
+        else {
+          adc = TMath::Nint(signalAmp * adcConvert);
+       }
+
+        // Saving all digits
+       digits->SetData(row,col,time,adc);
+
+      } // for: time
+
+    } // for: col
+  } // for: row
+
+  // Run the digital processing in the MCM
+  RunDigitalProcessing(digits, det);
+
+  return kTRUE;
+
+}
+
+//_____________________________________________________________________________
+Bool_t AliTRDdigitizer::Signal2SDigits(Int_t det, AliTRDarraySignal *signals)
+{
+  //
+  // Converts the sampled electron signals to s-digits
+  //
+
+  AliDebug(1,Form("Start converting signals to s-digits for detector=%d",det));
+
+  AliTRDcalibDB     *calibration = AliTRDcalibDB::Instance();
+  if (!calibration) {
+    AliFatal("Could not get calibration object");
+    return kFALSE;
+  }
+
+  Int_t row  = 0;
+  Int_t col  = 0;
+  Int_t time = 0;
+
+  Int_t nRowMax    = fGeo->GetPadPlane(det)->GetNrows();
+  Int_t nColMax    = fGeo->GetPadPlane(det)->GetNcols();
+  Int_t nTimeTotal = calibration->GetNumberOfTimeBins();
+
+  // Get the container for the digits of this detector
+
+  if (!fDigitsManager->HasSDigits()) {
+    AliError("Digits manager has no s-digits");
+    return kFALSE;
+  }
+
+  AliTRDarraySignal *digits = (AliTRDarraySignal *) fDigitsManager->GetSDigits(det);
+  // Allocate memory space for the digits buffer
+  if (!digits->HasData()) {
+    digits->Allocate(nRowMax,nColMax,nTimeTotal);
+  }
+
+  // Create the sdigits for this chamber
+  for (row  = 0; row  <  nRowMax; row++ ) {
+    for (col  = 0; col  <  nColMax; col++ ) {
+      for (time = 0; time < nTimeTotal; time++) {         
+        digits->SetData(row,col,time,signals->GetData(row,col,time));
+      } // for: time
+    } // for: col
+  } // for: row
+  
+  return kTRUE;
 
+}
+
+//_____________________________________________________________________________
+Bool_t AliTRDdigitizer::SDigits2Digits()
+{
+  //
+  // Merges the input s-digits and converts them to normal digits
+  //
+
+  if (!MergeSDigits()) {
+    return kFALSE;
+  }
+
+  return ConvertSDigits();
+
+}
+
+//_____________________________________________________________________________
+Bool_t AliTRDdigitizer::MergeSDigits()
+{
+  //
+  // Merges the input s-digits:
+  //   - The amplitude of the different inputs are summed up.
+  //   - Of the track IDs from the input dictionaries only one is
+  //     kept for each input. This works for maximal 3 different merged inputs.
+  //
+
+  // Number of track dictionary arrays
+  const Int_t kNDict = AliTRDdigitsManager::kNDict;
+
+  AliTRDSimParam    *simParam    = AliTRDSimParam::Instance();
+  if (!simParam) {
+    AliFatal("Could not get simulation parameters");
+    return kFALSE;
+  }
+  
+  AliTRDcalibDB     *calibration = AliTRDcalibDB::Instance();
+  if (!calibration) {
+    AliFatal("Could not get calibration object");
+    return kFALSE;
+  }
+  
+  Int_t iDict = 0;
+  Int_t jDict = 0;
+
+  AliTRDarraySignal     *digitsA;
+  AliTRDarraySignal     *digitsB;
+  AliTRDarrayDictionary *dictionaryA[kNDict];
+  AliTRDarrayDictionary *dictionaryB[kNDict];
+
+  AliTRDdigitsManager   *mergeSDigitsManager = 0x0;
+  // Get the first s-digits
+  fSDigitsManager = (AliTRDdigitsManager *) fSDigitsManagerList->First();
+  if (!fSDigitsManager) { 
+    AliError("No SDigits manager");
+    return kFALSE;
+  }
+
+  // Loop through the other sets of s-digits
+  mergeSDigitsManager = (AliTRDdigitsManager *) fSDigitsManagerList->After(fSDigitsManager);
+
+  if (mergeSDigitsManager) {
+    AliDebug(1,Form("Merge %d input files.",fSDigitsManagerList->GetSize()));
+  }
+  else {
+    AliDebug(1,"Only one input file.");
+  }
+  
+  Int_t nTimeTotal = calibration->GetNumberOfTimeBins();  
+  Int_t iMerge = 0;
+
+  while (mergeSDigitsManager) {
+
+    iMerge++;
+      
+    // Loop through the detectors
+    for (Int_t iDet = 0; iDet < AliTRDgeometry::Ndet(); iDet++) {
+
+      Int_t nRowMax = fGeo->GetPadPlane(iDet)->GetNrows();
+      Int_t nColMax = fGeo->GetPadPlane(iDet)->GetNcols();
+         
+      // Loop through the pixels of one detector and add the signals
+      digitsA = (AliTRDarraySignal *) fSDigitsManager->GetSDigits(iDet);    
+      digitsB = (AliTRDarraySignal *) mergeSDigitsManager->GetSDigits(iDet); 
+      digitsA->Expand();  
+      if (!digitsA->HasData()) continue;
+      digitsB->Expand();    
+      if (!digitsB->HasData()) continue;
+         
+      for (iDict = 0; iDict < kNDict; iDict++) {
+       dictionaryA[iDict] = (AliTRDarrayDictionary *) fSDigitsManager->GetDictionary(iDet,iDict);
+       dictionaryB[iDict] = (AliTRDarrayDictionary *) mergeSDigitsManager->GetDictionary(iDet,iDict);
+       dictionaryA[iDict]->Expand();  
+        dictionaryB[iDict]->Expand();
+      }
+
+      // Merge only detectors that contain a signal
+      Bool_t doMerge = kTRUE;
+      if (fMergeSignalOnly) {
+        if (digitsA->GetOverThreshold(0) == 0) {                             
+         doMerge = kFALSE;
        }
       }
+         
+      if (doMerge) {
+             
+       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++ ) {
+           for (Int_t iTime = 0; iTime < nTimeTotal; iTime++) {
+               
+             // Add the amplitudes of the summable digits 
+             Float_t ampA = digitsA->GetData(iRow,iCol,iTime);
+             Float_t ampB = digitsB->GetData(iRow,iCol,iTime);
+             ampA += ampB;
+             digitsA->SetData(iRow,iCol,iTime,ampA);
+
+             // Add the mask to the track id if defined.
+             for (iDict = 0; iDict < kNDict; iDict++) {
+               Int_t trackB = dictionaryB[iDict]->GetData(iRow,iCol,iTime);
+               if ((fMasks) && (trackB > 0))  {
+                 for (jDict = 0; jDict < kNDict; jDict++) { 
+                   Int_t trackA = dictionaryA[iDict]->GetData(iRow,iCol,iTime); 
+                   if (trackA == 0) {
+                     trackA = trackB + fMasks[iMerge];
+                     dictionaryA[iDict]->SetData(iRow,iCol,iTime,trackA);  
+                   } // if:  track A == 0
+                 } // for: jDict
+               } // if:  fMasks and trackB > 0
+             } // for: iDict
+
+           } // for: iTime
+         } // for: iCol
+        } // for: iRow
+
+      } // if:  doMerge
+
+      mergeSDigitsManager->RemoveDigits(iDet);
+      mergeSDigitsManager->RemoveDictionaries(iDet);
+  
+      if (fCompress) {
+        digitsA->Compress(0); 
+        for (iDict = 0; iDict < kNDict; iDict++) {                                     
+         dictionaryA[iDict]->Compress();
+        }
+      }
+      
+    } // for: detectors    
+      
+    // The next set of s-digits
+    mergeSDigitsManager = (AliTRDdigitsManager *) fSDigitsManagerList->After(mergeSDigitsManager);
+    
+  } // while: mergeDigitsManagers
+  
+  return kTRUE;
+
+}
+
+//_____________________________________________________________________________
+Bool_t AliTRDdigitizer::ConvertSDigits()
+{
+  //
+  // Converts s-digits to normal digits
+  //
+
+  AliTRDarraySignal *digitsIn = 0x0;
+
+  if (!fSDigitsManager->HasSDigits()) {
+    AliError("No s-digits in digits manager");
+    return kFALSE;
+  }
+
+  // Loop through the detectors
+  for (Int_t det = 0; det < AliTRDgeometry::Ndet(); det++) {
+
+    // Get the merged s-digits (signals)
+    digitsIn = (AliTRDarraySignal *) fSDigitsManager->GetSDigits(det);
+    if (!digitsIn->HasData()) {
+      AliDebug(2,Form("No digits for det=%d",det));
+      continue;
+    }
+    
+    // Convert the merged sdigits to digits
+    if (!Signal2ADC(det,digitsIn)) {
+      continue;
     }
 
-    // Compress the arrays
-    digits->Compress(1,0);
-    for (iDict = 0; iDict < kNDict; iDict++) {
-      dictionary[iDict]->Compress(1,0);
+    // Copy the dictionary information to the output array
+    if (!CopyDictionary(det)) {
+      continue;
     }
 
-    totalSizeDigits += digits->GetSize();
-    totalSizeDict0  += dictionary[0]->GetSize();
-    totalSizeDict1  += dictionary[1]->GetSize();
-    totalSizeDict2  += dictionary[2]->GetSize();
+    // Delete 
+    fSDigitsManager->RemoveDigits(det);
+    fSDigitsManager->RemoveDictionaries(det);
 
-    Float_t nPixel = nRowMax * nColMax * nTimeMax;
-    printf("AliTRDdigitizer::MakeDigits -- ");
-    printf("Found %d digits in detector %d (%3.0f).\n"
-          ,nDigits,iDet
-          ,100.0 * ((Float_t) nDigits) / nPixel);
-    if (fCompress) signals->Compress(1,0);
+    // Compress the arrays
+    CompressOutputArrays(det);
 
-  }
+  } // for: detector numbers
 
-  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);        
+  return kTRUE;
+
+}
 
+//_____________________________________________________________________________
+Bool_t AliTRDdigitizer::CopyDictionary(Int_t det)
+{
+  //
+  // Copies the dictionary information from the s-digits arrays
+  // to the output arrays
+  //
+
+  AliTRDcalibDB     *calibration = AliTRDcalibDB::Instance();
+  if (!calibration) {
+    AliFatal("Could not get calibration object");
+    return kFALSE;
+  }
+
+  AliDebug(1,Form("Start copying dictionaries for detector=%d",det));
+
+  const Int_t kNDict = AliTRDdigitsManager::kNDict;
+  AliTRDarrayDictionary *dictionaryIn[kNDict];
+  AliTRDarrayDictionary *dictionaryOut[kNDict];
+
+  Int_t nRowMax    = fGeo->GetPadPlane(det)->GetNrows();
+  Int_t nColMax    = fGeo->GetPadPlane(det)->GetNcols();
+  Int_t nTimeTotal = calibration->GetNumberOfTimeBins();
+
+  Int_t row  = 0;
+  Int_t col  = 0;
+  Int_t time = 0;
+  Int_t dict = 0;
+
+  for (dict = 0; dict < kNDict; dict++) {
+
+    dictionaryIn[dict]  = (AliTRDarrayDictionary *) fSDigitsManager->GetDictionary(det,dict);
+    dictionaryIn[dict]->Expand();
+    dictionaryOut[dict] = (AliTRDarrayDictionary *) fDigitsManager->GetDictionary(det,dict);
+    dictionaryOut[dict]->Allocate(nRowMax,nColMax,nTimeTotal);
+
+    for (row = 0; row < nRowMax; row++) {
+      for (col = 0; col < nColMax; col++) {
+        for (time = 0; time < nTimeTotal; time++) {
+         Int_t track = dictionaryIn[dict]->GetData(row,col,time);
+         dictionaryOut[dict]->SetData(row,col,time,track);
+       } // for: time
+      } // for: col
+    } // for: row
+    
+  } // for: dictionaries
+  
   return kTRUE;
 
 }
 
 //_____________________________________________________________________________
-Bool_t AliTRDdigitizer::CheckDetector(Int_t plane, Int_t chamber, Int_t sector)
+void AliTRDdigitizer::CompressOutputArrays(Int_t det)
 {
   //
-  // Checks whether a detector is enabled
+  // Compress the output arrays
   //
 
-  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;
+  const Int_t kNDict = AliTRDdigitsManager::kNDict;
+  AliTRDarrayDictionary *dictionary = 0x0;
+
+  if (fCompress) {
+
+    if (!fSDigits) {
+      AliTRDarrayADC *digits = 0x0;  
+      digits = (AliTRDarrayADC *) fDigitsManager->GetDigits(det);
+      digits->Compress();
     }
-    else {
-      if ((sector < sens1) && (sector >= sens2)) return kFALSE;
+
+    if (fSDigits) {
+      AliTRDarraySignal *digits = 0x0; 
+      digits = (AliTRDarraySignal *) fDigitsManager->GetSDigits(det);
+      digits->Compress(0);
     }
-  }
 
-  return kTRUE;
+    for (Int_t dict = 0; dict < kNDict; dict++) {
+      dictionary = (AliTRDarrayDictionary *) fDigitsManager->GetDictionary(det,dict);
+      dictionary->Compress();
+    }
+
+  }
 
 }
 
 //_____________________________________________________________________________
-Bool_t AliTRDdigitizer::WriteDigits()
+Bool_t AliTRDdigitizer::WriteDigits() const
 {
   //
   // Writes out the TRD-digits and the dictionaries
   //
 
-  // Create the branches
-  if (!(gAlice->TreeD()->GetBranch("TRDdigits"))) { 
-    if (!fDigits->MakeBranch()) return kFALSE;
-  }
+  // Write parameters
+  fRunLoader->CdGAFile();
 
   // Store the digits and the dictionary in the tree
-  fDigits->WriteDigits();
-
-  // Write the new tree into the input file (use overwrite option)
-  Char_t treeName[7];
-  sprintf(treeName,"TreeD%d",fEvent);
-  printf("AliTRDdigitizer::WriteDigits -- ");
-  printf("Write the digits tree %s for event %d.\n"
-        ,treeName,fEvent);
-  gAlice->TreeD()->Write(treeName,TObject::kOverwrite);
-  return kTRUE;
+  return fDigitsManager->WriteDigits();
 
 }
 
 //_____________________________________________________________________________
-void AliTRDdigitizer::SetPRF(TF1 *prf)
+void AliTRDdigitizer::InitOutput(Int_t iEvent)
 {
   //
-  // Defines a new pad response function
+  // Initializes the output branches
   //
 
-  if (fPRF) delete fPRF;
-  fPRF = prf;     
+  fEvent = iEvent;
+   
+  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
+    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();
+    }
+  }
+  fDigitsManager->SetEvent(iEvent);
+  fDigitsManager->MakeBranch(tree);
+
+}
+  
 //_____________________________________________________________________________
-void AliTRDdigitizer::SetTRF(TF1 *trf)
+Int_t AliTRDdigitizer::Diffusion(Float_t vdrift, Double_t absdriftlength
+                               , Double_t &lRow, Double_t &lCol, Double_t &lTime)
 {
   //
-  // Defines a new time response function
+  // Applies the diffusion smearing to the position of a single electron.
+  // Depends on absolute drift length.
   //
+  
+  Float_t diffL = 0.0;
+  Float_t diffT = 0.0;
+
+  if (AliTRDCommonParam::Instance()->GetDiffCoeff(diffL,diffT,vdrift)) {
 
-  if (fTRF) delete fTRF;
-  fTRF = trf;     
+    Float_t driftSqrt = TMath::Sqrt(absdriftlength);
+    Float_t sigmaT    = driftSqrt * diffT;
+    Float_t sigmaL    = driftSqrt * diffL;
+    lRow  = gRandom->Gaus(lRow ,sigmaT);
+    lCol  = gRandom->Gaus(lCol ,sigmaT * GetLorentzFactor(vdrift));
+    lTime = gRandom->Gaus(lTime,sigmaL * GetLorentzFactor(vdrift));
+
+    return 1;
+
+  }
+  else {
+
+    return 0;
+
+  }
 
 }
 
 //_____________________________________________________________________________
-Double_t TRFlandau(Double_t *x, Double_t *par)
+Float_t AliTRDdigitizer::GetLorentzFactor(Float_t vd)
+{
+  //
+  // Returns the Lorentz factor
+  //
+
+  Double_t omegaTau      = AliTRDCommonParam::Instance()->GetOmegaTau(vd);
+  Double_t lorentzFactor = 1.0;
+  if (AliTRDCommonParam::Instance()->ExBOn()) {
+    lorentzFactor = 1.0 / (1.0 + omegaTau*omegaTau);
+  }
+
+  return lorentzFactor;
+
+}
+  
+//_____________________________________________________________________________
+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.
+  // Depends on signed drift length.
+  //
 
-  Double_t xx = x[0];
-  Double_t landau = par[0] * TMath::Landau(xx,par[1],par[2]);
+  lCol = lCol 
+       + AliTRDCommonParam::Instance()->GetOmegaTau(vdrift) 
+       * driftlength;
+
+  return 1;
+
+}
 
-  return landau;
+//_____________________________________________________________________________
+void AliTRDdigitizer::RunDigitalProcessing(AliTRDarrayADC *digits, Int_t det)
+{
+  //
+  // Run the digital processing in the TRAP
+  //
+
+  AliTRDfeeParam *feeParam = AliTRDfeeParam::Instance();
+
+  //Create and initialize the mcm object 
+  AliTRDmcmSim* mcmfast = new AliTRDmcmSim(); 
+
+  //Call the methods in the mcm class using the temporary array as input  
+  for(Int_t rob = 0; rob < digits->GetNrow() / 4; rob++)
+  {
+    for(Int_t mcm = 0; mcm < 16; mcm++)
+    {
+      mcmfast->Init(det, rob, mcm); 
+      mcmfast->SetData(digits);
+      mcmfast->Filter();
+      if (feeParam->GetTracklet())
+        mcmfast->Tracklet();
+      mcmfast->ZSMapping();
+      mcmfast->WriteData(digits);
+    }
+  }
 
+  delete mcmfast;
 }