]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - STEER/AliRun.cxx
Method for file synchronization (P.Skowronski)
[u/mrichter/AliRoot.git] / STEER / AliRun.cxx
index a414845500e02c1dc5749a5bf1f4c8afcf9c0383..9f39bb9aef97021f5de34e1088f8515bfec864e7 100644 (file)
@@ -1,3 +1,20 @@
+/**************************************************************************
+ * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
+ *                                                                        *
+ * Author: The ALICE Off-line Project.                                    *
+ * Contributors are mentioned in the code where appropriate.              *
+ *                                                                        *
+ * Permission to use, copy, modify and distribute this software and its   *
+ * documentation strictly for non-commercial purposes is hereby granted   *
+ * without fee, provided that the above copyright notice appears in all   *
+ * copies and that both the copyright notice and this permission notice   *
+ * appear in the supporting documentation. The authors make no claims     *
+ * about the suitability of this software for any purpose. It is          *
+ * provided "as is" without express or implied warranty.                  *
+ **************************************************************************/
+
+/* $Id$ */
+
 ///////////////////////////////////////////////////////////////////////////////
 //                                                                           //
 //  Control class for Alice C++                                              //
 //                                                                           //
 ///////////////////////////////////////////////////////////////////////////////
 
-#include <TFile.h>
-#include <TRandom.h>
+#include <Riostream.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
 #include <TBRIK.h> 
-#include <TNode.h> 
-#include <AliMC.h> 
+#include <TBrowser.h>
 #include <TCint.h> 
+#include <TFile.h>
+#include <TFolder.h>
+#include <TGeometry.h>
+#include <TKey.h>
+#include <TNode.h>
+#include <TObjectTable.h>
+#include <TParticle.h>
+#include <TROOT.h>
+#include <TRandom.h>
+#include <TRandom3.h>
 #include <TSystem.h>
+#include <TTree.h>
+#include <TVirtualMC.h>
 
-#include "GParticle.h"
-#include "AliRun.h"
-#include "AliModule.h"
+#include "AliConfig.h"
+#include "AliDetector.h"
 #include "AliDisplay.h"
+#include "AliGenEventHeader.h"
+#include "AliGenerator.h"
+#include "AliHeader.h"
+#include "AliHit.h"
+#include "AliLego.h"
+#include "AliLegoGenerator.h"
+#include "AliLoader.h"
+#include "AliMCQA.h"
+#include "AliMagFC.h"
+#include "AliMagFCM.h"
+#include "AliMagFDM.h"
+#include "AliPDG.h"
+#include "AliRun.h"
+#include "AliRunLoader.h"
+#include "AliStack.h"
 
-#include "AliCallf77.h" 
-#include <stdlib.h>
-#include <stdio.h>
-#include <string.h>
 AliRun *gAlice;
 
-static AliHeader *header;
-
-#ifndef WIN32
-
-# define rxgtrak rxgtrak_
-# define rxstrak rxstrak_
-# define rxkeep  rxkeep_ 
-# define rxouth  rxouth_
-# define sxpart  sxpart_
-#else
-
-# define rxgtrak RXGTRAK 
-# define rxstrak RXSTRAK 
-# define rxkeep  RXKEEP  
-# define rxouth  RXOUTH
-# define sxpart  SXPART
-#endif
-
-static TArrayF sEventEnergy;
-static TArrayF sSummEnergy;
-static TArrayF sSum2Energy;
-
-extern "C" void type_of_call sxpart();
-
 ClassImp(AliRun)
 
-//_____________________________________________________________________________
-AliRun::AliRun()
+//_______________________________________________________________________
+AliRun::AliRun():
+  fRun(0),
+  fEvent(0),
+  fEventNrInRun(0),
+  fEventsPerRun(0),
+  fDebug(0),
+  fModules(0),
+  fGeometry(0),
+  fDisplay(0),
+  fTimer(),
+  fField(0),
+  fMC(0),
+  fImedia(0),
+  fNdets(0),
+  fTrRmax(1.e10),
+  fTrZmax(1.e10),
+  fGenerator(0),
+  fInitDone(kFALSE),
+  fLego(0),
+  fPDGDB(0),  //Particle factory object
+  fHitLists(0),
+  fEventEnergy(0),
+  fSummEnergy(0),
+  fSum2Energy(0),
+  fConfigFunction("\0"),
+  fRandom(0),
+  fMCQA(0),
+  fTransParName("\0"),
+  fRunLoader(0x0)
 {
   //
   // Default constructor for AliRun
   //
-  header=&fHeader;
-  fRun       = 0;
-  fEvent     = 0;
-  fCurrent   = -1;
-  fModules = 0;
-  fGenerator = 0;
-  fTreeD     = 0;
-  fTreeK     = 0;
-  fTreeH     = 0;
-  fTreeE     = 0;
-  fTreeR     = 0;
-  fParticles = 0;
-  fGeometry  = 0;
-  fDisplay   = 0;
-  fField     = 0;
-  fMC        = 0;
-  fNdets     = 0;
-  fImedia    = 0;
-  fTrRmax    = 1.e10;
-  fTrZmax    = 1.e10;
-  fIdtmed    = 0;
-  fInitDone  = kFALSE;
-  fLego      = 0;
+  AliConfig::Instance();//skowron 29 Feb 2002
+                        //ensures that the folder structure is build
+}
+
+//_______________________________________________________________________
+AliRun::AliRun(const AliRun& arun):
+  TVirtualMCApplication(arun),
+  fRun(0),
+  fEvent(0),
+  fEventNrInRun(0),
+  fEventsPerRun(0),
+  fDebug(0),
+  fModules(0),
+  fGeometry(0),
+  fDisplay(0),
+  fTimer(),
+  fField(0),
+  fMC(0),
+  fImedia(0),
+  fNdets(0),
+  fTrRmax(1.e10),
+  fTrZmax(1.e10),
+  fGenerator(0),
+  fInitDone(kFALSE),
+  fLego(0),
+  fPDGDB(0),  //Particle factory object
+  fHitLists(0),
+  fEventEnergy(0),
+  fSummEnergy(0),
+  fSum2Energy(0),
+  fConfigFunction("\0"),
+  fRandom(0),
+  fMCQA(0),
+  fTransParName("\0"),
+  fRunLoader(0x0)
+{
+  //
+  // Copy constructor for AliRun
+  //
+  arun.Copy(*this);
 }
 
 //_____________________________________________________________________________
-AliRun::AliRun(const char *name, const char *title)
-  : TNamed(name,title)
+AliRun::AliRun(const char *name, const char *title):
+  TVirtualMCApplication(name,title),
+  fRun(0),
+  fEvent(0),
+  fEventNrInRun(0),
+  fEventsPerRun(0),
+  fDebug(0),
+  fModules(new TObjArray(77)), // Support list for the Detectors
+  fGeometry(0),
+  fDisplay(0),
+  fTimer(),
+  fField(0),
+  fMC(gMC),
+  fImedia(new TArrayI(1000)),
+  fNdets(0),
+  fTrRmax(1.e10),
+  fTrZmax(1.e10),
+  fGenerator(0),
+  fInitDone(kFALSE),
+  fLego(0),
+  fPDGDB(TDatabasePDG::Instance()),        //Particle factory object!
+  fHitLists(new TList()),                  // Create HitLists list
+  fEventEnergy(0),
+  fSummEnergy(0),
+  fSum2Energy(0),
+  fConfigFunction("Config();"),
+  fRandom(new TRandom3()),
+  fMCQA(0),
+  fTransParName("\0"),
+  fRunLoader(0x0)
 {
   //
   //  Constructor for the main processor.
@@ -111,131 +199,100 @@ AliRun::AliRun(const char *name, const char *title)
   //  Creates the list of Detectors.
   //  Creates the list of particles.
   //
-  Int_t i;
-  
+
   gAlice     = this;
-  fTreeD     = 0;
-  fTreeK     = 0;
-  fTreeH     = 0;
-  fTreeE     = 0;
-  fTreeR     = 0;
-  fTrRmax    = 1.e10;
-  fTrZmax    = 1.e10;
-  fGenerator = 0;
-  fInitDone  = kFALSE;
-  fLego      = 0;
-  fField     = 0;
-  
+
+  // Set random number generator
+  gRandom = fRandom;
+
+  if (gSystem->Getenv("CONFIG_SEED")) {
+     gRandom->SetSeed(static_cast<UInt_t>(atoi(gSystem->Getenv("CONFIG_SEED"))));
+  }
+
+  // Add to list of browsable  
   gROOT->GetListOfBrowsables()->Add(this,name);
-  //
-  // create the support list for the various Detectors
-  fModules = new TObjArray(77);
-  //
   // Create the TNode geometry for the event display
-  
   BuildSimpleGeometry();
   
-
-  fNtrack=0;
-  fHgwmk=0;
-  fCurrent=-1;
-  header=&fHeader;
-  fRun       = 0;
-  fEvent     = 0;
-  //
-  // Create the particle stack
-  fParticles = new TClonesArray("GParticle",100);
-  
-  fDisplay = 0;
-  //
   // Create default mag field
   SetField();
-  //
-  fMC      = AliMC::GetMC();
-  //
-  //---------------Load detector names
-  
-  fNdets=21;
-  strcpy(fDnames[0],"BODY");
-  strcpy(fDnames[1],"NULL");
-  strcpy(fDnames[2],"ITS");
-  strcpy(fDnames[3],"MAG");
-  strcpy(fDnames[4],"TPC");
-  strcpy(fDnames[5],"TOF");
-  strcpy(fDnames[6],"PMD");
-  strcpy(fDnames[7],"PHOS");
-  strcpy(fDnames[8],"ZDC");
-  strcpy(fDnames[9],"FMD");
-  strcpy(fDnames[10],"RICH");
-  strcpy(fDnames[11],"MUON");
-  strcpy(fDnames[12],"FRAME");
-  strcpy(fDnames[13],"TRD");
-  strcpy(fDnames[14],"NULL");
-  strcpy(fDnames[15],"CASTOR");
-  strcpy(fDnames[16],"ABSO");
-  strcpy(fDnames[17],"SHIL");
-  strcpy(fDnames[18],"DIPO");
-  strcpy(fDnames[19],"HALL");
-  strcpy(fDnames[20],"PIPE");
-  
-  //
+
   // Prepare the tracking medium lists
-  fImedia = new TArrayI(1000);
-  for(i=0;i<1000;i++) (*fImedia)[i]=-99;
-  fIdtmed = new Int_t[fNdets*100];
-  for(i=0;i<fNdets*100;i++) fIdtmed[i]=0;
+  for(Int_t i=0;i<1000;i++) (*fImedia)[i]=-99;
+
+  // Add particle list to configuration
+  AliConfig::Instance()->Add(fPDGDB); 
+
+  // Set transport parameters
+  SetTransPar();
 }
 
-//_____________________________________________________________________________
+
+//_______________________________________________________________________
 AliRun::~AliRun()
 {
   //
-  // Defaullt AliRun destructor
+  // Default AliRun destructor
   //
-  delete [] fIdtmed;
+  gROOT->GetListOfBrowsables()->Remove(this);
+
+  if (fRunLoader)
+   {
+    TFolder* evfold = fRunLoader->GetEventFolder();
+    TFolder* modfold = dynamic_cast<TFolder*>(evfold->FindObjectAny(AliConfig::GetModulesFolderName()));
+    TIter next(fModules);
+    AliModule *mod;
+    while((mod = (AliModule*)next()))
+     { 
+       modfold->Remove(mod);
+     }
+   }
+   
   delete fImedia;
   delete fField;
-  delete fMC;
+  // delete fMC;
+  delete gMC; gMC=0;
   delete fGeometry;
   delete fDisplay;
   delete fGenerator;
   delete fLego;
-  delete fTreeD;
-  delete fTreeK;
-  delete fTreeH;
-  delete fTreeE;
-  delete fTreeR;
   if (fModules) {
     fModules->Delete();
     delete fModules;
   }
-  if (fParticles) {
-    fParticles->Delete();
-    delete fParticles;
-  }
+  
+  delete fHitLists;
+  delete fPDGDB;
+  delete fMCQA;
 }
 
-//_____________________________________________________________________________
+//_______________________________________________________________________
+void AliRun::Copy(AliRun &) const
+{
+  Fatal("Copy","Not implemented!\n");
+}
+
+//_______________________________________________________________________
 void AliRun::AddHit(Int_t id, Int_t track, Int_t *vol, Float_t *hits) const
 {
   //
   //  Add a hit to detector id
   //
   TObjArray &dets = *fModules;
-  if(dets[id]) ((AliModule*) dets[id])->AddHit(track,vol,hits);
+  if(dets[id]) dynamic_cast<AliModule*>(dets[id])->AddHit(track,vol,hits);
 }
 
-//_____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::AddDigit(Int_t id, Int_t *tracks, Int_t *digits) const
 {
   //
   // Add digit to detector id
   //
   TObjArray &dets = *fModules;
-  if(dets[id]) ((AliModule*) dets[id])->AddDigit(tracks,digits);
+  if(dets[id]) dynamic_cast<AliModule*>(dets[id])->AddDigit(tracks,digits);
 }
 
-//_____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::Browse(TBrowser *b)
 {
   //
@@ -243,20 +300,11 @@ void AliRun::Browse(TBrowser *b)
   // of the Root browser.
   // It displays the Root Trees and all detectors.
   //
-  if (fTreeK) b->Add(fTreeK,fTreeK->GetName());
-  if (fTreeH) b->Add(fTreeH,fTreeH->GetName());
-  if (fTreeD) b->Add(fTreeD,fTreeD->GetName());
-  if (fTreeE) b->Add(fTreeE,fTreeE->GetName());
-  if (fTreeR) b->Add(fTreeR,fTreeR->GetName());
-  
-  TIter next(fModules);
-  AliModule *detector;
-  while((detector = (AliModule*)next())) {
-    b->Add(detector,detector->GetName());
-  }
+  //detectors are in folders anyway
+  b->Add(fMCQA,"AliMCQA");
 }
 
-//_____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::Build()
 {
   //
@@ -265,7 +313,7 @@ void AliRun::Build()
   //
 }
  
-//_____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::BuildSimpleGeometry()
 {
   //
@@ -280,40 +328,17 @@ void AliRun::BuildSimpleGeometry()
   new TNode("alice","alice","S_alice");
 }
 
-//_____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::CleanDetectors()
 {
   //
   // Clean Detectors at the end of event
   //
-  TIter next(fModules);
-  AliModule *detector;
-  while((detector = (AliModule*)next())) {
-    detector->FinishEvent();
-  }
-}
-
-//_____________________________________________________________________________
-void AliRun::CleanParents()
-{
-  //
-  // Clean Particles stack.
-  // Set parent/child relations
-  //
-  TClonesArray &particles = *(gAlice->Particles());
-  GParticle *part;
-  int i;
-  for(i=0; i<fNtrack; i++) {
-    part = (GParticle *)particles.UncheckedAt(i);
-    if(!part->TestBit(Children_Bit)) {
-      part->SetFirstChild(-1);
-      part->SetLastChild(-1);
-    }
-  }
+   fRunLoader->CleanDetectors();
 }
 
-//_____________________________________________________________________________
-Int_t AliRun::DistancetoPrimitive(Int_t, Int_t)
+//_______________________________________________________________________
+Int_t AliRun::DistancetoPrimitive(Int_t, Int_t) const
 {
   //
   // Return the distance from the mouse to the AliRun object
@@ -322,35 +347,35 @@ Int_t AliRun::DistancetoPrimitive(Int_t, Int_t)
   return 9999;
 }
 
-//_____________________________________________________________________________
-void AliRun::DumpPart (Int_t i)
+//_______________________________________________________________________
+void AliRun::DumpPart (Int_t i) const
 {
   //
   // Dumps particle i in the stack
   //
-  TClonesArray &particles = *fParticles;
-  ((GParticle*) particles[i])->Dump();
+   if (fRunLoader->Stack())
+    fRunLoader->Stack()->DumpPart(i);
 }
 
-//_____________________________________________________________________________
-void AliRun::DumpPStack ()
+//_______________________________________________________________________
+void AliRun::DumpPStack () const
 {
   //
   // Dumps the particle stack
   //
-  TClonesArray &particles = *fParticles;
-  printf(
-        "\n\n=======================================================================\n");
-  for (Int_t i=0;i<fNtrack;i++) 
-    {
-      printf("-> %d ",i); ((GParticle*) particles[i])->Dump();
-      printf("--------------------------------------------------------------\n");
-    }
-  printf(
-        "\n=======================================================================\n\n");
+   if (fRunLoader->Stack())
+    fRunLoader->Stack()->DumpPStack();
 }
 
-//_____________________________________________________________________________
+//_______________________________________________________________________
+void  AliRun::SetField(AliMagF* magField)
+{
+    // Set Magnetic Field Map
+    fField = magField;
+    fField->ReadField();
+}
+
+//_______________________________________________________________________
 void AliRun::SetField(Int_t type, Int_t version, Float_t scale,
                      Float_t maxField, char* filename)
 {
@@ -363,208 +388,123 @@ void AliRun::SetField(Int_t type, Int_t version, Float_t scale,
 
   //
   // --- Sanity check on mag field flags
-  if(type<0 || type > 2) {
-    printf(" Invalid magnetic field flag: %5d; Helix tracking chosen instead\n"
-          ,type);
-    type=2;
-  }
   if(fField) delete fField;
   if(version==1) {
-    fField = new AliMagFC("Map1"," ",type,version,scale,maxField);
-  } else if(version<=3) {
-    fField = new AliMagFCM("Map2-3",filename,type,version,scale,maxField);
+    fField = new AliMagFC("Map1"," ",type,scale,maxField);
+  } else if(version<=2) {
+    fField = new AliMagFCM("Map2-3",filename,type,scale,maxField);
+    fField->ReadField();
+  } else if(version==3) {
+    fField = new AliMagFDM("Map4",filename,type,scale,maxField);
     fField->ReadField();
   } else {
-    printf("Invalid map %d\n",version);
+    Warning("SetField","Invalid map %d\n",version);
   }
 }
 
 //_____________________________________________________________________________
-void AliRun::FillTree()
-{
-  //
-  // Fills all AliRun TTrees
-  //
-  if (fTreeK) fTreeK->Fill();
-  if (fTreeH) fTreeH->Fill();
-  if (fTreeD) fTreeD->Fill();
-  if (fTreeR) fTreeR->Fill();
-}
-//_____________________________________________________________________________
-void AliRun::FinishPrimary()
-{
-  //
-  // Called  at the end of each primary track
-  //
-  
-  // This primary is finished, purify stack
-  gAlice->PurifyKine();
-
-  // Write out hits if any
-  if (gAlice->TreeH()) {
-    gAlice->TreeH()->Fill();
-  }
-  
-  // Reset Hits info
-  gAlice->ResetHits();
-}
 
-//_____________________________________________________________________________
-void AliRun::FinishEvent()
+void AliRun::InitLoaders()
 {
-  //
-  // Called at the end of the event.
-  //
-  
-  //Update the energy deposit tables
-  Int_t i;
-  for(i=0;i<sEventEnergy.GetSize();i++) {
-    sSummEnergy[i]+=sEventEnergy[i];
-    sSum2Energy[i]+=sEventEnergy[i]*sEventEnergy[i];
-  }
-  sEventEnergy.Reset();
-  
-  // Clean detector information
-  CleanDetectors();
-  
-  // Write out the kinematics
-  if (fTreeK) {
-    CleanParents();
-    fTreeK->Fill();
-  }
-  
-  // Write out the digits
-  if (fTreeD) {
-    fTreeD->Fill();
-    ResetDigits();
-  }
-  
-  // Write out reconstructed clusters  
-  if (fTreeR) {
-    fTreeR->Fill();
-  }
-
-  // Write out the event Header information
-  if (fTreeE) fTreeE->Fill();
-  
-  // Reset stack info
-  ResetStack();
-  
-  // Write Tree headers
-  Int_t ievent = fHeader.GetEvent();
-  char hname[30];
-  sprintf(hname,"TreeK%d",ievent);
-  if (fTreeK) fTreeK->Write(hname);
-  sprintf(hname,"TreeH%d",ievent);
-  if (fTreeH) fTreeH->Write(hname);
-  sprintf(hname,"TreeD%d",ievent);
-  if (fTreeD) fTreeD->Write(hname);
-  sprintf(hname,"TreeR%d",ievent);
-  if (fTreeR) fTreeR->Write(hname);
+  //creates list of getters
+  if (GetDebug()) Info("InitLoaders","");
+  TIter next(fModules);
+  AliModule *mod;
+  while((mod = (AliModule*)next()))
+   { 
+     AliDetector *det = dynamic_cast<AliDetector*>(mod);
+     if (det) 
+      {
+        if (GetDebug()) Info("InitLoaders"," Adding %s ",det->GetName());
+        fRunLoader->AddLoader(det);
+      }
+   }
+  if (GetDebug()) Info("InitLoaders","Done");
 }
-
 //_____________________________________________________________________________
+
 void AliRun::FinishRun()
 {
   //
   // Called at the end of the run.
   //
-
+  
+  if(fLego) 
+   {
+    if (GetDebug()) Info("FinishRun"," Finish Lego");
+    fRunLoader->CdGAFile();
+    fLego->FinishRun();
+   }
+  
   // Clean detector information
   TIter next(fModules);
   AliModule *detector;
-  while((detector = (AliModule*)next())) {
+  while((detector = dynamic_cast<AliModule*>(next()))) {
+    if (GetDebug()) Info("FinishRun"," %s->FinishRun()",detector->GetName());
     detector->FinishRun();
   }
   
   //Output energy summary tables
+  if (GetDebug()) Info("FinishRun"," EnergySummary()");
   EnergySummary();
   
-  // file is retrieved from whatever tree
-  TFile *File = 0;
-  if (fTreeK) File = fTreeK->GetCurrentFile();
-  if ((!File) && (fTreeH)) File = fTreeH->GetCurrentFile();
-  if ((!File) && (fTreeD)) File = fTreeD->GetCurrentFile();
-  if ((!File) && (fTreeE)) File = fTreeE->GetCurrentFile();
-  if( NULL==File ) {
-    Error("FinishRun","There isn't root file!");
-    exit(1);
-  }
-  File->cd();
-  fTreeE->Write();
+  if (GetDebug()) Info("FinishRun"," fRunLoader->WriteHeader(OVERWRITE)");
+  fRunLoader->WriteHeader("OVERWRITE");
+
+  // Write AliRun info and all detectors parameters
+  fRunLoader->CdGAFile();
+  Write(0,TObject::kOverwrite);//write AliRun
+  fRunLoader->Write(0,TObject::kOverwrite);//write RunLoader itself
   
   // Clean tree information
-  delete fTreeK; fTreeK = 0;
-  delete fTreeH; fTreeH = 0;
-  delete fTreeD; fTreeD = 0;
-  delete fTreeR; fTreeR = 0;
-  delete fTreeE; fTreeE = 0;
-  
-  // Write AliRun info and all detectors parameters
-  Write();
+  if (GetDebug()) Info("FinishRun"," fRunLoader->Stack()->FinishRun()");
+  fRunLoader->Stack()->FinishRun();
+
+  // Clean detector information
+  if (GetDebug()) Info("FinishRun"," fGenerator->FinishRun()");
+  fGenerator->FinishRun();
   
-  // Close output file
-  File->Write();
-  File->Close();
+  fRunLoader->Synchronize();
 }
 
-//_____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::FlagTrack(Int_t track)
 {
+  // Delegate to stack
   //
-  // Flags a track and all its family tree to be kept
-  //
-  int curr;
-  GParticle *particle;
-
-  curr=track;
-  while(1) {
-    particle=(GParticle*)fParticles->UncheckedAt(curr);
-    
-    // If the particle is flagged the three from here upward is saved already
-    if(particle->TestBit(Keep_Bit)) return;
-    
-    // Save this particle
-    particle->SetBit(Keep_Bit);
-    
-    // Move to father if any
-    if((curr=particle->GetParent())==-1) return;
-  }
+    fRunLoader->Stack()->FlagTrack(track);
 }
  
-//_____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::EnergySummary()
 {
   //
   // Print summary of deposited energy
   //
 
-  AliMC* pMC = AliMC::GetMC();
-
   Int_t ndep=0;
   Float_t edtot=0;
   Float_t ed, ed2;
   Int_t kn, i, left, j, id;
-  const Float_t zero=0;
-  Int_t ievent=fHeader.GetEvent()+1;
+  const Float_t kzero=0;
+  Int_t ievent=fRunLoader->GetHeader()->GetEvent()+1;
   //
   // Energy loss information
   if(ievent) {
     printf("***************** Energy Loss Information per event (GEV) *****************\n");
-    for(kn=1;kn<sEventEnergy.GetSize();kn++) {
-      ed=sSummEnergy[kn];
+    for(kn=1;kn<fEventEnergy.GetSize();kn++) {
+      ed=fSummEnergy[kn];
       if(ed>0) {
-       sEventEnergy[ndep]=kn;
+       fEventEnergy[ndep]=kn;
        if(ievent>1) {
          ed=ed/ievent;
-         ed2=sSum2Energy[kn];
+         ed2=fSum2Energy[kn];
          ed2=ed2/ievent;
-         ed2=100*TMath::Sqrt(TMath::Max(ed2-ed*ed,zero))/ed;
+         ed2=100*TMath::Sqrt(TMath::Max(ed2-ed*ed,kzero))/ed;
        } else 
          ed2=99;
-       sSummEnergy[ndep]=ed;
-       sSum2Energy[ndep]=TMath::Min((Float_t) 99.,TMath::Max(ed2,zero));
+       fSummEnergy[ndep]=ed;
+       fSum2Energy[ndep]=TMath::Min(static_cast<Float_t>(99.),TMath::Max(ed2,kzero));
        edtot+=ed;
        ndep++;
       }
@@ -573,8 +513,8 @@ void AliRun::EnergySummary()
       left=ndep-kn*3;
       for(i=0;i<(3<left?3:left);i++) {
        j=kn*3+i;
-        id=Int_t (sEventEnergy[j]+0.1);
-       printf(" %s %10.3f +- %10.3f%%;",pMC->VolName(id),sSummEnergy[j],sSum2Energy[j]);
+        id=Int_t (fEventEnergy[j]+0.1);
+       printf(" %s %10.3f +- %10.3f%%;",gMC->VolName(id),fSummEnergy[j],fSum2Energy[j]);
       }
       printf("\n");
     }
@@ -586,8 +526,8 @@ void AliRun::EnergySummary()
       left=ndep-kn*5;
       for(i=0;i<(5<left?5:left);i++) {
        j=kn*5+i;
-        id=Int_t (sEventEnergy[j]+0.1);
-       printf(" %s %10.3f%%;",pMC->VolName(id),100*sSummEnergy[j]/edtot);
+        id=Int_t (fEventEnergy[j]+0.1);
+       printf(" %s %10.3f%%;",gMC->VolName(id),100*fSummEnergy[j]/edtot);
       }
       printf("\n");
     }
@@ -596,131 +536,126 @@ void AliRun::EnergySummary()
   }
   //
   // Reset the TArray's
-  sEventEnergy.Set(0);
-  sSummEnergy.Set(0);
-  sSum2Energy.Set(0);
+  //  fEventEnergy.Set(0);
+  //  fSummEnergy.Set(0);
+  //  fSum2Energy.Set(0);
 }
 
-//_____________________________________________________________________________
-AliModule *AliRun::GetModule(const char *name)
+//_______________________________________________________________________
+void AliRun::Announce() const
+{
+  //
+  // Announce the current version of AliRoot
+  //
+  printf("%70s",
+        "****************************************************************\n");
+  printf("%6s","*");printf("%64s","*\n");
+
+  printf("%6s","*");
+  printf("    You are running AliRoot version NewIO\n");
+
+  printf("%6s","*");
+  printf("    The cvs tag for the current program is $Name$\n");
+
+  printf("%6s","*");printf("%64s","*\n");
+  printf("%70s",
+        "****************************************************************\n");
+}
+
+//_______________________________________________________________________
+AliModule *AliRun::GetModule(const char *name) const
 {
   //
   // Return pointer to detector from name
   //
-  return (AliModule*)fModules->FindObject(name);
+  return dynamic_cast<AliModule*>(fModules->FindObject(name));
 }
  
-//_____________________________________________________________________________
-AliDetector *AliRun::GetDetector(const char *name)
+//_______________________________________________________________________
+AliDetector *AliRun::GetDetector(const char *name) const
 {
   //
   // Return pointer to detector from name
   //
-  return (AliDetector*)fModules->FindObject(name);
+  return dynamic_cast<AliDetector*>(fModules->FindObject(name));
 }
  
-//_____________________________________________________________________________
-Int_t AliRun::GetModuleID(const char *name)
+//_______________________________________________________________________
+Int_t AliRun::GetModuleID(const char *name) const
 {
   //
   // Return galice internal detector identifier from name
   //
-  Int_t i;
-  for(i=0;i<fNdets;i++) if(!strcmp(fDnames[i],name)) {
-    return i;
-  }
-  printf(" * GetDetectorID * Detector %s not found: returning -1\n",name);
-  return -1;
+  Int_t i=-1;
+  TObject *mod=fModules->FindObject(name);
+  if(mod) i=fModules->IndexOf(mod);
+  return i;
 }
  
-//_____________________________________________________________________________
+//_______________________________________________________________________
 Int_t AliRun::GetEvent(Int_t event)
 {
-  //
-  // Connect the Trees Kinematics and Hits for event # event
-  // Set branch addresses
-  //
-  fHeader.SetEvent(event);
-
-  // Reset existing structures
-  ResetStack();
+//
+// Reloads data containers in folders # event
+// Set branch addresses
+//
+  if (fRunLoader == 0x0)
+   {
+     Error("GetEvent","RunLoader is not set. Can not load data.");
+     return -1;
+   }
+/*****************************************/ 
+/****   P R E    R E L O A D I N G    ****/
+/*****************************************/ 
+// Reset existing structures
   ResetHits();
+  ResetTrackReferences();
   ResetDigits();
-  
-  // Delete Trees already connected
-  if (fTreeK) delete fTreeK;
-  if (fTreeH) delete fTreeH;
-  if (fTreeD) delete fTreeD;
-  if (fTreeR) delete fTreeR;
-  
-  // Get Kine Tree from file
-  char treeName[20];
-  sprintf(treeName,"TreeK%d",event);
-  fTreeK = (TTree*)gDirectory->Get(treeName);
-  if (fTreeK) fTreeK->SetBranchAddress("Particles", &fParticles);
-  else        printf("ERROR: cannot find Kine Tree for event:%d\n",event);
-  
-  // Get Hits Tree header from file
-  sprintf(treeName,"TreeH%d",event);
-  fTreeH = (TTree*)gDirectory->Get(treeName);
-  if (!fTreeH) {
-    printf("ERROR: cannot find Hits Tree for event:%d\n",event);
-    return 0;
-  }
-  
-  // Get Digits Tree header from file
-  sprintf(treeName,"TreeD%d",event);
-  fTreeD = (TTree*)gDirectory->Get(treeName);
-  if (!fTreeD) {
-    printf("WARNING: cannot find Digits Tree for event:%d\n",event);
-  }
-  
-  
-  // Get Reconstruct Tree header from file
-  sprintf(treeName,"TreeR%d",event);
-  fTreeR = (TTree*)gDirectory->Get(treeName);
-  if (!fTreeR) {
-    //    printf("WARNING: cannot find Reconstructed Tree for event:%d\n",event);
-  }
+  ResetSDigits();
+
+/*****************************************/ 
+/****       R  E  L  O  A  D          ****/
+/*****************************************/
+
+  fRunLoader->GetEvent(event);
+
+/*****************************************/ 
+/****  P O S T    R E L O A D I N G   ****/
+/*****************************************/ 
+
   // Set Trees branch addresses
   TIter next(fModules);
   AliModule *detector;
-  while((detector = (AliModule*)next())) {
-    detector->SetTreeAddress();
-  }
-  
-  if (fTreeK) fTreeK->GetEvent(0);
-  fNtrack = Int_t (fParticles->GetEntries());
-  return fNtrack;
+  while((detector = dynamic_cast<AliModule*>(next()))) 
+   {
+     detector->SetTreeAddress();
+   }
+  return fRunLoader->GetHeader()->GetNtrack();
 }
 
-//_____________________________________________________________________________
+//_______________________________________________________________________
 TGeometry *AliRun::GetGeometry()
 {
   //
   // Import Alice geometry from current file
   // Return pointer to geometry object
   //
-  if (!fGeometry) fGeometry = (TGeometry*)gDirectory->Get("AliceGeom");
+  if (!fGeometry) fGeometry = dynamic_cast<TGeometry*>(gDirectory->Get("AliceGeom"));
   //
   // Unlink and relink nodes in detectors
   // This is bad and there must be a better way...
   //
-  TList *tnodes=fGeometry->GetListOfNodes(); 
-  TNode *alice=(TNode*)tnodes->At(0);
-  TList *gnodes=alice->GetListOfNodes();
   
   TIter next(fModules);
   AliModule *detector;
-  while((detector = (AliModule*)next())) {
-    detector->SetTreeAddress();
+  while((detector = dynamic_cast<AliModule*>(next()))) {
     TList *dnodes=detector->Nodes();
     Int_t j;
     TNode *node, *node1;
     for ( j=0; j<dnodes->GetSize(); j++) {
-      node = (TNode*) dnodes->At(j);
-      node1 = (TNode*) gnodes->FindObject(node->GetName());
+      node = dynamic_cast<TNode*>(dnodes->At(j));
+      node1 = fGeometry->GetNode(node->GetName());
       dnodes->Remove(node);
       dnodes->AddAt(node1,j);
     }
@@ -728,151 +663,36 @@ TGeometry *AliRun::GetGeometry()
   return fGeometry;
 }
 
-//_____________________________________________________________________________
-void AliRun::GetNextTrack(Int_t &mtrack, Int_t &ipart, Float_t *pmom,
-                         Float_t &e, Float_t *vpos, Float_t *polar,
-                         Float_t &tof)
-{
-  //
-  // Return next track from stack of particles
-  //
-  fCurrent=-1;
-  GParticle *track;
-  for(Int_t i=fNtrack-1; i>=0; i--) {
-    track=(GParticle*) fParticles->UncheckedAt(i);
-    if(!track->TestBit(Done_Bit)) {
-      //
-      // The track has not yet been processed
-      fCurrent=i;
-      ipart=track->GetKF();
-      pmom[0]=track->GetPx();
-      pmom[1]=track->GetPy(); 
-      pmom[2]=track->GetPz();
-      e     =track->GetEnergy();
-      vpos[0]=track->GetVx();
-      vpos[1]=track->GetVy();
-      vpos[2]=track->GetVz();
-      polar[0]=track->GetPolx();
-      polar[1]=track->GetPoly();
-      polar[2]=track->GetPolz();
-      tof=track->GetTime();
-      track->SetBit(Done_Bit);
-      break;
-    }
-  }
-  mtrack=fCurrent;
-  //
-  // stop and start timer when we start a primary track
-  Int_t nprimaries = fHeader.GetNprimary();
-  if (fCurrent >= nprimaries) return;
-  if (fCurrent < nprimaries-1) {
-    fTimer.Stop();
-    track=(GParticle*) fParticles->UncheckedAt(fCurrent+1);
-    track->SetProcessTime(fTimer.CpuTime());
-  }
-  fTimer.Start();
-}
-
-//_____________________________________________________________________________
-Int_t AliRun::GetPrimary(Int_t track)
+//_______________________________________________________________________
+Int_t AliRun::GetPrimary(Int_t track) const
 {
   //
   // return number of primary that has generated track
   //
-  int current, parent;
-  GParticle *part;
-  //
-  parent=track;
-  while (1) {
-    current=parent;
-    part = (GParticle *)fParticles->UncheckedAt(current);
-    parent=part->GetParent();
-    if(parent<0) return current;
-  }
+    return fRunLoader->Stack()->GetPrimary(track);
 }
  
-//_____________________________________________________________________________
-void AliRun::Init(const char *setup)
-{
-  //
-  // Initialize the Alice setup
-  //
-
-  gROOT->LoadMacro(setup);
-  gInterpreter->ProcessLine("Config();");
-
-  AliMC* pMC = AliMC::GetMC();
-
-  pMC->Gpart();  //Create standard Geant particles
-  sxpart();        //Define additional particles
-
-  TObject *objfirst, *objlast;
-
-  //
-  //=================Create Materials, geometry, histograms, etc
-   TIter next(fModules);
-   AliModule *detector;
-   while((detector = (AliModule*)next())) {
-      detector->SetTreeAddress();
-      objlast = gDirectory->GetList()->Last();
-      
-      // Initialise detector materials, geometry, histograms,etc
-      detector->CreateMaterials();
-      detector->CreateGeometry();
-      detector->BuildGeometry();
-      detector->Init();
-      
-      // Add Detector histograms in Detector list of histograms
-      if (objlast) objfirst = gDirectory->GetList()->After(objlast);
-      else         objfirst = gDirectory->GetList()->First();
-      while (objfirst) {
-       detector->Histograms()->Add(objfirst);
-       objfirst = gDirectory->GetList()->After(objfirst);
-      }
-   }
-   SetTransPar(); //Read the cuts for all materials
-   
-   MediaTable(); //Build the special IMEDIA table
-   
-   //Close the geometry structure
-   pMC->Ggclos();
-   
-   //Initialise geometry deposition table
-   sEventEnergy.Set(pMC->NofVolumes()+1);
-   sSummEnergy.Set(pMC->NofVolumes()+1);
-   sSum2Energy.Set(pMC->NofVolumes()+1);
-   
-   //Create the color table
-   pMC->SetColors();
-   
-   //Compute cross-sections
-   pMC->Gphysi();
-   
-   //Write Geometry object to current file.
-   fGeometry->Write();
-   
-   fInitDone = kTRUE;
-}
-
-//_____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::MediaTable()
 {
   //
   // Built media table to get from the media number to
   // the detector id
   //
-  Int_t kz, ibeg, nz, idt, lz, i, k, ind;
+
+  Int_t kz, nz, idt, lz, i, k, ind;
+  //  Int_t ibeg;
   TObjArray &dets = *gAlice->Detectors();
   AliModule *det;
   //
   // For all detectors
   for (kz=0;kz<fNdets;kz++) {
     // If detector is defined
-    if((det=(AliModule*) dets[kz])) {
-      ibeg=100*kz-1;
-      for(nz=ibeg==-1?1:0;nz<100;nz++) {
+    if((det=dynamic_cast<AliModule*>(dets[kz]))) {
+        TArrayI &idtmed = *(det->GetIdtmed()); 
+        for(nz=0;nz<100;nz++) {
        // Find max and min material number
-       if((idt=fIdtmed[ibeg+nz])) {
+       if((idt=idtmed[nz])) {
          det->LoMedium() = det->LoMedium() < idt ? det->LoMedium() : idt;
          det->HiMedium() = det->HiMedium() > idt ? det->HiMedium() : idt;
        }
@@ -882,7 +702,8 @@ void AliRun::MediaTable()
        det->HiMedium() = 0;
       } else {
        if(det->HiMedium() > fImedia->GetSize()) {
-         Error("MediaTable","Increase fImedia");
+         Error("MediaTable","Increase fImedia from %d to %d",
+               fImedia->GetSize(),det->HiMedium());
          return;
        }
        // Tag all materials in rage as belonging to detector kz
@@ -898,7 +719,7 @@ void AliRun::MediaTable()
   for(i=0;i<(fNdets-1)/6+1;i++) {
     for(k=0;k< (6<fNdets-i*6?6:fNdets-i*6);k++) {
       ind=i*6+k;
-      det=(AliModule*)dets[ind];
+      det=dynamic_cast<AliModule*>(dets[ind]);
       if(det)
        printf(" %6s: %3d -> %3d;",det->GetName(),det->LoMedium(),
               det->HiMedium());
@@ -909,7 +730,7 @@ void AliRun::MediaTable()
   }
 }
 
-//____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::SetGenerator(AliGenerator *generator)
 {
   //
@@ -918,47 +739,80 @@ void AliRun::SetGenerator(AliGenerator *generator)
   if(!fGenerator) fGenerator = generator;
 }
 
-//____________________________________________________________________________
-void AliRun::SetTransPar(char* filename)
+//_______________________________________________________________________
+void AliRun::ResetGenerator(AliGenerator *generator)
 {
   //
-  // Read filename to set the transport parameters
+  // Load the event generator
   //
+  if(fGenerator)
+    if(generator)
+      Warning("ResetGenerator","Replacing generator %s with %s\n",
+             fGenerator->GetName(),generator->GetName());
+    else
+      Warning("ResetGenerator","Replacing generator %s with NULL\n",
+             fGenerator->GetName());
+  fGenerator = generator;
+}
 
-  AliMC* pMC = AliMC::GetMC();
+//_______________________________________________________________________
+void AliRun::SetTransPar(const char *filename)
+{
+  //
+  // Sets the file name for transport parameters
+  //
+  fTransParName = filename;
+}
 
-  const Int_t ncuts=10;
-  const Int_t nflags=11;
-  const Int_t npars=ncuts+nflags;
-  const char pars[npars][7] = {"CUTGAM" ,"CUTELE","CUTNEU","CUTHAD","CUTMUO",
+//_______________________________________________________________________
+void AliRun::SetBaseFile(const char *filename)
+{
+  fBaseFileName = filename;
+}
+
+//_______________________________________________________________________
+void AliRun::ReadTransPar()
+{
+  //
+  // Read filename to set the transport parameters
+  //
+
+
+  const Int_t kncuts=10;
+  const Int_t knflags=11;
+  const Int_t knpars=kncuts+knflags;
+  const char kpars[knpars][7] = {"CUTGAM" ,"CUTELE","CUTNEU","CUTHAD","CUTMUO",
                               "BCUTE","BCUTM","DCUTE","DCUTM","PPCUTM","ANNI",
                               "BREM","COMP","DCAY","DRAY","HADR","LOSS",
                               "MULS","PAIR","PHOT","RAYL"};
   char line[256];
+  char detName[7];
   char* filtmp;
-  Float_t cut[ncuts];
-  Int_t flag[nflags];
+  Float_t cut[kncuts];
+  Int_t flag[knflags];
   Int_t i, itmed, iret, ktmed, kz;
   FILE *lun;
   //
   // See whether the file is there
-  filtmp=gSystem->ExpandPathName(filename);
+  filtmp=gSystem->ExpandPathName(fTransParName.Data());
   lun=fopen(filtmp,"r");
   delete [] filtmp;
   if(!lun) {
-    printf(" * AliRun::SetTransPar * file %s does not exist!\n",filename);
+    Warning("ReadTransPar","File %s does not exist!\n",fTransParName.Data());
     return;
   }
   //
-  printf(" "); for(i=0;i<60;i++) printf("*"); printf("\n");
-  printf(" *%59s\n","*");
-  printf(" *       Please check carefully what you are doing!%10s\n","*");
-  printf(" *%59s\n","*");
+  if(fDebug) {
+    printf(" "); for(i=0;i<60;i++) printf("*"); printf("\n");
+    printf(" *%59s\n","*");
+    printf(" *       Please check carefully what you are doing!%10s\n","*");
+    printf(" *%59s\n","*");
+  }
   //
   while(1) {
     // Initialise cuts and flags
-    for(i=0;i<ncuts;i++) cut[i]=-99;
-    for(i=0;i<nflags;i++) flag[i]=-99;
+    for(i=0;i<kncuts;i++) cut[i]=-99;
+    for(i=0;i<knflags;i++) flag[i]=-99;
     itmed=0;
     for(i=0;i<256;i++) line[i]='\0';
     // Read up to the end of line excluded
@@ -966,8 +820,10 @@ void AliRun::SetTransPar(char* filename)
     if(iret<0) {
       //End of file
       fclose(lun);
-      printf(" *%59s\n","*");
-      printf(" "); for(i=0;i<60;i++) printf("*"); printf("\n");
+      if(fDebug){
+       printf(" *%59s\n","*");
+       printf(" "); for(i=0;i<60;i++) printf("*"); printf("\n");
+      }
       return;
     }
     // Read the end of line
@@ -975,220 +831,195 @@ void AliRun::SetTransPar(char* filename)
     if(!iret) continue;
     if(line[0]=='*') continue;
     // Read the numbers
-    iret=sscanf(line,"%d %f %f %f %f %f %f %f %f %f %f %d %d %d %d %d %d %d %d %d %d %d",
-               &itmed,&cut[0],&cut[1],&cut[2],&cut[3],&cut[4],&cut[5],&cut[6],&cut[7],&cut[8],&cut[9],
-               &flag[0],&flag[1],&flag[2],&flag[3],&flag[4],&flag[5],&flag[6],&flag[7],&flag[8],
-               &flag[9],&flag[10]);
+    iret=sscanf(line,"%s %d %f %f %f %f %f %f %f %f %f %f %d %d %d %d %d %d %d %d %d %d %d",
+               detName,&itmed,&cut[0],&cut[1],&cut[2],&cut[3],&cut[4],&cut[5],&cut[6],&cut[7],&cut[8],
+               &cut[9],&flag[0],&flag[1],&flag[2],&flag[3],&flag[4],&flag[5],&flag[6],&flag[7],
+               &flag[8],&flag[9],&flag[10]);
     if(!iret) continue;
     if(iret<0) {
       //reading error
-      printf(" *   Error reading file %s\n",filename);
+      Warning("ReadTransPar","Error reading file %s\n",fTransParName.Data());
       continue;
     }
-    // Check that the tracking medium code is valid
-    if(0<itmed && itmed < 100*fNdets) {
-      ktmed=fIdtmed[itmed-1];
-      if(!ktmed) {
-       printf(" *     Invalid tracking medium code %d *\n",itmed);
-       continue;
-      }
-      // Set energy thresholds
-      for(kz=0;kz<ncuts;kz++) {
-       if(cut[kz]>=0) {
-         printf(" *  %-6s set to %10.3E for tracking medium code %4d  *\n",pars[kz],cut[kz],itmed);
-         pMC->Gstpar(ktmed,pars[kz],cut[kz]);
+    // Check that the module exist
+    AliModule *mod = GetModule(detName);
+    if(mod) {
+      // Get the array of media numbers
+      TArrayI &idtmed = *mod->GetIdtmed();
+      // Check that the tracking medium code is valid
+      if(0<=itmed && itmed < 100) {
+       ktmed=idtmed[itmed];
+       if(!ktmed) {
+         Warning("ReadTransPar","Invalid tracking medium code %d for %s\n",itmed,mod->GetName());
+         continue;
        }
-      }
-      // Set transport mechanisms
-      for(kz=0;kz<nflags;kz++) {
-       if(flag[kz]>=0) {
-         printf(" *  %-6s set to %10d for tracking medium code %4d  *\n",pars[ncuts+kz],flag[kz],itmed);
-         pMC->Gstpar(ktmed,pars[ncuts+kz],Float_t(flag[kz]));
+       // Set energy thresholds
+       for(kz=0;kz<kncuts;kz++) {
+         if(cut[kz]>=0) {
+           if(fDebug) printf(" *  %-6s set to %10.3E for tracking medium code %4d for %s\n",
+                  kpars[kz],cut[kz],itmed,mod->GetName());
+           gMC->Gstpar(ktmed,kpars[kz],cut[kz]);
+         }
        }
+       // Set transport mechanisms
+       for(kz=0;kz<knflags;kz++) {
+         if(flag[kz]>=0) {
+           if(fDebug) printf(" *  %-6s set to %10d for tracking medium code %4d for %s\n",
+                  kpars[kncuts+kz],flag[kz],itmed,mod->GetName());
+           gMC->Gstpar(ktmed,kpars[kncuts+kz],Float_t(flag[kz]));
+         }
+       }
+      } else {
+       Warning("ReadTransPar","Invalid medium code %d *\n",itmed);
+       continue;
       }
     } else {
-      printf(" *     Invalid tracking medium code %d *\n",itmed);
+      if(fDebug) printf("%s::ReadTransParModule: %s not present\n",ClassName(),detName);
       continue;
     }
   }
 }
-
 //_____________________________________________________________________________
-void AliRun::MakeTree(Option_t *option)
+
+void AliRun::BeginEvent()
 {
   //
-  //  Create the ROOT trees
-  //  Loop on all detectors to create the Root branch (if any)
-  //
+  // Clean-up previous event
+  // Energy scores
+  if (GetDebug()) 
+   {
+     Info("BeginEvent",">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
+     Info("BeginEvent",">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
+     Info("BeginEvent",">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
+     Info("BeginEvent","          BEGINNING EVENT               ");
+     Info("BeginEvent",">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
+     Info("BeginEvent",">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
+     Info("BeginEvent",">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
+   }
+    
+  /*******************************/    
+  /*   Clean after eventual      */
+  /*   previous event            */
+  /*******************************/    
 
+  
+  //Set the next event in Run Loader -> Cleans trees (TreeK and all trees in detectors),
+  fRunLoader->SetEventNumber(++fEventNrInRun);// sets new files, cleans the previous event stuff, if necessary, etc.,  
+  if (GetDebug()) Info("BeginEvent","EventNr is %d",fEventNrInRun);
+     
+  fEventEnergy.Reset();  
+    // Clean detector information
+  
+  if (fRunLoader->Stack())
+    fRunLoader->Stack()->Reset();//clean stack -> tree is unloaded
+  else
+    fRunLoader->MakeStack();//or make a new one
+    
+  if (GetDebug()) Info("BeginEvent","  fRunLoader->MakeTree(K)");
+  fRunLoader->MakeTree("K");
+  if (GetDebug()) Info("BeginEvent","  gMC->SetStack(fRunLoader->Stack())");
+  gMC->SetStack(fRunLoader->Stack());//Was in InitMC - but was moved here 
+                                     //because we don't have guarantee that 
+                                     //stack pointer is not going to change from event to event
+                        //since it bellobgs to header and is obtained via RunLoader
   //
-  // Analyse options
-  char *K = strstr(option,"K");
-  char *H = strstr(option,"H");
-  char *E = strstr(option,"E");
-  char *D = strstr(option,"D");
-  char *R = strstr(option,"R");
+  //  Reset all Detectors & kinematics & make/reset trees
   //
-  if (K && !fTreeK) fTreeK = new TTree("TK","Kinematics");
-  if (H && !fTreeH) fTreeH = new TTree("TH","Hits");
-  if (D && !fTreeD) fTreeD = new TTree("TD","Digits");
-  if (E && !fTreeE) fTreeE = new TTree("TE","Header");
-  if (R && !fTreeR) fTreeR = new TTree("TR","Reconstruction");
-  if (fTreeH) fTreeH->SetAutoSave(1000000000); //no autosave
+    
+  fRunLoader->GetHeader()->Reset(fRun,fEvent,fEventNrInRun);
+//  fRunLoader->WriteKinematics("OVERWRITE");  is there any reason to rewrite here since MakeTree does so
+
+  if (GetDebug()) Info("BeginEvent","  fRunLoader->MakeTrackRefsContainer()");
+  fRunLoader->MakeTrackRefsContainer();//for insurance
+
+  if (GetDebug()) Info("BeginEvent","  ResetHits()");
+  ResetHits();
+  if (GetDebug()) Info("BeginEvent","  fRunLoader->MakeTree(H)");
+  fRunLoader->MakeTree("H");
+
   //
-  // Create a branch for hits/digits for each detector
-  // Each branch is a TClonesArray. Each data member of the Hits classes
-  // will be in turn a subbranch of the detector master branch
+  if(fLego) 
+   {
+    fLego->BeginEvent();
+    return;
+   }
+
+  //create new branches and SetAdresses
   TIter next(fModules);
   AliModule *detector;
-  while((detector = (AliModule*)next())) {
-     if (H || D || R) detector->MakeBranch(option);
-  }
-  //  Create a branch for particles
-  if (fTreeK && K) fTreeK->Branch("Particles",&fParticles,4000);
-  
-  //  Create a branch for Header
-  if (fTreeE && E) fTreeE->Branch("Header","AliHeader",&header,4000);
+  while((detector = (AliModule*)next()))
+   {
+    if (GetDebug()) Info("BeginEvent","  %s->MakeBranch(H)",detector->GetName());
+    detector->MakeBranch("H"); 
+    if (GetDebug()) Info("BeginEvent","  %s->MakeBranchTR()",detector->GetName());
+    detector->MakeBranchTR();
+    if (GetDebug()) Info("BeginEvent","  %s->SetTreeAddress()",detector->GetName());
+    detector->SetTreeAddress();
+   }
 }
 
-//_____________________________________________________________________________
-Int_t AliRun::PurifyKine(Int_t lastSavedTrack, Int_t nofTracks)
+//_______________________________________________________________________
+TParticle* AliRun::Particle(Int_t i) const
 {
-  //
-  // PurifyKine with external parameters
-  //
-  fHgwmk = lastSavedTrack;
-  fNtrack = nofTracks;
-  PurifyKine();
-  return fHgwmk;
+  if (fRunLoader)
+   if (fRunLoader->Stack())
+    return fRunLoader->Stack()->Particle(i);
+  return 0x0;   
 }
 
-//_____________________________________________________________________________
-void AliRun::PurifyKine()
+//_______________________________________________________________________
+void AliRun::ResetDigits()
 {
   //
-  // Compress kinematic tree keeping only flagged particles
-  // and renaming the particle id's in all the hits
-  //
-  TClonesArray &particles = *fParticles;
-  int nkeep=fHgwmk+1, parent, i;
-  GParticle *part, *partnew, *father;
-  AliHit *OneHit;
-  int *map = new int[particles.GetEntries()];
-
-  // Save in Header total number of tracks before compression
-  fHeader.SetNtrack(fHeader.GetNtrack()+fNtrack-fHgwmk);
-
-  // Preset map, to be removed later
-  for(i=0; i<fNtrack; i++) {
-    if(i<=fHgwmk) map[i]=i ; else map[i] = -99 ;}
-  // Second pass, build map between old and new numbering
-  for(i=fHgwmk+1; i<fNtrack; i++) {
-    part = (GParticle *)particles.UncheckedAt(i);
-    if(part->TestBit(Keep_Bit)) {
-      
-      // This particle has to be kept
-      map[i]=nkeep;
-      if(i!=nkeep) {
-       
-       // Old and new are different, have to copy
-       partnew = (GParticle *)particles.UncheckedAt(nkeep);
-       *partnew = *part;
-      } else partnew = part;
-      
-      // as the parent is always *before*, it must be already
-      // in place. This is what we are checking anyway!
-      if((parent=partnew->GetParent())>fHgwmk) {
-       if(map[parent]==-99) printf("map[%d] = -99!\n",parent);
-       partnew->SetParent(map[parent]);
-      }
-      nkeep++;
-    }
-  }
-  fNtrack=nkeep;
-  
-  // Fix children information
-  for (i=fHgwmk+1; i<fNtrack; i++) {
-    part = (GParticle *)particles.UncheckedAt(i);
-    parent = part->GetParent();
-    father = (GParticle *)particles.UncheckedAt(parent);
-    if(father->TestBit(Children_Bit)) {
-      
-      if(i<father->GetFirstChild()) father->SetFirstChild(i);
-      if(i>father->GetLastChild())  father->SetLastChild(i);
-    } else {
-      // Iitialise children info for first pass
-      father->SetFirstChild(i);
-      father->SetLastChild(i);
-      father->SetBit(Children_Bit);
-    }
-  }
-  
-  // Now loop on all detectors and reset the hits
+  //  Reset all Detectors digits
+  //
   TIter next(fModules);
   AliModule *detector;
-  while((detector = (AliModule*)next())) {
-    if (!detector->Hits()) continue;
-    TClonesArray &vHits=*(detector->Hits());
-    if(vHits.GetEntries() != detector->GetNhits())
-      printf("vHits.GetEntries()!=detector->GetNhits(): %d != %d\n",
-            vHits.GetEntries(),detector->GetNhits());
-    for (i=0; i<detector->GetNhits(); i++) {
-      OneHit = (AliHit *)vHits.UncheckedAt(i);
-      OneHit->SetTrack(map[OneHit->GetTrack()]);
-    }
+  while((detector = dynamic_cast<AliModule*>(next()))) {
+     detector->ResetDigits();
   }
-
-  fHgwmk=nkeep-1;
-  particles.SetLast(fHgwmk);
-  delete [] map;
 }
 
-//_____________________________________________________________________________
-void AliRun::Reset(Int_t run, Int_t idevent)
+//_______________________________________________________________________
+void AliRun::ResetSDigits()
 {
   //
-  //  Reset all Detectors & kinematics & trees
+  //  Reset all Detectors digits
   //
-  ResetStack();
-  ResetHits();
-  ResetDigits();
-
-  // Initialise event header
-  fHeader.Reset(run,idevent);
-
-  if(fTreeK) fTreeK->Reset();
-  if(fTreeH) fTreeH->Reset();
-  if(fTreeD) fTreeD->Reset();
+  TIter next(fModules);
+  AliModule *detector;
+  while((detector = dynamic_cast<AliModule*>(next()))) {
+     detector->ResetSDigits();
+  }
 }
 
-//_____________________________________________________________________________
-void AliRun::ResetDigits()
+//_______________________________________________________________________
+void AliRun::ResetHits()
 {
   //
-  //  Reset all Detectors digits
+  //  Reset all Detectors hits
   //
   TIter next(fModules);
   AliModule *detector;
-  while((detector = (AliModule*)next())) {
-     detector->ResetDigits();
+  while((detector = dynamic_cast<AliModule*>(next()))) {
+     detector->ResetHits();
   }
 }
+//_______________________________________________________________________
 
-//_____________________________________________________________________________
-void AliRun::ResetHits()
+void AliRun::ResetTrackReferences()
 {
   //
   //  Reset all Detectors hits
   //
   TIter next(fModules);
   AliModule *detector;
-  while((detector = (AliModule*)next())) {
-     detector->ResetHits();
+  while((detector = dynamic_cast<AliModule*>(next()))) {
+     detector->ResetTrackReferences();
   }
 }
+//_______________________________________________________________________
 
-//_____________________________________________________________________________
 void AliRun::ResetPoints()
 {
   //
@@ -1196,13 +1027,97 @@ void AliRun::ResetPoints()
   //
   TIter next(fModules);
   AliModule *detector;
-  while((detector = (AliModule*)next())) {
+  while((detector = dynamic_cast<AliModule*>(next()))) {
      detector->ResetPoints();
   }
 }
+//_______________________________________________________________________
 
-//_____________________________________________________________________________
-void AliRun::Run(Int_t nevent, const char *setup)
+void AliRun::InitMC(const char *setup)
+{
+  //
+  // Initialize the Alice setup
+  //
+  Announce();
+
+  if(fInitDone) {
+    Warning("Init","Cannot initialise AliRun twice!\n");
+    return;
+  }
+    
+  gROOT->LoadMacro(setup);
+  gInterpreter->ProcessLine(fConfigFunction.Data());
+
+  // Register MC in configuration 
+  AliConfig::Instance()->Add(gMC);
+
+  InitLoaders();
+
+  fRunLoader->MakeTree("E");
+  fRunLoader->LoadKinematics("RECREATE");
+  fRunLoader->LoadTrackRefs("RECREATE");
+  fRunLoader->LoadHits("all","RECREATE");
+  
+  
+  fRunLoader->CdGAFile();
+
+  gMC->DefineParticles();  //Create standard MC particles
+  AliPDG::AddParticlesToPdgDataBase();  
+
+  TObject *objfirst, *objlast;
+
+  fNdets = fModules->GetLast()+1;
+
+  //
+  //=================Create Materials and geometry
+  gMC->Init();
+
+  // Added also after in case of interactive initialisation of modules
+  fNdets = fModules->GetLast()+1;
+
+  TIter next(fModules);
+  AliModule *detector;
+  while((detector = dynamic_cast<AliModule*>(next()))) 
+   {
+     objlast = gDirectory->GetList()->Last();
+      
+     // Add Detector histograms in Detector list of histograms
+     if (objlast) objfirst = gDirectory->GetList()->After(objlast);
+     else         objfirst = gDirectory->GetList()->First();
+     while (objfirst) 
+      {
+        detector->Histograms()->Add(objfirst);
+        objfirst = gDirectory->GetList()->After(objfirst);
+      }
+   }
+   ReadTransPar(); //Read the cuts for all materials
+   
+   MediaTable(); //Build the special IMEDIA table
+   
+   //Initialise geometry deposition table
+   fEventEnergy.Set(gMC->NofVolumes()+1);
+   fSummEnergy.Set(gMC->NofVolumes()+1);
+   fSum2Energy.Set(gMC->NofVolumes()+1);
+   
+   //Compute cross-sections
+   gMC->BuildPhysics();
+   
+   //Write Geometry object to current file.
+   fRunLoader->WriteGeometry();
+   
+   fInitDone = kTRUE;
+
+   fMCQA = new AliMCQA(fNdets);
+
+   //
+   // Save stuff at the beginning of the file to avoid file corruption
+   Write();
+   fEventNrInRun = -1; //important - we start Begin event from increasing current number in run
+}
+
+//_______________________________________________________________________
+
+void AliRun::RunMC(Int_t nevent, const char *setup)
 {
   //
   // Main function to be called to process a galice run
@@ -1211,37 +1126,129 @@ void AliRun::Run(Int_t nevent, const char *setup)
   // a positive number of events will cause the finish routine
   // to be called
   //
-
-  Int_t i, todo;
+  fEventsPerRun = nevent;
   // check if initialisation has been done
-  if (!fInitDone) Init(setup);
+  if (!fInitDone) InitMC(setup);
   
-  AliMC* pMC = AliMC::GetMC();
-
   // Create the Root Tree with one branch per detector
-  if(!fEvent) {
-    gAlice->MakeTree("KHDER");
-  }
+  //Hits moved to begin event -> now we are crating separate tree for each event
+
+  gMC->ProcessRun(nevent);
 
-  todo = TMath::Abs(nevent);
-  for (i=0; i<todo; i++) {
-  // Process one run (one run = one event)
-     gAlice->Reset(fRun, fEvent);
-     pMC->Gtrigi();
-     pMC->Gtrigc();
-     pMC->Gtrig();
-     gAlice->FinishEvent();
-     fEvent++;
-  }
-  
   // End of this run, close files
-  if(nevent>0) gAlice->FinishRun();
+  if(nevent>0) FinishRun();
 }
 
-//_____________________________________________________________________________
-void AliRun::RunLego(const char *setup,Int_t ntheta,Float_t themin,
-                    Float_t themax,Int_t nphi,Float_t phimin,Float_t phimax,
-                    Float_t rmin,Float_t rmax,Float_t zmax)
+//_______________________________________________________________________
+void AliRun::RunReco(const char *selected, Int_t first, Int_t last)
+{
+  //
+  // Main function to be called to reconstruct Alice event
+  // 
+   Int_t nev = fRunLoader->GetNumberOfEvents();
+   if (GetDebug()) Info("RunReco","Found %d events",nev);
+   Int_t nFirst = first;
+   Int_t nLast  = (last < 0)? nev : last;
+   
+   for (Int_t nevent = nFirst; nevent <= nLast; nevent++) {
+     if (GetDebug()) Info("RunReco","Processing event %d",nevent);
+     GetEvent(nevent);
+     Digits2Reco(selected);
+   }
+}
+
+//_______________________________________________________________________
+
+void AliRun::Hits2Digits(const char *selected)
+{
+
+   // Convert Hits to sumable digits
+   // 
+   for (Int_t nevent=0; nevent<gAlice->TreeE()->GetEntries(); nevent++) {
+     GetEvent(nevent);
+     Hits2SDigits(selected);
+     SDigits2Digits(selected);
+   }  
+}
+
+
+//_______________________________________________________________________
+
+void AliRun::Tree2Tree(Option_t *option, const char *selected)
+{
+  //
+  // Function to transform the content of
+  //  
+  // - TreeH to TreeS (option "S")
+  // - TreeS to TreeD (option "D")
+  // - TreeD to TreeR (option "R")
+  // 
+  // If multiple options are specified ("SDR"), transformation will be done in sequence for
+  // selected detector and for all detectors if none is selected (detector string 
+  // can contain blank separated list of detector names). 
+
+
+   const char *oS = strstr(option,"S");
+   const char *oD = strstr(option,"D");
+   const char *oR = strstr(option,"R");
+   
+   TObjArray *detectors = Detectors();
+
+   TIter next(detectors);
+
+   AliDetector *detector = 0;
+
+   while((detector = dynamic_cast<AliDetector*>(next()))) {
+     if (selected) 
+       if (strcmp(detector->GetName(),selected)) continue;
+     if (detector->IsActive())
+      { 
+       
+       AliLoader* loader = detector->GetLoader();
+       if (loader == 0x0) continue;
+       
+       if (oS) 
+        {
+          if (GetDebug()) Info("Tree2Tree","Processing Hits2SDigits for %s ...",detector->GetName());
+          loader->LoadHits("read");
+          if (loader->TreeS() == 0x0) loader->MakeTree("S");
+          detector->MakeBranch(option);
+          detector->SetTreeAddress();
+          detector->Hits2SDigits();
+          loader->UnloadHits();
+          loader->UnloadSDigits();
+        }  
+       if (oD) 
+        {
+          if (GetDebug()) Info("Tree2Tree","Processing SDigits2Digits for %s ...",detector->GetName());
+          loader->LoadSDigits("read");
+          if (loader->TreeD() == 0x0) loader->MakeTree("D");
+          detector->MakeBranch(option);
+          detector->SetTreeAddress();
+          detector->SDigits2Digits();
+          loader->UnloadSDigits();
+          loader->UnloadDigits();
+        } 
+       if (oR) 
+        {
+          if (GetDebug()) Info("Tree2Tree","Processing Digits2Reco for %s ...",detector->GetName());
+          loader->LoadDigits("read");
+          if (loader->TreeR() == 0x0) loader->MakeTree("R");
+          detector->MakeBranch(option);
+          detector->SetTreeAddress();
+          detector->Digits2Reco(); 
+          loader->UnloadDigits();
+          loader->UnloadRecPoints();
+
+        }
+     }   
+   }
+}
+
+//_______________________________________________________________________
+void AliRun::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)
 {
   //
   // Generates lego plots of:
@@ -1282,502 +1289,464 @@ void AliRun::RunLego(const char *setup,Int_t ntheta,Float_t themin,
   //
 
   // check if initialisation has been done
-  if (!fInitDone) Init(setup);
+  if (!fInitDone) InitMC(setup);
+  //Save current generator
+  AliGenerator *gen=Generator();
+
+  // Set new generator
+  if (!gener) gener  = new AliLegoGenerator();
+  ResetGenerator(gener);
+  //
+  // Configure Generator
+  gener->SetRadiusRange(rmin, rmax);
+  gener->SetZMax(zmax);
+  gener->SetCoor1Range(nc1, c1min, c1max);
+  gener->SetCoor2Range(nc2, c2min, c2max);
+  
   
-  fLego = new AliLego("lego","lego");
-  fLego->Init(ntheta,themin,themax,nphi,phimin,phimax,rmin,rmax,zmax);
-  fLego->Run();
+  //Create Lego object  
+  fLego = new AliLego("lego",gener);
+
+  //Prepare MC for Lego Run
+  gMC->InitLego();
+  
+  //Run Lego Object
+
+  //gMC->ProcessRun(nc1*nc2+1);
+  gMC->ProcessRun(nc1*nc2);
   
   // Create only the Root event Tree
-  gAlice->MakeTree("E");
+  fRunLoader->MakeTree("E");
   
   // End of this run, close files
-  gAlice->FinishRun();
+  FinishRun();
+  // Restore current generator
+  ResetGenerator(gen);
+  // Delete Lego Object
+  delete fLego; fLego=0;
 }
 
-//_____________________________________________________________________________
+//_______________________________________________________________________
+void AliRun::SetConfigFunction(const char * config) 
+{
+  //
+  // Set the signature of the function contained in Config.C to configure
+  // the run
+  //
+  fConfigFunction=config;
+}
+
+//_______________________________________________________________________
 void AliRun::SetCurrentTrack(Int_t track)
 { 
   //
   // Set current track number
   //
-  fCurrent = track
+    fRunLoader->Stack()->SetCurrentTrack(track)
 }
  
-//_____________________________________________________________________________
-void AliRun::SetTrack(Int_t done, Int_t parent, Int_t ipart, Float_t *pmom,
-                     Float_t *vpos, Float_t *polar, Float_t tof,
-                     const char *mecha, Int_t &ntr, Float_t weight)
+//_______________________________________________________________________
+void AliRun::PushTrack(Int_t done, Int_t parent, Int_t pdg, Float_t *pmom,
+                      Float_t *vpos, Float_t *polar, Float_t tof,
+                      TMCProcess mech, Int_t &ntr, Float_t weight, Int_t is)
 { 
+// Delegate to stack
+//
+    fRunLoader->Stack()->PushTrack(done, parent, pdg, pmom, vpos, polar, tof,
+                    mech, ntr, weight, is);
+}
+
+//_______________________________________________________________________
+void AliRun::PushTrack(Int_t done, Int_t parent, Int_t pdg,
+                     Double_t px, Double_t py, Double_t pz, Double_t e,
+                     Double_t vx, Double_t vy, Double_t vz, Double_t tof,
+                     Double_t polx, Double_t poly, Double_t polz,
+                     TMCProcess mech, Int_t &ntr, Float_t weight, Int_t is)
+{ 
+  // Delegate to stack
   //
-  // Load a track on the stack
-  //
-  // done     0 if the track has to be transported
-  //          1 if not
-  // parent   identifier of the parent track. -1 for a primary
-  // ipart    particle code
-  // pmom     momentum GeV/c
-  // vpos     position 
-  // polar    polarisation 
-  // tof      time of flight in seconds
-  // mecha    production mechanism
-  // ntr      on output the number of the track stored
-  //
-  TClonesArray &particles = *fParticles;
-  GParticle *particle;
-  Float_t mass;
-  char pname[21];
-  const Int_t firstchild=-1;
-  const Int_t lastchild=-1;
-  const Int_t KS=0;
-  const Float_t tlife=0;
-  
-  AliMC::GetMC()->GetParticle(ipart,pname,mass);
-  Float_t e=TMath::Sqrt(mass*mass+pmom[0]*pmom[0]+
-                       pmom[1]*pmom[1]+pmom[2]*pmom[2]);
-  
-  //printf("Loading particle %s mass %f ene %f No %d ip %d pos %f %f %f mom %f %f %f KS %d m %s\n",
-  //pname,mass,e,fNtrack,ipart,vpos[0],vpos[1],vpos[2],pmom[0],pmom[1],pmom[2],KS,mecha);
-  
-  particle=new(particles[fNtrack]) GParticle(KS,ipart,parent,firstchild,
-                                            lastchild,pmom[0],pmom[1],pmom[2],
-                                            e,mass,vpos[0],vpos[1],vpos[2],
-                                            polar[0],polar[1],polar[2],tof,
-                                            tlife,mecha,weight);
-  if(!done) particle->SetBit(Done_Bit);
-  
-  if(parent>=0) {
-    particle=(GParticle*) fParticles->UncheckedAt(parent);
-    particle->SetLastChild(fNtrack);
-    if(particle->GetFirstChild()<0) particle->SetFirstChild(fNtrack);
-  } else { 
-    //
-    // This is a primary track. Set high water mark for this event
-    fHgwmk=fNtrack;
+  fRunLoader->Stack()->PushTrack(done, parent, pdg, px, py, pz, e, vx, vy, vz, tof,
+                                polx, poly, polz, mech, ntr, weight, is);
+}
+
+//_______________________________________________________________________
+void AliRun::SetHighWaterMark(const Int_t nt)
+{
     //
-    // Set also number if primary tracks
-    fHeader.SetNprimary(fHgwmk+1);
-    fHeader.SetNtrack(fHgwmk+1);
-  }
-  ntr = fNtrack++;
+    // Set high water mark for last track in event
+    fRunLoader->Stack()->SetHighWaterMark(nt);
 }
 
-//_____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::KeepTrack(const Int_t track)
 { 
   //
-  // flags a track to be kept
+  // Delegate to stack
   //
-  TClonesArray &particles = *fParticles;
-  ((GParticle*)particles[track])->SetBit(Keep_Bit);
+    fRunLoader->Stack()->KeepTrack(track);
 }
  
-//_____________________________________________________________________________
-void AliRun::StepManager(Int_t id) const
+// 
+// MC Application
+// 
+
+//_______________________________________________________________________
+void  AliRun::ConstructGeometry() 
+{
+  //
+  // Create modules, materials, geometry
+  //
+
+    TStopwatch stw;
+    TIter next(fModules);
+    AliModule *detector;
+    if (GetDebug()) Info("ConstructGeometry","Geometry creation:");
+    while((detector = dynamic_cast<AliModule*>(next()))) {
+      stw.Start();
+      // Initialise detector materials and geometry
+      detector->CreateMaterials();
+      detector->CreateGeometry();
+      printf("%10s R:%.2fs C:%.2fs\n",
+             detector->GetName(),stw.RealTime(),stw.CpuTime());
+    }
+}
+
+//_______________________________________________________________________
+void  AliRun::InitGeometry()
+{ 
+  //
+  // Initialize detectors and display geometry
+  //
+
+   printf("Initialisation:\n");
+    TStopwatch stw;
+    TIter next(fModules);
+    AliModule *detector;
+    while((detector = dynamic_cast<AliModule*>(next()))) {
+      stw.Start();
+      // Initialise detector and display geometry
+      detector->Init();
+      detector->BuildGeometry();
+      printf("%10s R:%.2fs C:%.2fs\n",
+            detector->GetName(),stw.RealTime(),stw.CpuTime());
+    }
+}
+//_______________________________________________________________________
+
+void  AliRun::GeneratePrimaries()
+{ 
+  //
+  // Generate primary particles and fill them in the stack.
+  //
+
+  Generator()->Generate();
+}
+//_______________________________________________________________________
+
+void AliRun::BeginPrimary()
+{
+  //
+  // Called  at the beginning of each primary track
+  //
+  
+  // Reset Hits info
+  gAlice->ResetHits();
+  gAlice->ResetTrackReferences();
+
+}
+
+//_______________________________________________________________________
+void AliRun::PreTrack()
+{
+     TObjArray &dets = *fModules;
+     AliModule *module;
+
+     for(Int_t i=0; i<=fNdets; i++)
+       if((module = dynamic_cast<AliModule*>(dets[i])))
+        module->PreTrack();
+
+     fMCQA->PreTrack();
+}
+
+//_______________________________________________________________________
+void AliRun::Stepping() 
 {
   //
   // Called at every step during transport
   //
 
-  AliMC* pMC = AliMC::GetMC();
+  Int_t id = DetFromMate(gMC->GetMedium());
+  if (id < 0) return;
 
-  Int_t copy;
   //
   // --- If lego option, do it and leave 
-  if (fLego) {
+  if (fLego)
     fLego->StepManager();
-    return;
-  }
-  //Update energy deposition tables
-  sEventEnergy[pMC->CurrentVol(0,copy)]+=pMC->Edep();
+  else {
+    Int_t copy;
+    //Update energy deposition tables
+    AddEnergyDeposit(gMC->CurrentVolID(copy),gMC->Edep());
   
-  //Call the appropriate stepping routine;
-  AliModule *det = (AliModule*)fModules->At(id);
-  if(det) det->StepManager();
+    //Call the appropriate stepping routine;
+    AliModule *det = dynamic_cast<AliModule*>(fModules->At(id));
+    if(det && det->StepManagerIsEnabled()) {
+      fMCQA->StepManager(id);
+      det->StepManager();
+    }
+  }
 }
 
-//_____________________________________________________________________________
-void AliRun::ReadEuclid(const char* filnam, Int_t id_det, const char* topvol)
+//_______________________________________________________________________
+void AliRun::PostTrack()
+{
+     TObjArray &dets = *fModules;
+     AliModule *module;
+
+     for(Int_t i=0; i<=fNdets; i++)
+       if((module = dynamic_cast<AliModule*>(dets[i])))
+        module->PostTrack();
+}
+
+//_______________________________________________________________________
+void AliRun::FinishPrimary()
 {
-  //                                                                     
-  //       read in the geometry of the detector in euclid file format    
-  //                                                                     
-  //        id_det : the detector identification (2=its,...)            
-  //        topvol : return parameter describing the name of the top    
-  //        volume of geometry.                                          
-  //                                                                     
-  //            author : m. maire                                        
-  //                                                                     
-  //     28.07.98
-  //     several changes have been made by miroslav helbich
-  //     subroutine is rewrited to follow the new established way of memory
-  //     booking for tracking medias and rotation matrices.
-  //     all used tracking media have to be defined first, for this you can use
-  //     subroutine  greutmed.
-  //     top volume is searched as only volume not positioned into another 
-  //
-
-  AliMC* pMC = AliMC::GetMC();
-
-  Int_t i, nvol, iret, itmed, irot, numed, npar, ndiv, iaxe;
-  Int_t ndvmx, nr, flag;
-  char key[5], card[77], natmed[21];
-  char name[5], mother[5], shape[5], konly[5], volst[7000][5];
-  char *filtmp;
-  Float_t par[50];
-  Float_t teta1, phi1, teta2, phi2, teta3, phi3, orig, step;
-  Float_t xo, yo, zo;
-  Int_t idrot[5000],istop[7000];
-  FILE *lun;
-  AliModule *det;
   //
-  TObjArray &dets = *fModules;
-  if(!dets[id_det]) {
-    printf(" *** GREUTMED *** Detector %d not defined\n",id_det);
-    return;
-  } else {
-    det = (AliModule*) dets[id_det];
-  }
+  // Called  at the end of each primary track
   //
-  // *** The input filnam name will be with extension '.euc'
-  filtmp=gSystem->ExpandPathName(filnam);
-  lun=fopen(filtmp,"r");
-  delete [] filtmp;
-  if(!lun) {
-    printf(" *** GREUCL *** Could not open file %s\n",filnam);
-    return;
-  }
-  //* --- definition of rotation matrix 0 ---
-  idrot[0]=0;
-  nvol=0;
- L10:
-  for(i=0;i<77;i++) card[i]=0;
-  iret=fscanf(lun,"%77[^\n]",card);
-  if(iret<=0) goto L20;
-  fscanf(lun,"%*c");
-  //*
-  strncpy(key,card,4);
-  key[4]='\0';
-  if (!strcmp(key,"TMED")) {
-    sscanf(&card[5],"%d '%[^']'",&itmed,natmed);
-    //Pad the string with blanks
-    i=-1;
-    while(natmed[++i]);
-    while(i<20) natmed[i++]=' ';
-    natmed[i]='\0';
-    //
-    pMC->Gckmat(fIdtmed[itmed+id_det*100-1],natmed);
-    //*
-  } else if (!strcmp(key,"ROTM")) {
-    sscanf(&card[4],"%d %f %f %f %f %f %f",&irot,&teta1,&phi1,&teta2,&phi2,&teta3,&phi3);
-    det->AliMatrix(idrot[irot],teta1,phi1,teta2,phi2,teta3,phi3);
-    //*
-  } else if (!strcmp(key,"VOLU")) {
-    sscanf(&card[5],"'%[^']' '%[^']' %d %d", name, shape, &numed, &npar);
-    if (npar>0) {
-      for(i=0;i<npar;i++) fscanf(lun,"%f",&par[i]);
-      fscanf(lun,"%*c");
-    }
-    pMC->Gsvolu( name, shape, fIdtmed[numed+id_det*100-1], par, npar);
-    //*     save the defined volumes
-    strcpy(volst[++nvol],name);
-    istop[nvol]=1;
-    //*
-  } else if (!strcmp(key,"DIVN")) {
-    sscanf(&card[5],"'%[^']' '%[^']' %d %d", name, mother, &ndiv, &iaxe);
-    pMC->Gsdvn  ( name, mother, ndiv, iaxe );
-    //*
-  } else if (!strcmp(key,"DVN2")) {
-    sscanf(&card[5],"'%[^']' '%[^']' %d %d %f %d",name, mother, &ndiv, &iaxe, &orig, &numed);
-    pMC->Gsdvn2( name, mother, ndiv, iaxe, orig,fIdtmed[numed+id_det*100-1]);
-    //*
-  } else if (!strcmp(key,"DIVT")) {
-    sscanf(&card[5],"'%[^']' '%[^']' %f %d %d %d", name, mother, &step, &iaxe, &numed, &ndvmx);
-    pMC->Gsdvt ( name, mother, step, iaxe, fIdtmed[numed+id_det*100-1], ndvmx);
-    //*
-  } else if (!strcmp(key,"DVT2")) {
-    sscanf(&card[5],"'%[^']' '%[^']' %f %d %f %d %d", name, mother, &step, &iaxe, &orig, &numed, &ndvmx);
-    pMC->Gsdvt2 ( name, mother, step, iaxe, orig, fIdtmed[numed+id_det*100-1], ndvmx );
-    //*
-  } else if (!strcmp(key,"POSI")) {
-    sscanf(&card[5],"'%[^']' %d '%[^']' %f %f %f %d '%[^']'", name, &nr, mother, &xo, &yo, &zo, &irot, konly);
-    //*** volume name cannot be the top volume
-    for(i=1;i<=nvol;i++) {
-      if (!strcmp(volst[i],name)) istop[i]=0;
-    }
-    //*
-    pMC->Gspos  ( name, nr, mother, xo, yo, zo, idrot[irot], konly );
-    //*
-  } else if (!strcmp(key,"POSP")) {
-    sscanf(&card[5],"'%[^']' %d '%[^']' %f %f %f %d '%[^']' %d", name, &nr, mother, &xo, &yo, &zo, &irot, konly, &npar);
-    if (npar > 0) {
-      for(i=0;i<npar;i++) fscanf(lun,"%f",&par[i]);
-      fscanf(lun,"%*c");
-    }
-    //*** volume name cannot be the top volume
-    for(i=1;i<=nvol;i++) {
-      if (!strcmp(volst[i],name)) istop[i]=0;
-    }
-    //*
-    pMC->Gsposp ( name, nr, mother, xo,yo,zo, idrot[irot], konly, par, npar);
-  }
-  //*
-  if (strcmp(key,"END")) goto L10;
-  //* find top volume in the geometry
-  flag=0;
-  for(i=1;i<=nvol;i++) {
-    if (istop[i] && flag) {
-      printf(" *** GREUCL *** warning: %s is another possible top volume\n",volst[i]);
-    }
-    if (istop[i] && !flag) {
-      topvol=volst[i];
-      printf(" *** GREUCL *** volume %s taken as a top volume\n",topvol);
-      flag=1;
-    }
-  }
-  if (!flag) {
-    printf("*** GREUCL *** warning: top volume not found\n");
+  
+  //  static Int_t count=0;
+  //  const Int_t times=10;
+  // This primary is finished, purify stack
+  fRunLoader->Stack()->PurifyKine();
+
+  TIter next(fModules);
+  AliModule *detector;
+  while((detector = dynamic_cast<AliModule*>(next()))) {
+    detector->FinishPrimary();
+    if(detector->GetLoader())
+     {
+       detector->GetLoader()->TreeH()->Fill();
+     }
   }
-  fclose (lun);
-  //*
-  //*     commented out only for the not cernlib version
-  printf(" *** GREUCL *** file: %s is now read in\n",filnam);
-  //
-  return;
-  //*
-  L20:
-  printf(" *** GREUCL *** reading error or premature end of file\n");
+
+  // Write out track references if any
+  if (fRunLoader->TreeTR()) 
+   {
+    fRunLoader->TreeTR()->Fill();
+   }
 }
 
-//_____________________________________________________________________________
-void AliRun::ReadEuclidMedia(const char* filnam, Int_t id_det)
+//_______________________________________________________________________
+void AliRun::FinishEvent()
 {
-  //                                                                     
-  //       read in the materials and tracking media for the detector     
-  //                   in euclid file format                             
-  //                                                                     
-  //       filnam: name of the input file                                
-  //       id_det: id_det is the detector identification (2=its,...)     
-  //                                                                     
-  //            author : miroslav helbich                                
-  //
-  Float_t sxmgmx = gAlice->Field()->Max();
-  Int_t   isxfld = gAlice->Field()->Integ();
-  Int_t end, i, iret, itmed;
-  char key[5], card[130], natmed[21], namate[21];
-  Float_t ubuf[50];
-  char* filtmp;
-  FILE *lun;
-  Int_t imate;
-  Int_t nwbuf, isvol, ifield, nmat;
-  Float_t a, z, dens, radl, absl, fieldm, tmaxfd, stemax, deemax, epsil, stmin;
-  AliModule* det;
-//
-  TObjArray &dets = *fModules;
-  if(!dets[id_det]) {
-    printf(" *** GREUTMED *** Detector %d not defined\n",id_det);
-    return;
-  } else {
-    det = (AliModule*) dets[id_det];
-  }
-  end=strlen(filnam);
-  for(i=0;i<end;i++) if(filnam[i]=='.') {
-    end=i;
-    break;
-  }
   //
-  // *** The input filnam name will be with extension '.euc'
-  printf("The file name is %s\n",filnam); //Debug
-  filtmp=gSystem->ExpandPathName(filnam);
-  lun=fopen(filtmp,"r");
-  delete [] filtmp;
-  if(!lun) {
-    printf(" *** GREUTMED *** Could not open file %s\n",filnam);
-    return;
-  }
+  // Called at the end of the event.
   //
-  // Retrieve Mag Field parameters
-  Int_t ISXFLD=gAlice->Field()->Integ();
-  Float_t SXMGMX=gAlice->Field()->Max();
-  //
- L10:
-  for(i=0;i<130;i++) card[i]=0;
-  iret=fscanf(lun,"%4s %[^\n]",key,card);
-  if(iret<=0) goto L20;
-  fscanf(lun,"%*c");
-  //*
-  //* read material
-  if (!strcmp(key,"MATE")) {
-    sscanf(card,"%d '%[^']' %f %f %f %f %f %d",&imate,namate,&a,&z,&dens,&radl,&absl,&nwbuf);
-    if (nwbuf>0) for(i=0;i<nwbuf;i++) fscanf(lun,"%f",&ubuf[i]);
-    //Pad the string with blanks
-    i=-1;
-    while(namate[++i]);
-    while(i<20) namate[i++]=' ';
-    namate[i]='\0';
-    //
-    det->AliMaterial(imate,namate,a,z,dens,radl,absl,ubuf,nwbuf);
-    //* read tracking medium
-  } else if (!strcmp(key,"TMED")) {
-    sscanf(card,"%d '%[^']' %d %d %d %f %f %f %f %f %f %d",
-          &itmed,natmed,&nmat,&isvol,&ifield,&fieldm,&tmaxfd,
-          &stemax,&deemax,&epsil,&stmin,&nwbuf);
-    if (nwbuf>0) for(i=0;i<nwbuf;i++) fscanf(lun,"%f",&ubuf[i]);
-    if (ifield<0) ifield=isxfld;
-    if (fieldm<0) fieldm=sxmgmx;
-    //Pad the string with blanks
-    i=-1;
-    while(natmed[++i]);
-    while(i<20) natmed[i++]=' ';
-    natmed[i]='\0';
-    //
-    det->AliMedium(itmed+id_det*100,natmed,nmat,isvol,ISXFLD,SXMGMX,tmaxfd,
-                  stemax,deemax,epsil,stmin,ubuf,nwbuf);
-    (*fImedia)[fIdtmed[itmed+id_det*100-1]-1]=id_det;
-    //*
+  
+  //
+  if(fLego) fLego->FinishEvent();
+
+  TIter next(fModules);
+  AliModule *detector;
+  while((detector = dynamic_cast<AliModule*>(next()))) {
+    detector->FinishEvent();
   }
-  //*
-  if (strcmp(key,"END")) goto L10;
-  fclose (lun);
-  //*
-  //*     commented out only for the not cernlib version
-  printf(" *** GREUTMED *** file: %s is now read in\n",filnam);
-  //*
-  return;
-  //*
- L20:
-  printf(" *** GREUTMED *** reading error or premature end of file\n");
-} 
-//_____________________________________________________________________________
+
+  //Update the energy deposit tables
+  Int_t i;
+  for(i=0;i<fEventEnergy.GetSize();i++) 
+   {
+    fSummEnergy[i]+=fEventEnergy[i];
+    fSum2Energy[i]+=fEventEnergy[i]*fEventEnergy[i];
+   }
+
+  AliHeader* header = fRunLoader->GetHeader();
+  AliStack* stack = fRunLoader->Stack();
+  if ( (header == 0x0) || (stack == 0x0) )
+   {//check if we got header and stack. If not cry and exit aliroot
+    Fatal("AliRun","Can not get the stack or header from LOADER");
+    return;//never reached
+   }  
+  // Update Header information 
+  header->SetNprimary(stack->GetNprimary());
+  header->SetNtrack(stack->GetNtrack());  
+
+  
+  // Write out the kinematics
+  stack->FinishEvent();
+   
+  // Write out the event Header information
+  TTree* treeE = fRunLoader->TreeE();
+  if (treeE) 
+   {
+      header->SetStack(stack);
+      treeE->Fill();
+   }
+  else
+   {
+    Error("FinishEvent","Can not get TreeE from RL");
+   }
+  
+  fRunLoader->WriteKinematics("OVERWRITE");
+  fRunLoader->WriteTrackRefs("OVERWRITE");
+  fRunLoader->WriteHits("OVERWRITE");
+
+  if (GetDebug()) 
+   { 
+     Info("FinishEvent","<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
+     Info("FinishEvent","<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
+     Info("FinishEvent","<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
+     Info("FinishEvent","          FINISHING EVENT               ");
+     Info("FinishEvent","<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
+     Info("FinishEvent","<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
+     Info("FinishEvent","<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
+   }
+}
+
+//_______________________________________________________________________
+void AliRun::Field(const Double_t* x, Double_t *b) const
+{
+   Float_t xfloat[3];
+   for (Int_t i=0; i<3; i++) xfloat[i] = x[i]; 
+
+   if (Field()) {
+         Float_t bfloat[3];
+         Field()->Field(xfloat,bfloat);
+         for (Int_t j=0; j<3; j++) b[j] = bfloat[j]; 
+   } 
+   else {
+         printf("No mag field defined!\n");
+         b[0]=b[1]=b[2]=0.;
+   }
+
+}      
+
+// 
+// End of MC Application
+// 
+
+//_______________________________________________________________________
 void AliRun::Streamer(TBuffer &R__b)
 {
-  //
   // Stream an object of class AliRun.
-  //
+
   if (R__b.IsReading()) {
-    Version_t R__v = R__b.ReadVersion(); if (R__v) { }
-    TNamed::Streamer(R__b);
     if (!gAlice) gAlice = this;
+    AliRun::Class()->ReadBuffer(R__b, this);
     gROOT->GetListOfBrowsables()->Add(this,"Run");
-    R__b >> fNtrack;
-    R__b >> fHgwmk;
-    R__b >> fDebug;
-    fHeader.Streamer(R__b);
-    R__b >> fModules;
-    R__b >> fParticles;
-    R__b >> fField; 
-    //    R__b >> fMC;
-    R__b >> fNdets;
-    R__b >> fTrRmax;
-    R__b >> fTrZmax;
-    R__b >> fGenerator;
+
+    gRandom = fRandom;
   } else {
-    R__b.WriteVersion(AliRun::IsA());
-    TNamed::Streamer(R__b);
-    R__b << fNtrack;
-    R__b << fHgwmk;
-    R__b << fDebug;
-    fHeader.Streamer(R__b);
-    R__b << fModules;
-    R__b << fParticles;
-    R__b << fField;
-    //    R__b << fMC;
-    R__b << fNdets;
-    R__b << fTrRmax;
-    R__b << fTrZmax;
-    R__b << fGenerator;
+    AliRun::Class()->WriteBuffer(R__b, this);
   }
-} 
+}
 
 
-//_____________________________________________________________________________
-//
-//                 Interfaces to Fortran
-//
-//_____________________________________________________________________________
+//_______________________________________________________________________
+Int_t AliRun::GetCurrentTrackNumber() const {
+  //
+  // Returns current track
+  //
+  return fRunLoader->Stack()->GetCurrentTrackNumber();
+}
 
-extern "C" void type_of_call  rxgtrak (Int_t &mtrack, Int_t &ipart, Float_t *pmom, 
-                                      Float_t &e, Float_t *vpos, Float_t &tof)
-{
+//_______________________________________________________________________
+Int_t AliRun::GetNtrack() const {
   //
-  //     Fetches next track from the ROOT stack for transport. Called by the
-  //     modified version of GTREVE.
+  // Returns number of tracks in stack
   //
-  //              Track number in the ROOT stack. If MTRACK=0 no
-  //      mtrack  more tracks are left in the stack to be
-  //              transported.
-  //      ipart   Particle code in the GEANT conventions.
-  //      pmom[3] Particle momentum in GeV/c
-  //      e       Particle energy in GeV
-  //      vpos[3] Particle position
-  //      tof     Particle time of flight in seconds
+  return fRunLoader->Stack()->GetNtrack();
+}
+//_______________________________________________________________________
+
+//_______________________________________________________________________
+TObjArray* AliRun::Particles() const {
+  //
+  // Returns pointer to Particles array
   //
-  Float_t polar[3];
-  gAlice->GetNextTrack(mtrack, ipart, pmom, e, vpos, polar, tof);
-  mtrack++;
+  if (fRunLoader)
+   if (fRunLoader->Stack())
+    return fRunLoader->Stack()->Particles();
+  return 0x0;
 }
 
-//_____________________________________________________________________________
-extern "C" void type_of_call 
-#ifndef WIN32
-rxstrak (Int_t &keep, Int_t &parent, Int_t &ipart, Float_t *pmom, 
-              Float_t *vpos, Float_t &tof, const char* cmech, Int_t &ntr, const int cmlen)
-#else
-rxstrak (Int_t &keep, Int_t &parent, Int_t &ipart, Float_t *pmom,
-        Float_t *vpos, Float_t &tof, const char* cmech, const int cmlen,
-        Int_t &ntr)
-#endif
+//___________________________________________________________________________
+
+//_______________________________________________________________________
+void AliRun::SetGenEventHeader(AliGenEventHeader* header)
 {
-  //
-  //     Fetches next track from the ROOT stack for transport. Called by GUKINE
-  //     and GUSTEP.
-  //
-  //              Status of the track. If keep=0 the track is put
-  //      keep    on the ROOT stack but it is not fetched for
-  //              transport.
-  //      parent  Parent track. If parent=0 the track is a primary.
-  //              In GUSTEP the routine is normally called to store
-  //              secondaries generated by the current track whose
-  //              ROOT stack number is MTRACK (common SCKINE.
-  //      ipart   Particle code in the GEANT conventions.
-  //      pmom[3] Particle momentum in GeV/c
-  //      vpos[3] Particle position
-  //      tof     Particle time of flight in seconds
-  //
-  //      cmech   (CHARACTER*10) Particle origin. This field is user
-  //              defined and it is not used inside the GALICE code.
-  //      ntr     Number assigned to the particle in the ROOT stack.
-  //
-  char mecha[11];
-  Float_t polar[3]={0.,0.,0.};
-  for(int i=0; i<10 && i<cmlen; i++) mecha[i]=cmech[i];
-  mecha[10]=0;
-  gAlice->SetTrack(keep, parent-1, ipart, pmom, vpos, polar, tof, mecha, ntr);
-  ntr++;
+  fRunLoader->GetHeader()->SetGenEventHeader(header);
 }
 
-//_____________________________________________________________________________
-extern "C" void type_of_call  rxkeep(const Int_t &n)
+//___________________________________________________________________________
+
+Int_t AliRun::GetEvNumber() const
+{ 
+//Returns number of current event  
+  if (fRunLoader == 0x0)
+   {
+     Error("GetEvent","RunLoader is not set. Can not load data.");
+     return -1;
+   }
+
+  return fRunLoader->GetEventNumber();
+}
+
+void AliRun::SetRunLoader(AliRunLoader* rloader)
 {
-  if( NULL==gAlice ) exit(1);
+  fRunLoader = rloader;
+  if (fRunLoader == 0x0) return;
   
-  if( n<=0 || n>gAlice->Particles()->GetEntries() )
-    {
-      printf("  Bad index n=%d must be 0<n<=%d\n",
-            n,gAlice->Particles()->GetEntries());
-      exit(1);
-    }
+  TString evfoldname;
+  TFolder* evfold = fRunLoader->GetEventFolder();
+  if (evfold) evfoldname = evfold->GetName();
+  else Warning("SetRunLoader","Did not get Event Folder from Run Loader");
   
-  ((GParticle*)(gAlice->Particles()->UncheckedAt(n-1)))->SetBit(Keep_Bit);
+  if ( fRunLoader->GetAliRun() )
+   {//if alrun already exists in folder
+    if (fRunLoader->GetAliRun() != this )
+     {//and is different than this - crash
+       Fatal("AliRun","AliRun is already in Folder and it is not this object");
+       return;//pro forma
+     }//else do nothing
+   }
+  else
+   {
+     evfold->Add(this);//Post this AliRun to Folder
+   }
+  
+  TIter next(fModules);
+  AliModule *module;
+  while((module = (AliModule*)next())) 
+   {
+     if (evfold) AliConfig::Instance()->Add(module,evfoldname);
+     AliDetector* detector = dynamic_cast<AliDetector*>(module);
+     if (detector)
+      {
+        AliLoader* loader = fRunLoader->GetLoader(detector);
+        if (loader == 0x0)
+         {
+           Error("SetRunLoader","Can not get loader for detector %s",detector->GetName());
+         }
+        else
+         {
+           if (GetDebug()) Info("SetRunLoader","Setting loader for detector %s",detector->GetName());
+           detector->SetLoader(loader);
+         }
+      }
+   }
 }
 
-//_____________________________________________________________________________
-extern "C" void type_of_call  rxouth ()
+void AliRun::AddModule(AliModule* mod)
 {
-  //
-  // Called by Gtreve at the end of each primary track
-  //
-  gAlice->FinishPrimary();
-}
+  if (mod == 0x0) return;
+  if (strlen(mod->GetName()) == 0) return;
+  if (GetModuleID(mod->GetName()) >= 0) return;
+  
+  if (GetDebug()) Info("AddModule","%s",mod->GetName());
+  if (fRunLoader == 0x0) AliConfig::Instance()->Add(mod);
+  else AliConfig::Instance()->Add(mod,fRunLoader->GetEventFolder()->GetName());
 
+  Modules()->Add(mod);
+}