]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - MUON/AliMUONTrackReconstructor.cxx
- Adding *.C *.txt *.sh to FILE_PATTERNS
[u/mrichter/AliRoot.git] / MUON / AliMUONTrackReconstructor.cxx
index b933308a831afca8297d5271eab167f7fe46432b..d888016ce8b8114e9814089e2b54bd955c854c6c 100644 (file)
 ///
 
 #include "AliMUONTrackReconstructor.h"
-#include "AliMUONData.h"
+
 #include "AliMUONConstants.h"
-#include "AliMUONRawCluster.h"
 #include "AliMUONHitForRec.h"
-#include "AliMUONObjectPair.h"
 #include "AliMUONTrack.h"
 #include "AliMUONTrackParam.h"
 #include "AliMUONTrackExtrap.h"
-
 #include "AliLog.h"
 
 #include <TMinuit.h>
 #include <Riostream.h>
+#include <TMath.h>
 #include <TMatrixD.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);
-
-Double_t MultipleScatteringAngle2(AliMUONTrackParam *param);
+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::fgkMaxNormChi2 = 100.0;
-const Bool_t AliMUONTrackReconstructor::fgkTrackAllTracks = kFALSE;
-
-//__________________________________________________________________________
-AliMUONTrackReconstructor::AliMUONTrackReconstructor(AliMUONData* data)
-  : AliMUONVTrackReconstructor(data)
-{
-  /// Constructor for class AliMUONTrackReconstructor
-  
-  // Memory allocation for the TClonesArray of reconstructed tracks
-  fRecTracksPtr = new TClonesArray("AliMUONTrack", 10);
-}
+//************* Parameters for reconstruction
+const Double_t AliMUONTrackReconstructor::fgkBendingVertexDispersion = 10.;
+const Double_t AliMUONTrackReconstructor::fgkNonBendingVertexDispersion = 10.;
 
-  //__________________________________________________________________________
-AliMUONTrackReconstructor::~AliMUONTrackReconstructor(void)
-{
-  /// Destructor for class AliMUONTrackReconstructor
-  delete fRecTracksPtr;
-}
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::AddHitsForRecFromRawClusters()
+AliMUONTrackReconstructor::AliMUONTrackReconstructor()
+  : AliMUONVTrackReconstructor()
 {
-  /// To add to the list of hits for reconstruction all the raw clusters
-  TTree *treeR;
-  AliMUONHitForRec *hitForRec;
-  AliMUONRawCluster *clus;
-  Int_t iclus, nclus;
-  TClonesArray *rawclusters;
-  AliDebug(1,"Enter AddHitsForRecFromRawClusters");
-  
-  treeR = fMUONData->TreeR();
-  if (!treeR) {
-    AliError("TreeR must be loaded");
-    exit(0);
-  }
-  
-  fMUONData->SetTreeAddress("RC");
-  fMUONData->GetRawClusters(); // only one entry  
-  
-  // Loop over tracking chambers
-  for (Int_t ch = 0; ch < AliMUONConstants::NTrackingCh(); ch++) {
-    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++;
-      // 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));
-      if (AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 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();
-      }
-    }
-  }
-  
-  return;
+  /// Constructor for class AliMUONTrackReconstructor
+  AliInfo("*** Original tracking ***");
 }
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::MakeTracks(void)
+AliMUONTrackReconstructor::~AliMUONTrackReconstructor()
 {
-  /// 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();
-  // Fill out the AliMUONTrack's
-  FillMUONTrack();
-}
+/// Destructor
+} 
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::MakeTrackCandidates(void)
+void AliMUONTrackReconstructor::MakeTrackCandidates()
 {
-  /// To make track candidates:
+  /// 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 hitForRec's.
   /// Keep only best candidates or all of them according to the flag fgkTrackAllTracks.
   TClonesArray *segments;
-  AliMUONObjectPair *segment;
-  AliMUONHitForRec *hitForRec1, *hitForRec2;
   AliMUONTrack *track;
-  AliMUONTrackParam *trackParamAtFirstHit;
   Int_t iCandidate = 0;
+  Bool_t hitFound;
 
   AliDebug(1,"Enter MakeTrackCandidates");
 
   // 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(istat);
+    
     // Loop over segments
-    for (Int_t iseg=0; iseg<segments->GetEntriesFast(); iseg++) {
+    for (Int_t iseg=0; iseg<segments->GetEntriesFast(); iseg++) 
+    {
       AliDebug(1,Form("Making primary candidate(1..) %d",++iCandidate));
+      
       // Transform segments to tracks and put them at the end of fRecTracksPtr
-      segment = (AliMUONObjectPair*) ((*segments)[iseg]);
-      hitForRec1 = (AliMUONHitForRec*) segment->First();
-      hitForRec2 = (AliMUONHitForRec*) segment->Second();
-      track = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(hitForRec1, hitForRec2);
+      track = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack((AliMUONObjectPair*)((*segments)[iseg]));
       fNRecTracks++;
-      // Add MCS effects in parameter covariances
-      trackParamAtFirstHit = (AliMUONTrackParam*) (track->GetTrackParamAtHit()->First());
-      AliMUONTrackExtrap::AddMCSEffect(trackParamAtFirstHit,AliMUONConstants::ChamberThicknessInX0(),1.);
+      
       // Printout for debuging
-      if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
+      if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2))
+      {
         cout<<endl<<"Track parameter covariances at first hit with multiple Coulomb scattering effects:"<<endl;
-        trackParamAtFirstHit->GetCovariances()->Print();
+        ((AliMUONTrackParam*) track->GetTrackParamAtHit()->First())->GetCovariances().Print();
       }
+      
       // Look for compatible hitForRec(s) in the other station
-      FollowTrackInStation(track,7-istat);
+      if (fgkMakeTrackCandidatesFast) hitFound = FollowLinearTrackInStation(*track,7-istat);
+      else hitFound = FollowTrackInStation(*track,7-istat);
+      
+      // Remove track if no hit found
+      if (!hitFound) {
+        fRecTracksPtr->Remove(track);
+       fNRecTracks--;
+      }
+      
     }
+    
     // delete the array of segments
     delete segments;
   }
+  
   fRecTracksPtr->Compress(); // this is essential before checking tracks
   
   // Keep all different tracks or only the best ones as required
@@ -209,155 +128,70 @@ void AliMUONTrackReconstructor::MakeTrackCandidates(void)
 }
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::RemoveIdenticalTracks(void)
-{
-  /// To remove identical tracks:
-  /// Tracks are considered identical if they have all their hits in common.
-  /// One keeps the track with the larger number of hits if need be
-  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 ((hitsInCommon == nHits1) || (hitsInCommon == nHits2)) {
-        // decide which track to remove
-        if (nHits2 > nHits1) {
-         // remove track1 and continue the first loop with the track next to track1
-         trackToRemove = track1;
-         track1 = (AliMUONTrack*) fRecTracksPtr->After(track1);
-          fRecTracksPtr->Remove(trackToRemove);
-         fRecTracksPtr->Compress(); // this is essential to retrieve the TClonesArray afterwards
-         fNRecTracks--;
-         removedTrack1 = kTRUE;
-         break;
-       } else {
-         // remove track2 and continue the second loop with the track next to track2
-         trackToRemove = track2;
-         track2 = (AliMUONTrack*) fRecTracksPtr->After(track2);
-         fRecTracksPtr->Remove(trackToRemove);
-         fRecTracksPtr->Compress(); // this is essential to retrieve the TClonesArray afterwards
-         fNRecTracks--;
-        }
-      } else track2 = (AliMUONTrack*) fRecTracksPtr->After(track2);
-    } // track2
-    if (removedTrack1) continue;
-    track1 = (AliMUONTrack*) fRecTracksPtr->After(track1);
-  } // track1
-  return;
-}
-
-  //__________________________________________________________________________
-void AliMUONTrackReconstructor::RemoveDoubleTracks(void)
-{
-  /// To remove double tracks:
-  /// Tracks are considered identical if more than half of the hits of the track
-  /// which has the smaller number of hits are in common with the other track.
-  /// 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 (((nHits1 < nHits2) && (2 * hitsInCommon > nHits1)) || (2 * hitsInCommon > 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);
-         fRecTracksPtr->Compress(); // this is essential to retrieve the TClonesArray afterwards
-         fNRecTracks--;
-        } 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);
-         fRecTracksPtr->Compress(); // this is essential to retrieve the TClonesArray afterwards
-         fNRecTracks--;
-         removedTrack1 = kTRUE;
-         break;
-        }
-      } else track2 = (AliMUONTrack*) fRecTracksPtr->After(track2);
-    } // track2
-    if (removedTrack1) continue;
-    track1 = (AliMUONTrack*) fRecTracksPtr->After(track1);
-  } // track1
-  return;
-}
-
-  //__________________________________________________________________________
-void AliMUONTrackReconstructor::FollowTracks(void)
+void AliMUONTrackReconstructor::FollowTracks()
 {
   /// Follow tracks in stations(1..) 3, 2 and 1
   AliDebug(1,"Enter FollowTracks");
   
   AliMUONTrack *track, *nextTrack;
-  AliMUONTrackParam *trackParamAtFirstHit;
-  Double_t numberOfDegFree, chi2Norm;
   Int_t currentNRecTracks;
+  Bool_t hitFound;
   
   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) {
-        SetVertexForFit(track);
+        SetVertexForFit(*track);
         track->SetFitWithVertex(kTRUE);
       } else track->SetFitWithVertex(kFALSE);
-      Fit(track,kFALSE, kTRUE);
+      Fit(*track, kFALSE, kTRUE);
+      
       // Remove the track if the normalized chi2 is too high
-      numberOfDegFree = (2. * track->GetNTrackHits() - 5.);
-      if (numberOfDegFree > 0) chi2Norm = track->GetFitFMin() / numberOfDegFree;
-      else chi2Norm = 1.e10;
-      if (chi2Norm > fgkMaxNormChi2) {
+      if (track->GetNormalizedChi2() > fgkSigmaToCutForTracking * fgkSigmaToCutForTracking) {
        fRecTracksPtr->Remove(track);
        fNRecTracks--;
        continue;
       }
-      // Add MCS effects in parameter covariances
-      trackParamAtFirstHit = (AliMUONTrackParam*) (track->GetTrackParamAtHit()->First());
-      AliMUONTrackExtrap::AddMCSEffect(trackParamAtFirstHit,AliMUONConstants::ChamberThicknessInX0(),1.);
+      
       // Printout for debuging
       if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
         cout<<endl<<"Track parameter covariances at first hit with multiple Coulomb scattering effects:"<<endl;
-        trackParamAtFirstHit->GetCovariances()->Print();
+        ((AliMUONTrackParam*) track->GetTrackParamAtHit()->First())->GetCovariances().Print();
       }
+      
       // Look for compatible hitForRec in station(0..) "station"
-      FollowTrackInStation(track,station);
+      hitFound = FollowTrackInStation(*track,station);
+      
+      // Try to recover track if required
+      if (!hitFound && fgkRecoverTracks) hitFound = RecoverTrack(*track,station);
+      
+      // remove track if no hit found
+      if (!hitFound) {
+       fRecTracksPtr->Remove(track);
+       fNRecTracks--;
+      }
+      
     }
+    
     // Compress fRecTracksPtr for the next step
     fRecTracksPtr->Compress();
+    
     // Keep only the best tracks if required
     if (!fgkTrackAllTracks) RemoveDoubleTracks();
+    
   }
   
   // Last fit of track candidates with all station
@@ -365,31 +199,35 @@ void AliMUONTrackReconstructor::FollowTracks(void)
   Int_t trackIndex = -1;
   track = (AliMUONTrack*) fRecTracksPtr->First();
   while (track) {
+    
     trackIndex++;
     nextTrack = (AliMUONTrack*) fRecTracksPtr->After(track); // prepare next track
+    
     track->SetFitWithVertex(kFALSE); // just to be sure
-    Fit(track,kTRUE, kFALSE);
+    Fit(*track, kTRUE, 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
-    numberOfDegFree = (2.0 * track->GetNTrackHits() - 5);
-    if (numberOfDegFree > 0) chi2Norm = track->GetFitFMin() / numberOfDegFree;
-    else chi2Norm = 1.e10;
-    if (chi2Norm > fgkMaxNormChi2) {
+    if (track->GetNormalizedChi2() > fgkSigmaToCutForTracking * fgkSigmaToCutForTracking) {
       fRecTracksPtr->Remove(track);
       fNRecTracks--;
     }
+    
     track = nextTrack;
+    
   }
+  
   fRecTracksPtr->Compress();
   
 }
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::FollowTrackInStation(AliMUONTrack* trackCandidate, Int_t nextStation)
+Bool_t AliMUONTrackReconstructor::FollowTrackInStation(AliMUONTrack &trackCandidate, Int_t nextStation)
 {
   /// Follow trackCandidate in station(0..) nextStation and search for compatible HitForRec(s)
   /// Keep all possibilities or only the best one(s) according to the flag fgkTrackAllTracks:
@@ -399,203 +237,481 @@ void AliMUONTrackReconstructor::FollowTrackInStation(AliMUONTrack* trackCandidat
   /// kFALSE: add only the best hit(s) to the "trackCandidate". Try to add a couple of hits in priority.
   AliDebug(1,Form("Enter FollowTrackInStation(1..) %d", nextStation+1));
   
-  Int_t ch1 = 2*nextStation;
-  Int_t ch2 = 2*nextStation+1;
-  Double_t zCh2 = AliMUONConstants::DefaultChamberZ(ch2);
+  // 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 chi2WithOneHitForRec = 1.e10;
   Double_t chi2WithTwoHitForRec = 1.e10;
-  Double_t maxChi2WithOneHitForRec = 2.*fgkMaxNormChi2; // 2 because 2 quantities in chi2
-  Double_t maxChi2WithTwoHitForRec = 4.*fgkMaxNormChi2; // 4 because 4 quantities in chi2
+  Double_t maxChi2WithOneHitForRec = 2. * fgkSigmaToCutForTracking * fgkSigmaToCutForTracking; // 2 because 2 quantities in chi2
+  Double_t maxChi2WithTwoHitForRec = 4. * fgkSigmaToCutForTracking * fgkSigmaToCutForTracking; // 4 because 4 quantities in chi2
   Double_t bestChi2WithOneHitForRec = maxChi2WithOneHitForRec;
   Double_t bestChi2WithTwoHitForRec = maxChi2WithTwoHitForRec;
+  Bool_t foundOneHit = kFALSE;
+  Bool_t foundTwoHits = kFALSE;
   AliMUONTrack *newTrack = 0x0;
   AliMUONHitForRec *hitForRecCh1, *hitForRecCh2;
-  AliMUONHitForRec *bestHitForRec1 = 0x0, *bestHitForRec2 = 0x0;
+  AliMUONTrackParam extrapTrackParam;
+  AliMUONTrackParam extrapTrackParamAtHit1;
+  AliMUONTrackParam extrapTrackParamAtHit2;
+  AliMUONTrackParam bestTrackParamAtHit1;
+  AliMUONTrackParam bestTrackParamAtHit2;
   Bool_t *hitForRecCh1Used = new Bool_t[fNHitsForRecPerChamber[ch1]];
   for (Int_t hit1 = 0; hit1 < fNHitsForRecPerChamber[ch1]; hit1++) hitForRecCh1Used[hit1] = kFALSE;
-  //
-  //Extrapolate trackCandidate to chamber "ch2" to save computing time in the next steps
-  AliMUONTrackParam *extrapTrackParamPtr = trackCandidate->GetExtrapTrackParam();
-  *extrapTrackParamPtr = *((AliMUONTrackParam*)(trackCandidate->GetTrackParamAtHit()->First()));
-  AliMUONTrackExtrap::ExtrapToZCov(extrapTrackParamPtr, zCh2);
-  AliMUONTrackParam extrapTrackParamSave(*extrapTrackParamPtr);
-  //
+  
+  // Get track parameters
+  AliMUONTrackParam extrapTrackParamAtCh(*(AliMUONTrackParam*)trackCandidate.GetTrackParamAtHit()->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.GetHitForRecPtr()->GetChamberNumber() > 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)) {
-    TMatrixD* paramCovForDebug = extrapTrackParamPtr->GetCovariances();
-    cout<<endl<<"Track parameter covariances at first hit extrapolated to z = "<<zCh2<<":"<<endl;
-    paramCovForDebug->Print();
+    cout<<endl<<"Track parameter covariances at first hit extrapolated to z = "<<AliMUONConstants::DefaultChamberZ(ch2)<<":"<<endl;
+    extrapTrackParamAtCh.GetCovariances().Print();
   }
-  //
-  // look for candidates in chamber 2 
+  
   // Printout for debuging
   if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
     cout << "FollowTrackInStation: look for hits in chamber(1..): " << ch2+1 << endl;
   }
+  
+  // look for candidates in chamber 2 
   for (Int_t hit2 = 0; hit2 < fNHitsForRecPerChamber[ch2]; hit2++) {
+    
     hitForRecCh2 = (AliMUONHitForRec*) fHitsForRecPtr->UncheckedAt(fIndexOfFirstHitForRecPerChamber[ch2]+hit2);
-    // extrapolate track parameters and covariances only once for this hit
-    AliMUONTrackExtrap::ExtrapToZCov(extrapTrackParamPtr, hitForRecCh2->GetZ());
-    chi2WithOneHitForRec = trackCandidate->TryOneHitForRec(hitForRecCh2);
+    
+    // try to add the current hit fast
+    if (!TryOneHitForRecFast(extrapTrackParamAtCh, hitForRecCh2)) continue;
+    
+    // try to add the current hit accuratly
+    chi2WithOneHitForRec = TryOneHitForRec(extrapTrackParamAtCh, hitForRecCh2, extrapTrackParamAtHit2);
+    
     // if good chi2 then try to attach a hitForRec in the other chamber too
     if (chi2WithOneHitForRec < maxChi2WithOneHitForRec) {
+      Bool_t foundSecondHit = kFALSE;
+      
       // Printout for debuging
       if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
-        cout << "FollowTrackInStation: look for second hits in chamber(1..): " << ch1+1 << endl;
+        cout << "FollowTrackInStation: found one hit in chamber(1..): " << ch2+1
+            << " (Chi2 = " << chi2WithOneHitForRec << ")" << endl;
+        cout << "                      look for second hits in chamber(1..): " << ch1+1 << " ..." << endl;
       }
-      Bool_t foundSecondHit = kFALSE;
+      
+      // add MCS effect for next step
+      AliMUONTrackExtrap::AddMCSEffect(&extrapTrackParamAtHit2,AliMUONConstants::ChamberThicknessInX0(),1.);
+      
+      // copy new track parameters for next step
+      extrapTrackParam = extrapTrackParamAtHit2;
+      
+      //Extrapolate track parameters to chamber "ch1"
+      AliMUONTrackExtrap::ExtrapToZ(&extrapTrackParam, AliMUONConstants::DefaultChamberZ(ch1));
+      
       for (Int_t hit1 = 0; hit1 < fNHitsForRecPerChamber[ch1]; hit1++) {
-        hitForRecCh1 = (AliMUONHitForRec*) fHitsForRecPtr->UncheckedAt(fIndexOfFirstHitForRecPerChamber[ch1]+hit1);
-       chi2WithTwoHitForRec = trackCandidate->TryTwoHitForRec(hitForRecCh2, hitForRecCh1); // order hits like that to save computing time
-        // if good chi2 then create a new track by adding the 2 hitForRec to the "trackCandidate"
+        
+       hitForRecCh1 = (AliMUONHitForRec*) fHitsForRecPtr->UncheckedAt(fIndexOfFirstHitForRecPerChamber[ch1]+hit1);
+       
+       // try to add the current hit fast
+       if (!TryOneHitForRecFast(extrapTrackParam, hitForRecCh1)) continue;
+       
+       // try to add the current hit accuratly
+       chi2WithTwoHitForRec = TryTwoHitForRec(extrapTrackParamAtHit2, hitForRecCh1, extrapTrackParamAtHit1);
+        
+       // if good chi2 then create a new track by adding the 2 hitForRec to the "trackCandidate"
        if (chi2WithTwoHitForRec < maxChi2WithTwoHitForRec) {
          foundSecondHit = kTRUE;
-          if (fgkTrackAllTracks) {
+          foundTwoHits = kTRUE;
+          
+         // Printout for debuging
+         if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+           cout << "FollowTrackInStation: found second hit in chamber(1..): " << ch1+1
+                << " (Global Chi2 = " << chi2WithTwoHitForRec << ")" << endl;
+         }
+         
+         if (fgkTrackAllTracks) {
            // copy trackCandidate into a new track put at the end of fRecTracksPtr and add the new hitForRec's
-            newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(*trackCandidate);
+            newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(trackCandidate);
+           UpdateTrack(*newTrack,extrapTrackParamAtHit1,extrapTrackParamAtHit2);
            fNRecTracks++;
-            AliMUONTrackParam trackParam1(extrapTrackParamSave);
-            AliMUONTrackExtrap::ExtrapToZ(&trackParam1, hitForRecCh1->GetZ());
-           newTrack->AddTrackParamAtHit(&trackParam1,hitForRecCh1);
-            AliMUONTrackParam trackParam2(extrapTrackParamSave);
-            AliMUONTrackExtrap::ExtrapToZ(&trackParam2, hitForRecCh2->GetZ());
-           newTrack->AddTrackParamAtHit(&trackParam2,hitForRecCh2);
-            // Sort TrackParamAtHit according to increasing Z
-            newTrack->GetTrackParamAtHit()->Sort();
-           // Update the chi2 of the new track
-           if (newTrack->GetFitFMin()<0) newTrack->SetFitFMin(chi2WithTwoHitForRec);
-           else newTrack->SetFitFMin(newTrack->GetFitFMin() + chi2WithTwoHitForRec);
+           
            // Tag hitForRecCh1 as used
            hitForRecCh1Used[hit1] = kTRUE;
+           
            // Printout for debuging
            if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
-             cout << "FollowTrackInStation: added two hits in station(1..): " << nextStation+1
-                  << " (Chi2 = " << chi2WithTwoHitForRec << ")" << endl;
+             cout << "FollowTrackInStation: added two hits in station(1..): " << nextStation+1 << endl;
              if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
            }
+           
           } else if (chi2WithTwoHitForRec < bestChi2WithTwoHitForRec) {
            // keep track of the best couple of hits
            bestChi2WithTwoHitForRec = chi2WithTwoHitForRec;
-           bestHitForRec1 = hitForRecCh1;
-           bestHitForRec2 = hitForRecCh2;
+           bestTrackParamAtHit1 = extrapTrackParamAtHit1;
+           bestTrackParamAtHit2 = extrapTrackParamAtHit2;
           }
+         
        }
+       
       }
+      
       // if no hitForRecCh1 found then consider to add hitForRecCh2 only
       if (!foundSecondHit) {
-        if (fgkTrackAllTracks) {
+        foundOneHit = kTRUE;
+        
+       if (fgkTrackAllTracks) {
          // copy trackCandidate into a new track put at the end of fRecTracksPtr and add the new hitForRec's
-          newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(*trackCandidate);
+          newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(trackCandidate);
+         UpdateTrack(*newTrack,extrapTrackParamAtHit2);
          fNRecTracks++;
-          AliMUONTrackParam trackParam1(extrapTrackParamSave);
-          AliMUONTrackExtrap::ExtrapToZ(&trackParam1, hitForRecCh2->GetZ());
-          newTrack->AddTrackParamAtHit(&trackParam1,hitForRecCh2);
-          // Sort TrackParamAtHit according to increasing Z
-          newTrack->GetTrackParamAtHit()->Sort();
-         // Update the chi2 of the new track
-         if (newTrack->GetFitFMin()<0) newTrack->SetFitFMin(chi2WithOneHitForRec);
-         else newTrack->SetFitFMin(newTrack->GetFitFMin() + chi2WithOneHitForRec);
+         
          // Printout for debuging
          if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
-           cout << "FollowTrackInStation: added one hit in chamber(1..): " << ch2+1
-                << " (Chi2 = " << chi2WithOneHitForRec << ")" << endl;
+           cout << "FollowTrackInStation: added one hit in chamber(1..): " << ch2+1 << endl;
            if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
          }
-       } if (!bestHitForRec2 && chi2WithOneHitForRec < bestChi2WithOneHitForRec) {
-         // keep track of the best single hitForRec except if a couple
-          // of hits has already been found (i.e. bestHitForRec2!=0x0)
+         
+       } else if (!foundTwoHits && chi2WithOneHitForRec < bestChi2WithOneHitForRec) {
+         // keep track of the best single hitForRec except if a couple of hits has already been found
          bestChi2WithOneHitForRec = chi2WithOneHitForRec;
-         bestHitForRec1 = hitForRecCh2;
+         bestTrackParamAtHit1 = extrapTrackParamAtHit2;
         }
+       
       }
+      
     }
-    // reset the extrapolated track parameter for next step
-    trackCandidate->SetExtrapTrackParam(&extrapTrackParamSave);
+    
   }
-  //
+  
   // 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 hitForRec has been found
-  if (fgkTrackAllTracks || !bestHitForRec2) {
+  if (fgkTrackAllTracks || !foundTwoHits) {
+    
+    // Printout for debuging
     if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
       cout << "FollowTrackInStation: look for single hits 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));
+    
     for (Int_t hit1 = 0; hit1 < fNHitsForRecPerChamber[ch1]; hit1++) {
+      
       hitForRecCh1 = (AliMUONHitForRec*) fHitsForRecPtr->UncheckedAt(fIndexOfFirstHitForRecPerChamber[ch1]+hit1);
+      
       if (hitForRecCh1Used[hit1]) continue; // Skip hitForRec already used
-      chi2WithOneHitForRec = trackCandidate->TryOneHitForRec(hitForRecCh1);
-      // if good chi2 then create a new track by adding the good hitForRec in "ch1" to the "trackCandidate"
+      
+      // try to add the current hit fast
+      if (!TryOneHitForRecFast(extrapTrackParamAtCh, hitForRecCh1)) continue;
+      
+      // try to add the current hit accuratly
+      chi2WithOneHitForRec = TryOneHitForRec(extrapTrackParamAtCh, hitForRecCh1, extrapTrackParamAtHit1);
+    
+      // if good chi2 then consider to add hitForRecCh1
       // We do not try to attach a hitForRec in the other chamber too since it has already been done above
       if (chi2WithOneHitForRec < maxChi2WithOneHitForRec) {
+        foundOneHit = kTRUE;
+         
+       // Printout for debuging
+       if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+         cout << "FollowTrackInStation: found one hit in chamber(1..): " << ch1+1
+              << " (Chi2 = " << chi2WithOneHitForRec << ")" << endl;
+       }
+       
        if (fgkTrackAllTracks) {
          // copy trackCandidate into a new track put at the end of fRecTracksPtr and add the new hitForRec's
-         newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(*trackCandidate);
+         newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(trackCandidate);
+         UpdateTrack(*newTrack,extrapTrackParamAtHit1);
          fNRecTracks++;
-         AliMUONTrackParam trackParam1(extrapTrackParamSave);
-         AliMUONTrackExtrap::ExtrapToZ(&trackParam1, hitForRecCh1->GetZ());
-         newTrack->AddTrackParamAtHit(&trackParam1,hitForRecCh1);
-         // Sort TrackParamAtHit according to increasing Z
-         newTrack->GetTrackParamAtHit()->Sort();
-         // Update the chi2 of the new track
-         if (newTrack->GetFitFMin()<0) newTrack->SetFitFMin(chi2WithOneHitForRec);
-         else newTrack->SetFitFMin(newTrack->GetFitFMin() + chi2WithOneHitForRec);
-         // Printout for debuging
+         
+         // Printout for debuging
          if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
-           cout << "FollowTrackInStation: added one hit in chamber(1..): " << ch1+1
-                << " (Chi2 = " << chi2WithOneHitForRec << ")" << endl;
+           cout << "FollowTrackInStation: added one hit in chamber(1..): " << ch1+1 << endl;
            if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
          }
-       } if (!bestHitForRec2 && chi2WithOneHitForRec < bestChi2WithOneHitForRec) {
-         // keep track of the best single hitForRec except if a couple
-         // of hits has already been found (i.e. bestHitForRec1!=0x0)
+         
+       } else if (chi2WithOneHitForRec < bestChi2WithOneHitForRec) {
+         // keep track of the best single hitForRec except if a couple of hits has already been found
          bestChi2WithOneHitForRec = chi2WithOneHitForRec;
-         bestHitForRec1 = hitForRecCh1;
+         bestTrackParamAtHit1 = extrapTrackParamAtHit1;
        }
+       
       }
+      
     }
+    
   }
-  //
+  
   // fill out the best track if required else clean up the fRecTracksPtr array
-  if (!fgkTrackAllTracks && bestHitForRec1) {
-    AliMUONTrackParam trackParam1(extrapTrackParamSave);
-    AliMUONTrackExtrap::ExtrapToZ(&trackParam1, bestHitForRec1->GetZ());
-    trackCandidate->AddTrackParamAtHit(&trackParam1,bestHitForRec1);
-    if (bestHitForRec2) {
-      AliMUONTrackParam trackParam2(extrapTrackParamSave);
-      AliMUONTrackExtrap::ExtrapToZ(&trackParam2, bestHitForRec2->GetZ());
-      trackCandidate->AddTrackParamAtHit(&trackParam2,bestHitForRec2);
-      // Sort TrackParamAtHit according to increasing Z
-      trackCandidate->GetTrackParamAtHit()->Sort();
-      // Update the chi2 of the new track
-      if (trackCandidate->GetFitFMin()<0) trackCandidate->SetFitFMin(bestChi2WithTwoHitForRec);
-      else trackCandidate->SetFitFMin(trackCandidate->GetFitFMin() + bestChi2WithTwoHitForRec);
+  if (!fgkTrackAllTracks) {
+    if (foundTwoHits) {
+      UpdateTrack(trackCandidate,bestTrackParamAtHit1,bestTrackParamAtHit2);
+      
       // Printout for debuging
       if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
-        cout << "FollowTrackInStation: added the two best hits in station(1..): " << nextStation+1
-             << " (Chi2 = " << bestChi2WithTwoHitForRec << ")" << endl;
+        cout << "FollowTrackInStation: added the two best hits in station(1..): " << nextStation+1 << endl;
         if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
       }
-    } else {
-      // Sort TrackParamAtHit according to increasing Z
-      trackCandidate->GetTrackParamAtHit()->Sort();
-      // Update the chi2 of the new track
-      if (trackCandidate->GetFitFMin()<0) trackCandidate->SetFitFMin(bestChi2WithOneHitForRec);
-      else trackCandidate->SetFitFMin(trackCandidate->GetFitFMin() + bestChi2WithOneHitForRec);
+      
+    } else if (foundOneHit) {
+      UpdateTrack(trackCandidate,bestTrackParamAtHit1);
+      
       // Printout for debuging
       if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
-        cout << "FollowTrackInStation: added the best hit in station(1..): " << nextStation+1
-             << " (Chi2 = " << bestChi2WithOneHitForRec << ")" << endl;
+        cout << "FollowTrackInStation: added the best hit in chamber(1..): " << bestTrackParamAtHit1.GetHitForRecPtr()->GetChamberNumber()+1 << endl;
         if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
       }
+      
+    } else return kFALSE;
+    
+  } else if (foundOneHit || foundTwoHits) {
+    
+    // remove obsolete track
+    fRecTracksPtr->Remove(&trackCandidate);
+    fNRecTracks--;
+    
+  } else return kFALSE;
+  
+  return kTRUE;
+  
+}
+
+  //__________________________________________________________________________
+Double_t AliMUONTrackReconstructor::TryTwoHitForRec(const AliMUONTrackParam &trackParamAtHit1, AliMUONHitForRec* hitForRec2,
+                                                   AliMUONTrackParam &trackParamAtHit2)
+{
+/// Test the compatibility between the track and the 2 hitForRec together (using trackParam's covariance matrix):
+/// return the corresponding Chi2 accounting for covariances between the 2 hitForRec
+/// return trackParamAtHit1 & 2
+  
+  // extrapolate track parameters at the z position of the second hit
+  trackParamAtHit2.SetParameters(trackParamAtHit1.GetParameters());
+  trackParamAtHit2.SetZ(trackParamAtHit1.GetZ());
+  AliMUONTrackExtrap::ExtrapToZ(&trackParamAtHit2, hitForRec2->GetZ());
+  
+  // set pointer to hit2 into trackParamAtHit2
+  trackParamAtHit2.SetHitForRecPtr(hitForRec2);
+  
+  // Set differences between track and the 2 hitForRec in the bending and non bending directions
+  AliMUONHitForRec* hitForRec1 = trackParamAtHit1.GetHitForRecPtr();
+  TMatrixD dPos(4,1);
+  dPos(0,0) = hitForRec1->GetNonBendingCoor() - trackParamAtHit1.GetNonBendingCoor();
+  dPos(1,0) = hitForRec1->GetBendingCoor() - trackParamAtHit1.GetBendingCoor();
+  dPos(2,0) = hitForRec2->GetNonBendingCoor() - trackParamAtHit2.GetNonBendingCoor();
+  dPos(3,0) = hitForRec2->GetBendingCoor() - trackParamAtHit2.GetBendingCoor();
+  
+  // Calculate the error matrix from the track parameter covariances at first hitForRec
+  TMatrixD error(4,4);
+  error.Zero();
+  if (trackParamAtHit1.CovariancesExist()) {
+    // Save track parameters at first hitForRec
+    AliMUONTrackParam trackParamAtHit1Save(trackParamAtHit1);
+    TMatrixD paramAtHit1Save(trackParamAtHit1Save.GetParameters());
+    Double_t z1 = trackParamAtHit1Save.GetZ();
+    
+    // Save track coordinates at second hitForRec
+    Double_t nonBendingCoor2        = trackParamAtHit2.GetNonBendingCoor();
+    Double_t bendingCoor2           = trackParamAtHit2.GetBendingCoor();
+    
+    // add MCS effect at first hitForRec
+    AliMUONTrackExtrap::AddMCSEffect(&trackParamAtHit1Save,AliMUONConstants::ChamberThicknessInX0(),1.);
+    
+    // Get the pointer to the parameter covariance matrix at first hitForRec
+    const TMatrixD& kParamCov = trackParamAtHit1Save.GetCovariances();
+    
+    // Calculate the jacobian related to the transformation between track parameters
+    // at first hitForRec and track coordinates at the 2 hitForRec z-position
+    TMatrixD jacob(4,5);
+    jacob.Zero();
+    // first derivative at the first hitForRec:
+    jacob(0,0) = 1.; // dx1/dx
+    jacob(1,2) = 1.; // dy1/dy
+    // first derivative at the second hitForRec:
+    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.,-paramAtHit1Save(4,0)); // variation always in the same direction
+        } else dParam(j,0) = 0.;
+      }
+      
+      // Set new track parameters at first hitForRec
+      trackParamAtHit1Save.SetParameters(paramAtHit1Save);
+      trackParamAtHit1Save.AddParameters(dParam);
+      trackParamAtHit1Save.SetZ(z1);
+      
+      // Extrapolate new track parameters to the z position of the second hitForRec
+      AliMUONTrackExtrap::ExtrapToZ(&trackParamAtHit1Save,hitForRec2->GetZ());
+      
+      // Calculate the jacobian
+      jacob(2,i) = (trackParamAtHit1Save.GetNonBendingCoor()  - nonBendingCoor2) / dParam(i,0); // dx2/dParami
+      jacob(3,i) = (trackParamAtHit1Save.GetBendingCoor()     - bendingCoor2   ) / dParam(i,0); // dy2/dParami
     }
+    
+    // Calculate the error matrix
+    TMatrixD tmp(jacob,TMatrixD::kMult,kParamCov);
+    error = TMatrixD(tmp,TMatrixD::kMultTranspose,jacob);
+  }
+  
+  // Add hitForRec resolution to the error matrix
+  error(0,0) += hitForRec1->GetNonBendingReso2();
+  error(1,1) += hitForRec1->GetBendingReso2();
+  error(2,2) += hitForRec2->GetNonBendingReso2();
+  error(3,3) += hitForRec2->GetBendingReso2();
+  
+  // invert the error matrix for Chi2 calculation
+  if (error.Determinant() != 0) {
+    error.Invert();
   } else {
-    fRecTracksPtr->Remove(trackCandidate); // obsolete track
-    fNRecTracks--;
+    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);
+  
+}
+
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::UpdateTrack(AliMUONTrack &track, AliMUONTrackParam &trackParamAtHit)
+{
+  /// Add 1 hit to the track candidate
+  /// Update chi2 of the track 
+  
+  // Compute local chi2
+  AliMUONHitForRec* hit = trackParamAtHit.GetHitForRecPtr();
+  Double_t deltaX = trackParamAtHit.GetNonBendingCoor() - hit->GetNonBendingCoor();
+  Double_t deltaY = trackParamAtHit.GetBendingCoor() - hit->GetBendingCoor();
+  Double_t localChi2 = deltaX*deltaX / hit->GetNonBendingReso2() +
+                      deltaY*deltaY / hit->GetBendingReso2();
+  
+  // Flag hit as being not removable
+  trackParamAtHit.SetRemovable(kFALSE);
+  trackParamAtHit.SetLocalChi2(0.); // --> Local chi2 not used
+  
+  // Update the chi2 of the new track
+  track.SetFitFMin(track.GetFitFMin() + localChi2);
+  
+  // Update TrackParamAtHit
+  track.AddTrackParamAtHit(&trackParamAtHit,trackParamAtHit.GetHitForRecPtr());
+  track.GetTrackParamAtHit()->Sort();
+  
 }
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::SetVertexForFit(AliMUONTrack* trackCandidate)
+void AliMUONTrackReconstructor::UpdateTrack(AliMUONTrack &track, AliMUONTrackParam &trackParamAtHit1, AliMUONTrackParam &trackParamAtHit2)
+{
+  /// Add 2 hits to the track candidate
+  /// Update track and local chi2
+  
+  // Update local chi2 at first hit
+  AliMUONHitForRec* hit1 = trackParamAtHit1.GetHitForRecPtr();
+  Double_t deltaX = trackParamAtHit1.GetNonBendingCoor() - hit1->GetNonBendingCoor();
+  Double_t deltaY = trackParamAtHit1.GetBendingCoor() - hit1->GetBendingCoor();
+  Double_t localChi2AtHit1 = deltaX*deltaX / hit1->GetNonBendingReso2() +
+                            deltaY*deltaY / hit1->GetBendingReso2();
+  trackParamAtHit1.SetLocalChi2(localChi2AtHit1);
+  
+  // Flag first hit as being removable
+  trackParamAtHit1.SetRemovable(kTRUE);
+  
+  // Update local chi2 at second hit
+  AliMUONHitForRec* hit2 = trackParamAtHit2.GetHitForRecPtr();
+  deltaX = trackParamAtHit2.GetNonBendingCoor() - hit2->GetNonBendingCoor();
+  deltaY = trackParamAtHit2.GetBendingCoor() - hit2->GetBendingCoor();
+  Double_t localChi2AtHit2 = deltaX*deltaX / hit2->GetNonBendingReso2() +
+                            deltaY*deltaY / hit2->GetBendingReso2();
+  trackParamAtHit2.SetLocalChi2(localChi2AtHit2);
+  
+  // Flag first hit as being removable
+  trackParamAtHit2.SetRemovable(kTRUE);
+  
+  // Update the chi2 of the new track
+  track.SetFitFMin(track.GetFitFMin() + localChi2AtHit1 + localChi2AtHit2);
+  
+  // Update TrackParamAtHit
+  track.AddTrackParamAtHit(&trackParamAtHit1,trackParamAtHit1.GetHitForRecPtr());
+  track.AddTrackParamAtHit(&trackParamAtHit2,trackParamAtHit2.GetHitForRecPtr());
+  track.GetTrackParamAtHit()->Sort();
+  
+}
+
+  //__________________________________________________________________________
+Bool_t AliMUONTrackReconstructor::RecoverTrack(AliMUONTrack &trackCandidate, Int_t nextStation)
+{
+  /// Try to recover the track candidate in the next station
+  /// by removing the worst of the two hits attached in the current station
+  /// Return kTRUE if recovering succeeds
+  AliDebug(1,"Enter RecoverTrack");
+  
+  // Do not try to recover track until we have attached hit(s) on station(1..) 3
+  if (nextStation > 1) return kFALSE;
+  
+  Int_t worstHitNumber = -1;
+  Double_t localChi2, worstLocalChi2 = 0.;
+  
+  // Look for the hit to remove
+  for (Int_t hitNumber = 0; hitNumber < 2; hitNumber++) {
+    AliMUONTrackParam *trackParamAtHit = (AliMUONTrackParam*)trackCandidate.GetTrackParamAtHit()->UncheckedAt(hitNumber);
+    
+    // check if current hit is removable
+    if (!trackParamAtHit->IsRemovable()) return kFALSE;
+    
+    // Pick up hit with the worst chi2
+    localChi2 = trackParamAtHit->GetLocalChi2();
+    if (localChi2 > worstLocalChi2) {
+      worstLocalChi2 = localChi2;
+      worstHitNumber = hitNumber;
+    }
+  }
+  
+  // Reset best hit as being NOT removable
+  ((AliMUONTrackParam*)trackCandidate.GetTrackParamAtHit()->UncheckedAt((worstHitNumber+1)%2))->SetRemovable(kFALSE);
+  
+  // Remove the worst hit
+  trackCandidate.RemoveTrackParamAtHit((AliMUONTrackParam*)trackCandidate.GetTrackParamAtHit()->UncheckedAt(worstHitNumber));
+  
+  // Re-fit the track:
+  // Do not take into account the multiple scattering to speed up the fit
+  // Calculate the track parameter covariance matrix
+  trackCandidate.SetFitWithVertex(kFALSE); // To be sure
+  Fit(trackCandidate, kFALSE, kTRUE);
+  
+  // Look for new hit(s) in next station
+  return FollowTrackInStation(trackCandidate,nextStation);
+  
+}
+
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::SetVertexForFit(AliMUONTrack &trackCandidate)
 {
   /// Add the vertex as a measured hit to constrain the fit of the "trackCandidate"
   /// Compute the vertex resolution from natural vertex dispersion and
@@ -604,26 +720,26 @@ void AliMUONTrackReconstructor::SetVertexForFit(AliMUONTrack* trackCandidate)
   /// the "trackCandidate" to do not influence the result by changing track resolution at vertex
   AliDebug(1,"Enter SetVertexForFit");
   
-  Double_t nonBendingReso2 = fNonBendingVertexDispersion * fNonBendingVertexDispersion;
-  Double_t bendingReso2 = fBendingVertexDispersion * fBendingVertexDispersion;
+  Double_t nonBendingReso2 = fgkNonBendingVertexDispersion * fgkNonBendingVertexDispersion;
+  Double_t bendingReso2 = fgkBendingVertexDispersion * fgkBendingVertexDispersion;
   // add multiple scattering effets
-  AliMUONTrackParam paramAtVertex(*((AliMUONTrackParam*)(trackCandidate->GetTrackParamAtHit()->First())));
+  AliMUONTrackParam paramAtVertex(*((AliMUONTrackParam*)(trackCandidate.GetTrackParamAtHit()->First())));
   paramAtVertex.DeleteCovariances(); // to be sure to account only for multiple scattering
   AliMUONTrackExtrap::ExtrapToVertexUncorrected(&paramAtVertex,0.);
-  TMatrixD* paramCov = paramAtVertex.GetCovariances();
-  nonBendingReso2 += (*paramCov)(0,0);
-  bendingReso2 += (*paramCov)(2,2);
+  const TMatrixD& kParamCov = paramAtVertex.GetCovariances();
+  nonBendingReso2 += kParamCov(0,0);
+  bendingReso2 += kParamCov(2,2);
   // Set the vertex
   AliMUONHitForRec vertex; // Coordinates set to (0.,0.,0.) by default
   vertex.SetNonBendingReso2(nonBendingReso2);
   vertex.SetBendingReso2(bendingReso2);
-  trackCandidate->SetVertex(&vertex);
+  trackCandidate.SetVertex(&vertex);
 }
 
   //__________________________________________________________________________
-void AliMUONTrackReconstructor::Fit(AliMUONTrack *track, Bool_t includeMCS, Bool_t calcCov)
+void AliMUONTrackReconstructor::Fit(AliMUONTrack &track, Bool_t includeMCS, Bool_t calcCov)
 {
-  /// Fit the track "track" with or without multiple Coulomb scattering according to "includeMCS".
+  /// Fit the track "track" w/wo multiple Coulomb scattering according to "includeMCS".
   
   Double_t benC, errorParam, invBenP, nonBenC, x, y;
   AliMUONTrackParam *trackParam;
@@ -636,7 +752,7 @@ void AliMUONTrackReconstructor::Fit(AliMUONTrack *track, Bool_t includeMCS, Bool
   // Clear MINUIT parameters
   gMinuit->mncler();
   // Give the fitted track to MINUIT
-  gMinuit->SetObjectFit(track);
+  gMinuit->SetObjectFit(&track);
   if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
     // Define print level
     arg[0] = 1;
@@ -653,12 +769,21 @@ void AliMUONTrackReconstructor::Fit(AliMUONTrack *track, Bool_t includeMCS, Bool
   //arg[0] = 2;
   //gMinuit->mnexcm("SET STR", arg, 1, status);
   
-  // Switch between available FCN according to "includeMCS"
-  if (includeMCS) gMinuit->SetFCN(TrackChi2MCS);
-  else gMinuit->SetFCN(TrackChi2);
+  // set flag w/wo multiple scattering according to "includeMCS"
+  track.SetFitWithMCS(includeMCS);
+  if (includeMCS) {
+    // compute hit weights only once
+    if (!track.ComputeHitWeights()) {
+      AliWarning("cannot take into account the multiple scattering effects");
+      track.SetFitWithMCS(kFALSE);
+    }
+  }
+  
+  // Set fitting function
+  gMinuit->SetFCN(TrackChi2);
   
   // Set fitted parameters (!! The order is very important for the covariance matrix !!)
-  trackParam = (AliMUONTrackParam*) (track->GetTrackParamAtHit()->First());
+  trackParam = (AliMUONTrackParam*) (track.GetTrackParamAtHit()->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);
@@ -688,7 +813,7 @@ void AliMUONTrackReconstructor::Fit(AliMUONTrack *track, Bool_t includeMCS, Bool
   
   // global result of the fit
   gMinuit->mnstat(fitFMin, fedm, errdef, npari, nparx, covStatus);
-  track->SetFitFMin(fitFMin);
+  track.SetFitFMin(fitFMin);
   
   // Get the covariance matrix if required
   if (calcCov) {
@@ -698,39 +823,35 @@ void AliMUONTrackReconstructor::Fit(AliMUONTrack *track, Bool_t includeMCS, Bool
     gMinuit->mnemat(&matrix[0][0],5);
     if (covStatus == 3) trackParam->SetCovariances(matrix);
     else trackParam->SetVariances(matrix);
-  } else *(trackParam->GetCovariances()) = 0;
+  } 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".
+  /// Return the "Chi2" to be minimized with Minuit for track fitting.
   /// 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
+  /// 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();
-//  AliMUONTrack *trackBeingFitted = (AliMUONTrack*) AliMUONTrackReconstructor::Fitter()->GetObjectFit();
-  AliMUONTrackParam param1;
-  AliMUONTrackParam* trackParamAtHit;
-  AliMUONHitForRec* hitForRec;
-  Chi2 = 0.0; // initialize Chi2
+  AliMUONTrackParam* trackParamAtHit = (AliMUONTrackParam*) trackBeingFitted->GetTrackParamAtHit()->First();
   Double_t dX, dY;
+  chi2 = 0.; // initialize chi2
   
-  // copy of track parameters to be fitted
-  param1 = *((AliMUONTrackParam*) (trackBeingFitted->GetTrackParamAtHit()->First()));
-  param1.SetNonBendingCoor(Param[0]);
-  param1.SetNonBendingSlope(Param[1]);
-  param1.SetBendingCoor(Param[2]);
-  param1.SetBendingSlope(Param[3]);
-  param1.SetInverseBendingMomentum(Param[4]);
+  // update track parameters
+  trackParamAtHit->SetNonBendingCoor(param[0]);
+  trackParamAtHit->SetNonBendingSlope(param[1]);
+  trackParamAtHit->SetBendingCoor(param[2]);
+  trackParamAtHit->SetBendingSlope(param[3]);
+  trackParamAtHit->SetInverseBendingMomentum(param[4]);
+  trackBeingFitted->UpdateTrackParamAtHit();
   
   // Take the vertex into account in the fit if required
   if (trackBeingFitted->GetFitWithVertex()) {
-    AliMUONTrackParam paramAtVertex(param1);
+    AliMUONTrackParam paramAtVertex(*trackParamAtHit);
     AliMUONTrackExtrap::ExtrapToZ(&paramAtVertex, 0.);
     AliMUONHitForRec *vertex = trackBeingFitted->GetVertex();
     if (!vertex) {
@@ -739,280 +860,127 @@ void TrackChi2(Int_t & /*NParam*/, Double_t * /*Gradient*/, Double_t &Chi2, Doub
     }
     dX = vertex->GetNonBendingCoor() - paramAtVertex.GetNonBendingCoor();
     dY = vertex->GetBendingCoor() - paramAtVertex.GetBendingCoor();
-    Chi2 += dX * dX / vertex->GetNonBendingReso2() + dY * dY / vertex->GetBendingReso2();
+    chi2 += dX * dX / vertex->GetNonBendingReso2() + dY * dY / vertex->GetBendingReso2();
   }
   
-  // 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" !!!!
-    dX = hitForRec->GetNonBendingCoor() - param1.GetNonBendingCoor();
-    dY = hitForRec->GetBendingCoor() - param1.GetBendingCoor();
-    Chi2 = Chi2 + dX * dX / hitForRec->GetNonBendingReso2() + dY * dY / hitForRec->GetBendingReso2();
-    trackParamAtHit = (AliMUONTrackParam*) (trackBeingFitted->GetTrackParamAtHit()->After(trackParamAtHit));
-  }
+  // compute chi2 w/wo multiple scattering
+  if (trackBeingFitted->GetFitWithMCS()) chi2 += trackBeingFitted->ComputeGlobalChi2(kTRUE);
+  else chi2 += trackBeingFitted->ComputeGlobalChi2(kFALSE);
+  
 }
 
   //__________________________________________________________________________
-void TrackChi2MCS(Int_t & /*NParam*/, Double_t * /*Gradient*/, Double_t &Chi2, Double_t *Param, Int_t /*Flag*/)
+void AliMUONTrackReconstructor::ImproveTracks()
 {
-  /// 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.
+  /// 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");
   
-  AliMUONTrack *trackBeingFitted = (AliMUONTrack*) gMinuit->GetObjectFit();
-//  AliMUONTrack *trackBeingFitted = (AliMUONTrack*) AliMUONTrackReconstructor::Fitter()->GetObjectFit();
-  AliMUONTrackParam param1;
-  AliMUONTrackParam* trackParamAtHit;
-  AliMUONHitForRec* hitForRec;
-  Chi2 = 0.0; // initialize Chi2
-  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];
-  
-  // copy of track parameters to be fitted
-  param1 = *((AliMUONTrackParam*) (trackBeingFitted->GetTrackParamAtHit()->First()));
-  param1.SetNonBendingCoor(Param[0]);
-  param1.SetNonBendingSlope(Param[1]);
-  param1.SetBendingCoor(Param[2]);
-  param1.SetBendingSlope(Param[3]);
-  param1.SetInverseBendingMomentum(Param[4]);
-
-  // Take the vertex into account in the fit if required
-  if (trackBeingFitted->GetFitWithVertex()) {
-    AliMUONTrackParam paramAtVertex(param1);
-    AliMUONTrackExtrap::ExtrapToZ(&paramAtVertex, 0.);
-    AliMUONHitForRec *vertex = trackBeingFitted->GetVertex();
-    if (!vertex) {
-      cout<<"Error in TrackChi2MCS: Want to use the vertex in tracking but it has not been created!!"<<endl;
-      exit(-1);
-    }
-    Double_t dX = vertex->GetNonBendingCoor() - paramAtVertex.GetNonBendingCoor();
-    Double_t dY = vertex->GetBendingCoor() - paramAtVertex.GetBendingCoor();
-    Chi2 += dX * dX / vertex->GetNonBendingReso2() + dY * dY / vertex->GetBendingReso2();
-  }
+  Double_t localChi2, worstLocalChi2;
+  Int_t worstChamber;
+  AliMUONTrackParam *trackParamAtHit, *worstTrackParamAtHit;
   
-  // 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]); 
+  // Remove double track to improve only "good" tracks
+  RemoveDoubleTracks();
+  
+  AliMUONTrack *track = (AliMUONTrack*) fRecTracksPtr->First();
+  while (track) {
+    
+    while (!track->IsImproved()) {
+      
+      // Update track parameters and covariances
+      track->UpdateCovTrackParamAtHit();
+      
+      // Compute local chi2 of each hits
+      track->ComputeLocalChi2(kTRUE);
+      
+      // Look for the hit to remove
+      worstTrackParamAtHit = 0;
+      worstLocalChi2 = 0.;
+      trackParamAtHit = (AliMUONTrackParam*) track->GetTrackParamAtHit()->First();
+      while (trackParamAtHit) {
+        
+        // Pick up hit with the worst chi2
+        localChi2 = trackParamAtHit->GetLocalChi2();
+        if (localChi2 > worstLocalChi2) {
+          worstLocalChi2 = localChi2;
+          worstTrackParamAtHit = trackParamAtHit;
+        }
+        
+      trackParamAtHit = (AliMUONTrackParam*) track->GetTrackParamAtHit()->After(trackParamAtHit);
       }
-      // 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);
+      
+      // Check if bad hit found
+      if (!worstTrackParamAtHit) {
+        track->SetImproved(kTRUE);
+        break;
       }
-    } // for (hitNumber2 = hitNumber1;...
-  } // for (hitNumber1 = 0;...
-    
-  // Inversion of covariance matrices
-  Int_t ifailBending;
-  gMinuit->mnvert(&((*covBending)(0,0)), numberOfHit, numberOfHit, numberOfHit, ifailBending);
-  Int_t ifailNonBending;
-  gMinuit->mnvert(&((*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));
+      
+      // check whether the worst hit is removable or not
+      if (!worstTrackParamAtHit->IsRemovable()) {
+        track->SetImproved(kTRUE);
+        break;
       }
+      
+      // Check whether the worst chi2 is under requirement or not
+      if (worstLocalChi2 < 2. * fgkSigmaToCutForImprovement * fgkSigmaToCutForImprovement) { // 2 because 2 quantities in chi2
+        track->SetImproved(kTRUE);
+        break;
+      }
+      
+      // Reset the second hit in the same station as the bad one as being NOT removable
+      worstChamber = worstTrackParamAtHit->GetHitForRecPtr()->GetChamberNumber();
+      if (worstChamber%2 == 0) ((AliMUONTrackParam*)track->GetTrackParamAtHit()->After(worstTrackParamAtHit))->SetRemovable(kFALSE);
+      else ((AliMUONTrackParam*)track->GetTrackParamAtHit()->Before(worstTrackParamAtHit))->SetRemovable(kFALSE);
+      
+      // Remove the worst hit
+      track->RemoveTrackParamAtHit(worstTrackParamAtHit);
+      
+      // Re-fit the track:
+      // Take into account the multiple scattering
+      // Calculate the track parameter covariance matrix
+      track->SetFitWithVertex(kFALSE); // To be sure
+      Fit(*track, kTRUE, kTRUE);
+      
+      // Printout for debuging
+      if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+        cout << "ImproveTracks: track " << fRecTracksPtr->IndexOf(track)+1 << " improved " << endl;
+      }
+      
     }
-  } 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());
-    }
+    
+    track = (AliMUONTrack*) fRecTracksPtr->After(track);
   }
   
-  delete covBending;
-  delete covNonBending;
-  delete [] msa2;
 }
 
   //__________________________________________________________________________
-Double_t MultipleScatteringAngle2(AliMUONTrackParam *param)
+void AliMUONTrackReconstructor::Finalize()
 {
-  /// Returns square of multiple Coulomb scattering angle
-  /// from TrackParamAtHit pointed to by "param"
-  Double_t slopeBending, slopeNonBending, radiationLength, inverseBendingMomentum2, inverseTotalMomentum2;
-  Double_t varMultipleScatteringAngle;
-  slopeBending = param->GetBendingSlope();
-  slopeNonBending = param->GetNonBendingSlope();
-  // thickness in radiation length for the current track,
-  // taking local angle into account
-  radiationLength = AliMUONConstants::ChamberThicknessInX0() *
-                   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 AliMUONTrackReconstructor::FillMUONTrack()
-{
-  /// Fill fHitForRecAtHit of AliMUONTrack's
+  /// Fill AliMUONTrack's fHitForRecAtHit array
+  /// Recompute track parameters and covariances at each attached cluster from those at the first one
   AliMUONTrack *track;
   AliMUONTrackParam *trackParamAtHit;
+  
   track = (AliMUONTrack*) fRecTracksPtr->First();
   while (track) {
+    
+    // update track parameters if not already done
+    if (!track->IsImproved()) track->UpdateCovTrackParamAtHit();
+    
     trackParamAtHit = (AliMUONTrackParam*) (track->GetTrackParamAtHit()->First());
     while (trackParamAtHit) {
+      
+      // update array of track hit
       track->AddHitForRecAtHit(trackParamAtHit->GetHitForRecPtr());
-      trackParamAtHit = (AliMUONTrackParam*) (track->GetTrackParamAtHit()->After(trackParamAtHit)); 
+      
+      trackParamAtHit = (AliMUONTrackParam*) (track->GetTrackParamAtHit()->After(trackParamAtHit));
     }
+    
     track = (AliMUONTrack*) fRecTracksPtr->After(track);
+    
   }
-  return;
-}
-
-  //__________________________________________________________________________
-void AliMUONTrackReconstructor::EventDump(void)
-{
-  /// Dump reconstructed event (track parameters at vertex and at first hit),
-  /// and the particle parameters
-  AliMUONTrack *track;
-  AliMUONTrackParam trackParam, *trackParam1;
-  Double_t bendingSlope, nonBendingSlope, pYZ;
-  Double_t pX, pY, pZ, x, y, z, c;
-  Int_t 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 = (*((AliMUONTrackParam*) track->GetTrackParamAtHit()->First()));
-    AliMUONTrackExtrap::ExtrapToVertex(&trackParam,0.,0.,0.);
-    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));
-  }
-  // 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;
+    
 }