]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - MUON/AliMUONTrackReconstructor.cxx
Main changes:
[u/mrichter/AliRoot.git] / MUON / AliMUONTrackReconstructor.cxx
index 9a90ed7406b9926c35042e3d4c2531b50dcd8c91..2ce0754f3b176bac15276cefbc31ade5c28127e1 100644 (file)
@@ -15,6 +15,7 @@
 
 /* $Id$ */
 
+//-----------------------------------------------------------------------------
 /// \class AliMUONTrackReconstructor
 /// MUON track reconstructor using the original method
 ///
 ///
 /// It contains as methods, among others:
 /// - MakeTracks to build the tracks
-///
-
-#include <stdlib.h>
-#include <Riostream.h>
-#include <TMatrixD.h>
+//-----------------------------------------------------------------------------
 
-#include "AliMUONVTrackReconstructor.h"
 #include "AliMUONTrackReconstructor.h"
-#include "AliMUONData.h"
+
 #include "AliMUONConstants.h"
-#include "AliMUONRawCluster.h"
-#include "AliMUONHitForRec.h"
-#include "AliMUONSegment.h"
+#include "AliMUONVCluster.h"
+#include "AliMUONVClusterStore.h"
 #include "AliMUONTrack.h"
 #include "AliMUONTrackParam.h"
 #include "AliMUONTrackExtrap.h"
-#include "AliLog.h"
-#include <TVirtualFitter.h>
 
-// Functions to be minimized with Minuit
-void TrackChi2(Int_t &NParam, Double_t *Gradient, Double_t &Chi2, Double_t *Param, Int_t Flag);
-void TrackChi2MCS(Int_t &NParam, Double_t *Gradient, Double_t &Chi2, Double_t *Param, Int_t Flag);
+#include "AliLog.h"
 
-void mnvertLocal(Double_t* a, Int_t l, Int_t m, Int_t n, Int_t& ifail);
+#include <TMinuit.h>
+#include <Riostream.h>
+#include <TMath.h>
+#include <TMatrixD.h>
 
-Double_t MultipleScatteringAngle2(AliMUONTrackParam *param);
+// Functions to be minimized with Minuit
+void TrackChi2(Int_t &nParam, Double_t *gradient, Double_t &chi2, Double_t *param, Int_t flag);
 
 /// \cond CLASSIMP
 ClassImp(AliMUONTrackReconstructor) // Class implementation in ROOT context
 /// \endcond
 
-//************* Defaults parameters for reconstruction
-const Double_t AliMUONTrackReconstructor::fgkDefaultMaxChi2 = 100.0;
-
-TVirtualFitter* AliMUONTrackReconstructor::fgFitter = 0x0; 
-
-//__________________________________________________________________________
-AliMUONTrackReconstructor::AliMUONTrackReconstructor(AliMUONData* data)
-  : AliMUONVTrackReconstructor(data),
-    fMaxChi2(fgkDefaultMaxChi2)
+  //__________________________________________________________________________
+AliMUONTrackReconstructor::AliMUONTrackReconstructor()
+  : AliMUONVTrackReconstructor()
 {
-  /// Constructor for class AliMUONTrackReconstructor
-  
-  // Memory allocation for the TClonesArray of reconstructed tracks
-  fRecTracksPtr = new TClonesArray("AliMUONTrack", 10);
+  /// Constructor
 }
 
   //__________________________________________________________________________
-AliMUONTrackReconstructor::~AliMUONTrackReconstructor(void)
+AliMUONTrackReconstructor::~AliMUONTrackReconstructor()
 {
-  /// Destructor for class AliMUONTrackReconstructor
-  delete fRecTracksPtr;
-}
+/// Destructor
+} 
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::AddHitsForRecFromRawClusters()
+void AliMUONTrackReconstructor::MakeTrackCandidates(const AliMUONVClusterStore& clusterStore)
 {
-  /// To add to the list of hits for reconstruction all the raw clusters
-  TTree *treeR;
-  AliMUONHitForRec *hitForRec;
-  AliMUONRawCluster *clus;
-  Int_t iclus, nclus, nTRentries;
-  TClonesArray *rawclusters;
-  AliDebug(1,"Enter AddHitsForRecFromRawClusters");
-  
-  treeR = fMUONData->TreeR();
-  if (!treeR) {
-    AliError("TreeR must be loaded");
-    exit(0);
-  }
-  
-  nTRentries = Int_t(treeR->GetEntries());
+  /// 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.
   
-  if (!(fMUONData->IsRawClusterBranchesInTree())) {
-    AliError(Form("RawCluster information is not avalaible, nTRentries = %d not equal to 1",nTRentries));
-    exit(0);
-  }
+  TClonesArray *segments;
+  AliMUONTrack *track;
+  Int_t iCandidate = 0;
+  Bool_t clusterFound;
+
+  AliDebug(1,"Enter MakeTrackCandidates");
 
-  fMUONData->SetTreeAddress("RC");
-  fMUONData->GetRawClusters(); // only one entry  
-  
-  // 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);
-    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
-      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));
+  // Loop over stations(1..) 5 and 4 and make track candidates
+  for (Int_t istat=4; istat>=3; istat--) {
+    
+    // Make segments in the station
+    segments = MakeSegmentsInStation(clusterStore,istat);
+    
+    // Loop over segments
+    for (Int_t iseg=0; iseg<segments->GetEntriesFast(); iseg++) 
+    {
+      AliDebug(1,Form("Making primary candidate(1..) %d",++iCandidate));
       
-      StdoutToAliDebug(3,
-                       cout << "Chamber " << ch <<
-                       " raw cluster  " << iclus << " : " << endl;
-                       clus->Print("full");
-                       cout << "AliMUONHitForRec number (1...): " << fNHitsForRec << endl;
-                       hitForRec->Print("full");
-                       );
-    } // end of cluster loop
-  } // end of chamber loop
-  SortHitsForRecWithIncreasingChamber(); 
-  
-  AliDebug(1,"End of AddHitsForRecFromRawClusters");
-    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();
+      // Transform segments to tracks and put them at the end of fRecTracksPtr
+      track = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack((AliMUONObjectPair*)((*segments)[iseg]));
+      fNRecTracks++;
+      
+      // Printout for debuging
+      if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
+        cout<<endl<<"Track parameter covariances at first cluster:"<<endl;
+        ((AliMUONTrackParam*) track->GetTrackParamAtCluster()->First())->GetCovariances().Print();
+      }
+      
+      // Look for compatible cluster(s) in the other station
+      if (AliMUONReconstructor::GetRecoParam()->MakeTrackCandidatesFast())
+       clusterFound = FollowLinearTrackInStation(*track, clusterStore, 7-istat);
+      else clusterFound = FollowTrackInStation(*track, clusterStore, 7-istat);
+      
+      // Remove track if no cluster found
+      if (!clusterFound) {
+        fRecTracksPtr->Remove(track);
+       fNRecTracks--;
       }
+      
     }
+    
+    // delete the array of segments
+    delete segments;
   }
   
-  return;
+  fRecTracksPtr->Compress(); // this is essential before checking tracks
+  
+  // Keep all different tracks or only the best ones as required
+  if (AliMUONReconstructor::GetRecoParam()->TrackAllTracks()) RemoveIdenticalTracks();
+  else RemoveDoubleTracks();
+  
+  AliDebug(1,Form("Number of good candidates = %d",fNRecTracks));
+  
 }
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::MakeSegments(void)
+void AliMUONTrackReconstructor::FollowTracks(const AliMUONVClusterStore& clusterStore)
 {
-  /// To make the list of segments in all stations,
-  /// from the list of hits to be reconstructed
-  AliDebug(1,"Enter MakeSegments");
-  // Loop over stations
-  for (Int_t st = 0; st < AliMUONConstants::NTrackingCh()/2; st++) MakeSegmentsPerStation(st); 
-  
-  StdoutToAliDebug(3,
-    cout << "end of MakeSegments" << endl;
-    for (Int_t st = 0; st < AliMUONConstants::NTrackingCh()/2; st++) 
-    {
-      cout << "station " << st
-           << "  has " << fNSegments[st] << " segments:"
-           << endl;
-      for (Int_t seg = 0; seg < fNSegments[st]; seg++) 
-      {
-             ((*fSegmentsPtr[st])[seg])->Print();
+  /// Follow tracks in stations(1..) 3, 2 and 1
+  AliDebug(1,"Enter FollowTracks");
+  
+  AliMUONTrack *track, *nextTrack;
+  AliMUONTrackParam *trackParam, *nextTrackParam;
+  Int_t currentNRecTracks;
+  Bool_t clusterFound;
+  
+  Double_t sigmaCut2 = AliMUONReconstructor::GetRecoParam()->GetSigmaCutForTracking() *
+                       AliMUONReconstructor::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 "station" is station(1..) 3 then use the vertex to better constrain the fit
+      if (station==2) Fit(*track, kFALSE, kTRUE, kTRUE);
+      else Fit(*track, kFALSE, kFALSE, kTRUE);
+      
+      // Remove the track if the normalized chi2 is too high
+      if (track->GetNormalizedChi2() > sigmaCut2) {
+       fRecTracksPtr->Remove(track);
+       fNRecTracks--;
+       continue;
       }
+      
+      // save parameters from fit into smoothed parameters to complete track afterward
+      if (AliMUONReconstructor::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
+         
+         // save parameters from fit
+         trackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->First();
+         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());
+           
+         }
+         
+       }
+       
+      }
+      
+      // Printout for debuging
+      if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
+        cout<<endl<<"Track parameter covariances at first cluster:"<<endl;
+        ((AliMUONTrackParam*) track->GetTrackParamAtCluster()->First())->GetCovariances().Print();
+      }
+      
+      // Look for compatible cluster(s) in station(0..) "station"
+      clusterFound = FollowTrackInStation(*track, clusterStore, station);
+      
+      // Try to recover track if required
+      if (!clusterFound && AliMUONReconstructor::GetRecoParam()->RecoverTracks())
+       clusterFound = RecoverTrack(*track, clusterStore, station);
+      
+      // remove track if no cluster found
+      if (!clusterFound) {
+       fRecTracksPtr->Remove(track);
+       fNRecTracks--;
+      }
+      
+    }
+    
+    // Compress fRecTracksPtr for the next step
+    fRecTracksPtr->Compress();
+    
+    // Keep only the best tracks if required
+    if (!AliMUONReconstructor::GetRecoParam()->TrackAllTracks()) RemoveDoubleTracks();
+    
+  }
+  
+  // 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--;
+    }
+    
+    // save parameters from fit into smoothed parameters to complete track afterward
+    if (AliMUONReconstructor::GetRecoParam()->ComplementTracks()) {
+      
+      // save parameters from fit
+      trackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->First();
+      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());
+       
+      }
+      
     }
-                   );
-  return;
+    
+    track = nextTrack;
+    
+  }
+  
+  fRecTracksPtr->Compress();
+  
 }
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::MakeTracks(void)
+Bool_t AliMUONTrackReconstructor::FollowTrackInStation(AliMUONTrack &trackCandidate, const AliMUONVClusterStore& clusterStore, Int_t nextStation)
 {
-  /// To make the tracks from the list of segments and points in all stations
-  AliDebug(1,"Enter MakeTracks");
-  // 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();
-  UpdateHitForRecAtHit();
+  /// 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;
+  }
+  
+  Double_t chi2WithOneCluster = 1.e10;
+  Double_t chi2WithTwoClusters = 1.e10;
+  Double_t maxChi2WithOneCluster = 2. * AliMUONReconstructor::GetRecoParam()->GetSigmaCutForTracking() *
+                                       AliMUONReconstructor::GetRecoParam()->GetSigmaCutForTracking(); // 2 because 2 quantities in chi2
+  Double_t maxChi2WithTwoClusters = 4. * AliMUONReconstructor::GetRecoParam()->GetSigmaCutForTracking() *
+                                        AliMUONReconstructor::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 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
+  AliMUONTrackParam extrapTrackParamAtCh(*(AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->First());
+  
+  // Add MCS effect
+  AliMUONTrackExtrap::AddMCSEffect(&extrapTrackParamAtCh,AliMUONConstants::ChamberThicknessInX0(),1.);
+  
+  // Add MCS in the missing chamber if any (only 1 chamber can be missing according to tracking criteria)
+  if (ch1 < ch2 && extrapTrackParamAtCh.GetClusterPtr()->GetChamberId() > ch2 + 1) {
+    // extrapolation to the missing chamber
+    AliMUONTrackExtrap::ExtrapToZCov(&extrapTrackParamAtCh, AliMUONConstants::DefaultChamberZ(ch2 + 1));
+    // 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 parameter covariances at first cluster extrapolated to z = "<<AliMUONConstants::DefaultChamberZ(ch2)<<":"<<endl;
+    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;
+  }
+  
+  // 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;
+        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;
+         }
+         
+         if (AliMUONReconstructor::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;
+          }
+         
+       }
+       
+      }
+      
+      // if no clusterCh1 found then consider to add clusterCh2 only
+      if (!foundSecondCluster) {
+        foundOneCluster = kTRUE;
+        
+       if (AliMUONReconstructor::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;
+        }
+       
+      }
+      
+    }
+    
+  }
+  
+  // 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 (AliMUONReconstructor::GetRecoParam()->TrackAllTracks() || !foundTwoClusters) {
+    
+    // Printout for debuging
+    if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+      cout << "FollowTrackInStation: look for single clusters in chamber(1..): " << ch1+1 << endl;
+    }
+    
+    // add MCS effect for next step
+    AliMUONTrackExtrap::AddMCSEffect(&extrapTrackParamAtCh,AliMUONConstants::ChamberThicknessInX0(),1.);
+    
+    //Extrapolate trackCandidate to chamber "ch1"
+    AliMUONTrackExtrap::ExtrapToZCov(&extrapTrackParamAtCh, 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++;
+      
+      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;
+       }
+       
+       if (AliMUONReconstructor::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;
+       }
+       
+      }
+      
+    }
+    
+  }
+  
+  // fill out the best track if required else clean up the fRecTracksPtr array
+  if (!AliMUONReconstructor::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;
+    }
+    
+  } else if (foundOneCluster || foundTwoClusters) {
+    
+    // remove obsolete track
+    fRecTracksPtr->Remove(&trackCandidate);
+    fNRecTracks--;
+    
+  } else {
+    delete [] clusterCh1Used;
+    return kFALSE;
+  }
+  
+  delete [] clusterCh1Used;
+  return kTRUE;
+  
 }
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::MakeTrackCandidates(void)
+Double_t AliMUONTrackReconstructor::TryTwoClusters(const AliMUONTrackParam &trackParamAtCluster1, AliMUONVCluster* cluster2,
+                                                  AliMUONTrackParam &trackParamAtCluster2)
 {
-  /// 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;
+/// 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);
+  }
+  
+  // 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;
+  }
+  
+  // Compute the Chi2 value
+  TMatrixD tmp2(dPos,TMatrixD::kTransposeMult,error);
+  TMatrixD result(tmp2,TMatrixD::kMult,dPos);
+  
+  return result(0,0);
+  
 }
 
   //__________________________________________________________________________
-Int_t AliMUONTrackReconstructor::MakeTrackCandidatesWithTwoSegments(AliMUONSegment *BegSegment)
+void AliMUONTrackReconstructor::UpdateTrack(AliMUONTrack &track, AliMUONTrackParam &trackParamAtCluster)
 {
-  /// 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);
-      // Set track parameters at vertex from last stations 4 & 5
-      CalcTrackParamAtVertex(recTrack);
-      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;
+  /// 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
+  trackParamAtCluster.SetRemovable(kFALSE);
+  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);
+  track.GetTrackParamAtCluster()->Sort();
+  
 }
 
   //__________________________________________________________________________
-Int_t AliMUONTrackReconstructor::MakeTrackCandidatesWithOneSegmentAndOnePoint(AliMUONSegment *BegSegment)
+void AliMUONTrackReconstructor::UpdateTrack(AliMUONTrack &track, AliMUONTrackParam &trackParamAtCluster1, AliMUONTrackParam &trackParamAtCluster2)
 {
-  /// 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);
-        // Set track parameters at vertex from last stations 4 & 5
-        CalcTrackParamAtVertex(recTrack);
-       // 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;
+  /// 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);
+  track.GetTrackParamAtCluster()->Sort();
+  
 }
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::CalcTrackParamAtVertex(AliMUONTrack *Track) const
+Bool_t AliMUONTrackReconstructor::RecoverTrack(AliMUONTrack &trackCandidate, const AliMUONVClusterStore& clusterStore, Int_t nextStation)
 {
-  /// Set track parameters at vertex.
-  /// TrackHit's are assumed to be only in stations(1..) 4 and 5,
-  /// and sorted according to increasing Z.
-  /// Parameters are calculated from information in HitForRec's
-  /// of first and last TrackHit's.
-  AliMUONTrackParam *trackParamVertex = Track->GetTrackParamAtVertex(); // pointer to track parameters at vertex
-  // Pointer to HitForRec attached to first TrackParamAtHit
-  AliMUONHitForRec *firstHit = ((AliMUONTrackParam*) (Track->GetTrackParamAtHit()->First()))->GetHitForRecPtr();
-  // Pointer to HitForRec attached to last TrackParamAtHit
-  AliMUONHitForRec *lastHit = ((AliMUONTrackParam*) (Track->GetTrackParamAtHit()->Last()))->GetHitForRecPtr();
-  // Z difference between first and last hits
-  Double_t deltaZ = firstHit->GetZ() - lastHit->GetZ();
-  // bending slope in stations(1..) 4 and 5
-  Double_t bendingSlope = (firstHit->GetBendingCoor() - lastHit->GetBendingCoor()) / deltaZ;
-  trackParamVertex->SetBendingSlope(bendingSlope);
-  // impact parameter
-  Double_t impactParam = firstHit->GetBendingCoor() - bendingSlope * firstHit->GetZ();
-  // signed bending momentum
-  trackParamVertex->SetInverseBendingMomentum(1.0 / GetBendingMomentumFromImpactParam(impactParam));
-  // bending slope at vertex
-  trackParamVertex->SetBendingSlope(bendingSlope + impactParam / fSimpleBPosition);
-  // non bending slope
-  trackParamVertex->SetNonBendingSlope((firstHit->GetNonBendingCoor() - lastHit->GetNonBendingCoor()) / deltaZ);
-  // vertex coordinates at (0,0,0)
-  trackParamVertex->SetZ(0.0);
-  trackParamVertex->SetBendingCoor(0.0);
-  trackParamVertex->SetNonBendingCoor(0.0);
+  /// 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 = 0.;
+  
+  // Look for the cluster to remove
+  for (Int_t clusterNumber = 0; clusterNumber < 2; clusterNumber++) {
+    AliMUONTrackParam *trackParamAtCluster = (AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->UncheckedAt(clusterNumber);
+    
+    // check if current cluster is removable
+    if (!trackParamAtCluster->IsRemovable()) return kFALSE;
+    
+    // Pick up cluster with the worst chi2
+    localChi2 = trackParamAtCluster->GetLocalChi2();
+    if (localChi2 > worstLocalChi2) {
+      worstLocalChi2 = localChi2;
+      worstClusterNumber = clusterNumber;
+    }
+  }
+  
+  // Reset best cluster as being NOT removable
+  ((AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->UncheckedAt((worstClusterNumber+1)%2))->SetRemovable(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);
+  
 }
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::FollowTracks(void)
+void AliMUONTrackReconstructor::SetVertexErrXY2ForFit(AliMUONTrack &trackCandidate)
 {
-  /// 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;
-  while (track) {
-    trackIndex++;
-    nextTrack = (AliMUONTrack*) fRecTracksPtr->After(track); // prepare next track
-    AliDebug(2,Form("FollowTracks: track candidate(0..): %d", trackIndex));
-    // Fit track candidate from parameters at vertex
-    // -> with 3 parameters (X_vertex and Y_vertex are fixed)
-    // without multiple Coulomb scattering
-    Fit(track,0,0);
-    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 = (AliMUONTrackParam*) (track->GetTrackParamAtHit()->First());
-      // extrapolation to station
-      AliMUONTrackExtrap::ExtrapToStation(trackParam1, 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"
-       AliMUONTrackExtrap::ExtrapToZ(&(trackParam[0]), segment->GetZ());
-       AliMUONTrackExtrap::ExtrapToZ(&(trackParam[1]), segment->GetZ()); // now same as trackParam[0] !?!?!?!?!?!
-       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
-       AliMUONTrackExtrap::ExtrapToZ(&(trackParam[0]), bestSegment->GetZ());
-       track->AddTrackParamAtHit(&(trackParam[0]),bestSegment->GetHitForRec1());
-       AliMUONTrackExtrap::ExtrapToZ(&(trackParam[1]), bestSegment->GetZ()); // now same as trackParam[0] !?!?!?!?!?!
-       track->AddTrackParamAtHit(&(trackParam[1]),bestSegment->GetHitForRec2());
-       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));
-       
-       // 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
-           AliMUONTrackExtrap::ExtrapToZ(&(trackParam[chInStation]), 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
-         AliMUONTrackExtrap::ExtrapToZ(&(trackParam[chBestHit]), bestHit->GetZ());
-         track->AddTrackParamAtHit(&(trackParam[chBestHit]),bestHit);
-         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, ...
-         fRecTracksPtr->Remove(track);
-         fNRecTracks--;
-         delete extrapSegment;
-         delete extrapHit;
-         break; // stop the search for this candidate:
-         // exit from the loop over station
-       }
-       delete extrapHit;
-      }
-      delete extrapSegment;
-      // Sort TrackParamAtHit according to increasing Z
-      track->GetTrackParamAtHit()->Sort();
-      // Update track parameters at first track hit (smallest Z)
-      trackParam1 = (AliMUONTrackParam*) (track->GetTrackParamAtHit()->First());
-      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)) {
-       fRecTracksPtr->Remove(track);
-       fNRecTracks--;
-       break; // stop the search for this candidate:
-       // exit from the loop over station 
-      }
-      // Track fit from parameters at first hit
-      // -> with 5 parameters (momentum and position)
-      // with multiple Coulomb scattering if all stations
-      if (station == 0) Fit(track,1,1);
-      // without multiple Coulomb scattering if not all stations
-      else Fit(track,1,0);
-      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) {
-       fRecTracksPtr->Remove(track);
-       fNRecTracks--;
-       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 = *((AliMUONTrackParam*) (track->GetTrackParamAtHit()->First()));
-       AliMUONTrackExtrap::ExtrapToVertex(&trackParamVertex, 0., 0., 0.);
-       track->SetTrackParamAtVertex(&trackParamVertex);
-       if (AliLog::GetGlobalDebugLevel() > 0) {
-         cout << "FollowTracks: track candidate(0..): " << trackIndex
-              << " after extrapolation to vertex" << endl;
-         track->RecursiveDump();
-       }
-      }
-    } // for (station = 2;...
-    // go really to next track
-    track = nextTrack;
-  } // while (track)
-  // Compression of track array (necessary after Remove)
-  fRecTracksPtr->Compress();
-  return;
+  /// 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 = AliMUONReconstructor::GetRecoParam()->GetNonBendingVertexDispersion() *
+                             AliMUONReconstructor::GetRecoParam()->GetNonBendingVertexDispersion();
+  Double_t bendingReso2 = AliMUONReconstructor::GetRecoParam()->GetBendingVertexDispersion() *
+                         AliMUONReconstructor::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);
 }
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::Fit(AliMUONTrack *Track, Int_t FitStart, Int_t FitMCS)
+void AliMUONTrackReconstructor::Fit(AliMUONTrack &track, Bool_t includeMCS, Bool_t fitWithVertex, Bool_t calcCov)
 {
-  /// Fit the track "Track",
-  /// with or without multiple Coulomb scattering according to "FitMCS",
-  /// starting, according to "FitStart",
-  /// with track parameters at vertex or at the first TrackHit.
-  
-  if ((FitStart != 0) && (FitStart != 1)) {
-    cout << "ERROR in AliMUONTrackReconstructor::Fit(...)" << endl;
-    cout << "FitStart = " << FitStart << " is neither 0 nor 1" << endl;
-    exit(0);
-  }
-  if ((FitMCS != 0) && (FitMCS != 1)) {
-    cout << "ERROR in AliMUONTrackReconstructor::Fit(...)" << endl;
-    cout << "FitMCS = " << FitMCS << " is neither 0 nor 1" << endl;
-    exit(0);
-  }
+  /// 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".
   
-  Double_t arg[1], benC, errorParam, invBenP, lower, nonBenC, upper, x, y;
-  char parName[50];
+  Double_t benC, errorParam, invBenP, nonBenC, x, y;
   AliMUONTrackParam *trackParam;
-  // Check if Minuit is initialized...
-  fgFitter = TVirtualFitter::Fitter(Track,5);
-  fgFitter->Clear(); // necessary ???? probably yes
-  // how to reset the printout number at every fit ????
-  // is there any risk to leave it like that ????
-  // how to go faster ???? choice of Minuit parameters like EDM ????
-  // choice of function to be minimized according to fFitMCS
-  if (FitMCS == 0) fgFitter->SetFCN(TrackChi2);
-  else fgFitter->SetFCN(TrackChi2MCS);
-  // Switch off printout
-  arg[0] = -1;
-  fgFitter->ExecuteCommand("SET PRINT", arg, 1); // More printing !!!!
+  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
-  fgFitter->ExecuteCommand("SET NOW", arg, 0);
-  // Parameters according to "fFitStart"
-  // (should be a function to be used at every place where needed ????)
-  if (FitStart == 0) trackParam = Track->GetTrackParamAtVertex();
-  else trackParam = (AliMUONTrackParam*) (Track->GetTrackParamAtHit()->First());
-  // set first 3 Minuit parameters
-  // could be tried with no limits for the search (min=max=0) ????
-  fgFitter->SetParameter(0, "InvBenP",
-                        trackParam->GetInverseBendingMomentum(),
-                        0.003, -0.4, 0.4);
-  fgFitter->SetParameter(1, "BenS",
-                        trackParam->GetBendingSlope(),
-                        0.001, -0.5, 0.5);
-  fgFitter->SetParameter(2, "NonBenS",
-                        trackParam->GetNonBendingSlope(),
-                        0.001, -0.5, 0.5);
-  if (FitStart == 1) {
-    // set last 2 Minuit parameters when we start from first track hit
-    // mandatory limits in Bending to avoid NaN values of parameters
-    fgFitter->SetParameter(3, "X",
-                          trackParam->GetNonBendingCoor(),
-                          0.03, -500.0, 500.0);
-    // mandatory limits in non Bending to avoid NaN values of parameters
-    fgFitter->SetParameter(4, "Y",
-                          trackParam->GetBendingCoor(),
-                          0.10, -500.0, 500.0);
+  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);
+    }
   }
-  // search without gradient calculation in the function
-  fgFitter->ExecuteCommand("SET NOGRADIENT", arg, 0);
+  
+  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 !!)
+  trackParam = (AliMUONTrackParam*) (track.GetTrackParamAtCluster()->First());
+  // could be tried with no limits for the search (min=max=0) ????
+  // mandatory limits in non Bending to avoid NaN values of parameters
+  gMinuit->mnparm(0, "X", trackParam->GetNonBendingCoor(), 0.03, -500.0, 500.0, status);
+  gMinuit->mnparm(1, "NonBenS", trackParam->GetNonBendingSlope(), 0.001, -0.5, 0.5, status);
+  // mandatory limits in Bending to avoid NaN values of parameters
+  gMinuit->mnparm(2, "Y", trackParam->GetBendingCoor(), 0.10, -500.0, 500.0, status);
+  gMinuit->mnparm(3, "BenS", trackParam->GetBendingSlope(), 0.001, -0.5, 0.5, status);
+  gMinuit->mnparm(4, "InvBenP", trackParam->GetInverseBendingMomentum(), 0.003, -0.4, 0.4, status);
+  
   // minimization
-  fgFitter->ExecuteCommand("MINIMIZE", arg, 0);
-  // exit from Minuit
-  //  fgFitter->ExecuteCommand("EXIT", arg, 0); // necessary ????
+  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")
-  fgFitter->GetParameter(0, parName, invBenP, errorParam, lower, upper);
-  trackParam->SetInverseBendingMomentum(invBenP);
-  fgFitter->GetParameter(1, parName, benC, errorParam, lower, upper);
-  trackParam->SetBendingSlope(benC);
-  fgFitter->GetParameter(2, parName, nonBenC, errorParam, lower, upper);
+  gMinuit->GetParameter(0, x, errorParam);
+  trackParam->SetNonBendingCoor(x);
+  gMinuit->GetParameter(1, nonBenC, errorParam);
   trackParam->SetNonBendingSlope(nonBenC);
-  if (FitStart == 1) {
-    fgFitter->GetParameter(3, parName, x, errorParam, lower, upper);
-    trackParam->SetNonBendingCoor(x);
-    fgFitter->GetParameter(4, parName, y, errorParam, lower, upper);
-    trackParam->SetBendingCoor(y);
-  }
+  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
-  Double_t fedm, errdef, fitFMin;
-  Int_t npari, nparx;
-  fgFitter->GetStats(fitFMin, fedm, errdef, npari, nparx);
-  Track->SetFitFMin(fitFMin);
+  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 TrackChi2(Int_t &NParam, Double_t * /*Gradient*/, Double_t &Chi2, Double_t *Param, Int_t /*Flag*/)
+void TrackChi2(Int_t & /*nParam*/, Double_t * /*gradient*/, Double_t &chi2, Double_t *param, Int_t /*flag*/)
 {
-  /// Return the "Chi2" to be minimized with Minuit for track fitting,
-  /// with "NParam" parameters
-  /// and their current values in array pointed to by "Param".
-  /// Assumes that the track hits are sorted according to increasing Z.
-  /// Track parameters at each TrackHit are updated accordingly.
-  /// Multiple Coulomb scattering is not taken into account
-  AliMUONTrack *trackBeingFitted;
-  AliMUONTrackParam param1;
-  AliMUONTrackParam* trackParamAtHit;
-  AliMUONHitForRec* hitForRec;
-  Chi2 = 0.0; // initialize Chi2
-  // copy of track parameters to be fitted
-  trackBeingFitted = (AliMUONTrack*) AliMUONTrackReconstructor::Fitter()->GetObjectFit();
-  // 3 parameters means fit track candidate from parameters at vertex (X_vertex and Y_vertex are fixed)
-  if (NParam == 3) param1 = *(trackBeingFitted->GetTrackParamAtVertex());
-  else param1 = *((AliMUONTrackParam*) (trackBeingFitted->GetTrackParamAtHit()->First()));
-  // Minuit parameters to be fitted into this copy
-  param1.SetInverseBendingMomentum(Param[0]);
-  param1.SetBendingSlope(Param[1]);
-  param1.SetNonBendingSlope(Param[2]);
-  if (NParam == 5) {
-    param1.SetNonBendingCoor(Param[3]);
-    param1.SetBendingCoor(Param[4]);
-  }
-  // Follow track through all planes of track hits
-  trackParamAtHit = (AliMUONTrackParam*) (trackBeingFitted->GetTrackParamAtHit()->First());
-  while (trackParamAtHit) {
-    hitForRec = trackParamAtHit->GetHitForRecPtr();
-    // extrapolation to the plane of the hitForRec attached to the current trackParamAtHit
-    AliMUONTrackExtrap::ExtrapToZ(&param1, hitForRec->GetZ());
-    // update track parameters of the current hit
-    trackParamAtHit->SetTrackParam(param1);
-    // Increment Chi2
-    // done hit per hit, with hit resolution,
-    // and not with point and angle like in "reco_muon.F" !!!!
-    // Needs to add multiple scattering contribution ????
-    Double_t dX = hitForRec->GetNonBendingCoor() - param1.GetNonBendingCoor();
-    Double_t dY = hitForRec->GetBendingCoor() - param1.GetBendingCoor();
-    Chi2 = Chi2 + dX * dX / hitForRec->GetNonBendingReso2() + dY * dY / hitForRec->GetBendingReso2();
-    trackParamAtHit = (AliMUONTrackParam*) (trackBeingFitted->GetTrackParamAtHit()->After(trackParamAtHit));
+  /// 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 TrackChi2MCS(Int_t &NParam, Double_t * /*Gradient*/, Double_t &Chi2, Double_t *Param, Int_t /*Flag*/)
+void AliMUONTrackReconstructor::ComplementTracks(const AliMUONVClusterStore& clusterStore)
 {
-  /// Return the "Chi2" to be minimized with Minuit for track fitting,
-  /// with "NParam" parameters
-  /// and their current values in array pointed to by "Param".
-  /// Assumes that the track hits are sorted according to increasing Z.
-  /// Track parameters at each TrackHit are updated accordingly.
-  /// Multiple Coulomb scattering is taken into account with covariance matrix.
-  AliMUONTrack *trackBeingFitted;
-  AliMUONTrackParam param1;
-  AliMUONTrackParam* trackParamAtHit;
-  AliMUONHitForRec* hitForRec;
-  Chi2 = 0.0; // initialize Chi2
-  // copy of track parameters to be fitted
-  trackBeingFitted = (AliMUONTrack*) AliMUONTrackReconstructor::Fitter()->GetObjectFit();
-  // 3 parameters means fit track candidate from parameters at vertex (X_vertex and Y_vertex are fixed)
-  if (NParam == 3) param1 = *(trackBeingFitted->GetTrackParamAtVertex());
-  else param1 = *((AliMUONTrackParam*) (trackBeingFitted->GetTrackParamAtHit()->First()));
-  // Minuit parameters to be fitted into this copy
-  param1.SetInverseBendingMomentum(Param[0]);
-  param1.SetBendingSlope(Param[1]);
-  param1.SetNonBendingSlope(Param[2]);
-  if (NParam == 5) {
-    param1.SetNonBendingCoor(Param[3]);
-    param1.SetBendingCoor(Param[4]);
-  }
-
-  Int_t chCurrent, chPrev = 0, hitNumber, hitNumber1, hitNumber2, hitNumber3;
-  Double_t z1, z2, z3;
-  AliMUONTrackParam *trackParamAtHit1, *trackParamAtHit2, *trackParamAtHit3;
-  AliMUONHitForRec *hitForRec1, *hitForRec2;
-  Double_t hbc1, hbc2, pbc1, pbc2;
-  Double_t hnbc1, hnbc2, pnbc1, pnbc2;
-  Int_t numberOfHit = trackBeingFitted->GetNTrackHits();
-  TMatrixD *covBending = new TMatrixD(numberOfHit, numberOfHit);
-  TMatrixD *covNonBending = new TMatrixD(numberOfHit, numberOfHit);
-  Double_t *msa2 = new Double_t[numberOfHit];
-
-  // Predicted coordinates and  multiple scattering angles are first calculated
-  for (hitNumber = 0; hitNumber < numberOfHit; hitNumber++) {
-    trackParamAtHit = (AliMUONTrackParam*) (trackBeingFitted->GetTrackParamAtHit()->UncheckedAt(hitNumber));
-    hitForRec = trackParamAtHit->GetHitForRecPtr();
-    // extrapolation to the plane of the hitForRec attached to the current trackParamAtHit
-    AliMUONTrackExtrap::ExtrapToZ(&param1, hitForRec->GetZ());
-    // update track parameters of the current hit
-    trackParamAtHit->SetTrackParam(param1);
-    // square of multiple scattering angle at current hit, with one chamber
-    msa2[hitNumber] = MultipleScatteringAngle2(&param1);
-    // correction for eventual missing hits or multiple hits in a chamber,
-    // according to the number of chambers
-    // between the current hit and the previous one
-    chCurrent = hitForRec->GetChamberNumber();
-    if (hitNumber > 0) msa2[hitNumber] = msa2[hitNumber] * (chCurrent - chPrev);
-    chPrev = chCurrent;
-  }
-
-  // Calculates the covariance matrix
-  for (hitNumber1 = 0; hitNumber1 < numberOfHit; hitNumber1++) { 
-    trackParamAtHit1 = (AliMUONTrackParam*) (trackBeingFitted->GetTrackParamAtHit()->UncheckedAt(hitNumber1));
-    hitForRec1 = trackParamAtHit1->GetHitForRecPtr();
-    z1 = hitForRec1->GetZ();
-    for (hitNumber2 = hitNumber1; hitNumber2 < numberOfHit; hitNumber2++) {
-      trackParamAtHit2 = (AliMUONTrackParam*) (trackBeingFitted->GetTrackParamAtHit()->UncheckedAt(hitNumber2));
-      z2 = trackParamAtHit2->GetHitForRecPtr()->GetZ();
-      // initialization to 0 (diagonal plus upper triangular part)
-      (*covBending)(hitNumber2, hitNumber1) = 0.0;
-      // contribution from multiple scattering in bending plane:
-      // loop over upstream hits
-      for (hitNumber3 = 0; hitNumber3 < hitNumber1; hitNumber3++) {    
-        trackParamAtHit3 = (AliMUONTrackParam*) (trackBeingFitted->GetTrackParamAtHit()->UncheckedAt(hitNumber3));
-       z3 = trackParamAtHit3->GetHitForRecPtr()->GetZ();
-       (*covBending)(hitNumber2, hitNumber1) = (*covBending)(hitNumber2, hitNumber1) + ((z1 - z3) * (z2 - z3) * msa2[hitNumber3]); 
-      }
-      // equal contribution from multiple scattering in non bending plane
-      (*covNonBending)(hitNumber2, hitNumber1) = (*covBending)(hitNumber2, hitNumber1);
-      if (hitNumber1 == hitNumber2) {
-       // Diagonal elements: add contribution from position measurements
-       // in bending plane
-       (*covBending)(hitNumber2, hitNumber1) = (*covBending)(hitNumber2, hitNumber1) + hitForRec1->GetBendingReso2();
-       // and in non bending plane
-       (*covNonBending)(hitNumber2, hitNumber1) = (*covNonBending)(hitNumber2, hitNumber1) + hitForRec1->GetNonBendingReso2();
-      } else {
-       // Non diagonal elements: symmetrization
-       // for bending plane
-       (*covBending)(hitNumber1, hitNumber2) = (*covBending)(hitNumber2, hitNumber1);
-       // and non bending plane
-       (*covNonBending)(hitNumber1, hitNumber2) = (*covNonBending)(hitNumber2, hitNumber1);
-      }
-    } // for (hitNumber2 = hitNumber1;...
-  } // for (hitNumber1 = 0;...
+  /// 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 = AliMUONReconstructor::GetRecoParam()->GetSigmaCutForTracking() *
+                       AliMUONReconstructor::GetRecoParam()->GetSigmaCutForTracking();
+  Bool_t foundOneCluster, trackModified;
+  AliMUONVCluster* cluster;
+  AliMUONTrackParam *trackParam, *nextTrackParam, copyOfTrackParam, trackParamAtCluster, bestTrackParamAtCluster;
+  
+  // Remove double track to complete only "good" tracks
+  RemoveDoubleTracks();
+  
+  AliMUONTrack *track = (AliMUONTrack*) fRecTracksPtr->First();
+  while (track) {
+    trackModified = kFALSE;
     
-  // Inversion of covariance matrices
-  // with "mnvertLocal", local "mnvert" function of Minuit.
-  // One cannot use directly "mnvert" since "TVirtualFitter" does not know it.
-  // One will have to replace this local function by the right inversion function
-  // from a specialized Root package for symmetric positive definite matrices,
-  // when available!!!!
-  Int_t ifailBending;
-  mnvertLocal(&((*covBending)(0,0)), numberOfHit, numberOfHit, numberOfHit, ifailBending);
-  Int_t ifailNonBending;
-  mnvertLocal(&((*covNonBending)(0,0)), numberOfHit, numberOfHit, numberOfHit, ifailNonBending);
-
-  // It would be worth trying to calculate the inverse of the covariance matrix
-  // only once per fit, since it cannot change much in principle,
-  // and it would save a lot of computing time !!!!
-  
-  // Calculates Chi2
-  if ((ifailBending == 0) && (ifailNonBending == 0)) {
-    // with Multiple Scattering if inversion correct
-    for (hitNumber1 = 0; hitNumber1 < numberOfHit ; hitNumber1++) { 
-      trackParamAtHit1 = (AliMUONTrackParam*) (trackBeingFitted->GetTrackParamAtHit()->UncheckedAt(hitNumber1));
-      hitForRec1 = trackParamAtHit1->GetHitForRecPtr();
-      hbc1 = hitForRec1->GetBendingCoor();
-      pbc1 = trackParamAtHit1->GetBendingCoor();
-      hnbc1 = hitForRec1->GetNonBendingCoor();
-      pnbc1 = trackParamAtHit1->GetNonBendingCoor();
-      for (hitNumber2 = 0; hitNumber2 < numberOfHit; hitNumber2++) {
-       trackParamAtHit2 = (AliMUONTrackParam*) (trackBeingFitted->GetTrackParamAtHit()->UncheckedAt(hitNumber2));
-        hitForRec2 = trackParamAtHit2->GetHitForRecPtr();
-       hbc2 = hitForRec2->GetBendingCoor();
-       pbc2 = trackParamAtHit2->GetBendingCoor();
-       hnbc2 = hitForRec2->GetNonBendingCoor();
-       pnbc2 = trackParamAtHit2->GetNonBendingCoor();
-       Chi2 += ((*covBending)(hitNumber2, hitNumber1) * (hbc1 - pbc1) * (hbc2 - pbc2)) +
-               ((*covNonBending)(hitNumber2, hitNumber1) * (hnbc1 - pnbc1) * (hnbc2 - pnbc2));
+    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;
+       
+       // 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;
+       }
+       
       }
+      
+      // add new cluster if any
+      if (foundOneCluster) {
+       UpdateTrack(*track,bestTrackParamAtCluster);
+       bestTrackParamAtCluster.SetAloneInChamber(kFALSE);
+       trackParam->SetAloneInChamber(kFALSE);
+       trackModified = kTRUE;
+      }
+      
+      trackParam = nextTrackParam;
     }
-  } else {
-    // without Multiple Scattering if inversion impossible
-    for (hitNumber1 = 0; hitNumber1 < numberOfHit ; hitNumber1++) { 
-      trackParamAtHit1 = (AliMUONTrackParam*) (trackBeingFitted->GetTrackParamAtHit()->UncheckedAt(hitNumber1));
-      hitForRec1 = trackParamAtHit1->GetHitForRecPtr();
-      hbc1 = hitForRec1->GetBendingCoor();
-      pbc1 = trackParamAtHit1->GetBendingCoor();
-      hnbc1 = hitForRec1->GetNonBendingCoor();
-      pnbc1 = trackParamAtHit1->GetNonBendingCoor();
-      Chi2 += ((hbc1 - pbc1) * (hbc1 - pbc1) / hitForRec1->GetBendingReso2()) +
-             ((hnbc1 - pnbc1) * (hnbc1 - pnbc1) / hitForRec1->GetNonBendingReso2());
-    }
+    
+    // re-fit track parameters if needed
+    if (trackModified) Fit(*track, kTRUE, kFALSE, kTRUE);
+    
+    track = (AliMUONTrack*) fRecTracksPtr->After(track);
   }
   
-  delete covBending;
-  delete covNonBending;
-  delete [] msa2;
-}
-
-Double_t MultipleScatteringAngle2(AliMUONTrackParam *param)
-{
-  /// Returns square of multiple Coulomb scattering angle
-  /// from TrackParamAtHit pointed to by "param"
-  Double_t slopeBending, slopeNonBending, radiationLength, inverseBendingMomentum2, inverseTotalMomentum2;
-  Double_t varMultipleScatteringAngle;
-  // Better implementation in AliMUONTrack class ????
-  slopeBending = param->GetBendingSlope();
-  slopeNonBending = param->GetNonBendingSlope();
-  // thickness in radiation length for the current track,
-  // taking local angle into account
-  radiationLength = AliMUONConstants::DefaultChamberThicknessInX0() *
-                   TMath::Sqrt(1.0 + slopeBending*slopeBending + slopeNonBending*slopeNonBending);
-  inverseBendingMomentum2 =  param->GetInverseBendingMomentum() * param->GetInverseBendingMomentum();
-  inverseTotalMomentum2 = inverseBendingMomentum2 * (1.0 + slopeBending * slopeBending) /
-                         (1.0 + slopeBending *slopeBending + slopeNonBending * slopeNonBending); 
-  varMultipleScatteringAngle = 0.0136 * (1.0 + 0.038 * TMath::Log(radiationLength));
-  // The velocity is assumed to be 1 !!!!
-  varMultipleScatteringAngle = inverseTotalMomentum2 * radiationLength * varMultipleScatteringAngle * varMultipleScatteringAngle;
-  return varMultipleScatteringAngle;
-}
-
-//______________________________________________________________________________
- void mnvertLocal(Double_t *a, Int_t l, Int_t, Int_t n, Int_t &ifail)
-{
-///*-*-*-*-*-*-*-*-*-*-*-*Inverts a symmetric matrix*-*-*-*-*-*-*-*-*-*-*-*-*
-///*-*                    ==========================
-///*-*        inverts a symmetric matrix.   matrix is first scaled to
-///*-*        have all ones on the diagonal (equivalent to change of units)
-///*-*        but no pivoting is done since matrix is positive-definite.
-///*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
-
-  // taken from TMinuit package of Root (l>=n)
-  // fVERTs, fVERTq and fVERTpp changed to localVERTs, localVERTq and localVERTpp
-  //  Double_t localVERTs[n], localVERTq[n], localVERTpp[n];
-  Double_t * localVERTs = new Double_t[n];
-  Double_t * localVERTq = new Double_t[n];
-  Double_t * localVERTpp = new Double_t[n];
-  // fMaxint changed to localMaxint
-  Int_t localMaxint = n;
-
-    /* System generated locals */
-    Int_t aOffset;
-
-    /* Local variables */
-    Double_t si;
-    Int_t i, j, k, kp1, km1;
-
-    /* Parameter adjustments */
-    aOffset = l + 1;
-    a -= aOffset;
-
-    /* Function Body */
-    ifail = 0;
-    if (n < 1) goto L100;
-    if (n > localMaxint) goto L100;
-//*-*-                  scale matrix by sqrt of diag elements
-    for (i = 1; i <= n; ++i) {
-        si = a[i + i*l];
-        if (si <= 0) goto L100;
-        localVERTs[i-1] = 1 / TMath::Sqrt(si);
-    }
-    for (i = 1; i <= n; ++i) {
-        for (j = 1; j <= n; ++j) {
-            a[i + j*l] = a[i + j*l]*localVERTs[i-1]*localVERTs[j-1];
-        }
-    }
-//*-*-                                       . . . start main loop . . . .
-    for (i = 1; i <= n; ++i) {
-        k = i;
-//*-*-                  preparation for elimination step1
-        if (a[k + k*l] != 0) localVERTq[k-1] = 1 / a[k + k*l];
-        else goto L100;
-        localVERTpp[k-1] = 1;
-        a[k + k*l] = 0;
-        kp1 = k + 1;
-        km1 = k - 1;
-        if (km1 < 0) goto L100;
-        else if (km1 == 0) goto L50;
-        else               goto L40;
-L40:
-        for (j = 1; j <= km1; ++j) {
-            localVERTpp[j-1] = a[j + k*l];
-            localVERTq[j-1]  = a[j + k*l]*localVERTq[k-1];
-            a[j + k*l]   = 0;
-        }
-L50:
-        if (k - n < 0) goto L51;
-        else if (k - n == 0) goto L60;
-        else                goto L100;
-L51:
-        for (j = kp1; j <= n; ++j) {
-            localVERTpp[j-1] = a[k + j*l];
-            localVERTq[j-1]  = -a[k + j*l]*localVERTq[k-1];
-            a[k + j*l]   = 0;
-        }
-//*-*-                  elimination proper
-L60:
-        for (j = 1; j <= n; ++j) {
-            for (k = j; k <= n; ++k) { a[j + k*l] += localVERTpp[j-1]*localVERTq[k-1]; }
-        }
-    }
-//*-*-                  elements of left diagonal and unscaling
-    for (j = 1; j <= n; ++j) {
-        for (k = 1; k <= j; ++k) {
-            a[k + j*l] = a[k + j*l]*localVERTs[k-1]*localVERTs[j-1];
-            a[j + k*l] = a[k + j*l];
-        }
-    }
-    delete [] localVERTs;
-    delete [] localVERTq;
-    delete [] localVERTpp;
-    return;
-//*-*-                  failure return
-L100:
-    delete [] localVERTs;
-    delete [] localVERTq;
-    delete [] localVERTpp;
-    ifail = 1;
-} /* mnvertLocal */
-
-  //__________________________________________________________________________
-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;
-  Int_t hitsInCommon, nHits1, nHits2;
-  Bool_t removedTrack1;
-  // Loop over first track of the pair
-  track1 = (AliMUONTrack*) fRecTracksPtr->First();
-  while (track1) {
-    removedTrack1 = kFALSE;
-    nHits1 = track1->GetNTrackHits();
-    // Loop over second track of the pair
-    track2 = (AliMUONTrack*) fRecTracksPtr->After(track1);
-    while (track2) {
-      nHits2 = track2->GetNTrackHits();
-      // number of hits in common between two tracks
-      hitsInCommon = track1->HitsInCommon(track2);
-      // check for identical tracks
-      if ((4 * hitsInCommon) >= (nHits1 + nHits2)) {
-        // decide which track to remove
-        if ((nHits1 > nHits2) || ((nHits1 == nHits2) && (track1->GetFitFMin() < track2->GetFitFMin()))) {
-         // remove track2 and continue the second loop with the track next to track2
-         trackToRemove = track2;
-         track2 = (AliMUONTrack*) fRecTracksPtr->After(track2);
-         fRecTracksPtr->Remove(trackToRemove);
-         fNRecTracks--;
-         fRecTracksPtr->Compress(); // this is essential to retrieve the TClonesArray afterwards
-        } else {
-         // else remove track1 and continue the first loop with the track next to track1
-         trackToRemove = track1;
-         track1 = (AliMUONTrack*) fRecTracksPtr->After(track1);
-          fRecTracksPtr->Remove(trackToRemove);
-         fNRecTracks--;
-         fRecTracksPtr->Compress(); // this is essential to retrieve the TClonesArray afterwards
-         removedTrack1 = kTRUE;
-         break;
-        }
-      } else track2 = (AliMUONTrack*) fRecTracksPtr->After(track2);
-    } // track2
-    if (removedTrack1) continue;
-    track1 = (AliMUONTrack*) fRecTracksPtr->After(track1);
-  } // track1
-  return;
 }
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::UpdateHitForRecAtHit()
+void AliMUONTrackReconstructor::ImproveTracks()
 {
-  /// Set cluster parameters after track fitting. Fill fHitForRecAtHit of AliMUONTrack's
-  AliMUONTrack *track;
-  AliMUONTrackParam *trackParamAtHit;
+  /// Improve tracks by removing clusters with local chi2 highter than the defined cut
+  /// Recompute track parameters and covariances at the remaining clusters
+  AliDebug(1,"Enter ImproveTracks");
+  
+  Double_t localChi2, worstLocalChi2;
+  Int_t worstChamber, previousChamber;
+  AliMUONTrack *track, *nextTrack;
+  AliMUONTrackParam *trackParamAtCluster, *worstTrackParamAtCluster, *previousTrackParam, *nextTrackParam;
+  Double_t sigmaCut2 = AliMUONReconstructor::GetRecoParam()->GetSigmaCutForImprovement() *
+                      AliMUONReconstructor::GetRecoParam()->GetSigmaCutForImprovement();
+  
+  // Remove double track to improve only "good" tracks
+  RemoveDoubleTracks();
+  
   track = (AliMUONTrack*) fRecTracksPtr->First();
   while (track) {
-    trackParamAtHit = (AliMUONTrackParam*) (track->GetTrackParamAtHit()->First());
-    while (trackParamAtHit) {
-      track->AddHitForRecAtHit(trackParamAtHit->GetHitForRecPtr());
-      trackParamAtHit = (AliMUONTrackParam*) (track->GetTrackParamAtHit()->After(trackParamAtHit)); 
+    
+    // prepare next track in case the actual track is suppressed
+    nextTrack = (AliMUONTrack*) fRecTracksPtr->After(track);
+    
+    while (!track->IsImproved()) {
+      
+      // 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);
+      }
+      
+      // Check if bad cluster found
+      if (!worstTrackParamAtCluster) {
+        track->SetImproved(kTRUE);
+        break;
+      }
+      
+      // 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 the worst cluster is not removable then remove the entire track
+      if (!worstTrackParamAtCluster->IsRemovable() && worstTrackParamAtCluster->IsAloneInChamber()) {
+       fRecTracksPtr->Remove(track);
+       fNRecTracks--;
+        break;
+      }
+      
+      // Reset the second cluster in the same station as being not removable
+      // or reset the second cluster in the same chamber as being alone
+      worstChamber = worstTrackParamAtCluster->GetClusterPtr()->GetChamberId();
+      previousTrackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->Before(worstTrackParamAtCluster);
+      nextTrackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->After(worstTrackParamAtCluster);
+      if (worstTrackParamAtCluster->IsAloneInChamber()) { // Worst cluster removable and alone in chamber
+       
+       if (worstChamber%2 == 0) { // Modify flags in next chamber
+         
+         nextTrackParam->SetRemovable(kFALSE);
+         if (!nextTrackParam->IsAloneInChamber()) // Make sure both clusters in second chamber are not removable anymore
+           ((AliMUONTrackParam*) track->GetTrackParamAtCluster()->After(nextTrackParam))->SetRemovable(kFALSE);
+         
+       } else { // Modify flags in previous chamber
+         
+         previousTrackParam->SetRemovable(kFALSE);
+         if (!previousTrackParam->IsAloneInChamber()) // Make sure both clusters in second chamber are not removable anymore
+           ((AliMUONTrackParam*) track->GetTrackParamAtCluster()->Before(previousTrackParam))->SetRemovable(kFALSE);
+         
+       }
+       
+      } else { // Worst cluster not alone in its chamber
+        
+       if (previousTrackParam) previousChamber = previousTrackParam->GetClusterPtr()->GetChamberId();
+       else previousChamber = -1;
+       
+       if (previousChamber == worstChamber) { // the second cluster on the same chamber is the previous one
+         
+         previousTrackParam->SetAloneInChamber(kTRUE);
+         // transfert the removability to the second cluster
+         if (worstTrackParamAtCluster->IsRemovable()) previousTrackParam->SetRemovable(kTRUE);
+         
+       } else { // the second cluster on the same chamber is the next one
+         
+         nextTrackParam->SetAloneInChamber(kTRUE);
+         // transfert the removability to the second cluster
+         if (worstTrackParamAtCluster->IsRemovable()) nextTrackParam->SetRemovable(kTRUE);
+         
+       }
+       
+      }
+      
+      // 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;
+      }
+      
     }
-    track = (AliMUONTrack*) fRecTracksPtr->After(track);
+    
+    track = nextTrack;
   }
-  return;
+  
+  // compress the array in case of some tracks have been removed
+  fRecTracksPtr->Compress();
+  
 }
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::EventDump(void)
+void AliMUONTrackReconstructor::Finalize()
 {
-  /// Dump reconstructed event (track parameters at vertex and at first hit),
-  /// and the particle parameters
+  /// Recompute track parameters and covariances at each attached cluster from those at the first one
+  
   AliMUONTrack *track;
-  AliMUONTrackParam *trackParam, *trackParam1;
-  Double_t bendingSlope, nonBendingSlope, pYZ;
-  Double_t pX, pY, pZ, x, y, z, c;
-  Int_t 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++) {
-    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 = (AliMUONTrackParam*) track->GetTrackParamAtHit()->First();
-    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));
+  
+  track = (AliMUONTrack*) fRecTracksPtr->First();
+  while (track) {
+    
+    // update track parameters if not already done
+    if (!track->IsImproved()) track->UpdateCovTrackParamAtCluster();
+    
+    track = (AliMUONTrack*) fRecTracksPtr->After(track);
+    
   }
-  // informations about generated particles NO !!!!!!!!
-  
-//    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;
+  
 }
 
-