]> 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 8b0f876ba5dbc24cd97ac2c53878f33f08e93587..9f39bb9aef97021f5de34e1088f8515bfec864e7 100644 (file)
  * provided "as is" without express or implied warranty.                  *
  **************************************************************************/
 
-/*
-$Log$
-Revision 1.56  2001/02/14 15:45:20  hristov
-Algorithmic way of getting entry index in fParticleMap. Protection of fParticleFileMap (I.Hrivnacova)
-
-Revision 1.55  2001/02/12 15:52:54  buncic
-Removed OpenBaseFile().
-
-Revision 1.54  2001/02/07 10:39:05  hristov
-Remove default value for argument
-
-Revision 1.53  2001/02/06 11:02:26  hristov
-New SetTrack interface added, added check for unfilled particles in FinishEvent (I.Hrivnacova)
-
-Revision 1.52  2001/02/05 16:22:25  buncic
-Added TreeS to GetEvent().
-
-Revision 1.51  2001/02/02 15:16:20  morsch
-SetHighWaterMark method added to mark last particle in event.
-
-Revision 1.50  2001/01/27 10:32:00  hristov
-Leave the loop when primaries are filled (I.Hrivnacova)
-
-Revision 1.49  2001/01/26 19:58:48  hristov
-Major upgrade of AliRoot code
-
-Revision 1.48  2001/01/17 10:50:50  hristov
-Corrections to destructors
-
-Revision 1.47  2000/12/18 10:44:01  morsch
-Possibility to set field map by passing pointer to objet of type AliMagF via
-SetField().
-Example:
-gAlice->SetField(new AliMagFCM("Map2", "$(ALICE_ROOT)/data/field01.dat",2,1.,10.));
-
-Revision 1.46  2000/12/14 19:29:27  fca
-galice.cuts was not read any more
-
-Revision 1.45  2000/11/30 07:12:49  alibrary
-Introducing new Rndm and QA classes
-
-Revision 1.44  2000/10/26 13:58:59  morsch
-Add possibility to choose the lego generator (of type AliGeneratorLego or derived) when running
-RunLego(). Default is the base class AliGeneratorLego.
-
-Revision 1.43  2000/10/09 09:43:17  fca
-Special remapping of hits for TPC and TRD. End-of-primary action introduced
-
-Revision 1.42  2000/10/02 21:28:14  fca
-Removal of useless dependecies via forward declarations
-
-Revision 1.41  2000/07/13 16:19:09  fca
-Mainly coding conventions + some small bug fixes
-
-Revision 1.40  2000/07/12 08:56:25  fca
-Coding convention correction and warning removal
-
-Revision 1.39  2000/07/11 18:24:59  fca
-Coding convention corrections + few minor bug fixes
-
-Revision 1.38  2000/06/20 13:05:45  fca
-Writing down the TREE headers before job starts
-
-Revision 1.37  2000/06/09 20:05:11  morsch
-Introduce possibility to chose magnetic field version 3: AliMagFDM + field02.dat
-
-Revision 1.36  2000/06/08 14:03:58  hristov
-Only one initializer for a default argument
-
-Revision 1.35  2000/06/07 10:13:14  hristov
-Delete only existent objects.
-
-Revision 1.34  2000/05/18 10:45:38  fca
-Delete Particle Factory properly
-
-Revision 1.33  2000/05/16 13:10:40  fca
-New method IsNewTrack and fix for a problem in Father-Daughter relations
-
-Revision 1.32  2000/04/27 10:38:21  fca
-Correct termination of Lego Run and introduce Lego getter in AliRun
-
-Revision 1.31  2000/04/26 10:17:32  fca
-Changes in Lego for G4 compatibility
-
-Revision 1.30  2000/04/18 19:11:40  fca
-Introduce variable Config.C function signature
-
-Revision 1.29  2000/04/07 11:12:34  fca
-G4 compatibility changes
-
-Revision 1.28  2000/04/05 06:51:06  fca
-Workaround for an HP compiler problem
-
-Revision 1.27  2000/03/22 18:08:07  fca
-Rationalisation of the virtual MC interfaces
-
-Revision 1.26  2000/03/22 13:42:26  fca
-SetGenerator does not replace an existing generator, ResetGenerator does
-
-Revision 1.25  2000/02/23 16:25:22  fca
-AliVMC and AliGeant3 classes introduced
-ReadEuclid moved from AliRun to AliModule
-
-Revision 1.24  2000/01/19 17:17:20  fca
-Introducing a list of lists of hits -- more hits allowed for detector now
-
-Revision 1.23  1999/12/03 11:14:31  fca
-Fixing previous wrong checking
-
-Revision 1.21  1999/11/25 10:40:08  fca
-Fixing daughters information also in primary tracks
-
-Revision 1.20  1999/10/04 18:08:49  fca
-Adding protection against inconsistent Euclid files
-
-Revision 1.19  1999/09/29 07:50:40  fca
-Introduction of the Copyright and cvs Log
-
-*/
+/* $Id$ */
 
 ///////////////////////////////////////////////////////////////////////////////
 //                                                                           //
@@ -158,88 +40,158 @@ Introduction of the Copyright and cvs Log
 //                                                                           //
 ///////////////////////////////////////////////////////////////////////////////
 
-#include <stdlib.h>
+#include <Riostream.h>
 #include <stdio.h>
+#include <stdlib.h>
 #include <string.h>
-#include <iostream.h>
  
-#include <TFile.h>
-#include <TRandom.h>
 #include <TBRIK.h> 
-#include <TNode.h> 
+#include <TBrowser.h>
 #include <TCint.h> 
-#include <TSystem.h>
-#include <TObjectTable.h>
-#include <TTree.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 "TBrowser.h"
+#include <TRandom.h>
+#include <TRandom3.h>
+#include <TSystem.h>
+#include <TTree.h>
+#include <TVirtualMC.h>
 
-#include "TParticle.h"
-#include "AliRun.h"
+#include "AliConfig.h"
+#include "AliDetector.h"
 #include "AliDisplay.h"
-#include "AliMC.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 "AliHit.h"
-#include "TRandom3.h"
-#include "AliMCQA.h"
-#include "AliGenerator.h"
-#include "AliLegoGenerator.h"
-
-#include "AliDetector.h"
+#include "AliPDG.h"
+#include "AliRun.h"
+#include "AliRunLoader.h"
+#include "AliStack.h"
 
 AliRun *gAlice;
 
-static AliHeader *gAliHeader;
-
 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
   //
-  gAliHeader=&fHeader;
-  fRun       = 0;
-  fEvent     = 0;
-  fCurrent   = -1;
-  fModules = 0;
-  fGenerator = 0;
-  fTreeD     = 0;
-  fTreeK     = 0;
-  fTreeH     = 0;
-  fTreeE     = 0;
-  fTreeR     = 0;
-  fTreeS     = 0;
-  fParticles = 0;
-  fGeometry  = 0;
-  fDisplay   = 0;
-  fField     = 0;
-  fMC       = 0;
-  fNdets     = 0;
-  fImedia    = 0;
-  fTrRmax    = 1.e10;
-  fTrZmax    = 1.e10;
-  fInitDone  = kFALSE;
-  fLego      = 0;
-  fPDGDB     = 0;        //Particle factory object!
-  fHitLists  = 0;
-  fConfigFunction    = "\0";
-  fRandom = 0;
-  fMCQA = 0;
-  fTransParName = "\0";
-  fBaseFileName = ".\0";
-  fParticleBuffer = 0;
-  fParticleMap = new TObjArray(10000);
+  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.
@@ -247,127 +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;
-  fTreeS     = 0;
-  fTrRmax    = 1.e10;
-  fTrZmax    = 1.e10;
-  fGenerator = 0;
-  fInitDone  = kFALSE;
-  fLego      = 0;
-  fField     = 0;
-  fConfigFunction    = "Config();";
 
   // Set random number generator
-  gRandom = fRandom = new TRandom3();
+  gRandom = fRandom;
 
   if (gSystem->Getenv("CONFIG_SEED")) {
-     gRandom->SetSeed((UInt_t)atoi(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;
-  gAliHeader=&fHeader;
-  fRun       = 0;
-  fEvent     = 0;
-  //
-  // Create the particle stack
-  fParticles = new TClonesArray("TParticle",1000);
-  
-  fDisplay = 0;
-  //
   // Create default mag field
   SetField();
-  //
-  fMC      = gMC;
-  //
+
   // Prepare the tracking medium lists
-  fImedia = new TArrayI(1000);
-  for(i=0;i<1000;i++) (*fImedia)[i]=-99;
-  //
-  // Make particles
-  fPDGDB     = TDatabasePDG::Instance();        //Particle factory object!
-  //
-  // Create HitLists list
-  fHitLists  = new TList();
-  //
+  for(Int_t i=0;i<1000;i++) (*fImedia)[i]=-99;
+
+  // Add particle list to configuration
+  AliConfig::Instance()->Add(fPDGDB); 
+
+  // Set transport parameters
   SetTransPar();
-  fBaseFileName = ".\0";
-  fParticleBuffer = 0;
-  fParticleMap = new TObjArray(10000);
 }
 
 
-//_____________________________________________________________________________
+//_______________________________________________________________________
 AliRun::~AliRun()
 {
   //
   // Default AliRun destructor
   //
+  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;
-  delete fTreeS;
   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)
 {
   //
@@ -375,22 +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());
-  if (fTreeS) b->Add(fTreeS,fTreeS->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()
 {
   //
@@ -399,7 +313,7 @@ void AliRun::Build()
   //
 }
  
-//_____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::BuildSimpleGeometry()
 {
   //
@@ -414,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/daughter relations
-  //
-  TObjArray &particles = *fParticleMap;
-  TParticle *part;
-  int i;
-  for(i=0; i<fHgwmk+1; i++) {
-    part = (TParticle *)particles.At(i);
-    if(part) if(!part->TestBit(kDaughtersBit)) {
-      part->SetFirstDaughter(-1);
-      part->SetLastDaughter(-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
@@ -456,33 +347,27 @@ Int_t AliRun::DistancetoPrimitive(Int_t, Int_t)
   return 9999;
 }
 
-//_____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::DumpPart (Int_t i) const
 {
   //
   // Dumps particle i in the stack
   //
-  ((TParticle*) (*fParticleMap)[i])->Print();
+   if (fRunLoader->Stack())
+    fRunLoader->Stack()->DumpPart(i);
 }
 
-//_____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::DumpPStack () const
 {
   //
   // Dumps the particle stack
   //
-  TObjArray &particles = *fParticleMap;
-  printf(
-        "\n\n=======================================================================\n");
-  for (Int_t i=0;i<fNtrack;i++) 
-    {
-      printf("-> %d ",i); ((TParticle*) particles[i])->Print();
-      printf("--------------------------------------------------------------\n");
-    }
-  printf(
-        "\n=======================================================================\n\n");
+   if (fRunLoader->Stack())
+    fRunLoader->Stack()->DumpPStack();
 }
 
+//_______________________________________________________________________
 void  AliRun::SetField(AliMagF* magField)
 {
     // Set Magnetic Field Map
@@ -490,7 +375,7 @@ void  AliRun::SetField(AliMagF* magField)
     fField->ReadField();
 }
 
-//_____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::SetField(Int_t type, Int_t version, Float_t scale,
                      Float_t maxField, char* filename)
 {
@@ -516,222 +401,81 @@ void AliRun::SetField(Int_t type, Int_t version, Float_t scale,
     Warning("SetField","Invalid map %d\n",version);
   }
 }
-//_____________________________________________________________________________
-void AliRun::PreTrack()
-{
-     TObjArray &dets = *fModules;
-     AliModule *module;
-
-     for(Int_t i=0; i<=fNdets; i++)
-       if((module = (AliModule*)dets[i]))
-        module->PreTrack();
-
-     fMCQA->PreTrack();
-}
 
 //_____________________________________________________________________________
-void AliRun::PostTrack()
-{
-     TObjArray &dets = *fModules;
-     AliModule *module;
-
-     for(Int_t i=0; i<=fNdets; i++)
-       if((module = (AliModule*)dets[i]))
-        module->PostTrack();
-}
 
-//_____________________________________________________________________________
-void AliRun::FinishPrimary()
+void AliRun::InitLoaders()
 {
-  //
-  // Called  at the end of each primary track
-  //
-  
-  //  static Int_t count=0;
-  //  const Int_t times=10;
-  // This primary is finished, purify stack
-  PurifyKine();
-
+  //creates list of getters
+  if (GetDebug()) Info("InitLoaders","");
   TIter next(fModules);
-  AliModule *detector;
-  while((detector = (AliModule*)next())) {
-    detector->FinishPrimary();
-  }
-
-  // Write out hits if any
-  if (gAlice->TreeH()) {
-    gAlice->TreeH()->Fill();
-  }
-  
-  // Reset Hits info
-  gAlice->ResetHits();
-
-  //
-  //  if(++count%times==1) gObjectTable->Print();
+  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::FinishEvent()
-{
-  //
-  // Called at the end of the event.
-  //
-  
-  //
-  if(fLego) fLego->FinishEvent();
-
-  //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];
-  }
-  fEventEnergy.Reset();
-  
-  // Clean detector information
-  CleanDetectors();
-  
-  // Write out the kinematics
-  if (fTreeK) {
-    CleanParents();
-    if(fTreeK->GetEntries() ==0) {
-      // set the fParticleFileMap size for the first time
-      fParticleFileMap.Set(fHgwmk+1);
-    }
-     //    fTreeK->Fill();
-    Bool_t allFilled = kFALSE;
-    TObject *part;
-    for(i=0; i<fHgwmk+1; ++i) if((part=fParticleMap->At(i))) {
-      fParticleBuffer = (TParticle*) part;
-      fParticleFileMap[i]= (Int_t) fTreeK->GetEntries();
-      fTreeK->Fill();
-      (*fParticleMap)[i]=0;      
-      
-      // When all primaries were filled no particle!=0
-      // should be left => to be removed later.
-      if (allFilled) printf("Why != 0 part # %d?\n",i);
-    }
-    else {
-      // // printf("Why = 0 part # %d?\n",i); => We know.
-      // break;
-           // we don't break now in order to be sure there is no
-          // particle !=0 left.
-          // To be removed later and replaced with break.
-      if(!allFilled) allFilled = kTRUE;
-    }  
-  }
-  
-  // Set number of tracks to event header 
-  fHeader.SetNtrack(fNtrack);
-  
-  // Write out the digits
-  if (fTreeD) {
-    fTreeD->Fill();
-    ResetDigits();
-  }
-
-   if (fTreeS) {
-    fTreeS->Fill();
-    ResetSDigits();
-  }
-  // 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
-  if (fTreeK) fTreeK->Write(0,TObject::kOverwrite);
-  if (fTreeH) fTreeH->Write(0,TObject::kOverwrite);
-  if (fTreeD) fTreeD->Write(0,TObject::kOverwrite);
-  if (fTreeR) fTreeR->Write(0,TObject::kOverwrite);
-  if (fTreeS) fTreeS->Write(0,TObject::kOverwrite);
-  
-  ++fEvent;
-}
 
-//_____________________________________________________________________________
 void AliRun::FinishRun()
 {
   //
   // Called at the end of the run.
   //
-
-  //
-  if(fLego) fLego->FinishRun();
-
+  
+  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();
-
-  TFile *file = fTreeE->GetCurrentFile();
-
-  file->cd();
-  
-  fTreeE->Write(0,TObject::kOverwrite);
   
+  if (GetDebug()) Info("FinishRun"," fRunLoader->WriteHeader(OVERWRITE)");
+  fRunLoader->WriteHeader("OVERWRITE");
+
   // Write AliRun info and all detectors parameters
-  Write(0,TObject::kOverwrite);
+  fRunLoader->CdGAFile();
+  Write(0,TObject::kOverwrite);//write AliRun
+  fRunLoader->Write(0,TObject::kOverwrite);//write RunLoader itself
   
   // Clean tree information
-  if (fTreeK) {
-    delete fTreeK; fTreeK = 0;
-  }
-  if (fTreeH) {
-    delete fTreeH; fTreeH = 0;
-  }
-  if (fTreeD) {
-    delete fTreeD; fTreeD = 0;
-  }
-  if (fTreeR) {
-    delete fTreeR; fTreeR = 0;
-  }
-  if (fTreeE) {
-    delete fTreeE; fTreeE = 0;
-  }
-    
-  // Close output file
-  file->Write();
+  if (GetDebug()) Info("FinishRun"," fRunLoader->Stack()->FinishRun()");
+  fRunLoader->Stack()->FinishRun();
+
+  // Clean detector information
+  if (GetDebug()) Info("FinishRun"," fGenerator->FinishRun()");
+  fGenerator->FinishRun();
+  
+  fRunLoader->Synchronize();
 }
 
-//_____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::FlagTrack(Int_t track)
 {
+  // Delegate to stack
   //
-  // Flags a track and all its family tree to be kept
-  //
-  int curr;
-  TParticle *particle;
-
-  curr=track;
-  while(1) {
-    particle=(TParticle*)fParticleMap->At(curr);
-    
-    // If the particle is flagged the three from here upward is saved already
-    if(particle->TestBit(kKeepBit)) return;
-    
-    // Save this particle
-    particle->SetBit(kKeepBit);
-    
-    // Move to father if any
-    if((curr=particle->GetFirstMother())==-1) return;
-  }
+    fRunLoader->Stack()->FlagTrack(track);
 }
  
-//_____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::EnergySummary()
 {
   //
@@ -743,7 +487,7 @@ void AliRun::EnergySummary()
   Float_t ed, ed2;
   Int_t kn, i, left, j, id;
   const Float_t kzero=0;
-  Int_t ievent=fHeader.GetEvent()+1;
+  Int_t ievent=fRunLoader->GetHeader()->GetEvent()+1;
   //
   // Energy loss information
   if(ievent) {
@@ -760,7 +504,7 @@ void AliRun::EnergySummary()
        } else 
          ed2=99;
        fSummEnergy[ndep]=ed;
-       fSum2Energy[ndep]=TMath::Min((Float_t) 99.,TMath::Max(ed2,kzero));
+       fSum2Energy[ndep]=TMath::Min(static_cast<Float_t>(99.),TMath::Max(ed2,kzero));
        edtot+=ed;
        ndep++;
       }
@@ -797,25 +541,46 @@ void AliRun::EnergySummary()
   //  fSum2Energy.Set(0);
 }
 
-//_____________________________________________________________________________
+//_______________________________________________________________________
+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) 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) const
 {
   //
@@ -827,106 +592,56 @@ Int_t AliRun::GetModuleID(const char *name) const
   return i;
 }
  
-//_____________________________________________________________________________
+//_______________________________________________________________________
 Int_t AliRun::GetEvent(Int_t event)
 {
-  //
-  // Connect the Trees Kinematics and Hits for event # event
-  // Set branch addresses
-  //
-
-  // 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();
   ResetSDigits();
-  
-  // Delete Trees already connected
-  if (fTreeK) delete fTreeK;
-  if (fTreeH) delete fTreeH;
-  if (fTreeD) delete fTreeD;
-  if (fTreeR) delete fTreeR;
-  if (fTreeS) delete fTreeS;
-
-  // Get header from file
-  if(fTreeE) fTreeE->GetEntry(event);
-  else Error("GetEvent","Cannot file Header Tree\n");
-  TFile *file = fTreeE->GetCurrentFile();
-
-  file->cd();
-  
-  // Get Kine Tree from file
-  char treeName[20];
-  sprintf(treeName,"TreeK%d",event);
-  fTreeK = (TTree*)gDirectory->Get(treeName);
-  if (fTreeK) fTreeK->SetBranchAddress("Particles", &fParticleBuffer);
-  else    Error("GetEvent","cannot find Kine Tree for event:%d\n",event);
-  // Create the particle stack
-  if(!fParticles) fParticles = new TClonesArray("TParticle",1000);
-  // Build the pointer list
-  if(fParticleMap) {
-    fParticleMap->Clear();
-    fParticleMap->Expand(fTreeK->GetEntries());
-  } else
-    fParticleMap = new TObjArray(fTreeK->GetEntries());
-  
-  file->cd();
-
-  // Get Hits Tree header from file
-  sprintf(treeName,"TreeH%d",event);
-  fTreeH = (TTree*)gDirectory->Get(treeName);
-  if (!fTreeH) {
-    Error("GetEvent","cannot find Hits Tree for event:%d\n",event);
-  }
-  
-  file->cd();
 
-  // Get Digits Tree header from file
-  sprintf(treeName,"TreeD%d",event);
-  fTreeD = (TTree*)gDirectory->Get(treeName);
-  if (!fTreeD) {
-    // Warning("GetEvent","cannot find Digits Tree for event:%d\n",event);
-  }
+/*****************************************/ 
+/****       R  E  L  O  A  D          ****/
+/*****************************************/
 
-  file->cd();
+  fRunLoader->GetEvent(event);
 
-  // Get SDigits Tree header from file
-  sprintf(treeName,"TreeS%d",event);
-  fTreeS = (TTree*)gDirectory->Get(treeName);
-  if (!fTreeS) {
-    // Warning("GetEvent","cannot find SDigits Tree for event:%d\n",event);
-  }
+/*****************************************/ 
+/****  P O S T    R E L O A D I N G   ****/
+/*****************************************/ 
 
-  file->cd();
-  
-  // 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);
-  }
-
-  file->cd();
   // Set Trees branch addresses
   TIter next(fModules);
   AliModule *detector;
-  while((detector = (AliModule*)next())) {
-    detector->SetTreeAddress();
-  }
-  
-  fNtrack = Int_t (fTreeK->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...
@@ -934,12 +649,12 @@ TGeometry *AliRun::GetGeometry()
   
   TIter next(fModules);
   AliModule *detector;
-  while((detector = (AliModule*)next())) {
+  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);
+      node = dynamic_cast<TNode*>(dnodes->At(j));
       node1 = fGeometry->GetNode(node->GetName());
       dnodes->Remove(node);
       dnodes->AddAt(node1,j);
@@ -948,145 +663,23 @@ 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
-  //
-  TVector3 pol;
-  fCurrent=-1;
-  TParticle *track;
-  for(Int_t i=fNtrack-1; i>=0; i--) {
-    track=(TParticle*) fParticleMap->At(i);
-    if(track) if(!track->TestBit(kDoneBit)) {
-      //
-      // The track exists and has not yet been processed
-      fCurrent=i;
-      ipart=track->GetPdgCode();
-      pmom[0]=track->Px();
-      pmom[1]=track->Py(); 
-      pmom[2]=track->Pz();
-      e     =track->Energy();
-      vpos[0]=track->Vx();
-      vpos[1]=track->Vy();
-      vpos[2]=track->Vz();
-      track->GetPolarisation(pol);
-      polar[0]=pol.X();
-      polar[1]=pol.Y();
-      polar[2]=pol.Z();
-      tof=track->T();
-      track->SetBit(kDoneBit);
-      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=(TParticle*) fParticleMap->At(fCurrent+1);
-    //    track->SetProcessTime(fTimer.CpuTime());
-  }
-  fTimer.Start();
-}
-
-//_____________________________________________________________________________
+//_______________________________________________________________________
 Int_t AliRun::GetPrimary(Int_t track) const
 {
   //
   // return number of primary that has generated track
   //
-  int current, parent;
-  TParticle *part;
-  //
-  parent=track;
-  while (1) {
-    current=parent;
-    part = (TParticle *)fParticleMap->At(current);
-    parent=part->GetFirstMother();
-    if(parent<0) return current;
-  }
+    return fRunLoader->Stack()->GetPrimary(track);
 }
  
-//_____________________________________________________________________________
-void AliRun::InitMC(const char *setup)
-{
-  //
-  // Initialize the Alice setup
-  //
-
-  if(fInitDone) {
-    Warning("Init","Cannot initialise AliRun twice!\n");
-    return;
-  }
-    
-  gROOT->LoadMacro(setup);
-  gInterpreter->ProcessLine(fConfigFunction.Data());
-
-
-  gMC->DefineParticles();  //Create standard MC particles
-
-  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 = (AliModule*)next())) {
-      detector->SetTreeAddress();
-      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.
-   fGeometry->Write();
-   
-   fInitDone = kTRUE;
-
-   fMCQA = new AliMCQA(fNdets);
-
-   //
-   // Save stuff at the beginning of the file to avoid file corruption
-   Write();
-}
-
-//_____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::MediaTable()
 {
   //
   // Built media table to get from the media number to
   // the detector id
   //
+
   Int_t kz, nz, idt, lz, i, k, ind;
   //  Int_t ibeg;
   TObjArray &dets = *gAlice->Detectors();
@@ -1095,7 +688,7 @@ void AliRun::MediaTable()
   // For all detectors
   for (kz=0;kz<fNdets;kz++) {
     // If detector is defined
-    if((det=(AliModule*) dets[kz])) {
+    if((det=dynamic_cast<AliModule*>(dets[kz]))) {
         TArrayI &idtmed = *(det->GetIdtmed()); 
         for(nz=0;nz<100;nz++) {
        // Find max and min material number
@@ -1126,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());
@@ -1137,7 +730,7 @@ void AliRun::MediaTable()
   }
 }
 
-//____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::SetGenerator(AliGenerator *generator)
 {
   //
@@ -1146,7 +739,7 @@ void AliRun::SetGenerator(AliGenerator *generator)
   if(!fGenerator) fGenerator = generator;
 }
 
-//____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::ResetGenerator(AliGenerator *generator)
 {
   //
@@ -1162,19 +755,22 @@ void AliRun::ResetGenerator(AliGenerator *generator)
   fGenerator = generator;
 }
 
-//____________________________________________________________________________
-void AliRun::SetTransPar(char *filename)
+//_______________________________________________________________________
+void AliRun::SetTransPar(const char *filename)
 {
+  //
+  // Sets the file name for transport parameters
+  //
   fTransParName = filename;
 }
 
-//____________________________________________________________________________
-void AliRun::SetBaseFile(char *filename)
+//_______________________________________________________________________
+void AliRun::SetBaseFile(const char *filename)
 {
   fBaseFileName = filename;
 }
 
-//____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::ReadTransPar()
 {
   //
@@ -1206,10 +802,12 @@ void AliRun::ReadTransPar()
     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
@@ -1222,8 +820,10 @@ void AliRun::ReadTransPar()
     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
@@ -1256,7 +856,7 @@ void AliRun::ReadTransPar()
        // Set energy thresholds
        for(kz=0;kz<kncuts;kz++) {
          if(cut[kz]>=0) {
-           printf(" *  %-6s set to %10.3E for tracking medium code %4d for %s\n",
+           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]);
          }
@@ -1264,7 +864,7 @@ void AliRun::ReadTransPar()
        // Set transport mechanisms
        for(kz=0;kz<knflags;kz++) {
          if(flag[kz]>=0) {
-           printf(" *  %-6s set to %10d for tracking medium code %4d for %s\n",
+           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]));
          }
@@ -1274,340 +874,100 @@ void AliRun::ReadTransPar()
        continue;
       }
     } else {
-      Warning("ReadTransPar","Module %s not present\n",detName);
+      if(fDebug) printf("%s::ReadTransParModule: %s not present\n",ClassName(),detName);
       continue;
     }
   }
 }
-
 //_____________________________________________________________________________
-void AliRun::MakeBranchInTree(TTree *tree, const char* name, void* address, Int_t size, char *file)
-{ 
-    //
-    // Makes branch in given tree and diverts them  to a separate file 
-    //  
-    if (GetDebug()>1)
-        printf("* MakeBranch * Making Branch %s \n",name);
-
-    TBranch *branch = tree->Branch(name,address,size);
-
-    if (file) {
-        char * outFile = new char[strlen(gAlice->GetBaseFile())+strlen(file)+2];
-        sprintf(outFile,"%s/%s",gAlice->GetBaseFile(),file);
-        TDirectory *cwd = gDirectory;
-        branch->SetFile(outFile);
-        TIter next( branch->GetListOfBranches());
-        while ((branch=(TBranch*)next())) {
-           branch->SetFile(outFile);
-        }   
-        if (GetDebug()>1)
-            printf("* MakeBranch * Diverting Branch %s to file %s\n",name,file);
-        cwd->cd();
-        delete outFile;
-    } 
-}
 
-//_____________________________________________________________________________
-void AliRun::MakeBranchInTree(TTree *tree, const char* name, const char *classname, void* address, Int_t size, Int_t splitlevel, char *file)
-{ 
-    //
-    // Makes branch in given tree and diverts them to a separate file
-    //  
-    TDirectory *cwd = gDirectory;
-    TBranch *branch = tree->Branch(name,classname,address,size,splitlevel);
-    if (GetDebug()>1)
-      printf("* MakeBranch * Making Branch %s \n",name);
-    if (file) {
-        char * outFile = new char[strlen(gAlice->GetBaseFile())+strlen(file)+2];
-        sprintf(outFile,"%s/%s",gAlice->GetBaseFile(),file);
-        branch->SetFile(outFile);
-        TIter next( branch->GetListOfBranches());
-        while ((branch=(TBranch*)next())) {
-           branch->SetFile(outFile);
-        } 
-       if (GetDebug()>1)
-           printf("* MakeBranch * Diverting Branch %s to file %s\n",name,file);
-        cwd->cd();
-        delete outFile;
-    }
-}
-//_____________________________________________________________________________
-void AliRun::MakeTree(Option_t *option, char *file)
+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            */
+  /*******************************/    
 
-  char hname[30];
-  //
-  // Analyse options
-  char *oK = strstr(option,"K");
-  char *oH = strstr(option,"H");
-  char *oE = strstr(option,"E");
-  char *oD = strstr(option,"D");
-  char *oR = strstr(option,"R");
-  char *oS = strstr(option,"S");
-  //
   
-  if (oK && !fTreeK) {
-    sprintf(hname,"TreeK%d",fEvent);
-    fTreeK = new TTree(hname,"Kinematics");
-    //  Create a branch for particles
-    MakeBranchInTree(fTreeK, 
-                     "Particles", "TParticle", &fParticleBuffer, 4000, 1, file) ;
-    fTreeK->Write();
-  }
-  if (oH && !fTreeH) {
-    sprintf(hname,"TreeH%d",fEvent);
-    fTreeH = new TTree(hname,"Hits");
-    fTreeH->SetAutoSave(1000000000); //no autosave
-    fTreeH->Write();
-  }
-  if (oD && !fTreeD) {
-    sprintf(hname,"TreeD%d",fEvent);
-    fTreeD = new TTree(hname,"Digits");
-    fTreeD->Write();
-  }
-  if (oS && !fTreeS) {
-    sprintf(hname,"TreeS%d",fEvent);
-    fTreeS = new TTree(hname,"SDigits");
-    fTreeS->Write();
-  }
-  if (oR && !fTreeR) {
-    sprintf(hname,"TreeR%d",fEvent);
-    fTreeR = new TTree(hname,"Reconstruction");
-    fTreeR->Write();
-  }
-  if (oE && !fTreeE) {
-    fTreeE = new TTree("TE","Header");
-    //  Create a branch for Header
-    MakeBranchInTree(fTreeE, 
-                     "Header", "AliHeader", &gAliHeader, 4000, 1, file) ;
-    fTreeE->Write();
-  }
+  //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
   
-  //
-  // 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
-  TIter next(fModules);
-  AliModule *detector;
-  while((detector = (AliModule*)next())) {
-     if (oH) detector->MakeBranch(option,file);
-  }
-}
-
-//_____________________________________________________________________________
-Int_t AliRun::PurifyKine(Int_t lastSavedTrack, Int_t nofTracks)
-{
-  //
-  // PurifyKine with external parameters
-  //
-  fHgwmk = lastSavedTrack;
-  fNtrack = nofTracks;
-  PurifyKine();
-  return fHgwmk;
-}
-
-//_____________________________________________________________________________
-TParticle* AliRun::Particle(Int_t i)
-{
-  if(!(*fParticleMap)[i]) {
-    Int_t nentries = fParticles->GetEntries();
+  if (fRunLoader->Stack())
+    fRunLoader->Stack()->Reset();//clean stack -> tree is unloaded
+  else
+    fRunLoader->MakeStack();//or make a new one
     
-    // algorithmic way of getting entry index
-    // (primary particles are filled after secondaries)
-    Int_t entry;
-    if (i<fHeader.GetNprimary())
-      entry = i+fHeader.GetNsecondary();
-    else 
-      entry = i-fHeader.GetNprimary();
-      
-    // only check the algorithmic way and give
-    // the fatal error if it is wrong
-    if (entry != fParticleFileMap[i]) {
-      Fatal("Particle",
-        "!!!! The algorithmic way is WRONG: !!!\n entry: %d map: %d",
-       entry, fParticleFileMap[i]); 
-    }  
-      
-    fTreeK->GetEntry(fParticleFileMap[i]);
-    new ((*fParticles)[nentries]) TParticle(*fParticleBuffer);
-    fParticleMap->AddAt((*fParticles)[nentries],i);
-  }
-  return (TParticle *) (*fParticleMap)[i];
-}
-
-//_____________________________________________________________________________
-void AliRun::PurifyKine()
-{
+  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
   //
-  // Compress kinematic tree keeping only flagged particles
-  // and renaming the particle id's in all the hits
+  //  Reset all Detectors & kinematics & make/reset trees
   //
-  //  TClonesArray &particles = *fParticles;
-  TObjArray &particles = *fParticleMap;
-  int nkeep=fHgwmk+1, parent, i;
-  TParticle *part, *father;
-  TArrayI map(particles.GetLast()+1);
-
-  // Save in Header total number of tracks before compression
-  fHeader.SetNtrack(fHeader.GetNtrack()+fNtrack-fHgwmk);
-
-  // If no tracks generated return now
-  if(fHgwmk+1 == fNtrack) return;
-
-  Int_t toshrink = fNtrack-fHgwmk-1;
+    
+  fRunLoader->GetHeader()->Reset(fRun,fEvent,fEventNrInRun);
+//  fRunLoader->WriteKinematics("OVERWRITE");  is there any reason to rewrite here since MakeTree does so
 
-  // First pass, invalid Daughter information
-  for(i=0; i<fNtrack; i++) {
-    // Preset map, to be removed later
-    if(i<=fHgwmk) map[i]=i ; 
-    else {
-      map[i] = -99;
-      //      particles.UncheckedAt(i)->ResetBit(kDaughtersBit);
-      if((part=(TParticle*) particles.At(i))) part->ResetBit(kDaughtersBit);
-    }
-  }
-  // Invalid daughter information for the parent of the first particle
-  // generated. This may or may not be the current primary according to
-  // whether decays have been recorded among the primaries
-  part = (TParticle *)particles.At(fHgwmk+1);
-  particles.At(part->GetFirstMother())->ResetBit(kDaughtersBit);
-  // Second pass, build map between old and new numbering
-  for(i=fHgwmk+1; i<fNtrack; i++) {
-    if(particles.At(i)->TestBit(kKeepBit)) {
-      
-      // This particle has to be kept
-      map[i]=nkeep;
-      // If old and new are different, have to move the pointer
-      if(i!=nkeep) particles[nkeep]=particles.At(i);
-      part = (TParticle*) particles.At(nkeep);
-      
-      // as the parent is always *before*, it must be already
-      // in place. This is what we are checking anyway!
-      if((parent=part->GetFirstMother())>fHgwmk) 
-       if(map[parent]==-99) Fatal("PurifyKine","map[%d] = -99!\n",parent);
-       else part->SetFirstMother(map[parent]);
+  if (GetDebug()) Info("BeginEvent","  fRunLoader->MakeTrackRefsContainer()");
+  fRunLoader->MakeTrackRefsContainer();//for insurance
 
-      nkeep++;
-    }
-  }
-  
-  // Fix daughters information
-  for (i=fHgwmk+1; i<nkeep; i++) {
-    part = (TParticle *)particles.At(i);
-    parent = part->GetFirstMother();
-    if(parent>=0) {
-      father = (TParticle *)particles.At(parent);
-      if(father->TestBit(kDaughtersBit)) {
-      
-       if(i<father->GetFirstDaughter()) father->SetFirstDaughter(i);
-       if(i>father->GetLastDaughter())  father->SetLastDaughter(i);
-      } else {
-       // Initialise daughters info for first pass
-       father->SetFirstDaughter(i);
-       father->SetLastDaughter(i);
-       father->SetBit(kDaughtersBit);
-      }
-    }
-  }
-  
-  // Now loop on all registered hit lists
-  TIter next(fHitLists);
-  TCollection *hitList;
-  while((hitList = (TCollection*)next())) {
-    TIter nexthit(hitList);
-    AliHit *hit;
-    while((hit = (AliHit*)nexthit())) {
-      hit->SetTrack(map[hit->GetTrack()]);
-    }
-  }
+  if (GetDebug()) Info("BeginEvent","  ResetHits()");
+  ResetHits();
+  if (GetDebug()) Info("BeginEvent","  fRunLoader->MakeTree(H)");
+  fRunLoader->MakeTree("H");
 
-  // 
-  // This for detectors which have a special mapping mechanism
-  // for hits, such as TPC and TRD
   //
-
-   TIter nextmod(fModules);
-   AliModule *detector;
-   while((detector = (AliModule*)nextmod())) {
-     detector->RemapTrackHitIDs(map.GetArray());
+  if(fLego) 
+   {
+    fLego->BeginEvent();
+    return;
    }
-  
-   // Now the output bit, from fHgwmk to nkeep we write everything and we erase
-   if(nkeep>fParticleFileMap.GetSize()) fParticleFileMap.Set(Int_t (nkeep*1.5));
-
 
-   for (i=fHgwmk+1; i<nkeep; ++i) {
-     fParticleBuffer = (TParticle*) particles.At(i);
-     fParticleFileMap[i]=(Int_t) fTreeK->GetEntries();
-     fTreeK->Fill();
-     particles[i]=0;
+  //create new branches and SetAdresses
+  TIter next(fModules);
+  AliModule *detector;
+  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();
    }
-
-   for (i=nkeep; i<fNtrack; ++i) particles[i]=0;
-
-   fLoadPoint-=toshrink;
-   for(i=fLoadPoint; i<fLoadPoint+toshrink; ++i) fParticles->RemoveAt(i);
-
-   fNtrack=nkeep;
-   fHgwmk=nkeep-1;
-   //   delete [] map;
 }
 
-//_____________________________________________________________________________
-void AliRun::BeginEvent()
+//_______________________________________________________________________
+TParticle* AliRun::Particle(Int_t i) const
 {
-  //
-  //  Reset all Detectors & kinematics & trees
-  //
-  char hname[30];
-  //
-
-  //
-  if(fLego) {
-    fLego->BeginEvent();
-    return;
-  }
-
-  //
-  ResetStack();
-  ResetHits();
-  ResetDigits();
-  ResetSDigits();
-
-  // Initialise event header
-  fHeader.Reset(fRun,fEvent);
-
-  if(fTreeK) {
-    fTreeK->Reset();
-    sprintf(hname,"TreeK%d",fEvent);
-    fTreeK->SetName(hname);
-  }
-  if(fTreeH) {
-    fTreeH->Reset();
-    sprintf(hname,"TreeH%d",fEvent);
-    fTreeH->SetName(hname);
-  }
-  if(fTreeD) {
-    fTreeD->Reset();
-    sprintf(hname,"TreeD%d",fEvent);
-    fTreeD->SetName(hname);
-  }
-  if(fTreeS) {
-    fTreeS->Reset();
-    sprintf(hname,"TreeS%d",fEvent);
-    fTreeS->SetName(hname);
-  }
-  if(fTreeR) {
-    fTreeR->Reset();
-    sprintf(hname,"TreeR%d",fEvent);
-    fTreeR->SetName(hname);
-  }
+  if (fRunLoader)
+   if (fRunLoader->Stack())
+    return fRunLoader->Stack()->Particle(i);
+  return 0x0;   
 }
-//_____________________________________________________________________________
+
+//_______________________________________________________________________
 void AliRun::ResetDigits()
 {
   //
@@ -1615,12 +975,12 @@ void AliRun::ResetDigits()
   //
   TIter next(fModules);
   AliModule *detector;
-  while((detector = (AliModule*)next())) {
+  while((detector = dynamic_cast<AliModule*>(next()))) {
      detector->ResetDigits();
   }
 }
 
-//_____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::ResetSDigits()
 {
   //
@@ -1628,12 +988,12 @@ void AliRun::ResetSDigits()
   //
   TIter next(fModules);
   AliModule *detector;
-  while((detector = (AliModule*)next())) {
+  while((detector = dynamic_cast<AliModule*>(next()))) {
      detector->ResetSDigits();
   }
 }
 
-//_____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::ResetHits()
 {
   //
@@ -1641,12 +1001,25 @@ void AliRun::ResetHits()
   //
   TIter next(fModules);
   AliModule *detector;
-  while((detector = (AliModule*)next())) {
+  while((detector = dynamic_cast<AliModule*>(next()))) {
      detector->ResetHits();
   }
 }
+//_______________________________________________________________________
+
+void AliRun::ResetTrackReferences()
+{
+  //
+  //  Reset all Detectors hits
+  //
+  TIter next(fModules);
+  AliModule *detector;
+  while((detector = dynamic_cast<AliModule*>(next()))) {
+     detector->ResetTrackReferences();
+  }
+}
+//_______________________________________________________________________
 
-//_____________________________________________________________________________
 void AliRun::ResetPoints()
 {
   //
@@ -1654,12 +1027,96 @@ void AliRun::ResetPoints()
   //
   TIter next(fModules);
   AliModule *detector;
-  while((detector = (AliModule*)next())) {
+  while((detector = dynamic_cast<AliModule*>(next()))) {
      detector->ResetPoints();
   }
 }
+//_______________________________________________________________________
+
+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)
 {
   //
@@ -1669,20 +1126,12 @@ void AliRun::RunMC(Int_t nevent, const char *setup)
   // a positive number of events will cause the finish routine
   // to be called
   //
-
+  fEventsPerRun = nevent;
   // check if initialisation has been done
   if (!fInitDone) InitMC(setup);
   
   // Create the Root Tree with one branch per detector
-
-   MakeTree("ESD");
-
-  if (gSystem->Getenv("CONFIG_SPLIT_FILE")) {
-     MakeTree("K","Kine.root");
-     MakeTree("H","Hits.root");
-  } else {
-     MakeTree("KH");
-  }
+  //Hits moved to begin event -> now we are crating separate tree for each event
 
   gMC->ProcessRun(nevent);
 
@@ -1690,29 +1139,40 @@ void AliRun::RunMC(Int_t nevent, const char *setup)
   if(nevent>0) FinishRun();
 }
 
-//_____________________________________________________________________________
-void AliRun::RunReco(const char *detector)
+//_______________________________________________________________________
+void AliRun::RunReco(const char *selected, Int_t first, Int_t last)
 {
   //
   // Main function to be called to reconstruct Alice event
   // 
-
-   MakeTree("R");
-   Digits2Reco(detector);
+   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
    // 
-   Hits2SDigits(selected);
-   SDigits2Digits(selected);
+   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)
 {
@@ -1728,62 +1188,64 @@ void AliRun::Tree2Tree(Option_t *option, const char *selected)
   // can contain blank separated list of detector names). 
 
 
-   char *oS = strstr(option,"S");
-   char *oD = strstr(option,"D");
-   char *oR = strstr(option,"R");
+   const char *oS = strstr(option,"S");
+   const char *oD = strstr(option,"D");
+   const char *oR = strstr(option,"R");
    
-   gAlice->GetEvent(0);
-
-   TObjArray *detectors = gAlice->Detectors();
+   TObjArray *detectors = Detectors();
 
    TIter next(detectors);
 
    AliDetector *detector = 0;
 
-   TDirectory *cwd = gDirectory;
-
-   char outFile[32];
-   
-   while((detector = (AliDetector*)next())) {
+   while((detector = dynamic_cast<AliDetector*>(next()))) {
      if (selected) 
        if (strcmp(detector->GetName(),selected)) continue;
-     if (detector->IsActive()){ 
-       if (GetDebug()>0)
-             cout << "Processing " << detector->GetName() << "..." << endl;
-       if (gSystem->Getenv("CONFIG_SPLIT_FILE")) {          
-          if (oS) {
-            sprintf(outFile,"SDigits.%s.root",detector->GetName());
-            detector->MakeBranch("S",outFile);
-          }    
-          if (oD) {
-            sprintf(outFile,"Digits.%s.root",detector->GetName());
-            detector->MakeBranch("D",outFile);
-          }    
-          if (oR) {
-            sprintf(outFile,"Reco.%s.root",detector->GetName());
-            detector->MakeBranch("R",outFile);
-          }    
-       } else {
-          detector->MakeBranch(option);
-       }
+     if (detector->IsActive())
+      { 
+       
+       AliLoader* loader = detector->GetLoader();
+       if (loader == 0x0) continue;
        
-       cwd->cd(); 
-
        if (oS) 
-          detector->Hits2SDigits(); 
+        {
+          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) 
-          detector->SDigits2Digits(); 
+        {
+          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();
 
-       cwd->cd(); 
-       
-     }  
+        }
+     }   
    }
 }
 
-
-//_____________________________________________________________________________
+//_______________________________________________________________________
 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)
@@ -1850,10 +1312,11 @@ void AliRun::RunLego(const char *setup, Int_t nc1, Float_t c1min,
   
   //Run Lego Object
 
-  gMC->ProcessRun(nc1*nc2+1);
+  //gMC->ProcessRun(nc1*nc2+1);
+  gMC->ProcessRun(nc1*nc2);
   
   // Create only the Root event Tree
-  MakeTree("E");
+  fRunLoader->MakeTree("E");
   
   // End of this run, close files
   FinishRun();
@@ -1863,7 +1326,7 @@ void AliRun::RunLego(const char *setup, Int_t nc1, Float_t c1min,
   delete fLego; fLego=0;
 }
 
-//_____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::SetConfigFunction(const char * config) 
 {
   //
@@ -1873,195 +1336,149 @@ void AliRun::SetConfigFunction(const char * config)
   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 pdg, Float_t *pmom,
-                     Float_t *vpos, Float_t *polar, Float_t tof,
-                     AliMCProcess mech, 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)
 { 
-  //
-  // 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
-  // pdg    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;
-  TParticle *particle;
-  Float_t mass;
-  const Int_t kfirstdaughter=-1;
-  const Int_t klastdaughter=-1;
-  const Int_t kS=0;
-  //  const Float_t tlife=0;
-  
-  //
-  // Here we get the static mass
-  // For MC is ok, but a more sophisticated method could be necessary
-  // if the calculated mass is required
-  // also, this method is potentially dangerous if the mass
-  // used in the MC is not the same of the PDG database
-  //
-  mass = TDatabasePDG::Instance()->GetParticle(pdg)->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,pdg,vpos[0],vpos[1],vpos[2],pmom[0],pmom[1],pmom[2],kS,mecha);
-
-  particle=new(particles[fLoadPoint++]) TParticle(pdg,kS,parent,-1,kfirstdaughter,
-                                            klastdaughter,pmom[0],pmom[1],pmom[2],
-                                            e,vpos[0],vpos[1],vpos[2],tof);
-  particle->SetPolarisation(TVector3(polar[0],polar[1],polar[2]));
-  particle->SetWeight(weight);
-  particle->SetUniqueID(mech);
-  if(!done) particle->SetBit(kDoneBit);
-  //  Declare that the daughter information is valid
-  particle->SetBit(kDaughtersBit);
-  //  Add the particle to the stack
-  fParticleMap->AddAtAndExpand(particle,fNtrack);
-
-  if(parent>=0) {
-    particle=(TParticle*) fParticleMap->At(parent);
-    particle->SetLastDaughter(fNtrack);
-    if(particle->GetFirstDaughter()<0) particle->SetFirstDaughter(fNtrack);
-  } else { 
-    //
-    // This is a primary track. Set high water mark for this event
-    fHgwmk=fNtrack;
-    //
-    // Set also number if primary tracks
-    fHeader.SetNprimary(fHgwmk+1);
-    fHeader.SetNtrack(fHgwmk+1);
-  }
-  ntr = fNtrack++;
-  
-/*
-  //
-  // Here we get the static mass
-  // For MC is ok, but a more sophisticated method could be necessary
-  // if the calculated mass is required
-  // also, this method is potentially dangerous if the mass
-  // used in the MC is not the same of the PDG database
-  //
-  Float_t mass = TDatabasePDG::Instance()->GetParticle(pdg)->Mass();
-  Float_t e=TMath::Sqrt(mass*mass+pmom[0]*pmom[0]+
-                       pmom[1]*pmom[1]+pmom[2]*pmom[2]);
-                       
-  SetTrack(done, parent, pdg, pmom[0], pmom[1], pmom[2], e,
-           vpos[0], vpos[1], vpos[2], tof, polar[0],polar[1],polar[2],
-          mech, ntr, weight);
-*/        
+// Delegate to stack
+//
+    fRunLoader->Stack()->PushTrack(done, parent, pdg, pmom, vpos, polar, tof,
+                    mech, ntr, weight, is);
 }
 
-//_____________________________________________________________________________
-void AliRun::SetTrack(Int_t done, Int_t parent, Int_t pdg,
+//_______________________________________________________________________
+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,
-                     AliMCProcess mech, Int_t &ntr, Float_t weight)
+                     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
-  // pdg         particle code
-  // kS          generation status code
-  // px, py, pz  momentum GeV/c
-  // vx, vy, vz  position 
-  // polar       polarisation 
-  // tof         time of flight in seconds
-  // mech        production mechanism
-  // ntr         on output the number of the track stored
-  //    
-  // New method interface: 
-  // arguments were changed to be in correspondence with TParticle
-  // constructor.
-  // Note: the energy is not calculated from the static mass but
-  // it is passed by argument e.
-
-  TClonesArray &particles = *fParticles;
-
-  const Int_t kS=0;
-  const Int_t kFirstDaughter=-1;
-  const Int_t kLastDaughter=-1;
-  
-  TParticle* particle
-    = new(particles[fLoadPoint++]) TParticle(pdg, kS, parent, -1, 
-                                        kFirstDaughter, kLastDaughter,
-                                       px, py, pz, e, vx, vy, vz, tof);
-   
-  particle->SetPolarisation(polx, poly, polz);
-  particle->SetWeight(weight);
-  particle->SetUniqueID(mech);
-
-  if(!done) particle->SetBit(kDoneBit);
-
-  //  Declare that the daughter information is valid
-  particle->SetBit(kDaughtersBit);
-  //  Add the particle to the stack
-  fParticleMap->AddAtAndExpand(particle,fNtrack);
-
-  if(parent>=0) {
-    particle=(TParticle*) fParticleMap->At(parent);
-    particle->SetLastDaughter(fNtrack);
-    if(particle->GetFirstDaughter()<0) particle->SetFirstDaughter(fNtrack);
-  } else { 
-    //
-    // This is a primary track. Set high water mark for this event
-    fHgwmk=fNtrack;
-    //
-    // Set also number if primary tracks
-    fHeader.SetNprimary(fHgwmk+1);
-    fHeader.SetNtrack(fHgwmk+1);
-  }
-  ntr = 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 high water mark for last track in event
-    fHgwmk=fNtrack-1;
-    //
-    // Set also number if primary tracks
-    fHeader.SetNprimary(fHgwmk+1);
-    fHeader.SetNtrack(fHgwmk+1);
+    fRunLoader->Stack()->SetHighWaterMark(nt);
 }
 
-//_____________________________________________________________________________
+//_______________________________________________________________________
 void AliRun::KeepTrack(const Int_t track)
 { 
   //
-  // flags a track to be kept
+  // Delegate to stack
   //
-  fParticleMap->At(track)->SetBit(kKeepBit);
+    fRunLoader->Stack()->KeepTrack(track);
 }
  
-//_____________________________________________________________________________
-void AliRun::StepManager(Int_t id) 
+// 
+// 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
   //
 
+  Int_t id = DetFromMate(gMC->GetMedium());
+  if (id < 0) return;
+
   //
   // --- If lego option, do it and leave 
   if (fLego)
@@ -2072,34 +1489,264 @@ void AliRun::StepManager(Int_t id)
     AddEnergyDeposit(gMC->CurrentVolID(copy),gMC->Edep());
   
     //Call the appropriate stepping routine;
-    AliModule *det = (AliModule*)fModules->At(id);
-    if(det) {
+    AliModule *det = dynamic_cast<AliModule*>(fModules->At(id));
+    if(det && det->StepManagerIsEnabled()) {
       fMCQA->StepManager(id);
       det->StepManager();
     }
   }
 }
 
-//_____________________________________________________________________________
+//_______________________________________________________________________
+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()
+{
+  //
+  // Called  at the end of each primary track
+  //
+  
+  //  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();
+     }
+  }
+
+  // Write out track references if any
+  if (fRunLoader->TreeTR()) 
+   {
+    fRunLoader->TreeTR()->Fill();
+   }
+}
+
+//_______________________________________________________________________
+void AliRun::FinishEvent()
+{
+  //
+  // Called at the end of the event.
+  //
+  
+  //
+  if(fLego) fLego->FinishEvent();
+
+  TIter next(fModules);
+  AliModule *detector;
+  while((detector = dynamic_cast<AliModule*>(next()))) {
+    detector->FinishEvent();
+  }
+
+  //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.
+  // Stream an object of class AliRun.
+
+  if (R__b.IsReading()) {
+    if (!gAlice) gAlice = this;
+    AliRun::Class()->ReadBuffer(R__b, this);
+    gROOT->GetListOfBrowsables()->Add(this,"Run");
+
+    gRandom = fRandom;
+  } else {
+    AliRun::Class()->WriteBuffer(R__b, this);
+  }
+}
+
+
+//_______________________________________________________________________
+Int_t AliRun::GetCurrentTrackNumber() const {
+  //
+  // Returns current track
+  //
+  return fRunLoader->Stack()->GetCurrentTrackNumber();
+}
+
+//_______________________________________________________________________
+Int_t AliRun::GetNtrack() const {
+  //
+  // Returns number of tracks in stack
+  //
+  return fRunLoader->Stack()->GetNtrack();
+}
+//_______________________________________________________________________
+
+//_______________________________________________________________________
+TObjArray* AliRun::Particles() const {
+  //
+  // Returns pointer to Particles array
+  //
+  if (fRunLoader)
+   if (fRunLoader->Stack())
+    return fRunLoader->Stack()->Particles();
+  return 0x0;
+}
+
+//___________________________________________________________________________
+
+//_______________________________________________________________________
+void AliRun::SetGenEventHeader(AliGenEventHeader* header)
+{
+  fRunLoader->GetHeader()->SetGenEventHeader(header);
+}
 
-   if (R__b.IsReading()) {
-      if (!gAlice) gAlice = this;
+//___________________________________________________________________________
 
-      AliRun::Class()->ReadBuffer(R__b, this);
-      //
-      gROOT->GetListOfBrowsables()->Add(this,"Run");
+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;
+   }
 
-      fTreeE = (TTree*)gDirectory->Get("TE");
-      if (fTreeE) fTreeE->SetBranchAddress("Header", &gAliHeader);
-      else    Error("Streamer","cannot find Header Tree\n");
-      fTreeE->GetEntry(0);
+  return fRunLoader->GetEventNumber();
+}
 
-      gRandom = fRandom;
-   } else {
-      AliRun::Class()->WriteBuffer(R__b, this);
+void AliRun::SetRunLoader(AliRunLoader* rloader)
+{
+  fRunLoader = rloader;
+  if (fRunLoader == 0x0) return;
+  
+  TString evfoldname;
+  TFolder* evfold = fRunLoader->GetEventFolder();
+  if (evfold) evfoldname = evfold->GetName();
+  else Warning("SetRunLoader","Did not get Event Folder from Run Loader");
+  
+  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);
+         }
+      }
    }
 }
 
+void AliRun::AddModule(AliModule* mod)
+{
+  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);
+}