]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - ITS/UPGRADE/AliITSUTrackerGlo.cxx
Clean unfinished hypotheses before running afterburner passes
[u/mrichter/AliRoot.git] / ITS / UPGRADE / AliITSUTrackerGlo.cxx
index 171d96619930bc1049f93f1f94d2463bdbbcb7d1..9a8c00053e4499b3d643573d798c7f4c5a49468e 100644 (file)
 #include "AliITSUReconstructor.h"
 #include "AliITSReconstructor.h"
 #include "AliITSUSeed.h"
-#include "AliITSUAux.h"
 #include "AliITSUClusterPix.h"
+#include "AliITSUGeomTGeo.h"
+#include "AliCodeTimer.h"
+#include "AliRefArray.h"
 using namespace AliITSUAux;
 using namespace TMath;
 
@@ -58,20 +60,29 @@ AliITSUTrackerGlo::AliITSUTrackerGlo(AliITSUReconstructor* rec)
   ,fCountITSin(0)
   ,fCountITSout(0)
   ,fCountITSrefit(0)
+  ,fNTracksESD(0)
   ,fHypStore(100)
+  ,fLayerMaxCandidates(1000)
+  ,fLayerCandidates(0)
   ,fNBranchesAdded(0)
   ,fNCandidatesAdded(0)
   ,fCurrHyp(0)
+  ,fWorkHyp(0)
   ,fSeedsPool("AliITSUSeed",0)
   ,fFreeSeedsID(0)
+  ,fESDIndex(0)
   ,fNFreeSeeds(0)
   ,fLastSeedID(0)
+  ,fNLrActive(0)
   ,fDefTrackConds(0)
   ,fCurrTrackCond(0)
-  ,fTrackPhase(-1)
-  ,fClInfo(0)
-#ifdef  _FILL_CONTROL_HISTOS_
-  ,fCHistoArr(0)
+  ,fCurrActLrID(-1)
+  ,fCurrLayer(0)
+  ,fTrackPhaseID(-1)
+  ,fCurrPassID(-1)
+#ifdef  _ITSU_TUNING_MODE_
+  ,fCHistoArrCorr(0)
+  ,fCHistoArrFake(0)
 #endif
 {
   // Default constructor
@@ -83,19 +94,28 @@ AliITSUTrackerGlo::~AliITSUTrackerGlo()
 {
  // Default destructor
  //  
-  delete[] fClInfo;
+  delete[] fLayerCandidates;
+  if (fWorkHyp) fWorkHyp->SetTPCSeed(0); // this hypothesis does not own the seed
+  delete fWorkHyp;
   //
-#ifdef  _FILL_CONTROL_HISTOS_
-  if (fCHistoArr) {
+#ifdef  _ITSU_TUNING_MODE_
+  if (fCHistoArrCorr || fCHistoArrFake) {
     TFile* ctrOut = TFile::Open("itsuControlHistos.root","recreate");
     ctrOut->cd();
     AliInfo("Storing control histos");
-    fCHistoArr->Print();
     //    ctrOut->WriteObject(fCHistoArr,"controlH","kSingleKey");
-    fCHistoArr->Write();
+    if (fCHistoArrCorr) {
+      fCHistoArrCorr->Write();
+      delete fCHistoArrCorr;
+    }
+    if (fCHistoArrFake) {
+      fCHistoArrFake->Write();
+      delete fCHistoArrFake;
+    }
     ctrOut->Close();
     delete ctrOut;
-    fCHistoArr = 0;
+    fCHistoArrCorr = 0;
+    fCHistoArrFake = 0;    
   }
 #endif 
   //
@@ -107,11 +127,15 @@ void AliITSUTrackerGlo::Init(AliITSUReconstructor* rec)
   // init with external reconstructor
   //
   fITS = rec->GetITSInterface();
-  int nLr = fITS->GetNLayersActive();
-  fClInfo = new Int_t[nLr<<1];
+  fNLrActive = fITS->GetNLayersActive();
+  fWorkHyp = new AliITSUTrackHyp(fNLrActive);
   //
+  if (fLayerMaxCandidates<1) fLayerMaxCandidates = 1000;
+  fLayerCandidates = new AliITSUSeed*[fLayerMaxCandidates];
   fSeedsPool.ExpandCreateFast(1000); // RS TOCHECK
   fFreeSeedsID.Set(1000);
+  fESDIndex.Set(1000);
+  
   //
 }
 
@@ -119,14 +143,13 @@ void AliITSUTrackerGlo::Init(AliITSUReconstructor* rec)
 void AliITSUTrackerGlo::CreateDefaultTrackCond()
 {
   // creates default tracking conditions to be used when recoparam does not provide them
-  int nLr = fITS->GetNLayersActive();
-  fClInfo = new Int_t[nLr<<1];
-  //
+
   AliITSUTrackCond* cond = new AliITSUTrackCond();
   //
-  cond->SetNLayers(fITS->GetNLayersActive());
-  cond->AddNewCondition(nLr);
-  cond->AddGroupPattern( 0xffff ); // require all layers hit
+  cond->SetNLayers(fNLrActive);
+  cond->AddNewCondition(fNLrActive);
+  cond->AddGroupPattern( 0xffff, fNLrActive ); // require all layers hit
+  cond->Init();
   //
   fDefTrackConds.AddLast(cond);
   //
@@ -140,12 +163,16 @@ void AliITSUTrackerGlo::CreateDefaultTrackCond()
 Int_t AliITSUTrackerGlo::Clusters2Tracks(AliESDEvent *esdEv)
 {
   //
+  AliCodeTimerAuto("",0);
   SetTrackingPhase(kClus2Tracks);
   //
-#ifdef  _FILL_CONTROL_HISTOS_
-  if (!fCHistoArr) BookControlHistos();
+#ifdef  _ITSU_TUNING_MODE_
+  if (!fCHistoArrCorr) fCHistoArrCorr = BookControlHistos("Corr");
+  if (!fCHistoArrFake) fCHistoArrFake = BookControlHistos("Fake");
 #endif
-
+  static int evID = 0;
+  static TArrayF esdTrPt(fESDIndex.GetSize()); 
+  //
   TObjArray *trackConds = 0;
   //
   fCountProlongationTrials = 0;
@@ -154,8 +181,8 @@ Int_t AliITSUTrackerGlo::Clusters2Tracks(AliESDEvent *esdEv)
   fCountITSrefit = 0;
   //
   ResetSeedsPool();
-  int nTrESD = esdEv->GetNumberOfTracks();
-  AliInfo(Form("Will try to find prolongations for %d tracks",nTrESD));
+  fNTracksESD = esdEv->GetNumberOfTracks();
+  AliInfo(Form("Will try to find prolongations for %d tracks",fNTracksESD));
   int nTrackCond = AliITSUReconstructor::GetRecoParam()->GetNTrackingConditions();
   if (nTrackCond<1) {
     if (!fDefTrackConds.GetEntriesFast()) {
@@ -173,22 +200,57 @@ Int_t AliITSUTrackerGlo::Clusters2Tracks(AliESDEvent *esdEv)
     first = kFALSE;
   }
   fHypStore.Delete();
-  if (fHypStore.GetSize()<nTrESD) fHypStore.Expand(nTrESD+100);
+  if (fHypStore.GetSize()<fNTracksESD) fHypStore.Expand(fNTracksESD+100);
   //
   fITS->ProcessClusters();
   //
+#ifdef  _ITSU_TUNING_MODE_
   FlagSplitClusters(); // tmp RS
+#endif
+  //
+  // the tracks will be reconstructed in decreasing pt order, sort them
+  if (fESDIndex.GetSize()<fNTracksESD) {
+    fESDIndex.Set(fNTracksESD+200);
+    esdTrPt.Set(fNTracksESD+200);
+  }
+  int* esdTrackIndex = fESDIndex.GetArray();
+  float* trPt = esdTrPt.GetArray();
+  for (int itr=fNTracksESD;itr--;) {
+    AliESDtrack* esdTr = esdEv->GetTrack(itr);
+    esdTr->SetStatus(AliESDtrack::kITSupg);   // Flag all tracks as participating in the ITSup reco
+    trPt[itr] = esdTr->Pt();
+  }
+  Sort(fNTracksESD,trPt,esdTrackIndex,kTRUE);    
   //
   for (int icnd=0;icnd<nTrackCond;icnd++) {
+    fCurrPassID = icnd;
     fCurrTrackCond = (AliITSUTrackCond*)trackConds->UncheckedAt(icnd);
+    if (!fCurrTrackCond->IsInitDone()) fCurrTrackCond->Init();
     // select ESD tracks to propagate
-    for (int itr=0;itr<nTrESD;itr++) {
-      fCurrESDtrack = esdEv->GetTrack(itr);
+    for (int itr=0;itr<fNTracksESD;itr++) {
+      int trID = esdTrackIndex[itr];
+      fCurrESDtrack = esdEv->GetTrack(trID);
       fCurrESDtrMClb = fCurrESDtrack->GetLabel();
       //
-      if (!NeedToProlong(fCurrESDtrack)) continue;  // are we interested in this track?
-      AliDebug(+1,Form("Processing track %d | M=%.3f Pt=%.3f | MCLabel: %d",itr,fCurrESDtrack->GetMass(kTRUE),fCurrESDtrack->Pt(),fCurrESDtrMClb));//RS
-      FindTrack(fCurrESDtrack, itr);
+      
+      if (!NeedToProlong(fCurrESDtrack,trID)) continue;  // are we interested in this track?
+      /*
+       // if specific tracks should be checked, create a global array int wtc[] = {evITS*10000+trID, ...};
+      Bool_t dbg = kFALSE;
+      int nwtc = sizeof(wtc)/sizeof(int);
+
+      for (int k=0;k<nwtc;k++) {
+       if (wtc[k]==evID*10000+trID) {
+         dbg = kTRUE;
+         printf("At esdTr: %d MC: %d\n",wtc[k],fCurrESDtrMClb);
+         break;
+       }
+      }
+      AliLog::SetClassDebugLevel("AliITSUTrackerGlo",dbg ? 10:0);
+      */
+
+      AliDebug(1,Form("Processing track %d(esd%d) | M=%.3f Pt=%.3f | MCLabel: %d",itr,trID,fCurrESDtrack->GetMass(kTRUE),fCurrESDtrack->Pt(),fCurrESDtrMClb));//RS
+      FindTrack(fCurrESDtrack, trID);
     }   
     //
     if (AliDebugLevelClass()>+2) {
@@ -196,9 +258,15 @@ Int_t AliITSUTrackerGlo::Clusters2Tracks(AliESDEvent *esdEv)
       fHypStore.Print();
     }
     FinalizeHypotheses();
+#ifdef  _ITSU_TUNING_MODE_
+    CheckClusterUsage(); //!!RS
+#endif
+    //
+    //AliLog::SetClassDebugLevel("AliITSUTrackerGlo",0);     // in case wtc array was defined, uncomment this
   }
   //
-  AliInfo(Form("%d ITSin for %d tried TPC seeds out of %d ESD tracks\n",fCountITSin,fCountProlongationTrials,nTrESD));
+  AliInfo(Form("%d ITSin for %d tried TPC seeds out of %d ESD tracks\n",fCountITSin,fCountProlongationTrials,fNTracksESD));
+  evID++;
   return 0;
 }
 
@@ -207,19 +275,19 @@ Int_t AliITSUTrackerGlo::PropagateBack(AliESDEvent *esdEv)
 {
   //
   // Do outward fits in ITS
+  AliCodeTimerAuto("",0);
   //
   SetTrackingPhase(kPropBack);
-  int nTrESD = esdEv->GetNumberOfTracks();
-  AliDebug(1,Form("Will propagate back %d tracks",nTrESD));
+  fNTracksESD = esdEv->GetNumberOfTracks();
+  AliDebug(1,Form("Will propagate back %d tracks",fNTracksESD));
   //
   double bz0 = GetBz();
   Double_t xyzTrk[3],xyzVtx[3]={GetX(),GetY(),GetZ()};
-  AliITSUTrackHyp dummyTr,*currTr=0;
+  AliITSUTrackHyp dummyTr;
   const double kWatchStep=10.; // for larger steps watch arc vs segment difference
   Double_t times[AliPID::kSPECIES];
   //
-  //
-  for (int itr=0;itr<nTrESD;itr++) {
+  for (int itr=0;itr<fNTracksESD;itr++) {
     fCurrESDtrack = esdEv->GetTrack(itr);
     fCurrESDtrMClb = fCurrESDtrack->GetLabel();
     // Start time integral and add distance from current position to vertex 
@@ -257,25 +325,28 @@ Int_t AliITSUTrackerGlo::PropagateBack(AliESDEvent *esdEv)
       continue;
     }
     //
-    currTr = GetTrackHyp(itr);
-    currTr->StartTimeIntegral();
-    currTr->AddTimeStep(dst);
-    //    printf("Before resetCov: "); currTr->AliExternalTrackParam::Print();
-    currTr->ResetCovariance(10000);
-    if (RefitTrack(currTr,fITS->GetRMax())) { // propagate to exit from the ITS/TPC screen
-      UpdateESDTrack(currTr,AliESDtrack::kITSout);
-      fCountITSout++;
+    fCurrHyp = GetTrackHyp(itr);
+    fCurrMass = fCurrHyp->GetMass();
+    fCurrHyp->StartTimeIntegral();
+    fCurrHyp->AddTimeStep(dst);
+    fCurrHyp->ResetCovariance(10000);
+    double chi2 = RefitTrack(fCurrHyp,fITS->GetRMax());
+    if (chi2>0) { // propagate to exit from the ITS/TPC screen
+      int ndf = fCurrHyp->GetWinner()->GetNLayersHit()*2-5;
+      if (ndf>0) chi2 /= ndf;
+      fCurrHyp->SetChi2(chi2);
+      UpdateESDTrack(fCurrHyp,AliESDtrack::kITSout);
     }
     else {
       AliDebug(2,Form("Refit Failed for track %d | ESDtrack#%d (MClb:%d)",itr,fCurrESDtrack->GetID(),fCurrESDtrMClb));
-      //currTr->AliExternalTrackParam::Print();
-      //currTr->GetWinner()->Print();
+      //fCurrHyp->AliExternalTrackParam::Print();
+      //fCurrHyp->GetWinner()->Print();
     }
     //
   }
   //
   AliInfo(Form("%d ITSout in %d ITSin tracks for %d tried TPC seeds out of %d ESD tracks\n",
-              fCountITSout,fCountITSin,fCountProlongationTrials,nTrESD));
+              fCountITSout,fCountITSin,fCountProlongationTrials,fNTracksESD));
   //
   return 0;
 }
@@ -285,15 +356,15 @@ Int_t AliITSUTrackerGlo::RefitInward(AliESDEvent *esdEv)
 {
   //
   // refit the tracks inward, using current cov.matrix
+  AliCodeTimerAuto("",0);
   //
   SetTrackingPhase(kRefitInw);
-  Int_t nTrESD = esdEv->GetNumberOfTracks();
+  fNTracksESD = esdEv->GetNumberOfTracks();
   //  AliLog::SetClassDebugLevel("AliITSUTrackerGlo",10);
 
-  AliDebug(1,Form("Will refit inward %d tracks",nTrESD));
-  AliITSUTrackHyp *currTr=0;
+  AliDebug(1,Form("Will refit inward %d tracks",fNTracksESD));
   //
-  for (int itr=0;itr<nTrESD;itr++) {
+  for (int itr=0;itr<fNTracksESD;itr++) {
     fCurrESDtrack = esdEv->GetTrack(itr);
     fCurrESDtrMClb = fCurrESDtrack->GetLabel();
     // Start time integral and add distance from current position to vertex 
@@ -302,11 +373,14 @@ Int_t AliITSUTrackerGlo::RefitInward(AliESDEvent *esdEv)
     if (   trStat & AliESDtrack::kITSrefit ) continue; // already done
     if (  (trStat & AliESDtrack::kTPCout) && !(trStat & AliESDtrack::kTPCrefit) ) continue;
     //
-    currTr = GetTrackHyp(itr);
-    currTr->AliExternalTrackParam::operator=(*fCurrESDtrack);  // fetch current ESDtrack kinematics
-    if (RefitTrack(currTr,fITS->GetRMin())) { // propagate up to inside radius of the beam pipe
-      UpdateESDTrack(currTr,AliESDtrack::kITSrefit);
-      fCountITSrefit++;
+    fCurrHyp = GetTrackHyp(itr);
+    fCurrHyp->AliExternalTrackParam::operator=(*fCurrESDtrack);  // fetch current ESDtrack kinematics
+    fCurrMass = fCurrHyp->GetMass();
+    //
+    double chi2 = RefitTrack(fCurrHyp,fITS->GetRMin());
+    if (chi2>0) { // propagate up to inside radius of the beam pipe      
+      fCurrHyp->SetChi2(chi2);
+      UpdateESDTrack(fCurrHyp,AliESDtrack::kITSrefit);
     }
     else {
       AliDebug(2,Form("Refit Failed for track %d |ESDtrack#%d (MClb:%d)",itr,fCurrESDtrack->GetID(),fCurrESDtrMClb));
@@ -314,7 +388,7 @@ Int_t AliITSUTrackerGlo::RefitInward(AliESDEvent *esdEv)
   }    
   //
   AliInfo(Form("%d ITSrefit in %d ITSout in %d ITSin tracks for %d tried TPC seeds out of %d ESD tracks\n",
-              fCountITSrefit,fCountITSout,fCountITSin,fCountProlongationTrials,nTrESD));
+              fCountITSrefit,fCountITSout,fCountITSin,fCountProlongationTrials,fNTracksESD));
   //
   //  AliLog::SetClassDebugLevel("AliITSUTrackerGlo",0);
   return 0;
@@ -349,11 +423,21 @@ AliCluster * AliITSUTrackerGlo::GetCluster(Int_t /*index*/) const
 } 
 
 //_________________________________________________________________________
-Bool_t AliITSUTrackerGlo::NeedToProlong(AliESDtrack* esdTr)
+Bool_t AliITSUTrackerGlo::NeedToProlong(AliESDtrack* esdTr, Int_t esdID)
 {
   // do we need to match this track to ITS?
   //
   static double bz = GetBz();
+  //
+  // is it already prolonged
+  if (esdTr->IsOn(AliESDtrack::kITSin)) return kFALSE;
+  AliITSUTrackHyp* hyp = GetTrackHyp(esdID); // in case there is unfinished hypothesis from prev.pass, clean it
+  if (hyp) {
+    CleanHypothesis(hyp);
+    if (hyp->GetSkip()) return kFALSE; // need to skip this
+    return kTRUE;
+  }
+  //
   if (!esdTr->IsOn(AliESDtrack::kTPCin) ||
       esdTr->IsOn(AliESDtrack::kTPCout) ||
       esdTr->IsOn(AliESDtrack::kITSin)  ||
@@ -368,6 +452,7 @@ Bool_t AliITSUTrackerGlo::NeedToProlong(AliESDtrack* esdTr)
        && (Abs(dtz[0])>AliITSUReconstructor::GetRecoParam()->GetMaxDForProlongation() ||
           Abs(dtz[1])>AliITSUReconstructor::GetRecoParam()->GetMaxDZForProlongation())) return kFALSE;
   //
+  //  if (esdTr->Pt()<3) return kFALSE;//RS
   return kTRUE;
 }
 
@@ -379,60 +464,78 @@ void AliITSUTrackerGlo::FindTrack(AliESDtrack* esdTr, Int_t esdID)
   AliITSUSeed seedUC;  // copy of the seed from the upper layer
   AliITSUSeed seedT;   // transient seed between the seedUC and new prolongation hypothesis
   //
-  if (!InitHypothesis(esdTr,esdID)) return;  // initialize prolongations hypotheses tree
+  //  AliLog::SetClassDebugLevel("AliITSUTrackerGlo",10);
+  AliITSUTrackHyp* hypTr = InitHypothesis(esdTr,esdID);  // initialize prolongations hypotheses tree
+  if (!hypTr || hypTr->GetSkip()) return;
+  //
+  double bz = GetBz();
+  fCurrHyp = fWorkHyp;
+  fCurrHyp->InitFrom(hypTr);
   //
   AliITSURecoSens *hitSens[AliITSURecoSens::kNNeighbors+1];
   //
-  TObjArray clArr; // container for transfer of clusters matching to seed
+  int ilaUp = fNLrActive;     // previous active layer really checked (some may be excluded!)
   //
-  int nLrActive = fITS->GetNLayersActive();
-  for (int ila=nLrActive;ila--;) {
-    int ilaUp = ila+1;                         // prolong seeds from layer above
+  for (int ila=fNLrActive;ila--;ilaUp=fCurrActLrID) {
+    if (fCurrTrackCond->IsLayerExcluded(ila)) continue;
+    fCurrActLrID = ila;
+    fCurrLayer = fITS->GetLayerActive(ila);
+    Bool_t noClSharing = fCurrTrackCond->GetClSharing(ila)==0;
     //
     // for the outermost layer the seed is created from the ESD track
-    int nSeedsUp = (ilaUp==nLrActive) ? 1 : fCurrHyp->GetNSeeds(ilaUp);
+    int nSeedsUp = (ilaUp==fNLrActive) ? 1 : fCurrHyp->GetNSeeds(ilaUp);
     int maxNBranches   = fCurrTrackCond->GetMaxBranches(ila);
     int maxNCandidates = fCurrTrackCond->GetMaxCandidates(ila);
     //
     for (int isd=0;isd<nSeedsUp;isd++) {
       AliITSUSeed* seedU;
-      if (ilaUp==nLrActive) {
+      if (ilaUp==fNLrActive) {
        seedU = 0;
-       seedUC.InitFromESDTrack(esdTr);
+       seedUC.InitFromSeed(fCurrHyp->GetTPCSeed()); // init with TPC seed from ref.R
       }
       else {
        seedU = fCurrHyp->GetSeed(ilaUp,isd);  // seed on prev.active layer to prolong  
+       if (seedU->IsKilled()) continue;
        seedUC = *seedU;                       // its copy will be prolonged
        seedUC.SetParent(seedU);        
       }
       seedUC.ResetFMatrix();                    // reset the matrix for propagation to next layer
       // go till next active layer
       AliDebug(2,Form("working on Lr:%d Seed:%d of %d for esdID=%d (MClb:%d) | pT=%.3f",ila,isd,nSeedsUp,esdID,fCurrESDtrMClb,seedUC.Pt()));
-      if (!TransportToLayer(&seedUC, fITS->GetLrIDActive(ilaUp), fITS->GetLrIDActive(ila)) ) {
+      if (!TransportToLayer(&seedUC, fITS->GetLrIDActive(ilaUp), fITS->GetLrIDActive(ila)) ) { // external seed already prolonged
        //
        AliDebug(2,Form("Transport failed | esdID=%d (MClb:%d)",esdID,fCurrESDtrMClb));
        // Check if the seed satisfies to track definition
        if (NeedToKill(&seedUC,kTransportFailed) && seedU) KillSeed(seedU,kTRUE);
        continue; // RS TODO: decide what to do with tracks stopped on higher layers w/o killing
       }
-      AliITSURecoLayer* lrA = fITS->GetLayerActive(ila);
       if (!GetRoadWidth(&seedUC, ila)) { // failed to find road width on the layer
        if (NeedToKill(&seedUC,kRWCheckFailed) && seedU) KillSeed(seedU,kTRUE);
        continue;
       }
-      int nsens = lrA->FindSensors(&fTrImpData[kTrPhi0], hitSens);  // find detectors which may be hit by the track
+      /*
+      //RS toremove
+      int mcquest = -1;
+      if (!seedUC.ContainsFake() && AliDebugLevelClass()>2) {
+       mcquest = fCurrESDtrMClb;
+       seedUC.Print("etp");
+       printf("FSParams: "); for (int ip=0;ip<kNTrImpData;ip++) printf("%+e ",fTrImpData[ip]); printf("\n");
+      }
+      //
+      int nsens = fCurrLayer->FindSensors(&fTrImpData[kTrPhi0], hitSens, mcquest);  // find detectors which may be hit by the track
+      */
+      int nsens = fCurrLayer->FindSensors(&fTrImpData[kTrPhi0], hitSens);  // find detectors which may be hit by the track
       AliDebug(2,Form("Will check %d sensors on lr:%d | esdID=%d (MClb:%d)",nsens,ila,esdID,fCurrESDtrMClb));
       //
       seedUC.SetLr(ila);
       //
-      double bz = GetBz();
       for (int isn=nsens;isn--;) {
        AliITSURecoSens* sens = hitSens[isn];
        int ncl = sens->GetNClusters();
        if (!ncl) continue;
        seedT = seedUC;
        //
-       // We need to propagate the seed to sensor on lrA staying in the frame of the sensor from prev.layer,
+       // We need to propagate the seed to sensor on fCurrLayer staying in the frame of the sensor from prev.layer,
        // since the transport matrix should be defined in this frame.
        double xs; // X in the TF of current seed, corresponding to intersection with sensor plane
        if (!seedT.GetTrackingXAtXAlpha(sens->GetXTF(),sens->GetPhiTF(),bz, xs)) {
@@ -460,10 +563,12 @@ void AliITSUTrackerGlo::FindTrack(AliESDtrack* esdTr, Int_t esdID)
        if (!seedT.RotateToAlpha(sens->GetPhiTF())) continue;
        //
        int clID0 = sens->GetFirstClusterId();
-       for (int icl=ncl;icl--;) {
-         //      AliLog::SetClassDebugLevel("AliITSUTrackerGlo",10);
+       for (int icl=ncl;icl--;) { // don't change the order, clusters are sorted
+         //AliLog::SetClassDebugLevel("AliITSUTrackerGlo",10);
+         int clID = clID0 + icl;
+         if (noClSharing && fCurrLayer->GetCluster(clID)->IsClusterUsed()) continue;
          int res = CheckCluster(&seedT,ila,clID0+icl);
-         //      AliLog::SetClassDebugLevel("AliITSUTrackerGlo", 0);
+         //AliLog::SetClassDebugLevel("AliITSUTrackerGlo", 0);
          //
          if (res==kStopSearchOnSensor) break;     // stop looking on this sensor
          if (res==kClusterNotMatching) continue;  // cluster does not match
@@ -473,10 +578,13 @@ void AliITSUTrackerGlo::FindTrack(AliESDtrack* esdTr, Int_t esdID)
       // cluster search is done. Do we need to have a version of this seed skipping current layer
       if (!NeedToKill(&seedUC,kMissingCluster)) {
        AliITSUSeed* seedSkp = NewSeedFromPool(&seedUC);
-       double penalty = -AliITSUReconstructor::GetRecoParam()->GetMissPenalty(ila);
+       double penalty = -fCurrTrackCond->GetMissPenalty(ila);
        // to do: make penalty to account for probability to miss the cluster for good reason
        seedSkp->SetChi2Cl(penalty);
-       AddProlongationHypothesis(seedSkp,ila);      
+       if (seedSkp->GetChi2GloNrm()>fCurrTrackCond->GetMaxChi2GloNrm(ila)) {
+         MarkSeedFree(seedSkp);
+       }
+       else AddSeedBranch(seedSkp);
       }
       // transfer the new branches of the seed to the hypothesis container
       if (fNBranchesAdded) ValidateAllowedBranches(maxNBranches);
@@ -497,42 +605,51 @@ void AliITSUTrackerGlo::FindTrack(AliESDtrack* esdTr, Int_t esdID)
       AliITSUSeed* sp = fCurrHyp->GetSeed(ila,ih);
       while(sp->GetParent()) {
        sp->Smooth(vecL,matL);
-       if (sp->GetLayerID()>=fITS->GetNLayersActive()-1) break;
+       if (sp->GetLayerID()>=fNLrActive-1) break;
        sp = (AliITSUSeed*)sp->GetParent();
       }
       */
   }
   //
-  SaveCurrentTrackHypotheses();
+  SaveReducedHypothesesTree(hypTr);
+  if (AliDebugLevelClass()>1) {
+    printf("\nSaved hypotheses for esdTrack %d (MCLab:%d)\n",esdID,fCurrESDtrMClb);
+    hypTr->Print("l");
+  }
+  fCurrHyp = 0;
+  //  AliLog::SetClassDebugLevel("AliITSUTrackerGlo",0);
   //
 }
 
 //_________________________________________________________________________
-Bool_t AliITSUTrackerGlo::InitHypothesis(AliESDtrack *esdTr, Int_t esdID)
+AliITSUTrackHyp* AliITSUTrackerGlo::InitHypothesis(AliESDtrack *esdTr, Int_t esdID)
 {
   // init prolongaion candidates finding for single seed
-  fCurrHyp = GetTrackHyp(esdID);
-  if (fCurrHyp) return kTRUE;
+  AliITSUTrackHyp* hyp = GetTrackHyp(esdID);
+  if (hyp) return hyp;
   //
   fCountProlongationTrials++;
   //
   fCurrMass = esdTr->GetMass();
   if (fCurrMass<kPionMass*0.9) fCurrMass = kPionMass; // don't trust to mu, e identification from TPCin
   //
-  fCurrHyp = new AliITSUTrackHyp(fITS->GetNLayersActive());
-  fCurrHyp->SetESDTrack(esdTr);
-  fCurrHyp->SetUniqueID(esdID);
-  fCurrHyp->SetMass(fCurrMass);
-  SetTrackHyp(fCurrHyp,esdID);
+  hyp = new AliITSUTrackHyp(fNLrActive);
+  hyp->SetESDTrack(esdTr);
+  hyp->SetUniqueID(esdID);
+  hyp->SetMass(fCurrMass);
+  hyp->SetTPCSeed( new AliExternalTrackParam(*esdTr) );
+  SetTrackHyp(hyp,esdID);
+
+  if (!TransportToLayer(hyp->GetTPCSeed(),fITS->GetNLayers(), fITS->GetLrIDActive(fNLrActive-1), fITS->GetRITSTPCRef())) hyp->SetSkip(); // propagate to outer R of ITS
   //
-  return kTRUE;
+  return hyp;
   // TO DO
 }
 
 //_________________________________________________________________________
-Bool_t AliITSUTrackerGlo::TransportToLayer(AliITSUSeed* seed, Int_t lFrom, Int_t lTo)
+Bool_t AliITSUTrackerGlo::TransportToLayer(AliITSUSeed* seed, Int_t lFrom, Int_t lTo, Double_t rLim)
 {
-  // transport seed from layerFrom to the entrance (along the direction of the track) of layerTo
+  // transport seed from layerFrom to the entrance (along the direction of the track) of layerTo or to rLim (if>0), wathever is closer
   //  
   //
   if (lTo==lFrom) AliFatal(Form("was called with lFrom=%d lTo=%d",lFrom,lTo));
@@ -540,13 +657,10 @@ Bool_t AliITSUTrackerGlo::TransportToLayer(AliITSUSeed* seed, Int_t lFrom, Int_t
   int dir = lTo > lFrom ? 1:-1;
   AliITSURecoLayer* lrFr = fITS->GetLayer(lFrom); // this can be 0 when extrapolation from TPC to ITS is requested
   Bool_t checkFirst = kTRUE;
+  Bool_t limReached = kFALSE;
   while(lFrom!=lTo) {
     if (lrFr) {
-      if (!GoToExitFromLayer(seed,lrFr,dir,checkFirst)) {
-       //printf("FailHere0 Dir=%d\n",dir);
-       //seed->Print("etp");
-       return kFALSE; // go till the end of current layer
-      }
+      if (!GoToExitFromLayer(seed,lrFr,dir,checkFirst))        return kFALSE; // go till the end of current layer
       checkFirst = kFALSE;
     }
     AliITSURecoLayer* lrTo =  fITS->GetLayer( (lFrom+=dir) );
@@ -554,12 +668,19 @@ Bool_t AliITSUTrackerGlo::TransportToLayer(AliITSUSeed* seed, Int_t lFrom, Int_t
     //
     // go the entrance of the layer, assuming no materials in between
     double xToGo = lrTo->GetR(-dir);
+    if (rLim>0) {
+      if (dir>0) {
+       if (rLim<xToGo) {xToGo = rLim; limReached = kTRUE;}
+      }
+      else {
+       if (rLim>xToGo) {xToGo = rLim; limReached = kTRUE;}
+      }
+    }
     //    double xts = xToGo;
     if (!seed->GetXatLabR(xToGo,xToGo,GetBz(),dir)) {
       //printf("FailHere1: %f %f %d\n",xts,xToGo,dir);
       //seed->Print("etp");
-      //
-      
+      //      
       return kFALSE;
     }
     AliDebug(2,Form("go in dir=%d to R=%.4f(X:%.4f)",dir,lrTo->GetR(-dir), xToGo));
@@ -569,21 +690,23 @@ Bool_t AliITSUTrackerGlo::TransportToLayer(AliITSUSeed* seed, Int_t lFrom, Int_t
       return kFALSE;
     }
     lrFr = lrTo;
+    if (limReached) break;
   }
   return kTRUE;
   //
 }
 
 //_________________________________________________________________________
-Bool_t AliITSUTrackerGlo::TransportToLayer(AliExternalTrackParam* seed, Int_t lFrom, Int_t lTo)
+Bool_t AliITSUTrackerGlo::TransportToLayer(AliExternalTrackParam* seed, Int_t lFrom, Int_t lTo, Double_t rLim)
 {
-  // transport track from layerFrom to the entrance of layerTo
+  // transport track from layerFrom to the entrance of layerTo or to rLim (if>0), wathever is closer
   //  
   if (lTo==lFrom) AliFatal(Form("was called with lFrom=%d lTo=%d",lFrom,lTo));
   //
   int dir = lTo > lFrom ? 1:-1;
   AliITSURecoLayer* lrFr = fITS->GetLayer(lFrom); // this can be 0 when extrapolation from TPC to ITS is requested
   Bool_t checkFirst = kTRUE;
+  Bool_t limReached = kFALSE;
   while(lFrom!=lTo) {
     if (lrFr) {
       if (!GoToExitFromLayer(seed,lrFr,dir,checkFirst)) return kFALSE; // go till the end of current layer
@@ -594,6 +717,14 @@ Bool_t AliITSUTrackerGlo::TransportToLayer(AliExternalTrackParam* seed, Int_t lF
     //
     // go the entrance of the layer, assuming no materials in between
     double xToGo = lrTo->GetR(-dir);
+    if (rLim>0) {
+      if (dir>0) {
+       if (rLim<xToGo) {xToGo = rLim; limReached = kTRUE;}
+      }
+      else {
+       if (rLim>xToGo) {xToGo = rLim; limReached = kTRUE;}
+      }
+    }
     //    double xts = xToGo;
     if (!seed->GetXatLabR(xToGo,xToGo,GetBz(),dir)) {
       //      printf("FailHere1: %f %f %d\n",xts,xToGo,dir);
@@ -607,6 +738,7 @@ Bool_t AliITSUTrackerGlo::TransportToLayer(AliExternalTrackParam* seed, Int_t lF
       return kFALSE;
     }
     lrFr = lrTo;
+    if (limReached) break;
   }
   return kTRUE;
   //
@@ -748,25 +880,28 @@ Bool_t AliITSUTrackerGlo::GetRoadWidth(AliITSUSeed* seed, int ilrA)
     // special case: track does not reach inner radius, might be tangential
     double r = sc.GetD(0,0,bz);
     double x;
-    if (!sc.GetXatLabR(r,x,bz,-1)) {
-      sc.Print();
-      AliFatal(Form("This should not happen: r=%f",r));
-    }
+    if (!sc.GetXatLabR(r,x,bz,-1)) return kFALSE;
     dr = Abs(sc.GetX() - x);
-    if (!sc.GetXYZAt(x, bz, fTrImpData + kTrXOut)) {
-      sc.Print();
-      AliFatal(Form("This should not happen: x=%f",x));
-    }
+    if (!sc.GetXYZAt(x, bz, fTrImpData + kTrXOut)) return kFALSE;
   }
   //
   fTrImpData[kTrPhiOut] = ATan2(fTrImpData[kTrYOut],fTrImpData[kTrXOut]);
   double sgy = sc.GetSigmaY2() + dr*dr*sc.GetSigmaSnp2() + AliITSUReconstructor::GetRecoParam()->GetSigmaY2(ilrA);
   double sgz = sc.GetSigmaZ2() + dr*dr*sc.GetSigmaTgl2() + AliITSUReconstructor::GetRecoParam()->GetSigmaZ2(ilrA);
-  sgy = Sqrt(sgy)*AliITSUReconstructor::GetRecoParam()->GetNSigmaRoadY();
-  sgz = Sqrt(sgz)*AliITSUReconstructor::GetRecoParam()->GetNSigmaRoadZ();
-  fTrImpData[kTrPhi0] = 0.5*(fTrImpData[kTrPhiOut]+fTrImpData[kTrPhiIn]);
+  sgy = Sqrt(sgy)*fCurrTrackCond->GetNSigmaRoadY(ilrA);
+  sgz = Sqrt(sgz)*fCurrTrackCond->GetNSigmaRoadZ(ilrA);
+  double dphi0 = 0.5*Abs(fTrImpData[kTrPhiOut]-fTrImpData[kTrPhiIn]);
+  double phi0  = 0.5*(fTrImpData[kTrPhiOut]+fTrImpData[kTrPhiIn]);
+  if ( dphi0>(0.5*Pi()) ) {
+    // special case of angles around pi 
+    dphi0 = Abs(phi0);    
+    phi0  += Pi();
+  }
+
+  fTrImpData[kTrPhi0] = phi0;
   fTrImpData[kTrZ0]   = 0.5*(fTrImpData[kTrZOut]+fTrImpData[kTrZIn]);
-  fTrImpData[kTrDPhi] = 0.5*Abs(fTrImpData[kTrPhiOut]-fTrImpData[kTrPhiIn]) + sgy/lrA->GetR();
+  dphi0 += sgy/lrA->GetR();
+  fTrImpData[kTrDPhi] =  dphi0<PiOver2() ? dphi0 : PiOver2();
   fTrImpData[kTrDZ]   = 0.5*Abs(fTrImpData[kTrZOut]-fTrImpData[kTrZIn])   + sgz;
   //  
   return kTRUE;
@@ -807,7 +942,8 @@ Int_t AliITSUTrackerGlo::CheckCluster(AliITSUSeed* track, Int_t lr, Int_t clID)
   //           kClusterMatching    otherwise
   //
   const double kTolerX = 5e-4;
-  AliCluster *cl = fITS->GetLayerActive(lr)->GetCluster(clID);
+  //  AliCluster *cl = fITS->GetLayerActive(lr)->GetCluster(clID);
+  AliCluster *cl = fCurrLayer->GetCluster(clID);
   //
   Bool_t goodCl = kFALSE;
   int currLabel = Abs(fCurrESDtrMClb);
@@ -815,11 +951,11 @@ Int_t AliITSUTrackerGlo::CheckCluster(AliITSUSeed* track, Int_t lr, Int_t clID)
   if (cl->GetLabel(0)>=0) {
     for (int i=0;i<3;i++) if (cl->GetLabel(i)>=0 && cl->GetLabel(i)==currLabel) {goodCl = kTRUE; break;}
   }
-  Bool_t goodSeed = !track->ContainsFake();
   //
   if (TMath::Abs(cl->GetX())>kTolerX) { // if due to the misalingment X is large, propagate track only
     if (!track->PropagateParamOnlyTo(track->GetX()+cl->GetX(),GetBz())) {
-      if (goodCl&&goodSeed && AliDebugLevelClass()>2 ) {
+      //
+      if (AliDebugLevelClass()>2 && goodCl && !track->ContainsFake()) {
        AliDebug(2,Form("Lost good cl on L:%d failed propagation. |ESDtrack#%d (MClb:%d)",lr,fCurrESDtrack->GetID(),fCurrESDtrMClb)); 
        track->Print("etp");
        cl->Print();
@@ -830,38 +966,27 @@ Int_t AliITSUTrackerGlo::CheckCluster(AliITSUSeed* track, Int_t lr, Int_t clID)
   double dy = cl->GetY()-track->GetY();
   double dz = cl->GetZ()-track->GetZ();
   //
-#ifdef  _FILL_CONTROL_HISTOS_
-  int hcOffs = fTrackPhase*kHistosPhase + lr;
-  double htrPt=-1;
-  if (goodCl&&goodSeed && fCHistoArr /*&& track->GetChi2Penalty()<1e-5*/) {
-    htrPt = track->Pt();
-    ((TH2*)fCHistoArr->At(kHResY+hcOffs))->Fill(htrPt,dy);
-    ((TH2*)fCHistoArr->At(kHResZ+hcOffs))->Fill(htrPt,dz);
-    double errY = track->GetSigmaY2();
-    double errZ = track->GetSigmaZ2();
-    if (errY>0) ((TH2*)fCHistoArr->At(kHResYP+hcOffs))->Fill(htrPt,dy/Sqrt(errY));
-    if (errZ>0) ((TH2*)fCHistoArr->At(kHResZP+hcOffs))->Fill(htrPt,dz/Sqrt(errZ));
-  }
-#endif  
-  //
   double dy2 = dy*dy;
   double tol2 = (track->GetSigmaY2() + AliITSUReconstructor::GetRecoParam()->GetSigmaY2(lr))*
-    AliITSUReconstructor::GetRecoParam()->GetNSigmaRoadY()*AliITSUReconstructor::GetRecoParam()->GetNSigmaRoadY(); // RS TOOPTIMIZE
+    fCurrTrackCond->GetNSigmaRoadY(lr)*fCurrTrackCond->GetNSigmaRoadY(lr); // RS TOOPTIMIZE
   if (dy2>tol2) {                          // the clusters are sorted in Z(col) then in Y(row). 
-    if (goodCl&&goodSeed && AliDebugLevelClass()>2) {    
+    //
+    if (AliDebugLevelClass()>2 && goodCl &&  !track->ContainsFake()) {    
       AliDebug(2,Form("Lost good cl: dy2=%e > tol2=%e |ESDtrack#%d (MClb:%d)",dy2,tol2,fCurrESDtrack->GetID(),fCurrESDtrMClb)); 
       track->Print("etp");
       cl->Print();
       PrintSeedClusters(track);
     }
-    if (dy>0) return kStopSearchOnSensor;  // No chance that other cluster of this sensor will match (all Y's will be even larger)
+    // clusters are sorted in increasing Y and the loop goes from last (highers Y) to 1st.
+    // if the track has too large y for this cluster (dy<0) it will be so for all other clusters of the sensor
+    if (dy<0) return kStopSearchOnSensor;  // No chance that other cluster of this sensor will match (all Y's will be even larger)
     else      return kClusterNotMatching;   // Other clusters may match
   }
   double dz2 = dz*dz;
   tol2 = (track->GetSigmaZ2() + AliITSUReconstructor::GetRecoParam()->GetSigmaZ2(lr))*
-    AliITSUReconstructor::GetRecoParam()->GetNSigmaRoadZ()*AliITSUReconstructor::GetRecoParam()->GetNSigmaRoadZ(); // RS TOOPTIMIZE
+    fCurrTrackCond->GetNSigmaRoadZ(lr)*fCurrTrackCond->GetNSigmaRoadZ(lr); // RS TOOPTIMIZE
   if (dz2>tol2) {
-    if (goodCl&&goodSeed && AliDebugLevelClass()>2) {
+    if (AliDebugLevelClass()>2 && goodCl &&  !track->ContainsFake()) {
       AliDebug(2,Form("Lost good cl on L:%d : dz2=%e > tol2=%e |ESDtrack#%d (MClb:%d)",lr,dz2,tol2,fCurrESDtrack->GetID(),fCurrESDtrMClb)); 
       track->Print("etp");
       cl->Print();
@@ -875,16 +1000,10 @@ Int_t AliITSUTrackerGlo::CheckCluster(AliITSUSeed* track, Int_t lr, Int_t clID)
   Double_t cov[3]={cl->GetSigmaY2(), cl->GetSigmaYZ(), cl->GetSigmaZ2()};
   double chi2 = track->GetPredictedChi2(p,cov);
   //
-#ifdef  _FILL_CONTROL_HISTOS_
-  if (htrPt>0) {
-    ((TH2*)fCHistoArr->At(kHChi2Cl+hcOffs))->Fill(htrPt,chi2);
-  }
-#endif
-  //
-  if (chi2>AliITSUReconstructor::GetRecoParam()->GetMaxTr2ClChi2(lr)) {
-    if (goodCl&&goodSeed && AliDebugLevelClass()>2) {
+  if (chi2>fCurrTrackCond->GetMaxTr2ClChi2(lr)) {
+    if (AliDebugLevelClass()>2 && goodCl &&  !track->ContainsFake()) {
       AliDebug(2,Form("Lost good cl on L:%d : Chi2=%e > Chi2Max=%e |dy: %+.3e dz: %+.3e |ESDtrack#%d (MClb:%d)\n",
-                     lr,chi2,AliITSUReconstructor::GetRecoParam()->GetMaxTr2ClChi2(lr),dy,dz,fCurrESDtrack->GetID(),fCurrESDtrMClb)); 
+                     lr,chi2,fCurrTrackCond->GetMaxTr2ClChi2(lr),dy,dz,fCurrESDtrack->GetID(),fCurrESDtrMClb)); 
       track->Print("etp");
       cl->Print("");
       PrintSeedClusters(track);
@@ -894,7 +1013,7 @@ Int_t AliITSUTrackerGlo::CheckCluster(AliITSUSeed* track, Int_t lr, Int_t clID)
   //
   track = NewSeedFromPool(track);  // input track will be reused, use its clone for updates
   if (!track->Update()) {
-    if (goodCl&&goodSeed && AliDebugLevelClass()>2) {
+    if (AliDebugLevelClass()>2 && goodCl &&  !track->ContainsFake()) {
       AliDebug(2,Form("Lost good cluster on L:%d : failed to update",lr));
       track->Print("etp");
       cl->Print("");
@@ -905,7 +1024,19 @@ Int_t AliITSUTrackerGlo::CheckCluster(AliITSUSeed* track, Int_t lr, Int_t clID)
   }
   track->SetChi2Cl(chi2);
   track->SetLrClusterID(lr,clID);
-  cl->IncreaseClusterUsage();
+  //
+  if (track->GetChi2GloNrm()>fCurrTrackCond->GetMaxChi2GloNrm(lr)) {
+    if (AliDebugLevelClass()>2 && goodCl &&  !track->ContainsFake()) {
+      AliDebug(2,Form("Lost good cl on L:%d : Chi2Glo=%e > Chi2Max=%e |dy: %+.3e dz: %+.3e |ESDtrack#%d (MClb:%d)\n",
+                     lr,track->GetChi2GloNrm(),fCurrTrackCond->GetMaxChi2GloNrm(lr),dy,dz,fCurrESDtrack->GetID(),fCurrESDtrMClb)); 
+      track->Print("etp");
+      cl->Print("");
+      PrintSeedClusters(track);
+    }
+    MarkSeedFree(track);
+    return kClusterNotMatching;
+  }
+  //  cl->IncreaseClusterUsage(); // do this only for winners
   //
   track->SetFake(!goodCl);
   //
@@ -925,7 +1056,7 @@ Bool_t AliITSUTrackerGlo::NeedToKill(AliITSUSeed *seed, Int_t flag)
   if (flag==kMissingCluster) {
     int lastChecked = seed->GetLayerID();
     UShort_t patt = seed->GetHitsPattern();
-    if (lastChecked) patt |= ~(kMask<<lastChecked); // not all layers were checked, complete unchecked once by potential hits
+    if (lastChecked) patt |= ~(kMask<<lastChecked); // not all layers were checked, complete unchecked ones by potential hits
     Bool_t seedOK = fCurrTrackCond->CheckPattern(patt);
     return !seedOK;
   }
@@ -1027,104 +1158,249 @@ Bool_t AliITSUTrackerGlo::PropagateSeed(AliExternalTrackParam *seed, Double_t xT
 }
 
 //______________________________________________________________________________
-void AliITSUTrackerGlo::SaveCurrentTrackHypotheses()
+Bool_t AliITSUTrackerGlo::FinalizeHypothesis(AliITSUTrackHyp* hyp)
 {
-  // RS: shall we clean up killed seeds?
-  ((TObjArray*)fCurrHyp->GetLayerSeeds(0))->Sort();
-  fCurrHyp = 0;
-  // TODO
-  
+  // finalize single TPC track hypothesis
+  if (!hyp || hyp->GetESDTrack()->IsOn(AliESDtrack::kITSin)) return kFALSE;
+  AliITSUSeed* winner = 0;
+  fCurrHyp = hyp;
+  fCurrMass = hyp->GetMass();
+  if (!(winner=hyp->DefineWinner(fCurrTrackCond->GetActiveLrInner()))) return kFALSE;
+  CookMCLabel(hyp);
+  //
+#ifdef  _ITSU_TUNING_MODE_  // fill tuning histos
+  TObjArray* dest = hyp->GetLabel()>=0 ? fCHistoArrCorr : fCHistoArrFake;
+  if (dest) {
+    AliITSUSeed* sd = winner;
+    double htrPt = hyp->Pt();
+    do {
+      int clID,lrID;
+      if ( (clID=sd->GetLrCluster(lrID))<0 ) continue;
+      ((TH2*)dest->At( GetHistoID(lrID,kHChi2Nrm     ,fCurrPassID) ))->Fill(htrPt,sd->GetChi2GloNrm());
+      ((TH2*)dest->At( GetHistoID(lrID,kHBestInBranch,fCurrPassID) ))->Fill(htrPt,sd->GetOrdBranch());
+      ((TH2*)dest->At( GetHistoID(lrID,kHBestInCand  ,fCurrPassID) ))->Fill(htrPt,sd->GetOrdCand());
+      //
+      if (dest==fCHistoArrFake && !sd->IsFake()) continue; // for the fake seeds fill only fake clusters part
+      //
+      ((TH2*)dest->At( GetHistoID(lrID,kHResY        ,fCurrPassID) ))->Fill(htrPt,sd->GetResidY());
+      ((TH2*)dest->At( GetHistoID(lrID,kHResZ        ,fCurrPassID) ))->Fill(htrPt,sd->GetResidZ());
+      ((TH2*)dest->At( GetHistoID(lrID,kHResYP       ,fCurrPassID) ))->Fill(htrPt,sd->GetPullY());
+      ((TH2*)dest->At( GetHistoID(lrID,kHResZP       ,fCurrPassID) ))->Fill(htrPt,sd->GetPullZ());
+      ((TH2*)dest->At( GetHistoID(lrID,kHChi2Cl      ,fCurrPassID) ))->Fill(htrPt,sd->GetChi2Cl());
+      //
+    } while((sd=(AliITSUSeed*)sd->GetParent()));
+    //
+    ((TH2*)dest->At( GetHistoID(-1,kHChiMatch,fCurrPassID) ))->Fill(htrPt,winner->GetChi2ITSTPC());
+    ((TH2*)dest->At( GetHistoID(-1,kHChiITSSA,fCurrPassID) ))->Fill(htrPt,winner->GetChi2ITSSA());
+  }
+  //
+#endif
+  //
+  CheckClusterSharingConflicts(hyp);
+  return hyp->GetWinner();  // winner might change of disappear after resolving conflicts
+  //
 }
 
 //______________________________________________________________________________
 void AliITSUTrackerGlo::FinalizeHypotheses()
 {
   // select winner for each hypothesis, remove cl. sharing conflicts
-  AliDebug(2,"TODO");
+  AliCodeTimerAuto("",0); 
   //
-  int nh = fHypStore.GetEntriesFast();
-  for (int ih=0;ih<nh;ih++) {
-    AliITSUTrackHyp* hyp = (AliITSUTrackHyp*) fHypStore.UncheckedAt(ih); 
-    if (!hyp || !hyp->DefineWinner()) continue; // TODO
-    if (hyp->GetESDTrack()->IsOn(AliESDtrack::kITSin)) continue;
-    fCountITSin++;
-    CookMCLabel(hyp);
-    UpdateESDTrack(hyp,AliESDtrack::kITSin);
-  }
+  int* esdTrackIndex = fESDIndex.GetArray();
+  for (int ih=0;ih<fNTracksESD;ih++) FinalizeHypothesis(GetTrackHyp(esdTrackIndex[ih])); // finlize in decreasing pt order
+  //
+  for (int ih=fNTracksESD;ih--;) UpdateESDTrack(GetTrackHyp(esdTrackIndex[ih]),AliESDtrack::kITSin); 
+  //
+}
 
+//______________________________________________________________________________
+void AliITSUTrackerGlo::CheckClusterSharingConflicts(AliITSUTrackHyp* hyp)
+{
+  // remove eventual cluster sharing conflicts
+  AliITSUSeed* winner = 0;
+  if (!(winner=hyp->GetWinner())) return;
+  UShort_t idH = (UShort_t)hyp->GetUniqueID()+1;
+  int lrID,clID;
+  int inLr = fCurrTrackCond->GetActiveLrInner();
+  AliITSUSeed* winSD=winner;
+  do {
+    if ( (clID=winSD->GetLrCluster(lrID))<0 ) continue;
+    AliITSUClusterPix* cl = (AliITSUClusterPix*)fITS->GetLayerActive(lrID)->GetCluster(clID);
+    Int_t refID = cl->GetRecoInfo();                // was it already referred by some track (with refID-1 if >0)
+    if (!refID) {cl->SetRecoInfo(idH); continue;}   // if not, refer from track to cluster
+    if (refID==idH) continue;                          // ignore reference to itself
+    // the cluster is already used by other track, need to resolve the conflict
+    AliITSUTrackHyp* hypC = GetTrackHyp(refID-1);   // competitor
+    //    printf("Ref to %d (%p) from %d Cl %d %d\n",refID-1,hypC, idH-1,clID,lrID);
+    AliITSUSeed* winnerC = hypC->GetWinner();
+    if (!winnerC) {
+      printf("Missing winner, ERROR\n");
+      continue;
+    }
+    //
+    if (AliDebugLevelClass()>1) { //------------------------ DEBUG -------------------
+      AliInfo(Form("Shared cl#%4d on Lr:%d: Hyp%3d/Q:%6.3f vs Hyp%3d/Q:%6.3f",
+                  clID,lrID,idH-1,winner->GetQualityVar(),refID-1,winnerC->GetQualityVar()));
+      // dump winner of hyp
+      printf("#%4d Pt:%.3f Chi:%6.3f/%6.3f/%6.3f Ncl:%d MCits%+5d MCtpc:%+5d |",
+            idH-1,winner->Pt(),winner->GetChi2GloNrm(),winner->GetChi2ITSTPC(),winner->GetChi2ITSSA(),
+            winner->GetNLayersHit(),hyp->GetITSLabel(),hyp->GetESDTrack()->GetTPCLabel());
+      int prevL=-1;
+      AliITSUSeed* sd = winner;
+      do {
+       int lrs;
+       int clIDt = sd->GetLrCluster(lrs);
+       if (clIDt<0) continue;
+       while( lrs>++prevL ) printf("%4s        ","----");
+       printf("%4d (%5.1f)",clIDt,sd->GetChi2Cl());
+      } while ((sd=(AliITSUSeed*)sd->GetParent()));
+      printf("|\n");
+      // dump winner of hypC
+      printf("#%4d Pt:%.3f Chi:%6.3f/%6.3f/%6.3f Ncl:%d MCits%+5d MCtpc:%+5d |",
+            refID-1,winnerC->Pt(),winnerC->GetChi2GloNrm(),winnerC->GetChi2ITSTPC(),winnerC->GetChi2ITSSA(),
+            winnerC->GetNLayersHit(),hypC->GetITSLabel(),hypC->GetESDTrack()->GetTPCLabel());
+      prevL=-1;
+      sd = winnerC;
+      do {
+       int lrs;
+       int clIDt = sd->GetLrCluster(lrs);
+       if (clIDt<0) continue;
+       while( lrs>++prevL ) printf("%4s        ","----");
+       printf("%4d (%5.1f)",clIDt,sd->GetChi2Cl());
+      } while ((sd=(AliITSUSeed*)sd->GetParent()));
+      printf("|\n");
+    }  //-------------------------------------------------- DEBUG -------------------
+    //
+    if (winner->GetQualityVar()<winnerC->GetQualityVar()) { // current tracks is better then competitor track
+      FlagSeedClusters(winnerC,kFALSE,refID); // unflag cluster usage by loser
+      cl->SetRecoInfo(idH);
+      //
+      //if ( hypC->GetLabel()>=0) AliInfo(Form("KILLING CORRECT: %d",refID-1));
+      winnerC->Kill();
+      if (hypC->DefineWinner(inLr)) {             // find new winner instead of suppressed candidate
+       CookMCLabel(hypC);
+       CheckClusterSharingConflicts(hypC);   // and check its sharing conflicts again
+       if (winner->IsKilled()) break;        // the current winner might have been killed during check of new winner of hypC!
+      }
+    }    
+    else { // competitor hypC is better than the hyp
+      FlagSeedClusters(winner,kFALSE,idH); // unflag cluster usage by loser
+      winner->Kill();
+      //if ( hyp->GetLabel()>=0) AliInfo(Form("KILLING CORRECT: %d",idH-1));
+      if (hyp->DefineWinner(inLr)) {
+       CookMCLabel(hyp);
+       CheckClusterSharingConflicts(hyp);
+      }
+      break;
+    }
+    //   
+  } while ((winSD=(AliITSUSeed*)winSD->GetParent()));
+  //
+  return;
 }
 
 //______________________________________________________________________________
 void AliITSUTrackerGlo::UpdateESDTrack(AliITSUTrackHyp* hyp,Int_t flag)
 {
   // update ESD track with current best hypothesis
+  if (!hyp) return;
   AliESDtrack* esdTr = hyp->GetESDTrack();
-  if (!esdTr) return;
+  if (!esdTr || esdTr->IsOn(flag)) return;
   AliITSUSeed* win = hyp->GetWinner();
-  if (!win) return;
+  if (!win || win->IsKilled()) return;
+  double chiSav;
+  //
   switch (flag) {
   case AliESDtrack::kITSin: 
     esdTr->UpdateTrackParams(hyp,flag); // update kinematics
-    // TODO: set cluster info
+    fCountITSin++;
+    // set fakes cluster info
+    {
+      UShort_t clfake = 0;
+      AliITSUSeed* sd = win;
+      do {
+       if (sd->IsFake()) clfake |= 0x1<<sd->GetLayerID();
+      } while ((sd=(AliITSUSeed*)sd->GetParent()));
+      //
+      // RS: Temporary set special flag for tracks from the afterburner
+      if (fCurrPassID>0) clfake |= 0x1<<7;
+      //
+      esdTr->SetITSSharedMap(clfake);
+    }
     break;
     //
   case AliESDtrack::kITSout: 
+    // here the stored chi2 will correspond to backward ITS-SA fit
     esdTr->UpdateTrackParams(hyp,flag); // update kinematics
+    fCountITSout++;
     // TODO: avoid setting friend
     break;
     //
   case AliESDtrack::kITSrefit: 
+
+    // at the moment fill as a chi2 the TPC-ITS matching chi2
+    chiSav = hyp->GetChi2();
+    hyp->SetChi2(win->GetChi2ITSTPC());
     esdTr->UpdateTrackParams(hyp,flag); // update kinematics
+    hyp->SetChi2(chiSav);
+    fCountITSrefit++;
     // TODO: avoid setting cluster info
     break;
   default:
     AliFatal(Form("Unknown flag %d",flag));
   }
   //
+  esdTr->SetITSLabel(hyp->GetITSLabel());
   // transfer module indices
   // TODO
 }
 
 //______________________________________________________________________________
-Bool_t AliITSUTrackerGlo::RefitTrack(AliITSUTrackHyp* trc, Double_t rDest, Bool_t stopAtLastCl)
+Double_t AliITSUTrackerGlo::RefitTrack(AliExternalTrackParam* trc, Double_t rDest, Int_t stopCond)
 {
-  // refit track till radius rDest
-  AliITSUTrackHyp tmpTr;
+  // refit track till radius rDest. The cluster,mass info is taken from fCurrHyp (and its winner seed)
+  // if stopCond<0 : propagate till last cluster then stop
+  // if stopCond==0: propagate till last cluster then try to go till limiting rDest, don't mind if fail
+  // if stopCond>0 : rDest must be reached
   //
   double rCurr = Sqrt(trc->GetX()*trc->GetX() + trc->GetY()*trc->GetY());
   int dir,lrStart,lrStop;
   //
   dir = rCurr<rDest ? 1 : -1;
   lrStart = fITS->FindFirstLayerID(rCurr,dir);
-  lrStop  = fITS->FindLastLayerID(rDest,dir);
+  lrStop  = fITS->FindLastLayerID(rDest,dir); // lr id before which we have to stop
+  //
   if (AliDebugLevelClass()>2) {
     printf("Refit %d: Lr:%d (%f) -> Lr:%d (%f)\n",dir,lrStart,rCurr, lrStop,rDest);
-    printf("Before refit: "); trc->AliExternalTrackParam::Print();
+    printf("Before refit: "); trc->Print();
   }
   if (lrStop<0 || lrStart<0) AliFatal(Form("Failed to find start(%d) or last(%d) layers. Track from %.3f to %.3f",lrStart,lrStop,rCurr,rDest));
   //
-  int ncl = trc->FetchClusterInfo(fClInfo);
-  fCurrMass = trc->GetMass();
-  tmpTr.AliKalmanTrack::operator=(*trc);
-  tmpTr.SetChi2(0);
+  Int_t clInfo[2*AliITSUAux::kMaxLayers];
+  Int_t nCl = fCurrHyp->FetchClusterInfo(clInfo);
+  fCurrMass = fCurrHyp->GetMass();
+  AliExternalTrackParam tmpTr(*trc);
+  double chi2 = 0;
   int iclLr[2],nclLr,clCount=0;
   //
-  for (int ilr=lrStart;ilr!=lrStop;ilr+=dir) {
+  int lrStop1 = lrStop+1;
+  for (int ilr=lrStart;ilr!=lrStop1;ilr+=dir) {
     AliITSURecoLayer* lr = fITS->GetLayer(ilr);
     if ( dir*(rCurr-lr->GetR(dir))>0) continue; // this layer is already passed
     int ilrA2,ilrA = lr->GetActiveID();
     // passive layer or active w/o hits will be traversed on the way to next cluster
-    if (!lr->IsActive() || fClInfo[ilrA2=(ilrA<<1)]<0) continue; 
+    if (!lr->IsActive() || clInfo[ilrA2=(ilrA<<1)]<0) continue; 
     //
     // select the order in which possible 2 clusters (in case of the overlap) will be traversed and fitted
     nclLr=0;
     if (dir>0) { // clusters are stored in increasing radius order
-      iclLr[nclLr++]=fClInfo[ilrA2++];
-      if (fClInfo[ilrA2]>=0) iclLr[nclLr++]=fClInfo[ilrA2];
+      iclLr[nclLr++]=clInfo[ilrA2++];
+      if (clInfo[ilrA2]>=0) iclLr[nclLr++]=clInfo[ilrA2];
     }
     else {
-      if ( fClInfo[ilrA2+1]>=0 ) iclLr[nclLr++]=fClInfo[ilrA2+1];
-      iclLr[nclLr++]=fClInfo[ilrA2];
+      if ( clInfo[ilrA2+1]>=0 ) iclLr[nclLr++]=clInfo[ilrA2+1];
+      iclLr[nclLr++]=clInfo[ilrA2];
     }
     //
     Bool_t transportedToLayer = kFALSE;
@@ -1132,16 +1408,17 @@ Bool_t AliITSUTrackerGlo::RefitTrack(AliITSUTrackHyp* trc, Double_t rDest, Bool_
       AliITSUClusterPix* clus =  (AliITSUClusterPix*)lr->GetCluster(iclLr[icl]);
       AliITSURecoSens* sens = lr->GetSensorFromID(clus->GetVolumeId());
       if (!tmpTr.Rotate(sens->GetPhiTF())) {
-       AliDebug(2,Form("Failed on rotate to %f | ESDtrack#%d (MClb:%d)",sens->GetPhiTF(),fCurrESDtrack->GetID(),fCurrESDtrMClb));
-       return kFALSE;
+       AliESDtrack* trESD = fCurrHyp->GetESDTrack();
+       AliDebug(2,Form("Failed on rotate to %f | ESDtrack#%d (MClb:%d)",sens->GetPhiTF(),trESD->GetID(),trESD->GetTPCLabel()));
+       return -1;
       }
       //
       double xClus = sens->GetXTF()+clus->GetX();
       if (!transportedToLayer) {
        if (ilr!=lrStart && !TransportToLayerX(&tmpTr,lrStart,ilr,xClus)) {
-         AliDebug(2,Form("Failed to transport %d -> %d | ESDtrack#%d (MClb:%d)\n",lrStart,ilr,fCurrESDtrack->GetID(),fCurrESDtrMClb));
-         //tmpTr.AliExternalTrackParam::Print(); trc->GetWinner()->Print("etp");
-         return kFALSE; // go to the entrance to the layer
+         AliESDtrack* trESD = fCurrHyp->GetESDTrack();
+         AliDebug(2,Form("Failed to transport %d -> %d | ESDtrack#%d (MClb:%d)\n",lrStart,ilr,trESD->GetID(),trESD->GetTPCLabel()));
+         return -1; // go to the entrance to the layer
        }
        lrStart = ilr;
        transportedToLayer = kTRUE;
@@ -1149,45 +1426,48 @@ Bool_t AliITSUTrackerGlo::RefitTrack(AliITSUTrackHyp* trc, Double_t rDest, Bool_
       //
       if (AliDebugLevelClass()>1) {
        AliDebug(2,Form("Propagate to cl:%d on lr %d Need to go %.4f -> %.4f",icl,ilrA,tmpTr.GetX(),xClus));
-       //      printf("Before: "); tmpTr.AliExternalTrackParam::Print();
       }
       //
       if (!PropagateSeed(&tmpTr,xClus,fCurrMass)) {
-       AliDebug(2,Form("Failed on propagate to %f (dir=%d) | ESDtrack#%d (MClb:%d)",xClus,dir,fCurrESDtrack->GetID(),fCurrESDtrMClb));
-       //tmpTr.AliExternalTrackParam::Print(""); trc->GetWinner()->Print("etp");
-       return kFALSE;
+       AliESDtrack* trESD = fCurrHyp->GetESDTrack();
+       AliDebug(2,Form("Failed on propagate to %f (dir=%d) | ESDtrack#%d (MClb:%d)",xClus,dir,trESD->GetID(),trESD->GetTPCLabel()));
+       return -1;
       }
       //
-#ifdef  _FILL_CONTROL_HISTOS_
-      int hcOffs = fTrackPhase*kHistosPhase + ilrA;
-      double htrPt=-1;
-      if (fCHistoArr && trc->GetLabel()>=0/* && trc->Charge()>0*/) {
-       htrPt = tmpTr.Pt();
-       double dy = clus->GetY()-tmpTr.GetY();
-       double dz = clus->GetZ()-tmpTr.GetZ();
-       ((TH2*)fCHistoArr->At(kHResY+hcOffs))->Fill(htrPt,dy);
-       ((TH2*)fCHistoArr->At(kHResZ+hcOffs))->Fill(htrPt,dz);
+      Double_t p[2]={clus->GetY(), clus->GetZ()};
+      Double_t cov[3]={clus->GetSigmaY2(), clus->GetSigmaYZ(), clus->GetSigmaZ2()};
+      double chi2cl = tmpTr.GetPredictedChi2(p,cov);
+      chi2 += chi2cl;
+      //
+#ifdef  _ITSU_TUNING_MODE_
+      TObjArray* dest = trc->GetLabel()>=0 ? fCHistoArrCorr : fCHistoArrFake;
+      if (dest && fTrackPhaseID>kClus2Tracks) {
+       //
+       double htrPt = tmpTr.Pt();
+       double dy = p[0]-tmpTr.GetY();
+       double dz = p[1]-tmpTr.GetZ();
+       ((TH2*)dest->At( GetHistoID(ilrA,kHResY,0,fTrackPhaseID) ))->Fill(htrPt,dy);
+       ((TH2*)dest->At( GetHistoID(ilrA,kHResZ,0,fTrackPhaseID) ))->Fill(htrPt,dz);
        double errY = tmpTr.GetSigmaY2();
        double errZ = tmpTr.GetSigmaZ2();
-       if (errY>0) ((TH2*)fCHistoArr->At(kHResYP+hcOffs))->Fill(htrPt,dy/Sqrt(errY));
-       if (errZ>0) ((TH2*)fCHistoArr->At(kHResZP+hcOffs))->Fill(htrPt,dz/Sqrt(errZ));
+       if (errY>0) ((TH2*)dest->At( GetHistoID(ilrA,kHResYP,0,fTrackPhaseID) ))->Fill(htrPt,dy/Sqrt(errY));
+       if (errZ>0) ((TH2*)dest->At( GetHistoID(ilrA,kHResZP,0,fTrackPhaseID) ))->Fill(htrPt,dz/Sqrt(errZ));
+       ((TH2*)dest->At( GetHistoID(ilrA,kHChi2Cl,0,fTrackPhaseID) ))->Fill(htrPt,chi2cl);
       }
 #endif  
-      //
-      double chi2;
-      if ( (chi2=tmpTr.Update(clus))<0 ) {
-       AliDebug(2,Form("Failed on Update | ESDtrack#%d (MClb:%d)",fCurrESDtrack->GetID(),fCurrESDtrMClb));             
-       return kFALSE;
+      //      
+      if ( !tmpTr.Update(p,cov) ) {
+       AliESDtrack* trESD = fCurrHyp->GetESDTrack();
+       AliDebug(2,Form("Failed on Update | ESDtrack#%d (MClb:%d)",trESD->GetID(),trESD->GetTPCLabel()));
+       return -1;
       }
-#ifdef  _FILL_CONTROL_HISTOS_
-      if (htrPt>0) {
-       ((TH2*)fCHistoArr->At(kHChi2Cl+hcOffs))->Fill(htrPt,chi2);
-      }
-#endif 
       if (AliDebugLevelClass()>1) {
-       printf("AfterRefit: "); tmpTr.AliExternalTrackParam::Print();
+       printf("AfterRefit: "); tmpTr.Print();
+      }
+      if (++clCount==nCl && stopCond<0) {
+       *trc = tmpTr;
+       return chi2; // it was requested to not propagate after last update
       }
-      if (stopAtLastCl && ++clCount==ncl) return kTRUE; // it was requested to not propagate after last update
     }
     //
   }
@@ -1195,29 +1475,24 @@ Bool_t AliITSUTrackerGlo::RefitTrack(AliITSUTrackHyp* trc, Double_t rDest, Bool_
   // Still, try to go as close as possible to rDest.
   //
   if (lrStart!=lrStop) {
-    //printf("Going to last layer %d -> %d\n",lrStart,lrStop);
     if (!TransportToLayer(&tmpTr,lrStart,lrStop)) {
-      AliDebug(1,Form("Failed on TransportToLayer %d->%d | ESDtrack#%d (MClb:%d)",lrStart,lrStop,fCurrESDtrack->GetID(),fCurrESDtrMClb));
-      //tmpTr.AliExternalTrackParam::Print();
-      //trc->GetWinner()->Print("etp");
-      return kTRUE;
+      AliDebug(1,Form("Failed on TransportToLayer %d->%d | ESDtrack#%d (MClb:%d), X=%f",lrStart,lrStop,fCurrESDtrack->GetID(),fCurrESDtrMClb,tmpTr.GetX()));
+      return (stopCond>0) ? -chi2 : chi2; // rDest was obligatory
     }    
     if (!GoToExitFromLayer(&tmpTr,fITS->GetLayer(lrStop),dir)) {
-      AliDebug(3,Form("Failed on GoToExitFromLayer %d | ESDtrack#%d (MClb:%d)",lrStop,fCurrESDtrack->GetID(),fCurrESDtrMClb));
-      return kTRUE; // go till the exit from layer
+      AliDebug(1,Form("Failed on GoToExitFromLayer %d | ESDtrack#%d (MClb:%d), X=%f",lrStop,fCurrESDtrack->GetID(),fCurrESDtrMClb,tmpTr.GetX()));
+      return (stopCond>0) ? -chi2 : chi2; // rDest was obligatory
     }
-    //
-    //printf("On exit from last layer\n");
-    //tmpTr.AliExternalTrackParam::Print();
-    // go to the destination radius
-    if (!tmpTr.GetXatLabR(rDest,rDest,GetBz(),dir)) return kTRUE;
-    if (!PropagateSeed(&tmpTr,rDest,fCurrMass, 100, kFALSE)) return kTRUE;
   }
-  trc->AliKalmanTrack::operator=(tmpTr);
+  // go to the destination radius. Note that here we don't select direction to avoid precision problems
+  if (!tmpTr.GetXatLabR(rDest,rDest,GetBz(),0) || !PropagateSeed(&tmpTr,rDest,fCurrMass, 100, kFALSE)) {
+    return (stopCond>0) ? -chi2 : chi2; // rDest was obligatory
+  }
+  *trc=tmpTr;
   if (AliDebugLevelClass()>2) {
-    printf("After refit (now at lr %d): ",lrStop); trc->AliExternalTrackParam::Print();
+    printf("After refit (now at lr %d): ",lrStop); trc->Print();
   }
-  return kTRUE;
+  return chi2;
 }
 
 //__________________________________________________________________
@@ -1250,10 +1525,10 @@ void AliITSUTrackerGlo::CookMCLabel(AliITSUTrackHyp* hyp)
     seed = (AliITSUSeed*)seed->GetParent();
   } // loop over clusters
   // 
+  AliESDtrack* esdTr = hyp->GetESDTrack();
+  int tpcLab = esdTr ? Abs(esdTr->GetTPCLabel()) : -kDummyLabel;
   if (nCl && nLab) {
     int maxLab=0,nTPCok=0;
-    AliESDtrack* esdTr = hyp->GetESDTrack();
-    int tpcLab = esdTr ? Abs(esdTr->GetTPCLabel()) : -kDummyLabel;
     for (int ilb=nLab;ilb--;) {
       int st = lbStat[ilb];
       if (lbStat[maxLab]<st) maxLab=ilb;
@@ -1261,12 +1536,12 @@ void AliITSUTrackerGlo::CookMCLabel(AliITSUTrackHyp* hyp)
     }
     hyp->SetFakeRatio(1.-float(nTPCok)/nCl);
     hyp->SetLabel( nTPCok==nCl ? tpcLab : -tpcLab);
-    hyp->SetITSLabel( lbStat[maxLab]==nCl ? lbStat[maxLab] : -lbStat[maxLab]); // winner label
+    hyp->SetITSLabel( lbStat[maxLab]==nCl ? lbID[maxLab] : -lbID[maxLab]); // winner label
     return;
   }
   //
   hyp->SetFakeRatio(-1.);
-  hyp->SetLabel( kDummyLabel );
+  hyp->SetLabel( -tpcLab );
   hyp->SetITSLabel( kDummyLabel );
 }
 
@@ -1274,9 +1549,13 @@ void AliITSUTrackerGlo::CookMCLabel(AliITSUTrackHyp* hyp)
 Bool_t AliITSUTrackerGlo::AddSeedBranch(AliITSUSeed* seed)
 {
   // add new prolongation branch for the seed to temporary array. The seeds are sorted according to Compare f-n
-  if (fNCandidatesAdded+fNBranchesAdded>=AliITSUTrackCond::kMaxCandidates ) {
-    AliError(Form("Number of candidates for current seed reached limit of AliITSUTrackCond::kMaxCandidates=%d, increase it",AliITSUTrackCond::kMaxCandidates));
-    return kFALSE;
+  if (fNCandidatesAdded+fNBranchesAdded>=fLayerMaxCandidates ) {
+    AliInfo(Form("Number of candidates at layer %d for current seed reached %d, increasing buffer",fCurrActLrID,fLayerMaxCandidates));
+    fLayerMaxCandidates = 2*(fLayerMaxCandidates+1);
+    AliITSUSeed** tmpArr = fLayerCandidates;
+    fLayerCandidates = new AliITSUSeed*[fLayerMaxCandidates];
+    memcpy(fLayerCandidates,tmpArr,(fNCandidatesAdded+fNBranchesAdded)*sizeof(AliITSUSeed*));
+    delete tmpArr; // delete only array, not objects
   }
   AliITSUSeed** branches = &fLayerCandidates[fNCandidatesAdded]; // note: fNCandidatesAdded is incremented after adding all branches of current seed
   int slot=fNBranchesAdded++;
@@ -1297,20 +1576,17 @@ Bool_t AliITSUTrackerGlo::AddSeedBranch(AliITSUSeed* seed)
 void AliITSUTrackerGlo::ValidateAllowedBranches(Int_t acceptMax)
 {
   // keep allowed number of branches for current seed and disable extras
+  AliCodeTimerAuto("",0); 
   int nb = Min(fNBranchesAdded,acceptMax);
   //  if (nb<fNBranchesAdded) printf("ValidateAllowedBranches: %d of %d (%d) on lr %d\n",nb,fNBranchesAdded,fNCandidatesAdded,ilr);
   // disable unused branches
   AliITSUSeed** branches = &fLayerCandidates[fNCandidatesAdded];
-  for (int ib=nb;ib<fNBranchesAdded;ib++) {
-    /*
-    if (!branches[ib]->ContainsFake()) {
-      printf("Suppress good branch as %d of %d |",ib,fNBranchesAdded); branches[ib]->Print();
-      printf("Survivors : \n");
-      for (int j=0;j<nb;j++) branches[j]->Print();
-    }
-    */
-    MarkSeedFree(branches[ib]);
-  }
+  //
+#ifdef  _ITSU_TUNING_MODE_
+  for (int ib=0;ib<fNBranchesAdded;ib++) branches[ib]->SetOrdBranch(ib);
+#endif
+  //
+  for (int ib=nb;ib<fNBranchesAdded;ib++) MarkSeedFree(branches[ib]);
   fNCandidatesAdded += nb; // update total candidates counter
   fNBranchesAdded = 0; // reset branches counter
   //
@@ -1321,34 +1597,124 @@ void AliITSUTrackerGlo::ValidateAllowedCandidates(Int_t ilr, Int_t acceptMax)
 {
   // transfer allowed number of branches to hypothesis container
   //
+  AliCodeTimerAuto("",0); 
   // sort candidates in increasing order of chi2
-  Int_t index[AliITSUTrackCond::kMaxCandidates];
-  Float_t chi2[AliITSUTrackCond::kMaxCandidates];
+  static int lastSize = 0;
+  static int *index = 0;
+  static float *chi2 = 0;
+  if (fLayerMaxCandidates>lastSize) {
+    lastSize = fLayerMaxCandidates;
+    delete[] index;
+    delete[] chi2;
+    index = new int[lastSize];
+    chi2  = new float[lastSize];
+  }
   for (int i=fNCandidatesAdded;i--;) chi2[i] = fLayerCandidates[i]->GetChi2GloNrm();
   Sort(fNCandidatesAdded,chi2,index,kFALSE);
   //
-  int nb = Min(fNCandidatesAdded,acceptMax);
-  //  if (nb<fNCandidatesAdded) printf("ValidateAllowedCandidates: %d of %d on lr %d\n",nb,fNCandidatesAdded,ilr);
-  //
-  for (int ib=0;ib<nb;ib++) AddProlongationHypothesis(fLayerCandidates[index[ib]],ilr);
-  // disable unused candidates
-  for (int ib=nb;ib<fNCandidatesAdded;ib++) {
-    /*
-    if (!fLayerCandidates[index[ib]]->ContainsFake()) {
-      printf("Suppress good candidate as %d of %d |",index[ib],fNCandidatesAdded); fLayerCandidates[index[ib]]->Print();
+  int nacc=0,nb=0;
+  if (ilr>0) { // just take 1st acceptMax candidates
+    nb = Min(fNCandidatesAdded,acceptMax);
+    for (int ib=0;ib<nb;ib++) AddProlongationHypothesis(fLayerCandidates[index[ib]],ilr);
+  }
+  else { // for innermost layer test ITS SA backward chi2 and matching to TPC
+    AliITSUSeed* wn0 = fCurrHyp->GetWinner(); // in principle, should be NULL
+    for (nb=0;nb<fNCandidatesAdded;nb++) {
+      AliITSUSeed* sd = fLayerCandidates[index[nb]];    
+      fCurrHyp->SetWinner(sd);
+      if (!CheckBackwardMatching(sd)) MarkSeedFree(sd); // discard bad backward tracks
+      else {
+       AddProlongationHypothesis(sd,ilr);
+       if (++nacc==acceptMax) {nb++; break;} // the rest will be discarded
+      }
     }
-    */
-    MarkSeedFree(fLayerCandidates[index[ib]]);    
+    fCurrHyp->SetWinner(wn0); // restore original winner (NULL?)
   }
+  // disable unused candidates
+  for (int ib=nb;ib<fNCandidatesAdded;ib++) MarkSeedFree(fLayerCandidates[index[ib]]);    
   fNCandidatesAdded = 0; // reset candidates counter
   //
 }
 
+//__________________________________________________________________
+Bool_t AliITSUTrackerGlo::CheckBackwardMatching(AliITSUSeed* seed)
+{
+  // check seed backward propagation chi2 and matching to TPC 
+  double bz0 = GetBz();
+  double rDest = fITS->GetRITSTPCRef(); // reference radius for comparison
+  static AliExternalTrackParam trback;
+  trback = *seed;
+  trback.ResetCovariance(10000);
+  int ndf = seed->GetNLayersHit()*2-5;
+  double chi2sa = RefitTrack(&trback,rDest,1);
+  if (chi2sa<0) return kFALSE;
+  if (ndf>0) chi2sa /= ndf;
+  if (chi2sa>fCurrTrackCond->GetMaxITSSAChi2()) return kFALSE;
+  //
+  // relate to TPC track at outer layer
+  AliExternalTrackParam* tpcSeed = fCurrHyp->GetTPCSeed();
+  if (!trback.Rotate(tpcSeed->GetAlpha()) || !trback.PropagateParamOnlyTo(tpcSeed->GetX(),bz0)) {
+    if (AliDebugLevelClass()>+1 && !seed->ContainsFake()) {
+      AliInfo(Form("Failed to propagate seed to TPC track @ X:%.3f Alpha:%.3f",tpcSeed->GetX(),tpcSeed->GetAlpha()));
+      seed->Print("etp");
+      trback.Print();
+    }
+    return kFALSE; 
+  }
+  double chi2Match = trback.GetPredictedChi2(tpcSeed)/5;
+  if (chi2Match>fCurrTrackCond->GetMaxITSTPCMatchChi2()) return kFALSE;
+  //
+  seed->SetChi2ITSSA(chi2sa);
+  seed->SetChi2ITSTPC(chi2Match);
+  return kTRUE;
+}
+
+//__________________________________________________________________
+void AliITSUTrackerGlo::SaveReducedHypothesesTree(AliITSUTrackHyp* dest)
+{
+  // remove those hypothesis seeds which dont lead to candidates at final layer
+  //
+  // 1st, flag the seeds to save
+  int lr0 = fCurrTrackCond->GetActiveLrInner();
+  for (int isd=0;isd<fCurrHyp->GetNSeeds(lr0);isd++) {
+    AliITSUSeed* seed = fCurrHyp->RemoveSeed(lr0,isd);
+    if (!seed) continue;
+    seed->FlagTree(AliITSUSeed::kSave);
+    dest->AddSeed(seed,lr0);
+  }
+  for (int ilr=0;ilr<fNLrActive;ilr++) {
+    int nsd = fCurrHyp->GetNSeeds(ilr);
+    for (int isd=0;isd<nsd;isd++) {
+      AliITSUSeed* seed = fCurrHyp->RemoveSeed(ilr,isd);
+      if (!seed) continue; // already discarded or saved
+      if (seed->IsSaved()) dest->AddSeed(seed,ilr);
+      else MarkSeedFree(seed);
+    }
+  }
+  //
+  //  AliInfo(Form("SeedsPool: %d, BookedUpTo: %d, free: %d",fSeedsPool.GetSize(),fSeedsPool.GetEntriesFast(),fNFreeSeeds));
+}
+
+//__________________________________________________________________
+void AliITSUTrackerGlo::CleanHypothesis(AliITSUTrackHyp* hyp)
+{
+  // clean hypothesis
+  hyp->SetWinner(0);
+  for (int ilr=0;ilr<fNLrActive;ilr++) {
+    int nsd = hyp->GetNSeeds(ilr);
+    for (int isd=0;isd<nsd;isd++) {
+      AliITSUSeed* seed = hyp->RemoveSeed(ilr,isd);
+      if (!seed) continue; // already discarded or saved
+      MarkSeedFree(seed);
+    }
+  }
+}
+
 //__________________________________________________________________
 void AliITSUTrackerGlo::FlagSplitClusters()
 {
   // set special bit on split clusters using MC info
-  for (int ilr=fITS->GetNLayersActive();ilr--;) {
+  for (int ilr=fNLrActive;ilr--;) {
     int nsplit=0;
     AliITSURecoLayer* lr = fITS->GetLayerActive(ilr);
     for (int isn=lr->GetNSensors();isn--;) {
@@ -1400,56 +1766,177 @@ void AliITSUTrackerGlo::PrintSeedClusters(const AliITSUSeed* seed, Option_t* opt
   //
 }
 
-#ifdef  _FILL_CONTROL_HISTOS_
 //__________________________________________________________________
-void AliITSUTrackerGlo::BookControlHistos()
+void AliITSUTrackerGlo::FlagSeedClusters(const AliITSUSeed* seed, Bool_t flg, UShort_t ref)
+{
+  // mark used clusters
+  int lrID,clID;
+  while (seed) {
+    if ( (clID=seed->GetLrCluster(lrID))>=0 ) {
+      AliITSUClusterPix* cl = (AliITSUClusterPix*)fITS->GetLayerActive(lrID)->GetCluster(clID);
+      if (ref) { // do we need to set or delete cluster->track ref?
+       if (flg) {
+         if (!cl->GetRecoInfo()) cl->SetRecoInfo(ref);  // set ref only if cluster already does not refer to other track, inc.counter
+       }
+       else {
+         if (cl->GetRecoInfo()==ref) cl->SetRecoInfo(0); // unset reference only if it refers to ref, decrease counter     
+       }
+      }
+    }
+    seed = (AliITSUSeed*)seed->GetParent();
+  }
+  //
+}
+
+//__________________________________________________________________
+void AliITSUTrackerGlo::CheckClusterUsage()
+{
+  // check cluster usage info
+  for (int ilr=0;ilr<fNLrActive;ilr++) {
+    AliITSURecoLayer* lr = fITS->GetLayerActive(ilr);
+    int ncl = lr->GetNClusters();
+    int nclUsed = 0;
+    int nclUs0CntShr1 = 0;
+    int nclUs1Cnt0 = 0;
+    int nclUs1Shr1 = 0;
+    int nclUseL = 0;
+    for (int icl=0;icl<ncl;icl++) {
+      AliITSUClusterPix *cl = (AliITSUClusterPix*)lr->GetCluster(icl);
+      int usc = cl->GetClUsage();
+      if (usc<1) {
+       if (cl->IsClusterUsed() || cl->IsClusterShared()) {
+         nclUs0CntShr1++;
+         printf("Lr%d Cl%4d: UseCnt=0 but UseFlg=%d UseShr=%d\n",ilr,icl,cl->IsClusterUsed(),cl->IsClusterShared());
+       }
+       continue;
+      }
+      nclUsed++;
+      if (!cl->IsClusterUsed()) {
+       nclUs1Cnt0++;
+       printf("Lr%d Cl%4d: UseCnt=%d but UseFlg=%d UseShr=%d\n",ilr,icl,usc, cl->IsClusterUsed(),cl->IsClusterShared());
+      }
+      if (cl->IsClusterShared()) {
+       nclUs1Shr1++;
+       printf("Lr%d Cl%4d: UseCnt=%d but UseFlg=%d UseShr=%d\n",ilr,icl,usc, cl->IsClusterUsed(),cl->IsClusterShared());
+      }
+      if (usc>1) {
+       nclUseL++;
+       printf("Lr%d Cl%4d: UseCnt=%d!! but UseFlg=%d UseShr=%d\n",ilr,icl,usc, cl->IsClusterUsed(),cl->IsClusterShared());
+      }
+    }
+    printf("ClUsage Lr%d: Ncl=%5d Nusd=%5d (%5.2f) Use0CS1:%4d Use1C0:%4d Use1S1:%4d UseL:%d\n",
+          ilr,ncl,nclUsed,ncl? float(nclUsed)/ncl : 0, nclUs0CntShr1,nclUs1Cnt0,nclUs1Shr1,nclUseL);
+  }
+}
+
+
+#ifdef  _ITSU_TUNING_MODE_
+//__________________________________________________________________
+TObjArray* AliITSUTrackerGlo::BookControlHistos(const char* pref)
 {
   // book special control histos
-  if (!fCHistoArr) { // create control histos
-    const int kNResDef=7;
-    const double kResDef[kNResDef]={0.05,0.05,0.3, 0.05,1,0.5,1.5};
-    fCHistoArr = new TObjArray();
-    fCHistoArr->SetOwner(kTRUE);
-    const double ptMax=10;
-    const double plMax=10;
-    const double chiMax=100;
-    const int nptbins=50;
-    const int nresbins=400;
-    const int nplbins=50;
-    const int nchbins=200;
-    int nblr = fITS->GetNLayersActive();
-    TString ttl;
-    for (int stp=0;stp<kNTrackingPhases;stp++) {
-      for (int ilr=0;ilr<nblr;ilr++) {
-       int hoffs = stp*kHistosPhase + ilr;
+  TString prefS = pref;
+  prefS.ToLower();
+  TObjArray* dest = new TObjArray;
+  dest->SetOwner(kTRUE);
+  //
+  const int kNResDef=7;
+  const double kResDef[kNResDef]={0.05,0.05,0.3, 0.05,1,0.5,1.5};
+  const double ptMax=10;
+  const double plMax=10;
+  const double chiMax=100;
+  const int nptbins=50;
+  const int nresbins=400;
+  const int nplbins=50;
+  const int nchbins=200;
+  const int maxBr  = 15;
+  const int maxCand = 200;
+  TString ttl;
+  for (int phase=0;phase<kNTrackingPhases;phase++) {
+    for (int pass=0;pass<AliITSUReconstructor::GetRecoParam()->GetNTrackingConditions();pass++) {
+      //
+      for (int ilr=0;ilr<fNLrActive;ilr++) {
+       //
+       // ----------------- These are histos to be filled in Cluster2Tracks of each pass. 
+       // PropagateBack and RefitInward will be stored among the histos of 1st pass
+       if (pass>0 && phase!=kClus2Tracks) continue;
+       //
        double mxdf = ilr>=kNResDef ? kResDef[kNResDef-1] : kResDef[ilr];
-       ttl = Form("S%d_residY%d",stp,ilr);
+       ttl = Form("Pass%d_S%d_residY%d_%s",pass,phase,ilr,pref);
        TH2F* hdy = new TH2F(ttl.Data(),ttl.Data(),nptbins,0,ptMax,nresbins,-mxdf,mxdf);
-       fCHistoArr->AddAtAndExpand(hdy,hoffs + kHResY);
+       dest->AddAtAndExpand(hdy,GetHistoID(ilr,kHResY,pass,phase));
        hdy->SetDirectory(0);
        //
-       ttl = Form("S%d_residYPull%d",stp,ilr); 
+       ttl = Form("Pass%d_S%d_residYPull%d_%s",pass,phase,ilr,pref);   
        TH2F* hdyp = new TH2F(ttl.Data(),ttl.Data(),nptbins,0,ptMax,nplbins,-plMax,plMax);
-       fCHistoArr->AddAtAndExpand(hdyp,hoffs + kHResYP);
+       dest->AddAtAndExpand(hdyp,GetHistoID(ilr,kHResYP,pass,phase));
        hdyp->SetDirectory(0);
        //
-       ttl = Form("S%d_residZ%d",stp,ilr);     
+       ttl = Form("Pass%d_S%d_residZ%d_%s",pass,phase,ilr,pref);       
        TH2F* hdz = new TH2F(ttl.Data(),ttl.Data(),nptbins,0,ptMax,nresbins,-mxdf,mxdf);
-       fCHistoArr->AddAtAndExpand(hdz,hoffs + kHResZ);
+       dest->AddAtAndExpand(hdz,GetHistoID(ilr,kHResZ,pass,phase));
        hdz->SetDirectory(0);
        //
-       ttl = Form("S%d_residZPull%d",stp,ilr);         
+       ttl = Form("Pass%d_S%d_residZPull%d_%s",pass,phase,ilr,pref);           
        TH2F* hdzp = new TH2F(ttl.Data(),ttl.Data(),nptbins,0,ptMax,nplbins,-plMax,plMax);
        hdzp->SetDirectory(0);
-       fCHistoArr->AddAtAndExpand(hdzp,hoffs + kHResZP);
+       dest->AddAtAndExpand(hdzp,GetHistoID(ilr,kHResZP,pass,phase));
        //
-       ttl = Form("S%d_chi2Cl%d",stp,ilr);             
+       ttl = Form("Pass%d_S%d_chi2Cl%d_%s",pass,phase,ilr,pref);               
        TH2F* hchi = new TH2F(ttl.Data(),ttl.Data(),nptbins,0,ptMax, nchbins,0.,chiMax);
        hchi->SetDirectory(0);
-       fCHistoArr->AddAtAndExpand(hchi,hoffs + kHChi2Cl);
+       dest->AddAtAndExpand(hchi,GetHistoID(ilr,kHChi2Cl,pass,phase));
+       //
+       // ------------------- These histos are filled for Clusters2Tracks only
+       if (phase!=kClus2Tracks) continue;
+       //
+       ttl = Form("Pass%d_S%d_chi2Nrm%d_%s",pass,phase,ilr,pref);              
+       TH2F* hchiN = new TH2F(ttl.Data(),ttl.Data(),nptbins,0,ptMax, nchbins,0.,chiMax);
+       hchiN->SetDirectory(0);
+       dest->AddAtAndExpand(hchiN,GetHistoID(ilr,kHChi2Nrm,pass,phase));
+       //
+       ttl = Form("Pass%d_S%d_bestInBranch%d_%s",pass,phase,ilr,pref);         
+       TH2* hnbr = new TH2F(ttl.Data(),ttl.Data(),nptbins,0,ptMax, maxBr,-0.5,maxBr-0.5);
+       hnbr->SetDirectory(0);
+       dest->AddAtAndExpand(hnbr,GetHistoID(ilr,kHBestInBranch,pass,phase));
+       //
+       ttl = Form("Pass%d_S%d_bestInCands%d_%s",pass,phase,ilr,pref);          
+       TH2* hncn = new TH2F(ttl.Data(),ttl.Data(),nptbins,0,ptMax, maxCand,-0.5,maxCand-0.5);
+       hncn->SetDirectory(0);
+       dest->AddAtAndExpand(hncn,GetHistoID(ilr,kHBestInCand,pass,phase));
+       //
+      } // loop over layers
+      //
+      // these are special histos, filled not per layer but in the end of track fit in Clusters2Tracks in EVERY pass
+      //  
+      if (phase==kClus2Tracks) {
+       TH2* hchiMatch = 0; 
+       ttl = Form("Pass%d_Chi2Match_%s",pass,pref);
+       hchiMatch = new TH2F(ttl.Data(),ttl.Data(),nptbins,0,ptMax, nchbins,0.,chiMax);
+       hchiMatch->SetDirectory(0);
+       dest->AddAtAndExpand(hchiMatch,GetHistoID(-1,kHChiMatch,pass,phase));
+       // 
+       TH2* hchiSA = 0; 
+       ttl = Form("Pass%d_Chi2ITSSA_%s",pass,pref);
+       hchiSA = new TH2F(ttl.Data(),ttl.Data(),nptbins,0,ptMax, nchbins/2,0.,chiMax/2);
+       hchiSA->SetDirectory(0);
+       dest->AddAtAndExpand(hchiSA,GetHistoID(-1,kHChiITSSA,pass,phase));
+       //      
       }
-    }
-  }
-  //  
+    } // loop over tracking passes
+  }// loop over tracking phases
+  //
+  return dest;
 }
+
+//__________________________________________________________________
+Int_t AliITSUTrackerGlo::GetHistoID(Int_t lr, Int_t hid, Int_t pass, Int_t phase)
+{
+  // get id for the requested histo
+  if (lr<0) lr=-1;
+  lr++;
+  return pass*kHistosPass + phase*kHistosPhase + lr*kMaxHID + hid;
+  //
+}
+
 #endif