]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - STEER/AliSimulation.cxx
Replace QADataMakerSteer by QAManager deriving from CDBManager
[u/mrichter/AliRoot.git] / STEER / AliSimulation.cxx
index a7786a76ce5bd2976fd759dd627fbe1595a5bb6a..07e0fb4af2fbc95572ee7ab42df9ae5061e9a07c 100644 (file)
 //                                                                           //
 ///////////////////////////////////////////////////////////////////////////////
 
-#include <TVirtualMCApplication.h>
+#include <TCint.h>
+#include <TFile.h>
+#include <TGeoGlobalMagField.h>
 #include <TGeoManager.h>
 #include <TObjString.h>
-#include <TSystem.h>
-#include <TFile.h>
 #include <TROOT.h>
+#include <TSystem.h>
+#include <TVirtualMC.h>
+#include <TVirtualMCApplication.h>
 
-#include "AliCodeTimer.h"
-#include "AliCDBStorage.h"
+#include "AliAlignObj.h"
 #include "AliCDBEntry.h"
 #include "AliCDBManager.h"
-#include "AliGeomManager.h"
-#include "AliAlignObj.h"
+#include "AliCDBStorage.h"
+#include "AliCTPRawData.h"
+#include "AliCentralTrigger.h"
 #include "AliCentralTrigger.h"
+#include "AliCodeTimer.h"
 #include "AliDAQ.h"
 #include "AliDigitizer.h"
+#include "AliESD.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 "AliSysInfo.h"
-#include "AliMagF.h"
-#include "AliGRPObject.h"
+#include "AliVertexGenFile.h"
 
 ClassImp(AliSimulation)
 
@@ -166,7 +172,6 @@ AliSimulation::AliSimulation(const char* configFileName,
   fDeleteIntermediateFiles(kFALSE),
   fWriteSelRawData(kFALSE),
   fStopOnError(kFALSE),
-
   fNEvents(1),
   fConfigFileName(configFileName),
   fGAliceFileName("galice.root"),
@@ -183,10 +188,12 @@ AliSimulation::AliSimulation(const char* configFileName,
   fInitRunNumberCalled(kFALSE),
   fSetRunNumberFromDataCalled(kFALSE),
   fEmbeddingFlag(kFALSE),
+  fLego(NULL),
   fQADetectors("ALL"),                  
   fQATasks("ALL"),     
-  fQASteer(NULL), 
+  fQAManager(NULL), 
   fRunQA(kTRUE), 
+  fEventSpecie(AliRecoParam::kDefault),
   fRunHLT("default"),
   fWriteGRPEntry(kTRUE)
 {
@@ -195,80 +202,10 @@ AliSimulation::AliSimulation(const char* configFileName,
   SetGAliceFile("galice.root");
   
 // for QA
-       fQASteer = new AliQADataMakerSteer("sim") ; 
-       fQASteer->SetActiveDetectors(fQADetectors) ; 
+       fQAManager = AliQAManager::QAManager("sim") ; 
+       fQAManager->SetActiveDetectors(fQADetectors) ; 
        fQATasks = Form("%d %d %d", AliQA::kHITS, AliQA::kSDIGITS, AliQA::kDIGITS) ; 
-       fQASteer->SetTasks(fQATasks) ;  
-}
-
-//_____________________________________________________________________________
-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), 
-       fQASteer(sim.fQASteer), 
-  fRunQA(sim.fRunQA), 
-  fRunHLT(sim.fRunHLT),
-  fWriteGRPEntry(sim.fWriteGRPEntry)
-{
-// 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;
-}
-
-//_____________________________________________________________________________
-AliSimulation& AliSimulation::operator = (const AliSimulation& sim)
-{
-// assignment operator
-
-  this->~AliSimulation();
-  new(this) AliSimulation(sim);
-  return *this;
+       fQAManager->SetTasks(fQATasks) ;        
 }
 
 //_____________________________________________________________________________
@@ -288,7 +225,7 @@ AliSimulation::~AliSimulation()
   fSpecCDBUri.Delete();
   if (fgInstance==this) fgInstance = 0;
 
-       delete fQASteer ; 
+       delete fQAManager ; 
        
   AliCodeTimer::Instance()->Print();
 }
@@ -328,7 +265,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()));
@@ -449,7 +386,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;
     }
   
@@ -746,6 +683,144 @@ Bool_t AliSimulation::Run(Int_t nEvents)
   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("")
+
+  // 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();  
+  
+  gAlice->GetMCApp()->Init();
+  
+  gMC->SetMagField(TGeoGlobalMagField::Instance()->GetField());
+
+  
+  //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)
 {
@@ -771,7 +846,7 @@ Bool_t AliSimulation::RunTrigger(const char* config, const char* detectors)
    TString trconfiguration = config;
 
    if (trconfiguration.IsNull()) {
-     if (gAlice->GetTriggerDescriptor() != "") {
+     if (strcmp(gAlice->GetTriggerDescriptor(),"")) {
        trconfiguration = gAlice->GetTriggerDescriptor();
      }
      else
@@ -833,15 +908,48 @@ 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();
+
+  gROOT->LoadMacro(fConfigFileName.Data());
+  gInterpreter->ProcessLine(gAlice->GetConfigFunction());
+
+  if(AliCDBManager::Instance()->GetRun() >= 0) { 
+    AliRunLoader::Instance()->SetRunNumber(AliCDBManager::Instance()->GetRun());
+  } else {
+       AliWarning("Run number not initialized!!");
+  }
+  
+   AliRunLoader::Instance()->CdGAFile();
+    
+   AliPDG::AddParticlesToPdgDataBase();  
+
+   gAlice->GetMCApp()->Init();
+
+   gMC->SetMagField(TGeoGlobalMagField::Instance()->GetField());
+   
+   //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
+  //___________________________________________________________________________________________
   
   // Get the trigger descriptor string
   // Either from AliSimulation or from
   // gAlice
   if (fMakeTrigger.IsNull()) {
-    if (gAlice->GetTriggerDescriptor() != "")
+    if (strcmp(gAlice->GetTriggerDescriptor(),""))
       fMakeTrigger = gAlice->GetTriggerDescriptor();
   }
   else
@@ -850,7 +958,7 @@ Bool_t AliSimulation::RunSimulation(Int_t nEvents)
   // 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()));
@@ -877,7 +985,7 @@ Bool_t AliSimulation::RunSimulation(Int_t nEvents)
   MisalignGeometry(runLoader);
 #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()));
@@ -885,7 +993,7 @@ 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;
@@ -907,11 +1015,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
@@ -943,9 +1051,15 @@ Bool_t AliSimulation::RunSimulation(Int_t nEvents)
 
   AliInfo("running gAlice");
   AliSysInfo::AddStamp("Start_simulation");
-  StdoutToAliInfo(StderrToAliError(
-    gAlice->Run(nEvents);
-  ););
+
+  // 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_simulation");
   delete runLoader;
 
@@ -1005,8 +1119,8 @@ Bool_t AliSimulation::RunDigitization(const char* detectors,
   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;
@@ -1091,10 +1205,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;
 }
 
@@ -1265,6 +1375,11 @@ 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++) {
 
@@ -1448,7 +1563,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);
@@ -1562,17 +1677,46 @@ 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();  
+
+   gAlice->GetMCApp()->Init();
+
+   gMC->SetMagField(TGeoGlobalMagField::Instance()->GetField());
+   
+   //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();
@@ -1582,7 +1726,7 @@ 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);
@@ -1669,6 +1813,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)
 {
@@ -1740,12 +1918,14 @@ Bool_t AliSimulation::RunHLT()
   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";
+    Char_t* date=0;
+    Char_t* time=0;
+    (*fctInfo)(date,time);
+    if (!date) {date=new Char_t[8]; strcpy(date,"unknown");}
+    if (!time) {time=new Char_t[8]; strcpy(time,"unknown");}
     AliInfo(Form("%s build on %s (%s)", ALIHLTSIMULATION_LIBRARY, date, time));
+    delete date;
+    delete time;
   } else {
     AliInfo(Form("no build info available for %s", ALIHLTSIMULATION_LIBRARY));
   }
@@ -1802,15 +1982,15 @@ Bool_t AliSimulation::RunQA()
 {
        // run the QA on summable hits, digits or digits
        
-       fQASteer->SetRunLoader(gAlice->GetRunLoader()) ;
+  if(!gAlice) return kFALSE;
+       fQAManager->SetRunLoader(AliRunLoader::Instance()) ;
 
        TString detectorsw("") ;  
        Bool_t rv = kTRUE ; 
-       detectorsw = fQASteer->Run(fQADetectors.Data()) ; 
+  fQAManager->SetEventSpecie(fEventSpecie) ;
+       detectorsw = fQAManager->Run(fQADetectors.Data()) ; 
        if ( detectorsw.IsNull() ) 
                rv = kFALSE ; 
-  else 
-    fQASteer->EndOfCycle(detectorsw) ; 
        return rv ; 
 }
 
@@ -1855,8 +2035,11 @@ Bool_t AliSimulation::SetRunQA(TString detAndAction)
     tempo.ReplaceAll(Form("%d", AliQA::kDIGITS), AliQA::GetTaskName(AliQA::kDIGITS)) ;         
        AliInfo( Form("QA will be done on \"%s\" for \"%s\"\n", fQADetectors.Data(), tempo.Data()) ) ;  
        fRunQA = kTRUE ;
-       fQASteer->SetActiveDetectors(fQADetectors) ; 
-       fQASteer->SetTasks(fQATasks) ; 
+       fQAManager->SetActiveDetectors(fQADetectors) ; 
+       fQAManager->SetTasks(fQATasks) ; 
+  for (Int_t det = 0 ; det < AliQA::kNDET ; det++) 
+    fQAManager->SetWriteExpert(AliQA::DETECTORINDEX_t(det)) ;
+  
        return kTRUE; 
 } 
 
@@ -1900,7 +2083,6 @@ void AliSimulation::ProcessEnvironmentVars()
 }
 
 //---------------------------------------------------------------------
-
 void AliSimulation::WriteGRPEntry()
 {
   // Get the necessary information from galice (generator, trigger etc) and
@@ -1916,7 +2098,7 @@ void AliSimulation::WriteGRPEntry()
   grpObj->SetTimeStart(0);
   grpObj->SetTimeEnd(9999);
 
-  const AliGenerator *gen = gAlice->Generator();
+  const AliGenerator *gen = gAlice->GetMCApp()->Generator();
   if (gen) {
     grpObj->SetBeamEnergy(gen->GetEnergyCMS());
     TString projectile;
@@ -1925,15 +2107,25 @@ void AliSimulation::WriteGRPEntry()
     TString target;
     gen->GetTarget(target,a,z);
     TString beamType = projectile + "-" + target;
+    beamType.ReplaceAll(" ","");
     if (!beamType.CompareTo("-")) {
-
-       grpObj->SetBeamType("UNKNOWN");
+      grpObj->SetBeamType("UNKNOWN");
     }
     else {
-       grpObj->SetBeamType(beamType);
+      grpObj->SetBeamType(beamType);
+      // 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 {
+  } else {
     AliWarning("Unknown beam type and energy! Setting energy to 0");
     grpObj->SetBeamEnergy(0);
     grpObj->SetBeamType("UNKNOWN");
@@ -1948,6 +2140,10 @@ void AliSimulation::WriteGRPEntry()
       nDets++;
     }
   }
+  // CTP
+  if (!fMakeTrigger.IsNull() || strcmp(gAlice->GetTriggerDescriptor(),""))
+    detectorPattern |= (1 << AliDAQ::DetectorID("TRG"));
+
   // HLT
   if (!fRunHLT.IsNull())
     detectorPattern |= (1 << AliDAQ::kHLTId);
@@ -1959,9 +2155,9 @@ void AliSimulation::WriteGRPEntry()
   grpObj->SetLHCLuminosity(0,(AliGRPObject::Stats)0);
   grpObj->SetBeamIntensity(0,(AliGRPObject::Stats)0);
 
-  AliMagF *field = gAlice->Field();
-  Float_t solenoidField = TMath::Abs(field->SolenoidField());
-  Float_t factor = field->Factor();
+  AliMagF *field = (AliMagF*)TGeoGlobalMagField::Instance()->GetField();
+  Float_t solenoidField = field ? TMath::Abs(field->SolenoidField()) : 0;
+  Float_t factor =        field ? field->Factor() : 0;
   Float_t l3current = TMath::Abs(factor)*solenoidField*30000./5.;
   grpObj->SetL3Current(l3current,(AliGRPObject::Stats)0);
   
@@ -1986,7 +2182,7 @@ void AliSimulation::WriteGRPEntry()
   // Now store the entry in OCDB
   AliCDBManager* man = AliCDBManager::Instance();
 
-  AliCDBId id("GRP/GRP/Data", man->GetRun(), man->GetRun());
+  AliCDBId id("GRP/GRP/Data", man->GetRun(), man->GetRun(), 1, 1);
   AliCDBMetaData *metadata= new AliCDBMetaData();
 
   metadata->SetResponsible("alice-off@cern.ch");