]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - PHOS/AliPHOSTrackSegmentMakerv1.cxx
restyled Print
[u/mrichter/AliRoot.git] / PHOS / AliPHOSTrackSegmentMakerv1.cxx
index d44419959e84c20a8e9bcf457b64300d6c8a611b..3a6cb20573b998e067d0acff21f755b5495ddbdb 100644 (file)
  * about the suitability of this software for any purpose. It is          *
  * provided "as is" without express or implied warranty.                  *
  **************************************************************************/
-
 /* $Id$ */
-
 //_________________________________________________________________________
 // Implementation version 1 of algorithm class to construct PHOS track segments
-// Associates EMC and PPSD clusters
-// Unfolds the EMC cluster   
-//                  
-//*-- Author: Dmitri Peressounko (RRC Ki & SUBATECH)
+// Track segment for PHOS is list of 
+//        EMC RecPoint + (possibly) CPV RecPoint + (possibly) PPSD RecPoint
+// To find TrackSegments we do the following: 
+//  for each EMC RecPoints we look at
+//   CPV/PPSD RecPoints in the radious fRcpv. 
+//  If there is such a CPV RecPoint, 
+//   we make "Link" it is just indexes of EMC and CPV/PPSD RecPoint and distance
+//   between them in the PHOS plane. 
+//  Then we sort "Links" and starting from the 
+//   least "Link" pointing to the unassined EMC and CPV RecPoints assing them to 
+//   new TrackSegment. 
+// If there is no CPV/PPSD RecPoint we make TrackSegment 
+// consisting from EMC alone. There is no TrackSegments without EMC RecPoint.
+//// In principle this class should be called from AliPHOSReconstructioner, but 
+// one can use it as well in standalone mode.
+// Use  case:
+//  root [0] AliPHOSTrackSegmentMakerv1 * t = new AliPHOSTrackSegmentMaker("galice.root", "tracksegmentsname", "recpointsname")
+//  Warning in <TDatabasePDG::TDatabasePDG>: object already instantiated
+//               // reads gAlice from header file "galice.root", uses recpoints stored in the branch names "recpointsname" (default = "Default")
+//               // and saves recpoints in branch named "tracksegmentsname" (default = "recpointsname")                       
+//  root [1] t->ExecuteTask()
+//  root [2] t->SetMaxEmcPpsdDistance(5)
+//  root [3] t->SetTrackSegmentsBranch("max distance 5 cm")
+//  root [4] t->ExecuteTask("deb all time") 
+//                 
+//*-- Author: Dmitri Peressounko (RRC Ki & SUBATECH) & Yves Schutz (SUBATECH) 
 //
 
 // --- ROOT system ---
-
-#include "TObjArray.h"
-#include "TClonesArray.h"
-#include "TObjectTable.h"
+#include "TROOT.h"
+#include "TFile.h"
+#include "TFolder.h"
+#include "TTree.h"
+#include "TSystem.h"
+#include "TBenchmark.h"
 
 // --- Standard library ---
 
-#include <iostream.h>
-
 // --- AliRoot header files ---
 
 #include "AliPHOSTrackSegmentMakerv1.h"
+#include "AliPHOSClusterizerv1.h"
 #include "AliPHOSTrackSegment.h"
+#include "AliPHOSCpvRecPoint.h"
 #include "AliPHOSLink.h"
-#include "AliPHOSv0.h"
+#include "AliPHOSGetter.h"
+#include "AliPHOS.h"
 #include "AliRun.h"
 
-extern void UnfoldingChiSquare(Int_t &nPar, Double_t *Grad, Double_t & fret, Double_t *x, Int_t iflag) ; 
-
 ClassImp( AliPHOSTrackSegmentMakerv1) 
 
 
 //____________________________________________________________________________
- AliPHOSTrackSegmentMakerv1::AliPHOSTrackSegmentMakerv1() : AliPHOSTrackSegmentMaker()
 AliPHOSTrackSegmentMakerv1::AliPHOSTrackSegmentMakerv1() : AliPHOSTrackSegmentMaker()
 {
-  // ctor
+  // default ctor (to be used mainly by Streamer)
 
-  fR0 = 4. ;   
-  AliPHOSGeometry * geom = AliPHOSGeometry::GetInstance() ;
-  //clusters are sorted in "rows" and "columns" of width geom->GetCrystalSize(0),
-  fDelta = fR0 + geom->GetCrystalSize(0) ;
-  fMinuit = new TMinuit(100) ;
-  fUnfoldFlag = kTRUE ; 
-}
+  InitParameters() ; 
+//   fHeaderFileName           = "" ;
+//   fRecPointsBranchTitle     = "" ;
+//   fTrackSegmentsBranchTitle = "" ; 
+//   fFrom                     = "" ; 
 
-//____________________________________________________________________________
- AliPHOSTrackSegmentMakerv1::~AliPHOSTrackSegmentMakerv1()
-{ 
-  // dtor
-   delete fMinuit ; 
+  fTrackSegmentsInRun       = 0 ; 
+
+  fDefaultInit = kTRUE ; 
 }
 
 //____________________________________________________________________________
-Bool_t  AliPHOSTrackSegmentMakerv1::FindFit(AliPHOSEmcRecPoint * emcRP, int * maxAt, Float_t * maxAtEnergy,
-                                   Int_t nPar, Float_t * fitparameters)
-{ 
-  // Calls TMinuit to fit the energy distribution of a cluster with several maxima 
-
-  AliPHOSGeometry * geom = AliPHOSGeometry::GetInstance() ;
-
-  gMinuit->SetPrintLevel(-1) ;           // No Printout
-  gMinuit->SetFCN(UnfoldingChiSquare) ;  // To set the address of the minimization function 
-  gMinuit->SetObjectFit(emcRP) ;         // To tranfer pointer to UnfoldingChiSquare
-
-  // filling initial values for fit parameters
-  AliPHOSDigit * digit ;
-
-  Int_t ierflg  = 0; 
-  Int_t index   = 0 ;
-  Int_t nDigits = (Int_t) nPar / 3 ;
-
-  Int_t iDigit ;
+ AliPHOSTrackSegmentMakerv1::AliPHOSTrackSegmentMakerv1(const char * headerFile, const char * name, const Bool_t toSplit) : AliPHOSTrackSegmentMaker(headerFile, name, toSplit)
+{
+  // ctor
 
+  InitParameters() ; 
+//   fHeaderFileName           = GetTitle() ;
+//   fRecPointsBranchTitle     = GetName() ;
+//   fTrackSegmentsBranchTitle = GetName() ; 
+  fTrackSegmentsInRun       = 0 ; 
 
-  for(iDigit = 0; iDigit < nDigits; iDigit++){
-    digit = (AliPHOSDigit *) maxAt[iDigit]; 
+//   if ( from == 0 ) 
+//     fFrom = name ; 
+//   else
+//     fFrom = from ; 
+  Init() ;
 
-    Int_t relid[4] ;
-    Float_t x ;
-    Float_t z ;
-    geom->AbsToRelNumbering(digit->GetId(), relid) ;
-    geom->RelPosInModule(relid, x, z) ;
+  fDefaultInit = kFALSE ; 
 
-    Float_t energy = maxAtEnergy[iDigit] ;
+}
 
-    gMinuit->mnparm(index, "x",  x, 0.1, 0, 0, ierflg) ;
-    index++ ;   
-    if(ierflg != 0){ 
-      cout << "PHOS Unfolding>  Unable to set initial value for fit procedure : x = " << x << endl ;
-      return kFALSE;
-    }
-    gMinuit->mnparm(index, "z",  z, 0.1, 0, 0, ierflg) ;
-    index++ ;   
-    if(ierflg != 0){
-      cout << "PHOS Unfolding>  Unable to set initial value for fit procedure : z = " << z << endl ;
-      return kFALSE;
-    }
-    gMinuit->mnparm(index, "Energy",  energy , 0.05*energy, 0., 4.*energy, ierflg) ;
-    index++ ;   
-    if(ierflg != 0){
-      cout << "PHOS Unfolding>  Unable to set initial value for fit procedure : energy = " << energy << endl ;      
-      return kFALSE;
-    }
+//____________________________________________________________________________
+ AliPHOSTrackSegmentMakerv1::~AliPHOSTrackSegmentMakerv1()
+{ 
+  // dtor
+  // fDefaultInit = kTRUE if TrackSegmentMaker created by default ctor (to get just the parameters)
+  
+  if (!fDefaultInit) {
+    delete fLinkUpArray  ;
+    
+//     AliPHOSGetter * gime = AliPHOSGetter::GetInstance() ; 
+    
+//     // remove the task from the folder list
+//     gime->RemoveTask("T",GetName()) ;
+//     TString name(GetName()) ; 
+//     name.ReplaceAll("tsm", "clu") ; 
+//     gime->RemoveTask("C",name) ;
+    
+//     // remove the data from the folder list
+//     name = GetName() ; 
+//     name.Remove(name.Index(":")) ; 
+//     gime->RemoveObjects("RE", name) ; // EMCARecPoints
+//     gime->RemoveObjects("RC", name) ; // CPVRecPoints
+//     gime->RemoveObjects("T", name) ;  // TrackSegments
+    
+//     // Delete gAlice
+//     gime->CloseFile() ; 
+    
+    fSplitFile = 0 ; 
   }
+}
 
-  Double_t p0 = 0.1 ; // "Tolerance" Evaluation stops when EDM = 0.0001*p0 ; The number of function call slightly
-                      //  depends on it. 
-  Double_t p1 = 1.0 ;
-  Double_t p2 = 0.0 ;
-
-  gMinuit->mnexcm("SET STR", &p2, 0, ierflg) ;   // force TgMinuit to reduce function calls  
-  gMinuit->mnexcm("SET GRA", &p1, 1, ierflg) ;   // force TMinuit to use my gradient  
-  gMinuit->SetMaxIterations(5);
-  gMinuit->mnexcm("SET NOW", &p2 , 0, ierflg) ;  // No Warnings
-  gMinuit->mnexcm("MIGRAD", &p0, 0, ierflg) ;    // minimize 
-  if(ierflg == 4){  // Minimum not found   
-    cout << "PHOS Unfolding>  Fit not converged, cluster abandoned "<< endl ;      
-    return kFALSE ;
-  }            
-  for(index = 0; index < nPar; index++){
-    Double_t err ;
-    Double_t val ;
-    gMinuit->GetParameter(index, val, err) ;    // Returns value and error of parameter index
-    fitparameters[index] = val ;
-   }
-  return kTRUE;
 
+//____________________________________________________________________________
+const TString AliPHOSTrackSegmentMakerv1::BranchName() const 
+{  
+  TString branchName(GetName() ) ;
+  branchName.Remove(branchName.Index(Version())-1) ;
+  return branchName ;
 }
 
 //____________________________________________________________________________
-void  AliPHOSTrackSegmentMakerv1::FillOneModule(DigitsList * dl, RecPointsList * emcIn, TObjArray * emcOut, 
-                                       RecPointsList * ppsdIn, TObjArray * ppsdOutUp,
-                                       TObjArray * ppsdOutLow, Int_t & phosmod, Int_t & emcStopedAt, 
-                                       Int_t & ppsdStopedAt)
+void  AliPHOSTrackSegmentMakerv1::FillOneModule()
 {
-  // Unfold clusters and fill xxxOut arrays with clusters from one PHOS module
+  // Finds first and last indexes between which 
+  // clusters from one PHOS module are
+  
+  AliPHOSGetter * gime = AliPHOSGetter::GetInstance() ; 
+  TObjArray * emcRecPoints = gime->EmcRecPoints() ; 
+  TObjArray * cpvRecPoints = gime->CpvRecPoints() ; 
  
-  AliPHOSEmcRecPoint *  emcRecPoint  ; 
-  AliPHOSPpsdRecPoint * ppsdRecPoint ;
-  Int_t index ;
+  //First EMC clusters
+  Int_t totalEmc = emcRecPoints->GetEntriesFast() ;
+  for(fEmcFirst = fEmcLast; (fEmcLast < totalEmc) &&  
+       ((dynamic_cast<AliPHOSRecPoint *>(emcRecPoints->At(fEmcLast)))->GetPHOSMod() == fModule ); 
+      fEmcLast ++)  ;
   
-  Int_t nEmcUnfolded = emcIn->GetEntries() ;
-  for(index = emcStopedAt; index < nEmcUnfolded; index++){
-    emcRecPoint = (AliPHOSEmcRecPoint *) emcIn->At(index) ;
+  //Now CPV clusters
+  Int_t totalCpv = cpvRecPoints->GetEntriesFast() ;
 
-    if(emcRecPoint->GetPHOSMod() != phosmod )  
-       break ;
-    
-    Int_t nMultipl = emcRecPoint->GetMultiplicity() ; 
-    Int_t * maxAt = new Int_t[nMultipl] ;
-    Float_t * maxAtEnergy = new Float_t[nMultipl] ;
-    Int_t nMax = emcRecPoint->GetNumberOfLocalMax(maxAt, maxAtEnergy) ;
-
-    if(nMax <= 1 )     // if cluster is very flat (no pronounced maximum) then nMax = 0 
-      emcOut->Add(emcRecPoint) ;
-    else if (fUnfoldFlag) {
-      UnfoldClusters(dl, emcIn, emcRecPoint, nMax, maxAt, maxAtEnergy, emcOut) ;
-      emcIn->Remove(emcRecPoint); 
-      emcIn->Compress() ;
-      nEmcUnfolded-- ;
-      index-- ;
-    }
-    
-    delete[] maxAt ; 
-    delete[] maxAtEnergy ; 
-  }
-  emcStopedAt = index ;
-
-  for(index = ppsdStopedAt; index < ppsdIn->GetEntries(); index++){
-    ppsdRecPoint = (AliPHOSPpsdRecPoint *) ppsdIn->At(index) ;
-    if(ppsdRecPoint->GetPHOSMod() != phosmod )   
-      break ;
-    if(ppsdRecPoint->GetUp() ) 
-      ppsdOutUp->Add(ppsdRecPoint) ;
-    else  
-      ppsdOutLow->Add(ppsdRecPoint) ;
-  }
-  ppsdStopedAt = index ;
-   
-  emcOut->Sort() ;
-  ppsdOutUp->Sort() ;
-  ppsdOutLow->Sort() ;   
+    for(fCpvFirst = fCpvLast; (fCpvLast < totalCpv) && 
+         ((dynamic_cast<AliPHOSRecPoint *>(cpvRecPoints->At(fCpvLast)))->GetPHOSMod() == fModule ); 
+       fCpvLast ++) ;
+      
 }
+
 //____________________________________________________________________________
-Float_t  AliPHOSTrackSegmentMakerv1::GetDistanceInPHOSPlane(AliPHOSEmcRecPoint * emcclu,AliPHOSPpsdRecPoint * PpsdClu, Bool_t &toofar)
+Float_t  AliPHOSTrackSegmentMakerv1::GetDistanceInPHOSPlane(AliPHOSEmcRecPoint * emcClu,AliPHOSRecPoint * cpvClu, Bool_t &toofar)const
 {
   // Calculates the distance between the EMC RecPoint and the PPSD RecPoint
-  Float_t r = fR0 ;
+  // Clusters are sorted in "rows" and "columns" of width 1 cm
+
+  Float_t delta = 1 ;  // Width of the rows in sorting of RecPoints (in cm)
+                       // if you change this value, change it as well in xxxRecPoint::Compare()
+  Float_t r = fRcpv ;
  
   TVector3 vecEmc ;
-  TVector3 vecPpsd ;
+  TVector3 vecCpv ;
   
-  emcclu->GetLocalPosition(vecEmc) ;
-  PpsdClu->GetLocalPosition(vecPpsd)  ; 
-  if(emcclu->GetPHOSMod() == PpsdClu->GetPHOSMod()){ 
-    if(vecPpsd.X() >= vecEmc.X() - fDelta ){ 
-      if(vecPpsd.Z() >= vecEmc.Z() - fDelta ){
-       AliPHOSGeometry * geom = AliPHOSGeometry::GetInstance() ;
-       // Correct to difference in CPV and EMC position due to different distance to center.
-       // we assume, that particle moves from center
-       Float_t dCPV = geom->GetIPtoOuterCoverDistance();
-       Float_t dEMC = geom->GetIPtoCrystalSurface() ;
-       dEMC         = dEMC / dCPV ;
-        vecPpsd = dEMC * vecPpsd  - vecEmc ; 
-        r = vecPpsd.Mag() ;
-      } // if  zPpsd >= zEmc - fDelta
+  emcClu->GetLocalPosition(vecEmc) ;
+  cpvClu->GetLocalPosition(vecCpv)  ; 
+
+  if(emcClu->GetPHOSMod() == cpvClu->GetPHOSMod()){ 
+    if(vecCpv.X() <= vecEmc.X() + fRcpv + 2*delta ){ 
+
+      vecCpv = vecCpv  - vecEmc ; 
+      r = vecCpv.Mag() ;
       toofar = kFALSE ;
-    } // if  xPpsd >= xEmc - fDelta
+
+    } // if  xPpsd >= xEmc + ...
     else 
       toofar = kTRUE ;
   } 
   else 
     toofar = kTRUE ;
+
+  //toofar = kFALSE ;
   
   return r ;
 }
 
 //____________________________________________________________________________
-void  AliPHOSTrackSegmentMakerv1::MakeLinks(TObjArray * emcRecPoints, TObjArray * ppsdRecPointsUp, 
-                                    TObjArray * ppsdRecPointsLow, TClonesArray * linklowArray, 
-                                    TClonesArray *linkupArray) 
-{ 
-  // Finds distances (links) between all EMC and PPSD clusters, which are not further apart from each other than fR0 
+void  AliPHOSTrackSegmentMakerv1::Init()
+{
+  // Make all memory allocations that are not possible in default constructor
+  
+  if ( strcmp(GetTitle(), "") == 0 )
+    SetTitle("galice.root") ;
+    
+  TString branchname = GetName() ;
+  branchname.Remove(branchname.Index(Version())-1) ;
+  AliPHOSGetter * gime = AliPHOSGetter::GetInstance(GetTitle(),branchname.Data(), fToSplit ) ; 
+  if ( gime == 0 ) {
+    Error("Init", "Could not obtain the Getter object !") ; 
+    return ;
+  } 
   
-  TIter nextEmc(emcRecPoints) ;
-  Int_t iEmcClu = 0 ; 
+  fSplitFile = 0 ;
+  if(fToSplit){
+    //First - extract full path if necessary
+    TString fileName(GetTitle()) ;
+    Ssiz_t islash = fileName.Last('/') ;
+    if(islash<fileName.Length())
+      fileName.Remove(islash+1,fileName.Length()) ;
+    else
+      fileName="" ;
+    fileName+="PHOS.RecData." ;
+    if((strcmp(branchname.Data(),"Default")!=0)&&(strcmp(branchname.Data(),"")!=0)){
+      fileName+=branchname ;
+      fileName+="." ;
+    }
+    fileName+="root" ;
+    fSplitFile = static_cast<TFile*>(gROOT->GetFile(fileName.Data()));   
+    if(!fSplitFile)
+      fSplitFile =  TFile::Open(fileName.Data(),"update") ;
+  }
   
-  AliPHOSPpsdRecPoint * ppsdlow ; 
-  AliPHOSPpsdRecPoint * ppsdup ;
-  AliPHOSEmcRecPoint * emcclu ;
+  fLinkUpArray  = new TClonesArray("AliPHOSLink", 1000); 
   
-  Int_t iLinkLow = 0 ;
+
+  gime->PostTrackSegmentMaker(this) ;
+  gime->PostTrackSegments(BranchName()) ; 
+
+}
+
+//____________________________________________________________________________
+void  AliPHOSTrackSegmentMakerv1::InitParameters()
+{
+  fRcpv      = 10. ;   
+  fEmcFirst  = 0 ;    
+  fEmcLast   = 0 ;   
+  fCpvFirst  = 0 ;   
+  fCpvLast   = 0 ;   
+  fLinkUpArray = 0 ;
+  TString tsmName( GetName()) ; 
+  if (tsmName.IsNull() ) 
+    tsmName = "Default" ; 
+  tsmName.Append(":") ; 
+  tsmName.Append(Version()) ; 
+  SetName(tsmName) ;
+}
+
+
+//____________________________________________________________________________
+void  AliPHOSTrackSegmentMakerv1::MakeLinks()const
+{ 
+  // Finds distances (links) between all EMC and PPSD clusters, 
+  // which are not further apart from each other than fRcpv 
+  // and sort them in accordance with this distance
+  
+  AliPHOSGetter * gime = AliPHOSGetter::GetInstance() ; 
+  TObjArray * emcRecPoints = gime->EmcRecPoints() ; 
+  TObjArray * cpvRecPoints = gime->CpvRecPoints() ; 
+
+  fLinkUpArray->Clear() ;    
+
+  AliPHOSRecPoint * cpv ;
+  AliPHOSEmcRecPoint * emcclu ;
+
   Int_t iLinkUp  = 0 ;
   
-  while( (emcclu = (AliPHOSEmcRecPoint*)nextEmc() ) ) {
-    Bool_t toofar ;
-    TIter nextPpsdLow(ppsdRecPointsLow ) ;
-    Int_t iPpsdLow = 0 ;
-    
-    while( (ppsdlow = (AliPHOSPpsdRecPoint*)nextPpsdLow() ) ) { 
-      Float_t r = GetDistanceInPHOSPlane(emcclu, ppsdlow, toofar) ;
-      
-      if(toofar) 
-       break ;  
-      if(r < fR0){
-       new( (*linklowArray)[iLinkLow++]) AliPHOSLink(r, iEmcClu, iPpsdLow) ;
-     }
-      iPpsdLow++ ;
+  Int_t iEmcRP;
+  for(iEmcRP = fEmcFirst; iEmcRP < fEmcLast; iEmcRP++ ) {
+    emcclu = dynamic_cast<AliPHOSEmcRecPoint *>(emcRecPoints->At(iEmcRP)) ;
+
+    Bool_t toofar ;        
+    Int_t iCpv = 0 ;    
+    for(iCpv = fCpvFirst; iCpv < fCpvLast;iCpv++ ) { 
       
-    }
-    
-    TIter nextPpsdUp(ppsdRecPointsUp ) ;
-    Int_t iPpsdUp = 0 ;
-    
-    while( (ppsdup = (AliPHOSPpsdRecPoint*)nextPpsdUp() ) ) { 
-      Float_t r = GetDistanceInPHOSPlane(emcclu, ppsdup, toofar) ;
+      cpv = dynamic_cast<AliPHOSRecPoint *>(cpvRecPoints->At(iCpv)) ;
+      Float_t r = GetDistanceInPHOSPlane(emcclu, cpv, toofar) ;
       
       if(toofar)
        break ;  
-      if(r < fR0) { 
-       new( (*linkupArray)[iLinkUp++]) AliPHOSLink(r, iEmcClu, iPpsdUp) ;
-      }
-      iPpsdUp++ ;
-      
+      if(r < fRcpv) { 
+       new ((*fLinkUpArray)[iLinkUp++])  AliPHOSLink(r, iEmcRP, iCpv) ;
+      }      
     }
-    
-    iEmcClu++ ; 
-    
-  } // while nextEmC
+  } 
   
-  linklowArray->Sort() ; //first links with smallest distances
-  linkupArray->Sort() ;
+  fLinkUpArray->Sort() ;  //first links with smallest distances
 }
-    
+
 //____________________________________________________________________________
-void  AliPHOSTrackSegmentMakerv1::MakePairs(TObjArray * emcRecPoints, TObjArray * ppsdRecPointsUp, 
-                                   TObjArray * ppsdRecPointsLow, TClonesArray * linklowArray, 
-                                   TClonesArray * linkupArray, TrackSegmentsList * trsl) 
+void  AliPHOSTrackSegmentMakerv1::MakePairs()
 { 
-
-  // Finds the smallest links and makes pairs of PPSD and EMC clusters with smallest distance 
+  // Using the previously made list of "links", we found the smallest link - i.e. 
+  // link with the least distance between EMC and CPV and pointing to still 
+  // unassigned RecParticles. We assign these RecPoints to TrackSegment and 
+  // remove them from the list of "unassigned". 
   
-  TIter nextLow(linklowArray) ;
-  TIter nextUp(linkupArray) ;
+  AliPHOSGetter * gime = AliPHOSGetter::GetInstance() ; 
+  TObjArray * emcRecPoints = gime->EmcRecPoints() ; 
+  TObjArray * cpvRecPoints = gime->CpvRecPoints() ; 
+  TClonesArray * trackSegments = gime->TrackSegments(BranchName()) ;   
+    
+  //Make arrays to mark clusters already chosen
+  Int_t * emcExist = 0;
+  if(fEmcLast > fEmcFirst)
+    emcExist = new Int_t[fEmcLast-fEmcFirst] ;
+  
+  Int_t index;
+  for(index = 0; index <fEmcLast-fEmcFirst; index ++)
+    emcExist[index] = 1 ;
+  
+  Bool_t * cpvExist = 0;
+  if(fCpvLast > fCpvFirst)
+    cpvExist = new Bool_t[fCpvLast-fCpvFirst] ;
+  for(index = 0; index <fCpvLast-fCpvFirst; index ++)
+    cpvExist[index] = kTRUE ;
+  
+  
+  // Finds the smallest links and makes pairs of CPV and EMC clusters with smallest distance 
+  TIter nextUp(fLinkUpArray) ;
   
-  AliPHOSLink * linkLow ;
   AliPHOSLink * linkUp ;
-
-  AliPHOSEmcRecPoint * emc ;
-  AliPHOSPpsdRecPoint * ppsdLow ;
-  AliPHOSPpsdRecPoint * ppsdUp ;
-
+  
   AliPHOSRecPoint * nullpointer = 0 ;
+  
+  while ( (linkUp =  static_cast<AliPHOSLink *>(nextUp()) ) ){  
 
-  while ( (linkLow =  (AliPHOSLink *)nextLow() ) ){
-    emc = (AliPHOSEmcRecPoint *) emcRecPoints->At(linkLow->GetEmc()) ;
-    ppsdLow = (AliPHOSPpsdRecPoint *) ppsdRecPointsLow->At(linkLow->GetPpsd()) ;
-    if( (emc) && (ppsdLow) ){ // RecPoints not removed yet 
-        ppsdUp = 0 ;
-        
-        while ( (linkUp =  (AliPHOSLink *)nextUp() ) ){  
-          if(linkLow->GetEmc() == linkUp->GetEmc() ){
-            ppsdUp = (AliPHOSPpsdRecPoint *) ppsdRecPointsUp->At(linkUp->GetPpsd()) ;
-            break ;
-          }
+    if(emcExist[linkUp->GetEmc()-fEmcFirst] != -1){ //without ppsd Up yet 
+
+      if(cpvExist[linkUp->GetPpsd()-fCpvFirst]){ //CPV still exist
+       
+       new ((* trackSegments)[fNTrackSegments]) 
+         AliPHOSTrackSegment(dynamic_cast<AliPHOSEmcRecPoint *>(emcRecPoints->At(linkUp->GetEmc())) , 
+                             dynamic_cast<AliPHOSRecPoint *>(cpvRecPoints->At(linkUp->GetPpsd()))) ;
+       (dynamic_cast<AliPHOSTrackSegment *>(trackSegments->At(fNTrackSegments)))->SetIndexInList(fNTrackSegments);
+       fNTrackSegments++ ;
        
-        } // while nextUp
-        
-        nextUp.Reset();
-//          AliPHOSTrackSegment * subtr = new AliPHOSTrackSegment(emc, ppsdUp, ppsdLow ) ;
-//      trsl->Add(subtr) ;  
-        new( (*trsl)[fNTrackSegments] ) AliPHOSTrackSegment(emc, ppsdUp, ppsdLow ) ;
-        fNTrackSegments++ ;
-        emcRecPoints->AddAt(nullpointer,linkLow->GetEmc()) ;     
-        ppsdRecPointsLow->AddAt(nullpointer,linkLow->GetPpsd()) ;
-        
-        if(ppsdUp)  
-          ppsdRecPointsUp->AddAt(nullpointer,linkUp->GetPpsd()) ;
-        
+       emcExist[linkUp->GetEmc()-fEmcFirst] = -1 ; //Mark emc  that Cpv was found 
+       //mark CPV recpoint as already used 
+       cpvExist[linkUp->GetPpsd()-fCpvFirst] = kFALSE ;
+      } //if ppsdUp still exist
     } 
-  } 
-   
-  TIter nextEmc(emcRecPoints) ;          
-  nextEmc.Reset() ;
-
-  while( (emc = (AliPHOSEmcRecPoint*)nextEmc()) ){ //to create pairs if no ppsdlow
-    ppsdLow = 0 ; 
-    ppsdUp  = 0 ;
-    
-    while ( (linkUp =  (AliPHOSLink *)nextUp() ) ){
-      
-      if(emcRecPoints->IndexOf(emc) == linkUp->GetEmc() ){
-       ppsdUp = (AliPHOSPpsdRecPoint *) ppsdRecPointsUp->At(linkUp->GetPpsd()) ;
-       break ;
-      }
-      
+  }     
+
+  //look through emc recPoints left without CPV/PPSD
+  if(emcExist){ //if there is emc rec point
+    Int_t iEmcRP ;
+    for(iEmcRP = 0; iEmcRP < fEmcLast-fEmcFirst  ; iEmcRP++ ){
+      if(emcExist[iEmcRP] > 0 ){
+       new ((*trackSegments)[fNTrackSegments])  
+         AliPHOSTrackSegment(dynamic_cast<AliPHOSEmcRecPoint *>(emcRecPoints->At(iEmcRP+fEmcFirst)), 
+                             nullpointer) ;
+       (dynamic_cast<AliPHOSTrackSegment *>(trackSegments->At(fNTrackSegments)))->SetIndexInList(fNTrackSegments);
+       fNTrackSegments++;    
+      } 
     }
-//     AliPHOSTrackSegment * subtr = new AliPHOSTrackSegment(emc, ppsdUp, ppsdLow ) ;
-//     trsl->Add(subtr) ;   
-    new( (*trsl)[fNTrackSegments] ) AliPHOSTrackSegment(emc, ppsdUp, ppsdLow ) ;
-    fNTrackSegments++ ;
-    
-
-    if(ppsdUp)  
-      ppsdRecPointsUp->AddAt(nullpointer,linkUp->GetPpsd()) ;
   }
-     
+  delete [] emcExist ; 
+  delete [] cpvExist ; 
 }
 
 //____________________________________________________________________________
-void  AliPHOSTrackSegmentMakerv1::MakeTrackSegments(DigitsList * dl, RecPointsList * emcl, 
-                                       RecPointsList * ppsdl, TrackSegmentsList * trsl)
+void  AliPHOSTrackSegmentMakerv1::Exec(Option_t * option)
 {
-  // Makes the track segments out of the list of EMC and PPSD Recpoints and stores them in a list
-
-  Int_t phosmod      = 1 ;
-  Int_t emcStopedAt  = 0 ; 
-  Int_t ppsdStopedAt = 0 ; 
-  
-  TObjArray * emcRecPoints     = new TObjArray(100) ;  // these arrays keep pointers 
-  TObjArray * ppsdRecPointsUp  = new TObjArray(100) ;  // to RecPoints, which are 
-  TObjArray * ppsdRecPointsLow = new TObjArray(100) ;  // kept in TClonesArray's emcl and ppsdl
-  
-  
-  TClonesArray * linklowArray = new TClonesArray("AliPHOSLink", 100);
-  TClonesArray * linkupArray  = new TClonesArray("AliPHOSLink", 100); 
-  
-  AliPHOSGeometry * geom = AliPHOSGeometry::GetInstance() ;
-  
-  while(phosmod <= geom->GetNModules() ){
-    
-    FillOneModule(dl, emcl, emcRecPoints, ppsdl, ppsdRecPointsUp, ppsdRecPointsLow, phosmod, emcStopedAt, ppsdStopedAt) ;
+  // STEERing method
 
-    MakeLinks(emcRecPoints, ppsdRecPointsUp, ppsdRecPointsLow, linklowArray, linkupArray) ; 
+  if( strcmp(GetName(), "")== 0 ) 
+    Init() ;
 
-    MakePairs(emcRecPoints, ppsdRecPointsUp, ppsdRecPointsLow, linklowArray, linkupArray, trsl) ;
-    emcRecPoints->Clear() ;
+  if(strstr(option,"tim"))
+    gBenchmark->Start("PHOSTSMaker");
  
-    ppsdRecPointsUp->Clear() ;
-  
-    ppsdRecPointsLow->Clear() ;
-
-    linkupArray->Clear() ;
-   
-    linklowArray->Clear() ;
-   
-    phosmod++ ; 
+  if(strstr(option,"print")) {
+    Print("") ; 
+    return ; 
   }
-  delete emcRecPoints ; 
-  emcRecPoints = 0 ; 
 
-  delete ppsdRecPointsUp ; 
-  ppsdRecPointsUp = 0 ; 
+//   gAlice->GetEvent(0) ;
+//   //check, if the branch with name of this" already exits?
+//   if (gAlice->TreeR()) { 
+//     TObjArray * lob = static_cast<TObjArray*>(gAlice->TreeR()->GetListOfBranches()) ;
+//     TIter next(lob) ; 
+//     TBranch * branch = 0 ;  
+//     Bool_t phostsfound = kFALSE, tracksegmentmakerfound = kFALSE ; 
+    
+//     TString branchname = GetName() ;
+//     branchname.Remove(branchname.Index(Version())-1) ;
+    
+//     while ( (branch = static_cast<TBranch*>(next())) && (!phostsfound || !tracksegmentmakerfound) ) {
+//       if ( (strcmp(branch->GetName(), "PHOSTS")==0) && (strcmp(branch->GetTitle(), branchname.Data())==0) ) 
+//     phostsfound = kTRUE ;
+      
+//       else if ( (strcmp(branch->GetName(), "AliPHOSTrackSegmentMaker")==0) && (strcmp(branch->GetTitle(), GetName())==0) ) 
+//     tracksegmentmakerfound = kTRUE ; 
+//     }
+    
+//     if ( phostsfound || tracksegmentmakerfound ) {
+//       Warning("Exec", "TrackSegments and/or TrackSegmentMaker branch with name %s already exists", branchname.Data() ) ;
+//       return ; 
+//     }       
+//   }
+
+  AliPHOSGetter * gime = AliPHOSGetter::GetInstance() ; 
+  if(gime->BranchExists("TrackSegments") )
+    return ;
+  const AliPHOSGeometry * geom = gime->PHOSGeometry() ; 
+  Int_t nevents = gime->MaxEvent() ;       //(Int_t) gAlice->TreeE()->GetEntries() ;
+  Int_t ievent ;
+
+  for(ievent = 0; ievent < nevents; ievent++){
+
+    gime->Event(ievent,"R") ;
+    //Make some initializations 
+    fNTrackSegments = 0 ;
+    fEmcFirst = 0 ;    
+    fEmcLast  = 0 ;   
+    fCpvFirst = 0 ;   
+    fCpvLast  = 0 ;   
+    gime->TrackSegments(BranchName())->Clear() ; 
+
+    //    if(!ReadRecPoints(ievent))   continue; //reads RecPoints for event ievent
+    
+    for(fModule = 1; fModule <= geom->GetNModules() ; fModule++ ){
+      
+      FillOneModule() ; 
+      
+      MakeLinks() ;
+      
+      MakePairs() ;
+      
+    }
 
-  delete ppsdRecPointsLow ; 
-  ppsdRecPointsLow = 0 ; 
+    WriteTrackSegments(ievent) ;
+
+    if(strstr(option,"deb"))
+      PrintTrackSegments(option) ;
+    
+    //increment the total number of track segments per run 
+    fTrackSegmentsInRun += gime->TrackSegments(BranchName())->GetEntriesFast() ; 
 
-  delete linkupArray ; 
-  linkupArray = 0  ; 
+  }
 
-  delete linklowArray ; 
-  linklowArray = 0 ; 
+  if(strstr(option,"tim")){
+    gBenchmark->Stop("PHOSTSMaker");
+    Info("Exec", "took %f seconds for making TS %f seconds per event", 
+        gBenchmark->GetCpuTime("PHOSTSMaker"), gBenchmark->GetCpuTime("PHOSTSMaker")/nevents) ;
+  }
+    
 }
 
 //____________________________________________________________________________
-Double_t  AliPHOSTrackSegmentMakerv1::ShowerShape(Double_t r)
-{ 
-  // Shape of the shower (see PHOS TDR)
-  // If you change this function, change also the gradien evaluation  in ChiSquare()
-
-  Double_t r4    = r*r*r*r ;
-  Double_t r295  = TMath::Power(r, 2.95) ;
-  Double_t shape = TMath::Exp( -r4 * (1. / (2.32 + 0.26 * r4) + 0.0316 / (1 + 0.0652 * r295) ) ) ;
-  return shape ;
+void AliPHOSTrackSegmentMakerv1::Print(Option_t * option)const
+{
+  //  Print TrackSegmentMaker parameters
+
+  TString message("") ;
+  if( strcmp(GetName(), "") != 0 ) {
+    message = "\n======== AliPHOSTrackSegmentMakerv1 ========\n" ; 
+    message += "Making Track segments\n" ;
+    message += "with parameters:\n" ; 
+    message += "     Maximal EMC - CPV (PPSD) distance (cm) %f\n" ;
+    message += "============================================\n" ;
+    Info("Print", message.Data(),fRcpv) ;
+  }
+  else
+    Info("Print", "AliPHOSTrackSegmentMakerv1 not initialized ") ;
 }
 
 //____________________________________________________________________________
-void  AliPHOSTrackSegmentMakerv1::UnfoldClusters(DigitsList * dl, RecPointsList * emcIn,  AliPHOSEmcRecPoint * iniEmc, 
-                                        Int_t nMax, int * maxAt, Float_t * maxAtEnergy, TObjArray * emcList)
-{ 
-  // Performs the unfolding of a cluster with nMax overlapping showers 
-  // This is time consuming (use the (Un)SetUnfolFlag()  )
-
-  Int_t nPar = 3 * nMax ;
-  Float_t * fitparameters = new Float_t[nPar] ;
-  AliPHOSGeometry * geom = AliPHOSGeometry::GetInstance() ;
-
-  Bool_t rv = FindFit(iniEmc, maxAt, maxAtEnergy, nPar, fitparameters) ;
-  if( !rv ) {
-    // Fit failed, return and remove cluster
-    delete[] fitparameters ; 
-    return ;
-  }
+void AliPHOSTrackSegmentMakerv1::WriteTrackSegments(Int_t event)
+{
+  // Writes found TrackSegments to TreeR. Creates branches 
+  // "PHOSTS" and "AliPHOSTrackSegmentMaker" with the same title.
+  // In the former branch found TrackSegments are stored, while 
+  // in the latter all parameters, with which TS were made. 
+  // ROOT does not allow overwriting existing branches, therefore
+  // first we check, if branches with the same title already exist.
+  // If yes - exits without writing.
   
-  Float_t xDigit ;
-  Float_t zDigit ;
-  Int_t relid[4] ;
-
-  Int_t nDigits = iniEmc->GetMultiplicity() ;  
-  Float_t xpar  ;
-  Float_t zpar  ;
-  Float_t epar  ;
-  Float_t distance ;
-  Float_t ratio ;
-  Float_t * efit = new Float_t[nDigits] ;
-  Int_t iparam ;
-  Int_t iDigit ;
+  AliPHOSGetter *gime = AliPHOSGetter::GetInstance() ; 
+
+  TClonesArray * trackSegments = gime->TrackSegments() ; 
+  trackSegments->Expand(trackSegments->GetEntriesFast()) ;
+  TTree * treeR ;
   
-  AliPHOSDigit * digit ;
-  AliPHOSEmcRecPoint * emcRP ;  
-  Int_t * emcDigits = iniEmc->GetDigitsList() ;
-  Float_t * emcEnergies = iniEmc->GetEnergiesList() ;
-
-  Int_t iRecPoint = emcIn->GetEntries() ;
-
-  for(iDigit = 0 ; iDigit < nDigits ; iDigit ++){
-    digit = (AliPHOSDigit *) emcDigits[iDigit];
-    geom->AbsToRelNumbering(digit->GetId(), relid) ;
-    geom->RelPosInModule(relid, xDigit, zDigit) ;
-    efit[iDigit] = 0;
-    iparam = 0 ;
-    
-    while(iparam < nPar ){
-      xpar = fitparameters[iparam] ;
-      zpar = fitparameters[iparam+1] ;
-      epar = fitparameters[iparam+2] ;
-      iparam += 3 ;
-      distance = (xDigit - xpar) * (xDigit - xpar) + (zDigit - zpar) * (zDigit - zpar)  ;
-      distance =  TMath::Sqrt(distance) ;
-      efit[iDigit] += epar * AliPHOSTrackSegmentMakerv1::ShowerShape(distance) ;
-    }
+  if(fToSplit){
+    if(!fSplitFile)
+      return ;
+    fSplitFile->cd() ;
+    char name[10] ;
+    sprintf(name,"%s%d", "TreeR",event) ;
+    treeR = dynamic_cast<TTree*>(fSplitFile->Get(name)); 
   }
-
-  iparam = 0 ;
-  Float_t eDigit ;
-
-  while(iparam < nPar ){
-    xpar = fitparameters[iparam] ;
-    zpar = fitparameters[iparam+1] ;
-    epar = fitparameters[iparam+2] ;
-    iparam += 3 ;
-    new ((*emcIn)[iRecPoint]) AliPHOSEmcRecPoint( iniEmc->GetLogWeightCut(), iniEmc->GetLocMaxCut() ) ;
-    emcRP = (AliPHOSEmcRecPoint *) emcIn->At(iRecPoint++);
-
-    for(iDigit = 0 ; iDigit < nDigits ; iDigit ++){
-      digit = (AliPHOSDigit *) emcDigits[iDigit];
-      geom->AbsToRelNumbering(digit->GetId(), relid) ;
-      geom->RelPosInModule(relid, xDigit, zDigit) ;
-      distance = (xDigit - xpar) * (xDigit - xpar) + (zDigit - zpar) * (zDigit - zpar)  ;
-      distance =  TMath::Sqrt(distance) ;
-      ratio = epar * AliPHOSTrackSegmentMakerv1::ShowerShape(distance) / efit[iDigit] ; 
-      eDigit = emcEnergies[iDigit] * ratio ;
-      emcRP->AddDigit( *digit, eDigit ) ;
-    }
-
-    emcList->Add(emcRP) ;
-
+  else{
+    treeR = gAlice->TreeR();
   }
   
-  delete[] fitparameters ; 
-  delete[] efit ; 
-
+  if(!treeR){
+    gAlice->MakeTree("R", fSplitFile);
+    treeR = gAlice->TreeR() ;
+  }
+  
+  //First TS
+  Int_t bufferSize = 32000 ;    
+  TBranch * tsBranch = treeR->Branch("PHOSTS",&trackSegments,bufferSize);
+  tsBranch->SetTitle(BranchName());
+
+  //Second -TSMaker
+  Int_t splitlevel = 0 ;
+  AliPHOSTrackSegmentMakerv1 * ts = this ;
+  TBranch * tsMakerBranch = treeR->Branch("AliPHOSTrackSegmentMaker","AliPHOSTrackSegmentMakerv1",
+                                         &ts,bufferSize,splitlevel);
+  tsMakerBranch->SetTitle(BranchName());
+
+  tsBranch->Fill() ;  
+  tsMakerBranch->Fill() ;
+
+  treeR->AutoSave() ; //Write(0,kOverwrite) ;  
+  if(gAlice->TreeR()!=treeR)
+    treeR->Delete();
 }
 
-//______________________________________________________________________________
-void UnfoldingChiSquare(Int_t & nPar, Double_t * Grad, Double_t & fret, Double_t * x, Int_t iflag)
-{
-  // Calculates th Chi square for the cluster unfolding minimization
-  // Number of parameters, Gradient, Chi squared, parameters, what to do
-
-  AliPHOSGeometry * geom = AliPHOSGeometry::GetInstance() ;
 
-  AliPHOSEmcRecPoint * emcRP = (AliPHOSEmcRecPoint *) gMinuit->GetObjectFit() ; // EmcRecPoint to fit
-  Int_t * emcDigits     = emcRP->GetDigitsList() ;
-  Float_t * emcEnergies = emcRP->GetEnergiesList() ;
-  fret = 0. ;     
-  Int_t iparam ;
-
-  if(iflag == 2)
-    for(iparam = 0 ; iparam < nPar ; iparam++)    
-      Grad[iparam] = 0 ; // Will evaluate gradient
-  
-  Double_t efit ;  
+//____________________________________________________________________________
+void AliPHOSTrackSegmentMakerv1::PrintTrackSegments(Option_t * option)
+{
+  // option deb - prints # of found TrackSegments
+  // option deb all - prints as well indexed of found RecParticles assigned to the TS
+  TString taskName(GetName()) ; 
+  taskName.Remove(taskName.Index(Version())-1) ;
   
-  AliPHOSDigit * digit ;
-  Int_t iDigit = 0 ;
-
-  while ( (digit = (AliPHOSDigit *)emcDigits[iDigit] )){
-    Int_t relid[4] ;
-    Float_t xDigit ;
-    Float_t zDigit ;
-    geom->AbsToRelNumbering(digit->GetId(), relid) ;
-    geom->RelPosInModule(relid, xDigit, zDigit) ;
-    
-     if(iflag == 2){  // calculate gradient
-       Int_t iParam = 0 ;
-       efit = 0 ;
-       while(iParam < nPar ){
-        Double_t distance = (xDigit - x[iParam]) * (xDigit - x[iParam]) ;
-        iParam++ ; 
-        distance += (zDigit - x[iParam]) * (zDigit - x[iParam]) ; 
-        distance = TMath::Sqrt( distance ) ; 
-        iParam++ ;      
-        efit += x[iParam] * AliPHOSTrackSegmentMakerv1::ShowerShape(distance) ;
-        iParam++ ;
-       }
-       Double_t sum = 2. * (efit - emcEnergies[iDigit]) / emcEnergies[iDigit] ; // Here we assume, that sigma = sqrt(E) 
-       iParam = 0 ;
-       while(iParam < nPar ){
-        Double_t xpar = x[iParam] ;
-        Double_t zpar = x[iParam+1] ;
-        Double_t epar = x[iParam+2] ;
-        Double_t dr = TMath::Sqrt( (xDigit - xpar) * (xDigit - xpar) + (zDigit - zpar) * (zDigit - zpar) );
-        Double_t shape = sum * AliPHOSTrackSegmentMakerv1::ShowerShape(dr) ;
-        Double_t r4 = dr*dr*dr*dr ;
-        Double_t r295 = TMath::Power(dr,2.95) ;
-        Double_t deriv =-4. * dr*dr * ( 2.32 / ( (2.32 + 0.26 * r4) * (2.32 + 0.26 * r4) ) +
-                                        0.0316 * (1. + 0.0171 * r295) / ( ( 1. + 0.0652 * r295) * (1. + 0.0652 * r295) ) ) ;
-        
-        Grad[iParam] += epar * shape * deriv * (xpar - xDigit) ;  // Derivative over x    
-        iParam++ ; 
-        Grad[iParam] += epar * shape * deriv * (zpar - zDigit) ;  // Derivative over z         
-        iParam++ ; 
-        Grad[iParam] += shape ;                                  // Derivative over energy             
-        iParam++ ; 
-       }
-     }
-     efit = 0;
-     iparam = 0 ;
-     while(iparam < nPar ){
-       Double_t xpar = x[iparam] ;
-       Double_t zpar = x[iparam+1] ;
-       Double_t epar = x[iparam+2] ;
-       iparam += 3 ;
-       Double_t distance = (xDigit - xpar) * (xDigit - xpar) + (zDigit - zpar) * (zDigit - zpar)  ;
-       distance =  TMath::Sqrt(distance) ;
-       efit += epar * AliPHOSTrackSegmentMakerv1::ShowerShape(distance) ;
-     }
-     fret += (efit-emcEnergies[iDigit])*(efit-emcEnergies[iDigit])/emcEnergies[iDigit] ; 
-     // Here we assume, that sigma = sqrt(E)
-     iDigit++ ;
+  TClonesArray * trackSegments = AliPHOSGetter::GetInstance()->TrackSegments(taskName) ; 
+
+  TString message ; 
+  message  = "\nevent " ;
+  message += gAlice->GetEvNumber() ; 
+  message += "\n      Found " ;
+  message += trackSegments->GetEntriesFast() ; 
+  message += " TrackSegments\n" ; 
+
+  if(strstr(option,"all")) {  // printing found TS
+    message += "TrackSegment #  EMC RP#  CPV RP#\n" ; 
+    Int_t index;
+    for (index = 0 ; index <trackSegments->GetEntriesFast() ; index++) {
+      AliPHOSTrackSegment * ts = (AliPHOSTrackSegment * )trackSegments->At(index) ; 
+      message += "\n" ; 
+      message += ts->GetIndexInList() ; 
+      message += " " ; 
+      message += ts->GetEmcIndex() ; 
+      message += " " ; 
+      message += ts->GetCpvIndex() ; 
+    }  
   }
+  Info("Print", message.Data() ) ; 
 }