When calculating a*a-b*b the form (a-b)*(a+b) is usually more numerically stable.
[u/mrichter/AliRoot.git] / STEER / AliVertexerTracks.cxx
index 214dc4f..97a7626 100644 (file)
@@ -14,7 +14,7 @@
  **************************************************************************/
 
 //-----------------------------------------------------------------
-//    Implementation of the vertexer from ESD tracks
+//    Implementation of the vertexer from tracks
 //
 // Origin: AliITSVertexerTracks
 //         A.Dainese, Padova, 
 //         M.Masera,  Torino, 
 //         massimo.masera@to.infn.it
 // Moved to STEER and adapted to ESD tracks: 
-//          F.Prino,  Torino, prino@to.infn.it
+//         F.Prino,  Torino, prino@to.infn.it
 //-----------------------------------------------------------------
 
 //---- Root headers --------
+#include <TSystem.h>
+#include <TDirectory.h>
+#include <TFile.h>
 #include <TTree.h>
 #include <TMatrixD.h>
 //---- AliRoot headers -----
+#include "AliLog.h"
 #include "AliStrLine.h"
-#include "AliVertexerTracks.h"
-#include "AliESD.h"
+#include "AliExternalTrackParam.h"
+#include "AliNeutralTrackParam.h"
+#include "AliVEvent.h"
+#include "AliVTrack.h"
+#include "AliESDEvent.h"
 #include "AliESDtrack.h"
+#include "AliVertexerTracks.h"
 
 ClassImp(AliVertexerTracks)
 
@@ -42,60 +50,68 @@ AliVertexerTracks::AliVertexerTracks():
 TObject(),
 fVert(),
 fCurrentVertex(0),
+fMode(0),
+fFieldkG(-999.),
+fTrkArraySel(),
+fIdSel(0),
+fTrksToSkip(0),
+fNTrksToSkip(0),
 fConstraint(kFALSE),
 fOnlyFitter(kFALSE),
 fMinTracks(1),
-fMinITSClusters(5),
-fTrkArray(),
-fTrksToSkip(0),
-fNTrksToSkip(0),
-fDCAcut(0),
-fAlgo(1),
-fNSigma(3),
+fMinClusters(5),
+fDCAcut(0.1),
+fDCAcutIter0(0.1),
+fNSigma(3.),
 fMaxd0z0(0.5),
-fITSin(kTRUE),
+fMinDetFitter(100.),
+fMaxTgl(1000.),
 fITSrefit(kTRUE),
-fDebug(0)
+fFiducialR(3.),
+fFiducialZ(30.),
+fnSigmaForUi00(1.5),
+fAlgo(1),
+fAlgoIter0(4)
 {
 //
 // Default constructor
 //
   SetVtxStart();
   SetVtxStartSigma();
-  SetMinTracks();
-  SetMinITSClusters();
-  SetNSigmad0(); 
-  SetMaxd0z0(); 
 }
-//-----------------------------------------------------------------------------
-AliVertexerTracks::AliVertexerTracks(Double_t xStart, Double_t yStart):
+//----------------------------------------------------------------------------
+AliVertexerTracks::AliVertexerTracks(Double_t fieldkG):
 TObject(),
 fVert(),
 fCurrentVertex(0),
+fMode(0),
+fFieldkG(fieldkG),
+fTrkArraySel(),
+fIdSel(0),
+fTrksToSkip(0),
+fNTrksToSkip(0),
 fConstraint(kFALSE),
 fOnlyFitter(kFALSE),
 fMinTracks(1),
-fMinITSClusters(5),
-fTrkArray(),
-fTrksToSkip(0),
-fNTrksToSkip(0),
-fDCAcut(0),
-fAlgo(1),
-fNSigma(3),
+fMinClusters(5),
+fDCAcut(0.1),
+fDCAcutIter0(0.1),
+fNSigma(3.),
 fMaxd0z0(0.5),
-fITSin(kTRUE),
+fMinDetFitter(100.),
+fMaxTgl(1000.),
 fITSrefit(kTRUE),
-fDebug(0)
+fFiducialR(3.),
+fFiducialZ(30.),
+fnSigmaForUi00(1.5),
+fAlgo(1),
+fAlgoIter0(4)
 {
 //
 // Standard constructor
 //
-  SetVtxStart(xStart,yStart);
+  SetVtxStart();
   SetVtxStartSigma();
-  SetMinTracks();
-  SetMinITSClusters();
-  SetNSigmad0(); 
-  SetMaxd0z0(); 
 }
 //-----------------------------------------------------------------------------
 AliVertexerTracks::~AliVertexerTracks() 
@@ -104,73 +120,158 @@ AliVertexerTracks::~AliVertexerTracks()
   // The objects pointed by the following pointer are not owned
   // by this class and are not deleted
   fCurrentVertex = 0;
-  delete[] fTrksToSkip;
+  if(fTrksToSkip) { delete [] fTrksToSkip; fTrksToSkip=NULL; }
+  if(fIdSel) { delete [] fIdSel; fIdSel=NULL; }
 }
 //----------------------------------------------------------------------------
-AliESDVertex* AliVertexerTracks::FindPrimaryVertex(const AliESD *esdEvent)
+AliESDVertex* AliVertexerTracks::FindPrimaryVertex(const AliVEvent *vEvent)
 {
 //
-// Primary vertex for current ESD event
+// Primary vertex for current ESD or AOD event
 // (Two iterations: 
 //  1st with 5*fNSigma*sigma cut w.r.t. to initial vertex
 //      + cut on sqrt(d0d0+z0z0) if fConstraint=kFALSE  
 //  2nd with fNSigma*sigma cut w.r.t. to vertex found in 1st iteration) 
-// All ESD tracks with inside the beam pipe are then propagated to found vertex
 //
   fCurrentVertex = 0;
 
-  // read tracks from ESD
-  Int_t nTrksTot = (Int_t)esdEvent->GetNumberOfTracks();
-  if (nTrksTot<=0) return fCurrentVertex;
+  TString evtype = vEvent->IsA()->GetName();
+  Bool_t inputAOD = ((evtype=="AliAODEvent") ? kTRUE : kFALSE);
+
+  if(inputAOD && fMode==1) {
+    printf("Error : AliVertexerTracks: no TPC-only vertex from AOD\n"); 
+    TooFewTracks(); 
+    return fCurrentVertex;
+  }
+
+  // accept 1-track case only if constraint is available
+  if(!fConstraint && fMinTracks==1) fMinTracks=2;
 
-  TTree *trkTree = new TTree("TreeT","tracks");
-  AliESDtrack *esdTrack = 0;
-  trkTree->Branch("tracks","AliESDtrack",&esdTrack);
+  // read tracks from AlivEvent
+  Int_t nTrks = (Int_t)vEvent->GetNumberOfTracks();
+  if(nTrks<fMinTracks) {
+    TooFewTracks();
+    return fCurrentVertex;
+  } 
+  //
 
-  Bool_t   skipThis;
-  for(Int_t i=0; i<nTrksTot; i++) {
-    AliESDtrack *et = esdEvent->GetTrack(i);
-    esdTrack = new AliESDtrack(*et);
+  TDirectory * olddir = gDirectory;
+  TFile *f = 0;
+  if(nTrks>500) f = new TFile("VertexerTracks.root","recreate");
+  TObjArray trkArrayOrig(nTrks);
+  UShort_t *idOrig = new UShort_t[nTrks];
+
+  Int_t nTrksOrig=0;
+  AliExternalTrackParam *t=0;
+  // loop on tracks
+  for(Int_t i=0; i<nTrks; i++) {
+    AliVTrack *track = (AliVTrack*)vEvent->GetTrack(i);
     // check tracks to skip
-    skipThis = kFALSE;
+    Bool_t skipThis = kFALSE;
     for(Int_t j=0; j<fNTrksToSkip; j++) { 
-      if(et->GetID()==fTrksToSkip[j]) {
-       if(fDebug) printf("skipping track: %d\n",i);
+      if(track->GetID()==fTrksToSkip[j]) {
+       AliDebug(1,Form("skipping track: %d",i));
        skipThis = kTRUE;
       }
     }
-    if(skipThis) {delete esdTrack;continue;}
-    if(fITSin) {
-      if(!(esdTrack->GetStatus()&AliESDtrack::kITSin)) {delete esdTrack;continue;}
-      if(fITSrefit && !(esdTrack->GetStatus()&AliESDtrack::kITSrefit)) {delete esdTrack;continue;}
-      Int_t nclus=esdTrack->GetNcls(0); // check number of clusters in ITS
-      if(nclus<fMinITSClusters) {delete esdTrack;continue;}
+    if(skipThis) continue;
+
+    if(!inputAOD) {  // ESD
+      AliESDtrack* esdt = (AliESDtrack*)track;
+      if(esdt->GetNcls(fMode) < fMinClusters) continue;
+      if(fMode==0) {        // ITS mode
+       if(fITSrefit && !(esdt->GetStatus()&AliESDtrack::kITSrefit)) continue;
+       Double_t x,p[5],cov[15];
+       esdt->GetExternalParameters(x,p);
+       esdt->GetExternalCovariance(cov);
+       t = new AliExternalTrackParam(x,esdt->GetAlpha(),p,cov);
+      } else if(fMode==1) { // TPC mode
+       t = (AliExternalTrackParam*)esdt->GetTPCInnerParam();
+       if(!t) continue;
+       Double_t radius = 2.8; //something less than the beam pipe radius
+       if(!PropagateTrackTo(t,radius)) continue;
+      }
+    } else {          // AOD (only ITS mode)
+      Int_t ncls0=0;
+      for(Int_t l=0;l<6;l++) if(TESTBIT(track->GetITSClusterMap(),l)) ncls0++;
+      if(ncls0 < fMinClusters) continue;
+      t = new AliExternalTrackParam(track);
     }
-    trkTree->Fill();
-    delete esdTrack;
-  }
+    trkArrayOrig.AddLast(t);
+    idOrig[nTrksOrig]=(UShort_t)track->GetID();
+    nTrksOrig++;
+  } // end loop on tracks
   
+  // call method that will reconstruct the vertex
+  FindPrimaryVertex(&trkArrayOrig,idOrig);
+
+  if(fMode==0) trkArrayOrig.Delete();
+  delete [] idOrig; idOrig=NULL;
+
+  if(f) {
+    f->Close(); delete f; f = NULL;
+    gSystem->Unlink("VertexerTracks.root");
+    olddir->cd();
+  }
+
+  return fCurrentVertex;
+}
+//----------------------------------------------------------------------------
+AliESDVertex* AliVertexerTracks::FindPrimaryVertex(TObjArray *trkArrayOrig,
+                                                  UShort_t *idOrig)
+{
+//
+// Primary vertex using the AliExternalTrackParam's in the TObjArray.
+// idOrig must contain the track IDs from AliESDtrack::GetID()
+// (Two iterations: 
+//  1st with 5*fNSigma*sigma cut w.r.t. to initial vertex
+//      + cut on sqrt(d0d0+z0z0) if fConstraint=kFALSE  
+//  2nd with fNSigma*sigma cut w.r.t. to vertex found in 1st iteration) 
+//
+  fCurrentVertex = 0;
+
+  // accept 1-track case only if constraint is available
+  if(!fConstraint && fMinTracks==1) fMinTracks=2;
+
+  // read tracks from array
+  Int_t nTrksOrig = (Int_t)trkArrayOrig->GetEntriesFast();
+  AliDebug(1,Form("Initial number of tracks: %d",nTrksOrig));
+  if(nTrksOrig<fMinTracks) {
+    AliDebug(1,"TooFewTracks");
+    TooFewTracks();
+    return fCurrentVertex;
+  } 
+
   // If fConstraint=kFALSE
   // run VertexFinder(1) to get rough estimate of initVertex (x,y)
   if(!fConstraint) {
-    // fill fTrkArray, for VertexFinder()
-    if(!fTrkArray.IsEmpty()) fTrkArray.Delete();
-    PrepareTracks(*trkTree,0);
-    Double_t cutsave = fDCAcut;  fDCAcut = 0.1; // 1 mm
-    VertexFinder(1); // using weights, cutting dca < fDCAcut
+    // fill fTrkArraySel, for VertexFinder()
+    fIdSel = new UShort_t[nTrksOrig];
+    PrepareTracks(*trkArrayOrig,idOrig,0);
+    if(fIdSel) { delete [] fIdSel; fIdSel=NULL; }
+    Double_t cutsave = fDCAcut;  
+    fDCAcut = fDCAcutIter0;
+    // vertex finder
+    switch (fAlgoIter0) {
+    case 1: StrLinVertexFinderMinDist(1); break;
+    case 2: StrLinVertexFinderMinDist(0); break;
+    case 3: HelixVertexFinder();          break;
+    case 4: VertexFinder(1);              break;
+    case 5: VertexFinder(0);              break;
+    default: printf("Wrong algorithm\n"); break;  
+    }
     fDCAcut = cutsave;
-    fTrkArray.Delete();
     if(fVert.GetNContributors()>0) {
       fVert.GetXYZ(fNominalPos);
       fNominalPos[0] = fVert.GetXv();
       fNominalPos[1] = fVert.GetYv();
       fNominalPos[2] = fVert.GetZv();
-      if(fDebug) printf("No mean vertex: VertexFinder gives (%f, %f, %f)\n",fNominalPos[0],fNominalPos[1],fNominalPos[2]);
+      AliDebug(1,Form("No mean vertex: VertexFinder gives (%f, %f, %f)",fNominalPos[0],fNominalPos[1],fNominalPos[2]));
     } else {
       fNominalPos[0] = 0.;
       fNominalPos[1] = 0.;
       fNominalPos[2] = 0.;
-      if(fDebug) printf("No mean vertex and VertexFinder failed\n");
+      AliDebug(1,"No mean vertex and VertexFinder failed");
     }
   }
   
@@ -185,83 +286,68 @@ AliESDVertex* AliVertexerTracks::FindPrimaryVertex(const AliESD *esdEvent)
   // propagate tracks to best between initVertex and fCurrentVertex
   // preselect tracks (reject for |d0|>fNSigma*sigma w.r.t. best 
   //                   between initVertex and fCurrentVertex) 
-  for(Int_t iter=0; iter<2; iter++) {
-    if(fOnlyFitter && iter==0) continue; 
-    Int_t nTrksPrep = PrepareTracks(*trkTree,iter+1);
-    if(fDebug) printf(" tracks prepared - iteration %d: %d\n",iter+1,nTrksPrep);
-    if(nTrksPrep < fMinTracks) {
-      if(fDebug) printf("TooFewTracks\n");
-      TooFewTracks(esdEvent);
-      if(fDebug) fCurrentVertex->PrintStatus();
-      fTrkArray.Delete();
-      delete trkTree;
+  for(Int_t iter=1; iter<=2; iter++) {
+    if(fOnlyFitter && iter==1) continue; 
+    if(fIdSel) { delete [] fIdSel; fIdSel=NULL; }
+    fIdSel = new UShort_t[nTrksOrig];
+    Int_t nTrksSel = PrepareTracks(*trkArrayOrig,idOrig,iter);
+    AliDebug(1,Form("N tracks selected in iteration %d: %d",iter,nTrksSel));
+    if(nTrksSel < fMinTracks) {
+      TooFewTracks();
       return fCurrentVertex; 
     }
 
     // vertex finder
     if(!fOnlyFitter) {
-      if(nTrksPrep==1){
-       if(fDebug) printf("Just one track\n");
+      if(nTrksSel==1) {
+       AliDebug(1,"Just one track");
        OneTrackVertFinder();
-      }else{
+      } else {
        switch (fAlgo) {
         case 1: StrLinVertexFinderMinDist(1); break;
         case 2: StrLinVertexFinderMinDist(0); break;
         case 3: HelixVertexFinder();          break;
         case 4: VertexFinder(1);              break;
         case 5: VertexFinder(0);              break;
-        default: printf("Wrong algorithm\n"); break;  
+        default: printf("Wrong algorithm"); break;  
        }
       }
-      if(fDebug) printf(" Vertex finding completed\n");
+      AliDebug(1," Vertex finding completed");
     }
 
     // vertex fitter
-    VertexFitter(fConstraint);
-    if(fDebug) printf(" Vertex fit completed\n");
-    if(iter==0) fTrkArray.Delete();
+    VertexFitter();
   } // end loop on the two iterations
 
-
-  // take true pos from SPD vertex in ESD and write it in tracks' vertex
-  Double_t tp[3];
-  esdEvent->GetVertex()->GetTruePos(tp);
-  fCurrentVertex->SetTruePos(tp);
-
-  if(fConstraint) {
-    if(fOnlyFitter) {
-      fCurrentVertex->SetTitle("VertexerTracksWithConstraintOnlyFitter");
-    } else {
-      fCurrentVertex->SetTitle("VertexerTracksWithConstraint");
-    }
-  } else {
-    fCurrentVertex->SetTitle("VertexerTracksNoConstraint");
-  }
-
     
   // set indices of used tracks
   UShort_t *indices = 0;
-  AliESDtrack *ett = 0;
   if(fCurrentVertex->GetNContributors()>0) {
-    indices = new UShort_t[fCurrentVertex->GetNContributors()];
-    for(Int_t jj=0;jj<(Int_t)fTrkArray.GetEntriesFast();jj++) {
-      ett = (AliESDtrack*)fTrkArray.At(jj);
-      indices[jj] = (UShort_t)ett->GetID();
-    }
-    fCurrentVertex->SetIndices(fCurrentVertex->GetNContributors(),indices);
+    Int_t nIndices = (Int_t)fTrkArraySel.GetEntriesFast();
+    indices = new UShort_t[nIndices];
+    for(Int_t jj=0; jj<nIndices; jj++)
+      indices[jj] = fIdSel[jj];
+    fCurrentVertex->SetIndices(nIndices,indices);
   }
-  delete [] indices;
-
-  delete trkTree;
-  
-  fTrkArray.Delete();
-
-  if(fTrksToSkip) delete [] fTrksToSkip;
+  delete [] indices; indices=NULL;
+  //
 
+  // set vertex title
+  TString title="VertexerTracksNoConstraint";
+  if(fConstraint) {
+    title="VertexerTracksWithConstraint";
+    if(fOnlyFitter) title.Append("OnlyFitter");
+  }
+  fCurrentVertex->SetTitle(title.Data());
+  //
 
-  if(fDebug) fCurrentVertex->PrintStatus();
-  if(fDebug) fCurrentVertex->PrintIndices();
+  AliDebug(1,Form("xyz: %f %f %f; nc %d",fCurrentVertex->GetXv(),fCurrentVertex->GetYv(),fCurrentVertex->GetZv(),fCurrentVertex->GetNContributors()));
 
+  // clean up
+  delete [] fIdSel; fIdSel=NULL;
+  fTrkArraySel.Delete();
+  if(fTrksToSkip) { delete [] fTrksToSkip; fTrksToSkip=NULL; }
+  //
   
   return fCurrentVertex;
 }
@@ -347,21 +433,24 @@ Double_t AliVertexerTracks::GetStrLinMinDist(Double_t *p0,Double_t *p1,Double_t
   Double_t x10=p0[0]-x0[0];
   Double_t y10=p0[1]-x0[1];
   Double_t z10=p0[2]-x0[2];
-  return ((x10*x10+y10*y10+z10*z10)*(x12*x12+y12*y12+z12*z12)-(x10*x12+y10*y12+z10*z12)*(x10*x12+y10*y12+z10*z12))/(x12*x12+y12*y12+z12*z12);
+  //  return ((x10*x10+y10*y10+z10*z10)*(x12*x12+y12*y12+z12*z12)-(x10*x12+y10*y12+z10*z12)*(x10*x12+y10*y12+z10*z12))/(x12*x12+y12*y12+z12*z12);
+  return ((y10*z12-z10*y12)*(y10*z12-z10*y12)+
+         (z10*x12-x10*z12)*(z10*x12-x10*z12)+
+         (x10*y12-y10*x12)*(x10*y12-y10*x12))
+    /(x12*x12+y12*y12+z12*z12);
 }
 //---------------------------------------------------------------------------
 void AliVertexerTracks::OneTrackVertFinder() 
 {
   // find vertex for events with 1 track, using DCA to nominal beam axis
-  if(fDebug) printf("Number of prepared tracks =%d - Call OneTrackVertFinder",fTrkArray.GetEntries());
-  AliESDtrack *track1;
-  track1 = (AliESDtrack*)fTrkArray.At(0);
-  Double_t field=GetField();
+  AliDebug(1,Form("Number of prepared tracks =%d - Call OneTrackVertFinder",fTrkArraySel.GetEntries()));
+  AliExternalTrackParam *track1;
+  track1 = (AliExternalTrackParam*)fTrkArraySel.At(0);
   Double_t alpha=track1->GetAlpha();
   Double_t mindist = TMath::Cos(alpha)*fNominalPos[0]+TMath::Sin(alpha)*fNominalPos[1];
   Double_t pos[3],dir[3]; 
-  track1->GetXYZAt(mindist,field,pos);
-  track1->GetPxPyPzAt(mindist,field,dir);
+  track1->GetXYZAt(mindist,GetFieldkG(),pos);
+  track1->GetPxPyPzAt(mindist,GetFieldkG(),dir);
   AliStrLine *line1 = new AliStrLine(pos,dir);
   Double_t p1[3]={fNominalPos[0],fNominalPos[1],0.}; 
   Double_t p2[3]={fNominalPos[0],fNominalPos[1],10.}; 
@@ -389,43 +478,43 @@ void AliVertexerTracks::HelixVertexFinder()
   Double_t initPos[3];
   initPos[2] = 0.;
   for(Int_t i=0;i<2;i++)initPos[i]=fNominalPos[i];
-  Double_t field=GetField();
 
-  Int_t nacc = (Int_t)fTrkArray.GetEntriesFast();
+  Int_t nacc = (Int_t)fTrkArraySel.GetEntriesFast();
 
   Double_t aver[3]={0.,0.,0.};
   Double_t averquad[3]={0.,0.,0.};
   Double_t sigmaquad[3]={0.,0.,0.};
   Double_t sigma=0;
   Int_t ncombi = 0;
-  AliESDtrack *track1;
-  AliESDtrack *track2;
+  AliExternalTrackParam *track1;
+  AliExternalTrackParam *track2;
   Double_t distCA;
-  Double_t x, par[5];
+  Double_t x;
   Double_t alpha, cs, sn;
   Double_t crosspoint[3];
   for(Int_t i=0; i<nacc; i++){
-    track1 = (AliESDtrack*)fTrkArray.At(i);
+    track1 = (AliExternalTrackParam*)fTrkArraySel.At(i);
     
 
     for(Int_t j=i+1; j<nacc; j++){
-      track2 = (AliESDtrack*)fTrkArray.At(j);
+      track2 = (AliExternalTrackParam*)fTrkArraySel.At(j);
 
-      distCA=track2->PropagateToDCA(track1,field);
+      distCA=track2->PropagateToDCA(track1,GetFieldkG());
       if(fDCAcut<=0 ||(fDCAcut>0&&distCA<fDCAcut)){
-       track1->GetExternalParameters(x,par);
+       x=track1->GetX();
        alpha=track1->GetAlpha();
        cs=TMath::Cos(alpha); sn=TMath::Sin(alpha);
-       Double_t x1=x*cs - par[0]*sn;
-       Double_t y1=x*sn + par[0]*cs;
-       Double_t z1=par[1];
+       Double_t x1=x*cs - track1->GetY()*sn;
+       Double_t y1=x*sn + track1->GetY()*cs;
+       Double_t z1=track1->GetZ();
+       
        Double_t sx1=sn*sn*track1->GetSigmaY2(), sy1=cs*cs*track1->GetSigmaY2(); 
-       track2->GetExternalParameters(x,par);
+       x=track2->GetX();
        alpha=track2->GetAlpha();
        cs=TMath::Cos(alpha); sn=TMath::Sin(alpha);
-       Double_t x2=x*cs - par[0]*sn;
-       Double_t y2=x*sn + par[0]*cs;
-       Double_t z2=par[1];
+       Double_t x2=x*cs - track2->GetY()*sn;
+       Double_t y2=x*sn + track2->GetY()*cs;
+       Double_t z2=track2->GetZ();
        Double_t sx2=sn*sn*track2->GetSigmaY2(), sy2=cs*cs*track2->GetSigmaY2();
        Double_t sz1=track1->GetSigmaZ2(), sz2=track2->GetSigmaZ2();
        Double_t wx1=sx2/(sx1+sx2), wx2=1.- wx1;
@@ -460,93 +549,170 @@ void AliVertexerTracks::HelixVertexFinder()
   fVert.SetNContributors(ncombi);
 }
 //----------------------------------------------------------------------------
-Int_t AliVertexerTracks::PrepareTracks(TTree &trkTree,Int_t optImpParCut) 
+Int_t AliVertexerTracks::PrepareTracks(TObjArray &trkArrayOrig,
+                                      UShort_t *idOrig,
+                                      Int_t optImpParCut) 
 {
 //
 // Propagate tracks to initial vertex position and store them in a TObjArray
 //
+  AliDebug(1," PrepareTracks()");
+
+  Int_t nTrksOrig = (Int_t)trkArrayOrig.GetEntriesFast();
+  Int_t nTrksSel = 0;
   Double_t maxd0rphi; 
-  Double_t maxd0z0 = fMaxd0z0; // default is 5 mm  
-  Int_t    nTrks    = 0;
   Double_t sigmaCurr[3];
   Double_t normdistx,normdisty;
-  Float_t  d0z0[2],covd0z0[3]; 
-  Double_t sigma;
-  Double_t field=GetField();
+  Double_t d0z0[2],covd0z0[3]; 
+  Double_t sigmad0;
 
   AliESDVertex *initVertex = new AliESDVertex(fNominalPos,fNominalCov,1,1);
 
-  Int_t    nEntries = (Int_t)trkTree.GetEntries();
-  if(!fTrkArray.IsEmpty()) fTrkArray.Delete();
+  if(!fTrkArraySel.IsEmpty()) fTrkArraySel.Delete();
 
-  if(fDebug) {
-    printf(" PrepareTracks()\n");
-  }
+  AliExternalTrackParam *track=0;
 
-  for(Int_t i=0; i<nEntries; i++) {
-    AliESDtrack *track = new AliESDtrack; 
-    trkTree.SetBranchAddress("tracks",&track);
-    trkTree.GetEvent(i);
+  // loop on tracks
+  for(Int_t i=0; i<nTrksOrig; i++) {
+    AliExternalTrackParam *trackOrig=(AliExternalTrackParam*)trkArrayOrig.At(i);
+    if(trackOrig->Charge()!=0) { // normal tracks
+      track = new AliExternalTrackParam(*(AliExternalTrackParam*)trkArrayOrig.At(i));
+    } else { // neutral tracks (from a V0)
+      track = new AliNeutralTrackParam(*(AliNeutralTrackParam*)trkArrayOrig.At(i));
+    }
+    // tgl cut
+    if(TMath::Abs(track->GetTgl())>fMaxTgl) {
+      AliDebug(1,Form(" rejecting track with tgl = %f",track->GetTgl()));
+      delete track; continue;
+    }
 
+    Bool_t propagateOK = kFALSE;
     // propagate track to vertex
-    if(optImpParCut<=1 || fOnlyFitter) { // optImpParCut==1 or 0
-      track->RelateToVertex(initVertex,field,100.);
+    if(optImpParCut<2 || fOnlyFitter) { // optImpParCut==1 or 0
+      propagateOK = track->PropagateToDCA(initVertex,GetFieldkG(),100.,d0z0,covd0z0);
     } else {              // optImpParCut==2
       fCurrentVertex->GetSigmaXYZ(sigmaCurr);
       normdistx = TMath::Abs(fCurrentVertex->GetXv()-fNominalPos[0])/TMath::Sqrt(sigmaCurr[0]*sigmaCurr[0]+fNominalCov[0]);
-      normdisty = TMath::Abs(fCurrentVertex->GetYv()-fNominalPos[1])/TMath::Sqrt(sigmaCurr[1]*sigmaCurr[1]+fNominalCov[1]);
+      normdisty = TMath::Abs(fCurrentVertex->GetYv()-fNominalPos[1])/TMath::Sqrt(sigmaCurr[1]*sigmaCurr[1]+fNominalCov[2]);
       if(normdistx < 3. && normdisty < 3. &&
-        (sigmaCurr[0]+sigmaCurr[1])<(TMath::Sqrt(fNominalCov[0])+TMath::Sqrt(fNominalCov[1]))) {
-       track->RelateToVertex(fCurrentVertex,field,100.);
+        (sigmaCurr[0]+sigmaCurr[1])<(TMath::Sqrt(fNominalCov[0])+TMath::Sqrt(fNominalCov[2]))) {
+       propagateOK = track->PropagateToDCA(fCurrentVertex,GetFieldkG(),100.,d0z0,covd0z0);
       } else {
-       track->RelateToVertex(initVertex,field,100.);
+       propagateOK = track->PropagateToDCA(initVertex,GetFieldkG(),100.,d0z0,covd0z0);
       }
     }
 
-    track->GetImpactParameters(d0z0,covd0z0);
-    sigma = TMath::Sqrt(covd0z0[0]);
-    maxd0rphi = fNSigma*sigma;
+    if(!propagateOK) { 
+      AliDebug(1,"     rejected");
+      delete track; continue; 
+    }
+
+    sigmad0 = TMath::Sqrt(covd0z0[0]);
+    maxd0rphi = fNSigma*sigmad0;
     if(optImpParCut==1) maxd0rphi *= 5.;
+    maxd0rphi = TMath::Min(maxd0rphi,fFiducialR); 
+    //sigmad0z0 = TMath::Sqrt(covd0z0[0]+covd0z0[2]); // for future improvement
+    //maxd0z0 = 10.*fNSigma*sigmad0z0;
 
+    AliDebug(1,Form("trk %d; id %d; |d0| = %f;  d0 cut = %f; |z0| = %f; |d0|oplus|z0| = %f; d0z0 cut = %f",i,(Int_t)idOrig[i],TMath::Abs(d0z0[0]),maxd0rphi,TMath::Abs(d0z0[1]),TMath::Sqrt(d0z0[0]*d0z0[0]+d0z0[1]*d0z0[1]),fMaxd0z0));
 
 
-    if(fDebug) printf("trk %d; lab %d; |d0| = %f;  d0 cut = %f; |z0| = %f; |d0|oplus|z0| = %f; d0z0 cut = %f\n",i,track->GetLabel(),TMath::Abs(d0z0[0]),maxd0rphi,TMath::Abs(d0z0[1]),TMath::Sqrt(d0z0[0]*d0z0[0]+d0z0[1]*d0z0[1]),maxd0z0);
+    //---- track selection based on impact parameters ----//
 
-    // during iteration 1, if fConstraint=kFALSE,
-    // select tracks with d0oplusz0 < maxd0z0
-    if(optImpParCut==1 && !fConstraint && nEntries>=3 && 
-       fVert.GetNContributors()>0) {
-      if(TMath::Sqrt(d0z0[0]*d0z0[0]+d0z0[1]*d0z0[1]) > maxd0z0) { 
-       if(fDebug) printf("     rejected\n");
-       delete track; continue; 
-      }
+    // always reject tracks outside fiducial volume
+    if(TMath::Abs(d0z0[0])>fFiducialR || TMath::Abs(d0z0[1])>fFiducialZ) { 
+      AliDebug(1,"     rejected");
+      delete track; continue; 
     }
 
-    // select tracks with d0rphi < maxd0rphi
-    if(optImpParCut>0 && TMath::Abs(d0z0[0]) > maxd0rphi) { 
-      if(fDebug) printf("     rejected\n");
+    // during iterations 1 and 2 , reject tracks with d0rphi > maxd0rphi
+    if(optImpParCut>0 && TMath::Abs(d0z0[0])>maxd0rphi) { 
+      AliDebug(1,"     rejected");
       delete track; continue; 
     }
 
-    fTrkArray.AddLast(track);
-    nTrks++; 
-  }
+    // if fConstraint=kFALSE, during iterations 1 and 2 ||
+    // if fConstraint=kTRUE, during iteration 2,
+    // select tracks with d0oplusz0 < fMaxd0z0
+    if((!fConstraint && optImpParCut>0 && fVert.GetNContributors()>0) ||
+       ( fConstraint && optImpParCut==2)) {
+      if(nTrksOrig>=3 && 
+        TMath::Sqrt(d0z0[0]*d0z0[0]+d0z0[1]*d0z0[1])>fMaxd0z0) { 
+       AliDebug(1,"     rejected");
+       delete track; continue; 
+      }
+    }
+    
+    // track passed all selections
+    fTrkArraySel.AddLast(track);
+    fIdSel[nTrksSel] = idOrig[i];
+    nTrksSel++; 
+  } // end loop on tracks
 
   delete initVertex;
 
-  return nTrks;
+  return nTrksSel;
 } 
+//----------------------------------------------------------------------------
+Bool_t AliVertexerTracks::PropagateTrackTo(AliExternalTrackParam *track,
+                                          Double_t xToGo) {
+  //----------------------------------------------------------------
+  // COPIED from AliTracker
+  //
+  // Propagates the track to the plane X=xk (cm).
+  //
+  //  Origin: Marian Ivanov,  Marian.Ivanov@cern.ch
+  //----------------------------------------------------------------
+
+  const Double_t kEpsilon = 0.00001;
+  Double_t xpos = track->GetX();
+  Double_t dir = (xpos<xToGo) ? 1. : -1.;
+  Double_t maxStep = 5;
+  Double_t maxSnp = 0.8;
+  //
+  while ( (xToGo-xpos)*dir > kEpsilon){
+    Double_t step = dir*TMath::Min(TMath::Abs(xToGo-xpos), maxStep);
+    Double_t x    = xpos+step;
+    Double_t xyz0[3],xyz1[3];
+    track->GetXYZ(xyz0);   //starting global position
+
+    if(!track->GetXYZAt(x,GetFieldkG(),xyz1)) return kFALSE;   // no prolongation
+    xyz1[2]+=kEpsilon; // waiting for bug correction in geo
+
+    if(TMath::Abs(track->GetSnpAt(x,GetFieldkG())) >= maxSnp) return kFALSE;
+    if(!track->PropagateTo(x,GetFieldkG()))  return kFALSE;
+
+    if(TMath::Abs(track->GetSnp()) >= maxSnp) return kFALSE;
+    track->GetXYZ(xyz0);   // global position
+    Double_t alphan = TMath::ATan2(xyz0[1], xyz0[0]); 
+    //
+    Double_t ca=TMath::Cos(alphan-track->GetAlpha()), 
+      sa=TMath::Sin(alphan-track->GetAlpha());
+    Double_t sf=track->GetSnp(), cf=TMath::Sqrt((1.-sf)*(1.+sf));
+    Double_t sinNew =  sf*ca - cf*sa;
+    if(TMath::Abs(sinNew) >= maxSnp) return kFALSE;
+    if(!track->Rotate(alphan)) return kFALSE;
+    xpos = track->GetX();
+  }
+  return kTRUE;
+}
 //---------------------------------------------------------------------------
 AliESDVertex* AliVertexerTracks::RemoveTracksFromVertex(AliESDVertex *inVtx,
-                                                       TTree *trksTree,
+                                                       TObjArray *trkArray,
+                                                       UShort_t *id,
                                                        Float_t *diamondxy) 
 {
 //
 // Removes tracks in trksTree from fit of inVtx
 //
 
+  if(!strstr(inVtx->GetTitle(),"VertexerTracksWithConstraint")) {
+    printf("ERROR: primary vertex has no constraint: cannot remove tracks");
+    return 0x0;
+  }
   if(!strstr(inVtx->GetTitle(),"VertexerTracksWithConstraintOnlyFitter"))
-    printf("WARNING: result of tracks' removal will be only approximately correct\n");
+    printf("WARNING: result of tracks' removal will be only approximately correct");
 
   TMatrixD rv(3,1);
   rv(0,0) = inVtx->GetXv();
@@ -565,21 +731,20 @@ AliESDVertex* AliVertexerTracks::RemoveTracksFromVertex(AliESDVertex *inVtx,
   TMatrixD sumWi(TMatrixD::kInverted,vV);
   TMatrixD sumWiri(sumWi,TMatrixD::kMult,rv);
 
-  Int_t nUsedTrks = inVtx->GetNContributors();
+  Int_t nUsedTrks = inVtx->GetNIndices();
   Double_t chi2 = inVtx->GetChi2();
 
-  AliESDtrack *track = 0;
-  trksTree->SetBranchAddress("tracks",&track);
-  Int_t ntrks = trksTree->GetEntries();
+  AliExternalTrackParam *track = 0;
+  Int_t ntrks = (Int_t)trkArray->GetEntriesFast();
   for(Int_t i=0;i<ntrks;i++) {
-    trksTree->GetEvent(i);
-    if(!inVtx->UsesTrack(track->GetID())) {
-      printf("track %d was not used in vertex fit\n",track->GetID());
+    track = (AliExternalTrackParam*)trkArray->At(i);
+    if(!inVtx->UsesTrack(id[i])) {
+      printf("track %d was not used in vertex fit",id[i]);
       continue;
     }
     Double_t alpha = track->GetAlpha();
     Double_t xl = diamondxy[0]*TMath::Cos(alpha)+diamondxy[1]*TMath::Sin(alpha);
-    track->AliExternalTrackParam::PropagateTo(xl,AliTracker::GetBz()); 
+    track->PropagateTo(xl,GetFieldkG()); 
     // vector of track global coordinates
     TMatrixD ri(3,1);
     // covariance matrix of ri
@@ -604,7 +769,7 @@ AliESDVertex* AliVertexerTracks::RemoveTracksFromVertex(AliESDVertex *inVtx,
 
     nUsedTrks--;
     if(nUsedTrks<2) {
-      printf("Trying to remove too many tracks!\n");
+      printf("Trying to remove too many tracks!");
       return 0x0;
     }
   }
@@ -632,38 +797,125 @@ AliESDVertex* AliVertexerTracks::RemoveTracksFromVertex(AliESDVertex *inVtx,
   // store data in the vertex object
   AliESDVertex *outVtx = new AliESDVertex(position,cov,chi2,nUsedTrks);
   outVtx->SetTitle(inVtx->GetTitle());
-  Double_t tp[3];
-  inVtx->GetTruePos(tp);
-  outVtx->SetTruePos(tp);
   UShort_t *inindices = inVtx->GetIndices();
-  UShort_t *outindices = new UShort_t[outVtx->GetNContributors()];
+  Int_t nIndices = nUsedTrks;
+  UShort_t *outindices = new UShort_t[nIndices];
   Int_t j=0;
-  Bool_t copyindex;
   for(Int_t k=0; k<inVtx->GetNIndices(); k++) {
-    copyindex=kTRUE;
+    Bool_t copyindex=kTRUE;
     for(Int_t l=0; l<ntrks; l++) {
-      trksTree->GetEvent(l);
-      if(inindices[k]==track->GetID()) copyindex=kFALSE;
+      if(inindices[k]==id[l]) copyindex=kFALSE;
     }
     if(copyindex) {
       outindices[j] = inindices[k]; j++;
     }
   }
-  outVtx->SetIndices(outVtx->GetNContributors(),outindices);
+  outVtx->SetIndices(nIndices,outindices);
   delete [] outindices;
 
-  if(fDebug) {
-    printf("Vertex before removing tracks:\n");
+  /*
+    printf("Vertex before removing tracks:");
     inVtx->PrintStatus();
     inVtx->PrintIndices();
-    printf("Vertex after removing tracks:\n");
+    printf("Vertex after removing tracks:");
     outVtx->PrintStatus();
     outVtx->PrintIndices();
-  }
+  */
 
   return outVtx;
 }
 //---------------------------------------------------------------------------
+void AliVertexerTracks::SetCuts(Double_t *cuts) 
+{
+//
+//  Cut values
+//
+  SetDCAcut(cuts[0]);
+  SetDCAcutIter0(cuts[1]);
+  SetMaxd0z0(cuts[2]);
+  if(fMode==0 && cuts[3]<0) SetITSrefitNotRequired();
+  SetMinClusters((Int_t)(TMath::Abs(cuts[3])));
+  SetMinTracks((Int_t)(cuts[4]));
+  SetNSigmad0(cuts[5]);
+  SetMinDetFitter(cuts[6]);
+  SetMaxTgl(cuts[7]);
+  SetFiducialRZ(cuts[8],cuts[9]);
+  fAlgo=(Int_t)(cuts[10]);
+  fAlgoIter0=(Int_t)(cuts[11]);
+
+  return;
+}
+//---------------------------------------------------------------------------
+void AliVertexerTracks::SetITSMode(Double_t dcacut,
+                                  Double_t dcacutIter0,
+                                  Double_t maxd0z0,
+                                  Int_t minCls,
+                                  Int_t mintrks,
+                                  Double_t nsigma,
+                                  Double_t mindetfitter,
+                                  Double_t maxtgl,
+                                  Double_t fidR,
+                                  Double_t fidZ,
+                                  Int_t finderAlgo,
+                                  Int_t finderAlgoIter0)
+{
+//
+//  Cut values for ITS mode
+//
+  fMode = 0;
+  if(minCls>0) {
+    SetITSrefitRequired();
+  } else {
+    SetITSrefitNotRequired();
+  }
+  SetDCAcut(dcacut);
+  SetDCAcutIter0(dcacutIter0);
+  SetMaxd0z0(maxd0z0);
+  SetMinClusters(TMath::Abs(minCls));
+  SetMinTracks(mintrks);
+  SetNSigmad0(nsigma);
+  SetMinDetFitter(mindetfitter);
+  SetMaxTgl(maxtgl);
+  SetFiducialRZ(fidR,fidZ);
+  fAlgo=finderAlgo;
+  fAlgoIter0=finderAlgoIter0;
+
+  return; 
+}
+//---------------------------------------------------------------------------
+void AliVertexerTracks::SetTPCMode(Double_t dcacut,
+                                  Double_t dcacutIter0,
+                                  Double_t maxd0z0,
+                                  Int_t minCls,
+                                  Int_t mintrks,
+                                  Double_t nsigma,
+                                  Double_t mindetfitter,
+                                  Double_t maxtgl,
+                                  Double_t fidR,
+                                  Double_t fidZ,
+                                  Int_t finderAlgo,
+                                  Int_t finderAlgoIter0) 
+{
+//
+//  Cut values for TPC mode
+//
+  fMode = 1;
+  SetITSrefitNotRequired();
+  SetDCAcut(dcacut);
+  SetDCAcutIter0(dcacutIter0);
+  SetMaxd0z0(maxd0z0);
+  SetMinClusters(minCls);
+  SetMinTracks(mintrks);
+  SetNSigmad0(nsigma);
+  SetMinDetFitter(mindetfitter);
+  SetMaxTgl(maxtgl);
+  SetFiducialRZ(fidR,fidZ);
+  fAlgo=finderAlgo;
+  fAlgoIter0=finderAlgoIter0;
+
+  return; 
+}
+//---------------------------------------------------------------------------
 void AliVertexerTracks::SetSkipTracks(Int_t n,Int_t *skipped) 
 {
 //
@@ -688,37 +940,76 @@ void  AliVertexerTracks::SetVtxStart(AliESDVertex *vtx)
 //---------------------------------------------------------------------------
 void AliVertexerTracks::StrLinVertexFinderMinDist(Int_t optUseWeights)
 {
+  AliExternalTrackParam *track1;
+  const Int_t knacc = (Int_t)fTrkArraySel.GetEntriesFast();
+  static TClonesArray linarray("AliStrLine",knacc);
+  for(Int_t i=0; i<knacc; i++){
+    track1 = (AliExternalTrackParam*)fTrkArraySel.At(i);
+    Double_t alpha=track1->GetAlpha();
+    Double_t mindist = TMath::Cos(alpha)*fNominalPos[0]+TMath::Sin(alpha)*fNominalPos[1];
+    Double_t pos[3],dir[3],sigmasq[3]; 
+    track1->GetXYZAt(mindist,GetFieldkG(),pos);
+    track1->GetPxPyPzAt(mindist,GetFieldkG(),dir);
+    sigmasq[0]=TMath::Sin(alpha)*TMath::Sin(alpha)*track1->GetSigmaY2();
+    sigmasq[1]=TMath::Cos(alpha)*TMath::Cos(alpha)*track1->GetSigmaY2();
+    sigmasq[2]=track1->GetSigmaZ2();
+    TMatrixD ri(3,1);
+    TMatrixD wWi(3,3);
+    //if(!TrackToPoint(track1,ri,wWi)) {printf("WARNING\n");continue;}
+    if(!TrackToPoint(track1,ri,wWi)) {optUseWeights=kFALSE;printf("WARNING\n");}
+    Double_t wmat[9];
+    Int_t iel=0;
+    for(Int_t ia=0;ia<3;ia++){
+      for(Int_t ib=0;ib<3;ib++){
+       wmat[iel]=wWi(ia,ib);
+       iel++;
+      }    
+    }
+    new(linarray[i]) AliStrLine(pos,sigmasq,wmat,dir);
+  }
+  fVert=TrackletVertexFinder(&linarray,optUseWeights);
+  linarray.Clear("C");
+}
+//---------------------------------------------------------------------------
+AliESDVertex AliVertexerTracks::TrackletVertexFinder(TClonesArray *lines, Int_t optUseWeights)
+{
   // Calculate the point at minimum distance to prepared tracks 
-  
-  Double_t initPos[3];
-  initPos[2] = 0.;
-  Double_t sigma=0;
-  for(Int_t i=0;i<2;i++)initPos[i]=fNominalPos[i];
-  const Int_t knacc = (Int_t)fTrkArray.GetEntriesFast();
-  Double_t field=GetField();
+  const Int_t knacc = (Int_t)lines->GetEntriesFast();
+  Double_t initPos[3]={0.,0.,0.};
 
-  AliESDtrack *track1;
   Double_t (*vectP0)[3]=new Double_t [knacc][3];
   Double_t (*vectP1)[3]=new Double_t [knacc][3];
   
   Double_t sum[3][3];
   Double_t dsum[3]={0,0,0};
-  for(Int_t i=0;i<3;i++)
-    for(Int_t j=0;j<3;j++)sum[i][j]=0;
-  for(Int_t i=0; i<knacc; i++){
-    track1 = (AliESDtrack*)fTrkArray.At(i);
-    Double_t alpha=track1->GetAlpha();
-    Double_t mindist = TMath::Cos(alpha)*fNominalPos[0]+TMath::Sin(alpha)*fNominalPos[1];
-    Double_t pos[3],dir[3]; 
-    track1->GetXYZAt(mindist,field,pos);
-    track1->GetPxPyPzAt(mindist,field,dir);
-    AliStrLine *line1 = new AliStrLine(pos,dir); 
-    //    AliStrLine *line1 = new AliStrLine();
-    //    track1->ApproximateHelixWithLine(mindist,field,line1);
+  TMatrixD sumWi(3,3);
+  for(Int_t i=0;i<3;i++){
+    for(Int_t j=0;j<3;j++){
+      sum[i][j]=0;
+      sumWi(i,j)=0.;
+    }
+  }
 
-    Double_t p0[3],cd[3];
+  for(Int_t i=0; i<knacc; i++){
+    AliStrLine* line1 = (AliStrLine*)lines->At(i); 
+    Double_t p0[3],cd[3],sigmasq[3];
+    Double_t wmat[9];
+    if(!line1) printf("ERROR %d %d\n",i,knacc);
     line1->GetP0(p0);
     line1->GetCd(cd);
+    line1->GetSigma2P0(sigmasq);
+    line1->GetWMatrix(wmat);
+    TMatrixD wWi(3,3);
+    Int_t iel=0;
+    for(Int_t ia=0;ia<3;ia++){
+      for(Int_t ib=0;ib<3;ib++){
+       wWi(ia,ib)=wmat[iel];
+       iel++;
+      }    
+    }
+
+    sumWi+=wWi;
+
     Double_t p1[3]={p0[0]+cd[0],p0[1]+cd[1],p0[2]+cd[2]};
     vectP0[i][0]=p0[0];
     vectP0[i][1]=p0[1];
@@ -730,23 +1021,27 @@ void AliVertexerTracks::StrLinVertexFinderMinDist(Int_t optUseWeights)
     Double_t matr[3][3];
     Double_t dknow[3];
     if(optUseWeights==0)GetStrLinDerivMatrix(p0,p1,matr,dknow);
-    if(optUseWeights==1){
-      Double_t sigmasq[3];
-      sigmasq[0]=track1->GetSigmaY2();
-      sigmasq[1]=track1->GetSigmaY2();
-      sigmasq[2]=track1->GetSigmaZ2();
-      GetStrLinDerivMatrix(p0,p1,sigmasq,matr,dknow);
-    }
+    else GetStrLinDerivMatrix(p0,p1,sigmasq,matr,dknow);
+
 
     for(Int_t iii=0;iii<3;iii++){
       dsum[iii]+=dknow[iii]; 
       for(Int_t lj=0;lj<3;lj++) sum[iii][lj]+=matr[iii][lj];
     }
-    delete line1;
   }
-  
+  TMatrixD invsumWi(TMatrixD::kInverted,sumWi);
+  Double_t covmatrix[6];
+  covmatrix[0] = invsumWi(0,0);
+  covmatrix[1] = invsumWi(0,1);
+  covmatrix[2] = invsumWi(1,1);
+  covmatrix[3] = invsumWi(0,2);
+  covmatrix[4] = invsumWi(1,2);
+  covmatrix[5] = invsumWi(2,2);
+
   Double_t vett[3][3];
   Double_t det=GetDeterminant3X3(sum);
+  Double_t sigma=0;
   
   if(det!=0){
     for(Int_t zz=0;zz<3;zz++){
@@ -767,23 +1062,23 @@ void AliVertexerTracks::StrLinVertexFinderMinDist(Int_t optUseWeights)
       sigma+=GetStrLinMinDist(p0,p1,initPos);
     }
 
-    sigma=TMath::Sqrt(sigma);
+    if(sigma>0.) {sigma=TMath::Sqrt(sigma);}else{sigma=999;}
   }else{
-    Warning("StrLinVertexFinderMinDist","Finder did not succed");
     sigma=999;
   }
+  AliESDVertex theVert(initPos,covmatrix,99999.,knacc);
+  theVert.SetDispersion(sigma);
   delete vectP0;
   delete vectP1;
-  fVert.SetXYZ(initPos);
-  fVert.SetDispersion(sigma);
-  fVert.SetNContributors(knacc);
+  return theVert;
 }
 //---------------------------------------------------------------------------
-Bool_t AliVertexerTracks::TrackToPoint(AliESDtrack *t,
-                                      TMatrixD &ri,TMatrixD &wWi) const 
+Bool_t AliVertexerTracks::TrackToPoint(AliExternalTrackParam *t,
+                                      TMatrixD &ri,TMatrixD &wWi,
+                                      Bool_t uUi3by3) const 
 {
 //
-// Extract from the AliESDtrack the global coordinates ri and covariance matrix
+// Extract from the AliExternalTrackParam the global coordinates ri and covariance matrix
 // wWi of the space point that it represents (to be used in VertexFitter())
 //
 
@@ -797,70 +1092,126 @@ Bool_t AliVertexerTracks::TrackToPoint(AliESDtrack *t,
   ri(1,0) = t->GetX()*sinRot+t->GetY()*cosRot;
   ri(2,0) = t->GetZ();
 
-  // matrix to go from global (x,y,z) to local (y,z);
-  TMatrixD qQi(2,3);
-  qQi(0,0) = -sinRot;
-  qQi(0,1) = cosRot;
-  qQi(0,2) = 0.;
-  qQi(1,0) = 0.;
-  qQi(1,1) = 0.;
-  qQi(1,2) = 1.;
-
-  // covariance matrix of local (y,z) - inverted
-  TMatrixD uUi(2,2);
-  Double_t cc[15];
-  t->GetExternalCovariance(cc);
-  uUi(0,0) = cc[0];
-  uUi(0,1) = cc[1];
-  uUi(1,0) = cc[1];
-  uUi(1,1) = cc[2];
-  if(uUi.Determinant() <= 0.) return kFALSE;
-  TMatrixD uUiInv(TMatrixD::kInverted,uUi);
+
+
+  if(!uUi3by3) {
+    // matrix to go from global (x,y,z) to local (y,z);
+    TMatrixD qQi(2,3);
+    qQi(0,0) = -sinRot;
+    qQi(0,1) = cosRot;
+    qQi(0,2) = 0.;
+    qQi(1,0) = 0.;
+    qQi(1,1) = 0.;
+    qQi(1,2) = 1.;
+
+    // covariance matrix of local (y,z) - inverted
+    TMatrixD uUi(2,2);
+    uUi(0,0) = t->GetSigmaY2();
+    uUi(0,1) = t->GetSigmaZY();
+    uUi(1,0) = t->GetSigmaZY();
+    uUi(1,1) = t->GetSigmaZ2();
+    //printf(" Ui :");
+    //printf(" %f   %f",uUi(0,0),uUi(0,1));
+    //printf(" %f   %f",uUi(1,0),uUi(1,1));
+
+    if(uUi.Determinant() <= 0.) return kFALSE;
+    TMatrixD uUiInv(TMatrixD::kInverted,uUi);
+  
+    // weights matrix: wWi = qQiT * uUiInv * qQi
+    TMatrixD uUiInvQi(uUiInv,TMatrixD::kMult,qQi);
+    TMatrixD m(qQi,TMatrixD::kTransposeMult,uUiInvQi);
+    wWi = m;
+  } else {
+    if(fVert.GetNContributors()<1) AliFatal("Vertex from finder is empty");
+    // matrix to go from global (x,y,z) to local (x,y,z);
+    TMatrixD qQi(3,3);
+    qQi(0,0) = cosRot;
+    qQi(0,1) = sinRot;
+    qQi(0,2) = 0.;
+    qQi(1,0) = -sinRot;
+    qQi(1,1) = cosRot;
+    qQi(1,2) = 0.;
+    qQi(2,0) = 0.;
+    qQi(2,1) = 0.;
+    qQi(2,2) = 1.;
+   
+    // covariance of fVert along the track  
+    Double_t p[3],pt,ptot;
+    t->GetPxPyPz(p);
+    pt = TMath::Sqrt(p[0]*p[0]+p[1]*p[1]);
+    ptot = TMath::Sqrt(pt*pt+p[2]*p[2]);
+    Double_t cphi = p[0]/pt;               //cos(phi)=px/pt
+    Double_t sphi = p[1]/pt;               //sin(phi)=py/pt
+    Double_t clambda = pt/ptot;            //cos(lambda)=pt/ptot
+    Double_t slambda = p[2]/ptot;            //sin(lambda)=pz/ptot
+    Double_t covfVert[6];
+    fVert.GetCovMatrix(covfVert);
+    Double_t covfVertalongt = 
+       covfVert[0]*cphi*cphi*clambda*clambda 
+      +covfVert[1]*2.*cphi*sphi*clambda*clambda
+      +covfVert[3]*2.*cphi*clambda*slambda 
+      +covfVert[2]*sphi*sphi*clambda*clambda 
+      +covfVert[4]*2.*sphi*clambda*slambda 
+      +covfVert[5]*slambda*slambda; 
+    // covariance matrix of local (x,y,z) - inverted
+    TMatrixD uUi(3,3);
+    uUi(0,0) = covfVertalongt * fnSigmaForUi00 * fnSigmaForUi00;
+    AliDebug(1,Form("=====> sqrtUi00 cm  %f",TMath::Sqrt(uUi(0,0))));
+    uUi(0,1) = 0.;
+    uUi(0,2) = 0.;
+    uUi(1,0) = 0.;
+    uUi(1,1) = t->GetSigmaY2();
+    uUi(1,2) = t->GetSigmaZY();
+    uUi(2,0) = 0.;
+    uUi(2,1) = t->GetSigmaZY();
+    uUi(2,2) = t->GetSigmaZ2();
+    //printf(" Ui :\n");
+    //printf(" %f   %f\n",uUi(0,0),uUi(0,1));
+    //printf(" %f   %f\n",uUi(1,0),uUi(1,1));
   
-  // weights matrix: wWi = qQiT * uUiInv * qQi
-  TMatrixD uUiInvQi(uUiInv,TMatrixD::kMult,qQi);
-  TMatrixD m(qQi,TMatrixD::kTransposeMult,uUiInvQi);
-  wWi = m;
+    if(uUi.Determinant() <= 0.) return kFALSE;
+    TMatrixD uUiInv(TMatrixD::kInverted,uUi);
+  
+    // weights matrix: wWi = qQiT * uUiInv * qQi
+    TMatrixD uUiInvQi(uUiInv,TMatrixD::kMult,qQi);
+    TMatrixD m(qQi,TMatrixD::kTransposeMult,uUiInvQi);
+    wWi = m;
+  }
+
 
   return kTRUE;
 } 
 //---------------------------------------------------------------------------
-void AliVertexerTracks::TooFewTracks(const AliESD* esdEvent) 
+void AliVertexerTracks::TooFewTracks() 
 {
 //
-// When the number of tracks is < fMinTracks
+// When the number of tracks is < fMinTracks,
+// deal with vertices not found and prepare to exit
 //
+  AliDebug(1,"TooFewTracks");
 
-  // deal with vertices not found
   Double_t pos[3],err[3];
-  Int_t    ncontr=0;
   pos[0] = fNominalPos[0];
   err[0] = TMath::Sqrt(fNominalCov[0]);
   pos[1] = fNominalPos[1];
   err[1] = TMath::Sqrt(fNominalCov[2]);
-  pos[2] = esdEvent->GetVertex()->GetZv();
-  err[2] = esdEvent->GetVertex()->GetZRes();
-  if(err[0]>1. && esdEvent->GetVertex()->GetNContributors()<=0) 
-    ncontr = -1; // (x,y,z) = (0,0,0) 
-  if(err[0]>1. && esdEvent->GetVertex()->GetNContributors()>0) 
-    ncontr = -2; // (x,y,z) = (0,0,z_fromSPD) 
-  if(err[0]<1. && esdEvent->GetVertex()->GetNContributors()<=0) 
-    ncontr = -3; // (x,y,z) = (x_mean,y_mean,0)
-  if(err[0]<1. && esdEvent->GetVertex()->GetNContributors()>0) 
-    ncontr = -4; // (x,y,z) = (x_mean,y_mean,z_fromSPD)
-  fCurrentVertex = 0;
+  pos[2] = fNominalPos[2];
+  err[2] = TMath::Sqrt(fNominalCov[5]);
+  Int_t    ncontr = (err[0]>1. ? -1 : -3);
+  if(fCurrentVertex) { delete fCurrentVertex; fCurrentVertex=0; }
   fCurrentVertex = new AliESDVertex(pos,err);
   fCurrentVertex->SetNContributors(ncontr);
 
-  Double_t tp[3];
-  esdEvent->GetVertex()->GetTruePos(tp);
-  fCurrentVertex->SetTruePos(tp);
   if(fConstraint) {
     fCurrentVertex->SetTitle("VertexerTracksWithConstraint");
   } else {
     fCurrentVertex->SetTitle("VertexerTracksNoConstraint");
   }
 
+  if(!fTrkArraySel.IsEmpty()) fTrkArraySel.Delete(); 
+  if(fIdSel) {delete [] fIdSel; fIdSel=NULL;}
+  if(fTrksToSkip) {delete [] fTrksToSkip; fTrksToSkip=NULL;}
+
   return;
 }
 //---------------------------------------------------------------------------
@@ -872,38 +1223,37 @@ void AliVertexerTracks::VertexFinder(Int_t optUseWeights)
   Double_t initPos[3];
   initPos[2] = 0.;
   for(Int_t i=0;i<2;i++)initPos[i]=fNominalPos[i];
-  Int_t nacc = (Int_t)fTrkArray.GetEntriesFast();
+  Int_t nacc = (Int_t)fTrkArraySel.GetEntriesFast();
   Double_t aver[3]={0.,0.,0.};
   Double_t aversq[3]={0.,0.,0.};
   Double_t sigmasq[3]={0.,0.,0.};
   Double_t sigma=0;
   Int_t ncombi = 0;
-  AliESDtrack *track1;
-  AliESDtrack *track2;
+  AliExternalTrackParam *track1;
+  AliExternalTrackParam *track2;
   Double_t pos[3],dir[3]; 
   Double_t alpha,mindist;
-  Double_t field=GetField();
 
   for(Int_t i=0; i<nacc; i++){
-    track1 = (AliESDtrack*)fTrkArray.At(i);
+    track1 = (AliExternalTrackParam*)fTrkArraySel.At(i);
     alpha=track1->GetAlpha();
     mindist = TMath::Cos(alpha)*fNominalPos[0]+TMath::Sin(alpha)*fNominalPos[1];
-    track1->GetXYZAt(mindist,field,pos);
-    track1->GetPxPyPzAt(mindist,field,dir);
+    track1->GetXYZAt(mindist,GetFieldkG(),pos);
+    track1->GetPxPyPzAt(mindist,GetFieldkG(),dir);
     AliStrLine *line1 = new AliStrLine(pos,dir); 
 
    //    AliStrLine *line1 = new AliStrLine();
-   //    track1->ApproximateHelixWithLine(mindist,field,line1);
+   //    track1->ApproximateHelixWithLine(mindist,GetFieldkG(),line1);
    
     for(Int_t j=i+1; j<nacc; j++){
-      track2 = (AliESDtrack*)fTrkArray.At(j);
+      track2 = (AliExternalTrackParam*)fTrkArraySel.At(j);
       alpha=track2->GetAlpha();
       mindist = TMath::Cos(alpha)*fNominalPos[0]+TMath::Sin(alpha)*fNominalPos[1];
-      track2->GetXYZAt(mindist,field,pos);
-      track2->GetPxPyPzAt(mindist,field,dir);
+      track2->GetXYZAt(mindist,GetFieldkG(),pos);
+      track2->GetPxPyPzAt(mindist,GetFieldkG(),dir);
       AliStrLine *line2 = new AliStrLine(pos,dir); 
     //      AliStrLine *line2 = new AliStrLine();
-    //  track2->ApproximateHelixWithLine(mindist,field,line2);
+    //  track2->ApproximateHelixWithLine(mindist,GetFieldkG(),line2);
       Double_t distCA=line2->GetDCA(line1);
       //printf("%d   %d   %f\n",i,j,distCA);
        if(fDCAcut<=0 || (fDCAcut>0&&distCA<fDCAcut)){
@@ -964,25 +1314,34 @@ void AliVertexerTracks::VertexFinder(Int_t optUseWeights)
   fVert.SetNContributors(ncombi);
 }
 //---------------------------------------------------------------------------
-void AliVertexerTracks::VertexFitter(Bool_t useConstraint) 
+void AliVertexerTracks::VertexFitter() 
 {
 //
 // The optimal estimate of the vertex position is given by a "weighted 
-// average of tracks positions"
+// average of tracks positions".
 // Original method: V. Karimaki, CMS Note 97/0051
 //
+  Bool_t useConstraint = fConstraint;
   Double_t initPos[3];
-  fVert.GetXYZ(initPos);
-  Int_t arrEntries = (Int_t)fTrkArray.GetEntries();
-  if(arrEntries==1) useConstraint=kTRUE;
-  if(fDebug) { 
-    printf(" VertexFitter(): start\n");
-    printf(" Number of tracks in array: %d\n",(Int_t)fTrkArray.GetEntriesFast());
-    printf(" Minimum # tracks required in fit: %d\n",fMinTracks);
-    printf("Vertex position after finder: %f,%f,%f\n",initPos[0],initPos[1],initPos[2]);
-    if(useConstraint) printf(" This vertex will be used in fit: (%f+-%f,%f+-%f)\n",fNominalPos[0],TMath::Sqrt(fNominalCov[0]),fNominalPos[1],TMath::Sqrt(fNominalCov[2])); 
+  if(!fOnlyFitter) {
+    fVert.GetXYZ(initPos);
+  } else {
+    initPos[0]=fNominalPos[0];
+    initPos[1]=fNominalPos[1];
+    initPos[2]=fNominalPos[2];
   }
 
+  Int_t nTrksSel = (Int_t)fTrkArraySel.GetEntries();
+  if(nTrksSel==1) useConstraint=kTRUE;
+  AliDebug(1,"--- VertexFitter(): start");
+  AliDebug(1,Form(" Number of tracks in array: %d\n",nTrksSel));
+  AliDebug(1,Form(" Minimum # tracks required in fit: %d\n",fMinTracks));
+  AliDebug(1,Form(" Vertex position after finder: %f,%f,%f\n",initPos[0],initPos[1],initPos[2]));
+  if(useConstraint) AliDebug(1,Form(" This vertex will be used in fit: (%f+-%f,%f+-%f)\n",fNominalPos[0],TMath::Sqrt(fNominalCov[0]),fNominalPos[1],TMath::Sqrt(fNominalCov[2]))); 
+
+  // special treatment for few-tracks fits (e.g. secondary vertices)
+  Bool_t uUi3by3 = kFALSE; if(nTrksSel<5 && !useConstraint) uUi3by3 = kTRUE;
+
   Int_t i,j,k,step=0;
   TMatrixD rv(3,1);
   TMatrixD vV(3,3);
@@ -990,9 +1349,9 @@ void AliVertexerTracks::VertexFitter(Bool_t useConstraint)
   rv(1,0) = initPos[1];
   rv(2,0) = 0.;
   Double_t xlStart,alpha;
-  Int_t nUsedTrks;
+  Int_t nTrksUsed;
   Double_t chi2,chi2i,chi2b;
-  AliESDtrack *t = 0;
+  AliExternalTrackParam *t = 0;
   Int_t failed = 0;
 
   // initial vertex covariance matrix
@@ -1018,9 +1377,11 @@ void AliVertexerTracks::VertexFitter(Bool_t useConstraint)
   // 1st - estimate of vtx using all tracks
   // 2nd - estimate of global chi2
   for(step=0; step<2; step++) {
-    if(fDebug) printf(" step = %d\n",step);
+    AliDebug(1,Form(" step = %d\n",step));
     chi2 = 0.;
-    nUsedTrks = 0;
+    nTrksUsed = 0;
+
+    if(step==1) { initPos[0]=rv(0,0); initPos[0]=rv(1,0); }
 
     TMatrixD sumWiri(3,1);
     TMatrixD sumWi(3,3);
@@ -1044,25 +1405,22 @@ void AliVertexerTracks::VertexFitter(Bool_t useConstraint)
       chi2 += chi2b;
     }
 
-
     // loop on tracks  
-    for(k=0; k<arrEntries; k++) {
+    for(k=0; k<nTrksSel; k++) {
       // get track from track array
-      t = (AliESDtrack*)fTrkArray.At(k);
+      t = (AliExternalTrackParam*)fTrkArraySel.At(k);
       alpha = t->GetAlpha();
       xlStart = initPos[0]*TMath::Cos(alpha)+initPos[1]*TMath::Sin(alpha);
       // to vtxSeed (from finder)
-      t->AliExternalTrackParam::PropagateTo(xlStart,AliTracker::GetBz());   
+      t->PropagateTo(xlStart,GetFieldkG());   
  
-
       // vector of track global coordinates
       TMatrixD ri(3,1);
       // covariance matrix of ri
       TMatrixD wWi(3,3);
 
       // get space point from track
-      if(!TrackToPoint(t,ri,wWi)) continue;
-
+      if(!TrackToPoint(t,ri,wWi,uUi3by3)) continue;
       TMatrixD wWiri(wWi,TMatrixD::kMult,ri); 
 
       // track chi2
@@ -1078,36 +1436,32 @@ void AliVertexerTracks::VertexFitter(Bool_t useConstraint)
       sumWiri += wWiri;
       sumWi   += wWi;
 
-      nUsedTrks++;
+      nTrksUsed++;
     } // end loop on tracks
 
-    if(nUsedTrks < fMinTracks) {
+    if(nTrksUsed < fMinTracks) {
       failed=1;
       continue;
     }
 
     Double_t determinant = sumWi.Determinant();
-    //cerr<<" determinant: "<<determinant<<endl;
-    if(determinant < 100.)  { 
-      printf("det(V) = 0\n");       
+    if(determinant < fMinDetFitter)  { 
+      AliDebug(1,Form("det(V) = %f (<%f)\n",determinant,fMinDetFitter));       
       failed=1;
       continue;
     }
 
-    // inverted of weights matrix
-    TMatrixD invsumWi(TMatrixD::kInverted,sumWi);
-    vV = invsumWi;
-     
-    // position of primary vertex
-    rv.Mult(vV,sumWiri);
-
+    if(step==0) { 
+      // inverted of weights matrix
+      TMatrixD invsumWi(TMatrixD::kInverted,sumWi);
+      vV = invsumWi;
+      // position of primary vertex
+      rv.Mult(vV,sumWiri);
+    }
   } // end loop on the 2 steps
 
-  // delete t;
-
   if(failed) { 
-    if(fDebug) printf("TooFewTracks\n");
-    fCurrentVertex = new AliESDVertex(0.,0.,-1);
+    TooFewTracks();
     return; 
   }
 
@@ -1123,34 +1477,40 @@ void AliVertexerTracks::VertexFitter(Bool_t useConstraint)
   covmatrix[4] = vV(1,2);
   covmatrix[5] = vV(2,2);
   
+  // for correct chi2/ndf, count constraint as additional "track"
+  if(fConstraint) nTrksUsed++;
   // store data in the vertex object
-  fCurrentVertex = new AliESDVertex(position,covmatrix,chi2,nUsedTrks);
+  if(fCurrentVertex) { delete fCurrentVertex; fCurrentVertex=0; }
+  fCurrentVertex = new AliESDVertex(position,covmatrix,chi2,nTrksUsed);
 
-  if(fDebug) {
-    printf(" VertexFitter(): finish\n");
-    printf(" rv = ( %f , %f , %f )\n\n",rv(0,0),rv(1,0),rv(2,0));
-    fCurrentVertex->PrintStatus();
-  }
+  AliDebug(1," Vertex after fit:");
+  AliDebug(1,Form("xyz: %f %f %f; nc %d",fCurrentVertex->GetXv(),fCurrentVertex->GetYv(),fCurrentVertex->GetZv(),fCurrentVertex->GetNContributors()));
+  AliDebug(1,"--- VertexFitter(): finish\n");
 
   return;
 }
 //----------------------------------------------------------------------------
-AliESDVertex* AliVertexerTracks::VertexForSelectedTracks(TTree *trkTree,Bool_t optUseFitter,Bool_t optPropagate) 
+AliESDVertex* AliVertexerTracks::VertexForSelectedTracks(TObjArray *trkArray,
+                                                        UShort_t *id,
+                                                        Bool_t optUseFitter,
+                                                        Bool_t optPropagate) 
 {
 //
-// Return vertex from tracks in trkTree
+// Return vertex from tracks (AliExternalTrackParam) in array
 //
-
+  fCurrentVertex = 0;
   SetConstraintOff();
 
   // get tracks and propagate them to initial vertex position
-  Int_t nTrksPrep = PrepareTracks(*trkTree,0);
-  if(nTrksPrep <  TMath::Max(2,fMinTracks) ) {
-    if(fDebug) printf("TooFewTracks\n");
-    fCurrentVertex = new AliESDVertex(0.,0.,-1);
+  fIdSel = new UShort_t[(Int_t)trkArray->GetEntriesFast()];
+  Int_t nTrksSel = PrepareTracks(*trkArray,id,0);
+  if(nTrksSel <  TMath::Max(2,fMinTracks)) {
+    TooFewTracks();
     return fCurrentVertex;
   }
  
+  // vertex finder
   switch (fAlgo) {
     case 1: StrLinVertexFinderMinDist(1); break;
     case 2: StrLinVertexFinderMinDist(0); break;
@@ -1159,71 +1519,72 @@ AliESDVertex* AliVertexerTracks::VertexForSelectedTracks(TTree *trkTree,Bool_t o
     case 5: VertexFinder(0);              break;
     default: printf("Wrong algorithm\n"); break;  
   }
-  
-  if(fDebug) printf(" Vertex finding completed\n");
+  AliDebug(1," Vertex finding completed\n");
 
   // vertex fitter
-  if(optUseFitter){
-    VertexFitter(fConstraint);
-    if(fDebug) printf(" Vertex fit completed\n");
-  }else{
+  if(optUseFitter) {
+    VertexFitter();
+  } else {
     Double_t position[3]={fVert.GetXv(),fVert.GetYv(),fVert.GetZv()};
-    Double_t covmatrix[6]={0.,0.,0.,0.,0.,0.};
+    Double_t covmatrix[6];
+    fVert.GetCovMatrix(covmatrix);
     Double_t chi2=99999.;
-    Int_t    nUsedTrks=fVert.GetNContributors();
-    fCurrentVertex = new AliESDVertex(position,covmatrix,chi2,nUsedTrks);    
+    Int_t    nTrksUsed=fVert.GetNContributors();
+    fCurrentVertex = new AliESDVertex(position,covmatrix,chi2,nTrksUsed);    
   }
   fCurrentVertex->SetDispersion(fVert.GetDispersion());
 
 
   // set indices of used tracks and propagate track to found vertex
   UShort_t *indices = 0;
-  AliESDtrack *eta = 0;
+  Double_t d0z0[2],covd0z0[3];
+  AliExternalTrackParam *t = 0;
   if(fCurrentVertex->GetNContributors()>0) {
     indices = new UShort_t[fCurrentVertex->GetNContributors()];
-    for(Int_t jj=0;jj<(Int_t)fTrkArray.GetEntriesFast();jj++) {
-      eta = (AliESDtrack*)fTrkArray.At(jj);
-      indices[jj] = (UShort_t)eta->GetID();
-      if(optPropagate&&optUseFitter){
+    for(Int_t jj=0; jj<(Int_t)fTrkArraySel.GetEntriesFast(); jj++) {
+      indices[jj] = fIdSel[jj];
+      t = (AliExternalTrackParam*)fTrkArraySel.At(jj);
+      if(optPropagate && optUseFitter) {
        if(TMath::Sqrt(fCurrentVertex->GetXv()*fCurrentVertex->GetXv()+fCurrentVertex->GetYv()*fCurrentVertex->GetYv())<3.) {
-         eta->RelateToVertex(fCurrentVertex,GetField(),100.);
-         if(fDebug) printf("Track %d propagated to found vertex\n",jj);
-       }else{
+         t->PropagateToDCA(fCurrentVertex,GetFieldkG(),100.,d0z0,covd0z0);
+         AliDebug(1,Form("Track %d propagated to found vertex",jj));
+       } else {
          AliWarning("Found vertex outside beam pipe!");
        }
       }
     }
     fCurrentVertex->SetIndices(fCurrentVertex->GetNContributors(),indices);
   }
-  delete [] indices;
-  fTrkArray.Delete();
+
+  // clean up
+  delete [] indices; indices=NULL;
+  delete [] fIdSel; fIdSel=NULL;
+  fTrkArraySel.Delete();
   
   return fCurrentVertex;
 }
 //----------------------------------------------------------------------------
-AliESDVertex* AliVertexerTracks::VertexForSelectedTracks(TObjArray *trkArray,Bool_t optUseFitter, Bool_t optPropagate) 
+AliESDVertex* AliVertexerTracks::VertexForSelectedESDTracks(TObjArray *trkArray,
+                                                        Bool_t optUseFitter,
+                                                        Bool_t optPropagate) 
 {
 //
-// Return vertex from array of tracks
+// Return vertex from array of ESD tracks
 //
 
-  // get tracks and propagate them to initial vertex position
-  Int_t nTrks = trkArray->GetEntriesFast();
-  if(nTrks < TMath::Max(2,fMinTracks) ) {
-    if(fDebug) printf("TooFewTracks\n");
-    fCurrentVertex = new AliESDVertex(0.,0.,-1);
-    return fCurrentVertex;
-  }
-  TTree *trkTree = new TTree("TreeT","tracks");
-  AliESDtrack *esdTrack = 0;
-  trkTree->Branch("tracks","AliESDtrack",&esdTrack);
+  Int_t nTrks = (Int_t)trkArray->GetEntriesFast();
+  UShort_t *id = new UShort_t[nTrks];
+
+  AliESDtrack *esdt = 0;
   for(Int_t i=0; i<nTrks; i++){
-    esdTrack = (AliESDtrack*)trkArray->At(i);
-    trkTree->Fill();
+    esdt = (AliESDtrack*)trkArray->At(i);
+    id[i] = (UShort_t)esdt->GetID();
   }
     
-  AliESDVertex *vtx =  VertexForSelectedTracks(trkTree,optUseFitter,optPropagate);
-  delete trkTree;
-  return vtx;
+  VertexForSelectedTracks(trkArray,id,optUseFitter,optPropagate);
+
+  delete [] id; id=NULL;
+
+  return fCurrentVertex;
 }
 //--------------------------------------------------------------------------