]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - MUON/AliMUONTrackReconstructor.cxx
- AliMUONRecoParam.cxx:
[u/mrichter/AliRoot.git] / MUON / AliMUONTrackReconstructor.cxx
index 3c6c932a3995dc1b5e2367e9e00c2ccb929a4b3a..d087b33c5ebf19e8cd70d83ab8bf0239214028c0 100644 (file)
 
 /* $Id$ */
 
-////////////////////////////////////
-//
-// MUON track reconstructor in ALICE (class renamed from AliMUONEventReconstructor)
-//
-// This class contains as data:
-// * the parameters for the track reconstruction
-// * a pointer to the array of hits to be reconstructed (the event)
-// * a pointer to the array of segments made with these hits inside each station
-// * a pointer to the array of reconstructed tracks
-//
-// It contains as methods, among others:
-// * MakeEventToBeReconstructed to build the array of hits to be reconstructed
-// * MakeSegments to build the segments
-// * MakeTracks to build the tracks
-//
-////////////////////////////////////
-
-#include <stdlib.h>
-#include <Riostream.h>
-#include <TDirectory.h>
-#include <TFile.h>
-#include <TMatrixD.h>
+//-----------------------------------------------------------------------------
+/// \class AliMUONTrackReconstructor
+/// MUON track reconstructor using the original method
+///
+/// This class contains as data:
+/// - the parameters for the track reconstruction
+///
+/// It contains as methods, among others:
+/// - MakeTracks to build the tracks
+//-----------------------------------------------------------------------------
 
 #include "AliMUONTrackReconstructor.h"
-#include "AliMUON.h"
+
 #include "AliMUONConstants.h"
-#include "AliMUONHitForRec.h"
-#include "AliMUONTriggerTrack.h"
-#include "AliMUONTriggerCircuit.h"
-#include "AliMUONRawCluster.h"
-#include "AliMUONLocalTrigger.h"
-#include "AliMUONGlobalTrigger.h"
-#include "AliMUONSegment.h"
+#include "AliMUONVCluster.h"
+#include "AliMUONVClusterServer.h"
+#include "AliMUONVClusterStore.h"
 #include "AliMUONTrack.h"
-#include "AliMUONTrackHit.h"
-#include "AliMagF.h"
-#include "AliRun.h" // for gAlice
-#include "AliRunLoader.h"
-#include "AliLoader.h"
-#include "AliMUONTrackK.h" 
-#include "AliMC.h"
-#include "AliLog.h"
-#include "AliTrackReference.h"
+#include "AliMUONTrackParam.h"
+#include "AliMUONTrackExtrap.h"
 
-//************* Defaults parameters for reconstruction
-const Double_t AliMUONTrackReconstructor::fgkDefaultMinBendingMomentum = 3.0;
-const Double_t AliMUONTrackReconstructor::fgkDefaultMaxBendingMomentum = 3000.0;
-const Double_t AliMUONTrackReconstructor::fgkDefaultMaxChi2 = 100.0;
-const Double_t AliMUONTrackReconstructor::fgkDefaultMaxSigma2Distance = 16.0;
-const Double_t AliMUONTrackReconstructor::fgkDefaultBendingResolution = 0.01;
-const Double_t AliMUONTrackReconstructor::fgkDefaultNonBendingResolution = 0.144;
-const Double_t AliMUONTrackReconstructor::fgkDefaultChamberThicknessInX0 = 0.03;
-// Simple magnetic field:
-// Value taken from macro MUONtracking.C: 0.7 T, hence 7 kG
-// Length and Position from reco_muon.F, with opposite sign:
-// Length = ZMAGEND-ZCOIL
-// Position = (ZMAGEND+ZCOIL)/2
-// to be ajusted differently from real magnetic field ????
-const Double_t AliMUONTrackReconstructor::fgkDefaultSimpleBValue = 7.0;
-const Double_t AliMUONTrackReconstructor::fgkDefaultSimpleBLength = 428.0;
-const Double_t AliMUONTrackReconstructor::fgkDefaultSimpleBPosition = 1019.0;
-const Int_t    AliMUONTrackReconstructor::fgkDefaultRecTrackRefHits = 0;
-const Double_t AliMUONTrackReconstructor::fgkDefaultEfficiency = 0.95;
-
-ClassImp(AliMUONTrackReconstructor) // Class implementation in ROOT context
-
-  //__________________________________________________________________________
-AliMUONTrackReconstructor::AliMUONTrackReconstructor(AliLoader* loader)
-  : TObject()
-{
-  // Constructor for class AliMUONTrackReconstructor
-  SetReconstructionParametersToDefaults();
-  fTrackMethod = 1; //AZ - tracking method (1-default, 2-Kalman)
-  // Memory allocation for the TClonesArray of hits for reconstruction
-  // Is 10000 the right size ????
-  fHitsForRecPtr = new TClonesArray("AliMUONHitForRec", 10000);
-  fNHitsForRec = 0; // really needed or GetEntriesFast sufficient ????
-  // Memory allocation for the TClonesArray's of segments in stations
-  // Is 2000 the right size ????
-  for (Int_t st = 0; st < AliMUONConstants::NTrackingCh()/2; st++) {
-    fSegmentsPtr[st] = new TClonesArray("AliMUONSegment", 2000);
-    fNSegments[st] = 0; // really needed or GetEntriesFast sufficient ????
-  }
-  // Memory allocation for the TClonesArray of reconstructed tracks
-  // Is 10 the right size ????
-  fRecTracksPtr = new TClonesArray("AliMUONTrack", 10);
-  fNRecTracks = 0; // really needed or GetEntriesFast sufficient ????
-  // Memory allocation for the TClonesArray of hits on reconstructed tracks
-  // Is 100 the right size ????
-  fRecTrackHitsPtr = new TClonesArray("AliMUONTrackHit", 100);
-  fNRecTrackHits = 0; // really needed or GetEntriesFast sufficient ????
+#include "AliMpArea.h"
 
-  // Sign of fSimpleBValue according to sign of Bx value at (50,50,-950).
-  Float_t b[3], x[3];
-  x[0] = 50.; x[1] = 50.; x[2] = -950.;
-  gAlice->Field()->Field(x, b);
-  fSimpleBValue = TMath::Sign(fSimpleBValue,(Double_t) b[0]);
-  fSimpleBPosition = TMath::Sign(fSimpleBPosition,(Double_t) x[2]);
-  // See how to get fSimple(BValue, BLength, BPosition)
-  // automatically calculated from the actual magnetic field ????
+#include "AliLog.h"
 
-  AliDebug(1,"AliMUONTrackReconstructor constructed with defaults"); 
-  if ( AliLog::GetGlobalDebugLevel()>0) Dump();
-  AliDebug(1,"Magnetic field from root file:");
-  if ( AliLog::GetGlobalDebugLevel()>0) gAlice->Field()->Dump();
+#include <TMinuit.h>
+#include <Riostream.h>
+#include <TMath.h>
+#include <TMatrixD.h>
 
-  
-  // Initializions for track ref. background events
-  fBkgTrackRefFile = 0;
-  fBkgTrackRefTK = 0;
-  fBkgTrackRefParticles = 0;
-  fBkgTrackRefTTR = 0;
-  fBkgTrackRefEventNumber = -1;
-   
-  // initialize loader's
-  fLoader = loader;
+// Functions to be minimized with Minuit
+void TrackChi2(Int_t &nParam, Double_t *gradient, Double_t &chi2, Double_t *param, Int_t flag);
 
-  // initialize container
-  fMUONData  = new AliMUONData(fLoader,"MUON","MUON");
+/// \cond CLASSIMP
+ClassImp(AliMUONTrackReconstructor) // Class implementation in ROOT context
+/// \endcond
 
-  return;
-}
   //__________________________________________________________________________
-AliMUONTrackReconstructor::AliMUONTrackReconstructor (const AliMUONTrackReconstructor& rhs)
-  : TObject(rhs)
+AliMUONTrackReconstructor::AliMUONTrackReconstructor(const AliMUONRecoParam* recoParam, AliMUONVClusterServer* clusterServer)
+  : AliMUONVTrackReconstructor(recoParam,clusterServer)
 {
-// Protected copy constructor
-
-  AliFatal("Not implemented.");
-}
-
-AliMUONTrackReconstructor & 
-AliMUONTrackReconstructor::operator=(const AliMUONTrackReconstructor& rhs)
-{
-// Protected assignement operator
-
-  if (this == &rhs) return *this;
-
-  AliFatal("Not implemented.");
-    
-  return *this;  
+  /// Constructor
 }
 
   //__________________________________________________________________________
-AliMUONTrackReconstructor::~AliMUONTrackReconstructor(void)
+AliMUONTrackReconstructor::~AliMUONTrackReconstructor()
 {
-  // Destructor for class AliMUONTrackReconstructor
-  delete fHitsForRecPtr; // Correct destruction of everything ???? or delete [] ????
-  for (Int_t st = 0; st < AliMUONConstants::NTrackingCh()/2; st++)
-    delete fSegmentsPtr[st]; // Correct destruction of everything ????
-  return;
-}
+/// Destructor
+} 
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::SetReconstructionParametersToDefaults(void)
+void AliMUONTrackReconstructor::MakeTrackCandidates(AliMUONVClusterStore& clusterStore)
 {
-  // Set reconstruction parameters to default values
-  // Would be much more convenient with a structure (or class) ????
-  fMinBendingMomentum = fgkDefaultMinBendingMomentum;
-  fMaxBendingMomentum = fgkDefaultMaxBendingMomentum;
-  fMaxChi2 = fgkDefaultMaxChi2;
-  fMaxSigma2Distance = fgkDefaultMaxSigma2Distance;
-
-  // ******** Parameters for making HitsForRec
-  // minimum radius,
-  // like in TRACKF_STAT:
-  // 2 degrees for stations 1 and 2, or ch(0...) from 0 to 3;
-  // 30 cm for stations 3 to 5, or ch(0...) from 4 to 9
-  for (Int_t ch = 0; ch < AliMUONConstants::NTrackingCh(); ch++) {
-    if (ch < 4) fRMin[ch] = TMath::Abs(AliMUONConstants::DefaultChamberZ(ch)) *
-                 2.0 * TMath::Pi() / 180.0;
-    else fRMin[ch] = 30.0;
-    // maximum radius at 10 degrees and Z of chamber
-    fRMax[ch] = TMath::Abs(AliMUONConstants::DefaultChamberZ(ch)) *
-                 10.0 * TMath::Pi() / 180.0;
-  }
-
-  // ******** Parameters for making segments
-  // should be parametrized ????
-  // according to interval between chambers in a station ????
-  // Maximum distance in non bending plane
-  // 5 * 0.22 just to remember the way it was made in TRACKF_STAT
-  // SIGCUT*DYMAX(IZ)
-  for (Int_t st = 0; st < AliMUONConstants::NTrackingCh()/2; st++)
-    fSegmentMaxDistNonBending[st] = 5. * 0.22;
-  // Maximum distance in bending plane:
-  // values from TRACKF_STAT, corresponding to (J psi 20cm),
-  // scaled to the real distance between chambers in a station
-  fSegmentMaxDistBending[0] = TMath::Abs( 1.5 *
-                                         (AliMUONConstants::DefaultChamberZ(1) - AliMUONConstants::DefaultChamberZ(0)) / 20.0);
-  fSegmentMaxDistBending[1] = TMath::Abs( 1.5 *
-                                         (AliMUONConstants::DefaultChamberZ(3) - AliMUONConstants::DefaultChamberZ(2)) / 20.0);
-  fSegmentMaxDistBending[2] = TMath::Abs( 3.0 *
-                                         (AliMUONConstants::DefaultChamberZ(5) - AliMUONConstants::DefaultChamberZ(4)) / 20.0);
-  fSegmentMaxDistBending[3] = TMath::Abs( 6.0 *
-                                         (AliMUONConstants::DefaultChamberZ(7) - AliMUONConstants::DefaultChamberZ(6)) / 20.0);
-  fSegmentMaxDistBending[4] = TMath::Abs( 6.0 *
-                                         (AliMUONConstants::DefaultChamberZ(9) - AliMUONConstants::DefaultChamberZ(8)) / 20.0);
-
+  /// To make track candidates (assuming linear propagation if the flag fgkMakeTrackCandidatesFast is set to kTRUE):
+  /// Start with segments station(1..) 4 or 5 then follow track in station 5 or 4.
+  /// Good candidates are made of at least three clusters.
+  /// Keep only best candidates or all of them according to the flag fgkTrackAllTracks.
   
-  fBendingResolution = fgkDefaultBendingResolution;
-  fNonBendingResolution = fgkDefaultNonBendingResolution;
-  fChamberThicknessInX0 = fgkDefaultChamberThicknessInX0;
-  fSimpleBValue = fgkDefaultSimpleBValue;
-  fSimpleBLength = fgkDefaultSimpleBLength;
-  fSimpleBPosition = fgkDefaultSimpleBPosition;
-  fRecTrackRefHits = fgkDefaultRecTrackRefHits;
-  fEfficiency = fgkDefaultEfficiency;
-  return;
-}
-
-//__________________________________________________________________________
-Double_t AliMUONTrackReconstructor::GetImpactParamFromBendingMomentum(Double_t BendingMomentum) const
-{
-  // Returns impact parameter at vertex in bending plane (cm),
-  // from the signed bending momentum "BendingMomentum" in bending plane (GeV/c),
-  // using simple values for dipole magnetic field.
-  // The sign of "BendingMomentum" is the sign of the charge.
-  return (-0.0003 * fSimpleBValue * fSimpleBLength * fSimpleBPosition /
-         BendingMomentum);
-}
+  TClonesArray *segments;
+  AliMUONTrack *track;
+  Int_t iCandidate = 0;
+  Bool_t clusterFound;
 
-//__________________________________________________________________________
-Double_t AliMUONTrackReconstructor::GetBendingMomentumFromImpactParam(Double_t ImpactParam) const
-{
-  // Returns signed bending momentum in bending plane (GeV/c),
-  // the sign being the sign of the charge for particles moving forward in Z,
-  // from the impact parameter "ImpactParam" at vertex in bending plane (cm),
-  // using simple values for dipole magnetic field.
-  return (-0.0003 * fSimpleBValue * fSimpleBLength * fSimpleBPosition /
-         ImpactParam);
-}
+  AliDebug(1,"Enter MakeTrackCandidates");
 
-//__________________________________________________________________________
-void AliMUONTrackReconstructor::SetBkgTrackRefFile(Text_t *BkgTrackRefFileName)
-{
-  // Set background file ... for track ref. hits
-  // Must be called after having loaded the firts signal event
-  AliDebug(1,Form("Enter SetBkgTrackRefFile with BkgTrackRefFileName %s",BkgTrackRefFileName));
+  // Unless we're doing combined tracking, we'll clusterize all stations at once
+  Int_t firstChamber(0);
+  Int_t lastChamber(9);
   
-  if (strlen(BkgTrackRefFileName)) {
-    // BkgTrackRefFileName not empty: try to open the file
-
-    if(AliLog::GetGlobalDebugLevel()>1) {
-      cout << "Before File(Bkg)" << endl; gDirectory->Dump();
-    }
-    fBkgTrackRefFile = new TFile(BkgTrackRefFileName);
-    if(AliLog::GetGlobalDebugLevel()>1) {
-      cout << "After File(Bkg)" << endl; gDirectory->Dump();
-    }
-    if (fBkgTrackRefFile-> IsOpen()) {
-      if(AliLog::GetGlobalDebugLevel()>0) {
-       cout << "Background for Track ref. hits in file: ``" << BkgTrackRefFileName
-            << "'' successfully opened" << endl;}
-    }
-    else {
-      cout << "Background for Track Ref. hits in file: " << BkgTrackRefFileName << endl;
-      cout << "NOT FOUND: EXIT" << endl;
-      exit(0); // right instruction for exit ????
-    }
-    // Arrays for "particles" and "hits"
-    fBkgTrackRefParticles = new TClonesArray("TParticle", 200);
-    // Event number to -1 for initialization
-    fBkgTrackRefEventNumber = -1;
-    // Back to the signal file:
-    // first signal event must have been loaded previously,
-    // otherwise, Segmentation violation at the next instruction
-    // How is it possible to do smething better ????
-    ((gAlice->TreeK())->GetCurrentFile())->cd();
-    if(AliLog::GetGlobalDebugLevel()>1) cout << "After cd(gAlice)" << endl; gDirectory->Dump();
+  if (GetRecoParam()->CombineClusterTrackReco()) {
+    // ... Here's the exception : ask the clustering to reconstruct
+    // clusters *only* in station 4 and 5 for combined tracking
+    firstChamber = 6;
   }
-  return;
-}
 
-//__________________________________________________________________________
-void AliMUONTrackReconstructor::NextBkgTrackRefEvent(void)
-{
-  // Get next event in background file for track ref. hits
-  // Goes back to event number 0 when end of file is reached
-  char treeName[20];
-  
-  AliDebug(1,"Enter NextBkgTrackRefEvent");
-  // Clean previous event
-  if(fBkgTrackRefTK) delete fBkgTrackRefTK;
-  fBkgTrackRefTK = NULL;
-  if(fBkgTrackRefParticles) fBkgTrackRefParticles->Clear();
-  if(fBkgTrackRefTTR) delete fBkgTrackRefTTR;
-  fBkgTrackRefTTR = NULL;
-  // Increment event number
-  fBkgTrackRefEventNumber++;
-  // Get access to Particles and Hits for event from background file
-  if (AliLog::GetGlobalDebugLevel()>1) cout << "Before cd(Bkg)" << endl; gDirectory->Dump();
-  fBkgTrackRefFile->cd();
-  if (AliLog::GetGlobalDebugLevel()>1) cout << "After cd(Bkg)" << endl; gDirectory->Dump();
-  // Particles: TreeK for event and branch "Particles"
-  sprintf(treeName, "TreeK%d", fBkgTrackRefEventNumber);
-  fBkgTrackRefTK = (TTree*)gDirectory->Get(treeName);
-  if (!fBkgTrackRefTK) {
-   
-    AliDebug(1,Form("Cannot find Kine Tree for background event: %d",fBkgTrackRefEventNumber));
-    AliDebug(1,"Goes back to event 0");
+  for (Int_t i = firstChamber; i <= lastChamber; ++i ) 
+  {
+    if (fClusterServer && GetRecoParam()->UseChamber(i)) fClusterServer->Clusterize(i, clusterStore, AliMpArea());
+  }
+  
+  // Loop over stations(1..) 5 and 4 and make track candidates
+  for (Int_t istat=4; istat>=3; istat--) {
     
-    fBkgTrackRefEventNumber = 0;
-    sprintf(treeName, "TreeK%d", fBkgTrackRefEventNumber);
-    fBkgTrackRefTK = (TTree*)gDirectory->Get(treeName);
-    if (!fBkgTrackRefTK) {
-               AliError(Form("cannot find Kine Tree for background event: %d",fBkgTrackRefEventNumber));
-       exit(0);
+    // Make segments in the station
+    segments = MakeSegmentsBetweenChambers(clusterStore, 2*istat, 2*istat+1);
+    
+    // Loop over segments
+    for (Int_t iseg=0; iseg<segments->GetEntriesFast(); iseg++) 
+    {
+      AliDebug(1,Form("Making primary candidate(1..) %d",++iCandidate));
+      
+      // Transform segments to tracks and put them at the end of fRecTracksPtr
+      track = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack((AliMUONObjectPair*)((*segments)[iseg]),GetRecoParam()->GetBendingVertexDispersion());
+      fNRecTracks++;
+      
+      // Look for compatible cluster(s) in the other station
+      if (GetRecoParam()->MakeTrackCandidatesFast())
+       clusterFound = FollowLinearTrackInStation(*track, clusterStore, 7-istat);
+      else clusterFound = FollowTrackInStation(*track, clusterStore, 7-istat);
+      
+      // Remove track if no cluster found
+      if (!clusterFound && GetRecoParam()->RequestStation(7-istat)) {
+        fRecTracksPtr->Remove(track);
+       fNRecTracks--;
+      }
+      
     }
+    
+    // delete the array of segments
+    delete segments;
   }
-  if (fBkgTrackRefTK) 
-    fBkgTrackRefTK->SetBranchAddress("Particles", &fBkgTrackRefParticles);
-  fBkgTrackRefTK->GetEvent(0); // why event 0 ???? necessary ????
-  // Hits: TreeH for event and branch "MUON"
-  sprintf(treeName, "TreeTR%d", fBkgTrackRefEventNumber);
-  fBkgTrackRefTTR = (TTree*)gDirectory->Get(treeName);
-  if (!fBkgTrackRefTTR) {
-         AliError(Form("cannot find Hits Tree for background event: %d",fBkgTrackRefEventNumber));
-      exit(0);
-  }
-  fBkgTrackRefTTR->GetEntries(); // necessary ????
-  // Back to the signal file
-  ((gAlice->TreeK())->GetCurrentFile())->cd();
-  if (AliLog::GetGlobalDebugLevel()>1) 
-    cout << "After cd(gAlice)" << endl; gDirectory->Dump();
-  return;
-}
-
-//__________________________________________________________________________
-void AliMUONTrackReconstructor::EventReconstruct(void)
-{
-  // To reconstruct one event
-  AliDebug(1,"Enter EventReconstruct");
-  MakeEventToBeReconstructed();
-  MakeSegments();
-  MakeTracks();
-  if (fMUONData->IsTriggerTrackBranchesInTree()) 
-    ValidateTracksWithTrigger(); 
-
-  // Add tracks to MUON data container 
-  for(Int_t i=0; i<GetNRecTracks(); i++) {
-    AliMUONTrack * track = (AliMUONTrack*) GetRecTracksPtr()->At(i);
-    fMUONData->AddRecTrack(*track);
-  }
-
-  return;
-}
-
-//__________________________________________________________________________
-void AliMUONTrackReconstructor::EventReconstructTrigger(void)
-{
-  // To reconstruct one event
-  AliDebug(1,"Enter EventReconstructTrigger");
-  MakeTriggerTracks();  
-  return;
-}
-
-  //__________________________________________________________________________
-void AliMUONTrackReconstructor::ResetHitsForRec(void)
-{
-  // To reset the array and the number of HitsForRec,
-  // and also the number of HitsForRec
-  // and the index of the first HitForRec per chamber
-  if (fHitsForRecPtr) fHitsForRecPtr->Clear();
-  fNHitsForRec = 0;
-  for (Int_t ch = 0; ch < AliMUONConstants::NTrackingCh(); ch++)
-    fNHitsForRecPerChamber[ch] = fIndexOfFirstHitForRecPerChamber[ch] = 0;
-  return;
+  
+  fRecTracksPtr->Compress(); // this is essential before checking tracks
+  
+  // Keep all different tracks or only the best ones as required
+  if (GetRecoParam()->TrackAllTracks()) RemoveIdenticalTracks();
+  else RemoveDoubleTracks();
+  
+  AliDebug(1,Form("Number of good candidates = %d",fNRecTracks));
+  
 }
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::ResetSegments(void)
+void AliMUONTrackReconstructor::MakeMoreTrackCandidates(AliMUONVClusterStore& clusterStore)
 {
-  // To reset the TClonesArray of segments and the number of Segments
-  // for all stations
-  for (Int_t st = 0; st < AliMUONConstants::NTrackingCh()/2; st++) {
-    if (fSegmentsPtr[st]) fSegmentsPtr[st]->Clear();
-    fNSegments[st] = 0;
+  /// To make extra track candidates (assuming linear propagation if the flag fgkMakeTrackCandidatesFast is set to kTRUE):
+  /// clustering is supposed to be already done
+  /// Start with segments made of 1 cluster in each of the stations 4 and 5 then follow track in remaining chambers.
+  /// Good candidates are made of at least three clusters if both station are requested (two otherwise).
+  /// Keep only best candidates or all of them according to the flag fgkTrackAllTracks.
+  
+  TClonesArray *segments;
+  AliMUONTrack *track;
+  Int_t iCandidate = 0, iCurrentTrack, nCurrentTracks;
+  Bool_t clusterFound;
+  
+  AliDebug(1,"Enter MakeMoreTrackCandidates");
+  
+  // Double loop over chambers in stations(1..) 4 and 5 to make track candidates
+  for (Int_t ich1 = 6; ich1 <= 7; ich1++) {
+    for (Int_t ich2 = 8; ich2 <= 9; ich2++) {
+      
+      // Make segments in the station
+      segments = MakeSegmentsBetweenChambers(clusterStore, ich1, ich2);
+      
+      // Loop over segments
+      for (Int_t iseg=0; iseg<segments->GetEntriesFast(); iseg++) 
+      {
+       AliDebug(1,Form("Making primary candidate(1..) %d",++iCandidate));
+       
+       // Transform segments to tracks and put them at the end of fRecTracksPtr
+       iCurrentTrack = fRecTracksPtr->GetLast()+1;
+       track = new ((*fRecTracksPtr)[iCurrentTrack]) AliMUONTrack((AliMUONObjectPair*)((*segments)[iseg]),GetRecoParam()->GetBendingVertexDispersion());
+       fNRecTracks++;
+       
+       // Look for compatible cluster(s) in the second chamber of station 5
+       if (GetRecoParam()->MakeTrackCandidatesFast())
+         clusterFound = FollowLinearTrackInChamber(*track, clusterStore, 17-ich2);
+       else clusterFound = FollowTrackInChamber(*track, clusterStore, 17-ich2);
+       
+       // skip the original track in case it has been removed
+       if (GetRecoParam()->TrackAllTracks() && clusterFound) iCurrentTrack++;
+       
+       // loop over every new tracks
+       nCurrentTracks = fRecTracksPtr->GetLast()+1;
+       while (iCurrentTrack < nCurrentTracks) {
+         track = (AliMUONTrack*) fRecTracksPtr->UncheckedAt(iCurrentTrack);
+         
+         // Look for compatible cluster(s) in the second chamber of station 4
+         if (GetRecoParam()->MakeTrackCandidatesFast())
+           FollowLinearTrackInChamber(*track, clusterStore, 13-ich1);
+         else FollowTrackInChamber(*track, clusterStore, 13-ich1);
+         
+         iCurrentTrack++;
+       }
+       
+      }
+      
+      // delete the array of segments
+      delete segments;
+    }
   }
-  return;
-}
-
-  //__________________________________________________________________________
-void AliMUONTrackReconstructor::ResetTracks(void)
-{
-  // To reset the TClonesArray of reconstructed tracks
-  if (fRecTracksPtr) fRecTracksPtr->Delete();
-  // Delete in order that the Track destructors are called,
-  // hence the space for the TClonesArray of pointers to TrackHit's is freed
-  fNRecTracks = 0;
-  return;
-}
-
-
-  //__________________________________________________________________________
-void AliMUONTrackReconstructor::ResetTrackHits(void)
-{
-  // To reset the TClonesArray of hits on reconstructed tracks
-  if (fRecTrackHitsPtr) fRecTrackHitsPtr->Clear();
-  fNRecTrackHits = 0;
-  return;
+  
+  fRecTracksPtr->Compress(); // this is essential before checking tracks
+  
+  // Keep all different tracks or only the best ones as required
+  if (GetRecoParam()->TrackAllTracks()) RemoveIdenticalTracks();
+  else RemoveDoubleTracks();
+  
+  AliDebug(1,Form("Number of good candidates = %d",fNRecTracks));
+  
 }
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::MakeEventToBeReconstructed(void)
+void AliMUONTrackReconstructor::FollowTracks(AliMUONVClusterStore& clusterStore)
 {
-  // To make the list of hits to be reconstructed,
-  // either from the track ref. hits or from the raw clusters
-  // according to the parameter set for the reconstructor
-//   TString evfoldname = AliConfig::GetDefaultEventFolderName();//to be interfaced properly
-  
-//   AliRunLoader* rl = AliRunLoader::GetRunLoader(evfoldname);
-//   if (rl == 0x0)
-//    {
-//      Error("MakeEventToBeReconstructed",
-//            "Can not find Run Loader in Event Folder named %s.",
-//            evfoldname.Data());
-//      return;
-//    }
-//   AliLoader* gime = rl->GetLoader("MUONLoader");
-//   if (gime == 0x0)
-//    {
-//      Error("MakeEventToBeReconstructed","Can not get MUON Loader from Run Loader.");
-//      return;
-//    }
-  AliRunLoader *runLoader = fLoader->GetRunLoader();
-
-  AliDebug(1,"Enter MakeEventToBeReconstructed");
-  ResetHitsForRec();
-  if (fRecTrackRefHits == 1) {
-    // Reconstruction from track ref. hits
-    // Back to the signal file
-    TTree* treeTR = runLoader->TreeTR();
-    if (treeTR == 0x0)
-      {
-       Int_t retval = runLoader->LoadTrackRefs("READ");
-       if ( retval)
-          {
-            AliError("Error occured while loading hits.");
-            return;
-          }
-       treeTR = runLoader->TreeTR();
-       if (treeTR == 0x0)
-          {
-           AliError("Can not get TreeTR");
-           return;
-          }
+  /// Follow tracks in stations(1..) 3, 2 and 1
+  AliDebug(1,"Enter FollowTracks");
+  
+  AliMUONTrack *track, *nextTrack;
+  AliMUONTrackParam *trackParam, *nextTrackParam;
+  Int_t currentNRecTracks;
+  
+  Double_t sigmaCut2 = GetRecoParam()->GetSigmaCutForTracking() *
+                       GetRecoParam()->GetSigmaCutForTracking();
+  
+  for (Int_t station = 2; station >= 0; station--) {
+    
+    // Save the actual number of reconstructed track in case of
+    // tracks are added or suppressed during the tracking procedure
+    // !! Do not compress fRecTracksPtr until the end of the loop over tracks !!
+    currentNRecTracks = fNRecTracks;
+    
+    for (Int_t iRecTrack = 0; iRecTrack <currentNRecTracks; iRecTrack++) {
+      AliDebug(1,Form("FollowTracks: track candidate(1..) %d", iRecTrack+1));
+      
+      track = (AliMUONTrack*) fRecTracksPtr->UncheckedAt(iRecTrack);
+      
+      // Fit the track:
+      // Do not take into account the multiple scattering to speed up the fit
+      // Calculate the track parameter covariance matrix
+      // If there is no cluster out of station 4 or 5 then use the vertex to better constrain the fit
+      if (((AliMUONTrackParam*) track->GetTrackParamAtCluster()->First())->GetClusterPtr()->GetChamberId() > 5)
+       Fit(*track, kFALSE, kTRUE, kTRUE);
+      else Fit(*track, kFALSE, kFALSE, kTRUE);
+      
+      // remove track with absolute bending momentum out of limits
+      // or if the normalized chi2 is too high
+      Double_t bendingMomentum = TMath::Abs(1. / ((AliMUONTrackParam*)track->GetTrackParamAtCluster()->First())->GetInverseBendingMomentum());
+      if (bendingMomentum < GetRecoParam()->GetMinBendingMomentum() ||
+         bendingMomentum > GetRecoParam()->GetMaxBendingMomentum() ||
+         track->GetNormalizedChi2() > sigmaCut2) {
+       fRecTracksPtr->Remove(track);
+       fNRecTracks--;
+       continue;
       }
+      
+      // save parameters from fit into smoothed parameters to complete track afterward
+      if (GetRecoParam()->ComplementTracks()) {
+       
+       if (station==2) { // save track parameters on stations 4 and 5
+         
+         // extrapolate track parameters and covariances at each cluster
+         track->UpdateCovTrackParamAtCluster();
+         
+         // save them
+         trackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->First();
+         while (trackParam) {
+           trackParam->SetSmoothParameters(trackParam->GetParameters());
+           trackParam->SetSmoothCovariances(trackParam->GetCovariances());
+           trackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->After(trackParam);
+         }
+         
+       } else { // or save track parameters on last station only
+         
+         trackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->First();
+         if (trackParam->GetClusterPtr()->GetChamberId() < 2*(station+2)) {
+           
+           // save parameters from fit
+           trackParam->SetSmoothParameters(trackParam->GetParameters());
+           trackParam->SetSmoothCovariances(trackParam->GetCovariances());
+           
+           // save parameters extrapolated to the second chamber of the same station if it has been hit
+           nextTrackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->After(trackParam);
+           if (nextTrackParam->GetClusterPtr()->GetChamberId() < 2*(station+2)) {
+             
+             // reset parameters and covariances
+             nextTrackParam->SetParameters(trackParam->GetParameters());
+             nextTrackParam->SetZ(trackParam->GetZ());
+             nextTrackParam->SetCovariances(trackParam->GetCovariances());
+             
+             // extrapolate them to the z of the corresponding cluster
+             AliMUONTrackExtrap::ExtrapToZCov(nextTrackParam, nextTrackParam->GetClusterPtr()->GetZ());
+             
+             // save them
+             nextTrackParam->SetSmoothParameters(nextTrackParam->GetParameters());
+             nextTrackParam->SetSmoothCovariances(nextTrackParam->GetCovariances());
+             
+           }
+           
+         }
+         
+       }
+       
+      }
+      
+      // Look for compatible cluster(s) in station(0..) "station"
+      if (!FollowTrackInStation(*track, clusterStore, station)) {
+       
+       // Try to recover track if required
+       if (GetRecoParam()->RecoverTracks()) {
+         
+         // work on a copy of the track if this station is not required
+         // to keep the case where no cluster is reconstructed as a possible candidate
+         if (!GetRecoParam()->RequestStation(station)) {
+           track = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(*track);
+           fNRecTracks++;
+         }
+         
+         // try to recover
+         if (!RecoverTrack(*track, clusterStore, station)) {
+           // remove track if no cluster found
+           fRecTracksPtr->Remove(track);
+           fNRecTracks--;
+         }
+         
+       } else if (GetRecoParam()->RequestStation(station)) {
+         // remove track if no cluster found
+         fRecTracksPtr->Remove(track);
+         fNRecTracks--;
+       } 
+       
+      }
+      
+    }
     
-    AddHitsForRecFromTrackRef(treeTR,1);
+    // Compress fRecTracksPtr for the next step
+    fRecTracksPtr->Compress();
+    
+    // Keep only the best tracks if required
+    if (!GetRecoParam()->TrackAllTracks()) RemoveDoubleTracks();
     
-    // Background hits
-    AddHitsForRecFromTrackRef(fBkgTrackRefTTR,0);
-    // Sort HitsForRec in increasing order with respect to chamber number
-    SortHitsForRecWithIncreasingChamber();
-  }
-  else {
-    // Reconstruction from raw clusters
-    // AliMUON *MUON  = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
-    // Security on MUON ????
-    // TreeR assumed to be be "prepared" in calling function
-    // by "MUON->GetTreeR(nev)" ????
-    TTree *treeR = fLoader->TreeR();
-    //AZ? fMUONData->SetTreeAddress("RC");
-    AddHitsForRecFromRawClusters(treeR);
-    // No sorting: it is done automatically in the previous function
   }
-  AliDebug(1,"End of MakeEventToBeReconstructed");
-    if (AliLog::GetGlobalDebugLevel() > 0) {
-      AliDebug(1, Form("NHitsForRec: %d",fNHitsForRec));
-      for (Int_t ch = 0; ch < AliMUONConstants::NTrackingCh(); ch++) {
-       AliDebug(1, Form("Chamber(0...): %d",ch));
-       AliDebug(1, Form("NHitsForRec: %d", fNHitsForRecPerChamber[ch]));
-       AliDebug(1, Form("Index(first HitForRec): %d", fIndexOfFirstHitForRecPerChamber[ch]));
-       for (Int_t hit = fIndexOfFirstHitForRecPerChamber[ch];
-            hit < fIndexOfFirstHitForRecPerChamber[ch] + fNHitsForRecPerChamber[ch];
-            hit++) {
-         AliDebug(1, Form("HitForRec index(0...): %d",hit));
-         ((*fHitsForRecPtr)[hit])->Dump();
+  
+  // Last fit of track candidates with all stations
+  // Take into account the multiple scattering and remove bad tracks
+  Int_t trackIndex = -1;
+  track = (AliMUONTrack*) fRecTracksPtr->First();
+  while (track) {
+    
+    trackIndex++;
+    nextTrack = (AliMUONTrack*) fRecTracksPtr->After(track); // prepare next track
+    
+    Fit(*track, kTRUE, kFALSE, kTRUE);
+    
+    // Printout for debuging
+    if (AliLog::GetGlobalDebugLevel() >= 3) {
+      cout << "FollowTracks: track candidate(0..) " << trackIndex << " after final fit" << endl;
+      track->RecursiveDump();
+    } 
+    
+    // Remove the track if the normalized chi2 is too high
+    if (track->GetNormalizedChi2() > sigmaCut2) {
+      fRecTracksPtr->Remove(track);
+      fNRecTracks--;
+      track = nextTrack;
+      continue;
+    }
+    
+    // save parameters from fit into smoothed parameters to complete track afterward
+    if (GetRecoParam()->ComplementTracks()) {
+      
+      trackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->First();
+      if (trackParam->GetClusterPtr()->GetChamberId() < 2) {
+       
+       // save parameters from fit
+       trackParam->SetSmoothParameters(trackParam->GetParameters());
+       trackParam->SetSmoothCovariances(trackParam->GetCovariances());
+       
+       // save parameters extrapolated to the second chamber of the same station if it has been hit
+       nextTrackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->After(trackParam);
+       if (nextTrackParam->GetClusterPtr()->GetChamberId() < 2) {
+         
+         // reset parameters and covariances
+         nextTrackParam->SetParameters(trackParam->GetParameters());
+         nextTrackParam->SetZ(trackParam->GetZ());
+         nextTrackParam->SetCovariances(trackParam->GetCovariances());
+         
+         // extrapolate them to the z of the corresponding cluster
+         AliMUONTrackExtrap::ExtrapToZCov(nextTrackParam, nextTrackParam->GetClusterPtr()->GetZ());
+         
+         // save them
+         nextTrackParam->SetSmoothParameters(nextTrackParam->GetParameters());
+         nextTrackParam->SetSmoothCovariances(nextTrackParam->GetCovariances());
+         
+       }
+       
       }
+      
     }
+    
+    track = nextTrack;
+    
   }
-  return;
+  
+  fRecTracksPtr->Compress();
+  
 }
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::AddHitsForRecFromTrackRef(TTree *TTR, Int_t signal)
+Bool_t AliMUONTrackReconstructor::FollowTrackInChamber(AliMUONTrack &trackCandidate, AliMUONVClusterStore& clusterStore, Int_t nextChamber)
 {
-  // To add to the list of hits for reconstruction
-  // the signal hits from a track reference tree TreeTR.
-  TClonesArray *listOfTrackRefs = NULL;
-  AliTrackReference *trackRef;
+  /// Follow trackCandidate in chamber(0..) nextChamber and search for compatible cluster(s)
+  /// Keep all possibilities or only the best one(s) according to the flag fgkTrackAllTracks:
+  /// kTRUE:  duplicate "trackCandidate" if there are several possibilities and add the new tracks at the end of
+  ///         fRecTracksPtr to avoid conficts with other track candidates at this current stage of the tracking procedure.
+  ///         Remove the obsolete "trackCandidate" at the end.
+  /// kFALSE: add only the best cluster(s) to the "trackCandidate". Try to add a couple of clusters in priority.
+  AliDebug(1,Form("Enter FollowTrackInChamber(1..) %d", nextChamber+1));
   
-  Int_t track = 0;
-  AliDebug(2,Form("Enter AddHitsForRecFromTrackRef with TTR: %d",  TTR));
-  if (TTR == NULL) return;
+  Double_t chi2WithOneCluster = 1.e10;
+  Double_t maxChi2WithOneCluster = 2. * GetRecoParam()->GetSigmaCutForTracking() *
+                                       GetRecoParam()->GetSigmaCutForTracking(); // 2 because 2 quantities in chi2
+  Double_t bestChi2WithOneCluster = maxChi2WithOneCluster;
+  Bool_t foundOneCluster = kFALSE;
+  AliMUONTrack *newTrack = 0x0;
+  AliMUONVCluster *cluster;
+  AliMUONTrackParam extrapTrackParam;
+  AliMUONTrackParam extrapTrackParamAtCh;
+  AliMUONTrackParam extrapTrackParamAtCluster;
+  AliMUONTrackParam bestTrackParamAtCluster;
   
-  listOfTrackRefs = CleanTrackRefs(TTR);
-
-  Int_t ntracks = listOfTrackRefs->GetEntriesFast();
-
-  AliDebug(2,Form("ntracks: %d", ntracks));
-
-  for (Int_t index = 0; index < ntracks; index++) {
-    trackRef = (AliTrackReference*) listOfTrackRefs->At(index);
-    track =  trackRef->GetTrack();
+  // Get track parameters according to the propagation direction
+  if (nextChamber > 7) extrapTrackParamAtCh = *(AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->Last();
+  else extrapTrackParamAtCh = *(AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->First();
+  
+  // Printout for debuging
+  if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
+    cout<<endl<<"Track parameters and covariances at first cluster:"<<endl;
+    extrapTrackParamAtCh.GetParameters().Print();
+    extrapTrackParamAtCh.GetCovariances().Print();
+  }
+  
+  // Add MCS effect
+  AliMUONTrackExtrap::AddMCSEffect(&extrapTrackParamAtCh,AliMUONConstants::ChamberThicknessInX0(),1.);
+  
+  // Add MCS in the missing chamber(s) if any
+  Int_t currentChamber = extrapTrackParamAtCh.GetClusterPtr()->GetChamberId();
+  while (currentChamber > nextChamber + 1) {
+    // extrapolation to the missing chamber
+    currentChamber--;
+    AliMUONTrackExtrap::ExtrapToZCov(&extrapTrackParamAtCh, AliMUONConstants::DefaultChamberZ(currentChamber));
+    // add MCS effect
+    AliMUONTrackExtrap::AddMCSEffect(&extrapTrackParamAtCh,AliMUONConstants::ChamberThicknessInX0(),1.);
+  }
+  
+  //Extrapolate trackCandidate to chamber
+  AliMUONTrackExtrap::ExtrapToZCov(&extrapTrackParamAtCh, AliMUONConstants::DefaultChamberZ(nextChamber));
+  
+  // Printout for debuging
+  if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
+    cout<<endl<<"Track parameters and covariances at first cluster extrapolated to z = "<<AliMUONConstants::DefaultChamberZ(nextChamber)<<":"<<endl;
+    extrapTrackParamAtCh.GetParameters().Print();
+    extrapTrackParamAtCh.GetCovariances().Print();
+  }
+  
+  // Printout for debuging
+  if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+    cout << "FollowTrackInStation: look for clusters in chamber(1..): " << nextChamber+1 << endl;
+  }
+  
+  // Ask the clustering to reconstruct new clusters around the track position in the current chamber
+  // except for station 4 and 5 that are already entirely clusterized
+  if (GetRecoParam()->CombineClusterTrackReco()) {
+    if (nextChamber < 6) AskForNewClustersInChamber(extrapTrackParamAtCh, clusterStore, nextChamber);
+  }
+  
+  // Create iterators to loop over clusters in both chambers
+  TIter next(clusterStore.CreateChamberIterator(nextChamber,nextChamber));
+  
+  // look for cluster in chamber
+  while ( ( cluster = static_cast<AliMUONVCluster*>(next()) ) ) {
     
-    NewHitForRecFromTrackRef(trackRef,track,signal);
-  } // end of track ref.
+    // try to add the current cluster fast
+    if (!TryOneClusterFast(extrapTrackParamAtCh, cluster)) continue;
+    
+    // try to add the current cluster accuratly
+    chi2WithOneCluster = TryOneCluster(extrapTrackParamAtCh, cluster, extrapTrackParamAtCluster);
+    
+    // if good chi2 then consider to add cluster
+    if (chi2WithOneCluster < maxChi2WithOneCluster) {
+      foundOneCluster = kTRUE;
+      
+      // Printout for debuging
+      if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+       cout << "FollowTrackInStation: found one cluster in chamber(1..): " << nextChamber+1
+       << " (Chi2 = " << chi2WithOneCluster << ")" << endl;
+       cluster->Print();
+      }
+      
+      if (GetRecoParam()->TrackAllTracks()) {
+       // copy trackCandidate into a new track put at the end of fRecTracksPtr and add the new cluster
+       newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(trackCandidate);
+       UpdateTrack(*newTrack,extrapTrackParamAtCluster);
+       fNRecTracks++;
+       
+       // Printout for debuging
+       if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+         cout << "FollowTrackInStation: added one cluster in chamber(1..): " << nextChamber+1 << endl;
+         if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
+       }
+       
+      } else if (chi2WithOneCluster < bestChi2WithOneCluster) {
+       // keep track of the best single cluster except if a couple of clusters has already been found
+       bestChi2WithOneCluster = chi2WithOneCluster;
+       bestTrackParamAtCluster = extrapTrackParamAtCluster;
+      }
+      
+    }
+    
+  }
+  
+  // fill out the best track if required else clean up the fRecTracksPtr array
+  if (!GetRecoParam()->TrackAllTracks()) {
+    if (foundOneCluster) {
+      UpdateTrack(trackCandidate,bestTrackParamAtCluster);
+      
+      // Printout for debuging
+      if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+        cout << "FollowTrackInStation: added the best cluster in chamber(1..): " << bestTrackParamAtCluster.GetClusterPtr()->GetChamberId()+1 << endl;
+        if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
+      }
+      
+    } else return kFALSE;
+    
+  } else if (foundOneCluster) {
+    
+    // remove obsolete track
+    fRecTracksPtr->Remove(&trackCandidate);
+    fNRecTracks--;
+    
+  } else return kFALSE;
+  
+  return kTRUE;
   
-  listOfTrackRefs->Delete();
-  delete listOfTrackRefs;
-  return;
 }
 
-
   //__________________________________________________________________________
-AliMUONHitForRec* AliMUONTrackReconstructor::NewHitForRecFromTrackRef(AliTrackReference* Hit, Int_t TrackNumber, Int_t Signal)
+Bool_t AliMUONTrackReconstructor::FollowTrackInStation(AliMUONTrack &trackCandidate, AliMUONVClusterStore& clusterStore, Int_t nextStation)
 {
-  // To make a new hit for reconstruction from a track ref. hit pointed to by "Hit",
-  // with  the track numbered "TrackNumber",
-  // either from signal ("Signal" = 1) or background ("Signal" = 0) event.
-  // Selects hits in tracking (not trigger) chambers.
-  // Takes into account the efficiency (fEfficiency)
-  // and the smearing from resolution (fBendingResolution and fNonBendingResolution).
-  // Adds a condition on the radius between RMin and RMax
-  // to better simulate the real chambers.
-  // Returns the pointer to the new hit for reconstruction,
-  // or NULL in case of inefficiency or non tracking chamber or bad radius.
-  // No condition on at most 20 cm from a muon from a resonance
-  // like in Fortran TRACKF_STAT.
-  AliMUONHitForRec* hitForRec;
-  Double_t bendCoor, nonBendCoor, radius;
-  Int_t chamber = AliMUONConstants::ChamberNumber(Hit->Z()); // chamber(0...)
-  if (chamber < 0) return NULL;
-  // only in tracking chambers (fChamber starts at 1)
-  if (chamber >= AliMUONConstants::NTrackingCh()) return NULL;
-  // only if hit is efficient (keep track for checking ????)
-  if (gRandom->Rndm() > fEfficiency) return NULL;
-  // only if radius between RMin and RMax
-  bendCoor = Hit->Y();
-  nonBendCoor = Hit->X();
-  radius = TMath::Sqrt((bendCoor * bendCoor) + (nonBendCoor * nonBendCoor));
-  // This cut is not needed with a realistic chamber geometry !!!!
-//   if ((radius < fRMin[chamber]) || (radius > fRMax[chamber])) return NULL;
-  // new AliMUONHitForRec from track ref. hit and increment number of AliMUONHitForRec's
-  hitForRec = new ((*fHitsForRecPtr)[fNHitsForRec]) AliMUONHitForRec(Hit);
-  fNHitsForRec++;
-  // add smearing from resolution
-  hitForRec->SetBendingCoor(bendCoor + gRandom->Gaus(0., fBendingResolution));
-  hitForRec->SetNonBendingCoor(nonBendCoor
-                              + gRandom->Gaus(0., fNonBendingResolution));
-//   // !!!! without smearing
-//   hitForRec->SetBendingCoor(bendCoor);
-//   hitForRec->SetNonBendingCoor(nonBendCoor);
-  // more information into HitForRec
-  //  resolution: angular effect to be added here ????
-  hitForRec->SetBendingReso2(fBendingResolution * fBendingResolution);
-  hitForRec->SetNonBendingReso2(fNonBendingResolution * fNonBendingResolution);
-  //   track ref. info
-  hitForRec->SetTTRTrack(TrackNumber);
-  hitForRec->SetTrackRefSignal(Signal);
-  if (AliLog::GetGlobalDebugLevel()> 1) {
-    AliDebug(2,Form("Track: %d", TrackNumber));
-    Hit->Dump();
-    cout << "AliMUONHitForRec number (1...): " << fNHitsForRec << endl;
-    hitForRec->Dump();
+  /// Follow trackCandidate in station(0..) nextStation and search for compatible cluster(s)
+  /// Keep all possibilities or only the best one(s) according to the flag fgkTrackAllTracks:
+  /// kTRUE:  duplicate "trackCandidate" if there are several possibilities and add the new tracks at the end of
+  ///         fRecTracksPtr to avoid conficts with other track candidates at this current stage of the tracking procedure.
+  ///         Remove the obsolete "trackCandidate" at the end.
+  /// kFALSE: add only the best cluster(s) to the "trackCandidate". Try to add a couple of clusters in priority.
+  AliDebug(1,Form("Enter FollowTrackInStation(1..) %d", nextStation+1));
+  
+  // Order the chamber according to the propagation direction (tracking starts with chamber 2):
+  // - nextStation == station(1...) 5 => forward propagation
+  // - nextStation < station(1...) 5 => backward propagation
+  Int_t ch1, ch2;
+  if (nextStation==4) {
+    ch1 = 2*nextStation+1;
+    ch2 = 2*nextStation;
+  } else {
+    ch1 = 2*nextStation;
+    ch2 = 2*nextStation+1;
   }
-  return hitForRec;
-}
-  //__________________________________________________________________________
-TClonesArray* AliMUONTrackReconstructor::CleanTrackRefs(TTree *treeTR)
-{
-  // Make hits from track ref..  
-  // Re-calculate hits parameters because two AliTrackReferences are recorded for
-  // each chamber (one when particle is entering + one when particle is leaving 
-  // the sensitive volume) 
-  AliTrackReference *trackReference;
-  Float_t x1, y1, z1, pX1, pY1, pZ1;
-  Float_t x2, y2, z2, pX2, pY2, pZ2;
-  Int_t track1, track2;
-  Int_t nRec = 0;
-  Float_t maxGasGap = 1.; // cm 
-  Int_t iHit1 = 0;
-  Int_t iHitMin = 0;
-  AliTrackReference *trackReferenceNew = new AliTrackReference();
-  
-  TClonesArray* trackRefs = new TClonesArray("AliTrackReference", 10);
-  TClonesArray* cleanTrackRefs = new TClonesArray("AliTrackReference", 10);
-
-  if (treeTR == NULL) return NULL;
-  TBranch* branch = treeTR->GetBranch("MUON");
-  if (branch == NULL) return NULL;
-  branch->SetAddress(&trackRefs);
-
-  Int_t nTrack = (Int_t)treeTR->GetEntries();
-  for (Int_t iTrack  = 0; iTrack < nTrack; iTrack++) {
-    treeTR->GetEntry(iTrack);
-    iHitMin = 0;
-    iHit1 = 0;
-    while (iHit1 < trackRefs->GetEntries()) {
-      trackReference = (AliTrackReference*)trackRefs->At(iHit1);
-      x1 = trackReference->X();
-      y1 = trackReference->Y();
-      z1 = trackReference->Z();
-      pX1 = trackReference->Px();
-      pY1 = trackReference->Py();
-      pZ1 = trackReference->Pz();
-      track1 = trackReference->GetTrack();
-      nRec = 1;
-      iHitMin = iHit1+1;
-      for (Int_t iHit2 = iHit1+1; iHit2 < trackRefs->GetEntries(); iHit2++) {
-       trackReference = (AliTrackReference*)trackRefs->At(iHit2);
-       x2 = trackReference->X();
-       y2 = trackReference->Y();
-       z2 = trackReference->Z();
-       pX2 = trackReference->Px();
-       pY2 = trackReference->Py();
-       pZ2 = trackReference->Pz();
-       track2 = trackReference->GetTrack();
-       if (track2 == track1 && TMath::Abs(z2-z1) < maxGasGap ) {
-         nRec++;
-         x1 += x2;
-         y1 += y2;
-         z1 += z2;                             
-         pX1 += pX2;
-         pY1 += pY2;
-         pZ1 += pZ2;
-         iHitMin = iHit2+1;
+  
+  Double_t chi2WithOneCluster = 1.e10;
+  Double_t chi2WithTwoClusters = 1.e10;
+  Double_t maxChi2WithOneCluster = 2. * GetRecoParam()->GetSigmaCutForTracking() *
+                                       GetRecoParam()->GetSigmaCutForTracking(); // 2 because 2 quantities in chi2
+  Double_t maxChi2WithTwoClusters = 4. * GetRecoParam()->GetSigmaCutForTracking() *
+                                        GetRecoParam()->GetSigmaCutForTracking(); // 4 because 4 quantities in chi2
+  Double_t bestChi2WithOneCluster = maxChi2WithOneCluster;
+  Double_t bestChi2WithTwoClusters = maxChi2WithTwoClusters;
+  Bool_t foundOneCluster = kFALSE;
+  Bool_t foundTwoClusters = kFALSE;
+  AliMUONTrack *newTrack = 0x0;
+  AliMUONVCluster *clusterCh1, *clusterCh2;
+  AliMUONTrackParam extrapTrackParam;
+  AliMUONTrackParam extrapTrackParamAtCh;
+  AliMUONTrackParam extrapTrackParamAtCluster1;
+  AliMUONTrackParam extrapTrackParamAtCluster2;
+  AliMUONTrackParam bestTrackParamAtCluster1;
+  AliMUONTrackParam bestTrackParamAtCluster2;
+  
+  Int_t nClusters = clusterStore.GetSize();
+  Bool_t *clusterCh1Used = new Bool_t[nClusters];
+  for (Int_t i = 0; i < nClusters; i++) clusterCh1Used[i] = kFALSE;
+  Int_t iCluster1;
+  
+  // Get track parameters according to the propagation direction
+  if (nextStation==4) extrapTrackParamAtCh = *(AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->Last();
+  else extrapTrackParamAtCh = *(AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->First();
+  
+  // Printout for debuging
+  if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
+    cout<<endl<<"Track parameters and covariances at first cluster:"<<endl;
+    extrapTrackParamAtCh.GetParameters().Print();
+    extrapTrackParamAtCh.GetCovariances().Print();
+  }
+  
+  // Add MCS effect
+  AliMUONTrackExtrap::AddMCSEffect(&extrapTrackParamAtCh,AliMUONConstants::ChamberThicknessInX0(),1.);
+  
+  // Add MCS in the missing chamber(s) if any
+  Int_t currentChamber = extrapTrackParamAtCh.GetClusterPtr()->GetChamberId();
+  while (ch1 < ch2 && currentChamber > ch2 + 1) {
+    // extrapolation to the missing chamber
+    currentChamber--;
+    AliMUONTrackExtrap::ExtrapToZCov(&extrapTrackParamAtCh, AliMUONConstants::DefaultChamberZ(currentChamber));
+    // add MCS effect
+    AliMUONTrackExtrap::AddMCSEffect(&extrapTrackParamAtCh,AliMUONConstants::ChamberThicknessInX0(),1.);
+  }
+  
+  //Extrapolate trackCandidate to chamber "ch2"
+  AliMUONTrackExtrap::ExtrapToZCov(&extrapTrackParamAtCh, AliMUONConstants::DefaultChamberZ(ch2));
+  
+  // Printout for debuging
+  if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
+    cout<<endl<<"Track parameters and covariances at first cluster extrapolated to z = "<<AliMUONConstants::DefaultChamberZ(ch2)<<":"<<endl;
+    extrapTrackParamAtCh.GetParameters().Print();
+    extrapTrackParamAtCh.GetCovariances().Print();
+  }
+  
+  // Printout for debuging
+  if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+    cout << "FollowTrackInStation: look for clusters in chamber(1..): " << ch2+1 << endl;
+  }
+  
+  // Ask the clustering to reconstruct new clusters around the track position in the current station
+  // except for station 4 and 5 that are already entirely clusterized
+  if (GetRecoParam()->CombineClusterTrackReco()) {
+    if (nextStation < 3) AskForNewClustersInStation(extrapTrackParamAtCh, clusterStore, nextStation);
+  }
+  
+  // Create iterators to loop over clusters in both chambers
+  TIter nextInCh1(clusterStore.CreateChamberIterator(ch1,ch1));
+  TIter nextInCh2(clusterStore.CreateChamberIterator(ch2,ch2));
+  
+  // look for candidates in chamber 2
+  while ( ( clusterCh2 = static_cast<AliMUONVCluster*>(nextInCh2()) ) ) {
+    
+    // try to add the current cluster fast
+    if (!TryOneClusterFast(extrapTrackParamAtCh, clusterCh2)) continue;
+    
+    // try to add the current cluster accuratly
+    chi2WithOneCluster = TryOneCluster(extrapTrackParamAtCh, clusterCh2, extrapTrackParamAtCluster2);
+    
+    // if good chi2 then try to attach a cluster in the other chamber too
+    if (chi2WithOneCluster < maxChi2WithOneCluster) {
+      Bool_t foundSecondCluster = kFALSE;
+      
+      // Printout for debuging
+      if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+        cout << "FollowTrackInStation: found one cluster in chamber(1..): " << ch2+1
+            << " (Chi2 = " << chi2WithOneCluster << ")" << endl;
+       clusterCh2->Print();
+        cout << "                      look for second clusters in chamber(1..): " << ch1+1 << " ..." << endl;
+      }
+      
+      // add MCS effect for next step
+      AliMUONTrackExtrap::AddMCSEffect(&extrapTrackParamAtCluster2,AliMUONConstants::ChamberThicknessInX0(),1.);
+      
+      // copy new track parameters for next step
+      extrapTrackParam = extrapTrackParamAtCluster2;
+      
+      //Extrapolate track parameters to chamber "ch1"
+      AliMUONTrackExtrap::ExtrapToZ(&extrapTrackParam, AliMUONConstants::DefaultChamberZ(ch1));
+      
+      // reset cluster iterator of chamber 1
+      nextInCh1.Reset();
+      iCluster1 = -1;
+      
+      // look for second candidates in chamber 1
+      while ( ( clusterCh1 = static_cast<AliMUONVCluster*>(nextInCh1()) ) ) {
+        iCluster1++;
+       
+       // try to add the current cluster fast
+       if (!TryOneClusterFast(extrapTrackParam, clusterCh1)) continue;
+       
+       // try to add the current cluster accuratly
+       chi2WithTwoClusters = TryTwoClusters(extrapTrackParamAtCluster2, clusterCh1, extrapTrackParamAtCluster1);
+        
+       // if good chi2 then create a new track by adding the 2 clusters to the "trackCandidate"
+       if (chi2WithTwoClusters < maxChi2WithTwoClusters) {
+         foundSecondCluster = kTRUE;
+          foundTwoClusters = kTRUE;
+          
+         // Printout for debuging
+         if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+           cout << "FollowTrackInStation: found second cluster in chamber(1..): " << ch1+1
+                << " (Global Chi2 = " << chi2WithTwoClusters << ")" << endl;
+           clusterCh1->Print();
+         }
+         
+         if (GetRecoParam()->TrackAllTracks()) {
+           // copy trackCandidate into a new track put at the end of fRecTracksPtr and add the new clusters
+            newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(trackCandidate);
+           UpdateTrack(*newTrack,extrapTrackParamAtCluster1,extrapTrackParamAtCluster2);
+           fNRecTracks++;
+           
+           // Tag clusterCh1 as used
+           clusterCh1Used[iCluster1] = kTRUE;
+           
+           // Printout for debuging
+           if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+             cout << "FollowTrackInStation: added two clusters in station(1..): " << nextStation+1 << endl;
+             if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
+           }
+           
+          } else if (chi2WithTwoClusters < bestChi2WithTwoClusters) {
+           // keep track of the best couple of clusters
+           bestChi2WithTwoClusters = chi2WithTwoClusters;
+           bestTrackParamAtCluster1 = extrapTrackParamAtCluster1;
+           bestTrackParamAtCluster2 = extrapTrackParamAtCluster2;
+          }
+         
        }
        
-      } // for iHit2
-      x1 /= (Float_t)nRec;
-      y1 /= (Float_t)nRec;
-      z1 /= (Float_t)nRec;
-      pX1 /= (Float_t)nRec;
-      pY1 /= (Float_t)nRec;
-      pZ1 /= (Float_t)nRec;
-      trackReferenceNew->SetPosition(x1,y1,z1);
-      trackReferenceNew->SetMomentum(pX1,pY1,pZ1);
-      trackReferenceNew->SetTrack(track1);
-      {new ((*cleanTrackRefs)[cleanTrackRefs->GetEntriesFast()]) AliTrackReference(*trackReferenceNew);}       
-      iHit1 = iHitMin;
-    } // while iHit1
-  } // for track
-
-  trackRefs->Delete();
-  delete trackRefs;
-  delete trackReferenceNew;
-  return cleanTrackRefs;
-}
-  //__________________________________________________________________________
-void AliMUONTrackReconstructor::SortHitsForRecWithIncreasingChamber()
-{
-  // Sort HitsForRec's in increasing order with respect to chamber number.
-  // Uses the function "Compare".
-  // Update the information for HitsForRec per chamber too.
-  Int_t ch, nhits, prevch;
-  fHitsForRecPtr->Sort();
-  for (ch = 0; ch < AliMUONConstants::NTrackingCh(); ch++) {
-    fNHitsForRecPerChamber[ch] = 0;
-    fIndexOfFirstHitForRecPerChamber[ch] = 0;
+      }
+      
+      // if no clusterCh1 found then consider to add clusterCh2 only
+      if (!foundSecondCluster) {
+        foundOneCluster = kTRUE;
+        
+       if (GetRecoParam()->TrackAllTracks()) {
+         // copy trackCandidate into a new track put at the end of fRecTracksPtr and add the new cluster
+          newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(trackCandidate);
+         UpdateTrack(*newTrack,extrapTrackParamAtCluster2);
+         fNRecTracks++;
+         
+         // Printout for debuging
+         if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+           cout << "FollowTrackInStation: added one cluster in chamber(1..): " << ch2+1 << endl;
+           if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
+         }
+         
+       } else if (!foundTwoClusters && chi2WithOneCluster < bestChi2WithOneCluster) {
+         // keep track of the best single cluster except if a couple of clusters has already been found
+         bestChi2WithOneCluster = chi2WithOneCluster;
+         bestTrackParamAtCluster1 = extrapTrackParamAtCluster2;
+        }
+       
+      }
+      
+    }
+    
   }
-  prevch = 0; // previous chamber
-  nhits = 0; // number of hits in current chamber
-  // Loop over HitsForRec
-  for (Int_t hit = 0; hit < fNHitsForRec; hit++) {
-    // chamber number (0...)
-    ch = ((AliMUONHitForRec*)  ((*fHitsForRecPtr)[hit]))->GetChamberNumber();
-    // increment number of hits in current chamber
-    (fNHitsForRecPerChamber[ch])++;
-    // update index of first HitForRec in current chamber
-    // if chamber number different from previous one
-    if (ch != prevch) {
-      fIndexOfFirstHitForRecPerChamber[ch] = hit;
-      prevch = ch;
+  
+  // look for candidates in chamber 1 not already attached to a track
+  // if we want to keep all possible tracks or if no good couple of clusters has been found
+  if (GetRecoParam()->TrackAllTracks() || !foundTwoClusters) {
+    
+    // add MCS effect for next step
+    AliMUONTrackExtrap::AddMCSEffect(&extrapTrackParamAtCh,AliMUONConstants::ChamberThicknessInX0(),1.);
+    
+    //Extrapolate trackCandidate to chamber "ch1"
+    AliMUONTrackExtrap::ExtrapToZCov(&extrapTrackParamAtCh, AliMUONConstants::DefaultChamberZ(ch1));
+    
+    // Printout for debuging
+    if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
+      cout<<endl<<"Track parameters and covariances at first cluster extrapolated to z = "<<AliMUONConstants::DefaultChamberZ(ch1)<<":"<<endl;
+      extrapTrackParamAtCh.GetParameters().Print();
+      extrapTrackParamAtCh.GetCovariances().Print();
+    }
+    
+    // Printout for debuging
+    if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+      cout << "FollowTrackInStation: look for single clusters in chamber(1..): " << ch1+1 << endl;
     }
+    
+    // reset cluster iterator of chamber 1
+    nextInCh1.Reset();
+    iCluster1 = -1;
+    
+    // look for second candidates in chamber 1
+    while ( ( clusterCh1 = static_cast<AliMUONVCluster*>(nextInCh1()) ) ) {
+      iCluster1++;
+      
+      if (clusterCh1Used[iCluster1]) continue; // Skip cluster already used
+      
+      // try to add the current cluster fast
+      if (!TryOneClusterFast(extrapTrackParamAtCh, clusterCh1)) continue;
+      
+      // try to add the current cluster accuratly
+      chi2WithOneCluster = TryOneCluster(extrapTrackParamAtCh, clusterCh1, extrapTrackParamAtCluster1);
+      
+      // if good chi2 then consider to add clusterCh1
+      // We do not try to attach a cluster in the other chamber too since it has already been done above
+      if (chi2WithOneCluster < maxChi2WithOneCluster) {
+        foundOneCluster = kTRUE;
+       
+       // Printout for debuging
+       if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+         cout << "FollowTrackInStation: found one cluster in chamber(1..): " << ch1+1
+              << " (Chi2 = " << chi2WithOneCluster << ")" << endl;
+         clusterCh1->Print();
+       }
+       
+       if (GetRecoParam()->TrackAllTracks()) {
+         // copy trackCandidate into a new track put at the end of fRecTracksPtr and add the new cluster
+         newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(trackCandidate);
+         UpdateTrack(*newTrack,extrapTrackParamAtCluster1);
+         fNRecTracks++;
+         
+         // Printout for debuging
+         if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+           cout << "FollowTrackInStation: added one cluster in chamber(1..): " << ch1+1 << endl;
+           if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
+         }
+         
+       } else if (chi2WithOneCluster < bestChi2WithOneCluster) {
+         // keep track of the best single cluster except if a couple of clusters has already been found
+         bestChi2WithOneCluster = chi2WithOneCluster;
+         bestTrackParamAtCluster1 = extrapTrackParamAtCluster1;
+       }
+       
+      }
+      
+    }
+    
   }
-  return;
-}
-
-  //__________________________________________________________________________
-void AliMUONTrackReconstructor::AddHitsForRecFromRawClusters(TTree* TR)
-{
-  // To add to the list of hits for reconstruction all the raw clusters
-  // No condition added, like in Fortran TRACKF_STAT,
-  // on the radius between RMin and RMax.
-  AliMUONHitForRec *hitForRec;
-  AliMUONRawCluster *clus;
-  Int_t iclus, nclus, nTRentries;
-  TClonesArray *rawclusters;
-  AliDebug(1,"Enter AddHitsForRecFromRawClusters");
-
-  if (fTrackMethod != 3) { //AZ
-    fMUONData->SetTreeAddress("RC"); //AZ
-    nTRentries = Int_t(TR->GetEntries());
-    if (nTRentries != 1) {
-      AliError(Form("nTRentries = %d not equal to 1 ",nTRentries));
-      exit(0);
+  
+  // fill out the best track if required else clean up the fRecTracksPtr array
+  if (!GetRecoParam()->TrackAllTracks()) {
+    if (foundTwoClusters) {
+      UpdateTrack(trackCandidate,bestTrackParamAtCluster1,bestTrackParamAtCluster2);
+      
+      // Printout for debuging
+      if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+        cout << "FollowTrackInStation: added the two best clusters in station(1..): " << nextStation+1 << endl;
+        if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
+      }
+      
+    } else if (foundOneCluster) {
+      UpdateTrack(trackCandidate,bestTrackParamAtCluster1);
+      
+      // Printout for debuging
+      if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+        cout << "FollowTrackInStation: added the best cluster in chamber(1..): " << bestTrackParamAtCluster1.GetClusterPtr()->GetChamberId()+1 << endl;
+        if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
+      }
+      
+    } else {
+      delete [] clusterCh1Used;
+      return kFALSE;
     }
-    fLoader->TreeR()->GetEvent(0); // only one entry  
+    
+  } else if (foundOneCluster || foundTwoClusters) {
+    
+    // remove obsolete track
+    fRecTracksPtr->Remove(&trackCandidate);
+    fNRecTracks--;
+    
+  } else {
+    delete [] clusterCh1Used;
+    return kFALSE;
   }
-
-  // Loop over tracking chambers
-  for (Int_t ch = 0; ch < AliMUONConstants::NTrackingCh(); ch++) {
-    // number of HitsForRec to 0 for the chamber
-    fNHitsForRecPerChamber[ch] = 0;
-    // index of first HitForRec for the chamber
-    if (ch == 0) fIndexOfFirstHitForRecPerChamber[ch] = 0;
-    else fIndexOfFirstHitForRecPerChamber[ch] = fNHitsForRec;
-    rawclusters =fMUONData->RawClusters(ch);
-//     pMUON->ResetRawClusters();
-//     TR->GetEvent((Int_t) (TR->GetEntries()) - 1); // to be checked ????
-    nclus = (Int_t) (rawclusters->GetEntries());
-    // Loop over (cathode correlated) raw clusters
-    for (iclus = 0; iclus < nclus; iclus++) {
-      clus = (AliMUONRawCluster*) rawclusters->UncheckedAt(iclus);
-      // new AliMUONHitForRec from raw cluster
-      // and increment number of AliMUONHitForRec's (total and in chamber)
-      hitForRec = new ((*fHitsForRecPtr)[fNHitsForRec]) AliMUONHitForRec(clus);
-      fNHitsForRec++;
-      (fNHitsForRecPerChamber[ch])++;
-      // more information into HitForRec
-      //  resolution: info should be already in raw cluster and taken from it ????
-      hitForRec->SetBendingReso2(fBendingResolution * fBendingResolution);
-      hitForRec->SetNonBendingReso2(fNonBendingResolution * fNonBendingResolution);
-      //hitForRec->SetBendingReso2(clus->GetErrY() * clus->GetErrY());
-      //hitForRec->SetNonBendingReso2(clus->GetErrX() * clus->GetErrX());
-      //  original raw cluster
-      hitForRec->SetChamberNumber(ch);
-      hitForRec->SetHitNumber(iclus);
-      // Z coordinate of the raw cluster (cm)
-      hitForRec->SetZ(clus->GetZ(0));
-      if (AliLog::GetGlobalDebugLevel() > 1) {
-       cout << "chamber (0...): " << ch <<
-         " raw cluster (0...): " << iclus << endl;
-       clus->Dump();
-       cout << "AliMUONHitForRec number (1...): " << fNHitsForRec << endl;
-       hitForRec->Dump();}
-    } // end of cluster loop
-  } // end of chamber loop
-  SortHitsForRecWithIncreasingChamber(); 
-  return;
+  
+  delete [] clusterCh1Used;
+  return kTRUE;
+  
 }
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::MakeSegments(void)
+Double_t AliMUONTrackReconstructor::TryTwoClusters(const AliMUONTrackParam &trackParamAtCluster1, AliMUONVCluster* cluster2,
+                                                  AliMUONTrackParam &trackParamAtCluster2)
 {
-  // To make the list of segments in all stations,
-  // from the list of hits to be reconstructed
-  AliDebug(1,"Enter MakeSegments");
-  ResetSegments();
-  // Loop over stations
-  Int_t nb = (fTrackMethod != 1) ? 3 : 0; //AZ
-  for (Int_t st = nb; st < AliMUONConstants::NTrackingCh()/2; st++) 
-    MakeSegmentsPerStation(st); 
-  if (AliLog::GetGlobalDebugLevel() > 1) {
-    cout << "end of MakeSegments" << endl;
-    for (Int_t st = 0; st < AliMUONConstants::NTrackingCh()/2; st++) {
-      cout << "station(0...): " << st
-          << "  Segments: " << fNSegments[st]
-          << endl;
-      for (Int_t seg = 0;
-          seg < fNSegments[st];
-          seg++) {
-       cout << "Segment index(0...): " << seg << endl;
-       ((*fSegmentsPtr[st])[seg])->Dump();
+/// Test the compatibility between the track and the 2 clusters together (using trackParam's covariance matrix):
+/// return the corresponding Chi2 accounting for covariances between the 2 clusters
+/// return trackParamAtCluster1 & 2
+  
+  // extrapolate track parameters at the z position of the second cluster (no need to extrapolate the covariances)
+  trackParamAtCluster2.SetParameters(trackParamAtCluster1.GetParameters());
+  trackParamAtCluster2.SetZ(trackParamAtCluster1.GetZ());
+  AliMUONTrackExtrap::ExtrapToZ(&trackParamAtCluster2, cluster2->GetZ());
+  
+  // set pointer to cluster2 into trackParamAtCluster2
+  trackParamAtCluster2.SetClusterPtr(cluster2);
+  
+  // Set differences between track and the 2 clusters in the bending and non bending directions
+  AliMUONVCluster* cluster1 = trackParamAtCluster1.GetClusterPtr();
+  TMatrixD dPos(4,1);
+  dPos(0,0) = cluster1->GetX() - trackParamAtCluster1.GetNonBendingCoor();
+  dPos(1,0) = cluster1->GetY() - trackParamAtCluster1.GetBendingCoor();
+  dPos(2,0) = cluster2->GetX() - trackParamAtCluster2.GetNonBendingCoor();
+  dPos(3,0) = cluster2->GetY() - trackParamAtCluster2.GetBendingCoor();
+  
+  // Calculate the error matrix from the track parameter covariances at first cluster
+  TMatrixD error(4,4);
+  error.Zero();
+  if (trackParamAtCluster1.CovariancesExist()) {
+    // Save track parameters at first cluster
+    TMatrixD paramAtCluster1Save(trackParamAtCluster1.GetParameters());
+    
+    // Save track coordinates at second cluster
+    Double_t nonBendingCoor2 = trackParamAtCluster2.GetNonBendingCoor();
+    Double_t bendingCoor2    = trackParamAtCluster2.GetBendingCoor();
+    
+    // copy track parameters at first cluster for jacobian calculation
+    AliMUONTrackParam trackParam(trackParamAtCluster1);
+    
+    // add MCS effect to the covariance matrix at first cluster
+    AliMUONTrackExtrap::AddMCSEffect(&trackParam,AliMUONConstants::ChamberThicknessInX0(),1.);
+    
+    // Get the pointer to the parameter covariance matrix at first cluster
+    const TMatrixD& kParamCov = trackParam.GetCovariances();
+    
+    // Calculate the jacobian related to the transformation between track parameters
+    // at first cluster and track coordinates at the 2 cluster z-positions
+    TMatrixD jacob(4,5);
+    jacob.Zero();
+    // first derivative at the first cluster:
+    jacob(0,0) = 1.; // dx1/dx
+    jacob(1,2) = 1.; // dy1/dy
+    // first derivative at the second cluster:
+    TMatrixD dParam(5,1);
+    for (Int_t i=0; i<5; i++) {
+      // Skip jacobian calculation for parameters with no associated error
+      if (kParamCov(i,i) == 0.) continue;
+      // Small variation of parameter i only
+      for (Int_t j=0; j<5; j++) {
+        if (j==i) {
+          dParam(j,0) = TMath::Sqrt(kParamCov(i,i));
+         if (j == 4) dParam(j,0) *= TMath::Sign(1.,-paramAtCluster1Save(4,0)); // variation always in the same direction
+        } else dParam(j,0) = 0.;
       }
+      
+      // Set new track parameters at first cluster
+      trackParam.SetParameters(paramAtCluster1Save);
+      trackParam.AddParameters(dParam);
+      trackParam.SetZ(cluster1->GetZ());
+      
+      // Extrapolate new track parameters to the z position of the second cluster
+      AliMUONTrackExtrap::ExtrapToZ(&trackParam,cluster2->GetZ());
+      
+      // Calculate the jacobian
+      jacob(2,i) = (trackParam.GetNonBendingCoor() - nonBendingCoor2) / dParam(i,0); // dx2/dParami
+      jacob(3,i) = (trackParam.GetBendingCoor()    - bendingCoor2   ) / dParam(i,0); // dy2/dParami
     }
+    
+    // Calculate the error matrix
+    TMatrixD tmp(jacob,TMatrixD::kMult,kParamCov);
+    error = TMatrixD(tmp,TMatrixD::kMultTranspose,jacob);
   }
-  return;
-}
-
-  //__________________________________________________________________________
-void AliMUONTrackReconstructor::MakeSegmentsPerStation(Int_t Station)
-{
-  // To make the list of segments in station number "Station" (0...)
-  // from the list of hits to be reconstructed.
-  // Updates "fNSegments"[Station].
-  // Segments in stations 4 and 5 are sorted
-  // according to increasing absolute value of "impact parameter"
-  AliMUONHitForRec *hit1Ptr, *hit2Ptr;
-  AliMUONSegment *segment;
-  Bool_t last2st;
-  Double_t bendingSlope, distBend, distNonBend, extBendCoor, extNonBendCoor,
-      impactParam = 0., maxImpactParam = 0., minImpactParam = 0.; // =0 to avoid compilation warnings.
-  AliDebug(1,Form("Enter MakeSegmentsPerStation (0...) %d",Station));
-  // first and second chambers (0...) in the station
-  Int_t ch1 = 2 * Station;
-  Int_t ch2 = ch1 + 1;
-  // variable true for stations downstream of the dipole:
-  // Station(0..4) equal to 3 or 4
-  if ((Station == 3) || (Station == 4)) {
-    last2st = kTRUE;
-    // maximum impact parameter (cm) according to fMinBendingMomentum...
-    maxImpactParam =
-      TMath::Abs(GetImpactParamFromBendingMomentum(fMinBendingMomentum));
-    // minimum impact parameter (cm) according to fMaxBendingMomentum...
-    minImpactParam =
-      TMath::Abs(GetImpactParamFromBendingMomentum(fMaxBendingMomentum));
+  
+  // Add cluster resolution to the error matrix
+  error(0,0) += cluster1->GetErrX2();
+  error(1,1) += cluster1->GetErrY2();
+  error(2,2) += cluster2->GetErrX2();
+  error(3,3) += cluster2->GetErrY2();
+  
+  // invert the error matrix for Chi2 calculation
+  if (error.Determinant() != 0) {
+    error.Invert();
+  } else {
+    AliWarning(" Determinant error=0");
+    return 1.e10;
   }
-  else last2st = kFALSE;
-  // extrapolation factor from Z of first chamber to Z of second chamber
-  // dZ to be changed to take into account fine structure of chambers ????
-  Double_t extrapFact;
-  // index for current segment
-  Int_t segmentIndex = 0;
-  // Loop over HitsForRec in the first chamber of the station
-  for (Int_t hit1 = fIndexOfFirstHitForRecPerChamber[ch1];
-       hit1 < fIndexOfFirstHitForRecPerChamber[ch1] + fNHitsForRecPerChamber[ch1];
-       hit1++) {
-    // pointer to the HitForRec
-    hit1Ptr = (AliMUONHitForRec*) ((*fHitsForRecPtr)[hit1]);
-    // extrapolation,
-    // on the straight line joining the HitForRec to the vertex (0,0,0),
-    // to the Z of the second chamber of the station
-    // Loop over HitsForRec in the second chamber of the station
-    for (Int_t hit2 = fIndexOfFirstHitForRecPerChamber[ch2];
-        hit2 < fIndexOfFirstHitForRecPerChamber[ch2] + fNHitsForRecPerChamber[ch2];
-        hit2++) {
-      // pointer to the HitForRec
-      hit2Ptr = (AliMUONHitForRec*) ((*fHitsForRecPtr)[hit2]);
-      // absolute values of distances, in bending and non bending planes,
-      // between the HitForRec in the second chamber
-      // and the previous extrapolation
-      extrapFact = hit2Ptr->GetZ()/ hit1Ptr->GetZ();
-      extBendCoor = extrapFact * hit1Ptr->GetBendingCoor();
-      extNonBendCoor = extrapFact * hit1Ptr->GetNonBendingCoor();
-      distBend = TMath::Abs(hit2Ptr->GetBendingCoor() - extBendCoor);
-      distNonBend = TMath::Abs(hit2Ptr->GetNonBendingCoor() - extNonBendCoor);
-      if (last2st) {
-       // bending slope
-       bendingSlope = (hit1Ptr->GetBendingCoor() - hit2Ptr->GetBendingCoor()) /
-         (hit1Ptr->GetZ() - hit2Ptr->GetZ());
-       // absolute value of impact parameter
-       impactParam =
-         TMath::Abs(hit1Ptr->GetBendingCoor() - hit1Ptr->GetZ() * bendingSlope);
-      }
-      // check for distances not too large,
-      // and impact parameter not too big if stations downstream of the dipole.
-      // Conditions "distBend" and "impactParam" correlated for these stations ????
-      if ((distBend < fSegmentMaxDistBending[Station]) &&
-         (distNonBend < fSegmentMaxDistNonBending[Station]) &&
-         (!last2st || (impactParam < maxImpactParam)) &&
-         (!last2st || (impactParam > minImpactParam))) {
-       // make new segment
-       segment = new ((*fSegmentsPtr[Station])[segmentIndex])
-         AliMUONSegment(hit1Ptr, hit2Ptr);
-       // update "link" to this segment from the hit in the first chamber
-       if (hit1Ptr->GetNSegments() == 0)
-         hit1Ptr->SetIndexOfFirstSegment(segmentIndex);
-       hit1Ptr->SetNSegments(hit1Ptr->GetNSegments() + 1);
-       if (AliLog::GetGlobalDebugLevel() > 1) {
-         cout << "segmentIndex(0...): " << segmentIndex
-              << "  distBend: " << distBend
-              << "  distNonBend: " << distNonBend
-              << endl;
-         segment->Dump();
-         cout << "HitForRec in first chamber" << endl;
-         hit1Ptr->Dump();
-         cout << "HitForRec in second chamber" << endl;
-         hit2Ptr->Dump();
-       };
-       // increment index for current segment
-       segmentIndex++;
-      }
-    } //for (Int_t hit2
-  } // for (Int_t hit1...
-  fNSegments[Station] = segmentIndex;
-  // Sorting according to "impact parameter" if station(1..5) 4 or 5,
-  // i.e. Station(0..4) 3 or 4, using the function "Compare".
-  // After this sorting, it is impossible to use
-  // the "fNSegments" and "fIndexOfFirstSegment"
-  // of the HitForRec in the first chamber to explore all segments formed with it.
-  // Is this sorting really needed ????
-  if ((Station == 3) || (Station == 4)) (fSegmentsPtr[Station])->Sort();
-  AliDebug(1,Form("Station: %d  NSegments:  %d ", Station, fNSegments[Station]));
-  return;
+  
+  // Compute the Chi2 value
+  TMatrixD tmp2(dPos,TMatrixD::kTransposeMult,error);
+  TMatrixD result(tmp2,TMatrixD::kMult,dPos);
+  
+  return result(0,0);
+  
 }
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::MakeTracks(void)
+void AliMUONTrackReconstructor::UpdateTrack(AliMUONTrack &track, AliMUONTrackParam &trackParamAtCluster)
 {
-  // To make the tracks,
-  // from the list of segments and points in all stations
-  AliDebug(1,"Enter MakeTracks");
-  // The order may be important for the following Reset's
-  ResetTracks();
-  ResetTrackHits();
-  if (fTrackMethod != 1) { //AZ - Kalman filter
-    MakeTrackCandidatesK();
-    if (fRecTracksPtr->GetEntriesFast() == 0) return;
-    // Follow tracks in stations(1..) 3, 2 and 1
-    FollowTracksK();
-    // Remove double tracks
-    RemoveDoubleTracksK();
-    // Propagate tracks to the vertex thru absorber
-    GoToVertex();
-    // Fill AliMUONTrack data members
-    FillMUONTrack();
-  } else { 
-    // Look for candidates from at least 3 aligned points in stations(1..) 4 and 5
-    MakeTrackCandidates();
-    // Follow tracks in stations(1..) 3, 2 and 1
-    FollowTracks();
-    // Remove double tracks
-    RemoveDoubleTracks();
-    UpdateTrackParamAtHit();
-    UpdateHitForRecAtHit();
-  }
-  return;
+  /// Add 1 cluster to the track candidate
+  /// Update chi2 of the track 
+  
+  // Compute local chi2
+  AliMUONVCluster* cluster = trackParamAtCluster.GetClusterPtr();
+  Double_t deltaX = trackParamAtCluster.GetNonBendingCoor() - cluster->GetX();
+  Double_t deltaY = trackParamAtCluster.GetBendingCoor() - cluster->GetY();
+  Double_t localChi2 = deltaX*deltaX / cluster->GetErrX2() +
+                      deltaY*deltaY / cluster->GetErrY2();
+  
+  // Flag cluster as being not removable
+  if (GetRecoParam()->RequestStation(cluster->GetChamberId()/2))
+    trackParamAtCluster.SetRemovable(kFALSE);
+  else trackParamAtCluster.SetRemovable(kTRUE);
+  trackParamAtCluster.SetLocalChi2(0.); // --> Local chi2 not used
+  
+  // Update the chi2 of the new track
+  track.SetGlobalChi2(track.GetGlobalChi2() + localChi2);
+  
+  // Update TrackParamAtCluster
+  track.AddTrackParamAtCluster(trackParamAtCluster,*cluster);
+  
 }
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::ValidateTracksWithTrigger(void)
+void AliMUONTrackReconstructor::UpdateTrack(AliMUONTrack &track, AliMUONTrackParam &trackParamAtCluster1, AliMUONTrackParam &trackParamAtCluster2)
 {
-  // Try to match track from tracking system with trigger track
-  AliMUONTrack *track;
-  TClonesArray *recTriggerTracks;
+  /// Add 2 clusters to the track candidate
+  /// Update track and local chi2
+  
+  // Update local chi2 at first cluster
+  AliMUONVCluster* cluster1 = trackParamAtCluster1.GetClusterPtr();
+  Double_t deltaX = trackParamAtCluster1.GetNonBendingCoor() - cluster1->GetX();
+  Double_t deltaY = trackParamAtCluster1.GetBendingCoor() - cluster1->GetY();
+  Double_t localChi2AtCluster1 = deltaX*deltaX / cluster1->GetErrX2() +
+                                deltaY*deltaY / cluster1->GetErrY2();
+  trackParamAtCluster1.SetLocalChi2(localChi2AtCluster1);
+  
+  // Flag first cluster as being removable
+  trackParamAtCluster1.SetRemovable(kTRUE);
+  
+  // Update local chi2 at second cluster
+  AliMUONVCluster* cluster2 = trackParamAtCluster2.GetClusterPtr();
+  deltaX = trackParamAtCluster2.GetNonBendingCoor() - cluster2->GetX();
+  deltaY = trackParamAtCluster2.GetBendingCoor() - cluster2->GetY();
+  Double_t localChi2AtCluster2 = deltaX*deltaX / cluster2->GetErrX2() +
+                                deltaY*deltaY / cluster2->GetErrY2();
+  trackParamAtCluster2.SetLocalChi2(localChi2AtCluster2);
+  
+  // Flag first cluster as being removable
+  trackParamAtCluster2.SetRemovable(kTRUE);
+  
+  // Update the chi2 of the new track
+  track.SetGlobalChi2(track.GetGlobalChi2() + localChi2AtCluster1 + localChi2AtCluster2);
+  
+  // Update TrackParamAtCluster
+  track.AddTrackParamAtCluster(trackParamAtCluster1,*cluster1);
+  track.AddTrackParamAtCluster(trackParamAtCluster2,*cluster2);
   
-  fMUONData->SetTreeAddress("RL");
-  fMUONData->GetRecTriggerTracks();
-  recTriggerTracks = fMUONData->RecTriggerTracks();
-
-  track = (AliMUONTrack*) fRecTracksPtr->First();
-  while (track) {
-    track->MatchTriggerTrack(recTriggerTracks);
-    track = (AliMUONTrack*) fRecTracksPtr->After(track);
-  }
-
 }
 
   //__________________________________________________________________________
-Bool_t AliMUONTrackReconstructor::MakeTriggerTracks(void)
+Bool_t AliMUONTrackReconstructor::RecoverTrack(AliMUONTrack &trackCandidate, AliMUONVClusterStore& clusterStore, Int_t nextStation)
 {
-    // To make the trigger tracks from Local Trigger
-  AliDebug(1, "Enter MakeTriggerTracks");
+  /// Try to recover the track candidate in the next station
+  /// by removing the worst of the two clusters attached in the current station
+  /// Return kTRUE if recovering succeeds
+  AliDebug(1,"Enter RecoverTrack");
+  
+  // Do not try to recover track until we have attached cluster(s) on station(1..) 3
+  if (nextStation > 1) return kFALSE;
+  
+  Int_t worstClusterNumber = -1;
+  Double_t localChi2, worstLocalChi2 = -1.;
+  
+  // Look for the cluster to remove
+  for (Int_t clusterNumber = 0; clusterNumber < 2; clusterNumber++) {
+    AliMUONTrackParam *trackParamAtCluster = (AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->UncheckedAt(clusterNumber);
     
-    Int_t nTRentries;
-    Long_t gloTrigPat;
-    TClonesArray *localTrigger;
-    TClonesArray *globalTrigger;
-    AliMUONLocalTrigger *locTrg;
-    AliMUONGlobalTrigger *gloTrg;
-    AliMUONTriggerCircuit *circuit;
-    AliMUONTriggerTrack *recTriggerTrack = 0;
-
-    TTree* treeR = fLoader->TreeR();
+    // check if current cluster is in the previous station
+    if (trackParamAtCluster->GetClusterPtr()->GetChamberId()/2 != nextStation+1) break;
     
-    // Loading MUON subsystem
-    AliMUON * pMUON = (AliMUON *) gAlice->GetDetector("MUON");
+    // check if current cluster is removable
+    if (!trackParamAtCluster->IsRemovable()) return kFALSE;
     
-    nTRentries = Int_t(treeR->GetEntries());
-     
-    treeR->GetEvent(0); // only one entry  
-
-    if (!(fMUONData->IsTriggerBranchesInTree())) {
-      AliWarning(Form("Trigger information is not avalaible, nTRentries = %d not equal to 1",nTRentries));
-      return kFALSE;
-    }
-
-    fMUONData->SetTreeAddress("TC");
-    fMUONData->GetTrigger();
-
-    // global trigger for trigger pattern
-    gloTrigPat = 0;
-    globalTrigger = fMUONData->GlobalTrigger(); 
-    gloTrg = (AliMUONGlobalTrigger*)globalTrigger->UncheckedAt(0);     
-    if (gloTrg) {
-      if (gloTrg->SinglePlusLpt())  gloTrigPat|= 0x1;
-      if (gloTrg->SinglePlusHpt())  gloTrigPat|= 0x2;
-      if (gloTrg->SinglePlusApt())  gloTrigPat|= 0x4;
-      
-      if (gloTrg->SingleMinusLpt()) gloTrigPat|= 0x8;
-      if (gloTrg->SingleMinusHpt()) gloTrigPat|= 0x10;
-      if (gloTrg->SingleMinusApt()) gloTrigPat|= 0x20;
-      
-      if (gloTrg->SingleUndefLpt()) gloTrigPat|= 0x40;
-      if (gloTrg->SingleUndefHpt()) gloTrigPat|= 0x80;
-      if (gloTrg->SingleUndefApt()) gloTrigPat|= 0x100;
-      
-      if (gloTrg->PairUnlikeLpt())  gloTrigPat|= 0x200;
-      if (gloTrg->PairUnlikeHpt())  gloTrigPat|= 0x400;
-      if (gloTrg->PairUnlikeApt())  gloTrigPat|= 0x800;
-      
-      if (gloTrg->PairLikeLpt())    gloTrigPat|= 0x1000;
-      if (gloTrg->PairLikeHpt())    gloTrigPat|= 0x2000;
-      if (gloTrg->PairLikeApt())    gloTrigPat|= 0x4000;
+    // reset the current cluster as beig not removable if it is on a required station
+    if (GetRecoParam()->RequestStation(nextStation+1)) trackParamAtCluster->SetRemovable(kFALSE);
+    
+    // Pick up cluster with the worst chi2
+    localChi2 = trackParamAtCluster->GetLocalChi2();
+    if (localChi2 > worstLocalChi2) {
+      worstLocalChi2 = localChi2;
+      worstClusterNumber = clusterNumber;
     }
-
-    // local trigger for tracking 
-    localTrigger = fMUONData->LocalTrigger();    
-    Int_t nlocals = (Int_t) (localTrigger->GetEntries());
-
-    Float_t z11 = AliMUONConstants::DefaultChamberZ(10);
-    Float_t z21 = AliMUONConstants::DefaultChamberZ(12);
-
-    for (Int_t i=0; i<nlocals; i++) { // loop on Local Trigger
-      locTrg = (AliMUONLocalTrigger*)localTrigger->UncheckedAt(i);     
-      circuit = &(pMUON->TriggerCircuit(locTrg->LoCircuit()));
-      Float_t y11 = circuit->GetY11Pos(locTrg->LoStripX()); 
-      Int_t stripX21 = locTrg->LoStripX()+locTrg->LoDev()+1;
-      Float_t y21 = circuit->GetY21Pos(stripX21);      
-      Float_t x11 = circuit->GetX11Pos(locTrg->LoStripY());
-      Float_t thetax = TMath::ATan2( x11 , z11 );
-      Float_t thetay = TMath::ATan2( (y21-y11) , (z21-z11) );
-
-      recTriggerTrack = new AliMUONTriggerTrack(x11,y11,thetax,thetay,gloTrigPat);
-      
-      // since static statement does not work, set gloTrigPat for each track
-
-      fMUONData->AddRecTriggerTrack(*recTriggerTrack);
-      delete recTriggerTrack;
-    } // end of loop on Local Trigger
-    return kTRUE;    
+    
+  }
+  
+  // check if worst cluster found
+  if (worstClusterNumber < 0) return kFALSE;
+  
+  // Remove the worst cluster
+  trackCandidate.RemoveTrackParamAtCluster((AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->UncheckedAt(worstClusterNumber));
+  
+  // Re-fit the track:
+  // Do not take into account the multiple scattering to speed up the fit
+  // Calculate the track parameter covariance matrix
+  Fit(trackCandidate, kFALSE, kFALSE, kTRUE);
+  
+  // Look for new cluster(s) in next station
+  return FollowTrackInStation(trackCandidate,clusterStore,nextStation);
+  
 }
 
   //__________________________________________________________________________
-Int_t AliMUONTrackReconstructor::MakeTrackCandidatesWithTwoSegments(AliMUONSegment *BegSegment)
+void AliMUONTrackReconstructor::SetVertexErrXY2ForFit(AliMUONTrack &trackCandidate)
 {
-  // To make track candidates with two segments in stations(1..) 4 and 5,
-  // the first segment being pointed to by "BegSegment".
-  // Returns the number of such track candidates.
-  Int_t endStation, iEndSegment, nbCan2Seg;
-  AliMUONSegment *endSegment;
-  AliMUONSegment *extrapSegment = NULL;
-  AliMUONTrack *recTrack;
-  Double_t mcsFactor;
-  AliDebug(1,"Enter MakeTrackCandidatesWithTwoSegments");
-  // Station for the end segment
-  endStation = 7 - (BegSegment->GetHitForRec1())->GetChamberNumber() / 2;
-  // multiple scattering factor corresponding to one chamber
-  mcsFactor = 0.0136 /
-    GetBendingMomentumFromImpactParam(BegSegment->GetBendingImpact());
-  mcsFactor    = fChamberThicknessInX0 * mcsFactor * mcsFactor;
-  // linear extrapolation to end station
-  // number of candidates with 2 segments to 0
-  nbCan2Seg = 0;
-  // Loop over segments in the end station
-  for (iEndSegment = 0; iEndSegment < fNSegments[endStation]; iEndSegment++) {
-    // pointer to segment
-    endSegment = (AliMUONSegment*) ((*fSegmentsPtr[endStation])[iEndSegment]);
-    // test compatibility between current segment and "extrapSegment"
-    // 4 because 4 quantities in chi2
-    extrapSegment =
-      BegSegment->CreateSegmentFromLinearExtrapToStation(endSegment->GetZ(), mcsFactor);
-    if ((endSegment->
-        NormalizedChi2WithSegment(extrapSegment,
-                                  fMaxSigma2Distance)) <= 4.0) {
-      // both segments compatible:
-      // make track candidate from "begSegment" and "endSegment"
-      AliDebug(2,Form("TrackCandidate with Segment %d in Station(0..) %d", iEndSegment, endStation));
-      // flag for both segments in one track:
-      // to be done in track constructor ????
-      BegSegment->SetInTrack(kTRUE);
-      endSegment->SetInTrack(kTRUE);
-      recTrack = new ((*fRecTracksPtr)[fNRecTracks])
-       AliMUONTrack(BegSegment, endSegment, this);
-      fNRecTracks++;
-      if (AliLog::GetGlobalDebugLevel() > 1) recTrack->RecursiveDump();
-      // increment number of track candidates with 2 segments
-      nbCan2Seg++;
-    }
-    delete extrapSegment; // should not delete HitForRec's it points to !!!!
-  } // for (iEndSegment = 0;...
-  return nbCan2Seg;
+  /// Compute the vertex resolution square from natural vertex dispersion and
+  /// multiple scattering effets according to trackCandidate path in absorber
+  /// It is necessary to account for multiple scattering effects here instead of during the fit of
+  /// the "trackCandidate" to do not influence the result by changing track resolution at vertex
+  AliDebug(1,"Enter SetVertexForFit");
+  
+  Double_t nonBendingReso2 = GetRecoParam()->GetNonBendingVertexDispersion() *
+                             GetRecoParam()->GetNonBendingVertexDispersion();
+  Double_t bendingReso2 = GetRecoParam()->GetBendingVertexDispersion() *
+                         GetRecoParam()->GetBendingVertexDispersion();
+  
+  // add multiple scattering effets
+  AliMUONTrackParam paramAtVertex(*((AliMUONTrackParam*)(trackCandidate.GetTrackParamAtCluster()->First())));
+  paramAtVertex.DeleteCovariances(); // to be sure to account only for multiple scattering
+  AliMUONTrackExtrap::ExtrapToVertexUncorrected(&paramAtVertex,0.);
+  const TMatrixD& kParamCov = paramAtVertex.GetCovariances();
+  nonBendingReso2 += kParamCov(0,0);
+  bendingReso2 += kParamCov(2,2);
+  
+  // Set the vertex resolution square
+  trackCandidate.SetVertexErrXY2(nonBendingReso2,bendingReso2);
 }
 
   //__________________________________________________________________________
-Int_t AliMUONTrackReconstructor::MakeTrackCandidatesWithOneSegmentAndOnePoint(AliMUONSegment *BegSegment)
+void AliMUONTrackReconstructor::Fit(AliMUONTrack &track, Bool_t includeMCS, Bool_t fitWithVertex, Bool_t calcCov)
 {
-  // To make track candidates with one segment and one point
-  // in stations(1..) 4 and 5,
-  // the segment being pointed to by "BegSegment".
-  Int_t ch, ch1, ch2, endStation, iHit, iHitMax, iHitMin, nbCan1Seg1Hit;
-  AliMUONHitForRec *extrapHitForRec= NULL;
-  AliMUONHitForRec *hit;
-  AliMUONTrack *recTrack;
-  Double_t mcsFactor;
-  AliDebug(1,"Enter MakeTrackCandidatesWithOneSegmentAndOnePoint");
-  // station for the end point
-  endStation = 7 - (BegSegment->GetHitForRec1())->GetChamberNumber() / 2;
-  // multiple scattering factor corresponding to one chamber
-  mcsFactor = 0.0136 /
-    GetBendingMomentumFromImpactParam(BegSegment->GetBendingImpact());
-  mcsFactor    = fChamberThicknessInX0 * mcsFactor * mcsFactor;
-  // first and second chambers(0..) in the end station
-  ch1 = 2 * endStation;
-  ch2 = ch1 + 1;
-  // number of candidates to 0
-  nbCan1Seg1Hit = 0;
-  // Loop over chambers of the end station
-  for (ch = ch2; ch >= ch1; ch--) {
-    // limits for the hit index in the loop
-    iHitMin = fIndexOfFirstHitForRecPerChamber[ch];
-    iHitMax = iHitMin + fNHitsForRecPerChamber[ch];
-    // Loop over HitForRec's in the chamber
-    for (iHit = iHitMin; iHit < iHitMax; iHit++) {
-      // pointer to HitForRec
-      hit = (AliMUONHitForRec*) ((*fHitsForRecPtr)[iHit]);
-      // test compatibility between current HitForRec and "extrapHitForRec"
-      // 2 because 2 quantities in chi2
-      // linear extrapolation to chamber
-      extrapHitForRec =
-       BegSegment->CreateHitForRecFromLinearExtrapToChamber( hit->GetZ(), mcsFactor);
-      if ((hit->
-          NormalizedChi2WithHitForRec(extrapHitForRec,
-                                      fMaxSigma2Distance)) <= 2.0) {
-       // both HitForRec's compatible:
-       // make track candidate from begSegment and current HitForRec
-       AliDebug(2, Form("TrackCandidate with HitForRec  %d in Chamber(0..) %d", iHit, ch));
-       // flag for beginning segments in one track:
-       // to be done in track constructor ????
-       BegSegment->SetInTrack(kTRUE);
-       recTrack = new ((*fRecTracksPtr)[fNRecTracks])
-         AliMUONTrack(BegSegment, hit, this);
-       // the right place to eliminate "double counting" ???? how ????
-       fNRecTracks++;
-       if (AliLog::GetGlobalDebugLevel() > 1) recTrack->RecursiveDump();
-       // increment number of track candidates
-       nbCan1Seg1Hit++;
-      }
-      delete extrapHitForRec;
-    } // for (iHit = iHitMin;...
-  } // for (ch = ch2;...
-  return nbCan1Seg1Hit;
+  /// Fit the track
+  /// w/wo multiple Coulomb scattering according to "includeMCS".
+  /// w/wo constraining the vertex according to "fitWithVertex".
+  /// calculating or not the covariance matrix according to "calcCov".
+  AliDebug(1,"Enter Fit");
+  
+  Double_t benC, errorParam, invBenP, nonBenC, x, y;
+  AliMUONTrackParam *trackParam;
+  Double_t arg[1], fedm, errdef, globalChi2;
+  Int_t npari, nparx;
+  Int_t status, covStatus;
+  
+  // Instantiate gMinuit if not already done
+  if (!gMinuit) gMinuit = new TMinuit(6);
+  // Clear MINUIT parameters
+  gMinuit->mncler();
+  // Give the fitted track to MINUIT
+  gMinuit->SetObjectFit(&track);
+  if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
+    // Define print level
+    arg[0] = 1;
+    gMinuit->mnexcm("SET PRI", arg, 1, status);
+    // Print covariance matrix
+    gMinuit->mnexcm("SHO COV", arg, 0, status);
+  } else {
+    arg[0] = -1;
+    gMinuit->mnexcm("SET PRI", arg, 1, status);
+  }
+  // No warnings
+  gMinuit->mnexcm("SET NOW", arg, 0, status);
+  // Define strategy
+  //arg[0] = 2;
+  //gMinuit->mnexcm("SET STR", arg, 1, status);
+  
+  // set flag w/wo multiple scattering according to "includeMCS"
+  track.FitWithMCS(includeMCS);
+  if (includeMCS) {
+    // compute cluster weights only once
+    if (!track.ComputeClusterWeights()) {
+      AliWarning("cannot take into account the multiple scattering effects");
+      track.FitWithMCS(kFALSE);
+    }
+  }
+  
+  track.FitWithVertex(fitWithVertex);
+  if (fitWithVertex) SetVertexErrXY2ForFit(track);
+  
+  // Set fitting function
+  gMinuit->SetFCN(TrackChi2);
+  
+  // Set fitted parameters (!! The order is very important for the covariance matrix !!)
+  // Mandatory limits to avoid NaN values of parameters
+  trackParam = (AliMUONTrackParam*) (track.GetTrackParamAtCluster()->First());
+  Double_t maxIBM = 1. / GetRecoParam()->GetMinBendingMomentum();
+  gMinuit->mnparm(0, "X", trackParam->GetNonBendingCoor(), 0.03, -500.0, 500.0, status);
+  gMinuit->mnparm(1, "NonBenS", trackParam->GetNonBendingSlope(), 0.001, -1., 1., status);
+  gMinuit->mnparm(2, "Y", trackParam->GetBendingCoor(), 0.10, -500.0, 500.0, status);
+  gMinuit->mnparm(3, "BenS", trackParam->GetBendingSlope(), 0.001, -1.5, 1.5, status);
+  gMinuit->mnparm(4, "InvBenP", trackParam->GetInverseBendingMomentum(), 0.003, -maxIBM, maxIBM, status);
+  
+  // minimization
+  gMinuit->mnexcm("MIGRAD", arg, 0, status);
+  
+  // Calculate the covariance matrix more accurately if required
+  if (calcCov) gMinuit->mnexcm("HESSE", arg, 0, status);
+   
+  // get results into "invBenP", "benC", "nonBenC" ("x", "y")
+  gMinuit->GetParameter(0, x, errorParam);
+  trackParam->SetNonBendingCoor(x);
+  gMinuit->GetParameter(1, nonBenC, errorParam);
+  trackParam->SetNonBendingSlope(nonBenC);
+  gMinuit->GetParameter(2, y, errorParam);
+  trackParam->SetBendingCoor(y);
+  gMinuit->GetParameter(3, benC, errorParam);
+  trackParam->SetBendingSlope(benC);
+  gMinuit->GetParameter(4, invBenP, errorParam);
+  trackParam->SetInverseBendingMomentum(invBenP);
+  
+  // global result of the fit
+  gMinuit->mnstat(globalChi2, fedm, errdef, npari, nparx, covStatus);
+  track.SetGlobalChi2(globalChi2);
+  
+  // Get the covariance matrix if required
+  if (calcCov) {
+    // Covariance matrix according to HESSE status
+    // If problem then keep only the diagonal terms (variances)
+    Double_t matrix[5][5];
+    gMinuit->mnemat(&matrix[0][0],5);
+    if (covStatus == 3) trackParam->SetCovariances(matrix);
+    else trackParam->SetVariances(matrix);
+  } else trackParam->DeleteCovariances();
+  
 }
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::MakeTrackCandidates(void)
+void TrackChi2(Int_t & /*nParam*/, Double_t * /*gradient*/, Double_t &chi2, Double_t *param, Int_t /*flag*/)
 {
-  // To make track candidates
-  // with at least 3 aligned points in stations(1..) 4 and 5
-  // (two Segment's or one Segment and one HitForRec)
-  Int_t begStation, iBegSegment, nbCan1Seg1Hit, nbCan2Seg;
-  AliMUONSegment *begSegment;
-  AliDebug(1,"Enter MakeTrackCandidates");
-  // Loop over stations(1..) 5 and 4 for the beginning segment
-  for (begStation = 4; begStation > 2; begStation--) {
-    // Loop over segments in the beginning station
-    for (iBegSegment = 0; iBegSegment < fNSegments[begStation]; iBegSegment++) {
-      // pointer to segment
-      begSegment = (AliMUONSegment*) ((*fSegmentsPtr[begStation])[iBegSegment]);
-      AliDebug(2,Form("Look for TrackCandidate's with Segment %d  in Station(0..) %d", iBegSegment, begStation));
-      // Look for track candidates with two segments,
-      // "begSegment" and all compatible segments in other station.
-      // Only for beginning station(1..) 5
-      // because candidates with 2 segments have to looked for only once.
-      if (begStation == 4)
-       nbCan2Seg = MakeTrackCandidatesWithTwoSegments(begSegment);
-      // Look for track candidates with one segment and one point,
-      // "begSegment" and all compatible HitForRec's in other station.
-      // Only if "begSegment" does not belong already to a track candidate.
-      // Is that a too strong condition ????
-      if (!(begSegment->GetInTrack()))
-       nbCan1Seg1Hit = MakeTrackCandidatesWithOneSegmentAndOnePoint(begSegment);
-    } // for (iBegSegment = 0;...
-  } // for (begStation = 4;...
-  return;
+  /// Return the "Chi2" to be minimized with Minuit for track fitting.
+  /// Assumes that the trackParamAtCluster are sorted according to increasing Z.
+  /// Track parameters at each cluster are updated accordingly.
+  /// Vertex is used according to the flag "trackBeingFitted->GetFitWithVertex()".
+  /// Multiple Coulomb scattering is taken into account according to the flag "trackBeingFitted->GetFitWithMCS()".
+  
+  AliMUONTrack *trackBeingFitted = (AliMUONTrack*) gMinuit->GetObjectFit();
+  AliMUONTrackParam* trackParamAtCluster = (AliMUONTrackParam*) trackBeingFitted->GetTrackParamAtCluster()->First();
+  Double_t dX, dY;
+  chi2 = 0.; // initialize chi2
+  
+  // update track parameters
+  trackParamAtCluster->SetNonBendingCoor(param[0]);
+  trackParamAtCluster->SetNonBendingSlope(param[1]);
+  trackParamAtCluster->SetBendingCoor(param[2]);
+  trackParamAtCluster->SetBendingSlope(param[3]);
+  trackParamAtCluster->SetInverseBendingMomentum(param[4]);
+  trackBeingFitted->UpdateTrackParamAtCluster();
+  
+  // Take the vertex into account in the fit if required
+  if (trackBeingFitted->FitWithVertex()) {
+    Double_t nonBendingReso2,bendingReso2;
+    trackBeingFitted->GetVertexErrXY2(nonBendingReso2,bendingReso2);
+    if (nonBendingReso2 == 0. || bendingReso2 == 0.) chi2 += 1.e10;
+    else {
+      AliMUONTrackParam paramAtVertex(*trackParamAtCluster);
+      AliMUONTrackExtrap::ExtrapToZ(&paramAtVertex, 0.); // vextex position = (0,0,0)
+      dX = paramAtVertex.GetNonBendingCoor();
+      dY = paramAtVertex.GetBendingCoor();
+      chi2 += dX * dX / nonBendingReso2 + dY * dY / bendingReso2;
+    }
+  }
+  
+  // compute chi2 w/wo multiple scattering
+  chi2 += trackBeingFitted->ComputeGlobalChi2(trackBeingFitted->FitWithMCS());
+  
 }
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::FollowTracks(void)
+void AliMUONTrackReconstructor::ComplementTracks(const AliMUONVClusterStore& clusterStore)
 {
-  // Follow tracks in stations(1..) 3, 2 and 1
-  // too long: should be made more modular !!!!
-  AliMUONHitForRec *bestHit, *extrapHit, *hit;
-  AliMUONSegment *bestSegment, *extrapSegment, *segment;
-  AliMUONTrack *track, *nextTrack;
-  AliMUONTrackParam *trackParam1, trackParam[2], trackParamVertex;
-  // -1 to avoid compilation warnings
-  Int_t ch = -1, chInStation, chBestHit = -1, iHit, iSegment, station, trackIndex; 
-  Double_t bestChi2, chi2, dZ1, dZ2, dZ3, maxSigma2Distance, mcsFactor;
-  Double_t bendingMomentum, chi2Norm = 0.;
-
-  // local maxSigma2Distance, for easy increase in testing
-  maxSigma2Distance = fMaxSigma2Distance;
-  AliDebug(2,"Enter FollowTracks");
-  // Loop over track candidates
-  track = (AliMUONTrack*) fRecTracksPtr->First();
-  trackIndex = -1;
+  /// Complete tracks by adding missing clusters (if there is an overlap between
+  /// two detection elements, the track may have two clusters in the same chamber)
+  /// Re-fit track parameters and covariances
+  AliDebug(1,"Enter ComplementTracks");
+  
+  Int_t chamberId, detElemId;
+  Double_t chi2OfCluster, bestChi2OfCluster;
+  Double_t sigmaCut2 = GetRecoParam()->GetSigmaCutForTracking() *
+                       GetRecoParam()->GetSigmaCutForTracking();
+  Bool_t foundOneCluster, trackModified;
+  AliMUONVCluster* cluster;
+  AliMUONTrackParam *trackParam, *nextTrackParam, copyOfTrackParam, trackParamAtCluster, bestTrackParamAtCluster;
+  
+  AliMUONTrack *track = (AliMUONTrack*) fRecTracksPtr->First();
   while (track) {
-    // Follow function for each track candidate ????
-    trackIndex++;
-    nextTrack = (AliMUONTrack*) fRecTracksPtr->After(track); // prepare next track
-    AliDebug(2,Form("FollowTracks: track candidate(0..): %d", trackIndex));
-    // Fit track candidate
-    track->SetFitMCS(0); // without multiple Coulomb scattering
-    track->SetFitNParam(3); // with 3 parameters (X = Y = 0)
-    track->SetFitStart(0); // from parameters at vertex
-    track->Fit();
-    if (AliLog::GetGlobalDebugLevel()> 2) {
-      cout << "FollowTracks: track candidate(0..): " << trackIndex
-          << " after fit in stations(0..) 3 and 4" << endl;
-      track->RecursiveDump();
-    }
-    // Loop over stations(1..) 3, 2 and 1
-    // something SPECIAL for stations 2 and 1 for majority 3 coincidence ????
-    // otherwise: majority coincidence 2 !!!!
-    for (station = 2; station >= 0; station--) {
-      // Track parameters at first track hit (smallest Z)
-      trackParam1 = ((AliMUONTrackHit*)
-                    (track->GetTrackHitsPtr()->First()))->GetTrackParam();
-      // extrapolation to station
-      trackParam1->ExtrapToStation(station, trackParam);
-      extrapSegment = new AliMUONSegment(); //  empty segment
-      // multiple scattering factor corresponding to one chamber
-      // and momentum in bending plane (not total)
-      mcsFactor = 0.0136 * trackParam1->GetInverseBendingMomentum();
-      mcsFactor        = fChamberThicknessInX0 * mcsFactor * mcsFactor;
-      // Z difference from previous station
-      dZ1 = AliMUONConstants::DefaultChamberZ(2 * station) -
-           AliMUONConstants::DefaultChamberZ(2 * station + 2);
-      // Z difference between the two previous stations
-      dZ2 = AliMUONConstants::DefaultChamberZ(2 * station + 2) -
-           AliMUONConstants::DefaultChamberZ(2 * station + 4);
-      // Z difference between the two chambers in the previous station
-      dZ3 = AliMUONConstants::DefaultChamberZ(2 * station) -
-           AliMUONConstants::DefaultChamberZ(2 * station + 1);
-      extrapSegment->SetBendingCoorReso2(fBendingResolution * fBendingResolution);
-      extrapSegment->
-       SetNonBendingCoorReso2(fNonBendingResolution * fNonBendingResolution);
-      extrapSegment->UpdateFromStationTrackParam
-       (trackParam, mcsFactor, dZ1, dZ2, dZ3, station,
-        trackParam1->GetInverseBendingMomentum());
-      bestChi2 = 5.0;
-      bestSegment = NULL;
-      if (AliLog::GetGlobalDebugLevel() > 2) {
-       cout << "FollowTracks: track candidate(0..): " << trackIndex
-            << " Look for segment in station(0..): " << station << endl;
-      }
-      // Loop over segments in station
-      for (iSegment = 0; iSegment < fNSegments[station]; iSegment++) {
-       // Look for best compatible Segment in station
-       // should consider all possibilities ????
-       // multiple scattering ????
-       // separation in 2 functions: Segment and HitForRec ????
-       segment = (AliMUONSegment*) ((*fSegmentsPtr[station])[iSegment]);
-       // correction of corrected segment (fBendingCoor and fNonBendingCoor)
-       // according to real Z value of "segment" and slopes of "extrapSegment"
-       (&(trackParam[0]))->ExtrapToZ(segment->GetZ());
-       (&(trackParam[1]))->ExtrapToZ(segment->GetZ());
-       extrapSegment->SetBendingCoor((&(trackParam[0]))->GetBendingCoor());
-       extrapSegment->SetNonBendingCoor((&(trackParam[0]))->GetNonBendingCoor());
-       extrapSegment->SetBendingSlope((&(trackParam[0]))->GetBendingSlope());
-       extrapSegment->SetNonBendingSlope((&(trackParam[0]))->GetNonBendingSlope());
-       chi2 = segment->
-         NormalizedChi2WithSegment(extrapSegment, maxSigma2Distance);
-       if (chi2 < bestChi2) {
-         // update best Chi2 and Segment if better found
-         bestSegment = segment;
-         bestChi2 = chi2;
-       }
-      }
-      if (bestSegment) {
-       // best segment found: add it to track candidate
-       (&(trackParam[0]))->ExtrapToZ(bestSegment->GetZ());
-       (&(trackParam[1]))->ExtrapToZ(bestSegment->GetZ());
-       track->AddSegment(bestSegment);
-       // set track parameters at these two TrakHit's
-       track->SetTrackParamAtHit(track->GetNTrackHits() - 2, &(trackParam[0]));
-       track->SetTrackParamAtHit(track->GetNTrackHits() - 1, &(trackParam[1]));
-       AliDebug(3, Form("FollowTracks: track candidate(0..): %d  Added segment in station(0..): %d", trackIndex, station));
-       if (AliLog::GetGlobalDebugLevel()>2) track->RecursiveDump();
-      }
-      else {
-       // No best segment found:
-       // Look for best compatible HitForRec in station:
-       // should consider all possibilities ????
-       // multiple scattering ???? do about like for extrapSegment !!!!
-       extrapHit = new AliMUONHitForRec(); //  empty hit
-       bestChi2 = 3.0;
-       bestHit = NULL;
-       AliDebug(3, Form("FollowTracks: track candidate(0..): %d Segment not found, look for hit in station(0..): %d ", 
-                        trackIndex, station));
+    trackModified = kFALSE;
+    
+    trackParam = (AliMUONTrackParam*)track->GetTrackParamAtCluster()->First();
+    while (trackParam) {
+      foundOneCluster = kFALSE;
+      bestChi2OfCluster = 2. * sigmaCut2; // 2 because 2 quantities in chi2
+      chamberId = trackParam->GetClusterPtr()->GetChamberId();
+      detElemId = trackParam->GetClusterPtr()->GetDetElemId();
+      
+      // prepare nextTrackParam before adding new cluster because of the sorting
+      nextTrackParam = (AliMUONTrackParam*)track->GetTrackParamAtCluster()->After(trackParam);
+      
+      // recover track parameters from local fit and put them into a copy of trackParam
+      copyOfTrackParam.SetZ(trackParam->GetZ());
+      copyOfTrackParam.SetParameters(trackParam->GetSmoothParameters());
+      copyOfTrackParam.SetCovariances(trackParam->GetSmoothCovariances());
+      
+      // Create iterators to loop over clusters in current chamber
+      TIter nextInCh(clusterStore.CreateChamberIterator(chamberId,chamberId));
+      
+      // look for one second candidate in the same chamber
+      while ( ( cluster = static_cast<AliMUONVCluster*>(nextInCh()) ) ) {
+        
+       // look for a cluster in another detection element
+       if (cluster->GetDetElemId() == detElemId) continue;
        
-       // Loop over chambers of the station
-       for (chInStation = 0; chInStation < 2; chInStation++) {
-         ch = 2 * station + chInStation;
-         for (iHit = fIndexOfFirstHitForRecPerChamber[ch];
-              iHit < fIndexOfFirstHitForRecPerChamber[ch] +
-                fNHitsForRecPerChamber[ch];
-              iHit++) {
-           hit = (AliMUONHitForRec*) ((*fHitsForRecPtr)[iHit]);
-           // coordinates of extrapolated hit
-           (&(trackParam[chInStation]))->ExtrapToZ(hit->GetZ());
-           extrapHit->
-             SetBendingCoor((&(trackParam[chInStation]))->GetBendingCoor());
-           extrapHit->
-             SetNonBendingCoor((&(trackParam[chInStation]))->GetNonBendingCoor());
-           // resolutions from "extrapSegment"
-           extrapHit->SetBendingReso2(extrapSegment->GetBendingCoorReso2());
-           extrapHit->SetNonBendingReso2(extrapSegment->GetNonBendingCoorReso2());
-           // Loop over hits in the chamber
-           // condition for hit not already in segment ????
-           chi2 = hit->NormalizedChi2WithHitForRec(extrapHit, maxSigma2Distance);
-           if (chi2 < bestChi2) {
-             // update best Chi2 and HitForRec if better found
-             bestHit = hit;
-             bestChi2 = chi2;
-             chBestHit = chInStation;
-           }
-         }
-       }
-       if (bestHit) {
-         // best hit found: add it to track candidate
-         (&(trackParam[chBestHit]))->ExtrapToZ(bestHit->GetZ());
-         track->AddHitForRec(bestHit);
-         // set track parameters at this TrackHit
-         track->SetTrackParamAtHit(track->GetNTrackHits() - 1,
-                                   &(trackParam[chBestHit]));
-         if (AliLog::GetGlobalDebugLevel() > 2) {
-           cout << "FollowTracks: track candidate(0..): " << trackIndex
-                << " Added hit in station(0..): " << station << endl;
-           track->RecursiveDump();
-         }
-       }
-       else {
-         // Remove current track candidate
-         // and corresponding TrackHit's, ...
-         track->Remove();
-         delete extrapSegment;
-         delete extrapHit;
-         break; // stop the search for this candidate:
-         // exit from the loop over station
+       // try to add the current cluster fast
+       if (!TryOneClusterFast(copyOfTrackParam, cluster)) continue;
+       
+       // try to add the current cluster accurately
+       chi2OfCluster = TryOneCluster(copyOfTrackParam, cluster, trackParamAtCluster);
+       
+       // if better chi2 then prepare to add this cluster to the track
+       if (chi2OfCluster < bestChi2OfCluster) {
+         bestChi2OfCluster = chi2OfCluster;
+         bestTrackParamAtCluster = trackParamAtCluster;
+         foundOneCluster = kTRUE;
        }
-       delete extrapHit;
-      }
-      delete extrapSegment;
-      // Sort track hits according to increasing Z
-      track->GetTrackHitsPtr()->Sort();
-      // Update track parameters at first track hit (smallest Z)
-      trackParam1 = ((AliMUONTrackHit*)
-                    (track->GetTrackHitsPtr()->First()))->GetTrackParam();
-      bendingMomentum = 0.;
-      if (TMath::Abs(trackParam1->GetInverseBendingMomentum()) > 0.)
-       bendingMomentum = TMath::Abs(1/(trackParam1->GetInverseBendingMomentum()));
-      // Track removed if bendingMomentum not in window [min, max]
-      if ((bendingMomentum < fMinBendingMomentum) || (bendingMomentum > fMaxBendingMomentum)) {
-       track->Remove();
-       break; // stop the search for this candidate:
-       // exit from the loop over station 
-      }
-      // Track fit
-      // with multiple Coulomb scattering if all stations
-      if (station == 0) track->SetFitMCS(1);
-      // without multiple Coulomb scattering if not all stations
-      else track->SetFitMCS(0);
-      track->SetFitNParam(5);  // with 5 parameters (momentum and position)
-      track->SetFitStart(1);  // from parameters at first hit
-      track->Fit();
-      Double_t numberOfDegFree = (2.0 * track->GetNTrackHits() - 5);
-      if (numberOfDegFree > 0) {
-        chi2Norm =  track->GetFitFMin() / numberOfDegFree;
-      } else {
-       chi2Norm = 1.e10;
-      }
-      // Track removed if normalized chi2 too high
-      if (chi2Norm > fMaxChi2) {
-       track->Remove();
-       break; // stop the search for this candidate:
-       // exit from the loop over station 
-      }
-      if (AliLog::GetGlobalDebugLevel() > 2) {
-       cout << "FollowTracks: track candidate(0..): " << trackIndex
-            << " after fit from station(0..): " << station << " to 4" << endl;
-       track->RecursiveDump();
+       
       }
-      // Track extrapolation to the vertex through the absorber (Branson)
-      // after going through the first station
-      if (station == 0) {
-       trackParamVertex = *trackParam1;
-       (&trackParamVertex)->ExtrapToVertex(0.,0.,0.);
-       track->SetTrackParamAtVertex(&trackParamVertex);
-       if (AliLog::GetGlobalDebugLevel() > 0) {
-         cout << "FollowTracks: track candidate(0..): " << trackIndex
-              << " after extrapolation to vertex" << endl;
-         track->RecursiveDump();
+      
+      // add new cluster if any
+      if (foundOneCluster) {
+       
+       // Printout for debuging
+       if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+         cout << "ComplementTracks: found one cluster in chamber(1..): " << chamberId+1 << endl;
+         bestTrackParamAtCluster.GetClusterPtr()->Print();
+         cout<<endl<<"Track parameters and covariances at cluster:"<<endl;
+         bestTrackParamAtCluster.GetParameters().Print();
+         bestTrackParamAtCluster.GetCovariances().Print();
        }
+       
+       trackParam->SetRemovable(kTRUE);
+       bestTrackParamAtCluster.SetRemovable(kTRUE);
+       track->AddTrackParamAtCluster(bestTrackParamAtCluster,*(bestTrackParamAtCluster.GetClusterPtr()));
+       trackModified = kTRUE;
       }
-    } // for (station = 2;...
-    // go really to next track
-    track = nextTrack;
-  } // while (track)
-  // Compression of track array (necessary after Remove ????)
-  fRecTracksPtr->Compress();
-  return;
-}
-
-  //__________________________________________________________________________
-void AliMUONTrackReconstructor::RemoveDoubleTracks(void)
-{
-  // To remove double tracks.
-  // Tracks are considered identical
-  // if they have at least half of their hits in common.
-  // Among two identical tracks, one keeps the track with the larger number of hits
-  // or, if these numbers are equal, the track with the minimum Chi2.
-  AliMUONTrack *track1, *track2, *trackToRemove;
-  Bool_t identicalTracks;
-  Int_t hitsInCommon, nHits1, nHits2;
-  identicalTracks = kTRUE;
-  while (identicalTracks) {
-    identicalTracks = kFALSE;
-    // Loop over first track of the pair
-    track1 = (AliMUONTrack*) fRecTracksPtr->First();
-    while (track1 && (!identicalTracks)) {
-      nHits1 = track1->GetNTrackHits();
-      // Loop over second track of the pair
-      track2 = (AliMUONTrack*) fRecTracksPtr->After(track1);
-      while (track2 && (!identicalTracks)) {
-       nHits2 = track2->GetNTrackHits();
-       // number of hits in common between two tracks
-       hitsInCommon = track1->HitsInCommon(track2);
-       // check for identical tracks
-       if ((4 * hitsInCommon) >= (nHits1 + nHits2)) {
-         identicalTracks = kTRUE;
-         // decide which track to remove
-         if (nHits1 > nHits2) trackToRemove = track2;
-         else if (nHits1 < nHits2) trackToRemove = track1;
-         else if ((track1->GetFitFMin()) < (track2->GetFitFMin()))
-           trackToRemove = track2;
-         else trackToRemove = track1;
-         // remove it
-         trackToRemove->Remove();
-       }
-       track2 = (AliMUONTrack*) fRecTracksPtr->After(track2);
-      } // track2
-      track1 = (AliMUONTrack*) fRecTracksPtr->After(track1);
-    } // track1
-  }
-  return;
-}
-
-  //__________________________________________________________________________
-void AliMUONTrackReconstructor::UpdateTrackParamAtHit()
-{
-  // Set track parameters after track fitting. Fill fTrackParamAtHit of AliMUONTrack's
-  AliMUONTrack *track;
-  AliMUONTrackHit *trackHit;
-  AliMUONTrackParam *trackParam;
-  track = (AliMUONTrack*) fRecTracksPtr->First();
-  while (track) {
-    trackHit = (AliMUONTrackHit*) (track->GetTrackHitsPtr())->First();
-    while (trackHit) {
-      trackParam = trackHit->GetTrackParam();
-      track->AddTrackParamAtHit(trackParam);
-      trackHit = (AliMUONTrackHit*) (track->GetTrackHitsPtr())->After(trackHit); 
-    } // trackHit    
-    track = (AliMUONTrack*) fRecTracksPtr->After(track);
-  } // track
-  return;
-}
-
-  //__________________________________________________________________________
-void AliMUONTrackReconstructor::UpdateHitForRecAtHit()
-{
-  // Set cluster parameterss after track fitting. Fill fHitForRecAtHit of AliMUONTrack's
-  AliMUONTrack *track;
-  AliMUONTrackHit *trackHit;
-  AliMUONHitForRec *hitForRec;
-  track = (AliMUONTrack*) fRecTracksPtr->First();
-  while (track) {
-    trackHit = (AliMUONTrackHit*) (track->GetTrackHitsPtr())->First();
-    while (trackHit) {
-      hitForRec = trackHit->GetHitForRecPtr();
-      track->AddHitForRecAtHit(hitForRec);
-      trackHit = (AliMUONTrackHit*) (track->GetTrackHitsPtr())->After(trackHit); 
-    } // trackHit    
+      
+      trackParam = nextTrackParam;
+    }
+    
+    // re-fit track parameters if needed
+    if (trackModified) Fit(*track, kTRUE, kFALSE, kTRUE);
+    
     track = (AliMUONTrack*) fRecTracksPtr->After(track);
-  } // track
-  return;
-}
-
-  //__________________________________________________________________________
-void AliMUONTrackReconstructor::FillMUONTrack()
-{
-  // Set track parameters at hits for Kalman track. Fill fTrackParamAtHit of AliMUONTrack's
-  AliMUONTrackK *track;
-  track = (AliMUONTrackK*) fRecTracksPtr->First();
-  while (track) {
-    track->FillMUONTrack();
-    track = (AliMUONTrackK*) fRecTracksPtr->After(track);
-  } 
-  return;
-}
-
-  //__________________________________________________________________________
-void AliMUONTrackReconstructor::EventDump(void)
-{
-  // Dump reconstructed event (track parameters at vertex and at first hit),
-  // and the particle parameters
-
-  AliMUONTrack *track;
-  AliMUONTrackParam *trackParam, *trackParam1;
-  Double_t bendingSlope, nonBendingSlope, pYZ;
-  Double_t pX, pY, pZ, x, y, z, c;
-  Int_t np, trackIndex, nTrackHits;
-  AliDebug(1,"****** enter EventDump ******");
-  AliDebug(1, Form("Number of Reconstructed tracks : %d", fNRecTracks)); 
-  
-  fRecTracksPtr->Compress(); // for simple loop without "Next" since no hole
-  // Loop over reconstructed tracks
-  for (trackIndex = 0; trackIndex < fNRecTracks; trackIndex++) {
-    if (fTrackMethod != 1) continue; //AZ - skip the rest for now
-    AliDebug(1, Form("track number: %d", trackIndex));
-    // function for each track for modularity ????
-    track = (AliMUONTrack*) ((*fRecTracksPtr)[trackIndex]);
-    nTrackHits = track->GetNTrackHits();
-    AliDebug(1, Form("Number of track hits: %d ", nTrackHits));
-    // track parameters at Vertex
-    trackParam = track->GetTrackParamAtVertex();
-    x = trackParam->GetNonBendingCoor();
-    y = trackParam->GetBendingCoor();
-    z = trackParam->GetZ();
-    bendingSlope = trackParam->GetBendingSlope();
-    nonBendingSlope = trackParam->GetNonBendingSlope();
-    pYZ = 1/TMath::Abs(trackParam->GetInverseBendingMomentum());
-    pZ = pYZ/TMath::Sqrt(1+bendingSlope*bendingSlope);
-    pX = pZ * nonBendingSlope;
-    pY = pZ * bendingSlope;
-    c = TMath::Sign(1.0, trackParam->GetInverseBendingMomentum());
-    AliDebug(1, Form("Track parameters at Vertex z= %f: X= %f Y= %f pX= %f pY= %f pZ= %f c= %f\n",
-                    z, x, y, pX, pY, pZ, c));
-
-    // track parameters at first hit
-    trackParam1 = ((AliMUONTrackHit*)
-                  (track->GetTrackHitsPtr()->First()))->GetTrackParam();
-    x = trackParam1->GetNonBendingCoor();
-    y = trackParam1->GetBendingCoor();
-    z = trackParam1->GetZ();
-    bendingSlope = trackParam1->GetBendingSlope();
-    nonBendingSlope = trackParam1->GetNonBendingSlope();
-    pYZ = 1/TMath::Abs(trackParam1->GetInverseBendingMomentum());
-    pZ = pYZ/TMath::Sqrt(1.0 + bendingSlope * bendingSlope);
-    pX = pZ * nonBendingSlope;
-    pY = pZ * bendingSlope;
-    c = TMath::Sign(1.0, trackParam1->GetInverseBendingMomentum());
-    AliDebug(1, Form("track parameters at z= %f: X= %f Y= %f pX= %f pY= %f pZ= %f c= %f\n",
-                    z, x, y, pX, pY, pZ, c));
   }
-  // informations about generated particles
-  np = gAlice->GetMCApp()->GetNtrack();
-  printf(" **** number of generated particles: %d  \n", np);
-  
-//    for (Int_t iPart = 0; iPart < np; iPart++) {
-//      p = gAlice->Particle(iPart);
-//      printf(" particle %d: type= %d px= %f py= %f pz= %f pdg= %d\n",
-//        iPart, p->GetPdgCode(), p->Px(), p->Py(), p->Pz(), p->GetPdgCode());    
-//    }
-  return;
+  
 }
 
-
-//__________________________________________________________________________
-void AliMUONTrackReconstructor::EventDumpTrigger(void)
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::ImproveTrack(AliMUONTrack &track)
 {
-  // Dump reconstructed trigger event 
-  // and the particle parameters
+  /// Improve the given track by removing clusters with local chi2 highter than the defined cut
+  /// Recompute track parameters and covariances at the remaining clusters
+  AliDebug(1,"Enter ImproveTrack");
+  
+  Double_t localChi2, worstLocalChi2;
+  AliMUONTrackParam *trackParamAtCluster, *worstTrackParamAtCluster;
+  Double_t sigmaCut2 = GetRecoParam()->GetSigmaCutForImprovement() *
+                      GetRecoParam()->GetSigmaCutForImprovement();
+  
+  while (!track.IsImproved()) {
     
-  AliMUONTriggerTrack *triggertrack ;
-  Int_t nTriggerTracks = fMUONData->RecTriggerTracks()->GetEntriesFast();
-  AliDebug(1, "****** enter EventDumpTrigger ******");
-  AliDebug(1, Form("Number of Reconstructed tracks : %d ",  nTriggerTracks));
-  
-  // Loop over reconstructed tracks
-  for (Int_t trackIndex = 0; trackIndex < nTriggerTracks; trackIndex++) {
-    triggertrack = (AliMUONTriggerTrack*)fMUONData->RecTriggerTracks()->At(trackIndex);
-      printf(" trigger track number %i x11=%f y11=%f thetax=%f thetay=%f \n",
-            trackIndex,
-            triggertrack->GetX11(),triggertrack->GetY11(),
-            triggertrack->GetThetax(),triggertrack->GetThetay());      
-  } 
-}
-
-//__________________________________________________________________________
-void AliMUONTrackReconstructor::MakeTrackCandidatesK(void)
-{
-  // To make initial tracks for Kalman filter from the list of segments
-  Int_t istat, iseg;
-  AliMUONSegment *segment;
-  AliMUONTrackK *trackK;
-
-  AliDebug(1,"Enter MakeTrackCandidatesK");
-  // Reset the TClonesArray of reconstructed tracks
-  if (fRecTracksPtr) fRecTracksPtr->Delete();
-  // Delete in order that the Track destructors are called,
-  // hence the space for the TClonesArray of pointers to TrackHit's is freed
-  fNRecTracks = 0;
-
-  AliMUONTrackK a(this, fHitsForRecPtr); // bad idea ???
-  // Loop over stations(1...) 5 and 4
-  for (istat=4; istat>=3; istat--) {
-    // Loop over segments in the station
-    for (iseg=0; iseg<fNSegments[istat]; iseg++) {
-      // Transform segments to tracks and evaluate covariance matrix
-      segment = (AliMUONSegment*) ((*fSegmentsPtr[istat])[iseg]);
-      trackK = new ((*fRecTracksPtr)[fNRecTracks++]) AliMUONTrackK(segment);
-    } // for (iseg=0;...)
-  } // for (istat=4;...)
-  return;
-}
-
-//__________________________________________________________________________
-void AliMUONTrackReconstructor::FollowTracksK(void)
-{
-  // Follow tracks using Kalman filter
-  Bool_t ok;
-  Int_t icand, ichamBeg = 0, ichamEnd, chamBits;
-  Double_t zDipole1, zDipole2;
-  AliMUONTrackK *trackK;
-  AliMUONHitForRec *hit;
-  AliMUONRawCluster *clus;
-  TClonesArray *rawclusters;
-  clus = 0; rawclusters = 0;
-
-  zDipole1 = GetSimpleBPosition() + GetSimpleBLength()/2;
-  zDipole2 = zDipole1 - GetSimpleBLength();
-
-  // Print hits
-  trackK = (AliMUONTrackK*) ((*fRecTracksPtr)[0]);
-  if (trackK->DebugLevel() > 0) {
-    for (Int_t i1=0; i1<fNHitsForRec; i1++) {
-      hit = (AliMUONHitForRec*) ((*fHitsForRecPtr)[i1]);
-      //if (hit->GetTTRTrack() > 1 || hit->GetTrackRefSignal() == 0) continue;
-      printf(" Hit # %d %10.4f %10.4f %10.4f",
-             hit->GetChamberNumber(), hit->GetBendingCoor(),
-             hit->GetNonBendingCoor(), hit->GetZ());
-      if (fRecTrackRefHits) {
-        // from track ref hits
-       printf(" %3d %3d \n", hit->GetTrackRefSignal(), hit->GetTTRTrack());
-      } else {
-       // from raw clusters
-       rawclusters = fMUONData->RawClusters(hit->GetChamberNumber());
-       clus = (AliMUONRawCluster*) rawclusters->UncheckedAt(hit->
-                                                 GetHitNumber());
-       printf(" %d", clus->GetTrack(1));
-       if (clus->GetTrack(2) != -1) printf(" %d \n", clus->GetTrack(2));
-       else printf("\n");
-      } // if (fRecTrackRefHits)
-    }
-  } // if (trackK->DebugLevel() > 0)
-
-  icand = -1;
-  Int_t nSeeds;
-  nSeeds = fNRecTracks; // starting number of seeds
-  // Loop over track candidates
-  while (icand < fNRecTracks-1) {
-    icand ++;
-    if (trackK->DebugLevel()>0) cout << " *** Kalman track candidate No. " << icand << endl;
-    trackK = (AliMUONTrackK*) ((*fRecTracksPtr)[icand]);
-    if (trackK->GetRecover() < 0) continue; // failed track
-
-    // Discard candidate which will produce the double track
-    /*
-    if (icand > 0) {
-      ok = CheckCandidateK(icand,nSeeds);
-      if (!ok) {
-        trackK->SetRecover(-1); // mark candidate to be removed
-        continue;
-      }
-    }
-    */
-
-    ok = kTRUE;
-    if (trackK->GetRecover() == 0) hit = (AliMUONHitForRec*) 
-                                   trackK->GetHitOnTrack()->Last(); // last hit
-    //else hit = (AliMUONHitForRec*) (*trackK->GetHitOnTrack())[1]; // 2'nd hit
-    else hit = trackK->GetHitLastOk(); // hit where track stopped
-    if (hit) ichamBeg = hit->GetChamberNumber();
-    ichamEnd = 0;
-    // Check propagation direction
-    if (!hit) { ichamBeg = ichamEnd; AliFatal(" ??? "); }
-    else if (trackK->GetTrackDir() < 0) {
-      ichamEnd = 9; // forward propagation
-      ok = trackK->KalmanFilter(ichamBeg,ichamEnd,kFALSE,zDipole1,zDipole2);
-      if (ok) {
-        ichamBeg = ichamEnd;
-        ichamEnd = 6; // backward propagation
-       // Change weight matrix and zero fChi2 for backpropagation
-        trackK->StartBack();
-       trackK->SetTrackDir(1);
-        ok = trackK->KalmanFilter(ichamBeg,ichamEnd,kTRUE,zDipole1,zDipole2);
-        ichamBeg = ichamEnd;
-        ichamEnd = 0;
-      }
-    } else {
-      if (trackK->GetBPFlag()) {
-       // backpropagation
-        ichamEnd = 6; // backward propagation
-       // Change weight matrix and zero fChi2 for backpropagation
-        trackK->StartBack();
-        ok = trackK->KalmanFilter(ichamBeg,ichamEnd,kTRUE,zDipole1,zDipole2);
-        ichamBeg = ichamEnd;
-        ichamEnd = 0;
+    // identify removable clusters
+    track.TagRemovableClusters(GetRecoParam()->RequestedStationMask());
+    
+    // Update track parameters and covariances
+    track.UpdateCovTrackParamAtCluster();
+    
+    // Compute local chi2 of each clusters
+    track.ComputeLocalChi2(kTRUE);
+    
+    // Look for the cluster to remove
+    worstTrackParamAtCluster = NULL;
+    worstLocalChi2 = 0.;
+    trackParamAtCluster = (AliMUONTrackParam*) track.GetTrackParamAtCluster()->First();
+    while (trackParamAtCluster) {
+      
+      // Pick up cluster with the worst chi2
+      localChi2 = trackParamAtCluster->GetLocalChi2();
+      if (localChi2 > worstLocalChi2) {
+       worstLocalChi2 = localChi2;
+       worstTrackParamAtCluster = trackParamAtCluster;
       }
+      
+    trackParamAtCluster = (AliMUONTrackParam*) track.GetTrackParamAtCluster()->After(trackParamAtCluster);
     }
-
-    if (ok) {
-      trackK->SetTrackDir(1);
-      trackK->SetBPFlag(kFALSE);
-      ok = trackK->KalmanFilter(ichamBeg,ichamEnd,kFALSE,zDipole1,zDipole2);
-    }
-    if (!ok) { trackK->SetRecover(-1); continue; } // mark candidate to be removed
-
-    // Apply smoother
-    if (trackK->GetRecover() >= 0) {
-      ok = trackK->Smooth();
-      if (!ok) trackK->SetRecover(-1); // mark candidate to be removed
+    
+    // Check if worst cluster found
+    if (!worstTrackParamAtCluster) {
+      AliWarning("Bad local chi2 values?");
+      break;
     }
-
-    // Majority 3 of 4 in first 2 stations
-    if (!ok) continue;
-    chamBits = 0;
-    Double_t chi2max = 0;
-    for (Int_t i=0; i<trackK->GetNTrackHits(); i++) {
-      hit = (AliMUONHitForRec*) (*trackK->GetHitOnTrack())[i];
-      chamBits |= BIT(hit->GetChamberNumber());
-      if (trackK->GetChi2PerPoint(i) > chi2max) chi2max = trackK->GetChi2PerPoint(i);
+    
+    // Check whether the worst chi2 is under requirement or not
+    if (worstLocalChi2 < 2. * sigmaCut2) { // 2 because 2 quantities in chi2
+      track.SetImproved(kTRUE);
+      break;
     }
-    if (!((chamBits&3)==3 || (chamBits>>2&3)==3) && chi2max > 25) {
-      //trackK->Recover();
-      trackK->SetRecover(-1); //mark candidate to be removed
-      continue;
+    
+    // if the worst cluster is not removable then stop improvement
+    if (!worstTrackParamAtCluster->IsRemovable()) break;
+    
+    // Remove the worst cluster
+    track.RemoveTrackParamAtCluster(worstTrackParamAtCluster);
+    
+    // Re-fit the track:
+    // Take into account the multiple scattering
+    // Calculate the track parameter covariance matrix
+    Fit(track, kTRUE, kFALSE, kTRUE);
+    
+    // Printout for debuging
+    if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+      cout << "ImproveTracks: track " << fRecTracksPtr->IndexOf(&track)+1 << " improved " << endl;
     }
-    if (ok) trackK->SetTrackQuality(0); // compute "track quality"
-  } // while
-
-  for (Int_t i=0; i<fNRecTracks; i++) {
-    trackK = (AliMUONTrackK*) ((*fRecTracksPtr)[i]);
-    if (trackK->GetRecover() < 0) fRecTracksPtr->RemoveAt(i);
+    
   }
-
-  // Compress TClonesArray
-  fRecTracksPtr->Compress();
-  fNRecTracks = fRecTracksPtr->GetEntriesFast();
-  return;
-}
-
-//__________________________________________________________________________
-Bool_t AliMUONTrackReconstructor::CheckCandidateK(Int_t icand, Int_t nSeeds) const
-{
-  // Discards track candidate if it will produce the double track (having
-  // the same seed segment hits as hits of a good track found before)
-  AliMUONTrackK *track1, *track2;
-  AliMUONHitForRec *hit1, *hit2, *hit;
-
-  track1 = (AliMUONTrackK*) ((*fRecTracksPtr)[icand]);
-  hit1 = (AliMUONHitForRec*) (*track1->GetHitOnTrack())[0]; // 1'st hit
-  hit2 = (AliMUONHitForRec*) (*track1->GetHitOnTrack())[1]; // 2'nd hit
-
-  for (Int_t i=0; i<icand; i++) {
-    track2 = (AliMUONTrackK*) ((*fRecTracksPtr)[i]);
-    //if (track2->GetRecover() < 0) continue;
-    if (track2->GetRecover() < 0 && icand >= nSeeds) continue;
-
-    if (track1->GetStartSegment() == track2->GetStartSegment()) {
-      return kFALSE;
-    } else {
-      Int_t nSame = 0;
-      for (Int_t j=0; j<track2->GetNTrackHits(); j++) {
-        hit = (AliMUONHitForRec*) (*track2->GetHitOnTrack())[j];
-        if (hit == hit1 || hit == hit2) {
-          nSame++;
-          if (nSame == 2) return kFALSE;
-        }
-      } // for (Int_t j=0;
-    }
-  } // for (Int_t i=0;
-  return kTRUE;
+  
 }
 
-//__________________________________________________________________________
-void AliMUONTrackReconstructor::RemoveDoubleTracksK(void)
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::FinalizeTrack(AliMUONTrack &track)
 {
-  // Removes double tracks (sharing more than half of their hits). Keeps
-  // the track with higher quality
-  AliMUONTrackK *track1, *track2, *trackToKill;
-
-  // Sort tracks according to their quality
-  fRecTracksPtr->Sort();
-
-  // Loop over first track of the pair
-  track1 = (AliMUONTrackK*) fRecTracksPtr->First();
-  Int_t debug = track1->DebugLevel();
-  while (track1) {
-    // Loop over second track of the pair
-    track2 = (AliMUONTrackK*) fRecTracksPtr->After(track1);
-    while (track2) {
-      // Check whether or not to keep track2
-      if (!track2->KeepTrack(track1)) {
-        if (debug >= 0) cout << " Killed track: " << 1/(*track2->GetTrackParameters())(4,0) <<
-         " " << track2->GetTrackQuality() << endl;
-        trackToKill = track2;
-        track2 = (AliMUONTrackK*) fRecTracksPtr->After(track2);
-        trackToKill->Kill();
-        fRecTracksPtr->Compress();
-      } else track2 = (AliMUONTrackK*) fRecTracksPtr->After(track2);
-    } // track2
-    track1 = (AliMUONTrackK*) fRecTracksPtr->After(track1);
-  } // track1
-
-  fNRecTracks = fRecTracksPtr->GetEntriesFast();
-  if (debug >= 0) cout << " Number of Kalman tracks: " << fNRecTracks << endl;
+  /// Recompute track parameters and covariances at each attached cluster
+  /// from those at the first one, if not already done
+  AliDebug(1,"Enter FinalizeTrack");
+  if (!track.IsImproved()) track.UpdateCovTrackParamAtCluster();
 }
 
-//__________________________________________________________________________
-void AliMUONTrackReconstructor::GoToVertex(void)
+  //__________________________________________________________________________
+Bool_t AliMUONTrackReconstructor::RefitTrack(AliMUONTrack &track, Bool_t enableImprovement)
 {
-  // Propagates track to the vertex thru absorber
-  // (using Branson correction for now)
-
-  Double_t zVertex;
-  zVertex = 0;
-  for (Int_t i=0; i<fNRecTracks; i++) {
-    //((AliMUONTrackK*)(*fRecTracksPtr)[i])->Branson();
-    ((AliMUONTrackK*)(*fRecTracksPtr)[i])->SetTrackQuality(1); // compute Chi2
-    //((AliMUONTrackK*)(*fRecTracksPtr)[i])->GoToZ(zVertex); // w/out absorber
-    ((AliMUONTrackK*)(*fRecTracksPtr)[i])->GoToVertex(1); // with absorber
+  /// re-fit the given track
+  
+  // check validity of the track
+  if (track.GetNClusters() < 3) {
+    AliWarning("the track does not contain enough clusters --> unable to refit");
+    return kFALSE;
   }
+  
+  // reset the seed (i.e. parameters at first cluster) before fitting
+  AliMUONTrackParam* firstTrackParam = (AliMUONTrackParam*) track.GetTrackParamAtCluster()->First();
+  if (firstTrackParam->GetInverseBendingMomentum() == 0.) {
+    AliWarning("track parameters at first chamber are not initialized --> unable to refit");
+    return kFALSE;
+  }
+  
+  // compute track parameters at each cluster from parameters at the first one
+  // necessary to compute multiple scattering effect during refitting
+  track.UpdateTrackParamAtCluster();
+  
+  // Re-fit the track:
+  // Take into account the multiple scattering
+  // Calculate the track parameter covariance matrix
+  Fit(track, kTRUE, kFALSE, kTRUE);
+  
+  // Improve the reconstructed tracks if required
+  track.SetImproved(kFALSE);
+  if (enableImprovement && GetRecoParam()->ImproveTracks()) ImproveTrack(track);
+  
+  // Fill AliMUONTrack data members
+  FinalizeTrack(track);
+  
+  return kTRUE;
+  
 }
 
-//__________________________________________________________________________
-void AliMUONTrackReconstructor::SetTrackMethod(Int_t iTrackMethod)
-{
-  // Set track method and recreate track container if necessary
-  
-  fTrackMethod = TMath::Min (iTrackMethod, 3);
-  fTrackMethod = TMath::Max (fTrackMethod, 1);
-  if (fTrackMethod != 1) {
-    if (fRecTracksPtr) delete fRecTracksPtr;
-    fRecTracksPtr = new TClonesArray("AliMUONTrackK", 10);
-    if (fTrackMethod == 2) cout << " *** Tracking with the Kalman filter *** " << endl;
-    else cout << " *** Combined cluster / track finder ***" << endl;
-  } else cout << " *** Traditional tracking *** " << endl;
-
-}