]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - STEER/AliSimulation.cxx
Set beam energy in GRP object to energy per charge.
[u/mrichter/AliRoot.git] / STEER / AliSimulation.cxx
index 0887a7bb3639c8a37c5dd9f2874878460fca4678..ca5b3a6948c6a5f793618bbb2a89ef1ca7009a8b 100644 (file)
 //                                                                           //
 ///////////////////////////////////////////////////////////////////////////////
 
-#include <TVirtualMCApplication.h>
+#include <TCint.h>
+#include <TFile.h>
+#include <TGeoGlobalMagField.h>
 #include <TGeoManager.h>
 #include <TObjString.h>
+#include <TROOT.h>
 #include <TSystem.h>
-#include <TFile.h>
+#include <TVirtualMC.h>
+#include <TVirtualMCApplication.h>
+#include <TDatime.h>
 
-#include "AliCodeTimer.h"
-#include "AliCDBStorage.h"
+#include "AliAlignObj.h"
 #include "AliCDBEntry.h"
 #include "AliCDBManager.h"
-#include "AliGeomManager.h"
-#include "AliAlignObj.h"
+#include "AliGRPManager.h"
+#include "AliCDBStorage.h"
+#include "AliCTPRawData.h"
+#include "AliCentralTrigger.h"
 #include "AliCentralTrigger.h"
+#include "AliCodeTimer.h"
 #include "AliDAQ.h"
 #include "AliDigitizer.h"
+#include "AliESDEvent.h"
+#include "AliGRPObject.h"
+#include "AliGenEventHeader.h"
 #include "AliGenerator.h"
+#include "AliGeomManager.h"
+#include "AliHLTSimulation.h"
+#include "AliHeader.h"
+#include "AliLego.h"
+#include "AliLegoGenerator.h"
 #include "AliLog.h"
+#include "AliMC.h"
+#include "AliMagF.h"
 #include "AliModule.h"
+#include "AliPDG.h"
+#include "AliRawReaderDate.h"
+#include "AliRawReaderFile.h"
+#include "AliRawReaderRoot.h"
 #include "AliRun.h"
 #include "AliRunDigitizer.h"
 #include "AliRunLoader.h"
 #include "AliSimulation.h"
-#include "AliVertexGenFile.h"
-#include "AliCentralTrigger.h"
-#include "AliCTPRawData.h"
-#include "AliRawReaderFile.h"
-#include "AliRawReaderRoot.h"
-#include "AliRawReaderDate.h"
-#include "AliESD.h"
-#include "AliHeader.h"
-#include "AliGenEventHeader.h"
-#include "AliMC.h"
-#include "AliHLTSimulation.h"
-#include "AliQADataMakerSteer.h"
 #include "AliSysInfo.h"
+#include "AliVertexGenFile.h"
 
 ClassImp(AliSimulation)
 
@@ -157,14 +167,13 @@ AliSimulation::AliSimulation(const char* configFileName,
   fLoadAlObjsListOfDets("ALL"),
   fMakeSDigits("ALL"),
   fMakeDigits("ALL"),
-  fMakeTrigger(""),
+  fTriggerConfig(""),
   fMakeDigitsFromHits(""),
   fWriteRawData(""),
   fRawDataFileName(""),
   fDeleteIntermediateFiles(kFALSE),
   fWriteSelRawData(kFALSE),
   fStopOnError(kFALSE),
-
   fNEvents(1),
   fConfigFileName(configFileName),
   fGAliceFileName("galice.root"),
@@ -174,6 +183,7 @@ AliSimulation::AliSimulation(const char* configFileName,
   fUseBkgrdVertex(kTRUE),
   fRegionOfInterest(kFALSE),
   fCDBUri(""),
+  fQARefUri(""), 
   fSpecCDBUri(),
   fRun(-1),
   fSeed(0),
@@ -181,90 +191,30 @@ AliSimulation::AliSimulation(const char* configFileName,
   fInitRunNumberCalled(kFALSE),
   fSetRunNumberFromDataCalled(kFALSE),
   fEmbeddingFlag(kFALSE),
+  fLego(NULL),
+  fKey(0),
+  fUseVertexFromCDB(0),
+  fUseMagFieldFromGRP(0),
+  fGRPWriteLocation(Form("local://%s", gSystem->pwd())),
   fQADetectors("ALL"),                  
   fQATasks("ALL"),     
   fRunQA(kTRUE), 
-  fRunHLT("default")
+  fEventSpecie(AliRecoParam::kDefault),
+  fWriteQAExpertData(kTRUE), 
+  fGeometryFile(),
+  fRunHLT("default"),
+  fpHLT(NULL),
+  fWriteGRPEntry(kTRUE)
 {
 // create simulation object with default parameters
   fgInstance = this;
   SetGAliceFile("galice.root");
   
 // for QA
-   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) 
-       fQACycles[iDet] = 999999;
-}
-
-//_____________________________________________________________________________
-AliSimulation::AliSimulation(const AliSimulation& sim) :
-  TNamed(sim),
-
-  fRunGeneration(sim.fRunGeneration),
-  fRunSimulation(sim.fRunSimulation),
-  fLoadAlignFromCDB(sim.fLoadAlignFromCDB),
-  fLoadAlObjsListOfDets(sim.fLoadAlObjsListOfDets),
-  fMakeSDigits(sim.fMakeSDigits),
-  fMakeDigits(sim.fMakeDigits),
-  fMakeTrigger(sim.fMakeTrigger),
-  fMakeDigitsFromHits(sim.fMakeDigitsFromHits),
-  fWriteRawData(sim.fWriteRawData),
-  fRawDataFileName(""),
-  fDeleteIntermediateFiles(kFALSE),
-  fWriteSelRawData(kFALSE),
-  fStopOnError(sim.fStopOnError),
-
-  fNEvents(sim.fNEvents),
-  fConfigFileName(sim.fConfigFileName),
-  fGAliceFileName(sim.fGAliceFileName),
-  fEventsPerFile(),
-  fBkgrdFileNames(NULL),
-  fAlignObjArray(NULL),
-  fUseBkgrdVertex(sim.fUseBkgrdVertex),
-  fRegionOfInterest(sim.fRegionOfInterest),
-  fCDBUri(sim.fCDBUri),
-  fSpecCDBUri(),
-  fRun(-1),
-  fSeed(0),
-  fInitCDBCalled(sim.fInitCDBCalled),
-  fInitRunNumberCalled(sim.fInitRunNumberCalled),
-  fSetRunNumberFromDataCalled(sim.fSetRunNumberFromDataCalled),
-  fEmbeddingFlag(sim.fEmbeddingFlag),
-  fQADetectors(sim.fQADetectors),                  
-  fQATasks(sim.fQATasks),      
-  fRunQA(sim.fRunQA), 
-  fRunHLT(sim.fRunHLT)
-{
-// copy constructor
-
-  for (Int_t i = 0; i < sim.fEventsPerFile.GetEntriesFast(); i++) {
-    if (!sim.fEventsPerFile[i]) continue;
-    fEventsPerFile.Add(sim.fEventsPerFile[i]->Clone());
-  }
-
-  fBkgrdFileNames = new TObjArray;
-  for (Int_t i = 0; i < sim.fBkgrdFileNames->GetEntriesFast(); i++) {
-    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;
-
-// for QA
-   for (Int_t iDet = 0; iDet < fgkNDetectors; iDet++) 
-       fQACycles[iDet] = sim.fQACycles[iDet];
-}
-
-//_____________________________________________________________________________
-AliSimulation& AliSimulation::operator = (const AliSimulation& sim)
-{
-// assignment operator
-
-  this->~AliSimulation();
-  new(this) AliSimulation(sim);
-  return *this;
+       AliQAManager * qam = AliQAManager::QAManager(AliQAv1::kSIMMODE) ; 
+       qam->SetActiveDetectors(fQADetectors) ; 
+       fQATasks = Form("%d %d %d", AliQAv1::kHITS, AliQAv1::kSDIGITS, AliQAv1::kDIGITS) ; 
+       qam->SetTasks(fQATasks) ;       
 }
 
 //_____________________________________________________________________________
@@ -284,6 +234,8 @@ AliSimulation::~AliSimulation()
   fSpecCDBUri.Delete();
   if (fgInstance==this) fgInstance = 0;
 
+  AliQAManager::QAManager()->ShowQA() ; 
+  AliQAManager::Destroy() ;    
   AliCodeTimer::Instance()->Print();
 }
 
@@ -296,6 +248,45 @@ void AliSimulation::SetNumberOfEvents(Int_t nEvents)
   fNEvents = nEvents;
 }
 
+//_____________________________________________________________________________
+void AliSimulation::InitQA()
+{
+  // 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
+  
+  if (fInitCDBCalled) return;
+  fInitCDBCalled = kTRUE;
+
+  AliQAManager * qam = AliQAManager::QAManager(AliQAv1::kSIMMODE) ; 
+  qam->SetActiveDetectors(fQADetectors) ; 
+  fQATasks = Form("%d %d %d", AliQAv1::kHITS, AliQAv1::kSDIGITS, AliQAv1::kDIGITS) ; 
+  qam->SetTasks(fQATasks) ;
+       if (fWriteQAExpertData)
+    qam->SetWriteExpert() ; 
+  
+  if (qam->IsDefaultStorageSet()) {
+    AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
+    AliWarning("Default QA reference storage has been already set !");
+    AliWarning(Form("Ignoring the default storage declared in AliSimulation: %s",fQARefUri.Data()));
+    AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
+    fQARefUri = qam->GetDefaultStorage()->GetURI();
+  } else {
+      if (fQARefUri.Length() > 0) {
+        AliDebug(2,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
+        AliDebug(2, Form("Default QA reference storage is set to: %s", fQARefUri.Data()));
+        AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
+      } else {
+        fQARefUri="local://$ALICE_ROOT/QARef";
+        AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
+        AliWarning("Default QA reference storage not yet set !!!!");
+        AliWarning(Form("Setting it now to: %s", fQARefUri.Data()));
+        AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
+      }
+    qam->SetDefaultStorage(fQARefUri);
+  }
+}
+
 //_____________________________________________________________________________
 void AliSimulation::InitCDB()
 {
@@ -322,7 +313,7 @@ void AliSimulation::InitCDB()
        AliDebug(2, Form("Default CDB storage is set to: %s", fCDBUri.Data()));
        AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
     } else {
-       fCDBUri="local://$ALICE_ROOT";
+       fCDBUri="local://$ALICE_ROOT/OCDB";
        AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        AliWarning("Default CDB storage not yet set !!!!");
        AliWarning(Form("Setting it now to: %s", fCDBUri.Data()));
@@ -359,16 +350,11 @@ void AliSimulation::InitRunNumber(){
   }
     
   if(fRun >= 0) {
-       AliDebug(2,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        AliDebug(2, Form("Setting CDB run number to: %d",fRun));
-       AliDebug(2, "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
   } else {
        fRun=0;
-       AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
-       AliWarning("Run number not yet set !!!!");
-       AliWarning(Form("Setting it now to: %d", fRun));
-       AliWarning("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
-       
+       AliWarning(Form("Run number not yet set !!!! Setting it now to: %d",
+                       fRun));
   }
   man->SetRun(fRun);
 
@@ -381,16 +367,26 @@ void AliSimulation::SetCDBLock() {
   // Set CDB lock: from now on it is forbidden to reset the run number
   // or the default storage or to activate any further storage!
   
-  AliCDBManager::Instance()->SetLock(1);
+  ULong_t key = AliCDBManager::Instance()->SetLock(1);
+  if (key) fKey = key;
 }
 
 //_____________________________________________________________________________
 void AliSimulation::SetDefaultStorage(const char* uri) {
-// Store the desired default CDB storage location
-// Activate it later within the Run() method
-
+  // Store the desired default CDB storage location
+  // Activate it later within the Run() method
+  
   fCDBUri = uri;
+  
+}
 
+//_____________________________________________________________________________
+void AliSimulation::SetQARefDefaultStorage(const char* uri) {
+  // Store the desired default CDB storage location
+  // Activate it later within the Run() method
+  
+  fQARefUri = uri;
+  AliQAv1::SetQARefStorage(fQARefUri.Data()) ;
 }
 
 //_____________________________________________________________________________
@@ -443,7 +439,7 @@ Bool_t AliSimulation::SetRunNumberFromData()
     AliRunLoader* runLoader = LoadRun("READ");
     if (!runLoader) return kFALSE;
     else {
-       runData = runLoader->GetAliRun()->GetHeader()->GetRun();
+       runData = runLoader->GetHeader()->GetRun();
        delete runLoader;
     }
   
@@ -537,7 +533,7 @@ Bool_t AliSimulation::MisalignGeometry(AliRunLoader *runLoader)
   }
   
   // Export ideal geometry 
-  if(!gAlice->IsRootGeometry()) AliGeomManager::GetGeometry()->Export("geometry.root");
+  if(!IsGeometryFromFile()) AliGeomManager::GetGeometry()->Export("geometry.root");
 
   // Load alignment data from CDB and apply to geometry through AliGeomManager
   if(fLoadAlignFromCDB){
@@ -613,24 +609,35 @@ Bool_t AliSimulation::Run(Int_t nEvents)
 // run the generation, simulation and digitization
 
  
-  AliCodeTimerAuto("")
+  AliCodeTimerAuto("",0)
+  AliSysInfo::AddStamp("Start_Run");
   
   // Load run number and seed from environmental vars
   ProcessEnvironmentVars();
+  AliSysInfo::AddStamp("ProcessEnvironmentVars");
 
   gRandom->SetSeed(fSeed);
    
   if (nEvents > 0) fNEvents = nEvents;
 
+  // create and setup the HLT instance
+  if (!fRunHLT.IsNull() && !CreateHLT()) {
+    if (fStopOnError) return kFALSE;
+    // disable HLT
+    fRunHLT="";
+  }
+  
   // generation and simulation -> hits
   if (fRunGeneration) {
     if (!RunSimulation()) if (fStopOnError) return kFALSE;
   }
+  AliSysInfo::AddStamp("RunSimulation");
            
   // initialize CDB storage from external environment
   // (either CDB manager or AliSimulation setters),
   // if not already done in RunSimulation()
   InitCDB();
+  AliSysInfo::AddStamp("InitCDB");
   
   // Set run number in CDBManager from data 
   // From this point on the run number must be always loaded from data!
@@ -644,7 +651,7 @@ Bool_t AliSimulation::Run(Int_t nEvents)
   if (!AliGeomManager::GetGeometry()) {
     // Initialize the geometry manager
     AliGeomManager::LoadGeometry("geometry.root");
-    
+    AliSysInfo::AddStamp("GetGeometry");
 //    // Check that the consistency of symbolic names for the activated subdetectors
 //    // in the geometry loaded by AliGeomManager
 //    AliRunLoader* runLoader = LoadRun("READ");
@@ -666,6 +673,7 @@ Bool_t AliSimulation::Run(Int_t nEvents)
     // Misalign geometry
     if(!MisalignGeometry()) if (fStopOnError) return kFALSE;
   }
+  AliSysInfo::AddStamp("MissalignGeometry");
 
 
   // hits -> summable digits
@@ -700,13 +708,15 @@ Bool_t AliSimulation::Run(Int_t nEvents)
     }
   }
 
+  AliSysInfo::AddStamp("Hits2Digits");
   
   
   // digits -> trigger
-  if (!RunTrigger(fMakeTrigger,fMakeDigits)) {
+  if (!RunTrigger(fTriggerConfig,fMakeDigits)) {
     if (fStopOnError) return kFALSE;
   }
 
+  AliSysInfo::AddStamp("RunTrigger");
   
   
   // digits -> raw data
@@ -717,14 +727,17 @@ Bool_t AliSimulation::Run(Int_t nEvents)
     }
   }
 
+  AliSysInfo::AddStamp("WriteRaw");
   
-  
-  // run HLT simulation
-  if (!fRunHLT.IsNull()) {
+  // run HLT simulation on simulated digit data if raw data is not
+  // simulated, otherwise its called as part of WriteRawData
+  if (!fRunHLT.IsNull() && fWriteRawData.IsNull()) {
     if (!RunHLT()) {
       if (fStopOnError) return kFALSE;
     }
   }
+
+  AliSysInfo::AddStamp("RunHLT");
   
   //QA
        if (fRunQA) {
@@ -734,18 +747,158 @@ Bool_t AliSimulation::Run(Int_t nEvents)
                                return kFALSE ;         
        }
 
+  AliSysInfo::AddStamp("RunQA");
+
   // Cleanup of CDB manager: cache and active storages!
   AliCDBManager::Instance()->ClearCache();
 
   return kTRUE;
 }
 
+//_______________________________________________________________________
+Bool_t AliSimulation::RunLego(const char *setup, Int_t nc1, Float_t c1min,
+                    Float_t c1max,Int_t nc2,Float_t c2min,Float_t c2max,
+                    Float_t rmin,Float_t rmax,Float_t zmax, AliLegoGenerator* gener, Int_t nev)
+{
+  //
+  // Generates lego plots of:
+  //    - radiation length map phi vs theta
+  //    - radiation length map phi vs eta
+  //    - interaction length map
+  //    - g/cm2 length map
+  //
+  //  ntheta    bins in theta, eta
+  //  themin    minimum angle in theta (degrees)
+  //  themax    maximum angle in theta (degrees)
+  //  nphi      bins in phi
+  //  phimin    minimum angle in phi (degrees)
+  //  phimax    maximum angle in phi (degrees)
+  //  rmin      minimum radius
+  //  rmax      maximum radius
+  //  
+  //
+  //  The number of events generated = ntheta*nphi
+  //  run input parameters in macro setup (default="Config.C")
+  //
+  //  Use macro "lego.C" to visualize the 3 lego plots in spherical coordinates
+  //Begin_Html
+  /*
+    <img src="picts/AliRunLego1.gif">
+  */
+  //End_Html
+  //Begin_Html
+  /*
+    <img src="picts/AliRunLego2.gif">
+  */
+  //End_Html
+  //Begin_Html
+  /*
+    <img src="picts/AliRunLego3.gif">
+  */
+  //End_Html
+  //
+
+// run the generation and simulation
+
+  AliCodeTimerAuto("",0)
+
+  // initialize CDB storage and run number from external environment
+  // (either CDB manager or AliSimulation setters)
+  InitCDB();
+  InitRunNumber();
+  SetCDBLock();
+  
+  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()));
+
+  // Number of events 
+    if (nev == -1) nev  = nc1 * nc2;
+    
+  // check if initialisation has been done
+  // If runloader has been initialized, set the number of events per file to nc1 * nc2
+    
+  // Set new generator
+  if (!gener) gener  = new AliLegoGenerator();
+  //
+  // Configure Generator
+
+  gener->SetRadiusRange(rmin, rmax);
+  gener->SetZMax(zmax);
+  gener->SetCoor1Range(nc1, c1min, c1max);
+  gener->SetCoor2Range(nc2, c2min, c2max);
+  
+  
+  //Create Lego object  
+  fLego = new AliLego("lego",gener);
+
+  //__________________________________________________________________________
+
+  gAlice->Announce();
+
+  gROOT->LoadMacro(setup);
+  gInterpreter->ProcessLine(gAlice->GetConfigFunction());
+
+  if(AliCDBManager::Instance()->GetRun() >= 0) { 
+    SetRunNumber(AliCDBManager::Instance()->GetRun());
+  } else {
+    AliWarning("Run number not initialized!!");
+  }
+
+  AliRunLoader::Instance()->CdGAFile();
+  
+  AliPDG::AddParticlesToPdgDataBase();  
+  
+  gMC->SetMagField(TGeoGlobalMagField::Instance()->GetField());
+
+  gAlice->GetMCApp()->Init();
+  
+  
+  //Must be here because some MCs (G4) adds detectors here and not in Config.C
+  gAlice->InitLoaders();
+  AliRunLoader::Instance()->MakeTree("E");
+  
+  //
+  // Save stuff at the beginning of the file to avoid file corruption
+  AliRunLoader::Instance()->CdGAFile();
+  gAlice->Write();
+
+  //Save current generator
+  AliGenerator *gen=gAlice->GetMCApp()->Generator();
+  gAlice->GetMCApp()->ResetGenerator(gener);
+  //Prepare MC for Lego Run
+  gMC->InitLego();
+  
+  //Run Lego Object
+  
+  
+  AliRunLoader::Instance()->SetNumberOfEventsPerFile(nev);
+  gMC->ProcessRun(nev);
+  
+  // End of this run, close files
+  FinishRun();
+  // Restore current generator
+  gAlice->GetMCApp()->ResetGenerator(gen);
+  // Delete Lego Object
+  delete fLego;
+
+  return kTRUE;
+}
+
 //_____________________________________________________________________________
 Bool_t AliSimulation::RunTrigger(const char* config, const char* detectors)
 {
   // run the trigger
 
-  AliCodeTimerAuto("")
+  AliCodeTimerAuto("",0)
 
   // initialize CDB storage from external environment
   // (either CDB manager or AliSimulation setters),
@@ -765,8 +918,8 @@ Bool_t AliSimulation::RunTrigger(const char* config, const char* detectors)
    TString trconfiguration = config;
 
    if (trconfiguration.IsNull()) {
-     if (gAlice->GetTriggerDescriptor() != "") {
-       trconfiguration = gAlice->GetTriggerDescriptor();
+     if(!fTriggerConfig.IsNull()) {
+       trconfiguration = fTriggerConfig;
      }
      else
        AliWarning("No trigger descriptor is specified. Loading the one that is in the CDB.");
@@ -808,13 +961,16 @@ Bool_t AliSimulation::RunSimulation(Int_t nEvents)
 {
 // run the generation and simulation
 
-  AliCodeTimerAuto("")
+  AliCodeTimerAuto("",0)
 
   // initialize CDB storage and run number from external environment
   // (either CDB manager or AliSimulation setters)
+  AliSysInfo::AddStamp("RunSimulation_Begin");
   InitCDB();
+  AliSysInfo::AddStamp("RunSimulation_InitCDB");
   InitRunNumber();
   SetCDBLock();
+  AliSysInfo::AddStamp("RunSimulation_SetCDBLock");
   
   if (!gAlice) {
     AliError("no gAlice object. Restart aliroot and try again.");
@@ -827,24 +983,92 @@ Bool_t AliSimulation::RunSimulation(Int_t nEvents)
 
   AliInfo(Form("initializing gAlice with config file %s",
           fConfigFileName.Data()));
-  StdoutToAliInfo(StderrToAliError(
-    gAlice->Init(fConfigFileName.Data());
-  ););
+
+  //
+  // Initialize ALICE Simulation run
+  //
+  gAlice->Announce();
+
+  //
+  // If requested set the mag. field from the GRP entry.
+  // After this the field is loccked and cannot be changed by Config.C
+  if (fUseMagFieldFromGRP) {
+      AliGRPManager grpM;
+      grpM.ReadGRPEntry();
+      grpM.SetMagField();
+      AliInfo("Field is locked now. It cannot be changed in Config.C");
+  }
+//
+// Execute Config.C
+  gROOT->LoadMacro(fConfigFileName.Data());
+  gInterpreter->ProcessLine(gAlice->GetConfigFunction());
+  AliSysInfo::AddStamp("RunSimulation_Config");
+
+//
+// If requested obtain the vertex position and vertex sigma_z from the CDB
+// This overwrites the settings from the Config.C  
+  if (fUseVertexFromCDB) {
+      Double_t vtxPos[3] = {0., 0., 0.}; 
+      Double_t vtxSig[3] = {0., 0., 0.};
+      AliCDBEntry* entry = AliCDBManager::Instance()->Get("GRP/Calib/MeanVertex");
+      AliESDVertex* vertex = dynamic_cast<AliESDVertex*> (entry->GetObject());
+      if(vertex) {
+         if(vertex->GetXRes()>2.8) { // > pipe radius --> it's a dummy object, don't use it 
+             entry = AliCDBManager::Instance()->Get("GRP/Calib/MeanVertexSPD");
+             vertex = dynamic_cast<AliESDVertex*> (entry->GetObject());
+         }
+      }
+      if (vertex) {
+         vertex->GetXYZ(vtxPos);
+         vertex->GetSigmaXYZ(vtxSig);
+         AliInfo("Overwriting Config.C vertex settings !");
+         AliInfo(Form("Vertex position from OCDB entry: x = %13.3f, y = %13.3f, z = %13.3f (sigma = %13.3f)\n",
+                vtxPos[0], vtxPos[1], vtxPos[2], vtxSig[2]));
+
+         AliGenerator *gen = gAlice->GetMCApp()->Generator();
+         gen->SetOrigin(vtxPos[0], vtxPos[1], vtxPos[2]);   // vertex position
+         gen->SetSigmaZ(vtxSig[2]);
+      }
+  }
   
-  // Get the trigger descriptor string
-  // Either from AliSimulation or from
-  // gAlice
-  if (fMakeTrigger.IsNull()) {
-    if (gAlice->GetTriggerDescriptor() != "")
-      fMakeTrigger = gAlice->GetTriggerDescriptor();
+  if(AliCDBManager::Instance()->GetRun() >= 0) { 
+    AliRunLoader::Instance()->SetRunNumber(AliCDBManager::Instance()->GetRun());
+    AliRunLoader::Instance()->SetNumberOfEventsPerRun(fNEvents);
+  } else {
+       AliWarning("Run number not initialized!!");
   }
-  else
-    gAlice->SetTriggerDescriptor(fMakeTrigger.Data());
+  
+   AliRunLoader::Instance()->CdGAFile();
+   
+
+   AliPDG::AddParticlesToPdgDataBase();  
+
+   gMC->SetMagField(TGeoGlobalMagField::Instance()->GetField());
+   AliSysInfo::AddStamp("RunSimulation_GetField");
+   
+   gAlice->GetMCApp()->Init();
+   AliSysInfo::AddStamp("RunSimulation_InitMCApp");
+
+   //Must be here because some MCs (G4) adds detectors here and not in Config.C
+   gAlice->InitLoaders();
+   AliRunLoader::Instance()->MakeTree("E");
+   AliRunLoader::Instance()->LoadKinematics("RECREATE");
+   AliRunLoader::Instance()->LoadTrackRefs("RECREATE");
+   AliRunLoader::Instance()->LoadHits("all","RECREATE");
+   //
+   // Save stuff at the beginning of the file to avoid file corruption
+   AliRunLoader::Instance()->CdGAFile();
+   gAlice->Write();
+   gAlice->SetEventNrInRun(-1); //important - we start Begin event from increasing current number in run
+   AliSysInfo::AddStamp("RunSimulation_InitLoaders");
+  //___________________________________________________________________________________________
+  
+  AliSysInfo::AddStamp("RunSimulation_TriggerDescriptor");
 
   // Set run number in CDBManager
   AliInfo(Form("Run number: %d",AliCDBManager::Instance()->GetRun()));
 
-  AliRunLoader* runLoader = gAlice->GetRunLoader();
+  AliRunLoader* runLoader = AliRunLoader::Instance();
   if (!runLoader) {
              AliError(Form("gAlice has no run loader object. "
                             "Check your config file: %s", fConfigFileName.Data()));
@@ -869,9 +1093,10 @@ Bool_t AliSimulation::RunSimulation(Int_t nEvents)
   if(!AliGeomManager::CheckSymNamesLUT(detsToBeChecked.Data()))
     AliFatalClass("Current loaded geometry differs in the definition of symbolic names!");
   MisalignGeometry(runLoader);
+  AliSysInfo::AddStamp("RunSimulation_MisalignGeometry");
 #endif
 
-//   AliRunLoader* runLoader = gAlice->GetRunLoader();
+//   AliRunLoader* runLoader = AliRunLoader::Instance();
 //   if (!runLoader) {
 //     AliError(Form("gAlice has no run loader object. "
 //                   "Check your config file: %s", fConfigFileName.Data()));
@@ -879,11 +1104,17 @@ Bool_t AliSimulation::RunSimulation(Int_t nEvents)
 //   }
 //   SetGAliceFile(runLoader->GetFileName());
 
-  if (!gAlice->Generator()) {
+  if (!gAlice->GetMCApp()->Generator()) {
     AliError(Form("gAlice has no generator object. "
                   "Check your config file: %s", fConfigFileName.Data()));
     return kFALSE;
   }
+
+  // Write GRP entry corresponding to the setting found in Cofig.C
+  if (fWriteGRPEntry)
+    WriteGRPEntry();
+  AliSysInfo::AddStamp("RunSimulation_WriteGRP");
+
   if (nEvents <= 0) nEvents = fNEvents;
 
   // get vertex from background file in case of merging
@@ -896,11 +1127,11 @@ Bool_t AliSimulation::RunSimulation(Int_t nEvents)
                  "file %s with nSignalPerBackground = %d", 
                  fileName, signalPerBkgrd));
     AliVertexGenFile* vtxGen = new AliVertexGenFile(fileName, signalPerBkgrd);
-    gAlice->Generator()->SetVertexGenerator(vtxGen);
+    gAlice->GetMCApp()->Generator()->SetVertexGenerator(vtxGen);
   }
 
   if (!fRunSimulation) {
-    gAlice->Generator()->SetTrackingFlag(0);
+    gAlice->GetMCApp()->Generator()->SetTrackingFlag(0);
   }
 
   // set the number of events per file for given detectors and data types
@@ -912,8 +1143,7 @@ Bool_t AliSimulation::RunSimulation(Int_t nEvents)
     loaderName += "Loader";
     AliLoader* loader = runLoader->GetLoader(loaderName);
     if (!loader) {
-      AliError(Form("RunSimulation", "no loader for %s found\n"
-                    "Number of events per file not set for %s %s", 
+      AliError(Form("RunSimulation no loader for %s found\n Number of events per file not set for %s %s", 
                     detName, typeName, detName));
       continue;
     }
@@ -931,11 +1161,17 @@ Bool_t AliSimulation::RunSimulation(Int_t nEvents)
   }
 
   AliInfo("running gAlice");
-  AliSysInfo::AddStamp("Start_simulation");
-  StdoutToAliInfo(StderrToAliError(
-    gAlice->Run(nEvents);
-  ););
-  AliSysInfo::AddStamp("Stop_simulation");
+  AliSysInfo::AddStamp("Start_ProcessRun");
+
+  // Create the Root Tree with one branch per detector
+  //Hits moved to begin event -> now we are crating separate tree for each event
+
+  gMC->ProcessRun(nEvents);
+
+  // End of this run, close files
+  if(nEvents>0) FinishRun();
+
+  AliSysInfo::AddStamp("Stop_ProcessRun");
   delete runLoader;
 
   return kTRUE;
@@ -946,7 +1182,7 @@ Bool_t AliSimulation::RunSDigitization(const char* detectors)
 {
 // run the digitization and produce summable digits
   static Int_t eventNr=0;
-  AliCodeTimerAuto("")
+  AliCodeTimerAuto("",0) ;
 
   // initialize CDB storage, run number, set CDB lock
   InitCDB();
@@ -963,8 +1199,9 @@ Bool_t AliSimulation::RunSDigitization(const char* detectors)
     if (!det || !det->IsActive()) continue;
     if (IsSelected(det->GetName(), detStr)) {
       AliInfo(Form("creating summable digits for %s", det->GetName()));
-      AliCodeTimerAuto(Form("creating summable digits for %s", det->GetName()));
+      AliCodeTimerStart(Form("creating summable digits for %s", det->GetName()));
       det->Hits2SDigits();
+      AliCodeTimerStop(Form("creating summable digits for %s", det->GetName()));
       AliSysInfo::AddStamp(Form("Digit_%s_%d",det->GetName(),eventNr), 0,1, eventNr);
     }
   }
@@ -987,15 +1224,15 @@ Bool_t AliSimulation::RunDigitization(const char* detectors,
 {
 // run the digitization and produce digits from sdigits
 
-  AliCodeTimerAuto("")
+  AliCodeTimerAuto("",0)
 
   // initialize CDB storage, run number, set CDB lock
   InitCDB();
   if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
   SetCDBLock();
   
-  while (AliRunLoader::GetRunLoader()) delete AliRunLoader::GetRunLoader();
-  if (gAlice) delete gAlice;
+  delete AliRunLoader::Instance();
+  delete gAlice;
   gAlice = NULL;
 
   Int_t nStreams = 1;
@@ -1053,7 +1290,7 @@ Bool_t AliSimulation::RunHitsDigitization(const char* detectors)
 {
 // run the digitization and produce digits from hits
 
-  AliCodeTimerAuto("")
+  AliCodeTimerAuto("",0)
 
   // initialize CDB storage, run number, set CDB lock
   InitCDB();
@@ -1080,10 +1317,6 @@ Bool_t AliSimulation::RunHitsDigitization(const char* detectors)
     if (fStopOnError) return kFALSE;
   }
 
-  delete runLoader;
-  //PH Temporary fix to avoid interference with the PHOS loder/getter
-  //PH The problem has to be solved in more general way 09/06/05
-
   return kTRUE;
 }
 
@@ -1104,18 +1337,29 @@ Bool_t AliSimulation::WriteRawData(const char* detectors,
 // 'selrawdata' flag can be used to enable writing of detectors raw data
 // accoring to the trigger cluster.
 
-  AliCodeTimerAuto("")
+  AliCodeTimerAuto("",0)
+  AliSysInfo::AddStamp("WriteRawData_Start");
   
   TString detStr = detectors;
-  if (IsSelected("HLT", detStr))
-  {
-       // Do nothing. "HLT" will be removed from detStr because the HLT raw
-       // data files are generated in RunHLT.
-  }
-
   if (!WriteRawFiles(detStr.Data())) {
     if (fStopOnError) return kFALSE;
   }
+  AliSysInfo::AddStamp("WriteRawFiles");
+
+  // run HLT simulation on simulated DDL raw files
+  // and produce HLT ddl raw files to be included in date/root file
+  // bugfix 2009-06-26: the decision whether to write HLT raw data
+  // is taken in RunHLT. Here HLT always needs to be run in order to
+  // create HLT digits, unless its switched off. This is due to the
+  // special placement of the HLT between the generation of DDL files
+  // and conversion to DATE/Root file.
+  detStr.ReplaceAll("HLT", "");
+  if (!fRunHLT.IsNull()) {
+    if (!RunHLT()) {
+      if (fStopOnError) return kFALSE;
+    }
+  }
+  AliSysInfo::AddStamp("WriteRawData_RunHLT");
 
   TString dateFileName(fileName);
   if (!dateFileName.IsNull()) {
@@ -1129,6 +1373,7 @@ Bool_t AliSimulation::WriteRawData(const char* detectors,
     if (!ConvertRawFilesToDate(dateFileName,selDateFileName)) {
       if (fStopOnError) return kFALSE;
     }
+    AliSysInfo::AddStamp("ConvertRawFilesToDate");
     if (deleteIntermediateFiles) {
       AliRunLoader* runLoader = LoadRun("READ");
       if (runLoader) for (Int_t iEvent = 0; 
@@ -1137,12 +1382,14 @@ Bool_t AliSimulation::WriteRawData(const char* detectors,
        sprintf(command, "rm -r raw%d", iEvent);
        gSystem->Exec(command);
       }
+      delete runLoader;
     }
 
     if (rootOutput) {
       if (!ConvertDateToRoot(dateFileName, fileName)) {
        if (fStopOnError) return kFALSE;
       }
+      AliSysInfo::AddStamp("ConvertDateToRoot");
       if (deleteIntermediateFiles) {
        gSystem->Unlink(dateFileName);
       }
@@ -1167,7 +1414,7 @@ Bool_t AliSimulation::WriteRawFiles(const char* detectors)
 {
 // convert the digits to raw data DDL files
 
-  AliCodeTimerAuto("")
+  AliCodeTimerAuto("",0)
   
   AliRunLoader* runLoader = LoadRun("READ");
   if (!runLoader) return kFALSE;
@@ -1185,7 +1432,15 @@ Bool_t AliSimulation::WriteRawFiles(const char* detectors)
       if (fStopOnError) return kFALSE; else continue;
     }
 
+    ofstream runNbFile(Form("run%u",runLoader->GetHeader()->GetRun()));
+    runNbFile.close();
+
     TString detStr = detectors;
+    if (IsSelected("HLT", detStr)) {
+      // Do nothing. "HLT" will be removed from detStr and HLT raw
+      // data files are generated in RunHLT.
+    }
+
     TObjArray* detArray = runLoader->GetAliRun()->Detectors();
     for (Int_t iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
       AliModule* det = (AliModule*) detArray->At(iDet);
@@ -1220,7 +1475,7 @@ Bool_t AliSimulation::ConvertRawFilesToDate(const char* dateFileName,
 // The second argument is not empty when the user decides to write
 // the detectors raw data according to the trigger cluster.
 
-  AliCodeTimerAuto("")
+  AliCodeTimerAuto("",0)
   
   char* path = gSystem->Which(gSystem->Getenv("PATH"), "dateStream");
   if (!path) {
@@ -1244,25 +1499,36 @@ Bool_t AliSimulation::ConvertRawFilesToDate(const char* dateFileName,
          dateFileName, runLoader->GetNumberOfEvents(),runLoader->GetHeader()->GetRun());
   FILE* pipe = gSystem->OpenPipe(command, "w");
 
+  if (!pipe) {
+    AliError(Form("Cannot execute command: %s",command));
+    return kFALSE;
+  }
+
   Int_t selEvents = 0;
   for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
-    fprintf(pipe, "GDC\n");
-    Float_t ldc = 0;
-    Int_t prevLDC = -1;
 
-    if (selrawdata) {
+    UInt_t detectorPattern = 0;
+    runLoader->GetEvent(iEvent);
+    if (!runLoader->LoadTrigger()) {
+      AliCentralTrigger *aCTP = runLoader->GetTrigger();
+      detectorPattern = aCTP->GetClusterMask();
       // Check if the event was triggered by CTP
-      runLoader->GetEvent(iEvent);
-      if (!runLoader->LoadTrigger()) {
-       AliCentralTrigger *aCTP = runLoader->GetTrigger();
+      if (selrawdata) {
        if (aCTP->GetClassMask()) selEvents++;
       }
-      else {
+    }
+    else {
+      AliWarning("No trigger can be loaded! Some fields in the event header will be empty !");
+      if (selrawdata) {
        AliWarning("No trigger can be loaded! Writing of selected raw data is abandoned !");
        selrawdata = kFALSE;
       }
     }
 
+    fprintf(pipe, "GDC DetectorPattern %u\n", detectorPattern);
+    Float_t ldc = 0;
+    Int_t prevLDC = -1;
+
     // loop over detectors and DDLs
     for (Int_t iDet = 0; iDet < AliDAQ::kNDetectors; iDet++) {
       for (Int_t iDDL = 0; iDDL < AliDAQ::NumberOfDdls(iDet); iDDL++) {
@@ -1308,16 +1574,18 @@ Bool_t AliSimulation::ConvertRawFilesToDate(const char* dateFileName,
   for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
 
     // Get the trigger decision and cluster
+    UInt_t detectorPattern = 0;
     TString detClust;
     runLoader->GetEvent(iEvent);
     if (!runLoader->LoadTrigger()) {
       AliCentralTrigger *aCTP = runLoader->GetTrigger();
       if (aCTP->GetClassMask() == 0) continue;
-      detClust = AliDAQ::ListOfTriggeredDetectors(aCTP->GetClusterMask());
+      detectorPattern = aCTP->GetClusterMask();
+      detClust = AliDAQ::ListOfTriggeredDetectors(detectorPattern);
       AliInfo(Form("List of detectors to be read out: %s",detClust.Data()));
     }
 
-    fprintf(pipe2, "GDC\n");
+    fprintf(pipe2, "GDC DetectorPattern %u\n", detectorPattern);
     Float_t ldc = 0;
     Int_t prevLDC = -1;
 
@@ -1419,7 +1687,7 @@ AliRunLoader* AliSimulation::LoadRun(const char* mode) const
 {
 // delete existing run loaders, open a new one and load gAlice
 
-  while (AliRunLoader::GetRunLoader()) delete AliRunLoader::GetRunLoader();
+  delete AliRunLoader::Instance();
   AliRunLoader* runLoader = 
     AliRunLoader::Open(fGAliceFileName.Data(), 
                       AliConfig::GetDefaultEventFolderName(), mode);
@@ -1524,7 +1792,7 @@ Bool_t AliSimulation::IsSelected(TString detName, TString& detectors) const
 }
 
 //_____________________________________________________________________________
-Bool_t AliSimulation::ConvertRaw2SDigits(const char* rawDirectory, const char* esdFileName) 
+Bool_t AliSimulation::ConvertRaw2SDigits(const char* rawDirectory, const char* esdFileName, Int_t N
 {
 //
 // Steering routine  to convert raw data in directory rawDirectory/ to fake SDigits. 
@@ -1533,17 +1801,47 @@ Bool_t AliSimulation::ConvertRaw2SDigits(const char* rawDirectory, const char* e
 //
 // 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;
-    }
+  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()));
+  
+  gAlice->Announce();
+  
+  gROOT->LoadMacro(fConfigFileName.Data());
+  gInterpreter->ProcessLine(gAlice->GetConfigFunction());
+  
+  if(AliCDBManager::Instance()->GetRun() >= 0) { 
+       SetRunNumber(AliCDBManager::Instance()->GetRun());
+  } else {
+       AliWarning("Run number not initialized!!");
+  }
+  
+   AliRunLoader::Instance()->CdGAFile();
     
-    AliInfo(Form("initializing gAlice with config file %s",fConfigFileName.Data()));
-    StdoutToAliInfo(StderrToAliError(gAlice->Init(fConfigFileName.Data());););
+   AliPDG::AddParticlesToPdgDataBase();  
+
+   gMC->SetMagField(TGeoGlobalMagField::Instance()->GetField());
+   
+   gAlice->GetMCApp()->Init();
+
+   //Must be here because some MCs (G4) adds detectors here and not in Config.C
+   gAlice->InitLoaders();
+   AliRunLoader::Instance()->MakeTree("E");
+   AliRunLoader::Instance()->LoadKinematics("RECREATE");
+   AliRunLoader::Instance()->LoadTrackRefs("RECREATE");
+   AliRunLoader::Instance()->LoadHits("all","RECREATE");
+
+   //
+   // Save stuff at the beginning of the file to avoid file corruption
+   AliRunLoader::Instance()->CdGAFile();
+   gAlice->Write();
 //
 //  Initialize CDB     
     InitCDB();
@@ -1553,22 +1851,21 @@ Bool_t AliSimulation::ConvertRaw2SDigits(const char* rawDirectory, const char* e
     Int_t iDet;
     //
     // Get the runloader
-    AliRunLoader* runLoader = gAlice->GetRunLoader();
+    AliRunLoader* runLoader = AliRunLoader::Instance();
     //
     // Open esd file if available
-    TFile* esdFile = TFile::Open(esdFileName);
-    Bool_t esdOK = (esdFile != 0);
-    AliESD* esd = new AliESD;
+    TFile* esdFile = 0;
     TTree* treeESD = 0;
-    if (esdOK) {
-       treeESD = (TTree*) esdFile->Get("esdTree");
-       if (!treeESD) {
-           AliWarning("No ESD tree found");
-           esdOK = kFALSE;
-       } else {
-           treeESD->SetBranchAddress("ESD", &esd);
-       }
+    AliESDEvent* esd = 0;
+    if (esdFileName && (strlen(esdFileName)>0)) {
+      esdFile = TFile::Open(esdFileName);
+      if (esdFile) {
+        esd = new AliESDEvent();
+        esdFile->GetObject("esdTree", treeESD);
+        if (treeESD) esd->ReadFromTree(treeESD);
+      }
     }
+
     //
     // Create the RawReader
     TString fileName(rawDirectory);
@@ -1588,28 +1885,33 @@ Bool_t AliSimulation::ConvertRaw2SDigits(const char* rawDirectory, const char* e
     //
     // Get Header
     AliHeader* header = runLoader->GetHeader();
-    //
-    TString detStr = fMakeSDigits;
     // Event loop
     Int_t nev = 0;
     while(kTRUE) {
        if (!(rawReader->NextEvent())) break;
+       runLoader->SetEventNumber(nev);
+        runLoader->GetHeader()->Reset(rawReader->GetRunNumber(), 
+                                      nev, nev);
+       runLoader->TreeE()->Fill();
+        runLoader->GetEvent(nev);
+        AliInfo(Form("We are at event %d",nev));
        //
        // Detector loop
+        TString detStr = fMakeSDigits;
        for (iDet = 0; iDet < detArray->GetEntriesFast(); iDet++) {
            AliModule* det = (AliModule*) detArray->At(iDet);
            if (!det || !det->IsActive()) continue;
            if (IsSelected(det->GetName(), detStr)) {
-             AliInfo(Form("Calling Raw2SDigits for %s\n", det->GetName()));
+             AliInfo(Form("Calling Raw2SDigits for %s", det->GetName()));
              det->Raw2SDigits(rawReader);
              rawReader->Reset();
            }
        } // detectors
-
+        
 
        //
        //  If ESD information available obtain reconstructed vertex and store in header.
-       if (esdOK) {
+       if (treeESD) {
            treeESD->GetEvent(nev);
            const AliESDVertex* esdVertex = esd->GetPrimaryVertex();
            Double_t position[3];
@@ -1621,13 +1923,14 @@ Bool_t AliSimulation::ConvertRaw2SDigits(const char* rawDirectory, const char* e
            mcHeader->SetPrimaryVertex(mcV);
            header->Reset(0,nev);
            header->SetGenEventHeader(mcHeader);
-           printf("***** Saved vertex %f %f %f \n", position[0], position[1], position[2]);
+           AliInfo(Form("***** Saved vertex %f %f %f \n", position[0], position[1], position[2]));
        }
-       nev++;
 //
 //      Finish the event
-       runLoader->TreeE()->Fill();
-       runLoader->SetNextEvent();
+        AliInfo(Form("Finished event %d",nev));
+       nev++;
+        if (N>0&&nev>=N)
+          break;
     } // events
  
     delete rawReader;
@@ -1640,6 +1943,40 @@ Bool_t AliSimulation::ConvertRaw2SDigits(const char* rawDirectory, const char* e
     return kTRUE;
 }
 
+//_____________________________________________________________________________
+void AliSimulation::FinishRun()
+{
+  //
+  // Called at the end of the run.
+  //
+
+  if(IsLegoRun()) 
+   {
+    AliDebug(1, "Finish Lego");
+    AliRunLoader::Instance()->CdGAFile();
+    fLego->FinishRun();
+   }
+  
+  // Clean detector information
+  TIter next(gAlice->Modules());
+  AliModule *detector;
+  while((detector = dynamic_cast<AliModule*>(next()))) {
+    AliDebug(2, Form("%s->FinishRun()", detector->GetName()));
+    detector->FinishRun();
+  }
+  
+  AliDebug(1, "AliRunLoader::Instance()->WriteHeader(OVERWRITE)");
+  AliRunLoader::Instance()->WriteHeader("OVERWRITE");
+
+  // Write AliRun info and all detectors parameters
+  AliRunLoader::Instance()->CdGAFile();
+  gAlice->Write(0,TObject::kOverwrite);//write AliRun
+  AliRunLoader::Instance()->Write(0,TObject::kOverwrite);//write RunLoader itself
+  
+  if(gAlice->GetMCApp()) gAlice->GetMCApp()->FinishRun();  
+  AliRunLoader::Instance()->Synchronize();
+}
+
 //_____________________________________________________________________________
 Int_t AliSimulation::GetDetIndex(const char* detector)
 {
@@ -1652,6 +1989,62 @@ Int_t AliSimulation::GetDetIndex(const char* detector)
   return index ; 
 }
 
+//_____________________________________________________________________________
+Bool_t AliSimulation::CreateHLT()
+{
+  // Init the HLT simulation.
+  // The function  loads the library and creates the instance of AliHLTSimulation.
+  // the main reason for the decoupled creation is to set the transient OCDB
+  // objects before the OCDB is locked
+
+  // load the library dynamically
+  gSystem->Load(ALIHLTSIMULATION_LIBRARY);
+
+  // check for the library version
+  AliHLTSimulationGetLibraryVersion_t fctVersion=(AliHLTSimulationGetLibraryVersion_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_GET_LIBRARY_VERSION));
+  if (!fctVersion) {
+    AliError(Form("can not load library %s", ALIHLTSIMULATION_LIBRARY));
+    return kFALSE;
+  }
+  if (fctVersion()!= ALIHLTSIMULATION_LIBRARY_VERSION) {
+    AliWarning(Form("%s version does not match: compiled for version %d, loaded %d", ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_LIBRARY_VERSION, fctVersion()));
+  }
+
+  // print compile info
+  typedef void (*CompileInfo)( const char*& date, const char*& time);
+  CompileInfo fctInfo=(CompileInfo)gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, "CompileInfo");
+  if (fctInfo) {
+    const char* date="";
+    const char* time="";
+    (*fctInfo)(date, time);
+    if (!date) date="unknown";
+    if (!time) time="unknown";
+    AliInfo(Form("%s build on %s (%s)", ALIHLTSIMULATION_LIBRARY, date, time));
+  } else {
+    AliInfo(Form("no build info available for %s", ALIHLTSIMULATION_LIBRARY));
+  }
+
+  // create instance of the HLT simulation
+  AliHLTSimulationCreateInstance_t fctCreate=(AliHLTSimulationCreateInstance_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_CREATE_INSTANCE));
+  if (fctCreate==NULL || (fpHLT=(fctCreate()))==NULL) {
+    AliError(Form("can not create instance of HLT simulation (creator %p)", fctCreate));
+    return kFALSE;    
+  }
+
+  TString specObjects;
+  for (Int_t i = 0; i < fSpecCDBUri.GetEntriesFast(); i++) {
+    if (specObjects.Length()>0) specObjects+=" ";
+    specObjects+=fSpecCDBUri[i]->GetName();
+  }
+
+  AliHLTSimulationSetup_t fctSetup=(AliHLTSimulationSetup_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_SETUP));
+  if (fctSetup==NULL || fctSetup(fpHLT, this, specObjects.Data())<0) {
+    AliWarning(Form("failed to setup HLT simulation (function %p)", fctSetup));
+  }
+
+  return kTRUE;
+}
+
 //_____________________________________________________________________________
 Bool_t AliSimulation::RunHLT()
 {
@@ -1661,8 +2054,8 @@ Bool_t AliSimulation::RunHLT()
   // AliSimulation::SetRunHLT can be used to set the options for HLT simulation
   // The default simulation depends on the HLT component libraries and their
   // corresponding agents which define components and chains to run. See
-  // http://web.ift.uib.no/~kjeks/doc/alice-hlt/
-  // http://web.ift.uib.no/~kjeks/doc/alice-hlt/classAliHLTModuleAgent.html
+  // http://web.ift.uib.no/~kjeks/doc/alice-hlt-current/
+  // http://web.ift.uib.no/~kjeks/doc/alice-hlt-current/classAliHLTModuleAgent.html
   //
   // The libraries to be loaded can be specified as an option.
   // <pre>
@@ -1678,62 +2071,47 @@ Bool_t AliSimulation::RunHLT()
   //     disable redirection of log messages to AliLog class
   // \li config=<i>macro</i>
   //     configuration macro
-  // \li localrec=<i>configuration</i>
+  // \li chains=<i>configuration</i>
   //     comma separated list of configurations to be run during simulation
+  // \li rawfile=<i>file</i>
+  //     source for the RawReader to be created, the default is <i>./</i> if
+  //     raw data is simulated
 
   int iResult=0;
+
+  if (!fpHLT && !CreateHLT()) {
+    return kFALSE;
+  }
+  AliHLTSimulation* pHLT=fpHLT;
+
   AliRunLoader* pRunLoader = LoadRun("READ");
   if (!pRunLoader) return kFALSE;
 
   // initialize CDB storage, run number, set CDB lock
+  // thats for the case of running HLT simulation without all the other steps
+  // multiple calls are handled by the function, so we can just call
   InitCDB();
   if (!SetRunNumberFromData()) if (fStopOnError) return kFALSE;
   SetCDBLock();
   
-  // load the library dynamically
-  gSystem->Load(ALIHLTSIMULATION_LIBRARY);
-
-  // check for the library version
-  AliHLTSimulationGetLibraryVersion_t fctVersion=(AliHLTSimulationGetLibraryVersion_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_GET_LIBRARY_VERSION));
-  if (!fctVersion) {
-    AliError(Form("can not load library %s", ALIHLTSIMULATION_LIBRARY));
-    return kFALSE;
-  }
-  if (fctVersion()!= ALIHLTSIMULATION_LIBRARY_VERSION) {
-    AliError(Form("%s version does not match: compiled for version %d, loaded %d", ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_LIBRARY_VERSION, fctVersion()));
-    return kFALSE;
-  }
-
-  // print compile info
-  typedef void (*CompileInfo)( char*& date, char*& time);
-  CompileInfo fctInfo=(CompileInfo)gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, "CompileInfo");
-  if (fctInfo) {
-    char* date="";
-    char* time="";
-    (*fctInfo)(date, time);
-    if (!date) date="unknown";
-    if (!time) time="unknown";
-    AliInfo(Form("%s build on %s (%s)", ALIHLTSIMULATION_LIBRARY, date, time));
-  } else {
-    AliInfo(Form("no build info available for %s", ALIHLTSIMULATION_LIBRARY));
-  }
-
-  // create instance of the HLT simulation
-  AliHLTSimulationCreateInstance_t fctCreate=(AliHLTSimulationCreateInstance_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_CREATE_INSTANCE));
-  AliHLTSimulation* pHLT=NULL;
-  if (fctCreate==NULL || (pHLT=(fctCreate()))==NULL) {
-    AliError(Form("can not create instance of HLT simulation (creator %p)", fctCreate));
-    return kFALSE;    
-  }
-
   // init the HLT simulation
   TString options;
   if (fRunHLT.CompareTo("default")!=0) options=fRunHLT;
-  if (!IsSelected("HLT", fWriteRawData)) {
+  TString detStr = fWriteRawData;
+  if (!IsSelected("HLT", detStr)) {
     options+=" writerawfiles=";
   } else {
     options+=" writerawfiles=HLT";
   }
+
+  if (!detStr.IsNull() && !options.Contains("rawfile=")) {
+    // as a matter of fact, HLT will run reconstruction and needs the RawReader
+    // in order to get detector data. By default, RawReaderFile is used to read
+    // the already simulated ddl files. Date and Root files from the raw data
+    // are generated after the HLT simulation.
+    options+=" rawfile=./";
+  }
+
   AliHLTSimulationInit_t fctInit=(AliHLTSimulationInit_t)(gSystem->DynFindSymbol(ALIHLTSIMULATION_LIBRARY, ALIHLTSIMULATION_INIT));
   if (fctInit==NULL || (iResult=(fctInit(pHLT, pRunLoader, options.Data())))<0) {
     AliError(Form("can not init HLT simulation: error %d (init %p)", iResult, fctInit));
@@ -1759,21 +2137,14 @@ Bool_t AliSimulation::RunHLT()
 Bool_t AliSimulation::RunQA()
 {
        // run the QA on summable hits, digits or digits
-
-       AliQADataMakerSteer qas("sim") ; 
-    qas.SetRunLoader(gAlice->GetRunLoader()) ;
+       
+    //if(!gAlice) return kFALSE;
+       AliQAManager::QAManager()->SetRunLoader(AliRunLoader::Instance()) ;
 
        TString detectorsw("") ;  
        Bool_t rv = kTRUE ; 
-       if (fQATasks.Contains(Form("%d", AliQA::kHITS))) 
-               detectorsw =  qas.Run(fQADetectors.Data(), AliQA::kHITS) ; 
-//     qas.Reset() ; 
-       if (fQATasks.Contains(Form("%d", AliQA::kSDIGITS))) 
-               detectorsw += qas.Run(fQADetectors.Data(), AliQA::kSDIGITS) ;   
-//     qas.Reset() ; 
-       if (fQATasks.Contains(Form("%d", AliQA::kDIGITS))) 
-               detectorsw += qas.Run(fQADetectors.Data(), AliQA::kDIGITS) ;    
-
+  AliQAManager::QAManager()->SetEventSpecie(fEventSpecie) ;
+       detectorsw = AliQAManager::QAManager()->Run(fQADetectors.Data()) ; 
        if ( detectorsw.IsNull() ) 
                rv = kFALSE ; 
        return rv ; 
@@ -1793,20 +2164,32 @@ Bool_t AliSimulation::SetRunQA(TString detAndAction)
        }
        Int_t colon = detAndAction.Index(":") ; 
        fQADetectors = detAndAction(0, colon) ; 
-       if (fQADetectors.Contains("ALL") )
-               fQADetectors = Form("%s %s", fMakeDigits.Data(), fMakeDigitsFromHits.Data()) ; 
-       fQATasks   = detAndAction(colon+1, detAndAction.Sizeof() ) ; 
+       if (fQADetectors.Contains("ALL") ){
+    TString tmp = Form("%s %s", fMakeDigits.Data(), fMakeDigitsFromHits.Data()) ; 
+    Int_t minus = fQADetectors.Last('-') ; 
+    TString toKeep = Form("%s %s", fMakeDigits.Data(), fMakeDigitsFromHits.Data()) ; 
+    TString toRemove("") ;
+    while (minus >= 0) {
+      toRemove = fQADetectors(minus+1, fQADetectors.Length()) ; 
+      toRemove = toRemove.Strip() ; 
+      toKeep.ReplaceAll(toRemove, "") ; 
+      fQADetectors.ReplaceAll(Form("-%s", toRemove.Data()), "") ; 
+      minus = fQADetectors.Last('-') ; 
+    }
+    fQADetectors = toKeep ; 
+  }
+  fQATasks   = detAndAction(colon+1, detAndAction.Sizeof() ) ; 
        if (fQATasks.Contains("ALL") ) {
-               fQATasks = Form("%d %d %d", AliQA::kHITS, AliQA::kSDIGITS, AliQA::kDIGITS) ; 
+               fQATasks = Form("%d %d %d", AliQAv1::kHITS, AliQAv1::kSDIGITS, AliQAv1::kDIGITS) ; 
        } else {
                fQATasks.ToUpper() ; 
                TString tempo("") ; 
                if ( fQATasks.Contains("HIT") ) 
-                       tempo = Form("%d ", AliQA::kHITS) ; 
+                       tempo = Form("%d ", AliQAv1::kHITS) ; 
                if ( fQATasks.Contains("SDIGIT") ) 
-                       tempo += Form("%d ", AliQA::kSDIGITS) ; 
+                       tempo += Form("%d ", AliQAv1::kSDIGITS) ; 
                if ( fQATasks.Contains("DIGIT") ) 
-                       tempo += Form("%d ", AliQA::kDIGITS) ; 
+                       tempo += Form("%d ", AliQAv1::kDIGITS) ; 
                fQATasks = tempo ; 
                if (fQATasks.IsNull()) {
                        AliInfo("No QA requested\n")  ;
@@ -1815,11 +2198,16 @@ Bool_t AliSimulation::SetRunQA(TString detAndAction)
                }
        }       
        TString tempo(fQATasks) ; 
-    tempo.ReplaceAll(Form("%d", AliQA::kHITS), AliQA::GetTaskName(AliQA::kHITS))       ;
-    tempo.ReplaceAll(Form("%d", AliQA::kSDIGITS), AliQA::GetTaskName(AliQA::kSDIGITS)) ;       
-    tempo.ReplaceAll(Form("%d", AliQA::kDIGITS), AliQA::GetTaskName(AliQA::kDIGITS)) ;         
+    tempo.ReplaceAll(Form("%d", AliQAv1::kHITS), AliQAv1::GetTaskName(AliQAv1::kHITS))         ;
+    tempo.ReplaceAll(Form("%d", AliQAv1::kSDIGITS), AliQAv1::GetTaskName(AliQAv1::kSDIGITS)) ; 
+    tempo.ReplaceAll(Form("%d", AliQAv1::kDIGITS), AliQAv1::GetTaskName(AliQAv1::kDIGITS)) ;   
        AliInfo( Form("QA will be done on \"%s\" for \"%s\"\n", fQADetectors.Data(), tempo.Data()) ) ;  
        fRunQA = kTRUE ;
+       AliQAManager::QAManager()->SetActiveDetectors(fQADetectors) ; 
+       AliQAManager::QAManager()->SetTasks(fQATasks) ; 
+  for (Int_t det = 0 ; det < AliQAv1::kNDET ; det++) 
+    AliQAManager::QAManager()->SetWriteExpert(AliQAv1::DETECTORINDEX_t(det)) ;
+  
        return kTRUE; 
 } 
 
@@ -1862,4 +2250,124 @@ void AliSimulation::ProcessEnvironmentVars()
     AliInfo(Form("Run number = %d", fRun)); 
 }
 
+//---------------------------------------------------------------------
+void AliSimulation::WriteGRPEntry()
+{
+  // Get the necessary information from galice (generator, trigger etc) and
+  // write a GRP entry corresponding to the settings in the Config.C used
+  // note that Hall probes and Cavern and Surface Atmos pressures are not simulated.
+
+
+  AliInfo("Writing global run parameters entry into the OCDB");
+
+  AliGRPObject* grpObj = new AliGRPObject();
+
+  grpObj->SetRunType("PHYSICS");
+  grpObj->SetTimeStart(0);
+  TDatime curtime;
+  grpObj->SetTimeStart(0);
+  grpObj->SetTimeEnd(curtime.Convert()); 
+  grpObj->SetBeamEnergyIsSqrtSHalfGeV(); // new format of GRP: store sqrt(s)/2 in GeV
+
+  const AliGenerator *gen = gAlice->GetMCApp()->Generator();
+  Int_t a = 0;
+  Int_t z = 0;
+
+  if (gen) {
+    TString projectile;
+    gen->GetProjectile(projectile,a,z);
+    TString target;
+    gen->GetTarget(target,a,z);
+    TString beamType = projectile + "-" + target;
+    beamType.ReplaceAll(" ","");
+    if (!beamType.CompareTo("-")) {
+      grpObj->SetBeamType("UNKNOWN");
+      grpObj->SetBeamEnergy(gen->GetEnergyCMS()/2);
+    }
+    else {
+      grpObj->SetBeamType(beamType);
+      if (z != 0) {
+         grpObj->SetBeamEnergy(gen->GetEnergyCMS()/2 * a / z);
+      } else {
+         grpObj->SetBeamEnergy(gen->GetEnergyCMS()/2 );
+      }
+      // Heavy ion run, the event specie is set to kHighMult
+      fEventSpecie = AliRecoParam::kHighMult;
+      if ((strcmp(beamType,"p-p") == 0) ||
+          (strcmp(beamType,"p-")  == 0) ||
+          (strcmp(beamType,"-p")  == 0) ||
+          (strcmp(beamType,"P-P") == 0) ||
+          (strcmp(beamType,"P-")  == 0) ||
+          (strcmp(beamType,"-P")  == 0)) {
+        // Proton run, the event specie is set to kLowMult
+        fEventSpecie = AliRecoParam::kLowMult;
+      } 
+    }
+  } else {
+    AliWarning("Unknown beam type and energy! Setting energy to 0");
+    grpObj->SetBeamEnergy(0);
+    grpObj->SetBeamType("UNKNOWN");
+  }
+
+  UInt_t detectorPattern  = 0;
+  Int_t nDets = 0;
+  TObjArray *detArray = gAlice->Detectors();
+  for (Int_t iDet = 0; iDet < AliDAQ::kNDetectors-1; iDet++) {
+    if (detArray->FindObject(AliDAQ::OfflineModuleName(iDet))) {
+      detectorPattern |= (1 << iDet);
+      nDets++;
+    }
+  }
+  // CTP
+  if (!fTriggerConfig.IsNull())
+    detectorPattern |= (1 << AliDAQ::DetectorID("TRG"));
+
+  // HLT
+  if (!fRunHLT.IsNull())
+    detectorPattern |= (1 << AliDAQ::kHLTId);
+
+  grpObj->SetNumberOfDetectors((Char_t)nDets);
+  grpObj->SetDetectorMask((Int_t)detectorPattern);
+  grpObj->SetLHCPeriod("LHC08c");
+  grpObj->SetLHCState("STABLE_BEAMS");
+  //
+  AliMagF *field = (AliMagF*)TGeoGlobalMagField::Instance()->GetField();
+  Float_t solenoidField = field ? TMath::Abs(field->SolenoidField()) : 0;
+
+  Float_t factorSol     = field ? field->GetFactorSol() : 0;
+  Float_t currentSol    = TMath::Abs(factorSol)>1E-6 ? 
+    TMath::Nint(TMath::Abs(solenoidField/factorSol))/5.*30000.*TMath::Abs(factorSol) : 0;
+  //
+  Float_t factorDip     = field ? field->GetFactorDip() : 0;
+  Float_t currentDip    = 6000.*TMath::Abs(factorDip);
+  //
+  grpObj->SetL3Current(currentSol,(AliGRPObject::Stats)0);
+  grpObj->SetDipoleCurrent(currentDip,(AliGRPObject::Stats)0);  
+  grpObj->SetL3Polarity(factorSol>0 ? 0:1);  
+  grpObj->SetDipolePolarity(factorDip>0 ? 0:1);
+  grpObj->SetUniformBMap(field->IsUniform());            // for special MC with k5kGUniform map
+  grpObj->SetPolarityConventionLHC();                    // LHC convention +/+ current -> -/- field main components
+  //
+  grpObj->SetCavernTemperature(0,(AliGRPObject::Stats)0);
+  
+  //grpMap->Add(new TObjString("fCavernPressure"),new TObjString("0")); ---> not inserted in simulation with the new object, since it is now an AliDCSSensor
+
+  // Now store the entry in OCDB
+  AliCDBManager* man = AliCDBManager::Instance();
+  
+  man->SetLock(0, fKey);
+  
+  AliCDBStorage* sto = man->GetStorage(fGRPWriteLocation.Data());
+  
+
+  AliCDBId id("GRP/GRP/Data", man->GetRun(), man->GetRun(), 1, 1);
+  AliCDBMetaData *metadata= new AliCDBMetaData();
+
+  metadata->SetResponsible("alice-off@cern.ch");
+  metadata->SetComment("Automatically produced GRP entry for Monte Carlo");
+  sto->Put(grpObj,id,metadata);
+  man->SetLock(1, fKey);
+}
+