]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - STEER/AliSimulation.cxx
Using the new AliGeomManager functionality
[u/mrichter/AliRoot.git] / STEER / AliSimulation.cxx
index 3f1427952538ba8928466588d07a52e81fb65b9f..0ca530ad38e63e8d03f00d6c280756acbae68e45 100644 (file)
 //                                                                           //
 ///////////////////////////////////////////////////////////////////////////////
 
+#include <TVirtualMCApplication.h>
 #include <TGeoManager.h>
 #include <TObjString.h>
 #include <TStopwatch.h>
 #include "AliCDBStorage.h"
 #include "AliCDBEntry.h"
 #include "AliCDBManager.h"
+#include "AliGeomManager.h"
 #include "AliAlignObj.h"
 #include "AliCentralTrigger.h"
-#include "AliDAQConfig.h"
+#include "AliDAQ.h"
 #include "AliDigitizer.h"
 #include "AliGenerator.h"
 #include "AliLog.h"
 #include "AliVertexGenFile.h"
 #include "AliCentralTrigger.h"
 #include "AliCTPRawData.h"
+#include "AliRawReaderFile.h"
+#include "AliESD.h"
+#include "AliHeader.h"
+#include "AliGenEventHeader.h"
+#include "AliMC.h"
 
 ClassImp(AliSimulation)
 
+AliSimulation *AliSimulation::fgInstance = 0;
 
 //_____________________________________________________________________________
 AliSimulation::AliSimulation(const char* configFileName, const char* cdbUri,
@@ -140,7 +148,7 @@ AliSimulation::AliSimulation(const char* configFileName, const char* cdbUri,
   fRunGeneration(kTRUE),
   fRunSimulation(kTRUE),
   fLoadAlignFromCDB(kTRUE),
-  fLoadAlignData("ALL"),
+  fLoadAlObjsListOfDets("ALL"),
   fMakeSDigits("ALL"),
   fMakeDigits("ALL"),
   fMakeTrigger(""),
@@ -158,10 +166,12 @@ AliSimulation::AliSimulation(const char* configFileName, const char* cdbUri,
   fAlignObjArray(NULL),
   fUseBkgrdVertex(kTRUE),
   fRegionOfInterest(kFALSE),
-  fCDBUri(cdbUri)
+  fCDBUri(cdbUri),
+  fSpecCDBUri(),
+  fEmbeddingFlag(kFALSE)
 {
 // create simulation object with default parameters
-
+  fgInstance = this;
   SetGAliceFile("galice.root");
 }
 
@@ -172,7 +182,7 @@ AliSimulation::AliSimulation(const AliSimulation& sim) :
   fRunGeneration(sim.fRunGeneration),
   fRunSimulation(sim.fRunSimulation),
   fLoadAlignFromCDB(sim.fLoadAlignFromCDB),
-  fLoadAlignData(sim.fLoadAlignData),
+  fLoadAlObjsListOfDets(sim.fLoadAlObjsListOfDets),
   fMakeSDigits(sim.fMakeSDigits),
   fMakeDigits(sim.fMakeDigits),
   fMakeTrigger(sim.fMakeTrigger),
@@ -190,7 +200,9 @@ AliSimulation::AliSimulation(const AliSimulation& sim) :
   fAlignObjArray(NULL),
   fUseBkgrdVertex(sim.fUseBkgrdVertex),
   fRegionOfInterest(sim.fRegionOfInterest),
-  fCDBUri(sim.fCDBUri)
+  fCDBUri(sim.fCDBUri),
+  fSpecCDBUri(),
+  fEmbeddingFlag(sim.fEmbeddingFlag)
 {
 // copy constructor
 
@@ -204,6 +216,11 @@ AliSimulation::AliSimulation(const AliSimulation& sim) :
     if (!sim.fBkgrdFileNames->At(i)) continue;
     fBkgrdFileNames->Add(sim.fBkgrdFileNames->At(i)->Clone());
   }
+
+  for (Int_t i = 0; i < sim.fSpecCDBUri.GetEntriesFast(); i++) {
+    if (sim.fSpecCDBUri[i]) fSpecCDBUri.Add(sim.fSpecCDBUri[i]->Clone());
+  }
+  fgInstance = this;
 }
 
 //_____________________________________________________________________________
@@ -229,6 +246,9 @@ AliSimulation::~AliSimulation()
     fBkgrdFileNames->Delete();
     delete fBkgrdFileNames;
   }
+
+  fSpecCDBUri.Delete();
+  if (fgInstance==this) fgInstance = 0;
 }
 
 
@@ -241,37 +261,63 @@ void AliSimulation::SetNumberOfEvents(Int_t nEvents)
 }
 
 //_____________________________________________________________________________
-void AliSimulation::InitCDBStorage(const char* uri)
+void AliSimulation::InitCDBStorage()
 {
 // activate a default CDB storage
 // First check if we have any CDB storage set, because it is used 
 // to retrieve the calibration and alignment constants
 
   AliCDBManager* man = AliCDBManager::Instance();
-  if (!man->IsDefaultStorageSet())
+  if (man->IsDefaultStorageSet())
   {
-    AliWarningClass("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
-    AliWarningClass("Default CDB storage not yet set");
-    AliWarningClass(Form("Using default storage declared in AliSimulation: %s",uri));
-    AliWarningClass("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
-    SetDefaultStorage(uri);
-  }  
-  
+    AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
+    AliWarning("Default CDB storage has been already set !");
+    AliWarning(Form("Ignoring the default storage declared in AliReconstruction: %s",fCDBUri.Data()));
+    AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
+    fCDBUri = "";
+  }
+  else {
+    AliDebug(2,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
+    AliDebug(2, Form("Default CDB storage is set to: %s",fCDBUri.Data()));
+    AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
+    man->SetDefaultStorage(fCDBUri);
+  }
+
+  // Now activate the detector specific CDB storage locations
+  for (Int_t i = 0; i < fSpecCDBUri.GetEntriesFast(); i++) {
+    TObject* obj = fSpecCDBUri[i];
+    if (!obj) continue;
+    AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
+    AliDebug(2, Form("Specific CDB storage for %s is set to: %s",obj->GetName(),obj->GetTitle()));
+    AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
+    man->SetSpecificStorage(obj->GetName(), obj->GetTitle());
+  }
+  man->Print();
 }
 
 //_____________________________________________________________________________
 void AliSimulation::SetDefaultStorage(const char* uri) {
-// activate a default CDB storage 
+// Store the desired default CDB storage location
+// Activate it later within the Run() method
 
-   AliCDBManager::Instance()->SetDefaultStorage(uri);
+  fCDBUri = uri;
 
 }
 
 //_____________________________________________________________________________
-void AliSimulation::SetSpecificStorage(const char* detName, const char* uri) {
-// activate a detector-specific CDB storage 
+void AliSimulation::SetSpecificStorage(const char* calibType, const char* uri) {
+// Store a detector-specific CDB storage location
+// Activate it later within the Run() method
+
+  AliCDBPath aPath(calibType);
+  if(!aPath.IsValid()){
+       AliError(Form("Not a valid path: %s", calibType));
+       return;
+  }
 
-   AliCDBManager::Instance()->SetSpecificStorage(detName, uri);
+  TObject* obj = fSpecCDBUri.FindObject(calibType);
+  if (obj) fSpecCDBUri.Remove(obj);
+  fSpecCDBUri.Add(new TNamed(calibType, uri));
 
 }
 
@@ -312,149 +358,6 @@ void AliSimulation::SetEventsPerFile(const char* detector, const char* type,
   fEventsPerFile.Add(obj);
 }
 
-//_____________________________________________________________________________
-Bool_t AliSimulation::ApplyAlignObjsToGeom(TObjArray* alObjArray)
-{
-  // Read collection of alignment objects (AliAlignObj derived) saved
-  // in the TClonesArray ClArrayName and apply them to the geometry
-  // manager singleton.
-  //
-  alObjArray->Sort();
-  Int_t nvols = alObjArray->GetEntriesFast();
-
-  Bool_t flag = kTRUE;
-
-  for(Int_t j=0; j<nvols; j++)
-    {
-      AliAlignObj* alobj = (AliAlignObj*) alObjArray->UncheckedAt(j);
-      if (alobj->ApplyToGeometry() == kFALSE) flag = kFALSE;
-    }
-
-  if (AliDebugLevelClass() >= 1) {
-    gGeoManager->CheckOverlaps(20);
-    TObjArray* ovexlist = gGeoManager->GetListOfOverlaps();
-    if(ovexlist->GetEntriesFast()){  
-      AliError("The application of alignment objects to the geometry caused huge overlaps/extrusions!");
-   }
-  }
-
-  return flag;
-
-}
-
-//_____________________________________________________________________________
-Bool_t AliSimulation::ApplyAlignObjsToGeom(const char* fileName, const char* clArrayName)
-{
-  // read collection of alignment objects (AliAlignObj derived) saved
-  // in the TClonesArray ClArrayName in the file fileName and apply
-  // them to the TGeo geometry passed as argument
-  //
-
-  TFile* inFile = TFile::Open(fileName,"READ");
-  if (!inFile || !inFile->IsOpen()) {
-    AliErrorClass(Form("Could not open file %s !",fileName));
-    return kFALSE;
-  }
-
-  TClonesArray* alObjArray = ((TClonesArray*) inFile->Get(clArrayName));
-  inFile->Close();
-  if (!alObjArray) {
-    AliErrorClass(Form("Could not get array (%s) from file (%s) !",clArrayName,fileName));
-    return kFALSE;
-  }
-
-  return ApplyAlignObjsToGeom(alObjArray);
-
-}
-
-//_____________________________________________________________________________
-Bool_t AliSimulation::ApplyAlignObjsToGeom(AliCDBParam* param, AliCDBId& Id)
-{
-  // read collection of alignment objects (AliAlignObj derived) saved
-  // in the TClonesArray ClArrayName in the AliCDBEntry identified by
-  // param (to get the AliCDBStorage) and Id; apply the alignment objects
-  // to the TGeo geometry passed as argument
-  //
-
-  AliCDBStorage* storage = AliCDBManager::Instance()->GetStorage(param);
-  AliCDBEntry* entry = storage->Get(Id);
-  TClonesArray* AlObjArray = ((TClonesArray*) entry->GetObject());
-
-  return ApplyAlignObjsToGeom(AlObjArray);
-
-}
-
-//_____________________________________________________________________________
-Bool_t AliSimulation::ApplyAlignObjsToGeom(const char* uri, const char* path, Int_t runnum, Int_t version, Int_t sversion)
-{
-  // read collection of alignment objects (AliAlignObj derived) saved
-  // in the TClonesArray ClArrayName in the AliCDBEntry identified by
-  // param (to get the AliCDBStorage) and Id; apply the alignment objects
-  // to the TGeo geometry passed as argument
-  //
-
-  AliCDBParam* param = AliCDBManager::Instance()->CreateParameter(uri);
-  AliCDBId id(path, runnum, runnum, version, sversion);
-
-  return ApplyAlignObjsToGeom(param, id);
-
-}
-
-//_____________________________________________________________________________
-Bool_t AliSimulation::ApplyAlignObjsToGeom(const char* detName, Int_t runnum, Int_t version, Int_t sversion)
-{
-  // read collection of alignment objects (AliAlignObj derived) saved
-  // in the TClonesArray ClArrayName in the AliCDBEntry identified by
-  // param (to get the AliCDBStorage) and Id; apply the alignment objects
-  // to the TGeo geometry passed as argument
-  //
-
-  InitCDBStorage("local://$ALICE_ROOT");
-  AliCDBPath path(detName,"Align","Data");
-  AliCDBEntry* entry = AliCDBManager::Instance()->Get(path.GetPath(),runnum,version,sversion);
-
-  if(!entry) return kFALSE;
-  TClonesArray* AlObjArray = ((TClonesArray*) entry->GetObject());
-
-  return ApplyAlignObjsToGeom(AlObjArray);
-}
-
-//_____________________________________________________________________________
-Bool_t AliSimulation::SetAlignObjArraySingleDet(const char* detName)
-{
-  // Fills array of single detector's alignable objects from CDB
-  
-  AliDebug(2, Form("Loading alignment data for detector: %s",detName));
-  
-  AliCDBEntry *entry;
-       
-  AliCDBPath path(detName,"Align","Data");
-       
-  entry=AliCDBManager::Instance()->Get(path.GetPath());
-  if(!entry){ 
-       AliDebug(2,Form("Couldn't load alignment data for detector %s",detName));
-       return kFALSE;
-  }
-  entry->SetOwner(1);
-  TClonesArray *alignArray = (TClonesArray*) entry->GetObject();       
-  alignArray->SetOwner(0);
-  AliDebug(2,Form("Found %d alignment objects for %s",
-                       alignArray->GetEntries(),detName));
-
-  AliAlignObj *alignObj=0;
-  TIter iter(alignArray);
-       
-  // loop over align objects in detector
-  while( ( alignObj=(AliAlignObj *) iter.Next() ) ){
-       fAlignObjArray->Add(alignObj);
-  }
-  // delete entry --- Don't delete, it is cached!
-       
-  AliDebug(2, Form("fAlignObjArray entries: %d",fAlignObjArray->GetEntries() ));
-  return kTRUE;
-
-}
-
 //_____________________________________________________________________________
 Bool_t AliSimulation::MisalignGeometry(AliRunLoader *runLoader)
 {
@@ -466,6 +369,10 @@ Bool_t AliSimulation::MisalignGeometry(AliRunLoader *runLoader)
   // then applied to the TGeo geometry.
   // Finally an overlaps check is performed.
 
+  if (!gGeoManager || !gGeoManager->IsClosed()) {
+    AliError("Can't apply the misalignment! gGeoManager doesn't exist or it is still opened!");
+    return kFALSE;
+  }  
   Bool_t delRunLoader = kFALSE;
   if (!runLoader) {
     runLoader = LoadRun("READ");
@@ -473,60 +380,53 @@ Bool_t AliSimulation::MisalignGeometry(AliRunLoader *runLoader)
     delRunLoader = kTRUE;
   }
 
-  // Load alignment data from CDB and fill fAlignObjArray 
+  // Export ideal geometry 
+  gGeoManager->Export("geometry.root");
+
+  // Load alignment data from CDB and apply to geometry through AliGeomManager
   if(fLoadAlignFromCDB){
-       if(!fAlignObjArray) fAlignObjArray = new TObjArray();
-       
-       //fAlignObjArray->RemoveAll(); 
-       fAlignObjArray->Clear();        
-       fAlignObjArray->SetOwner(0);
-       TString detStr = fLoadAlignData;
-       TString dataNotLoaded="";
-       TString dataLoaded="";
-  
-       TObjArray* detArray = runLoader->GetAliRun()->Detectors();
-       for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
-               AliModule* det = (AliModule*) detArray->At(iDet);
-               if (!det || !det->IsActive()) continue;
-               if (IsSelected(det->GetName(), detStr)) {
-                       if(!SetAlignObjArraySingleDet(det->GetName())){
-                               dataNotLoaded += det->GetName();
-                               dataNotLoaded += " ";
-                       } else {
-                               dataLoaded += det->GetName();
-                               dataLoaded += " ";
-                       }
-               }
-       } // end loop over detectors
-  
-       if ((detStr.CompareTo("ALL") == 0)) detStr = "";
-       dataNotLoaded += detStr;
-       AliInfo(Form("Alignment data loaded for: %s",
-                         dataLoaded.Data()));
-       AliInfo(Form("Didn't/couldn't load alignment data for: %s",
-                         dataNotLoaded.Data()));
-  } // fLoadAlignFromCDB flag
-  // Check if the array with alignment objects was
-  // provided by the user. If yes, apply the objects
-  // to the present TGeo geometry
-  if (fAlignObjArray) {
-    if (gGeoManager && gGeoManager->IsClosed()) {
-      if (ApplyAlignObjsToGeom(fAlignObjArray) == kFALSE) {
-       AliError("The misalignment of one or more volumes failed!"
-                "Compare the list of simulated detectors and the list of detector alignment data!");
-       if (delRunLoader) delete runLoader;
-       return kFALSE;
+    
+    TString detStr = fLoadAlObjsListOfDets;
+    TString loadAlObjsListOfDets = "";
+    
+    TObjArray* detArray = runLoader->GetAliRun()->Detectors();
+    for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
+      AliModule* det = (AliModule*) detArray->At(iDet);
+      if (!det || !det->IsActive()) continue;
+      if (IsSelected(det->GetName(), detStr)) {
+        //add det to list of dets to be aligned from CDB
+        loadAlObjsListOfDets += det->GetName();
+        loadAlObjsListOfDets += " ";
+      }
+    } // end loop over detectors
+    AliGeomManager::ApplyAlignObjsFromCDB(loadAlObjsListOfDets.Data());
+  }else{
+    // Check if the array with alignment objects was
+    // provided by the user. If yes, apply the objects
+    // to the present TGeo geometry
+    if (fAlignObjArray) {
+      if (AliGeomManager::ApplyAlignObjsToGeom(*fAlignObjArray) == kFALSE) {
+        AliError("The misalignment of one or more volumes failed!"
+                 "Compare the list of simulated detectors and the list of detector alignment data!");
+        if (delRunLoader) delete runLoader;
+        return kFALSE;
       }
-    }
-    else {
-      AliError("Can't apply the misalignment! gGeoManager doesn't exist or it is still opened!");
-      if (delRunLoader) delete runLoader;
-      return kFALSE;
     }
   }
 
+  // Update the internal geometry of modules (ITS needs it)
+  TString detStr = fLoadAlObjsListOfDets;
+  TObjArray* detArray = runLoader->GetAliRun()->Detectors();
+  for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
+
+    AliModule* det = (AliModule*) detArray->At(iDet);
+    if (!det || !det->IsActive()) continue;
+    if (IsSelected(det->GetName(), detStr)) {
+      det->UpdateInternalGeometry();
+    }
+  } // end loop over detectors
+
+
   if (delRunLoader) delete runLoader;
 
   return kTRUE;
@@ -562,13 +462,19 @@ void AliSimulation::MergeWith(const char* fileName, Int_t nSignalPerBkgrd)
   fBkgrdFileNames->Add(fileNameStr);
 }
 
+void AliSimulation::EmbedInto(const char* fileName, Int_t nSignalPerBkgrd)
+{
+// add a file with background events for embeddin
+  MergeWith(fileName, nSignalPerBkgrd);
+  fEmbeddingFlag = kTRUE;
+}
 
 //_____________________________________________________________________________
 Bool_t AliSimulation::Run(Int_t nEvents)
 {
 // run the generation, simulation and digitization
 
-  InitCDBStorage(fCDBUri);
+  InitCDBStorage();
 
   if (nEvents > 0) fNEvents = nEvents;
 
@@ -580,11 +486,12 @@ Bool_t AliSimulation::Run(Int_t nEvents)
   // Set run number in CDBManager (if it is not already set in RunSimulation)
   if (!SetRunNumber()) if (fStopOnError) return kFALSE;
 
-  // Load and misalign the geometry
+  // If RunSimulation was not called, load the geometry and misalign it
   if (!gGeoManager) {
-    TGeoManager::Import("geometry.root");
+    AliGeomManager::LoadGeometry("geometry.root");
     if (!gGeoManager) if (fStopOnError) return kFALSE;
-    if (!MisalignGeometry()) if (fStopOnError) return kFALSE;
+    // Initialize the geometry manager (if not already done)
+    if(!MisalignGeometry()) if (fStopOnError) return kFALSE;
   }
 
   // hits -> summable digits
@@ -650,7 +557,7 @@ Bool_t AliSimulation::RunTrigger(const char* descriptors)
      }
    }
 
-   runLoader->MakeTree( "CT" );
+   runLoader->MakeTree( "GG" );
    AliCentralTrigger* aCTP = runLoader->GetTrigger();
   // Load Descriptors
    aCTP->LoadDescriptor( des );
@@ -717,7 +624,6 @@ Bool_t AliSimulation::RunSimulation(Int_t nEvents)
     gAlice->SetTriggerDescriptor(fMakeTrigger.Data());
 
   // Set run number in CDBManager
-  AliCDBManager::Instance()->SetRun(gAlice->GetRunNumber());
   AliInfo(Form("Run number: %d",AliCDBManager::Instance()->GetRun()));
 
   AliRunLoader* runLoader = gAlice->GetRunLoader();
@@ -728,33 +634,10 @@ Bool_t AliSimulation::RunSimulation(Int_t nEvents)
   }
   SetGAliceFile(runLoader->GetFileName());
  
-  // Export ideal geometry 
-  if (gGeoManager) gGeoManager->Export("geometry.root");
-
   // Misalign geometry
-//   if (!MisalignGeometry(runLoader)) {
-//     delete runLoader;
-//     return kFALSE;
-//   }
+#if ROOT_VERSION_CODE < 331527
   MisalignGeometry(runLoader);
-
-  // Temporary fix by A.Gheata
-  // Could be removed with the next Root version (>5.11)
-  if (gGeoManager) {
-    TIter next(gGeoManager->GetListOfVolumes());
-    TGeoVolume *vol;
-    while ((vol = (TGeoVolume *)next())) {
-      if (vol->GetVoxels()) {
-       if (vol->GetVoxels()->NeedRebuild()) {
-         vol->GetVoxels()->Voxelize();
-         vol->FindOverlaps();
-       }
-      }
-    }
-  }
-
-  // Export (mis)aligned geometry 
-  if (gGeoManager) gGeoManager->Export("misaligned_geometry.root");
+#endif
 
 //   AliRunLoader* runLoader = gAlice->GetRunLoader();
 //   if (!runLoader) {
@@ -886,6 +769,7 @@ Bool_t AliSimulation::RunDigitization(const char* detectors,
   if (fBkgrdFileNames) nStreams = fBkgrdFileNames->GetEntriesFast() + 1;
   Int_t signalPerBkgrd = GetNSignalPerBkgrd();
   AliRunDigitizer* manager = new AliRunDigitizer(nStreams, signalPerBkgrd);
+  // manager->SetEmbeddingFlag(fEmbeddingFlag);
   manager->SetInputStream(0, fGAliceFileName.Data());
   for (Int_t iStream = 1; iStream < nStreams; iStream++) {
     const char* fileName = ((TObjString*)
@@ -905,6 +789,7 @@ Bool_t AliSimulation::RunDigitization(const char* detectors,
     if (IsSelected(det->GetName(), detStr) && 
        !IsSelected(det->GetName(), detExcl)) {
       AliDigitizer* digitizer = det->CreateDigitizer(manager);
+      
       if (!digitizer) {
        AliError(Form("no digitizer for %s", det->GetName()));
        if (fStopOnError) return kFALSE;
@@ -1090,7 +975,9 @@ Bool_t AliSimulation::ConvertRawFilesToDate(const char* dateFileName)
 
   AliInfo(Form("converting raw data DDL files to DATE file %s", dateFileName));
   char command[256];
-  sprintf(command, "dateStream -D -o %s -# %d -C", 
+  // Note the option -s. It is used in order to avoid
+  // the generation of SOR/EOR events.
+  sprintf(command, "dateStream -s -D -o %s -# %d -C", 
          dateFileName, runLoader->GetNumberOfEvents());
   FILE* pipe = gSystem->OpenPipe(command, "w");
 
@@ -1100,16 +987,16 @@ Bool_t AliSimulation::ConvertRawFilesToDate(const char* dateFileName)
     Int_t prevLDC = -1;
 
     // loop over detectors and DDLs
-    for (Int_t iDet = 0; iDet < kNDetectors; iDet++) {
-      for (Int_t iDDL = 0; iDDL < kDetectorDDLs[iDet]; iDDL++) {
+    for (Int_t iDet = 0; iDet < AliDAQ::kNDetectors; iDet++) {
+      for (Int_t iDDL = 0; iDDL < AliDAQ::NumberOfDdls(iDet); iDDL++) {
 
-        Int_t ddlID = 0x100*iDet + iDDL;
+        Int_t ddlID = AliDAQ::DdlID(iDet,iDDL);
         Int_t ldcID = Int_t(ldc + 0.0001);
-        ldc += kDetectorLDCs[iDet] / kDetectorDDLs[iDet];
+        ldc += AliDAQ::NumberOfLdcs(iDet) / AliDAQ::NumberOfDdls(iDet);
 
         char rawFileName[256];
-        sprintf(rawFileName, "raw%d/%s_%d.ddl", 
-                iEvent, kDetectors[iDet], ddlID);
+        sprintf(rawFileName, "raw%d/%s", 
+                iEvent, AliDAQ::DdlFileName(iDet,iDDL));
 
        // check existence and size of raw data file
         FILE* file = fopen(rawFileName, "rb");
@@ -1141,10 +1028,10 @@ Bool_t AliSimulation::ConvertDateToRoot(const char* dateFileName,
 // convert a DATE file to a root file with the program "alimdc"
 
   // ALIMDC setup
-  const Int_t kDBSize = 1000000000;
+  const Int_t kDBSize = 2000000000;
   const Int_t kTagDBSize = 1000000000;
   const Bool_t kFilter = kFALSE;
-  const Int_t kCompression = 1;
+  const Int_t kCompression = 0;
 
   char* path = gSystem->Which(gSystem->Getenv("PATH"), "alimdc");
   if (!path) {
@@ -1159,7 +1046,6 @@ Bool_t AliSimulation::ConvertDateToRoot(const char* dateFileName,
 
   const char* rawDBFS[2] = { "/tmp/mdc1", "/tmp/mdc2" };
   const char* tagDBFS    = "/tmp/mdc1/tags";
-  const char* runDBFS    = "/tmp/mdc1/meta";
 
   // User defined file system locations
   if (gSystem->Getenv("ALIMDC_RAWDB1")) 
@@ -1168,18 +1054,14 @@ Bool_t AliSimulation::ConvertDateToRoot(const char* dateFileName,
     rawDBFS[1] = gSystem->Getenv("ALIMDC_RAWDB2");
   if (gSystem->Getenv("ALIMDC_TAGDB")) 
     tagDBFS = gSystem->Getenv("ALIMDC_TAGDB");
-  if (gSystem->Getenv("ALIMDC_RUNDB")) 
-    runDBFS = gSystem->Getenv("ALIMDC_RUNDB");
 
   gSystem->Exec(Form("rm -rf %s",rawDBFS[0]));
   gSystem->Exec(Form("rm -rf %s",rawDBFS[1]));
   gSystem->Exec(Form("rm -rf %s",tagDBFS));
-  gSystem->Exec(Form("rm -rf %s",runDBFS));
 
   gSystem->Exec(Form("mkdir %s",rawDBFS[0]));
   gSystem->Exec(Form("mkdir %s",rawDBFS[1]));
   gSystem->Exec(Form("mkdir %s",tagDBFS));
-  gSystem->Exec(Form("mkdir %s",runDBFS));
 
   Int_t result = gSystem->Exec(Form("alimdc %d %d %d %d %s", 
                                    kDBSize, kTagDBSize, kFilter, kCompression, dateFileName));
@@ -1188,7 +1070,6 @@ Bool_t AliSimulation::ConvertDateToRoot(const char* dateFileName,
   gSystem->Exec(Form("rm -rf %s",rawDBFS[0]));
   gSystem->Exec(Form("rm -rf %s",rawDBFS[1]));
   gSystem->Exec(Form("rm -rf %s",tagDBFS));
-  gSystem->Exec(Form("rm -rf %s",runDBFS));
 
   return (result == 0);
 }
@@ -1229,8 +1110,9 @@ Int_t AliSimulation::GetNSignalPerBkgrd(Int_t nEvents) const
   // get the number of signal events
   if (nEvents <= 0) {
     AliRunLoader* runLoader = 
-      AliRunLoader::Open(fGAliceFileName.Data(), "SIGNAL");
+       AliRunLoader::Open(fGAliceFileName.Data(), "SIGNAL");
     if (!runLoader) return 1;
+    
     nEvents = runLoader->GetNumberOfEvents();
     delete runLoader;
   }
@@ -1240,12 +1122,12 @@ Int_t AliSimulation::GetNSignalPerBkgrd(Int_t nEvents) const
     // get the number of background events
     const char* fileName = ((TObjString*)
                            (fBkgrdFileNames->At(iBkgrdFile)))->GetName();
-    AliRunLoader* runLoader = 
+    AliRunLoader* runLoader =
       AliRunLoader::Open(fileName, "BKGRD");
     if (!runLoader) continue;
     Int_t nBkgrdEvents = runLoader->GetNumberOfEvents();
     delete runLoader;
-
+  
     // get or calculate the number of signal per background events
     Int_t nSignalPerBkgrd = fBkgrdFileNames->At(iBkgrdFile)->GetUniqueID();
     if (nSignalPerBkgrd <= 0) {
@@ -1300,3 +1182,104 @@ Bool_t AliSimulation::IsSelected(TString detName, TString& detectors) const
 
   return result;
 }
+
+Bool_t AliSimulation::ConvertRaw2SDigits(const char* rawDirectory, const char* esdFileName) 
+{
+//
+// Steering routine  to convert raw data in directory rawDirectory/ to fake SDigits. 
+// These can be used for embedding of MC tracks into RAW data using the standard 
+// merging procedure.
+//
+// If an ESD file is given the reconstructed vertex is taken from it and stored in the event header.
+//
+    if (!gAlice) {
+       AliError("no gAlice object. Restart aliroot and try again.");
+       return kFALSE;
+    }
+    if (gAlice->Modules()->GetEntries() > 0) {
+       AliError("gAlice was already run. Restart aliroot and try again.");
+       return kFALSE;
+    }
+    
+    AliInfo(Form("initializing gAlice with config file %s",fConfigFileName.Data()));
+    StdoutToAliInfo(StderrToAliError(gAlice->Init(fConfigFileName.Data());););
+//
+//  Initialize CDB     
+    InitCDBStorage();
+    AliCDBManager* man = AliCDBManager::Instance();
+    man->SetRun(0); // Should this come from rawdata header ?
+    
+    Int_t iDet;
+    //
+    // Get the runloader
+    AliRunLoader* runLoader = gAlice->GetRunLoader();
+    //
+    // Open esd file if available
+    TFile* esdFile = TFile::Open(esdFileName);
+    Bool_t esdOK = (esdFile != 0);
+    AliESD* esd = new AliESD;
+    TTree* treeESD = 0;
+    if (esdOK) {
+       treeESD = (TTree*) esdFile->Get("esdTree");
+       if (!treeESD) {
+           AliWarning("No ESD tree found");
+           esdOK = kFALSE;
+       } else {
+           treeESD->SetBranchAddress("ESD", &esd);
+       }
+    }
+    //
+    // Create the RawReader
+    AliRawReaderFile* rawReader = new AliRawReaderFile(rawDirectory);
+    //
+    // Get list of detectors
+    TObjArray* detArray = runLoader->GetAliRun()->Detectors();
+    //
+    // Get Header
+    AliHeader* header = runLoader->GetHeader();
+    //
+    // Event loop
+    Int_t nev = 0;
+    while(kTRUE) {
+       if (!(rawReader->NextEvent())) break;
+       //
+       // Detector loop
+       for (iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
+           AliModule* det = (AliModule*) detArray->At(iDet);
+           AliInfo(Form("Calling Raw2SDigits for %s\n", det->GetName()));
+           det->Raw2SDigits(rawReader);
+           rawReader->Reset();
+       } // detectors
+
+       //
+       //  If ESD information available obtain reconstructed vertex and store in header.
+       if (esdOK) {
+           treeESD->GetEvent(nev);
+           const AliESDVertex* esdVertex = esd->GetPrimaryVertex();
+           Double_t position[3];
+           esdVertex->GetXYZ(position);
+           AliGenEventHeader* mcHeader = new  AliGenEventHeader("ESD");
+           TArrayF mcV;
+           mcV.Set(3);
+           for (Int_t i = 0; i < 3; i++) mcV[i] = position[i];
+           mcHeader->SetPrimaryVertex(mcV);
+           header->Reset(0,nev);
+           header->SetGenEventHeader(mcHeader);
+           printf("***** Saved vertex %f %f %f \n", position[0], position[1], position[2]);
+       }
+       nev++;
+//
+//      Finish the event
+       runLoader->TreeE()->Fill();
+       runLoader->SetNextEvent();
+    } // events
+    delete rawReader;
+//
+//  Finish the run 
+    runLoader->CdGAFile();
+    runLoader->WriteHeader("OVERWRITE");
+    runLoader->WriteRunLoader();
+
+    return kTRUE;
+}