]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - STEER/AliStack.cxx
Coding Convention Violations
[u/mrichter/AliRoot.git] / STEER / AliStack.cxx
index 3a5449b47eb4444616b64eb93940f73a1ab14d84..8b5128b5d64dfe961b25bbbe509905817bf4f85c 100644 (file)
  * provided "as is" without express or implied warranty.                  *
  **************************************************************************/
 
-/*
-$Log$
-Revision 1.24  2002/10/22 15:02:15  alibrary
-Introducing Riostream.h
-
-Revision 1.23  2002/10/14 14:57:32  hristov
-Merging the VirtualMC branch to the main development branch (HEAD)
-
-Revision 1.19.4.2  2002/08/28 15:06:52  alibrary
-Updating to v3-09-01
-
-Revision 1.19.4.1  2002/06/10 14:43:06  hristov
-Merged with v3-08-02
-
-Revision 1.21  2002/05/28 14:24:57  hristov
-Correct warning messages
-
-Revision 1.20  2002/04/30 11:47:30  morsch
-KeepPhysics method called by PurifyKine added (N. Carrer, A.M.)
-
-Revision 1.19  2002/03/12 11:06:03  morsch
-Add particle status code to argument list of SetTrack(..).
-
-Revision 1.18  2002/02/20 16:14:41  hristov
-fParticleBuffer points to object which doesn't belong to AliStack, do not delete it (J.Chudoba)
-
-Revision 1.17  2001/12/05 08:51:56  hristov
-The default constructor now creates no objects (thanks to r.Brun). Some corrections required by the previous changes.
-
-Revision 1.16  2001/11/20 09:27:55  hristov
-Possibility to investigate a primary of not yet loaded particle (I.Hrivnacova)
-
-Revision 1.15  2001/09/04 15:10:37  hristov
-Additional protection is included to avoid some problems using Hijing
-
-Revision 1.14  2001/08/30 09:44:06  hristov
-VertexSource_t added to avoid the warnings
-
-Revision 1.13  2001/08/29 13:31:42  morsch
-Protection against (fTreeK == 0) in destructor.
-
-Revision 1.12  2001/07/27 13:03:13  hristov
-Default Branch split level set to 99
-
-Revision 1.11  2001/07/27 12:34:20  jchudoba
-remove the dummy argument in GetEvent method
-
-Revision 1.10  2001/07/20 10:13:54  morsch
-In Particle(Int_t) use GetEntriesFast to speed up the procedure.
-
-Revision 1.9  2001/07/03 08:10:57  hristov
-J.Chudoba's changes merged correctly with the HEAD
-
-Revision 1.6  2001/05/31 06:59:06  fca
-Clean setting and deleting of fParticleBuffer
-
-Revision 1.5  2001/05/30 12:18:46  hristov
-Loop variables declared once
-
-Revision 1.4  2001/05/25 07:25:20  hristov
-AliStack destructor corrected (I.Hrivnacova)
-
-Revision 1.3  2001/05/22 14:33:16  hristov
-Minor changes
-
-Revision 1.2  2001/05/17 05:49:39  fca
-Reset pointers to daughters
-
-Revision 1.1  2001/05/16 14:57:22  alibrary
-New files for folders and Stack
-
-*/
+/* $Id$ */
 
 ///////////////////////////////////////////////////////////////////////////////
 //                                                                           //
-//  Particles stack class
+//  Particles stack class                                                    //
+//  Implements the TMCVirtualStack of the Virtual Monte Carlo                //
+//  Holds the particles transported during simulation                        //
+//  Is used to compare results of reconstruction with simulation             //
+//  Author A.Morsch                                                          //
 //                                                                           //
 ///////////////////////////////////////////////////////////////////////////////
 
-#include <Riostream.h>
  
 #include <TObjArray.h>
 #include <TParticle.h>
+#include <TParticlePDG.h>
 #include <TTree.h>
-#include <TFile.h>
-#include <TFolder.h>
-#include <TROOT.h>
 
-#include "AliStack.h"
-#include "AliRun.h"
-#include "AliModule.h"
 #include "AliHit.h"
+#include "AliModule.h"
+#include "AliRun.h"
+#include "AliMC.h"
+#include "AliRunLoader.h"
+#include "AliStack.h"
 
 ClassImp(AliStack)
 
-//_____________________________________________________________________________
-AliStack::AliStack(Int_t size)
-  : TVirtualMCStack()
+//_______________________________________________________________________
+AliStack::AliStack():
+  fParticles(0),
+  fParticleMap(0),
+  fParticleFileMap(0),
+  fParticleBuffer(0),
+  fTreeK(0),
+  fNtrack(0),
+  fNprimary(0),
+  fCurrent(-1),
+  fCurrentPrimary(-1),
+  fHgwmk(0),
+  fLoadPoint(0),
+  fEventFolderName(AliConfig::GetDefaultEventFolderName())
 {
   //
-  //  Constructor
+  // Default constructor
   //
-  
-  // Create the particles arrays 
-  fParticles      = new TClonesArray("TParticle",1000);
-  fParticleMap    = new TObjArray(size);
-  fParticleBuffer = 0;
-  fNtrack         = 0;
-  fNprimary       = 0;
-  fCurrent        = -1;
-  fCurrentPrimary = -1;
-  fTreeK          = 0;
 }
 
+//_______________________________________________________________________
+AliStack::AliStack(Int_t size, const char* evfoldname):
+  fParticles(new TClonesArray("TParticle",1000)),
+  fParticleMap(new TObjArray(size)),
+  fParticleFileMap(0),
+  fParticleBuffer(0),
+  fTreeK(0),
+  fNtrack(0),
+  fNprimary(0),
+  fCurrent(-1),
+  fCurrentPrimary(-1),
+  fHgwmk(0),
+  fLoadPoint(0),
+  fEventFolderName(evfoldname)
+{
+  //
+  //  Constructor
+  //
+}
 
-//_____________________________________________________________________________
-AliStack::AliStack()
-  : TVirtualMCStack()
+//_______________________________________________________________________
+AliStack::AliStack(const AliStack& st):
+  TVirtualMCStack(st),
+  fParticles(0),
+  fParticleMap(0),
+  fParticleFileMap(0),
+  fParticleBuffer(0),
+  fTreeK(0),
+  fNtrack(0),
+  fNprimary(0),
+  fCurrent(-1),
+  fCurrentPrimary(-1),
+  fHgwmk(0),
+  fLoadPoint(0)
 {
   //
-  //  Default constructor
+  // Copy constructor
   //
-  
-  // Create the particles arrays 
-  fParticles      = 0;
-  fParticleMap    = 0;
-  fParticleBuffer = 0;
-  fNtrack         = 0;
-  fCurrent        = -1;
-  fNprimary       = 0;
-  fCurrentPrimary = -1;
-  fTreeK          = 0;
+  st.Copy(*this);
 }
 
+//_______________________________________________________________________
+void AliStack::Copy(TObject&) const
+{
+  Fatal("Copy","Not implemented!\n");
+}
 
-//_____________________________________________________________________________
+//_______________________________________________________________________
 AliStack::~AliStack()
 {
   //
@@ -160,7 +119,7 @@ AliStack::~AliStack()
     delete fParticles;
   }
   delete fParticleMap;
-  if (fTreeK) delete fTreeK;
+  //PH???  delete fTreeK;
 }
 
 //
@@ -168,9 +127,9 @@ AliStack::~AliStack()
 //
 
 //_____________________________________________________________________________
-void AliStack::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, Int_t is)
+void AliStack::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
@@ -196,25 +155,31 @@ void AliStack::SetTrack(Int_t done, Int_t parent, Int_t pdg, Float_t *pmom,
   // 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]);
-  
+    TParticlePDG* pmc =  TDatabasePDG::Instance()->GetParticle(pdg);
+    if (pmc) {
+       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]);
+       
 //    printf("Loading  mass %f ene %f No %d ip %d parent %d done %d pos %f %f %f mom %f %f %f kS %d m \n",
 //        mass,e,fNtrack,pdg,parent,done,vpos[0],vpos[1],vpos[2],pmom[0],pmom[1],pmom[2],kS);
   
 
-  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, is);
+       PushTrack(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, is);
+    } else {
+       Warning("PushTrack", "Particle type %d not defined in PDG Database !\n", pdg);
+       Warning("PushTrack", "Particle skipped !\n");
+    }
 }
 
 //_____________________________________________________________________________
-void AliStack::SetTrack(Int_t done, Int_t parent, Int_t pdg,
+void AliStack::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, Double_t weight, Int_t is)
+                     TMCProcess mech, Int_t &ntr, Double_t weight, Int_t is)
 { 
   //
   // Load a track on the stack
@@ -259,13 +224,13 @@ void AliStack::SetTrack(Int_t done, Int_t parent, Int_t pdg,
   fParticleMap->AddAtAndExpand(particle, fNtrack);//CHECK!!
 
   if(parent>=0) {
-    particle = (TParticle*) fParticleMap->At(parent);
+    particle = dynamic_cast<TParticle*>(fParticleMap->At(parent));
     if (particle) {
       particle->SetLastDaughter(fNtrack);
       if(particle->GetFirstDaughter()<0) particle->SetFirstDaughter(fNtrack);
     }
     else {
-      printf("Error in AliStack::SetTrack: Parent %d does not exist\n",parent);
+      printf("Error in AliStack::PushTrack: Parent %d does not exist\n",parent);
     }
   } 
   else { 
@@ -281,7 +246,7 @@ void AliStack::SetTrack(Int_t done, Int_t parent, Int_t pdg,
 }
 
 //_____________________________________________________________________________
-TParticle*  AliStack::GetNextTrack(Int_t& itrack)
+TParticle*  AliStack::PopNextTrack(Int_t& itrack)
 {
   //
   // Returns next track from stack of particles
@@ -294,64 +259,15 @@ TParticle*  AliStack::GetNextTrack(Int_t& itrack)
     itrack = fCurrent;
     track->SetBit(kDoneBit);
   }
-  else 
+  else
     itrack = -1;
-
-  return track;
-}
-
-/*
-//_____________________________________________________________________________
-void  AliStack::GetNextTrack(Int_t& itrack, 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) 
-{
-  //
-  // Return next track from stack of particles
-  //
   
-
-  TParticle* track = GetNextParticle();
-//    cout << "GetNextTrack():" << fCurrent << fNprimary << endl;
-
-  if (track) {
-    itrack = fCurrent;
-    pdg = track->GetPdgCode();
-    px = track->Px();
-    py = track->Py(); 
-    pz = track->Pz();
-    e  = track->Energy();
-    vx = track->Vx();
-    vy = track->Vy();
-    vz = track->Vz();
-    tof = track->T();
-    TVector3 pol;
-    track->GetPolarisation(pol);
-    polx = pol.X();
-    poly = pol.Y();
-    polz = pol.Z();
-    track->SetBit(kDoneBit);
-//      cout << "Filled params" << endl;
-  }
-  else 
-    itrack = -1;
-
-  //
-  // stop and start timer when we start a primary track
-  Int_t nprimaries = fNprimary;
-  if (fCurrent >= nprimaries) return;
-  if (fCurrent < nprimaries-1) { 
-    fTimer.Stop();
-    track=(TParticle*) fParticleMap->At(fCurrent+1);
-    //    track->SetProcessTime(fTimer.CpuTime());
-  }
-  fTimer.Start();
+  fCurrentTrack = track;
+  return track;
 }
 
-*/
 //_____________________________________________________________________________
-TParticle*  AliStack::GetPrimaryForTracking(Int_t i)
+TParticle*  AliStack::PopPrimaryForTracking(Int_t i)
 {
   //
   // Returns i-th primary particle if it is flagged to be tracked,
@@ -366,7 +282,6 @@ TParticle*  AliStack::GetPrimaryForTracking(Int_t i)
     return 0;
 }      
 
-
 //_____________________________________________________________________________
 void AliStack::PurifyKine()
 {
@@ -391,10 +306,10 @@ void AliStack::PurifyKine()
     if(i<=fHgwmk) map[i]=i ; 
     else {
       map[i] = -99;
-      if((part=(TParticle*) particles.At(i))) {
+      if((part=dynamic_cast<TParticle*>(particles.At(i)))) {
 //
 //        Check of this track should be kept for physics reasons 
-         if (KeepPhysics(part)) KeepTrack(i);
+          if (KeepPhysics(part)) KeepTrack(i);
 //
           part->ResetBit(kDaughtersBit);
           part->SetFirstDaughter(-1);
@@ -405,7 +320,7 @@ void AliStack::PurifyKine()
   // 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);
+  part = dynamic_cast<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++) {
@@ -415,7 +330,7 @@ void AliStack::PurifyKine()
       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);
+      part = dynamic_cast<TParticle*>(particles.At(nkeep));
       
       // as the parent is always *before*, it must be already
       // in place. This is what we are checking anyway!
@@ -429,10 +344,10 @@ void AliStack::PurifyKine()
   
   // Fix daughters information
   for (i=fHgwmk+1; i<nkeep; i++) {
-    part = (TParticle *)particles.At(i);
+    part = dynamic_cast<TParticle*>(particles.At(i));
     parent = part->GetFirstMother();
     if(parent>=0) {
-      father = (TParticle *)particles.At(parent);
+      father = dynamic_cast<TParticle*>(particles.At(parent));
       if(father->TestBit(kDaughtersBit)) {
       
        if(i<father->GetFirstDaughter()) father->SetFirstDaughter(i);
@@ -447,13 +362,13 @@ void AliStack::PurifyKine()
   }
   
   // Now loop on all registered hit lists
-  TList* hitLists = gAlice->GetHitLists();
+  TList* hitLists = gAlice->GetMCApp()->GetHitLists();
   TIter next(hitLists);
   TCollection *hitList;
-  while((hitList = (TCollection*)next())) {
+  while((hitList = dynamic_cast<TCollection*>(next()))) {
     TIter nexthit(hitList);
     AliHit *hit;
-    while((hit = (AliHit*)nexthit())) {
+    while((hit = dynamic_cast<AliHit*>(nexthit()))) {
       hit->SetTrack(map[hit->GetTrack()]);
     }
   }
@@ -462,24 +377,26 @@ void AliStack::PurifyKine()
   // This for detectors which have a special mapping mechanism
   // for hits, such as TPC and TRD
   //
-
+  
    TObjArray* modules = gAlice->Modules();
    TIter nextmod(modules);
    AliModule *detector;
-   while((detector = (AliModule*)nextmod())) {
+   while((detector = dynamic_cast<AliModule*>(nextmod()))) {
      detector->RemapTrackHitIDs(map.GetArray());
      detector->RemapTrackReferencesIDs(map.GetArray());
    }
-  
+   //
+   gAlice->GetMCApp()->RemapTrackReferencesIDs(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();
+     fParticleBuffer = dynamic_cast<TParticle*>(particles.At(i));
+     fParticleFileMap[i]=static_cast<Int_t>(TreeK()->GetEntries());
+     TreeK()->Fill();
      particles[i]=fParticleBuffer=0;
-   }
+    }
 
    for (i=nkeep; i<fNtrack; ++i) particles[i]=0;
 
@@ -504,7 +421,7 @@ Bool_t AliStack::KeepPhysics(TParticle* part)
     //
     Int_t parent = part->GetFirstMother();
     if (parent >= 0 && parent <= fHgwmk) {
-       TParticle* father = (TParticle*) Particles()->At(parent);
+       TParticle* father = dynamic_cast<TParticle*>(Particles()->At(parent));
        Int_t kf = father->GetPdgCode();
        kf = TMath::Abs(kf);
        Int_t kfl = kf;
@@ -523,22 +440,21 @@ Bool_t AliStack::KeepPhysics(TParticle* part)
 //_____________________________________________________________________________
 void AliStack::FinishEvent()
 {
-  //
-  // Write out the kinematics that was not yet filled
-  //
+//
+// Write out the kinematics that was not yet filled
+//
   
-  // Update event header
+// Update event header
 
 
-  if (!fTreeK) {
+  if (!TreeK()) {
 //    Fatal("FinishEvent", "No kinematics tree is defined.");
 //    Don't panic this is a probably a lego run
       return;
-      
   }  
   
   CleanParents();
-  if(fTreeK->GetEntries() ==0) {
+  if(TreeK()->GetEntries() ==0) {
     // set the fParticleFileMap size for the first time
     fParticleFileMap.Set(fHgwmk+1);
   }
@@ -547,9 +463,9 @@ void AliStack::FinishEvent()
   TObject *part;
   for(Int_t i=0; i<fHgwmk+1; ++i) 
     if((part=fParticleMap->At(i))) {
-      fParticleBuffer = (TParticle*) part;
-      fParticleFileMap[i]= (Int_t) fTreeK->GetEntries();
-      fTreeK->Fill();
+      fParticleBuffer = dynamic_cast<TParticle*>(part);
+      fParticleFileMap[i]= static_cast<Int_t>(TreeK()->GetEntries());
+      TreeK()->Fill();
       //PH      (*fParticleMap)[i]=fParticleBuffer=0;      
       fParticleBuffer=0;      
       fParticleMap->AddAt(0,i);      
@@ -558,19 +474,18 @@ void AliStack::FinishEvent()
       // should be left => to be removed later.
       if (allFilled) printf("Why != 0 part # %d?\n",i);
     }
-    else {
+    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;
-    } 
-//    cout << "Nof particles: " << fNtrack << endl;
-  //Reset();   
+      // 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;
+     } 
 } 
-
 //_____________________________________________________________________________
+
 void AliStack::FlagTrack(Int_t track)
 {
   //
@@ -581,7 +496,7 @@ void AliStack::FlagTrack(Int_t track)
 
   Int_t curr=track;
   while(1) {
-    particle=(TParticle*)fParticleMap->At(curr);
+    particle=dynamic_cast<TParticle*>(fParticleMap->At(curr));
     
     // If the particle is flagged the three from here upward is saved already
     if(particle->TestBit(kKeepBit)) return;
@@ -610,12 +525,13 @@ void  AliStack::Reset(Int_t size)
   //
   // Resets stack
   //
-
+  
   fNtrack=0;
   fNprimary=0;
   fHgwmk=0;
   fLoadPoint=0;
   fCurrent = -1;
+  fTreeK = 0x0;
   ResetArrays(size);
 }
 
@@ -638,7 +554,7 @@ void  AliStack::ResetArrays(Int_t size)
 }
 
 //_____________________________________________________________________________
-void AliStack::SetHighWaterMark(Int_t nt)
+void AliStack::SetHighWaterMark(Int_t)
 {
   //
   // Set high water mark for last track in event
@@ -673,12 +589,12 @@ TParticle* AliStack::Particle(Int_t i)
        entry, fParticleFileMap[i]); 
     } 
       
-    fTreeK->GetEntry(entry);
+    TreeK()->GetEntry(entry);
     new ((*fParticles)[nentries]) TParticle(*fParticleBuffer);
     fParticleMap->AddAt((*fParticles)[nentries],i);
   }
-  //PH  return (TParticle *) (*fParticleMap)[i];
-  return (TParticle *) fParticleMap->At(i);
+  //PH  return dynamic_cast<TParticle *>((*fParticleMap)[i]);
+  return dynamic_cast<TParticle*>(fParticleMap->At(i));
 }
 
 //_____________________________________________________________________________
@@ -708,6 +624,23 @@ Int_t AliStack::TreeKEntry(Int_t id) const
   return entry;
 }
 
+//_____________________________________________________________________________
+Int_t AliStack::GetCurrentParentTrackNumber() const
+{
+  //
+  // Return number of the parent of the current track
+  //
+  
+  TParticle* current = (TParticle*)fParticleMap->At(fCurrent);
+
+  if (current) 
+    return current->GetFirstMother();
+  else {
+    Warning("GetCurrentParentTrackNumber", "Current track not found in the stack");
+    return -1;
+  }  
+}
 //_____________________________________________________________________________
 Int_t AliStack::GetPrimary(Int_t id)
 {
@@ -732,8 +665,8 @@ void AliStack::DumpPart (Int_t i) const
   // Dumps particle i in the stack
   //
   
-  //PH  ((TParticle*) (*fParticleMap)[i])->Print();
-  ((TParticle*) fParticleMap->At(i))->Print();
+  //PH  dynamic_cast<TParticle*>((*fParticleMap)[i])->Print();
+  dynamic_cast<TParticle*>(fParticleMap->At(i))->Print();
 }
 
 //_____________________________________________________________________________
@@ -745,8 +678,7 @@ void AliStack::DumpPStack ()
 
   Int_t i;
 
-  printf(
-        "\n\n=======================================================================\n");
+  printf("\n\n=======================================================================\n");
   for (i=0;i<fNtrack;i++) 
     {
       TParticle* particle = Particle(i);
@@ -758,8 +690,7 @@ void AliStack::DumpPStack ()
         Warning("DumpPStack", "No particle with id %d.", i); 
     }   
 
-  printf(
-        "\n=======================================================================\n\n");
+  printf("\n=======================================================================\n\n");
   
   // print  particle file map
   printf("\nParticle file map: \n");
@@ -781,7 +712,7 @@ void AliStack::DumpLoadedStack() const
         "\n\n=======================================================================\n");
   for (Int_t i=0;i<fNtrack;i++) 
     {
-      TParticle* particle = (TParticle*) particles[i];
+      TParticle* particle = dynamic_cast<TParticle*>(particles[i]);
       if (particle) {
         printf("-> %d ",i); particle->Print();
         printf("--------------------------------------------------------------\n");
@@ -811,7 +742,7 @@ void AliStack::CleanParents()
   TParticle *part;
   int i;
   for(i=0; i<fHgwmk+1; i++) {
-    part = (TParticle *)particles.At(i);
+    part = dynamic_cast<TParticle*>(particles.At(i));
     if(part) if(!part->TestBit(kDaughtersBit)) {
       part->SetFirstDaughter(-1);
       part->SetLastDaughter(-1);
@@ -831,11 +762,9 @@ TParticle* AliStack::GetNextParticle()
   // search secondaries
   //for(Int_t i=fNtrack-1; i>=0; i--) {
   for(Int_t i=fNtrack-1; i>fHgwmk; i--) {
-      particle = (TParticle*) fParticleMap->At(i);
+      particle = dynamic_cast<TParticle*>(fParticleMap->At(i));
       if ((particle) && (!particle->TestBit(kDoneBit))) {
          fCurrent=i;    
-         //cout << "GetNextParticle() - secondary " 
-         // << fNtrack << " " << fHgwmk << " " << fCurrent << endl;
          return particle;
       }   
   }    
@@ -843,89 +772,139 @@ TParticle* AliStack::GetNextParticle()
   // take next primary if all secondaries were done
   while (fCurrentPrimary>=0) {
       fCurrent = fCurrentPrimary;    
-      particle = (TParticle*) fParticleMap->At(fCurrentPrimary--);
+      particle = dynamic_cast<TParticle*>(fParticleMap->At(fCurrentPrimary--));
       if ((particle) && (!particle->TestBit(kDoneBit))) {
-         //cout << "GetNextParticle() - primary " 
-         //   << fNtrack << " " << fHgwmk << " " << fCurrent << endl;
          return particle;
       } 
   }
   
   // nothing to be tracked
   fCurrent = -1;
-    //cout << "GetNextParticle() - none  " 
-    //   << fNtrack << " " << fHgwmk << " " << fCurrent << endl;
   return particle;  
 }
+//__________________________________________________________________________________________
 
+TTree* AliStack::TreeK()
+{
+//returns TreeK
+  if (fTreeK)
+   {
+     return fTreeK;
+   }
+  else
+   {
+     AliRunLoader *rl = AliRunLoader::GetRunLoader(fEventFolderName);
+     if (rl == 0x0)
+      {
+        Fatal("TreeK","Can not get RunLoader from event folder named %s",fEventFolderName.Data());
+        return 0x0;//pro forma
+      }
+    fTreeK = rl->TreeK();
+    if ( fTreeK )
+     {
+      ConnectTree();
+     }
+    else
+     {
+      //don't panic - could be Lego
+      if (AliLoader::GetDebug()) 
+       { 
+         Warning("TreeK","Can not get TreeK from RL. Ev. Folder is %s",fEventFolderName.Data());
+       } 
+     }
+   }
+  return fTreeK;//never reached
+}
 //__________________________________________________________________________________________
-void AliStack::MakeTree(Int_t event, const char *file)
+
+void AliStack::ConnectTree()
 {
 //
-//  Make Kine tree and creates branch for writing particles
-//  
-  TBranch *branch=0;
-  // Make Kinematics Tree
-  char hname[30];
-  if (!fTreeK) {
-    sprintf(hname,"TreeK%d",event);
-    fTreeK = new TTree(hname,"Kinematics");
-    //  Create a branch for particles
-    branch = fTreeK->Branch("Particles", "TParticle", &fParticleBuffer, 4000);          
-    fTreeK->Write(0,TObject::kOverwrite);
-  }
+//  Creates branch for writing particles
+//
+  if (AliLoader::GetDebug()) Info("ConnectTree","Connecting TreeK");
+  if (fTreeK == 0x0)
+   {
+    if (TreeK() == 0x0)
+     {
+      Fatal("ConnectTree","Parameter is NULL");//we don't like such a jokes
+      return;
+     }
+    return;//in this case TreeK() calls back this method (ConnectTree) 
+           //tree after setting fTreeK, the rest was already executed
+           //it is safe to return now
+   }
+
+ //  Create a branch for particles   
+  
+  if (AliLoader::GetDebug()) 
+   Info("ConnectTree","Tree name is %s",fTreeK->GetName());
+   
+  if (fTreeK->GetDirectory())
+   {
+     if (AliLoader::GetDebug())    
+      Info("ConnectTree","and dir is %s",fTreeK->GetDirectory()->GetName());
+   }    
+  else
+    Warning("ConnectTree","DIR IS NOT SET !!!");
+  
+  TBranch *branch=fTreeK->GetBranch(AliRunLoader::GetKineBranchName());
+  if(branch == 0x0)
+   {
+    branch = fTreeK->Branch(AliRunLoader::GetKineBranchName(), "TParticle", &fParticleBuffer, 4000);
+    if (AliLoader::GetDebug()) Info("ConnectTree","Creating Branch in Tree");
+   }  
+  else
+   {
+    if (AliLoader::GetDebug()) Info("ConnectTree","Branch Found in Tree");
+    branch->SetAddress(&fParticleBuffer);
+   }
+  if (branch->GetDirectory())
+   {
+    if (AliLoader::GetDebug()) 
+      Info("ConnectTree","Branch Dir Name is %s",branch->GetDirectory()->GetName());
+   } 
+  else
+    Warning("ConnectTree","Branch Dir is NOT SET");
 }
+//__________________________________________________________________________________________
 
-//_____________________________________________________________________________
-void AliStack::BeginEvent(Int_t event)
+
+void AliStack::BeginEvent()
 {
 // start a new event
-//
-//
-    fNprimary = 0;
-    fNtrack   = 0;
-    
-    char hname[30];
-    if(fTreeK) {
-       fTreeK->Reset();
-       sprintf(hname,"TreeK%d",event);
-       fTreeK->SetName(hname);
-    }
+ Reset();
 }
 
 //_____________________________________________________________________________
 void AliStack::FinishRun()
 {
 // Clean TreeK information
-    if (fTreeK) {
-       delete fTreeK; fTreeK = 0;
-    }
 }
+//_____________________________________________________________________________
 
-Bool_t AliStack::GetEvent(Int_t event)
+Bool_t AliStack::GetEvent()
 {
 //
 // Get new event from TreeK
 
     // Reset/Create the particle stack
-    if (fTreeK) delete fTreeK;
-    
-    // Get Kine Tree from file
-    char treeName[20];
-    sprintf(treeName,"TreeK%d",event);
-    fTreeK = (TTree*)gDirectory->Get(treeName);
+    fTreeK = 0x0;
 
-    if (fTreeK) 
-      fTreeK->SetBranchAddress("Particles", &fParticleBuffer);
-    else {
-      //      Error("GetEvent","cannot find Kine Tree for event:%d\n",event);
-      Warning("GetEvent","cannot find Kine Tree for event:%d\n",event);
+    if (TreeK() == 0x0) //forces connecting
+     {
+      Error("GetEvent","cannot find Kine Tree for current event\n");
       return kFALSE;
-    }
-//      printf("\n primaries %d", fNprimary);
-//      printf("\n tracks    %d", fNtrack);    
+     }
       
-    Int_t size = (Int_t)fTreeK->GetEntries();
+    Int_t size = (Int_t)TreeK()->GetEntries();
     ResetArrays(size);
     return kTRUE;
 }
+//_____________________________________________________________________________
+
+void AliStack::SetEventFolderName(const char* foldname)
+{
+ //Sets event folder name
+ fEventFolderName = foldname;
+}