]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - MUON/AliMUONTrackReconstructor.cxx
next50 trigger mask in AliHLTGlobalEsdConverterComponent
[u/mrichter/AliRoot.git] / MUON / AliMUONTrackReconstructor.cxx
index 30fd9edc861d77ddbf3e0ba83bc04bad44b64d9b..8a41b4c726e3fd9e9d862f464255703a981f5acf 100644 (file)
  * about the suitability of this software for any purpose. It is          *
  * provided "as is" without express or implied warranty.                  *
  **************************************************************************/
-/*
-$Log$
 
-Revision 1.6  2001/01/26 20:00:53  hristov
-Major upgrade of AliRoot code
+/* $Id$ */
 
-Revision 1.4  2000/12/21 22:14:38  morsch
-Clean-up of coding rule violations.
+//-----------------------------------------------------------------------------
+/// \class AliMUONTrackReconstructor
+/// MUON track reconstructor using the original method
+///
+/// This class contains as data:
+/// - the parameters for the track reconstruction
+///
+/// It contains as methods, among others:
+/// - MakeTracks to build the tracks
+//-----------------------------------------------------------------------------
 
-Revision 1.3  2000/10/02 21:28:09  fca
-Removal of useless dependecies via forward declarations
+#include "AliMUONTrackReconstructor.h"
 
-Revision 1.2  2000/06/15 07:58:49  morsch
-Code from MUON-dev joined
+#include "AliMUONConstants.h"
+#include "AliMUONVCluster.h"
+#include "AliMUONVClusterServer.h"
+#include "AliMUONVClusterStore.h"
+#include "AliMUONTrack.h"
+#include "AliMUONTrackParam.h"
+#include "AliMUONTrackExtrap.h"
+#include "AliMUONRecoParam.h"
+#include "AliMUONGeometryTransformer.h"
 
-Revision 1.1.2.7  2000/06/09 22:06:29  morsch
-Some coding rule violations corrected. Will soon be obsolete.
+#include "AliMpArea.h"
 
-Revision 1.1.2.6  2000/05/02 07:15:29  morsch
-Put back TH1.h and TH2.h includes.
+#include "AliLog.h"
 
-Revision 1.1.2.5  2000/02/17 18:12:43  morsch
-Corrections in trackf_read_spoint causing segmentation violations in previous version (I. Chevrot)
-New histos (I. Chevrot)
-
-Revision 1.1.2.4  2000/02/15 18:01:08  morsch
-Log messages
-
-Revision 1.1.2.3  2000/02/15 17:59:01  morsch
-Log message added
-
-Revision 1.1.2.2  2000/02/15 18:54:56  morsch
-Reference between track contributing to reconstructed hit and particle corrected  
-*/
-
-#include "AliCallf77.h" 
-#include "AliMUONTrackReconstructor.h" 
-#include "AliRun.h"
-#include "AliMUON.h"
-#include "AliMC.h"
-
-#include "AliMUONHit.h"
-#include "AliMUONPadHit.h"
-#include "AliMUONDigit.h"
-#include "AliMUONRawCluster.h"
-#include "AliMUONReconstHit.h"
-
-#include "AliPDG.h"
-
-#include <TRandom.h> 
-#include <TFile.h> 
-#include <TH1.h>
-#include <TH2.h>  
-#include <TTree.h> 
-#include <TParticle.h> 
 #include <TMinuit.h>
-#include <iostream.h>
-
-#ifndef WIN32 
-# define reco_init       reco_init_
-# define cutpxz          cutpxz_
-# define sigmacut        sigmacut_
-# define xpreci          xpreci_
-# define ypreci          ypreci_
-# define reconstmuon     reconstmuon_
-# define reconstmuon2    reconstmuon2_
-# define trackf_read_geant     trackf_read_geant_
-# define trackf_read_fit     trackf_read_fit_
-# define trackf_read_spoint     trackf_read_spoint_
-# define chfill          chfill_
-# define chfill2         chfill2_
-# define chf1            chf1_
-# define chfnt           chfnt_
-# define hist_create     hist_create_
-# define hist_closed     hist_closed_
-# define rndm            rndm_
-# define fcn             fcn_
-# define trackf_fit      trackf_fit_
-# define prec_fit        prec_fit_
-# define fcnfit          fcnfit_
-# define reco_term       reco_term_
-#else 
-# define reco_init       RECO_INIT
-# define cutpxz          CUTPXZ
-# define sigmacut        SIGMACUT
-# define xpreci          XPRECI
-# define ypreci          YPRECI
-# define reconstmuon     RECONSTMUON
-# define reconstmuon2    RECONSTMUON2
-# define trackf_read_geant     TRACKF_READ_GEANT
-# define trackf_read_fit     TRACKF_READ_FIT
-# define trackf_read_spoint     TRACKF_READ_SPOINT
-# define chfill          CHFILL
-# define chfill2         CHFILL2
-# define chf1            CHF1
-# define chfnt           CHFNT
-# define hist_create     HIST_CREATE
-# define hist_closed     HIST_CLOSED
-# define rndm            RNDM
-# define fcn             FCN
-# define trackf_fit      TRACKF_FIT
-# define prec_fit        PREC_FIT
-# define fcnfit          FCNFIT
-# define reco_term       RECO_TERM
-#endif 
-
-extern "C"
+#include <Riostream.h>
+#include <TMath.h>
+#include <TMatrixD.h>
+#include <TClonesArray.h>
+
+// Functions to be minimized with Minuit
+void TrackChi2(Int_t &nParam, Double_t *gradient, Double_t &chi2, Double_t *param, Int_t flag);
+
+using std::endl;
+using std::cout;
+/// \cond CLASSIMP
+ClassImp(AliMUONTrackReconstructor) // Class implementation in ROOT context
+/// \endcond
+
+  //__________________________________________________________________________
+AliMUONTrackReconstructor::AliMUONTrackReconstructor(const AliMUONRecoParam* recoParam, AliMUONVClusterServer* clusterServer,
+                                                    const AliMUONGeometryTransformer* transformer)
+  : AliMUONVTrackReconstructor(recoParam, clusterServer, transformer)
 {
-void type_of_call reco_init(Double_t &, Double_t &, Double_t &);
-void type_of_call reco_term();
-void type_of_call cutpxz(Double_t &);
-void type_of_call sigmacut(Double_t &);
-void type_of_call xpreci(Double_t &);
-void type_of_call ypreci(Double_t &);
-void type_of_call reconstmuon(Int_t &, Int_t &, Int_t &, Int_t &, Int_t &);
-void type_of_call reconstmuon2(Int_t &, Int_t &, Int_t &);
-void type_of_call trackf_read_fit(Int_t &, Int_t &, Int_t &, Int_t *, Double_t *, Double_t *);
-void type_of_call trackf_read_geant(Int_t *, Double_t *, Double_t *, Double_t *, Int_t *, Int_t *, Double_t *, Double_t *, Double_t *, Double_t *,Int_t &, Double_t *, Double_t *, Double_t *, Int_t &, Int_t &, Double_t *, Double_t *, Double_t *, Double_t *); 
-void type_of_call trackf_read_spoint(Int_t *, Double_t *, Double_t *, Double_t *, Int_t *, Int_t *, Double_t *, Double_t *, Double_t *, Double_t *,Int_t &, Double_t *, Double_t *, Double_t *, Int_t &, Int_t &, Double_t *, Double_t *, Double_t *, Double_t *); 
-void type_of_call chfill(Int_t &, Float_t &, Float_t &, Float_t &);
-void type_of_call chfill2(Int_t &, Float_t &, Float_t &, Float_t &);
-void type_of_call chf1(Int_t &, Float_t &, Float_t &);
-void type_of_call chfnt(Int_t &, Int_t &, Int_t *, Int_t *, Float_t *, Float_t *, Float_t *, Float_t *, Float_t *, Float_t *, Float_t *, Float_t *);
-void type_of_call hist_create();
-void type_of_call hist_closed();
-void type_of_call fcnf(Int_t &, Double_t *, Double_t &, Double_t *, Int_t);
-void type_of_call fcn(Int_t &, Double_t *, Double_t &, Double_t *, Int_t &, Int_t &);
-void type_of_call trackf_fit(Int_t &, Double_t *, Double_t *, Double_t &, Double_t &, Double_t &, Double_t &, Double_t &);
-void type_of_call prec_fit(Double_t &, Double_t &, Double_t &, Double_t &, Double_t&, Double_t &, Double_t &, Double_t &, Double_t &, Double_t &, Double_t &, Double_t &, Double_t &, Double_t &, Double_t &);
-void type_of_call fcnfitf(Int_t &, Double_t *, Double_t &, Double_t *, Int_t);
-void type_of_call fcnfit(Int_t &, Double_t *, Double_t &, Double_t *, Int_t &, Int_t &);
-Float_t type_of_call rndm() {return gRandom->Rndm();}
-void type_of_call fit_trace(Float_t &, Float_t &, Float_t &, Float_t &, Float_t &, Float_t &, Int_t &, Int_t &, Int_t &, Int_t &);
+  /// Constructor
 }
 
-static TTree *gAliNtupleGlobal;
-static TFile *gAliFileGlobal;
-static TTree *gAliTreeK1;
-static TTree *gAliTrH1;
-static TClonesArray *gAliHits2;        //List of hits for one track only
-static TClonesArray *gAliParticles2;   //List of particles in the Kine tree
-
+  //__________________________________________________________________________
+AliMUONTrackReconstructor::~AliMUONTrackReconstructor()
+{
+/// Destructor
+} 
 
-// variables of the tracking ntuple 
-struct { 
-  Int_t ievr;           // number of event 
-  Int_t ntrackr;        // number of tracks per event
-  Int_t istatr[500];    // 1 = good muon, 2 = ghost, 0 = something else
-  Int_t isignr[500];    // sign of the track
-  Float_t pxr[500];     // x momentum of the reconstructed track
-  Float_t pyr[500];     // y momentum of the reconstructed track
-  Float_t pzr[500];     // z momentum of the reconstructed track
-  Float_t zvr[500];     // z vertex 
-  Float_t chi2r[500];   // chi2 of the fit of the track with the field map
-  Float_t pxv[500];     // x momentum at vertex
-  Float_t pyv[500];     // y momentum at vertex
-  Float_t pzv[500];     // z momentum at vertex
-} NtupleSt;
+  //__________________________________________________________________________
+Bool_t AliMUONTrackReconstructor::MakeTrackCandidates(AliMUONVClusterStore& clusterStore)
+{
+  /// 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.
+  
+  TClonesArray *segments;
+  AliMUONTrack *track;
+  Int_t iCandidate = 0;
+  Bool_t clusterFound;
 
-ClassImp(AliMUONTrackReconstructor)
+  AliDebug(1,"Enter MakeTrackCandidates");
 
-//___________________________________________________
-AliMUONTrackReconstructor::AliMUONTrackReconstructor()
-{
-// Constructor
-//
-   fSPxzCut   = 3.0;
-   fSSigmaCut = 4.0;
-   fSXPrec    = 0.01; 
-   fSYPrec    = 0.144;
+  // Unless we're doing combined tracking, we'll clusterize all stations at once
+  Int_t firstChamber(0);
+  Int_t lastChamber(9);
+  
+  if (GetRecoParam()->CombineClusterTrackReco()) {
+    // ... Here's the exception : ask the clustering to reconstruct
+    // clusters *only* in station 4 and 5 for combined tracking
+    firstChamber = 6;
+  }
+
+  for (Int_t i = firstChamber; i <= lastChamber; ++i ) 
+  {
+    if (fClusterServer && GetRecoParam()->UseChamber(i)) fClusterServer->Clusterize(i, clusterStore, AliMpArea(), GetRecoParam());
+  }
+  
+  // 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 = MakeSegmentsBetweenChambers(clusterStore, 2*istat, 2*istat+1);
+    
+    // Loop over segments
+    for (Int_t iseg=0; iseg<segments->GetEntriesFast(); iseg++) 
+    {
+      AliDebug(1,Form("Making primary candidate(1..) %d",++iCandidate));
+      
+      // Transform segments to tracks and put them at the end of fRecTracksPtr
+      track = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack((AliMUONObjectPair*)((*segments)[iseg]),GetRecoParam()->GetBendingVertexDispersion());
+      fNRecTracks++;
+      
+      // Look for compatible cluster(s) in the other station
+      if (GetRecoParam()->MakeTrackCandidatesFast())
+       clusterFound = FollowLinearTrackInStation(*track, clusterStore, 7-istat);
+      else clusterFound = FollowTrackInStation(*track, clusterStore, 7-istat);
+      
+      // Remove track if no cluster found on a requested station
+      // or abort tracking if there are too many candidates
+      if (GetRecoParam()->RequestStation(7-istat)) {
+       if (!clusterFound) {
+         fRecTracksPtr->Remove(track);
+         fNRecTracks--;
+       } else if (fNRecTracks > GetRecoParam()->GetMaxTrackCandidates()) {
+         AliError(Form("Too many track candidates (%d tracks). Stop tracking.", fNRecTracks));
+         return kFALSE;
+       }
+      } else {
+       if ((fNRecTracks + segments->GetEntriesFast() - iseg - 1) > GetRecoParam()->GetMaxTrackCandidates()) {
+         AliError(Form("Too many track candidates (%d tracks). Stop tracking.", fNRecTracks + segments->GetEntriesFast() - iseg - 1));
+         return kFALSE;
+       }
+      }
+      
+    }
+    
+  }
+  
+  // Keep all different tracks or only the best ones as required
+  if (GetRecoParam()->TrackAllTracks()) RemoveIdenticalTracks();
+  else RemoveDoubleTracks();
+  
+  AliDebug(1,Form("Number of good candidates = %d",fNRecTracks));
+  
+  return kTRUE;
+  
 }
 
-//_____________________________________________________________________________
-void AliMUONTrackReconstructor::Reconst2(Int_t &ifit, Int_t &idebug, Int_t &nev)
+  //__________________________________________________________________________
+Bool_t AliMUONTrackReconstructor::MakeMoreTrackCandidates(AliMUONVClusterStore& clusterStore)
 {
-//
-//
-    reconstmuon2(ifit,idebug,nev);
+  /// To make extra track candidates (assuming linear propagation if the flag fgkMakeTrackCandidatesFast is set to kTRUE):
+  /// clustering is supposed to be already done
+  /// Start with segments made of 1 cluster in each of the stations 4 and 5 then follow track in remaining chambers.
+  /// Good candidates are made of at least three clusters if both station are requested (two otherwise).
+  /// Keep only best candidates or all of them according to the flag fgkTrackAllTracks.
+  
+  TClonesArray *segments;
+  AliMUONObjectPair *segment;
+  AliMUONTrack *track;
+  Int_t iCandidate = 0, iCurrentTrack, nCurrentTracks;
+  Bool_t clusterFound;
+  
+  AliDebug(1,"Enter MakeMoreTrackCandidates");
+  
+  // Double loop over chambers in stations(1..) 4 and 5 to make track candidates
+  for (Int_t ich1 = 6; ich1 <= 7; ich1++) {
+    for (Int_t ich2 = 8; ich2 <= 9; ich2++) {
+      
+      // Make segments in the station
+      segments = MakeSegmentsBetweenChambers(clusterStore, ich1, ich2);
+      
+      /// Remove segments already attached to a track
+      RemoveUsedSegments(*segments);
+      
+      // Loop over segments
+      for (Int_t iSegment=0; iSegment<segments->GetEntriesFast(); iSegment++)
+      {
+       AliDebug(1,Form("Making primary candidate(1..) %d",++iCandidate));
+       segment = (AliMUONObjectPair*) segments->UncheckedAt(iSegment);
+       
+       // Transform segments to tracks and put them at the end of fRecTracksPtr
+       iCurrentTrack = fRecTracksPtr->GetLast()+1;
+       track = new ((*fRecTracksPtr)[iCurrentTrack]) AliMUONTrack(segment,GetRecoParam()->GetBendingVertexDispersion());
+       fNRecTracks++;
+       
+       // Look for compatible cluster(s) in the second chamber of station 5
+       clusterFound = FollowLinearTrackInChamber(*track, clusterStore, 17-ich2);
+       
+       // skip the original track in case it has been removed
+       if (GetRecoParam()->TrackAllTracks() && clusterFound) iCurrentTrack++;
+       
+       // loop over every new tracks
+       nCurrentTracks = fRecTracksPtr->GetLast()+1;
+       while (iCurrentTrack < nCurrentTracks) {
+         track = (AliMUONTrack*) fRecTracksPtr->UncheckedAt(iCurrentTrack);
+         
+         // Look for compatible cluster(s) in the second chamber of station 4
+         FollowLinearTrackInChamber(*track, clusterStore, 13-ich1);
+         
+         iCurrentTrack++;
+       }
+       
+       // abort tracking if there are too many candidates
+       if ((fNRecTracks + segments->GetEntriesFast() - iSegment - 1) > GetRecoParam()->GetMaxTrackCandidates()) {
+         AliError(Form("Too many track candidates (%d tracks). Stop tracking.", fNRecTracks + segments->GetEntriesFast() - iSegment - 1));
+         return kFALSE;
+       }
+       
+      }
+      
+    }
+  }
+  
+  // Keep only the best tracks if required
+  if (!GetRecoParam()->TrackAllTracks()) RemoveDoubleTracks();
+  else fRecTracksPtr->Compress();
+  
+  AliDebug(1,Form("Number of good candidates = %d",fNRecTracks));
+  
+  return kTRUE;
+  
 }
 
-//_____________________________________________________________________________
-void AliMUONTrackReconstructor::Reconst(Int_t &ifit, Int_t &idebug, Int_t bgdEvent, Int_t &nev, Int_t &idres, Int_t &ireadgeant, Option_t *option,Text_t *filename)
+  //__________________________________________________________________________
+Bool_t AliMUONTrackReconstructor::FollowTracks(AliMUONVClusterStore& clusterStore)
 {
-  //
-  // open kine and hits tree of background file for reconstruction of geant hits 
-  // call tracking fortran program
-  static Bool_t first=kTRUE;
-  static TFile *pFile;
-  char *addBackground = strstr(option,"Add");
-  
-  if (addBackground ) { // only in case of background with geant hits 
-    if(first) {
-      fFileName=filename;
-      cout<<"filename  "<<fFileName<<endl;
-      pFile=new TFile(fFileName);
-      cout<<"I have opened "<<fFileName<<" file "<<endl;
-      gAliHits2     = new TClonesArray("AliMUONHit",1000);
-      gAliParticles2 = new TClonesArray("TParticle",1000);
-      first=kFALSE;
-    }
-    pFile->cd();
-    if(gAliHits2) gAliHits2->Clear();
-    if(gAliParticles2) gAliParticles2->Clear();
-    if(gAliTrH1) delete gAliTrH1;
-    gAliTrH1=0;
-    if(gAliTreeK1) delete gAliTreeK1;
-    gAliTreeK1=0;
-    // Get Hits Tree header from file
-    char treeName[20];
-    sprintf(treeName,"TreeH%d",bgdEvent);
-    gAliTrH1 = (TTree*)gDirectory->Get(treeName);
-    //     printf("gAliTrH1 %p of treename %s for event %d \n",gAliTrH1,treeName,bgdEvent);
-    if (!gAliTrH1) {
-      printf("ERROR: cannot find Hits Tree for event:%d\n",bgdEvent);
+  /// Follow tracks in stations(1..) 3, 2 and 1
+  AliDebug(1,"Enter FollowTracks");
+  
+  AliMUONTrack *track, *nextTrack;
+  AliMUONTrackParam *trackParam, *nextTrackParam;
+  Int_t currentNRecTracks;
+  
+  Double_t sigmaCut2 = GetRecoParam()->GetSigmaCutForTracking() *
+                       GetRecoParam()->GetSigmaCutForTracking();
+  
+  for (Int_t station = 2; station >= 0; station--) {
+    
+    // Save the actual number of reconstructed track in case of
+    // tracks are added or suppressed during the tracking procedure
+    // !! Do not compress fRecTracksPtr until the end of the loop over tracks !!
+    currentNRecTracks = fNRecTracks;
+    
+    for (Int_t iRecTrack = 0; iRecTrack <currentNRecTracks; iRecTrack++) {
+      AliDebug(1,Form("FollowTracks: track candidate(1..) %d", iRecTrack+1));
+      
+      track = (AliMUONTrack*) fRecTracksPtr->UncheckedAt(iRecTrack);
+      
+      // Fit the track:
+      // Do not take into account the multiple scattering to speed up the fit
+      // Calculate the track parameter covariance matrix
+      // If there is no cluster out of station 4 or 5 then use the vertex to better constrain the fit
+      if (((AliMUONTrackParam*) track->GetTrackParamAtCluster()->First())->GetClusterPtr()->GetChamberId() > 5)
+       Fit(*track, kFALSE, kTRUE, kTRUE);
+      else Fit(*track, kFALSE, kFALSE, kTRUE);
+      
+      // remove tracks out of limits
+      if (!IsAcceptable(*((AliMUONTrackParam*)track->GetTrackParamAtCluster()->First()))) {
+       fRecTracksPtr->Remove(track);
+       fNRecTracks--;
+       continue;
+      }
+      
+      // remove 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 (GetRecoParam()->ComplementTracks()) {
+       
+       if (station==2) { // save track parameters on stations 4 and 5
+         
+         // extrapolate track parameters and covariances at each cluster
+         // remove the track in case of failure
+         if (!track->UpdateCovTrackParamAtCluster()) {
+           fRecTracksPtr->Remove(track);
+           fNRecTracks--;
+           continue;
+         }
+         
+         // save them
+         trackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->First();
+         while (trackParam) {
+           trackParam->SetSmoothParameters(trackParam->GetParameters());
+           trackParam->SetSmoothCovariances(trackParam->GetCovariances());
+           trackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->After(trackParam);
+         }
+         
+       } else { // or save track parameters on last station only
+         
+         trackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->First();
+         if (trackParam->GetClusterPtr()->GetChamberId() < 2*(station+2)) {
+           
+           // save parameters from fit
+           trackParam->SetSmoothParameters(trackParam->GetParameters());
+           trackParam->SetSmoothCovariances(trackParam->GetCovariances());
+           
+           // save parameters extrapolated to the second chamber of the same station if it has been hit
+           nextTrackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->After(trackParam);
+           if (nextTrackParam->GetClusterPtr()->GetChamberId() < 2*(station+2)) {
+             
+             // reset parameters and covariances
+             nextTrackParam->SetParameters(trackParam->GetParameters());
+             nextTrackParam->SetZ(trackParam->GetZ());
+             nextTrackParam->SetCovariances(trackParam->GetCovariances());
+             
+             // extrapolate them to the z of the corresponding cluster
+             // remove the track in case of failure
+             if (!AliMUONTrackExtrap::ExtrapToZCov(nextTrackParam, nextTrackParam->GetClusterPtr()->GetZ())) {
+               fRecTracksPtr->Remove(track);
+               fNRecTracks--;
+               continue;
+             }
+             
+             // save them
+             nextTrackParam->SetSmoothParameters(nextTrackParam->GetParameters());
+             nextTrackParam->SetSmoothCovariances(nextTrackParam->GetCovariances());
+             
+           }
+           
+         }
+         
+       }
+       
+      }
+      
+      // Look for compatible cluster(s) in station(0..) "station"
+      if (!FollowTrackInStation(*track, clusterStore, station)) {
+       
+       // Try to recover track if required
+       if (GetRecoParam()->RecoverTracks()) {
+         
+         // work on a copy of the track if this station is not required
+         // to keep the case where no cluster is reconstructed as a possible candidate
+         if (!GetRecoParam()->RequestStation(station)) {
+           track = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(*track);
+           fNRecTracks++;
+         }
+         
+         // try to recover
+         if (!RecoverTrack(*track, clusterStore, station)) {
+           // remove track if no cluster found
+           fRecTracksPtr->Remove(track);
+           fNRecTracks--;
+         }
+         
+       } else if (GetRecoParam()->RequestStation(station)) {
+         // remove track if no cluster found
+         fRecTracksPtr->Remove(track);
+         fNRecTracks--;
+       } 
+       
+      }
+      
+      // abort tracking if there are too many candidates
+      if (fNRecTracks > GetRecoParam()->GetMaxTrackCandidates()) {
+       AliError(Form("Too many track candidates (%d tracks). Stop tracking.", fNRecTracks));
+       return kFALSE;
+      }
+      
     }
-    // set branch addresses
-    TBranch *branch;
-    char branchname[30];
-    AliMUON *pMUON  = (AliMUON*) gAlice->GetModule("MUON");  
-    sprintf(branchname,"%s",pMUON->GetName());       
-    if (gAliTrH1 && gAliHits2) {
-      branch = gAliTrH1->GetBranch(branchname);
-      if (branch) branch->SetAddress(&gAliHits2);
+    
+    // Compress fRecTracksPtr for the next step
+    fRecTracksPtr->Compress();
+    
+    // Keep only the best tracks if required
+    if (!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--;
+      track = nextTrack;
+      continue;
     }
-    gAliTrH1->GetEntries();
-    // get the Kine tree
-    sprintf(treeName,"TreeK%d",bgdEvent);
-    gAliTreeK1 = (TTree*)gDirectory->Get(treeName);
-    if (!gAliTreeK1) {
-      printf("ERROR: cannot find Kine Tree for event:%d\n",bgdEvent);
+    
+    // save parameters from fit into smoothed parameters to complete track afterward
+    if (GetRecoParam()->ComplementTracks()) {
+      
+      trackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->First();
+      if (trackParam->GetClusterPtr()->GetChamberId() < 2) {
+       
+       // save parameters from fit
+       trackParam->SetSmoothParameters(trackParam->GetParameters());
+       trackParam->SetSmoothCovariances(trackParam->GetCovariances());
+       
+       // save parameters extrapolated to the second chamber of the same station if it has been hit
+       nextTrackParam = (AliMUONTrackParam*) track->GetTrackParamAtCluster()->After(trackParam);
+       if (nextTrackParam->GetClusterPtr()->GetChamberId() < 2) {
+         
+         // reset parameters and covariances
+         nextTrackParam->SetParameters(trackParam->GetParameters());
+         nextTrackParam->SetZ(trackParam->GetZ());
+         nextTrackParam->SetCovariances(trackParam->GetCovariances());
+         
+         // extrapolate them to the z of the corresponding cluster
+         // remove the track in case of failure
+         if (!AliMUONTrackExtrap::ExtrapToZCov(nextTrackParam, nextTrackParam->GetClusterPtr()->GetZ())) {
+           fRecTracksPtr->Remove(track);
+           fNRecTracks--;
+           track = nextTrack;
+           continue;
+         }
+         
+         // save them
+         nextTrackParam->SetSmoothParameters(nextTrackParam->GetParameters());
+         nextTrackParam->SetSmoothCovariances(nextTrackParam->GetCovariances());
+         
+       }
+       
+      }
+      
     }
-    // set branch addresses
-    if (gAliTreeK1) 
-      gAliTreeK1->SetBranchAddress("Particles", &gAliParticles2);
-    gAliTreeK1->GetEvent(0);
     
-    // get back to the first file
-    TTree *treeK = gAlice->TreeK();
-    TFile *file1 = 0;
-    if (treeK) file1 = treeK->GetCurrentFile();
-    file1->cd();
+    track = nextTrack;
     
-  } // end if addBackground
+  }
+  
+  fRecTracksPtr->Compress();
+  
+  return kTRUE;
   
-  // call tracking fortran program
-  reconstmuon(ifit,idebug,nev,idres,ireadgeant);
 }
 
-//________________________________________________________________________________
-void AliMUONTrackReconstructor::Init(Double_t &seff, Double_t &sb0, Double_t &sbl3)
+  //__________________________________________________________________________
+Bool_t AliMUONTrackReconstructor::FollowTrackInChamber(AliMUONTrack &trackCandidate, AliMUONVClusterStore& clusterStore, Int_t nextChamber)
 {
-  //
-  // introduce in fortran program somme parameters and cuts for tracking 
-  // create output file "reconst.root" (histos + ntuple)
-  cutpxz(fSPxzCut);          // Pxz cut (GeV/c) to begin the track finding
-  sigmacut(fSSigmaCut);      // Number of sigmas delimiting the searching areas
-  xpreci(fSXPrec);           // Chamber precision in X (cm) 
-  ypreci(fSYPrec);           // Chamber precision in Y (cm)
-  reco_init(seff,sb0,sbl3);
+  /// Follow trackCandidate in chamber(0..) nextChamber and search for compatible cluster(s)
+  /// Keep all possibilities or only the best one(s) according to the flag fgkTrackAllTracks:
+  /// kTRUE:  duplicate "trackCandidate" if there are several possibilities and add the new tracks at the end of
+  ///         fRecTracksPtr to avoid conficts with other track candidates at this current stage of the tracking procedure.
+  ///         Remove the obsolete "trackCandidate" at the end.
+  /// kFALSE: add only the best cluster(s) to the "trackCandidate". Try to add a couple of clusters in priority.
+  AliDebug(1,Form("Enter FollowTrackInChamber(1..) %d", nextChamber+1));
+  
+  Double_t chi2WithOneCluster = AliMUONTrack::MaxChi2();
+  Double_t maxChi2WithOneCluster = 2. * GetRecoParam()->GetSigmaCutForTracking() *
+                                       GetRecoParam()->GetSigmaCutForTracking(); // 2 because 2 quantities in chi2
+  Double_t bestChi2WithOneCluster = maxChi2WithOneCluster;
+  Bool_t foundOneCluster = kFALSE;
+  AliMUONTrack *newTrack = 0x0;
+  AliMUONVCluster *cluster;
+  AliMUONTrackParam extrapTrackParam;
+  AliMUONTrackParam extrapTrackParamAtCh;
+  AliMUONTrackParam extrapTrackParamAtCluster;
+  AliMUONTrackParam bestTrackParamAtCluster;
+  
+  // Get track parameters according to the propagation direction
+  if (nextChamber > 7) extrapTrackParamAtCh = *(AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->Last();
+  else extrapTrackParamAtCh = *(AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->First();
+  
+  // Printout for debuging
+  if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
+    cout<<endl<<"Track parameters and covariances at first cluster:"<<endl;
+    extrapTrackParamAtCh.GetParameters().Print();
+    extrapTrackParamAtCh.GetCovariances().Print();
+  }
+  
+  // Add MCS effect
+  Int_t currentChamber = extrapTrackParamAtCh.GetClusterPtr()->GetChamberId();
+  AliMUONTrackExtrap::AddMCSEffect(&extrapTrackParamAtCh,AliMUONConstants::ChamberThicknessInX0(currentChamber),-1.);
+  
+  // Add MCS in the missing chamber(s) if any
+  while (currentChamber > nextChamber + 1) {
+    // extrapolation to the missing chamber
+    currentChamber--;
+    if (!AliMUONTrackExtrap::ExtrapToZCov(&extrapTrackParamAtCh, AliMUONConstants::DefaultChamberZ(currentChamber))) return kFALSE;
+    // add MCS effect
+    AliMUONTrackExtrap::AddMCSEffect(&extrapTrackParamAtCh,AliMUONConstants::ChamberThicknessInX0(currentChamber),-1.);
+  }
+  
+  //Extrapolate trackCandidate to chamber
+  if (!AliMUONTrackExtrap::ExtrapToZCov(&extrapTrackParamAtCh, AliMUONConstants::DefaultChamberZ(nextChamber))) return kFALSE;
+  
+  // Printout for debuging
+  if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
+    cout<<endl<<"Track parameters and covariances at first cluster extrapolated to z = "<<AliMUONConstants::DefaultChamberZ(nextChamber)<<":"<<endl;
+    extrapTrackParamAtCh.GetParameters().Print();
+    extrapTrackParamAtCh.GetCovariances().Print();
+  }
+  
+  // Printout for debuging
+  if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+    cout << "FollowTrackInStation: look for clusters in chamber(1..): " << nextChamber+1 << endl;
+  }
+  
+  // Ask the clustering to reconstruct new clusters around the track position in the current chamber
+  // except for station 4 and 5 that are already entirely clusterized
+  if (GetRecoParam()->CombineClusterTrackReco()) {
+    if (nextChamber < 6) AskForNewClustersInChamber(extrapTrackParamAtCh, clusterStore, nextChamber);
+  }
+  
+  // Create iterators to loop over clusters in both chambers
+  TIter next(clusterStore.CreateChamberIterator(nextChamber,nextChamber));
+  
+  // look for cluster in chamber
+  while ( ( cluster = static_cast<AliMUONVCluster*>(next()) ) ) {
+    
+    // try to add the current cluster fast
+    if (!TryOneClusterFast(extrapTrackParamAtCh, cluster)) continue;
+    
+    // try to add the current cluster accuratly
+    chi2WithOneCluster = TryOneCluster(extrapTrackParamAtCh, cluster, extrapTrackParamAtCluster);
+    
+    // if good chi2 then consider to add cluster
+    if (chi2WithOneCluster < maxChi2WithOneCluster) {
+      foundOneCluster = kTRUE;
+      
+      // Printout for debuging
+      if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+       cout << "FollowTrackInStation: found one cluster in chamber(1..): " << nextChamber+1
+       << " (Chi2 = " << chi2WithOneCluster << ")" << endl;
+       cluster->Print();
+      }
+      
+      if (GetRecoParam()->TrackAllTracks()) {
+       // copy trackCandidate into a new track put at the end of fRecTracksPtr and add the new cluster
+       newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(trackCandidate);
+       UpdateTrack(*newTrack,extrapTrackParamAtCluster);
+       fNRecTracks++;
+       
+       // Printout for debuging
+       if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+         cout << "FollowTrackInStation: added one cluster in chamber(1..): " << nextChamber+1 << endl;
+         if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
+       }
+       
+      } else if (chi2WithOneCluster < bestChi2WithOneCluster) {
+       // keep track of the best single cluster except if a couple of clusters has already been found
+       bestChi2WithOneCluster = chi2WithOneCluster;
+       bestTrackParamAtCluster = extrapTrackParamAtCluster;
+      }
+      
+    }
+    
+  }
+  
+  // fill out the best track if required else clean up the fRecTracksPtr array
+  if (!GetRecoParam()->TrackAllTracks()) {
+    if (foundOneCluster) {
+      UpdateTrack(trackCandidate,bestTrackParamAtCluster);
+      
+      // Printout for debuging
+      if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+        cout << "FollowTrackInStation: added the best cluster in chamber(1..): " << bestTrackParamAtCluster.GetClusterPtr()->GetChamberId()+1 << endl;
+        if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
+      }
+      
+    } else return kFALSE;
+    
+  } else if (foundOneCluster) {
+    
+    // remove obsolete track
+    fRecTracksPtr->Remove(&trackCandidate);
+    fNRecTracks--;
+    
+  } else return kFALSE;
+  
+  return kTRUE;
+  
 }
 
-//__________________________________________
-void AliMUONTrackReconstructor::FinishEvent()
+  //__________________________________________________________________________
+Bool_t AliMUONTrackReconstructor::FollowTrackInStation(AliMUONTrack &trackCandidate, AliMUONVClusterStore& clusterStore, Int_t nextStation)
 {
-   // Finish
-   // TTree *treeK = gAlice->TreeK();
-   // TFile *file1 = 0;
-   // if (treeK) file1 = treeK->GetCurrentFile();
-   // file1->cd();
+  /// 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 = AliMUONTrack::MaxChi2();
+  Double_t chi2WithTwoClusters = AliMUONTrack::MaxChi2();
+  Double_t maxChi2WithOneCluster = 2. * GetRecoParam()->GetSigmaCutForTracking() *
+                                       GetRecoParam()->GetSigmaCutForTracking(); // 2 because 2 quantities in chi2
+  Double_t maxChi2WithTwoClusters = 4. * GetRecoParam()->GetSigmaCutForTracking() *
+                                        GetRecoParam()->GetSigmaCutForTracking(); // 4 because 4 quantities in chi2
+  Double_t bestChi2WithOneCluster = maxChi2WithOneCluster;
+  Double_t bestChi2WithTwoClusters = maxChi2WithTwoClusters;
+  Bool_t foundOneCluster = kFALSE;
+  Bool_t foundTwoClusters = kFALSE;
+  AliMUONTrack *newTrack = 0x0;
+  AliMUONVCluster *clusterCh1, *clusterCh2;
+  AliMUONTrackParam extrapTrackParam;
+  AliMUONTrackParam extrapTrackParamAtCh;
+  AliMUONTrackParam extrapTrackParamAtCluster1;
+  AliMUONTrackParam extrapTrackParamAtCluster2;
+  AliMUONTrackParam bestTrackParamAtCluster1;
+  AliMUONTrackParam bestTrackParamAtCluster2;
+  
+  // Get track parameters according to the propagation direction
+  if (nextStation==4) extrapTrackParamAtCh = *(AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->Last();
+  else extrapTrackParamAtCh = *(AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->First();
+  
+  // Printout for debuging
+  if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
+    cout<<endl<<"Track parameters and covariances at first cluster:"<<endl;
+    extrapTrackParamAtCh.GetParameters().Print();
+    extrapTrackParamAtCh.GetCovariances().Print();
+  }
+  
+  // Add MCS effect
+  Int_t currentChamber = extrapTrackParamAtCh.GetClusterPtr()->GetChamberId();
+  AliMUONTrackExtrap::AddMCSEffect(&extrapTrackParamAtCh,AliMUONConstants::ChamberThicknessInX0(currentChamber),-1.);
+  
+  // Add MCS in the missing chamber(s) if any
+  while (ch1 < ch2 && currentChamber > ch2 + 1) {
+    // extrapolation to the missing chamber
+    currentChamber--;
+    if (!AliMUONTrackExtrap::ExtrapToZCov(&extrapTrackParamAtCh, AliMUONConstants::DefaultChamberZ(currentChamber))) return kFALSE;
+    // add MCS effect
+    AliMUONTrackExtrap::AddMCSEffect(&extrapTrackParamAtCh,AliMUONConstants::ChamberThicknessInX0(currentChamber),-1.);
+  }
+  
+  //Extrapolate trackCandidate to chamber "ch2"
+  if (!AliMUONTrackExtrap::ExtrapToZCov(&extrapTrackParamAtCh, AliMUONConstants::DefaultChamberZ(ch2))) return kFALSE;
+  
+  // Printout for debuging
+  if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
+    cout<<endl<<"Track parameters and covariances at first cluster extrapolated to z = "<<AliMUONConstants::DefaultChamberZ(ch2)<<":"<<endl;
+    extrapTrackParamAtCh.GetParameters().Print();
+    extrapTrackParamAtCh.GetCovariances().Print();
+  }
+  
+  // Printout for debuging
+  if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+    cout << "FollowTrackInStation: look for clusters in chamber(1..): " << ch2+1 << endl;
+  }
+  
+  // Ask the clustering to reconstruct new clusters around the track position in the current station
+  // except for station 4 and 5 that are already entirely clusterized
+  if (GetRecoParam()->CombineClusterTrackReco()) {
+    if (nextStation < 3) AskForNewClustersInStation(extrapTrackParamAtCh, clusterStore, nextStation);
+  }
+  
+  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;
+  
+  // Create iterators to loop over clusters in both chambers
+  TIter nextInCh1(clusterStore.CreateChamberIterator(ch1,ch1));
+  TIter nextInCh2(clusterStore.CreateChamberIterator(ch2,ch2));
+  
+  // look for candidates in chamber 2
+  while ( ( clusterCh2 = static_cast<AliMUONVCluster*>(nextInCh2()) ) ) {
+    
+    // try to add the current cluster fast
+    if (!TryOneClusterFast(extrapTrackParamAtCh, clusterCh2)) continue;
+    
+    // try to add the current cluster accuratly
+    chi2WithOneCluster = TryOneCluster(extrapTrackParamAtCh, clusterCh2, extrapTrackParamAtCluster2);
+    
+    // if good chi2 then try to attach a cluster in the other chamber too
+    if (chi2WithOneCluster < maxChi2WithOneCluster) {
+      Bool_t foundSecondCluster = kFALSE;
+      
+      // Printout for debuging
+      if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+        cout << "FollowTrackInStation: found one cluster in chamber(1..): " << ch2+1
+            << " (Chi2 = " << chi2WithOneCluster << ")" << endl;
+       clusterCh2->Print();
+        cout << "                      look for second clusters in chamber(1..): " << ch1+1 << " ..." << endl;
+      }
+      
+      // add MCS effect for next step
+      AliMUONTrackExtrap::AddMCSEffect(&extrapTrackParamAtCluster2,AliMUONConstants::ChamberThicknessInX0(ch2),-1.);
+      
+      // copy new track parameters for next step
+      extrapTrackParam = extrapTrackParamAtCluster2;
+      
+      //Extrapolate track parameters to chamber "ch1"
+      Bool_t normalExtrap = AliMUONTrackExtrap::ExtrapToZ(&extrapTrackParam, AliMUONConstants::DefaultChamberZ(ch1));
+      
+      // reset cluster iterator of chamber 1
+      nextInCh1.Reset();
+      iCluster1 = -1;
+      
+      // look for second candidates in chamber 1
+      if (normalExtrap) 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 accurately
+       chi2WithTwoClusters = TryTwoClusters(extrapTrackParamAtCluster2, clusterCh1, extrapTrackParamAtCluster1);
+        
+       // if good chi2 then create a new track by adding the 2 clusters to the "trackCandidate"
+       if (chi2WithTwoClusters < maxChi2WithTwoClusters) {
+         foundSecondCluster = kTRUE;
+          foundTwoClusters = kTRUE;
+          
+         // Printout for debuging
+         if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+           cout << "FollowTrackInStation: found second cluster in chamber(1..): " << ch1+1
+                << " (Global Chi2 = " << chi2WithTwoClusters << ")" << endl;
+           clusterCh1->Print();
+         }
+         
+         if (GetRecoParam()->TrackAllTracks()) {
+           // copy trackCandidate into a new track put at the end of fRecTracksPtr and add the new clusters
+            newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(trackCandidate);
+           UpdateTrack(*newTrack,extrapTrackParamAtCluster1,extrapTrackParamAtCluster2);
+           fNRecTracks++;
+           
+           // Tag clusterCh1 as used
+           clusterCh1Used[iCluster1] = kTRUE;
+           
+           // Printout for debuging
+           if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+             cout << "FollowTrackInStation: added two clusters in station(1..): " << nextStation+1 << endl;
+             if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
+           }
+           
+          } else if (chi2WithTwoClusters < bestChi2WithTwoClusters) {
+           // keep track of the best couple of clusters
+           bestChi2WithTwoClusters = chi2WithTwoClusters;
+           bestTrackParamAtCluster1 = extrapTrackParamAtCluster1;
+           bestTrackParamAtCluster2 = extrapTrackParamAtCluster2;
+          }
+         
+       }
+       
+      }
+      
+      // if no clusterCh1 found then consider to add clusterCh2 only
+      if (!foundSecondCluster) {
+        foundOneCluster = kTRUE;
+        
+       if (GetRecoParam()->TrackAllTracks()) {
+         // copy trackCandidate into a new track put at the end of fRecTracksPtr and add the new cluster
+          newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(trackCandidate);
+         UpdateTrack(*newTrack,extrapTrackParamAtCluster2);
+         fNRecTracks++;
+         
+         // Printout for debuging
+         if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+           cout << "FollowTrackInStation: added one cluster in chamber(1..): " << ch2+1 << endl;
+           if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
+         }
+         
+       } else if (!foundTwoClusters && chi2WithOneCluster < bestChi2WithOneCluster) {
+         // keep track of the best single cluster except if a couple of clusters has already been found
+         bestChi2WithOneCluster = chi2WithOneCluster;
+         bestTrackParamAtCluster1 = extrapTrackParamAtCluster2;
+        }
+       
+      }
+      
+    }
+    
+  }
+  
+  // look for candidates in chamber 1 not already attached to a track
+  // if we want to keep all possible tracks or if no good couple of clusters has been found
+  if (GetRecoParam()->TrackAllTracks() || !foundTwoClusters) {
+    
+    // add MCS effect for next step
+    AliMUONTrackExtrap::AddMCSEffect(&extrapTrackParamAtCh,AliMUONConstants::ChamberThicknessInX0(ch2),-1.);
+    
+    //Extrapolate trackCandidate to chamber "ch1"
+    Bool_t normalExtrap = AliMUONTrackExtrap::ExtrapToZCov(&extrapTrackParamAtCh, AliMUONConstants::DefaultChamberZ(ch1));
+    
+    // Printout for debuging
+    if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
+      cout<<endl<<"Track parameters and covariances at first cluster extrapolated to z = "<<AliMUONConstants::DefaultChamberZ(ch1)<<":"<<endl;
+      extrapTrackParamAtCh.GetParameters().Print();
+      extrapTrackParamAtCh.GetCovariances().Print();
+    }
+    
+    // Printout for debuging
+    if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+      cout << "FollowTrackInStation: look for single clusters in chamber(1..): " << ch1+1 << endl;
+    }
+    
+    // reset cluster iterator of chamber 1
+    nextInCh1.Reset();
+    iCluster1 = -1;
+    
+    // look for second candidates in chamber 1
+    if (normalExtrap) while ( ( clusterCh1 = static_cast<AliMUONVCluster*>(nextInCh1()) ) ) {
+      iCluster1++;
+      
+      if (clusterCh1Used[iCluster1]) continue; // Skip cluster already used
+      
+      // try to add the current cluster fast
+      if (!TryOneClusterFast(extrapTrackParamAtCh, clusterCh1)) continue;
+      
+      // try to add the current cluster accuratly
+      chi2WithOneCluster = TryOneCluster(extrapTrackParamAtCh, clusterCh1, extrapTrackParamAtCluster1);
+      
+      // if good chi2 then consider to add clusterCh1
+      // We do not try to attach a cluster in the other chamber too since it has already been done above
+      if (chi2WithOneCluster < maxChi2WithOneCluster) {
+        foundOneCluster = kTRUE;
+       
+       // Printout for debuging
+       if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+         cout << "FollowTrackInStation: found one cluster in chamber(1..): " << ch1+1
+              << " (Chi2 = " << chi2WithOneCluster << ")" << endl;
+         clusterCh1->Print();
+       }
+       
+       if (GetRecoParam()->TrackAllTracks()) {
+         // copy trackCandidate into a new track put at the end of fRecTracksPtr and add the new cluster
+         newTrack = new ((*fRecTracksPtr)[fRecTracksPtr->GetLast()+1]) AliMUONTrack(trackCandidate);
+         UpdateTrack(*newTrack,extrapTrackParamAtCluster1);
+         fNRecTracks++;
+         
+         // Printout for debuging
+         if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+           cout << "FollowTrackInStation: added one cluster in chamber(1..): " << ch1+1 << endl;
+           if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
+         }
+         
+       } else if (chi2WithOneCluster < bestChi2WithOneCluster) {
+         // keep track of the best single cluster except if a couple of clusters has already been found
+         bestChi2WithOneCluster = chi2WithOneCluster;
+         bestTrackParamAtCluster1 = extrapTrackParamAtCluster1;
+       }
+       
+      }
+      
+    }
+    
+  }
+  
+  // fill out the best track if required else clean up the fRecTracksPtr array
+  if (!GetRecoParam()->TrackAllTracks()) {
+    if (foundTwoClusters) {
+      UpdateTrack(trackCandidate,bestTrackParamAtCluster1,bestTrackParamAtCluster2);
+      
+      // Printout for debuging
+      if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+        cout << "FollowTrackInStation: added the two best clusters in station(1..): " << nextStation+1 << endl;
+        if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
+      }
+      
+    } else if (foundOneCluster) {
+      UpdateTrack(trackCandidate,bestTrackParamAtCluster1);
+      
+      // Printout for debuging
+      if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+        cout << "FollowTrackInStation: added the best cluster in chamber(1..): " << bestTrackParamAtCluster1.GetClusterPtr()->GetChamberId()+1 << endl;
+        if (AliLog::GetGlobalDebugLevel() >= 3) newTrack->RecursiveDump();
+      }
+      
+    } else {
+      delete [] clusterCh1Used;
+      return kFALSE;
+    }
+    
+  } else if (foundOneCluster || foundTwoClusters) {
+    
+    // remove obsolete track
+    fRecTracksPtr->Remove(&trackCandidate);
+    fNRecTracks--;
+    
+  } else {
+    delete [] clusterCh1Used;
+    return kFALSE;
+  }
+  
+  delete [] clusterCh1Used;
+  return kTRUE;
+  
 }
 
-//_____________________________________
-void AliMUONTrackReconstructor::Close()
+  //__________________________________________________________________________
+Double_t AliMUONTrackReconstructor::TryTwoClusters(const AliMUONTrackParam &trackParamAtCluster1, AliMUONVCluster* cluster2,
+                                                  AliMUONTrackParam &trackParamAtCluster2)
 {
-  //
-  // write histos and ntuple to "reconst.root" file
-    reco_term();
+/// 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)
+  // and set pointer to cluster into trackParamAtCluster
+  trackParamAtCluster2.SetParameters(trackParamAtCluster1.GetParameters());
+  trackParamAtCluster2.SetZ(trackParamAtCluster1.GetZ());
+  trackParamAtCluster2.SetClusterPtr(cluster2);
+  if (!AliMUONTrackExtrap::ExtrapToZ(&trackParamAtCluster2, cluster2->GetZ())) return 2.*AliMUONTrack::MaxChi2();
+  
+  // 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);
+    
+    // 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);
+    Double_t direction[5] = {-1.,-1.,1.,1.,-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));
+         dParam(j,0) *= TMath::Sign(1.,direction[j]*paramAtCluster1Save(j,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
+      if (!AliMUONTrackExtrap::ExtrapToZ(&trackParam,cluster2->GetZ())) return 2.*AliMUONTrack::MaxChi2();
+      
+      // 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 2.*AliMUONTrack::MaxChi2();
+  }
+  
+  // Compute the Chi2 value
+  TMatrixD tmp2(dPos,TMatrixD::kTransposeMult,error);
+  TMatrixD result(tmp2,TMatrixD::kMult,dPos);
+  
+  return result(0,0);
+  
 }
 
-//________________________________________________________
-void chfill(Int_t &id, Float_t &x, Float_t &y, Float_t &w)
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::UpdateTrack(AliMUONTrack &track, AliMUONTrackParam &trackParamAtCluster)
 {
-  //
-  // fill histo like hfill in fortran
-    char name[5];
-    sprintf(name,"h%d",id);
-    TH1F *h1 = (TH1F*) gDirectory->Get(name);
-    h1->Fill(x);
+  /// Add 1 cluster to the track candidate
+  /// Update chi2 of the track 
+  
+  // Compute local chi2
+  AliMUONVCluster* cluster = trackParamAtCluster.GetClusterPtr();
+  Double_t deltaX = trackParamAtCluster.GetNonBendingCoor() - cluster->GetX();
+  Double_t deltaY = trackParamAtCluster.GetBendingCoor() - cluster->GetY();
+  Double_t localChi2 = deltaX*deltaX / cluster->GetErrX2() +
+                      deltaY*deltaY / cluster->GetErrY2();
+  
+  // Flag cluster as being not removable
+  if (GetRecoParam()->RequestStation(cluster->GetChamberId()/2))
+    trackParamAtCluster.SetRemovable(kFALSE);
+  else trackParamAtCluster.SetRemovable(kTRUE);
+  trackParamAtCluster.SetLocalChi2(0.); // --> Local chi2 not used
+  
+  // Update the chi2 of the new track
+  track.SetGlobalChi2(track.GetGlobalChi2() + localChi2);
+  
+  // Update TrackParamAtCluster
+  track.AddTrackParamAtCluster(trackParamAtCluster,*cluster);
+  
 }
 
-//_________________________________________________________
-void chfill2(Int_t &id, Float_t &x, Float_t &y, Float_t &w)
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::UpdateTrack(AliMUONTrack &track, AliMUONTrackParam &trackParamAtCluster1, AliMUONTrackParam &trackParamAtCluster2)
 {
-  //
-  // fill histo like hfill2 in fortran
-    char name[5];
-    sprintf(name,"h%d",id);
-    TH2F *h2 = (TH2F*) gDirectory->Get(name);
-    h2->Fill(x,y,w);
+  /// 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);
+  
 }
 
-//__________________________________________
-void chf1(Int_t &id, Float_t &x, Float_t &w)
+  //__________________________________________________________________________
+Bool_t AliMUONTrackReconstructor::RecoverTrack(AliMUONTrack &trackCandidate, AliMUONVClusterStore& clusterStore, Int_t nextStation)
 {
-  //
-  // fill histo like hf1 in fortran
-    char name[5];
-    sprintf(name,"h%d",id);
-    TH1F *h1 = (TH1F*) gDirectory->Get(name);
-    h1->Fill(x,w);
+  /// Try to recover the track candidate in the next station
+  /// by removing the worst of the two clusters attached in the current station
+  /// Return kTRUE if recovering succeeds
+  AliDebug(1,"Enter RecoverTrack");
+  
+  // Do not try to recover track until we have attached cluster(s) on station(1..) 3
+  if (nextStation > 1) return kFALSE;
+  
+  Int_t worstClusterNumber = -1;
+  Double_t localChi2, worstLocalChi2 = -1.;
+  
+  // Look for the cluster to remove
+  for (Int_t clusterNumber = 0; clusterNumber < 2; clusterNumber++) {
+    AliMUONTrackParam *trackParamAtCluster = (AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->UncheckedAt(clusterNumber);
+    
+    // check if current cluster is in the previous station
+    if (trackParamAtCluster->GetClusterPtr()->GetChamberId()/2 != nextStation+1) break;
+    
+    // check if current cluster is removable
+    if (!trackParamAtCluster->IsRemovable()) return kFALSE;
+    
+    // reset the current cluster as beig not removable if it is on a required station
+    if (GetRecoParam()->RequestStation(nextStation+1)) trackParamAtCluster->SetRemovable(kFALSE);
+    
+    // Pick up cluster with the worst chi2
+    localChi2 = trackParamAtCluster->GetLocalChi2();
+    if (localChi2 > worstLocalChi2) {
+      worstLocalChi2 = localChi2;
+      worstClusterNumber = clusterNumber;
+    }
+    
+  }
+  
+  // check if worst cluster found
+  if (worstClusterNumber < 0) return kFALSE;
+  
+  // Remove the worst cluster
+  trackCandidate.RemoveTrackParamAtCluster((AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->UncheckedAt(worstClusterNumber));
+  
+  // Re-fit the track:
+  // Do not take into account the multiple scattering to speed up the fit
+  // Calculate the track parameter covariance matrix
+  Fit(trackCandidate, kFALSE, kFALSE, kTRUE);
+  
+  // skip track if the normalized chi2 is too high
+  if (trackCandidate.GetNormalizedChi2() > GetRecoParam()->GetSigmaCutForTracking() * GetRecoParam()->GetSigmaCutForTracking()) return kFALSE;
+  
+  // skip track out of limits
+  if (!IsAcceptable(*((AliMUONTrackParam*)trackCandidate.GetTrackParamAtCluster()->First()))) return kFALSE;
+  
+  // Look for new cluster(s) in next station
+  return FollowTrackInStation(trackCandidate,clusterStore,nextStation);
+  
 }
 
-//_________________
-void hist_create()
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::SetVertexErrXY2ForFit(AliMUONTrack &trackCandidate)
 {
-  //
-  // Create an output file ("reconst.root")
-  // Create some histograms and an ntuple
-
-    gAliFileGlobal = new TFile("reconst.root","RECREATE","Ntuple - reconstruction");
-
-   gAliNtupleGlobal = new TTree("ntuple","Reconst ntuple");
-   gAliNtupleGlobal->Branch("ievr",&NtupleSt.ievr,"ievr/I");
-   gAliNtupleGlobal->Branch("ntrackr",&NtupleSt.ntrackr,"ntrackr/I");
-   gAliNtupleGlobal->Branch("istatr",&NtupleSt.istatr[0],"istatr[500]/I");
-   gAliNtupleGlobal->Branch("isignr",&NtupleSt.isignr[0],"isignr[500]/I");
-   gAliNtupleGlobal->Branch("pxr",&NtupleSt.pxr[0],"pxr[500]/F");
-   gAliNtupleGlobal->Branch("pyr",&NtupleSt.pyr[0],"pyr[500]/F");
-   gAliNtupleGlobal->Branch("pzr",&NtupleSt.pzr[0],"pzr[500]/F");
-   gAliNtupleGlobal->Branch("zvr",&NtupleSt.zvr[0],"zvr[500]/F");
-   gAliNtupleGlobal->Branch("chi2r",&NtupleSt.chi2r[0],"chi2r[500]/F");
-   gAliNtupleGlobal->Branch("pxv",&NtupleSt.pxv[0],"pxv[500]/F");
-   gAliNtupleGlobal->Branch("pyv",&NtupleSt.pyv[0],"pyv[500]/F");
-   gAliNtupleGlobal->Branch("pzv",&NtupleSt.pzv[0],"pzv[500]/F");
-
-   // test aliroot
-
-  new TH1F("h100","particule id du hit geant",20,0.,20.);
-  new TH1F("h101","position en x du hit geant",100,-200.,200.);
-  new TH1F("h102","position en y du hit geant",100,-200.,200.);
-  new TH1F("h103","chambre de tracking concernee",15,0.,14.);
-  new TH1F("h104","moment ptot du hit geant",50,0.,100.);
-  new TH1F("h105","px au vertex",50,0.,20.);
-  new TH1F("h106","py au vertex",50,0.,20.);
-  new TH1F("h107","pz au vertex",50,0.,20.);
-  new TH1F("h108","position zv",50,-15.,15.);
-  new TH1F("h109","position en x du hit reconstruit",100,-300.,300.);
-  new TH1F("h110","position en y du hit reconstruit",100,-300.,300.);
-  new TH1F("h111","delta x station 1",100,-0.3,0.3);
-  new TH1F("h112","delta x station 2",100,-0.3,0.3);
-  new TH1F("h113","delta x station 3",100,-0.3,0.3);
-  new TH1F("h114","delta x station 4",100,-0.5,0.5);
-  new TH1F("h115","delta x station 5",100,-0.5,0.5);
-  new TH1F("h116","delta x station 1",100,-2,2);
-  new TH1F("h117","delta x station 2",100,-2,2);
-  new TH1F("h121","delta y station 1",100,-0.04,0.04);
-  new TH1F("h122","delta y station 2",100,-0.04,0.04);
-  new TH1F("h123","delta y station 3",100,-0.04,0.04);
-  new TH1F("h124","delta y station 4",100,-0.04,0.04);
-  new TH1F("h125","delta y station 5",100,-0.04,0.04);
-
-  /*  char hname[30];
-      char hname1[30];
-      for (int i=0;i<10;i++) {
-      sprintf(hname,"deltax%d",i);
-      sprintf(hname1,"h12%d",i);
-      new TH1F(hname1,hname ,100,-0.4,0.4);
-      sprintf(hname,"deltay%d",i);
-      sprintf(hname1,"h13%d",i);
-      new TH1F(hname1,hname ,100,-0.4,0.4);
-      }
-  */
-  new TH2F("h2000","VAR X st. 5",30,3.0,183.0,100,0.,25.);
-  new TH2F("h2001","VAR Y st. 5",30,3.0,183.0,100,0.,25.);
-
-  new TH2F("h2500","P vs X HHIT",30,3.0,183.0,200,0.,200.);
-  new TH2F("h2501","P vs X HHIT**2",30,3.0,183.0,200,0.,5000.);
-  new TH2F("h2502","P vs X EPH2 st. 5",30,3.0,183.0,100,0.,0.000005);
-  new TH2F("h2503","P vs X EAL2 st. 5",30,3.0,183.0,100,0.,0.01);
-  //new TH2F("h2504","P vs X EXM2 st. 5",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2504","P vs X EXM2 st. 5",30,3.0,183.0,100,0.,0.1);
-  new TH2F("h2505","P vs X EYM2 st. 5",30,3.0,183.0,100,0.,30.);
-
-  new TH2F("h2507","P vs X EPH st. 5",30,3.0,183.0,100,0.,0.003);
-  new TH2F("h2508","P vs X EAL st. 5",30,3.0,183.0,100,0.,0.3);
-  //new TH2F("h2509","P vs X EXM st. 5",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2509","P vs X EXM st. 5",30,3.0,183.0,100,0.,0.4);
-  new TH2F("h2510","P vs X EYM st. 5",30,3.0,183.0,100,0.,30.);
-
-  new TH2F("h2511","P vs X EPH cut st. 5",30,3.0,183.0,100,0.,0.01);
-  new TH2F("h2512","P vs X EAL cut st. 5",30,3.0,183.0,100,0.,0.3);
-  //new TH2F("h2513","P vs X EXM cut st. 5",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2513","P vs X EXM cut st. 5",30,3.0,183.0,100,0.,0.4);
-  new TH2F("h2514","P vs X EYM cut st. 5",30,3.0,183.0,100,0.,30.);
-  // 4
-  new TH2F("h2400","P vs X HHIT",30,3.0,183.0,200,0.,200.);
-  new TH2F("h2401","P vs X HHIT**2",30,3.0,183.0,200,0.,5000.);
-  new TH2F("h2402","P vs X EPH2 st. 4",30,3.0,183.0,100,0.,0.000005);
-  new TH2F("h2403","P vs X EAL2 st. 4",30,3.0,183.0,100,0.,0.05);
-  //new TH2F("h2404","P vs X EXM2 st. 4",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2404","P vs X EXM2 st. 4",30,3.0,183.0,100,0.,0.1);
-  new TH2F("h2405","P vs X EYM2 st. 4",30,3.0,183.0,100,0.,30.);
-
-  new TH2F("h2407","P vs X EPH st. 4",30,3.0,183.0,100,0.,0.003);
-  new TH2F("h2408","P vs X EAL st. 4",30,3.0,183.0,100,0.,0.3);
-  //new TH2F("h2409","P vs X EXM st. 4",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2409","P vs X EXM st. 4",30,3.0,183.0,100,0.,0.1);
-  new TH2F("h2410","P vs X EYM st. 4",30,3.0,183.0,100,0.,30.);
-
-  new TH2F("h2411","P vs X EPH cut st. 4",30,3.0,183.0,100,0.,0.01);
-  new TH2F("h2412","P vs X EAL cut st. 4",30,3.0,183.0,100,0.,0.3);
-  //new TH2F("h2413","P vs X EXM cut st. 4",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2413","P vs X EXM cut st. 4",30,3.0,183.0,100,0.,0.1);
-  new TH2F("h2414","P vs X EYM cut st. 4",30,3.0,183.0,100,0.,30.);
-  // 3
-  new TH1F("h2301","P2",30,3.0,183.0);
-  new TH2F("h2302","P2 vs X EPH2 st. 3",30,3.0,183.0,100,0.,0.0006);
-  new TH2F("h2303","P2 vs X EAL2 st. 3",30,3.0,183.0,100,0.,0.0005);
-  //new TH2F("h2304","P2 vs X EXM2 st. 3",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2304","P2 vs X EXM2 st. 3",30,3.0,183.0,100,0.,2.);
-  new TH2F("h2305","P2 vs X EYM2 st. 3",30,3.0,183.0,100,0.,3.);
-
-  new TH2F("h2307","P vs X EPH2 st. 3",30,3.0,183.0,100,0.,0.0006);
-  new TH2F("h2308","P vs X EAL2 st. 3",30,3.0,183.0,100,0.,0.005);
-  //new TH2F("h2309","P vs X EXM2 st. 3",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2309","P vs X EXM2 st. 3",30,3.0,183.0,100,0.,2.);
-  new TH2F("h2310","P vs X EYM2 st. 3",30,3.0,183.0,100,0.,3.);
-
-  new TH2F("h2311","P vs X EPH cut st. 3",30,3.0,183.0,100,0.,0.06);
-  new TH2F("h2312","P vs X EAL cut st. 3",30,3.0,183.0,100,0.,0.05);
-  //new TH2F("h2313","P vs X EXM cut st. 3",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2313","P vs X EXM cut st. 3",30,3.0,183.0,100,0.,6.);
-  new TH2F("h2314","P vs X EYM cut st. 3",30,3.0,183.0,100,0.,7.);
-
-  new TH2F("h2315","P2 vs X EPH cut st. 3",30,3.0,183.0,100,0.,0.06);
-  new TH2F("h2316","P2 vs X EAL cut st. 3",30,3.0,183.0,100,0.,0.05);
-  //new TH2F("h2317","P2 vs X EXM cut st. 3",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2317","P2 vs X EXM cut st. 3",30,3.0,183.0,100,0.,6.);
-  new TH2F("h2318","P2 vs X EYM cut st. 3",30,3.0,183.0,100,0.,7.);
-  
-  // 2
-  new TH1F("h2201","P2",30,3.0,183.0);
-  new TH2F("h2202","P2 vs X EPH2 st. 2",30,3.0,183.0,100,0.,0.0006);
-  new TH2F("h2203","P2 vs X EAL2 st. 2",30,3.0,183.0,100,0.,0.005);
-  //new TH2F("h2204","P2 vs X EXM2 st. 2",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2204","P2 vs X EXM2 st. 2",30,3.0,183.0,100,0.,7.);
-  new TH2F("h2205","P2 vs X EYM2 st. 2",30,3.0,183.0,100,0.,5.);
-
-  new TH2F("h2207","P vs X EPH2 st. 2",30,3.0,183.0,100,0.,0.0006);
-  new TH2F("h2208","P vs X EAL2 st. 2",30,3.0,183.0,100,0.,0.005);
-  //new TH2F("h2209","P vs X EXM2 st. 2",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2209","P vs X EXM2 st. 2",30,3.0,183.0,100,0.,7.);
-  new TH2F("h2210","P vs X EYM2 st. 2",30,3.0,183.0,100,0.,5.);
-
-  new TH2F("h2211","P vs X EPH cut st. 2",30,3.0,183.0,100,0.,0.05);
-  new TH2F("h2212","P vs X EAL cut st. 2",30,3.0,183.0,100,0.,0.2);
-  //new TH2F("h2213","P vs X EXM cut st. 2",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2213","P vs X EXM cut st. 2",30,3.0,183.0,100,0.,11.);
-  new TH2F("h2214","P vs X EYM cut st. 2",30,3.0,183.0,100,0.,10.);
-
-  new TH2F("h2215","P2 vs X EPH cut st. 2",30,3.0,183.0,100,0.,0.05);
-  new TH2F("h2216","P2 vs X EAL cut st. 2",30,3.0,183.0,100,0.,0.2);
-  //new TH2F("h2217","P2 vs X EXM cut st. 2",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2217","P2 vs X EXM cut st. 2",30,3.0,183.0,100,0.,11.);
-  new TH2F("h2218","P2 vs X EYM cut st. 2",30,3.0,183.0,100,0.,10.);
-
-  // 1
-  new TH2F("h2102","P2 vs X EPH2 st. 2",30,3.0,183.0,100,0.,0.0006);
-  new TH2F("h2103","P2 vs X EAL2 st. 2",30,3.0,183.0,100,0.,0.005);
-  //new TH2F("h2104","P2 vs X EXM2 st. 2",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2104","P2 vs X EXM2 st. 2",30,3.0,183.0,100,0.,7.);
-  new TH2F("h2105","P2 vs X EYM2 st. 2",30,3.0,183.0,100,0.,7.);
-
-  new TH2F("h2107","P vs X EPH2 st. 2",30,3.0,183.0,100,0.,0.0006);
-  new TH2F("h2108","P vs X EAL2 st. 2",30,3.0,183.0,100,0.,0.005);
-  //new TH2F("h2109","P vs X EXM2 st. 2",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2109","P vs X EXM2 st. 2",30,3.0,183.0,100,0.,7.);
-  new TH2F("h2110","P vs X EYM2 st. 2",30,3.0,183.0,100,0.,7.);
-
-  new TH2F("h2111","P vs X EPH cut st. 2",30,3.0,183.0,100,0.,0.1);
-  new TH2F("h2112","P vs X EAL cut st. 2",30,3.0,183.0,100,0.,0.2);
-  //new TH2F("h2113","P vs X EXM cut st. 2",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2113","P vs X EXM cut st. 2",30,3.0,183.0,100,0.,11.);
-  new TH2F("h2114","P vs X EYM cut st. 2",30,3.0,183.0,100,0.,11.);
-
-  new TH2F("h2115","P2 vs X EPH cut st. 2",30,3.0,183.0,100,0.,0.1);
-  new TH2F("h2116","P2 vs X EAL cut st. 2",30,3.0,183.0,100,0.,0.2);
-  //new TH2F("h2117","P2 vs X EXM cut st. 2",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2117","P2 vs X EXM cut st. 2",30,3.0,183.0,100,0.,11.);
-  new TH2F("h2118","P2 vs X EYM cut st. 2",30,3.0,183.0,100,0.,11.);
-
-  // 2,3,4,5
-  new TH1F("h2701","P2 fit 2",30,3.0,183.0);
-  new TH2F("h2702","P2 vs X EPH2 st. 1 fit 2",30,3.0,183.0,100,0.,0.0006);
-  new TH2F("h2703","P2 vs X EAL2 st. 1 fit 2",30,3.0,183.0,100,0.,0.005);
-  // new TH2F("h2704","P2 vs X EXM2 st. 1 fit 2",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2704","P2 vs X EXM2 st. 1 fit 2",30,3.0,183.0,100,0.,2.);
-  new TH2F("h2705","P2 vs X EYM2 st. 1 fit 2",30,3.0,183.0,100,0.,3.);
-
-  new TH2F("h2707","P vs X EPH2 st. 1 fit 2",30,3.0,183.0,100,0.,0.0006);
-  new TH2F("h2708","P vs X EAL2 st. 1 fit 2",30,3.0,183.0,100,0.,0.005);
-  //new TH2F("h2709","P vs X EXM2 st. 1 fit 2",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2709","P vs X EXM2 st. 1 fit 2",30,3.0,183.0,100,0.,2.);
-  new TH2F("h2710","P vs X EYM2 st. 1 fit 2",30,3.0,183.0,100,0.,3.);
-
-  new TH2F("h2711","P vs X EPH cut st. 1 fit 2",30,3.0,183.0,100,0.,0.07);
-  new TH2F("h2712","P vs X EAL cut st. 1 fit 2",30,3.0,183.0,100,0.,0.2);
-  //new TH2F("h2713","P vs X EXM cut st. 1 fit 2",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2713","P vs X EXM cut st. 1 fit 2",30,3.0,183.0,100,0.,6.);
-  new TH2F("h2714","P vs X EYM cut st. 1 fit 2",30,3.0,183.0,100,0.,7.);
-
-  new TH2F("h2715","P2 vs X EPH cut st. 1 fit 2",30,3.0,183.0,100,0.,0.07);
-  new TH2F("h2716","P2 vs X EAL cut st. 1 fit 2",30,3.0,183.0,100,0.,0.2);
-  //new TH2F("h2717","P2 vs X EXM cut st. 1 fit 2",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2717","P2 vs X EXM cut st. 1 fit 2",30,3.0,183.0,100,0.,6.);
-  new TH2F("h2718","P2 vs X EYM cut st. 1 fit 2",30,3.0,183.0,100,0.,7.);
-
-  // 1,3,4,5
-  new TH1F("h2801","P2 fit 1",30,3.0,183.0);
-  new TH2F("h2802","P2 vs X EPH2 st. 2 fit 1",30,3.0,183.0,100,0.,0.0006);
-  new TH2F("h2803","P2 vs X EAL2 st. 2 fit 1",30,3.0,183.0,100,0.,0.005);
-  //new TH2F("h2804","P2 vs X EXM2 st. 2 fit 1",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2804","P2 vs X EXM2 st. 2 fit 1",30,3.0,183.0,100,0.,2.);
-  new TH2F("h2805","P2 vs X EYM2 st. 2 fit 1",30,3.0,183.0,100,0.,3.);
-
-  new TH2F("h2807","P vs X EPH2 st. 2 fit 1",30,3.0,183.0,100,0.,0.0006);
-  new TH2F("h2808","P vs X EAL2 st. 2 fit 1",30,3.0,183.0,100,0.,0.005);
-  //new TH2F("h2809","P vs X EXM2 st. 2 fit 1",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2809","P vs X EXM2 st. 2 fit 1",30,3.0,183.0,100,0.,2.);
-  new TH2F("h2810","P vs X EYM2 st. 2 fit 1",30,3.0,183.0,100,0.,3.);
-
-  new TH2F("h2811","P vs X EPH cut st. 2 fit 1",30,3.0,183.0,100,0.,0.05);
-  new TH2F("h2812","P vs X EAL cut st. 2 fit 1",30,3.0,183.0,100,0.,0.2);
-  //new TH2F("h2813","P vs X EXM cut st. 2 fit 1",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2813","P vs X EXM cut st. 2 fit 1",30,3.0,183.0,100,0.,5.);
-  new TH2F("h2814","P vs X EYM cut st. 2 fit 1",30,3.0,183.0,100,0.,7.);
-
-  new TH2F("h2815","P2 vs X EPH cut st. 2 fit 1",30,3.0,183.0,100,0.,0.05);
-  new TH2F("h2816","P2 vs X EAL cut st. 2 fit 1",30,3.0,183.0,100,0.,0.2);
-  //new TH2F("h2817","P2 vs X EXM cut st. 2 fit 1",30,3.0,183.0,100,0.,1.5);
-  new TH2F("h2817","P2 vs X EXM cut st. 2 fit 1",30,3.0,183.0,100,0.,5.);
-  new TH2F("h2818","P2 vs X EYM cut st. 2 fit 1",30,3.0,183.0,100,0.,7.);
-
-
-  new TH2F("h1111","dx vs x station 1",30,-250.,250.,30,-0.5,0.5);
-  new TH2F("h1112","dx vs x station 2",30,-250.,250.,30,-0.5,0.5);
-  new TH2F("h1113","dx vs x station 3",30,-250.,250.,30,-0.5,0.5);
-  new TH2F("h1114","dx vs x station 4",30,-250.,250.,30,-0.5,0.5);
-  new TH2F("h1115","dx vs x station 5",30,-250.,250.,30,-0.5,0.5);
-  new TH2F("h1121","dy vs y station 1",30,-250.,250.,30,-0.04,0.04);
-  new TH2F("h1122","dy vs y station 2",30,-250.,250.,30,-0.04,0.04);
-  new TH2F("h1123","dy vs y station 3",30,-250.,250.,30,-0.04,0.04);
-  new TH2F("h1124","dy vs y station 4",30,-250.,250.,30,-0.04,0.04);
-  new TH2F("h1125","dy vs y station 5",30,-250.,250.,30,-0.04,0.04);
-
-  // fin de test
-
-  new TH1F("h500","Acceptance en H st. 4",500,0.,500.);
-  new TH1F("h600","Acceptance en H st. 5",500,0.,500.);
-  new TH1F("h700","X vertex track found",200,-10.,10.);
-  new TH1F("h701","Y vertex track found",200,-10.,10.);
-  new TH1F("h800","Rap. muon gen.",100,0.,5.);
-  new TH1F("h801","Rap. muon gen. recons.",100,0.,5.);
-  new TH1F("h802","Rap. muon gen. ghost ",100,0.,5.);
-  new TH1F("h900","Pt muon gen.",100,0.,20.);
-  new TH1F("h901","Pt muon gen. recons.",100,0.,20.);
-  new TH1F("h902","Pt muon gen. ghost",100,0.,20.);
-  new TH1F("h910","phi muon gen.",100,-10.,10.);
-  new TH1F("h911","phi muon gen. recons.",100,-10.,10.);
-  new TH1F("h912","phi muon gen. ghost",100,-10.,10.);
-  new TH2F("h1001","Y VS X hit st. 1",300,-300.,300.,300,-300.,300.);
-  new TH2F("h1002","Y VS X hit st. 2",300,-300.,300.,300,-300.,300.);
-  new TH2F("h1003","Y VS X hit st. 3",300,-300.,300.,300,-300.,300.);
-  new TH2F("h1004","Y VS X hit st. 4",300,-300.,300.,300,-300.,300.);
-  new TH2F("h1005","Y VS X hit st. 5",300,-300.,300.,300,-300.,300.);
-  //  Histos variance dans 4      
-  new TH2F("h11","VAR X st. 4",30,3.0,183.0,100,0.,2.);
-  new TH2F("h12","VAR Y st. 4",30,3.0,183.0,100,0.,600.);
-  new TH2F("h13","VAR PHI st. 4",30,3.0,183.0,100,0.,0.0001);
-  new TH2F("h14","VAR ALM st. 4",30,3.0,183.0,100,0.,0.05);
-  new TH1F("h15","P",30,3.0,183.0);
-  new TH1F("h411","VAR X st. 4",100,-1.42,1.42);
-  new TH1F("h412","VAR Y st. 4",100,-25.,25.);
-  new TH1F("h413","VAR PHI st. 4",100,-0.01,0.01);
-  new TH1F("h414","VAR ALM st. 4",100,-0.23,0.23);
-  // histo2
-  new TH2F("h211","histo2-VAR X st. 4",30,3.0,183.0,100,0.,2.);
-  new TH2F("h212","histo2-VAR Y st. 4",30,3.0,183.0,100,0.,600.);
-  new TH1F("h213","histo2-VAR X st. 4",100,-1.42,1.42);
-  new TH1F("h214","histo2-VAR Y st. 4",100,-25.,25.);
-  new TH1F("h215","histo2-P",30,3.0,183.0);
-
-  //  Histos variance dans 2      
-  new TH2F("h21","VAR X st. 2",30,3.0,183.0,100,0.,3.);
-  new TH2F("h22","VAR Y st. 2",30,3.0,183.0,100,0.,7.);
-  new TH2F("h23","VAR PHI st. 2",30,3.0,183.0,100,0.,0.006);
-  new TH2F("h24","VAR ALM st. 2",30,3.0,183.0,100,0.,0.005);
-  new TH1F("h25","P",30,3.0,183.0);
-  new TH1F("h421","VAR X st. 2",100,-1.72,1.72);
-  new TH1F("h422","VAR Y st. 2",100,-2.7,2.7);
-  new TH1F("h423","VAR PHI st. 2",100,-0.08,0.08);
-  new TH1F("h424","VAR ALM st. 2",100,-0.072,0.072);
-  // histo2
-  new TH2F("h221","histo2-VAR X st. 2",30,3.0,183.0,100,0.,3.);
-  new TH2F("h222","histo2-VAR Y st. 2",30,3.0,183.0,100,0.,7.);
-  new TH1F("h223","histo2-VAR X st. 2",100,-1.72,1.72);
-  new TH1F("h224","histo2-VAR Y st. 2",100,-2.7,2.7);
-  new TH1F("h225","histo2-P",30,3.0,183.0);
-
-  //  Histos variance dans 1      
-  new TH2F("h31","VAR X st. 1",30,3.0,183.0,100,0.,2.);
-  new TH2F("h32","VAR Y st. 1",30,3.0,183.0,100,0.,0.5);
-  new TH2F("h33","VAR PHI st. 1",30,3.0,183.0,100,0.,0.006);
-  new TH2F("h34","VAR ALM st. 1",30,3.0,183.0,100,0.,0.005);
-  new TH1F("h35","P",30,3.0,183.0);
-  new TH1F("h431","VAR X st. 1",100,-1.42,1.42);
-  new TH1F("h432","VAR Y st. 1",100,-0.72,0.72);
-  new TH1F("h433","VAR PHI st. 1",100,-0.08,0.08);
-  new TH1F("h434","VAR ALM st. 1",100,-0.072,0.072);
-  //  Histos variance dans 1      
-  new TH2F("h41","VAR X st. 1 fit 5,4,3,2,V",30,3.0,183.0,100,0.,4.);
-  new TH2F("h42","VAR Y st. 1 fit 5,4,3,2,V",30,3.0,183.0,100,0.,20.);
-  new TH2F("h43","VAR PHI st. 1 fit 5,4,3,2,V",30,3.0,183.0,100,0.,0.005);
-  new TH2F("h44","VAR ALM st. 1 fit 5,4,3,2,V",30,3.0,183.0,100,0.,0.005);
-  new TH1F("h45","P",30,3.0,183.0);
-  new TH1F("h441","VAR X st. 1 fit 5,4,3,2,V",100,-2.,2.);
-  new TH1F("h442","VAR Y st. 1 fit 5,4,3,2,V",100,-4.5,4.5);
-  new TH1F("h443","VAR PHI st. 1 fit 5,4,3,2,V",100,-0.072,0.072);
-  new TH1F("h444","VAR ALM st. 1 fit 5,4,3,2,V",100,-0.072,0.072);
-  // histo2
-  new TH2F("h241","histo2-VAR X st. 1 fit 5,4,3,2,V",30,3.0,183.0,100,0.,4.);
-  new TH2F("h242","histo2-VAR Y st. 1 fit 5,4,3,2,V",30,3.0,183.0,100,0.,20.);
-  new TH1F("h243","histo2-VAR X st. 1 fit 5,4,3,2,V",100,-2.,2.);
-  new TH1F("h244","histo2-VAR Y st. 1 fit 5,4,3,2,V",100,-4.5,4.5);
-  new TH1F("h245","histo2-P",30,3.0,183.0);
-
-  //  Histos variance dans 2      
-  new TH2F("h51","VAR X st. 2 fit 5,4,3,1,V",30,3.0,183.0,100,0.,0.5);
-  new TH2F("h52","VAR Y st. 2 fit 5,4,3,1,V",30,3.0,183.0,100,0.,2.);
-  new TH2F("h53","VAR PHI st. 2 fit 5,4,3,1,V",30,3.0,183.0,100,0.,0.005);
-  new TH2F("h54","VAR ALM st. 2 fit 5,4,3,1,V",30,3.0,183.0,100,0.,0.01);
-  new TH1F("h55","P",30,3.0,183.0);
-  new TH1F("h451","VAR X st. 2 fit 5,4,3,1,V",100,-0.72,0.72);
-  new TH1F("h452","VAR Y st. 2 fit 5,4,3,1,V",100,-1.42,1.42);
-  new TH1F("h453","VAR PHI st. 2 fit 5,4,3,1,V",100,-0.072,0.072);
-  new TH1F("h454","VAR ALM st. 2 fit 5,4,3,1,V",100,-0.1,0.1);
-  new TH1F("h999","PTOT",30,3.0,183.0);
-  // histo2
-  new TH2F("h251","histo2-VAR X st. 2 fit 5,4,3,1,V",30,3.0,183.0,100,0.,0.5);
-  new TH2F("h252","histo2-VAR Y st. 2 fit 5,4,3,1,V",30,3.0,183.0,100,0.,2.);
-  new TH1F("h253","histo2-VAR X st. 2 fit 5,4,3,1,V",100,-0.72,0.72);
-  new TH1F("h254","histo2-VAR Y st. 2 fit 5,4,3,1,V",100,-1.42,1.42);
-  new TH1F("h255","histo2-P",30,3.0,183.0);
-  //  Histos variance dans 3      
-  new TH2F("h61","VAR X st. 3 fit 4,5,V",30,3.0,183.0,100,0.,5.);
-  new TH2F("h62","VAR Y st. 3 fit 4,5,V",30,3.0,183.0,100,0.,2.);
-  new TH2F("h63","VAR PHI st. 3 fit 4,5,V",30,3.0,183.0,100,0.,0.0006);
-  new TH2F("h64","VAR ALM st. 3 fit 4,5,V",30,3.0,183.0,100,0.,0.0006);
-  new TH1F("h65","P",30,3.0,183.0);
-  new TH1F("h461","VAR X st. 3 fit 4,5,V",100,-2.25,2.25);
-  new TH1F("h462","VAR Y st. 3 fit 4,5,V",100,-1.42,1.42);
-  new TH1F("h463","VAR PHI st. 3 fit 4,5,V",100,-0.024,0.024);
-  new TH1F("h464","VAR ALM st. 3 fit 4,5,V",100,-0.024,0.024);
-  // histo2
-  new TH2F("h261","histo2-VAR X st. 3 fit 4,5,V",30,3.0,183.0,100,0.,5.);
-  new TH2F("h262","histo2-VAR Y st. 3 fit 4,5,V",30,3.0,183.0,100,0.,2.);
-  new TH1F("h263","histo2-VAR X st. 3 fit 4,5,V",100,-2.25,2.25);
-  new TH1F("h264","histo2-VAR Y st. 3 fit 4,5,V",100,-1.42,1.42);
-  new TH1F("h265","Phisto2-",30,3.0,183.0);
-  // Histos dx,dy distribution between chambers inside stations
-  new TH1F("h71","DX in st. ID-70",100,-5.,5.);
-  new TH1F("h81","DY in st. ID-80",100,-5.,5.);
-  new TH1F("h72","DX in st. ID-70",100,-5.,5.);
-  new TH1F("h82","DY in st. ID-80",100,-5.,5.);
-  new TH1F("h73","DX in st. ID-70",100,-5.,5.);
-  new TH1F("h83","DY in st. ID-80",100,-5.,5.);
-  new TH1F("h74","DX in st. ID-70",100,-5.,5.);
-  new TH1F("h84","DY in st. ID-80",100,-5.,5.);
-  new TH1F("h75","DX in st. ID-70",100,-5.,5.);
-  new TH1F("h85","DY in st. ID-80",100,-5.,5.);
+  /// Compute the vertex resolution square from natural vertex dispersion and
+  /// multiple scattering effets according to trackCandidate path in absorber
+  /// It is necessary to account for multiple scattering effects here instead of during the fit of
+  /// the "trackCandidate" to do not influence the result by changing track resolution at vertex
+  AliDebug(1,"Enter SetVertexForFit");
+  
+  Double_t nonBendingReso2 = GetRecoParam()->GetNonBendingVertexDispersion() *
+                             GetRecoParam()->GetNonBendingVertexDispersion();
+  Double_t bendingReso2 = GetRecoParam()->GetBendingVertexDispersion() *
+                         GetRecoParam()->GetBendingVertexDispersion();
+  
+  // add multiple scattering effets
+  AliMUONTrackParam paramAtVertex(*((AliMUONTrackParam*)(trackCandidate.GetTrackParamAtCluster()->First())));
+  paramAtVertex.DeleteCovariances(); // to be sure to account only for multiple scattering
+  if (!AliMUONTrackExtrap::ExtrapToZ(&paramAtVertex,AliMUONConstants::AbsZEnd())) {
+    nonBendingReso2 = 0.;
+    bendingReso2 = 0.;
+  } else {
+    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 chfnt(Int_t &ievr, Int_t &ntrackr, Int_t *istatr, Int_t *isignr, Float_t *pxr, Float_t *pyr, Float_t *pzr, Float_t *zvr, Float_t *chi2r,  Float_t *pxv, Float_t *pyv, Float_t *pzv)
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::Fit(AliMUONTrack &track, Bool_t includeMCS, Bool_t fitWithVertex, Bool_t calcCov)
 {
-  //
-  // fill the ntuple 
-    NtupleSt.ievr = ievr;
-    NtupleSt.ntrackr = ntrackr;
-    for (Int_t i=0; i<500; i++) {
-       NtupleSt.istatr[i] = istatr[i];
-       NtupleSt.isignr[i] = isignr[i]; 
-       NtupleSt.pxr[i]    = pxr[i]; 
-       NtupleSt.pyr[i]    = pyr[i];
-       NtupleSt.pzr[i]    = pzr[i];
-       NtupleSt.zvr[i]    = zvr[i];
-       NtupleSt.chi2r[i]  = chi2r[i];
-       NtupleSt.pxv[i]    = pxv[i]; 
-       NtupleSt.pyv[i]    = pyv[i];
-       NtupleSt.pzv[i]    = pzv[i];
+  /// Fit the track
+  /// w/wo multiple Coulomb scattering according to "includeMCS".
+  /// w/wo constraining the vertex according to "fitWithVertex".
+  /// calculating or not the covariance matrix according to "calcCov".
+  AliDebug(1,"Enter Fit");
+  
+  Double_t benC, errorParam, invBenP, nonBenC, x, y;
+  AliMUONTrackParam *trackParam;
+  Double_t arg[1], fedm, errdef, globalChi2;
+  Int_t npari, nparx;
+  Int_t status, covStatus;
+  
+  // Instantiate gMinuit if not already done
+  if (!gMinuit) gMinuit = new TMinuit(6);
+  // Clear MINUIT parameters
+  gMinuit->mncler();
+  // Give the fitted track to MINUIT
+  gMinuit->SetObjectFit(&track);
+  if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 2) || (AliLog::GetGlobalDebugLevel() >= 2)) {
+    // Define print level
+    arg[0] = 1;
+    gMinuit->mnexcm("SET PRI", arg, 1, status);
+    // Print covariance matrix
+    gMinuit->mnexcm("SHO COV", arg, 0, status);
+  } else {
+    arg[0] = -1;
+    gMinuit->mnexcm("SET PRI", arg, 1, status);
+  }
+  // No warnings
+  gMinuit->mnexcm("SET NOW", arg, 0, status);
+  // Define strategy
+  //arg[0] = 2;
+  //gMinuit->mnexcm("SET STR", arg, 1, status);
+  
+  // set flag w/wo multiple scattering according to "includeMCS"
+  track.FitWithMCS(includeMCS);
+  if (includeMCS) {
+    // compute cluster weights only once
+    if (!track.UpdateTrackParamAtCluster() || !track.ComputeClusterWeights()) {
+      AliWarning("cannot take into account the multiple scattering effects");
+      track.FitWithMCS(kFALSE);
     }
-    gAliNtupleGlobal->Fill();   
+  }
+  
+  track.FitWithVertex(fitWithVertex);
+  if (fitWithVertex) SetVertexErrXY2ForFit(track);
+  
+  // Set fitting function
+  gMinuit->SetFCN(TrackChi2);
+  
+  // Set fitted parameters (!! The order is very important for the covariance matrix !!)
+  // Mandatory limits to avoid NaN values of parameters
+  trackParam = (AliMUONTrackParam*) (track.GetTrackParamAtCluster()->First());
+  Double_t maxIBM = 1. / GetRecoParam()->GetMinBendingMomentum();
+  gMinuit->mnparm(0, "X", trackParam->GetNonBendingCoor(), 0.03, -500.0, 500.0, status);
+  gMinuit->mnparm(1, "NonBenS", trackParam->GetNonBendingSlope(), 0.001, -1., 1., status);
+  gMinuit->mnparm(2, "Y", trackParam->GetBendingCoor(), 0.10, -500.0, 500.0, status);
+  gMinuit->mnparm(3, "BenS", trackParam->GetBendingSlope(), 0.001, -1.5, 1.5, status);
+  gMinuit->mnparm(4, "InvBenP", trackParam->GetInverseBendingMomentum(), 0.003, -maxIBM, maxIBM, status);
+  
+  // minimization
+  gMinuit->mnexcm("MIGRAD", arg, 0, status);
+  
+  // Calculate the covariance matrix more accurately if required
+  if (calcCov) gMinuit->mnexcm("HESSE", arg, 0, status);
+   
+  // get results into "invBenP", "benC", "nonBenC" ("x", "y")
+  gMinuit->GetParameter(0, x, errorParam);
+  trackParam->SetNonBendingCoor(x);
+  gMinuit->GetParameter(1, nonBenC, errorParam);
+  trackParam->SetNonBendingSlope(nonBenC);
+  gMinuit->GetParameter(2, y, errorParam);
+  trackParam->SetBendingCoor(y);
+  gMinuit->GetParameter(3, benC, errorParam);
+  trackParam->SetBendingSlope(benC);
+  gMinuit->GetParameter(4, invBenP, errorParam);
+  trackParam->SetInverseBendingMomentum(invBenP);
+  
+  // global result of the fit
+  gMinuit->mnstat(globalChi2, fedm, errdef, npari, nparx, covStatus);
+  track.SetGlobalChi2(globalChi2);
+  
+  // Get the covariance matrix if required
+  if (calcCov) {
+    // Covariance matrix according to HESSE status
+    // If problem then keep only the diagonal terms (variances)
+    Double_t matrix[5][5];
+    for (Int_t i=0; i<5; i++) for (Int_t j=0; j<5; j++) matrix[i][j] = 0.;
+    gMinuit->mnemat(&matrix[0][0],5);
+    if (covStatus == 3) trackParam->SetCovariances(matrix);
+    else trackParam->SetVariances(matrix);
+  } else trackParam->DeleteCovariances();
+  
 }
 
-//________________
-void hist_closed()
+  //__________________________________________________________________________
+void TrackChi2(Int_t & /*nParam*/, Double_t * /*gradient*/, Double_t &chi2, Double_t *param, Int_t /*flag*/)
 {
-  //
-  // write histos and ntuple to "reconst.root" file
-  gAliFileGlobal->Write();
+  /// 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]);
+  if (!trackBeingFitted->UpdateTrackParamAtCluster()) {
+    chi2 = 2.*AliMUONTrack::MaxChi2();
+    return;
+  }
+  
+  // Take the vertex into account in the fit if required
+  if (trackBeingFitted->FitWithVertex()) {
+    Double_t nonBendingReso2,bendingReso2;
+    trackBeingFitted->GetVertexErrXY2(nonBendingReso2,bendingReso2);
+    AliMUONTrackParam paramAtVertex(*trackParamAtCluster);
+    if (nonBendingReso2 != 0. && bendingReso2 != 0. && AliMUONTrackExtrap::ExtrapToZ(&paramAtVertex, 0.)) { // vextex position = (0,0,0)
+      dX = paramAtVertex.GetNonBendingCoor();
+      dY = paramAtVertex.GetBendingCoor();
+      chi2 += dX * dX / nonBendingReso2 + dY * dY / bendingReso2;
+    } else {
+      chi2 = 2.*AliMUONTrack::MaxChi2();
+      return;
+    }
+  }
+  
+  // compute chi2 w/wo multiple scattering
+  chi2 += trackBeingFitted->ComputeGlobalChi2(trackBeingFitted->FitWithMCS());
+  
 }
 
-//________________________________________________________________________
-void trackf_read_fit(Int_t &ievr, Int_t &nev, Int_t &nhittot1, Int_t *izch, Double_t *xgeant, Double_t *ygeant) 
+  //__________________________________________________________________________
+Bool_t AliMUONTrackReconstructor::ComplementTracks(const AliMUONVClusterStore& clusterStore)
 {
-
-  // introduce aliroot variables in fortran common 
-  // tracking study from geant hits 
-  //
-
-  AliMUON *pMUON  = (AliMUON*) gAlice->GetModule("MUON");
-  TTree *treeH = gAlice->TreeH();
-  Int_t ntracks = (Int_t)treeH->GetEntries();
-  cout<<"ntrack="<<ntracks<<endl;
-
-  nhittot1 = 0;
-
-//  Loop over tracks
-  for (Int_t track=0; track<ntracks;track++) {
-      gAlice->ResetHits();
-      treeH->GetEvent(track);
+  /// 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.
+  /// Return kTRUE if one or more tracks have been complemented.
+  AliDebug(1,"Enter ComplementTracks");
+  
+  Int_t chamberId, detElemId;
+  Double_t chi2OfCluster, bestChi2OfCluster;
+  Double_t sigmaCut2 = GetRecoParam()->GetSigmaCutForTracking() *
+                       GetRecoParam()->GetSigmaCutForTracking();
+  Bool_t foundOneCluster, trackModified, hasChanged = kFALSE;
+  AliMUONVCluster* cluster;
+  AliMUONTrackParam *trackParam, *nextTrackParam, copyOfTrackParam, trackParamAtCluster, bestTrackParamAtCluster;
+  
+  AliMUONTrack *track = (AliMUONTrack*) fRecTracksPtr->First();
+  while (track) {
+    trackModified = kFALSE;
+    
+    trackParam = (AliMUONTrackParam*)track->GetTrackParamAtCluster()->First();
+    while (trackParam) {
+      foundOneCluster = kFALSE;
+      bestChi2OfCluster = 2. * sigmaCut2; // 2 because 2 quantities in chi2
+      chamberId = trackParam->GetClusterPtr()->GetChamberId();
+      detElemId = trackParam->GetClusterPtr()->GetDetElemId();
       
-      if (pMUON)  {
-
-//  Loop over hits
-         for(AliMUONHit* mHit=(AliMUONHit*)pMUON->FirstHit(-1); 
-             mHit;
-             mHit=(AliMUONHit*)pMUON->NextHit()) 
-         {
-<<<<<<< AliMUONTrackReconstructor.cxx
-             if (mHit->Chamber() > 10) continue;
-=======
-             if (mHit->fChamber > 10) continue;
->>>>>>> 1.6
-             Int_t ftrack = mHit->Track();
-             Int_t id = gAlice->Particle(ftrack)->GetPdgCode();
-             
-             if (id==kMuonPlus||id==kMuonMinus) {
-                 xgeant[nhittot1]   = mHit->Y();
-                 ygeant[nhittot1]   = mHit->X();
-                 izch[nhittot1]     = mHit->Chamber();
-//               printf("id %d ch %d x %f y %f\n",id,izch[nhittot1],xgeant[nhittot1],ygeant[nhittot1]);  
-                 nhittot1++;
-             }
-         } // hit loop
-      } // if pMUON
-  } // track loop
-
-  ievr=nev;
-  gAliFileGlobal->cd();    
+      // 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) {
+       
+       // Printout for debuging
+       if ((AliLog::GetDebugLevel("MUON","AliMUONTrackReconstructor") >= 1) || (AliLog::GetGlobalDebugLevel() >= 1)) {
+         cout << "ComplementTracks: found one cluster in chamber(1..): " << chamberId+1 << endl;
+         bestTrackParamAtCluster.GetClusterPtr()->Print();
+         cout<<endl<<"Track parameters and covariances at cluster:"<<endl;
+         bestTrackParamAtCluster.GetParameters().Print();
+         bestTrackParamAtCluster.GetCovariances().Print();
+       }
+       
+       trackParam->SetRemovable(kTRUE);
+       bestTrackParamAtCluster.SetRemovable(kTRUE);
+       track->AddTrackParamAtCluster(bestTrackParamAtCluster,*(bestTrackParamAtCluster.GetClusterPtr()));
+       trackModified = kTRUE;
+       hasChanged = kTRUE;
+      }
+      
+      trackParam = nextTrackParam;
+    }
+    
+    // re-fit track parameters if needed
+    if (trackModified) Fit(*track, kTRUE, kFALSE, kTRUE);
+    
+    track = (AliMUONTrack*) fRecTracksPtr->After(track);
+  }
+  
+  return hasChanged;
+  
 }
 
-//______________________________________________________________________________
-void trackf_read_geant(Int_t *itypg, Double_t *xtrg, Double_t *ytrg, Double_t *ptotg, Int_t *idg, Int_t *izch, Double_t *pvert1g, Double_t *pvert2g, Double_t *pvert3g, Double_t *zvertg, Int_t &nhittot1, Double_t *cx, Double_t *cy, Double_t *cz, Int_t &ievr,Int_t &nev,Double_t *xgeant, Double_t *ygeant, Double_t *clsize1, Double_t *clsize2) 
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::ImproveTrack(AliMUONTrack &track)
 {
-  //
-  // introduce aliroot variables in fortran common 
-  // tracking study from geant hits 
-  //
-
-  AliMUON *pMUON  = (AliMUON*) gAlice->GetModule("MUON");
+  /// Improve the given track by removing clusters with local chi2 highter than the defined cut
+  /// Recompute track parameters and covariances at the remaining clusters
+  AliDebug(1,"Enter ImproveTrack");
   
-  //  TTree *treeK = gAlice->TreeK();
-  TTree *treeH = gAlice->TreeH();
-  Int_t ntracks = (Int_t)treeH->GetEntries();
-  cout<<"ntrack="<<ntracks<<endl;
-
-  Int_t maxidg = 0;
-  Int_t nres=0;
+  Double_t localChi2, worstLocalChi2;
+  AliMUONTrackParam *trackParamAtCluster, *worstTrackParamAtCluster;
+  Double_t sigmaCut2 = GetRecoParam()->GetSigmaCutForImprovement() *
+                      GetRecoParam()->GetSigmaCutForImprovement();
   
-//
-//  Loop over tracks
-//
-
-  for (Int_t track=0; track<ntracks;track++) {
-      gAlice->ResetHits();
-      treeH->GetEvent(track);
+  while (!track.IsImproved()) {
+    
+    // identify removable clusters
+    track.TagRemovableClusters(GetRecoParam()->RequestedStationMask());
+    
+    // Update track parameters and covariances
+    if (!track.UpdateCovTrackParamAtCluster()) {
+      AliWarning("unable to update track parameters and covariances --> stop improvement");
+      break;
+    }
+    
+    // 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) {
       
-      if (pMUON)  {
-//
-//  Loop over hits
-//
-         for(AliMUONHit* mHit=(AliMUONHit*)pMUON->FirstHit(-1); 
-             mHit;
-             mHit=(AliMUONHit*)pMUON->NextHit()) 
-         {
-             if (maxidg<=20000) {
-               
-<<<<<<< AliMUONTrackReconstructor.cxx
-               if (mHit->Chamber() > 10) continue;
-=======
-               if (mHit->fChamber > 10) continue;
->>>>>>> 1.6
-               TParticle *particle;
-               Int_t ftrack = mHit->Track();
-               Int_t id = gAlice->Particle(ftrack)->GetPdgCode();
-
-//             if (id==kMuonPlus||id==kMuonMinus) {
-                   
-                   // inversion de x et y car le champ est inverse dans le programme tracking
-                   xtrg[maxidg]   = 0;       
-                   ytrg[maxidg]   = 0;       
-                   xgeant[maxidg]   = mHit->Y();             // x-pos of hit
-                   ygeant[maxidg]   = mHit->X();             // y-pos of hit
-                   clsize1[maxidg]   = 0;     // cluster size on 1-st cathode
-                   clsize2[maxidg]   = 0;     // cluster size on 2-nd cathode
-                   cx[maxidg]     = mHit->Cy();              // Px/P of hit
-                   cy[maxidg]     = mHit->Cx();              // Py/P of hit
-                   cz[maxidg]     = mHit->Cz();              // Pz/P of hit
-                   izch[maxidg]   = mHit->Chamber();         
-                   /*      
-                   Int_t pdgtype  = Int_t(mHit->fParticle); // particle number
-                   itypg[maxidg]  = gMC->IdFromPDG(pdgtype);
-                   */
-                   itypg[maxidg] = 0;
-                    if (id==kMuonPlus) itypg[maxidg]  = 5;
-                   if (id==kMuonMinus) itypg[maxidg]  = 6;
-
-                    //printf("ich, itypg[maxidg] %d %d\n",izch[maxidg],itypg[maxidg]);
-
-                   ptotg[maxidg]  = mHit->Momentum();          // P of hit 
-                   
-                   particle = gAlice->Particle(ftrack);
-                   Float_t thet = particle->Theta();
-                   thet = thet*180./3.1416;
-                   
-                   //cout<<"chambre "<<izch[maxidg]<<"  ptot="<<ptotg[maxidg]<<"   theta="<<thet<<"   phi="<<mHit->fPhi<<" z="<<zz<<endl;          
-                   
-                   Int_t iparent = particle->GetFirstMother();
-                   if (iparent >= 0) {
-                       Int_t ip;
-                       while(1) {
-                           ip=gAlice->Particle(iparent)->GetFirstMother();
-                           if (ip < 0) {
-                               break;
-                           } else {
-                               iparent = ip;
-                           }
-                       }
-                   }
-                   //printf("iparent - %d\n",iparent);
-                   Int_t id1  = ftrack; // numero de la particule generee au vertex
-                   Int_t idum = track+1;
-                   Int_t id2 = gAlice->Particle(iparent)->GetPdgCode();
-
-                   if (id2==443) id2=114;
-                   else id2=116;
-                   
-                    if (id2==116) {
-                     nres++;
-                   }
-                   //printf("id2 %d\n",id2);
-                   idg[maxidg] = 30000*id1+10000*idum+id2;
-                   
-                   pvert1g[maxidg] = particle->Py();      // Px vertex
-                   pvert2g[maxidg] = particle->Px();      // Py vertex  
-                   pvert3g[maxidg] = particle->Pz();      // Pz vertex
-                   zvertg[maxidg]  = particle->Vz();      // z vertex 
-           
-                   //      cout<<"x="<<xgeant[maxidg]<<endl;
-                   //cout<<"y="<<ygeant[maxidg]<<endl;
-                   //cout<<"typ="<<itypg[maxidg]<<endl;
-
-                   maxidg ++;
-
-               }
-             }
-         } // hit loop
-//      } // if pMUON
-  } // track loop first file
-
-  if (gAliTrH1 && gAliHits2 ) { // if background file
-    ntracks =(Int_t)gAliTrH1->GetEntries();
-    printf("Trackf_read - 2-nd file - ntracks %d\n",ntracks);
-
-    //  Loop over tracks
-    for (Int_t track=0; track<ntracks; track++) {
+      // Pick up cluster with the worst chi2
+      localChi2 = trackParamAtCluster->GetLocalChi2();
+      if (localChi2 > worstLocalChi2) {
+       worstLocalChi2 = localChi2;
+       worstTrackParamAtCluster = trackParamAtCluster;
+      }
       
-      if (gAliHits2) gAliHits2->Clear();
-      gAliTrH1->GetEvent(track);
-
-      //  Loop over hits
-      AliMUONHit *mHit;
-      for (int i=0;i<gAliHits2->GetEntriesFast();i++) 
-       {
-         mHit=(AliMUONHit*) (*gAliHits2)[i];
-         if (mHit->Chamber() > 10) continue;
-         if (maxidg<=20000) {
-           
-           // inversion de x et y car le champ est inverse dans le programme tracking !!!!
-           xtrg[maxidg]   = 0;                    // only for reconstructed point
-           ytrg[maxidg]   = 0;                    // only for reconstructed point
-           xgeant[maxidg]   = mHit->Y();           // x-pos of hit
-           ygeant[maxidg]   = mHit->X();           // y-pos of hit
-           clsize1[maxidg]   = 0;           // cluster size on 1-st cathode
-           clsize2[maxidg]   = 0;           // cluster size on 2-nd cathode
-           cx[maxidg]     = mHit->Cy();            // Px/P of hit
-           cy[maxidg]     = mHit->Cx();            // Py/P of hit
-           cz[maxidg]     = mHit->Cz();            // Pz/P of hit
-           izch[maxidg]   = mHit->Chamber();       // chamber number
-           ptotg[maxidg]  = mHit->Momentum();      // P of hit 
-           
-           Int_t ftrack = mHit->Track();
-           Int_t id1  = ftrack;                   // track number 
-           Int_t idum = track+1;
-           
-           TClonesArray *fPartArray = gAliParticles2;
-//         TParticle *Part=NULL;
-           Int_t id = ((TParticle*) fPartArray->UncheckedAt(ftrack))->GetPdgCode();
-           if (id==kMuonPlus||id==kMuonMinus) {
-               if (id==kMuonPlus) itypg[maxidg]  = 5;
-               else  itypg[maxidg]  = 6;
-           } else itypg[maxidg]=0;
-           
-           Int_t id2=0; // set parent to 0 for background !!
-           idg[maxidg] = 30000*id1+10000*idum+id2;
-           
-
-           pvert1g[maxidg] = 0;      // Px vertex
-           pvert2g[maxidg] = 0;      // Py vertex  
-           pvert3g[maxidg] = 0;      // Pz vertex
-           zvertg[maxidg]  = 0;      // z vertex 
-           maxidg ++;
-
-         } // check limits (maxidg)
-       } // hit loop 
-    } // track loop
-  } // if gAliTrH1
-
-  ievr = nev;
-  nhittot1 = maxidg ;
-  cout<<"nhittot1="<<nhittot1<<endl;
-
-  static Int_t nbres=0;
-  if (nres>=19) nbres++;
-  printf("nres, nbres %d %d \n",nres,nbres);
-
-  gAliFileGlobal->cd();      
-
-}
-
-//________________________________________________________________________
-void trackf_read_spoint(Int_t *itypg, Double_t *xtrg, Double_t *ytrg, Double_t *ptotg, Int_t *idg, Int_t *izch, Double_t *pvert1g, Double_t *pvert2g, Double_t *pvert3g, Double_t *zvertg, Int_t &nhittot1, Double_t *cx, Double_t *cy, Double_t *cz, Int_t &ievr,Int_t &nev,Double_t *xgeant, Double_t *ygeant,Double_t *clsize1, Double_t *clsize2) 
-
-{
-    //
-    // introduce aliroot variables in fortran common 
-    // tracking study from reconstructed points 
-    //
-    AliMUON *pMUON  = (AliMUON*) gAlice->GetModule("MUON");
+    trackParamAtCluster = (AliMUONTrackParam*) track.GetTrackParamAtCluster()->After(trackParamAtCluster);
+    }
+    
+    // Check if worst cluster found
+    if (!worstTrackParamAtCluster) {
+      AliWarning("Bad local chi2 values?");
+      break;
+    }
     
-    cout<<"numero de l'evenement "<<nev<<endl;
+    // Check whether the worst chi2 is under requirement or not
+    if (worstLocalChi2 < 2. * sigmaCut2) { // 2 because 2 quantities in chi2
+      track.SetImproved(kTRUE);
+      break;
+    }
     
-    TTree *treeR = gAlice->TreeR();
-    Int_t nent=(Int_t)treeR->GetEntries();
-    if (nev < 10) 
-       printf("Found %d entries in the tree (must be one per cathode per event! + 1empty)\n",
-              nent);
-//
+    // if the worst cluster is not removable then stop improvement
+    if (!worstTrackParamAtCluster->IsRemovable()) break;
     
-    Int_t mult1, mult2;
+    // Remove the worst cluster
+    track.RemoveTrackParamAtCluster(worstTrackParamAtCluster);
     
-    if (pMUON) {
-       Int_t mpoi=0;
-       for (Int_t ich=0;ich<10;ich++) {
-           printf("chambre %d\n",ich+1);
-           TClonesArray *reconstPoints  = pMUON->RawClustAddress(ich);
-
-           pMUON->ResetRawClusters();
-           treeR->GetEvent(nent-1);
-           Int_t npoints = (Int_t) reconstPoints->GetEntries();
-           if (!npoints) continue;
-           printf("\n ch %d npoints = %d\n",ich+1,npoints);
-           //  Loop over reconstruted points
-           for (Int_t ipoi=0; ipoi<npoints; ipoi++) {
-               printf("  point %d\n",ipoi);
-               AliMUONRawCluster* point = 
-                   (AliMUONRawCluster*) reconstPoints->UncheckedAt(ipoi);
-               
-               mult1=point->fMultiplicity[0];
-               mult2=point->fMultiplicity[1];        
-               xtrg[mpoi]=(Double_t) point->fY[0];
-               ytrg[mpoi]=(Double_t) point->fX[0];
-               izch[mpoi]=ich+1;
-               Int_t itrack  = point->fTracks[1];
-               Int_t ihit    = point->fTracks[0];
-               xgeant[mpoi] = 0;
-               ygeant[mpoi] = 0;
-               clsize1[mpoi] = mult1;
-               clsize2[mpoi] = mult2;
-               Int_t id1, id2, idum;
-               id1=id2=idum=-1;
-               itypg[mpoi]=0;
-               ihit = ihit-1;
-               if (ihit >=0 && itrack >=0) {
-                   gAlice->ResetHits();
-                   gAlice->TreeH()->GetEvent(itrack);
-                   TClonesArray *pMUONhits  = pMUON->Hits();
-                   AliMUONHit* mHit;
-                   mHit=(AliMUONHit*) (pMUONhits->UncheckedAt(ihit));
-                   Int_t id = (Int_t) mHit->Particle();
-                   xgeant[mpoi] = mHit->Y();          
-                   ygeant[mpoi] = mHit->X(); 
-                   if (id == kMuonPlus)  itypg[mpoi]=5;
-                   if (id == kMuonMinus) itypg[mpoi]=6;
-                   TParticle *particle;
-                   particle = gAlice->Particle(mHit->Track());
-                   TParticle* particleM=gAlice->Particle(particle->GetFirstMother());
-                   Int_t iparent=particleM->GetPdgCode();
-                   printf("\n Particle Id:%d %d \n", id, iparent);
-                   if (iparent == 443) id2=114;
-                   if (iparent == 553) id2=116;
-               }
-               id1=itrack;
-               idum=itrack+1;
-               idg[mpoi] = 30000*id1+10000*idum+id2;
-               mpoi++;
-           } // loop over points
-       } // loop over chamber
-       ievr = nev;
-       cout<<"evenement "<<ievr<<endl;
-       nhittot1 = mpoi;
-       cout<<"nhittot1="<<nhittot1<<endl;
-       
-       treeR->Reset();
-
-       gAliFileGlobal->cd();
-
-    } // if pMUON
+    // 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;
+    }
+    
+  }
+  
 }
 
-//____________________________________________________________________________
-void trackf_fit(Int_t &ivertex, Double_t *pest, Double_t *pstep, Double_t &pxzinv, Double_t &tphi, Double_t &talam, Double_t &xvert, Double_t &yvert)
-{
-  //
-  //  Fit a track candidate with the following input parameters: 
-  //  INPUT :  IVERTEX  : vertex flag, if IVERTEX=1 (XVERT,YVERT) are free paramaters
-  //                                   if IVERTEX=1 (XVERT,YVERT)=(0.,0.) 
-  //           PEST(5)  : starting value of parameters (minuit)
-  //           PSTEP(5) : step size for parameters (minuit)
-  //  OUTPUT : PXZINV,TPHI,TALAM,XVERT,YVERT : fitted value of the parameters
-
-  static Double_t arglist[10];
-  static Double_t c[5] = {0.4, 0.45, 0.45, 90., 90.};
-  static Double_t b1, b2, epxz, efi, exs, exvert, eyvert;
-  TString chname;
-  Int_t ierflg = 0;
-  
-  TMinuit *gMinuit = new TMinuit(5);
-  gMinuit->mninit(5,10,7);
-  gMinuit->SetFCN(fcnf);  // constant m.f.
-
-  arglist[0] = -1;
-  
-  gMinuit->mnexcm("SET PRINT", arglist, 1, ierflg);
-  //      gMinuit->mnseti('track fitting');
-  
-  gMinuit->mnparm(0, "invmom",  pest[0], pstep[0], -c[0], c[0], ierflg);
-  gMinuit->mnparm(1, "azimuth", pest[1], pstep[1], -c[1], c[1], ierflg);
-  gMinuit->mnparm(2, "deep",    pest[2], pstep[2], -c[2], c[2], ierflg);
-  if (ivertex==1) {
-    gMinuit->mnparm(3, "x ", pest[3], pstep[3], -c[3], c[3], ierflg);
-    gMinuit->mnparm(4, "y ", pest[4], pstep[4], -c[4], c[4], ierflg);  
-  }   
-  
-  gMinuit->mnexcm("SET NOGR", arglist, 0, ierflg);
-  gMinuit->mnexcm("MINIMIZE", arglist, 0, ierflg);
-  gMinuit->mnexcm("EXIT" , arglist, 0, ierflg);
-  
-  gMinuit->mnpout(0, chname, pxzinv, epxz, b1, b2, ierflg);
-  gMinuit->mnpout(1, chname, tphi, efi, b1, b2, ierflg);
-  gMinuit->mnpout(2, chname, talam, exs, b1, b2, ierflg);
-  if (ivertex==1) {
-    gMinuit->mnpout(3, chname, xvert, exvert, b1, b2, ierflg);
-    gMinuit->mnpout(4, chname, yvert, eyvert, b1, b2, ierflg);
-  }   
-  
-  delete gMinuit;
-}
-          
-//________________________________________________________________________________
-void fcnf(Int_t &npar, Double_t *grad, Double_t &fval, Double_t *pest, Int_t iflag)
+  //__________________________________________________________________________
+Bool_t AliMUONTrackReconstructor::FinalizeTrack(AliMUONTrack &track)
 {
-  //
-  // function called by trackf_fit
-      Int_t futil = 0;
-      fcn(npar,grad,fval,pest,iflag,futil);
+  /// Recompute track parameters and covariances at each attached cluster
+  /// from those at the first one, if not already done
+  AliDebug(1,"Enter FinalizeTrack");
+  if (!track.IsImproved() && !track.UpdateCovTrackParamAtCluster()) {
+    AliWarning("finalization failed due to extrapolation problem");
+    return kFALSE;
+  }
+  return kTRUE;
 }
 
-//____________________________________________________________________________
-void prec_fit(Double_t &pxzinv, Double_t &fis, Double_t &alams, Double_t &xvert, Double_t &yvert, Double_t &pxzinvf, Double_t &fif, Double_t &alf, Double_t &xvertf, Double_t &yvertf, Double_t &epxzinv, Double_t &efi, Double_t &exs, Double_t &exvert, Double_t &eyvert)
+  //__________________________________________________________________________
+Bool_t AliMUONTrackReconstructor::RefitTrack(AliMUONTrack &track, Bool_t enableImprovement)
 {
-  // 
-  // minuit fits for tracking finding 
-                                                                            
-      static Double_t arglist[10];
-      static Double_t c1[5] = {0.001, 0.001, 0.001, 1., 1.};
-      static Double_t c2[5] = {0.5, 0.5, 0.5, 120., 120.};
-      static Double_t emat[9];
-      static Double_t b1, b2;
-      Double_t fmin, fedm, errdef; 
-      Int_t npari, nparx, istat;
-
-      TString chname;
-      Int_t ierflg = 0;
-      
-      TMinuit *gMinuit = new TMinuit(5);
-      gMinuit->mninit(5,10,7);
-      gMinuit->SetFCN(fcnfitf);
-
-      arglist[0] = -1.;
-      gMinuit->mnexcm("SET PRINT", arglist, 1, ierflg);
-      
-      //      gMinuit->mnseti('track fitting');
-
-      gMinuit->mnparm(0,"invmom",   pxzinv, c1[0], -c2[0], c2[0], ierflg); // 0.003, 0.5
-      gMinuit->mnparm(1,"azimuth ", fis,    c1[1], -c2[1], c2[1], ierflg);
-      gMinuit->mnparm(2,"deep    ", alams,  c1[2], -c2[2], c2[2], ierflg);
-      gMinuit->mnparm(3,"xvert",    xvert,  c1[3], -c2[3], c2[3], ierflg);
-      gMinuit->mnparm(4,"yvert",    yvert,  c1[4], -c2[4], c2[4], ierflg);
-
-      gMinuit->mnexcm("SET NOGR", arglist, 0, ierflg);
-      arglist[0] = 2.;
-      gMinuit->mnexcm("MINIMIZE", arglist, 0, ierflg);
-      gMinuit->mnexcm("EXIT", arglist, 0, ierflg);
-      gMinuit->mnpout(0, chname, pxzinvf, epxzinv, b1, b2, ierflg);
-      gMinuit->mnpout(1, chname, fif, efi, b1, b2, ierflg);
-      gMinuit->mnpout(2, chname, alf, exs, b1, b2, ierflg);
-      gMinuit->mnpout(3, chname, xvertf, exvert, b1, b2, ierflg);
-      gMinuit->mnpout(4, chname, yvertf, eyvert, b1, b2, ierflg);
-  
-      gMinuit->mnemat(emat, 3);
-      gMinuit->mnstat(fmin, fedm, errdef, npari, nparx, istat);
-
-     delete gMinuit;
+  /// re-fit the given track
+  
+  // check validity of the track
+  if (track.GetNClusters() < 3) {
+    AliWarning("the track does not contain enough clusters --> unable to refit");
+    return kFALSE;
+  }
+  
+  // reset the seed (i.e. parameters at first cluster) before fitting
+  AliMUONTrackParam* firstTrackParam = (AliMUONTrackParam*) track.GetTrackParamAtCluster()->First();
+  if (firstTrackParam->GetInverseBendingMomentum() == 0.) {
+    AliWarning("track parameters at first chamber are not initialized --> unable to refit");
+    return kFALSE;
+  }
+  
+  // compute track parameters at each cluster from parameters at the first one
+  // necessary to compute multiple scattering effect during refitting
+  if (!track.UpdateTrackParamAtCluster()) {
+    AliWarning("bad track refitting due to extrapolation failure");
+    return kFALSE;
+  }
+  
+  // Re-fit the track:
+  // Take into account the multiple scattering
+  // Calculate the track parameter covariance matrix
+  Fit(track, kTRUE, kFALSE, kTRUE);
+  
+  // Improve the reconstructed tracks if required
+  track.SetImproved(kFALSE);
+  if (enableImprovement && GetRecoParam()->ImproveTracks()) ImproveTrack(track);
+  
+  // Fill AliMUONTrack data members
+  if (track.GetGlobalChi2() < AliMUONTrack::MaxChi2()) return FinalizeTrack(track);
+  else {
+    AliWarning("track not finalized due to extrapolation failure");
+    return kFALSE;
+  }
+  
 }
 
-//____________________________________________________________________
-void fcnfitf(Int_t &npar, Double_t *grad, Double_t &fval, Double_t *xval, Int_t iflag)
-{
-  //
-  // function called by prec_fit 
-      Int_t futil = 0;
-      fcnfit(npar,grad,fval,xval,iflag,futil);
-}