]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - STEER/AliRun.cxx
Fix for multiple events per file: inhibit decrease of size of fParticleFileMap.
[u/mrichter/AliRoot.git] / STEER / AliRun.cxx
index f16f78cdafba5a4dcada1e42739c395f81c41e80..5447c982610741830e62220d95d800406ec33b3b 100644 (file)
 
 /*
 $Log$
+Revision 1.57  2001/02/23 17:40:23  buncic
+All trees needed for simulation created in RunMC(). TreeR and its branches
+are now created in new RunReco() method.
+
+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
 
@@ -115,6 +165,7 @@ Introduction of the Copyright and cvs Log
 #include <stdlib.h>
 #include <stdio.h>
 #include <string.h>
+#include <iostream.h>
  
 #include <TFile.h>
 #include <TRandom.h>
@@ -137,6 +188,10 @@ Introduction of the Copyright and cvs Log
 #include "AliMagFCM.h"
 #include "AliMagFDM.h"
 #include "AliHit.h"
+#include "TRandom3.h"
+#include "AliMCQA.h"
+#include "AliGenerator.h"
+#include "AliLegoGenerator.h"
 
 #include "AliDetector.h"
 
@@ -163,6 +218,7 @@ AliRun::AliRun()
   fTreeH     = 0;
   fTreeE     = 0;
   fTreeR     = 0;
+  fTreeS     = 0;
   fParticles = 0;
   fGeometry  = 0;
   fDisplay   = 0;
@@ -177,6 +233,12 @@ AliRun::AliRun()
   fPDGDB     = 0;        //Particle factory object!
   fHitLists  = 0;
   fConfigFunction    = "\0";
+  fRandom = 0;
+  fMCQA = 0;
+  fTransParName = "\0";
+  fBaseFileName = ".\0";
+  fParticleBuffer = 0;
+  fParticleMap = new TObjArray(10000);
 }
 
 //_____________________________________________________________________________
@@ -197,6 +259,7 @@ AliRun::AliRun(const char *name, const char *title)
   fTreeH     = 0;
   fTreeE     = 0;
   fTreeR     = 0;
+  fTreeS     = 0;
   fTrRmax    = 1.e10;
   fTrZmax    = 1.e10;
   fGenerator = 0;
@@ -204,6 +267,13 @@ AliRun::AliRun(const char *name, const char *title)
   fLego      = 0;
   fField     = 0;
   fConfigFunction    = "Config();";
+
+  // Set random number generator
+  gRandom = fRandom = new TRandom3();
+
+  if (gSystem->Getenv("CONFIG_SEED")) {
+     gRandom->SetSeed((UInt_t)atoi(gSystem->Getenv("CONFIG_SEED")));
+  }
   
   gROOT->GetListOfBrowsables()->Add(this,name);
   //
@@ -223,7 +293,7 @@ AliRun::AliRun(const char *name, const char *title)
   fEvent     = 0;
   //
   // Create the particle stack
-  fParticles = new TClonesArray("TParticle",100);
+  fParticles = new TClonesArray("TParticle",1000);
   
   fDisplay = 0;
   //
@@ -241,6 +311,11 @@ AliRun::AliRun(const char *name, const char *title)
   //
   // Create HitLists list
   fHitLists  = new TList();
+  //
+  SetTransPar();
+  fBaseFileName = ".\0";
+  fParticleBuffer = 0;
+  fParticleMap = new TObjArray(10000);
 }
 
 
@@ -248,7 +323,7 @@ AliRun::AliRun(const char *name, const char *title)
 AliRun::~AliRun()
 {
   //
-  // Defaullt AliRun destructor
+  // Default AliRun destructor
   //
   delete fImedia;
   delete fField;
@@ -262,6 +337,7 @@ AliRun::~AliRun()
   delete fTreeH;
   delete fTreeE;
   delete fTreeR;
+  delete fTreeS;
   if (fModules) {
     fModules->Delete();
     delete fModules;
@@ -272,6 +348,7 @@ AliRun::~AliRun()
   }
   delete fHitLists;
   delete fPDGDB;
+  delete fMCQA;
 }
 
 //_____________________________________________________________________________
@@ -307,12 +384,14 @@ void AliRun::Browse(TBrowser *b)
   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());
   }
+  b->Add(fMCQA,"AliMCQA");
 }
 
 //_____________________________________________________________________________
@@ -359,12 +438,12 @@ void AliRun::CleanParents()
   // Clean Particles stack.
   // Set parent/daughter relations
   //
-  TClonesArray &particles = *(gAlice->Particles());
+  TObjArray &particles = *fParticleMap;
   TParticle *part;
   int i;
-  for(i=0; i<fNtrack; i++) {
-    part = (TParticle *)particles.UncheckedAt(i);
-    if(!part->TestBit(kDaughtersBit)) {
+  for(i=0; i<fHgwmk+1; i++) {
+    part = (TParticle *)particles.At(i);
+    if(part) if(!part->TestBit(kDaughtersBit)) {
       part->SetFirstDaughter(-1);
       part->SetLastDaughter(-1);
     }
@@ -387,8 +466,7 @@ void AliRun::DumpPart (Int_t i) const
   //
   // Dumps particle i in the stack
   //
-  TClonesArray &particles = *fParticles;
-  ((TParticle*) particles[i])->Print();
+  ((TParticle*) (*fParticleMap)[i])->Print();
 }
 
 //_____________________________________________________________________________
@@ -397,7 +475,7 @@ void AliRun::DumpPStack () const
   //
   // Dumps the particle stack
   //
-  TClonesArray &particles = *fParticles;
+  TObjArray &particles = *fParticleMap;
   printf(
         "\n\n=======================================================================\n");
   for (Int_t i=0;i<fNtrack;i++) 
@@ -409,6 +487,13 @@ void AliRun::DumpPStack () const
         "\n=======================================================================\n\n");
 }
 
+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)
@@ -422,38 +507,44 @@ void AliRun::SetField(Int_t type, Int_t version, Float_t scale,
 
   //
   // --- Sanity check on mag field flags
-  if(type<0 || type > 2) {
-    Warning("SetField",
-           "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);
+    fField = new AliMagFC("Map1"," ",type,scale,maxField);
   } else if(version<=2) {
-    fField = new AliMagFCM("Map2-3",filename,type,version,scale,maxField);
+    fField = new AliMagFCM("Map2-3",filename,type,scale,maxField);
     fField->ReadField();
   } else if(version==3) {
-    fField = new AliMagFDM("Map4",filename,type,version,scale,maxField);
+    fField = new AliMagFDM("Map4",filename,type,scale,maxField);
     fField->ReadField();
   } else {
     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::FillTree()
+void AliRun::PostTrack()
 {
-  //
-  // Fills all AliRun TTrees
-  //
-  if (fTreeK) fTreeK->Fill();
-  if (fTreeH) fTreeH->Fill();
-  if (fTreeD) fTreeD->Fill();
-  if (fTreeR) fTreeR->Fill();
+     TObjArray &dets = *fModules;
+     AliModule *module;
+
+     for(Int_t i=0; i<=fNdets; i++)
+       if((module = (AliModule*)dets[i]))
+        module->PostTrack();
 }
+
 //_____________________________________________________________________________
 void AliRun::FinishPrimary()
 {
@@ -508,15 +599,48 @@ void AliRun::FinishEvent()
   // Write out the kinematics
   if (fTreeK) {
     CleanParents();
-    fTreeK->Fill();
+    if(fTreeK->GetEntries() ==0) {
+      // set the fParticleFileMap size for the first time
+      if (fHgwmk+1 > fParticleFileMap.GetSize())
+      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();
@@ -529,17 +653,12 @@ void AliRun::FinishEvent()
   ResetStack();
   
   // Write Tree headers
-  //  Int_t ievent = fHeader.GetEvent();
-  //  char hname[30];
-  //  sprintf(hname,"TreeK%d",ievent);
   if (fTreeK) fTreeK->Write(0,TObject::kOverwrite);
-  //  sprintf(hname,"TreeH%d",ievent);
   if (fTreeH) fTreeH->Write(0,TObject::kOverwrite);
-  //  sprintf(hname,"TreeD%d",ievent);
   if (fTreeD) fTreeD->Write(0,TObject::kOverwrite);
-  //  sprintf(hname,"TreeR%d",ievent);
   if (fTreeR) fTreeR->Write(0,TObject::kOverwrite);
-
+  if (fTreeS) fTreeS->Write(0,TObject::kOverwrite);
+  
   ++fEvent;
 }
 
@@ -562,20 +681,16 @@ void AliRun::FinishRun()
   
   //Output energy summary tables
   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);
-  }
+
+  TFile *file = fTreeE->GetCurrentFile();
+
   file->cd();
+  
   fTreeE->Write(0,TObject::kOverwrite);
   
+  // Write AliRun info and all detectors parameters
+  Write(0,TObject::kOverwrite);
+  
   // Clean tree information
   if (fTreeK) {
     delete fTreeK; fTreeK = 0;
@@ -592,10 +707,7 @@ void AliRun::FinishRun()
   if (fTreeE) {
     delete fTreeE; fTreeE = 0;
   }
-  
-  // Write AliRun info and all detectors parameters
-  Write();
-  
+    
   // Close output file
   file->Write();
 }
@@ -611,7 +723,7 @@ void AliRun::FlagTrack(Int_t track)
 
   curr=track;
   while(1) {
-    particle=(TParticle*)fParticles->UncheckedAt(curr);
+    particle=(TParticle*)fParticleMap->At(curr);
     
     // If the particle is flagged the three from here upward is saved already
     if(particle->TestBit(kKeepBit)) return;
@@ -729,27 +841,42 @@ Int_t AliRun::GetEvent(Int_t event)
   //
 
   // Reset existing structures
-  ResetStack();
+  //  ResetStack();
   ResetHits();
   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", &fParticles);
+  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);
@@ -757,13 +884,25 @@ Int_t AliRun::GetEvent(Int_t event)
     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);
+    // Warning("GetEvent","cannot find Digits Tree for event:%d\n",event);
   }
-  
+
+  file->cd();
+
+  // 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);
+  }
+
+  file->cd();
   
   // Get Reconstruct Tree header from file
   sprintf(treeName,"TreeR%d",event);
@@ -771,6 +910,8 @@ Int_t AliRun::GetEvent(Int_t event)
   if (!fTreeR) {
     //    printf("WARNING: cannot find Reconstructed Tree for event:%d\n",event);
   }
+
+  file->cd();
  
   // Set Trees branch addresses
   TIter next(fModules);
@@ -779,8 +920,7 @@ Int_t AliRun::GetEvent(Int_t event)
     detector->SetTreeAddress();
   }
   
-  if (fTreeK) fTreeK->GetEvent(0);
-  fNtrack = Int_t (fParticles->GetEntries());
+  fNtrack = Int_t (fTreeK->GetEntries());
   return fNtrack;
 }
 
@@ -800,7 +940,6 @@ TGeometry *AliRun::GetGeometry()
   TIter next(fModules);
   AliModule *detector;
   while((detector = (AliModule*)next())) {
-    detector->SetTreeAddress();
     TList *dnodes=detector->Nodes();
     Int_t j;
     TNode *node, *node1;
@@ -826,10 +965,10 @@ void AliRun::GetNextTrack(Int_t &mtrack, Int_t &ipart, Float_t *pmom,
   fCurrent=-1;
   TParticle *track;
   for(Int_t i=fNtrack-1; i>=0; i--) {
-    track=(TParticle*) fParticles->UncheckedAt(i);
-    if(!track->TestBit(kDoneBit)) {
+    track=(TParticle*) fParticleMap->At(i);
+    if(track) if(!track->TestBit(kDoneBit)) {
       //
-      // The track has not yet been processed
+      // The track exists and has not yet been processed
       fCurrent=i;
       ipart=track->GetPdgCode();
       pmom[0]=track->Px();
@@ -855,7 +994,7 @@ void AliRun::GetNextTrack(Int_t &mtrack, Int_t &ipart, Float_t *pmom,
   if (fCurrent >= nprimaries) return;
   if (fCurrent < nprimaries-1) {
     fTimer.Stop();
-    track=(TParticle*) fParticles->UncheckedAt(fCurrent+1);
+    track=(TParticle*) fParticleMap->At(fCurrent+1);
     //    track->SetProcessTime(fTimer.CpuTime());
   }
   fTimer.Start();
@@ -873,7 +1012,7 @@ Int_t AliRun::GetPrimary(Int_t track) const
   parent=track;
   while (1) {
     current=parent;
-    part = (TParticle *)fParticles->UncheckedAt(current);
+    part = (TParticle *)fParticleMap->At(current);
     parent=part->GetFirstMother();
     if(parent<0) return current;
   }
@@ -890,10 +1029,11 @@ void AliRun::InitMC(const char *setup)
     Warning("Init","Cannot initialise AliRun twice!\n");
     return;
   }
-
+    
   gROOT->LoadMacro(setup);
   gInterpreter->ProcessLine(fConfigFunction.Data());
 
+
   gMC->DefineParticles();  //Create standard MC particles
 
   TObject *objfirst, *objlast;
@@ -904,6 +1044,9 @@ void AliRun::InitMC(const char *setup)
   //=================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())) {
@@ -918,7 +1061,7 @@ void AliRun::InitMC(const char *setup)
        objfirst = gDirectory->GetList()->After(objfirst);
       }
    }
-   SetTransPar(); //Read the cuts for all materials
+   ReadTransPar(); //Read the cuts for all materials
    
    MediaTable(); //Build the special IMEDIA table
    
@@ -935,6 +1078,8 @@ void AliRun::InitMC(const char *setup)
    
    fInitDone = kTRUE;
 
+   fMCQA = new AliMCQA(fNdets);
+
    //
    // Save stuff at the beginning of the file to avoid file corruption
    Write();
@@ -1023,7 +1168,19 @@ void AliRun::ResetGenerator(AliGenerator *generator)
 }
 
 //____________________________________________________________________________
-void AliRun::SetTransPar(char* filename)
+void AliRun::SetTransPar(char *filename)
+{
+  fTransParName = filename;
+}
+
+//____________________________________________________________________________
+void AliRun::SetBaseFile(char *filename)
+{
+  fBaseFileName = filename;
+}
+
+//____________________________________________________________________________
+void AliRun::ReadTransPar()
 {
   //
   // Read filename to set the transport parameters
@@ -1046,11 +1203,11 @@ void AliRun::SetTransPar(char* filename)
   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) {
-    Warning("SetTransPar","File %s does not exist!\n",filename);
+    Warning("ReadTransPar","File %s does not exist!\n",fTransParName.Data());
     return;
   }
   //
@@ -1086,7 +1243,7 @@ void AliRun::SetTransPar(char* filename)
     if(!iret) continue;
     if(iret<0) {
       //reading error
-      Warning("SetTransPar","Error reading file %s\n",filename);
+      Warning("ReadTransPar","Error reading file %s\n",fTransParName.Data());
       continue;
     }
     // Check that the module exist
@@ -1098,7 +1255,7 @@ void AliRun::SetTransPar(char* filename)
       if(0<=itmed && itmed < 100) {
        ktmed=idtmed[itmed];
        if(!ktmed) {
-         Warning("SetTransPar","Invalid tracking medium code %d for %s\n",itmed,mod->GetName());
+         Warning("ReadTransPar","Invalid tracking medium code %d for %s\n",itmed,mod->GetName());
          continue;
        }
        // Set energy thresholds
@@ -1118,18 +1275,69 @@ void AliRun::SetTransPar(char* filename)
          }
        }
       } else {
-       Warning("SetTransPar","Invalid medium code %d *\n",itmed);
+       Warning("ReadTransPar","Invalid medium code %d *\n",itmed);
        continue;
       }
     } else {
-      Warning("SetTransPar","Module %s not present\n",detName);
+      Warning("ReadTransPar","Module %s not present\n",detName);
       continue;
     }
   }
 }
 
 //_____________________________________________________________________________
-void AliRun::MakeTree(Option_t *option)
+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)
 {
   //
   //  Create the ROOT trees
@@ -1144,12 +1352,15 @@ void AliRun::MakeTree(Option_t *option)
   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
-    fTreeK->Branch("Particles",&fParticles,4000);
+    MakeBranchInTree(fTreeK, 
+                     "Particles", "TParticle", &fParticleBuffer, 4000, 1, file) ;
     fTreeK->Write();
   }
   if (oH && !fTreeH) {
@@ -1163,6 +1374,11 @@ void AliRun::MakeTree(Option_t *option)
     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");
@@ -1171,9 +1387,11 @@ void AliRun::MakeTree(Option_t *option)
   if (oE && !fTreeE) {
     fTreeE = new TTree("TE","Header");
     //  Create a branch for Header
-    fTreeE->Branch("Header","AliHeader",&gAliHeader,4000);
+    MakeBranchInTree(fTreeE, 
+                     "Header", "AliHeader", &gAliHeader, 4000, 1, file) ;
     fTreeE->Write();
   }
+  
   //
   // Create a branch for hits/digits for each detector
   // Each branch is a TClonesArray. Each data member of the Hits classes
@@ -1181,7 +1399,7 @@ void AliRun::MakeTree(Option_t *option)
   TIter next(fModules);
   AliModule *detector;
   while((detector = (AliModule*)next())) {
-     if (oH || oD || oR) detector->MakeBranch(option);
+     if (oH) detector->MakeBranch(option,file);
   }
 }
 
@@ -1197,6 +1415,35 @@ Int_t AliRun::PurifyKine(Int_t lastSavedTrack, Int_t nofTracks)
   return fHgwmk;
 }
 
+//_____________________________________________________________________________
+TParticle* AliRun::Particle(Int_t i)
+{
+  if(!(*fParticleMap)[i]) {
+    Int_t nentries = fParticles->GetEntries();
+    
+    // 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()
 {
@@ -1204,59 +1451,67 @@ void AliRun::PurifyKine()
   // Compress kinematic tree keeping only flagged particles
   // and renaming the particle id's in all the hits
   //
-  TClonesArray &particles = *fParticles;
+  //  TClonesArray &particles = *fParticles;
+  TObjArray &particles = *fParticleMap;
   int nkeep=fHgwmk+1, parent, i;
-  TParticle *part, *partnew, *father;
-  int *map = new int[particles.GetEntries()];
+  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;
+
   // 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;
-    ((TParticle *)particles.UncheckedAt(i))->ResetBit(kDaughtersBit);
+    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++) {
-    part = (TParticle *)particles.UncheckedAt(i);
-    if(part->TestBit(kKeepBit)) {
+    if(particles.At(i)->TestBit(kKeepBit)) {
       
       // This particle has to be kept
       map[i]=nkeep;
-      if(i!=nkeep) {
-       
-       // Old and new are different, have to copy
-       partnew = (TParticle *)particles.UncheckedAt(nkeep);
-       // Change due to a bug in the HP compiler
-       //      *partnew = *part;
-       memcpy(partnew,part,sizeof(TParticle));
-      } else partnew = part;
+      // 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=partnew->GetFirstMother())>fHgwmk) {
-       if(map[parent]==-99) printf("map[%d] = -99!\n",parent);
-       partnew->SetFirstMother(map[parent]);
-      }
+      if((parent=part->GetFirstMother())>fHgwmk) 
+       if(map[parent]==-99) Fatal("PurifyKine","map[%d] = -99!\n",parent);
+       else part->SetFirstMother(map[parent]);
+
       nkeep++;
     }
   }
-  fNtrack=nkeep;
   
   // Fix daughters information
-  for (i=0; i<fNtrack; i++) {
-    part = (TParticle *)particles.UncheckedAt(i);
+  for (i=fHgwmk+1; i<nkeep; i++) {
+    part = (TParticle *)particles.At(i);
     parent = part->GetFirstMother();
     if(parent>=0) {
-      father = (TParticle *)particles.UncheckedAt(parent);
+      father = (TParticle *)particles.At(parent);
       if(father->TestBit(kDaughtersBit)) {
       
        if(i<father->GetFirstDaughter()) father->SetFirstDaughter(i);
        if(i>father->GetLastDaughter())  father->SetLastDaughter(i);
       } else {
-       // Iitialise daughters info for first pass
+       // Initialise daughters info for first pass
        father->SetFirstDaughter(i);
        father->SetLastDaughter(i);
        father->SetBit(kDaughtersBit);
@@ -1264,24 +1519,6 @@ void AliRun::PurifyKine()
     }
   }
   
-#ifdef old
-  // Now loop on all detectors and reset the hits
-  AliHit *OneHit;
-  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()]);
-    }
-  }
-#else
-
   // Now loop on all registered hit lists
   TIter next(fHitLists);
   TCollection *hitList;
@@ -1292,7 +1529,6 @@ void AliRun::PurifyKine()
       hit->SetTrack(map[hit->GetTrack()]);
     }
   }
-#endif
 
   // 
   // This for detectors which have a special mapping mechanism
@@ -1302,13 +1538,28 @@ void AliRun::PurifyKine()
    TIter nextmod(fModules);
    AliModule *detector;
    while((detector = (AliModule*)nextmod())) {
-     detector->RemapTrackHitIDs(map);
+     detector->RemapTrackHitIDs(map.GetArray());
    }
   
+   // 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;
+   }
+
+   for (i=nkeep; i<fNtrack; ++i) particles[i]=0;
 
-  fHgwmk=nkeep-1;
-  particles.SetLast(fHgwmk);
-  delete [] map;
+   fLoadPoint-=toshrink;
+   for(i=fLoadPoint; i<fLoadPoint+toshrink; ++i) fParticles->RemoveAt(i);
+
+   fNtrack=nkeep;
+   fHgwmk=nkeep-1;
+   //   delete [] map;
 }
 
 //_____________________________________________________________________________
@@ -1330,6 +1581,7 @@ void AliRun::BeginEvent()
   ResetStack();
   ResetHits();
   ResetDigits();
+  ResetSDigits();
 
   // Initialise event header
   fHeader.Reset(fRun,fEvent);
@@ -1349,13 +1601,17 @@ void AliRun::BeginEvent()
     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);
   }
 }
-
 //_____________________________________________________________________________
 void AliRun::ResetDigits()
 {
@@ -1369,6 +1625,19 @@ void AliRun::ResetDigits()
   }
 }
 
+//_____________________________________________________________________________
+void AliRun::ResetSDigits()
+{
+  //
+  //  Reset all Detectors digits
+  //
+  TIter next(fModules);
+  AliModule *detector;
+  while((detector = (AliModule*)next())) {
+     detector->ResetSDigits();
+  }
+}
+
 //_____________________________________________________________________________
 void AliRun::ResetHits()
 {
@@ -1410,7 +1679,15 @@ void AliRun::RunMC(Int_t nevent, const char *setup)
   if (!fInitDone) InitMC(setup);
   
   // Create the Root Tree with one branch per detector
-  MakeTree("KHDER");
+
+   MakeTree("ESD");
+
+  if (gSystem->Getenv("CONFIG_SPLIT_FILE")) {
+     MakeTree("K","Kine.root");
+     MakeTree("H","Hits.root");
+  } else {
+     MakeTree("KH");
+  }
 
   gMC->ProcessRun(nevent);
 
@@ -1419,9 +1696,102 @@ void AliRun::RunMC(Int_t nevent, const char *setup)
 }
 
 //_____________________________________________________________________________
-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 *detector)
+{
+  //
+  // Main function to be called to reconstruct Alice event
+  // 
+
+   MakeTree("R");
+   Digits2Reco(detector);
+}
+
+//_____________________________________________________________________________
+
+void AliRun::Hits2Digits(const char *selected)
+{
+   // Convert Hits to sumable digits
+   // 
+   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). 
+
+
+   char *oS = strstr(option,"S");
+   char *oD = strstr(option,"D");
+   char *oR = strstr(option,"R");
+   
+   gAlice->GetEvent(0);
+
+   TObjArray *detectors = gAlice->Detectors();
+
+   TIter next(detectors);
+
+   AliDetector *detector = 0;
+
+   TDirectory *cwd = gDirectory;
+
+   char outFile[32];
+   
+   while((detector = (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);
+       }
+       
+       cwd->cd(); 
+
+       if (oS) 
+          detector->Hits2SDigits(); 
+       if (oD) 
+          detector->SDigits2Digits(); 
+       if (oR) 
+          detector->Digits2Reco(); 
+
+       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)
 {
   //
   // Generates lego plots of:
@@ -1463,30 +1833,39 @@ void AliRun::RunLego(const char *setup,Int_t ntheta,Float_t themin,
 
   // check if initialisation has been done
   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);
+  
+  
   //Create Lego object  
-  fLego = new AliLego("lego",ntheta,themin,themax,nphi,phimin,phimax,rmin,rmax,zmax);
+  fLego = new AliLego("lego",gener);
 
   //Prepare MC for Lego Run
   gMC->InitLego();
   
   //Run Lego Object
-  gMC->ProcessRun(ntheta*nphi+1);
+
+  gMC->ProcessRun(nc1*nc2+1);
   
   // Create only the Root event Tree
   MakeTree("E");
   
   // End of this run, close files
   FinishRun();
-
+  // Restore current generator
+  ResetGenerator(gen);
   // Delete Lego Object
   delete fLego; fLego=0;
-
-  // Restore current generator
-  SetGenerator(gen);
 }
 
 //_____________________________________________________________________________
@@ -1511,7 +1890,7 @@ void AliRun::SetCurrentTrack(Int_t 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,
-                     const char* /* mecha */, Int_t &ntr, Float_t weight)
+                     AliMCProcess mech, Int_t &ntr, Float_t weight)
 { 
   //
   // Load a track on the stack
@@ -1548,20 +1927,104 @@ void AliRun::SetTrack(Int_t done, Int_t parent, Int_t pdg, Float_t *pmom,
   
   //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[fNtrack]) TParticle(pdg,kS,parent,-1,kfirstdaughter,
+
+  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);
-  //                                        polar[0],polar[1],polar[2],tof,
-  //                                        mecha,weight);
-  ((TParticle*)particles[fNtrack])->SetPolarisation(TVector3(polar[0],polar[1],polar[2]));
-  ((TParticle*)particles[fNtrack])->SetWeight(weight);
+  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
-  ((TParticle*)particles[fNtrack])->SetBit(kDaughtersBit);
+  //  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);
+*/        
+}
+
+//_____________________________________________________________________________
+void AliRun::SetTrack(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)
+{ 
+  //
+  // 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*) fParticles->UncheckedAt(parent);
+    particle=(TParticle*) fParticleMap->At(parent);
     particle->SetLastDaughter(fNtrack);
     if(particle->GetFirstDaughter()<0) particle->SetFirstDaughter(fNtrack);
   } else { 
@@ -1576,14 +2039,25 @@ void AliRun::SetTrack(Int_t done, Int_t parent, Int_t pdg, Float_t *pmom,
   ntr = fNtrack++;
 }
 
+//_____________________________________________________________________________
+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);
+}
+
 //_____________________________________________________________________________
 void AliRun::KeepTrack(const Int_t track)
 { 
   //
   // flags a track to be kept
   //
-  TClonesArray &particles = *fParticles;
-  ((TParticle*)particles[track])->SetBit(kKeepBit);
+  fParticleMap->At(track)->SetBit(kKeepBit);
 }
  
 //_____________________________________________________________________________
@@ -1604,64 +2078,33 @@ void AliRun::StepManager(Int_t id)
   
     //Call the appropriate stepping routine;
     AliModule *det = (AliModule*)fModules->At(id);
-    if(det) det->StepManager();
+    if(det) {
+      fMCQA->StepManager(id);
+      det->StepManager();
+    }
   }
 }
 
 //_____________________________________________________________________________
 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;
-    gROOT->GetListOfBrowsables()->Add(this,"Run");
-    fTreeE = (TTree*)gDirectory->Get("TE");
-    if (fTreeE) fTreeE->SetBranchAddress("Header", &gAliHeader);
-    else    Error("Streamer","cannot find Header Tree\n");
-    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;
-    if(R__v>1) {
-      R__b >> fPDGDB;        //Particle factory object!
+   // 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");
+
+      fTreeE = (TTree*)gDirectory->Get("TE");
+      if (fTreeE) fTreeE->SetBranchAddress("Header", &gAliHeader);
+      else    Error("Streamer","cannot find Header Tree\n");
       fTreeE->GetEntry(0);
-    } else {
-      fHeader.SetEvent(0);
-      fPDGDB     = TDatabasePDG::Instance();        //Particle factory object!
-    }
-    if(R__v>2) {
-      fConfigFunction.Streamer(R__b);
-    } else {
-      fConfigFunction="Config();";
-    }
-  } 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;
-    R__b << fPDGDB;        //Particle factory object!
-    fConfigFunction.Streamer(R__b);
-  }
-} 
+
+      gRandom = fRandom;
+   } else {
+      AliRun::Class()->WriteBuffer(R__b, this);
+   }
+}
+