]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - MUON/AliMUONTrackReconstructor.cxx
remove AliMUONTriggerCircuit and call to old trigger code
[u/mrichter/AliRoot.git] / MUON / AliMUONTrackReconstructor.cxx
index 438e6b1a9e3cacd2c613dbadf27f049578d45870..d2771f041e31c8948c7b78efde95f6d06a5cda5e 100644 (file)
  * about the suitability of this software for any purpose. It is          *
  * provided "as is" without express or implied warranty.                  *
  **************************************************************************/
-/*
-$Log$
-Revision 1.4  2000/12/21 22:14:38  morsch
-Clean-up of coding rule violations.
 
-Revision 1.3  2000/10/02 21:28:09  fca
-Removal of useless dependecies via forward declarations
+/* $Id$ */
 
-Revision 1.2  2000/06/15 07:58:49  morsch
-Code from MUON-dev joined
-
-Revision 1.1.2.7  2000/06/09 22:06:29  morsch
-Some coding rule violations corrected. Will soon be obsolete.
-
-Revision 1.1.2.6  2000/05/02 07:15:29  morsch
-Put back TH1.h and TH2.h includes.
+////////////////////////////////////
+//
+// MUON track reconstructor in ALICE (class renamed from AliMUONEventReconstructor)
+//
+// This class contains as data:
+// * the parameters for the track reconstruction
+// * a pointer to the array of hits to be reconstructed (the event)
+// * a pointer to the array of segments made with these hits inside each station
+// * a pointer to the array of reconstructed tracks
+//
+// It contains as methods, among others:
+// * MakeEventToBeReconstructed to build the array of hits to be reconstructed
+// * MakeSegments to build the segments
+// * MakeTracks to build the tracks
+//
+////////////////////////////////////
 
-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)
+#include <stdlib.h>
+#include <Riostream.h>
+#include <TDirectory.h>
+#include <TFile.h>
+#include <TMatrixD.h>
 
-Revision 1.1.2.4  2000/02/15 18:01:08  morsch
-Log messages
+#include "AliMUONTrackReconstructor.h"
+#include "AliMUON.h"
+#include "AliMUONConstants.h"
+#include "AliMUONHitForRec.h"
+#include "AliMUONTriggerTrack.h"
+#include "AliMUONTriggerCircuitNew.h"
+#include "AliMUONRawCluster.h"
+#include "AliMUONLocalTrigger.h"
+#include "AliMUONGlobalTrigger.h"
+#include "AliMUONSegment.h"
+#include "AliMUONTrack.h"
+#include "AliMUONTrackHit.h"
+#include "AliMagF.h"
+#include "AliRun.h" // for gAlice
+#include "AliRunLoader.h"
+#include "AliLoader.h"
+#include "AliMUONTrackK.h" 
+#include "AliLog.h"
+
+//************* Defaults parameters for reconstruction
+const Double_t AliMUONTrackReconstructor::fgkDefaultMinBendingMomentum = 3.0;
+const Double_t AliMUONTrackReconstructor::fgkDefaultMaxBendingMomentum = 3000.0;
+const Double_t AliMUONTrackReconstructor::fgkDefaultMaxChi2 = 100.0;
+const Double_t AliMUONTrackReconstructor::fgkDefaultMaxSigma2Distance = 16.0;
+const Double_t AliMUONTrackReconstructor::fgkDefaultBendingResolution = 0.01;
+const Double_t AliMUONTrackReconstructor::fgkDefaultNonBendingResolution = 0.144;
+const Double_t AliMUONTrackReconstructor::fgkDefaultChamberThicknessInX0 = 0.03;
+// Simple magnetic field:
+// Value taken from macro MUONtracking.C: 0.7 T, hence 7 kG
+// Length and Position from reco_muon.F, with opposite sign:
+// Length = ZMAGEND-ZCOIL
+// Position = (ZMAGEND+ZCOIL)/2
+// to be ajusted differently from real magnetic field ????
+const Double_t AliMUONTrackReconstructor::fgkDefaultSimpleBValue = 7.0;
+const Double_t AliMUONTrackReconstructor::fgkDefaultSimpleBLength = 428.0;
+const Double_t AliMUONTrackReconstructor::fgkDefaultSimpleBPosition = 1019.0;
+const Double_t AliMUONTrackReconstructor::fgkDefaultEfficiency = 0.95;
+
+ClassImp(AliMUONTrackReconstructor) // Class implementation in ROOT context
+
+//__________________________________________________________________________
+AliMUONTrackReconstructor::AliMUONTrackReconstructor(AliLoader* loader, AliMUONData* data)
+  : TObject(),
+    fTrackMethod(1), //AZ - tracking method (1-default, 2-Kalman)
+    fMinBendingMomentum(fgkDefaultMinBendingMomentum),
+    fMaxBendingMomentum(fgkDefaultMaxBendingMomentum),
+    fMaxChi2(fgkDefaultMaxChi2),
+    fMaxSigma2Distance(fgkDefaultMaxSigma2Distance),
+    fBendingResolution(fgkDefaultBendingResolution),
+    fNonBendingResolution(fgkDefaultNonBendingResolution),
+    fChamberThicknessInX0(fgkDefaultChamberThicknessInX0),
+    fSimpleBValue(fgkDefaultSimpleBValue),
+    fSimpleBLength(fgkDefaultSimpleBLength),
+    fSimpleBPosition(fgkDefaultSimpleBPosition),
+    fEfficiency(fgkDefaultEfficiency),
+    fHitsForRecPtr(0x0),
+    fNHitsForRec(0),
+    fRecTracksPtr(0x0),
+    fNRecTracks(0),
+    fRecTrackHitsPtr(0x0),
+    fNRecTrackHits(0),
+    fMUONData(data),
+    fLoader(loader),
+    fMuons(0),
+    fTriggerTrack(new AliMUONTriggerTrack())
 
-Revision 1.1.2.3  2000/02/15 17:59:01  morsch
-Log message added
+{
+  // Constructor for class AliMUONTrackReconstructor
+  SetReconstructionParametersToDefaults();
+
+  // Memory allocation for the TClonesArray of hits for reconstruction
+  // Is 10000 the right size ????
+  fHitsForRecPtr = new TClonesArray("AliMUONHitForRec", 10000);
+
+  // Memory allocation for the TClonesArray's of segments in stations
+  // Is 2000 the right size ????
+  for (Int_t st = 0; st < AliMUONConstants::NTrackingCh()/2; st++) {
+    fSegmentsPtr[st] = new TClonesArray("AliMUONSegment", 2000);
+    fNSegments[st] = 0; // really needed or GetEntriesFast sufficient ????
+  }
+  // Memory allocation for the TClonesArray of reconstructed tracks
+  // Is 10 the right size ????
+  fRecTracksPtr = new TClonesArray("AliMUONTrack", 10);
+
+  // Memory allocation for the TClonesArray of hits on reconstructed tracks
+  // Is 100 the right size ????
+  fRecTrackHitsPtr = new TClonesArray("AliMUONTrackHit", 100);
+
+  // Sign of fSimpleBValue according to sign of Bx value at (50,50,-950).
+  Float_t b[3], x[3];
+  x[0] = 50.; x[1] = 50.; x[2] = -950.;
+  gAlice->Field()->Field(x, b);
+  fSimpleBValue = TMath::Sign(fSimpleBValue,(Double_t) b[0]);
+  fSimpleBPosition = TMath::Sign(fSimpleBPosition,(Double_t) x[2]);
+  // See how to get fSimple(BValue, BLength, BPosition)
+  // automatically calculated from the actual magnetic field ????
+
+  AliDebug(1,"AliMUONTrackReconstructor constructed with defaults"); 
+  if ( AliLog::GetGlobalDebugLevel()>0) Dump();
+  AliDebug(1,"Magnetic field from root file:");
+  if ( AliLog::GetGlobalDebugLevel()>0) gAlice->Field()->Dump();
+
+  // initialize container
+  // fMUONData  = new AliMUONData(fLoader,"MUON","MUON");
+  //fMUONData  = data;
+
+  return;
+}
 
-Revision 1.1.2.2  2000/02/15 18:54:56  morsch
-Reference between track contributing to reconstructed hit and particle corrected  
-*/
+  //__________________________________________________________________________
+AliMUONTrackReconstructor::~AliMUONTrackReconstructor(void)
+{
+  // Destructor for class AliMUONTrackReconstructor
+  delete fHitsForRecPtr; // Correct destruction of everything ???? or delete [] ????
+  for (Int_t st = 0; st < AliMUONConstants::NTrackingCh()/2; st++)
+    delete fSegmentsPtr[st]; // Correct destruction of everything ????
 
-#include "AliCallf77.h" 
-#include "AliMUONTrackReconstructor.h" 
-#include "AliRun.h"
-#include "AliMUON.h"
-#include "AliMC.h"
+  delete fTriggerTrack;
+}
 
-#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"
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::SetReconstructionParametersToDefaults(void)
 {
-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 &);
+  // Set reconstruction parameters to default values
+  // Would be much more convenient with a structure (or class) ????
+
+  // ******** Parameters for making HitsForRec
+  // minimum radius,
+  // like in TRACKF_STAT:
+  // 2 degrees for stations 1 and 2, or ch(0...) from 0 to 3;
+  // 30 cm for stations 3 to 5, or ch(0...) from 4 to 9
+  for (Int_t ch = 0; ch < AliMUONConstants::NTrackingCh(); ch++) {
+    if (ch < 4) fRMin[ch] = TMath::Abs(AliMUONConstants::DefaultChamberZ(ch)) *
+                 2.0 * TMath::Pi() / 180.0;
+    else fRMin[ch] = 30.0;
+    // maximum radius at 10 degrees and Z of chamber
+    fRMax[ch] = TMath::Abs(AliMUONConstants::DefaultChamberZ(ch)) *
+                 10.0 * TMath::Pi() / 180.0;
+  }
+
+  // ******** Parameters for making segments
+  // should be parametrized ????
+  // according to interval between chambers in a station ????
+  // Maximum distance in non bending plane
+  // 5 * 0.22 just to remember the way it was made in TRACKF_STAT
+  // SIGCUT*DYMAX(IZ)
+  for (Int_t st = 0; st < AliMUONConstants::NTrackingCh()/2; st++)
+    fSegmentMaxDistNonBending[st] = 5. * 0.22;
+  // Maximum distance in bending plane:
+  // values from TRACKF_STAT, corresponding to (J psi 20cm),
+  // scaled to the real distance between chambers in a station
+  fSegmentMaxDistBending[0] = TMath::Abs( 1.5 *
+                                         (AliMUONConstants::DefaultChamberZ(1) - AliMUONConstants::DefaultChamberZ(0)) / 20.0);
+  fSegmentMaxDistBending[1] = TMath::Abs( 1.5 *
+                                         (AliMUONConstants::DefaultChamberZ(3) - AliMUONConstants::DefaultChamberZ(2)) / 20.0);
+  fSegmentMaxDistBending[2] = TMath::Abs( 3.0 *
+                                         (AliMUONConstants::DefaultChamberZ(5) - AliMUONConstants::DefaultChamberZ(4)) / 20.0);
+  fSegmentMaxDistBending[3] = TMath::Abs( 6.0 *
+                                         (AliMUONConstants::DefaultChamberZ(7) - AliMUONConstants::DefaultChamberZ(6)) / 20.0);
+  fSegmentMaxDistBending[4] = TMath::Abs( 6.0 *
+                                         (AliMUONConstants::DefaultChamberZ(9) - AliMUONConstants::DefaultChamberZ(8)) / 20.0);
+
+  return;
 }
 
-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
-
-
-// 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;
-
-ClassImp(AliMUONTrackReconstructor)
-
-//___________________________________________________
-AliMUONTrackReconstructor::AliMUONTrackReconstructor()
+//__________________________________________________________________________
+Double_t AliMUONTrackReconstructor::GetImpactParamFromBendingMomentum(Double_t BendingMomentum) const
 {
-// Constructor
-//
-   fSPxzCut   = 3.0;
-   fSSigmaCut = 4.0;
-   fSXPrec    = 0.01; 
-   fSYPrec    = 0.144;
-   fFileName = 0;
+  // Returns impact parameter at vertex in bending plane (cm),
+  // from the signed bending momentum "BendingMomentum" in bending plane (GeV/c),
+  // using simple values for dipole magnetic field.
+  // The sign of "BendingMomentum" is the sign of the charge.
+  return (-0.0003 * fSimpleBValue * fSimpleBLength * fSimpleBPosition /
+         BendingMomentum);
 }
 
-//_____________________________________________________________________________
-void AliMUONTrackReconstructor::Reconst2(Int_t &ifit, Int_t &idebug, Int_t &nev)
+//__________________________________________________________________________
+Double_t AliMUONTrackReconstructor::GetBendingMomentumFromImpactParam(Double_t ImpactParam) const
 {
-//
-//
-    reconstmuon2(ifit,idebug,nev);
+  // Returns signed bending momentum in bending plane (GeV/c),
+  // the sign being the sign of the charge for particles moving forward in Z,
+  // from the impact parameter "ImpactParam" at vertex in bending plane (cm),
+  // using simple values for dipole magnetic field.
+  return (-0.0003 * fSimpleBValue * fSimpleBLength * fSimpleBPosition /
+         ImpactParam);
 }
 
-//_____________________________________________________________________________
-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)
+//__________________________________________________________________________
+void AliMUONTrackReconstructor::EventReconstruct(void)
 {
-  //
-  // 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);
-    }
-    // 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);
-    }
-    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);
-    }
-    // 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();
-    
-  } // end if addBackground
-  
-  // call tracking fortran program
-  reconstmuon(ifit,idebug,nev,idres,ireadgeant);
+  // To reconstruct one event
+  AliDebug(1,"Enter EventReconstruct");
+  ResetTracks(); //AZ
+  ResetTrackHits(); //AZ 
+  ResetSegments(); //AZ
+  ResetHitsForRec(); //AZ
+  MakeEventToBeReconstructed();
+  MakeSegments();
+  MakeTracks();
+  if (fMUONData->IsTriggerTrackBranchesInTree()) 
+    ValidateTracksWithTrigger(); 
+
+  // Add tracks to MUON data container 
+  for(Int_t i=0; i<GetNRecTracks(); i++) {
+    AliMUONTrack * track = (AliMUONTrack*) GetRecTracksPtr()->At(i);
+    fMUONData->AddRecTrack(*track);
+  }
+
+  return;
 }
 
-//________________________________________________________________________________
-void AliMUONTrackReconstructor::Init(Double_t &seff, Double_t &sb0, Double_t &sbl3)
+//__________________________________________________________________________
+void AliMUONTrackReconstructor::EventReconstructTrigger(void)
 {
-  //
-  // 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);
+  // To reconstruct one event
+  AliDebug(1,"Enter EventReconstructTrigger");
+  MakeTriggerTracks();  
+  return;
 }
 
-//__________________________________________
-void AliMUONTrackReconstructor::FinishEvent()
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::ResetHitsForRec(void)
 {
-// Finish
-    TTree *treeK = gAlice->TreeK();
-    TFile *file1 = 0;
-    if (treeK) file1 = treeK->GetCurrentFile();
-    file1->cd();
+  // To reset the array and the number of HitsForRec,
+  // and also the number of HitsForRec
+  // and the index of the first HitForRec per chamber
+  if (fHitsForRecPtr) fHitsForRecPtr->Delete();
+  fNHitsForRec = 0;
+  for (Int_t ch = 0; ch < AliMUONConstants::NTrackingCh(); ch++)
+    fNHitsForRecPerChamber[ch] = fIndexOfFirstHitForRecPerChamber[ch] = 0;
+  return;
 }
 
-//_____________________________________
-void AliMUONTrackReconstructor::Close()
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::ResetSegments(void)
 {
-  //
-  // write histos and ntuple to "reconst.root" file
-    reco_term();
+  // To reset the TClonesArray of segments and the number of Segments
+  // for all stations
+  for (Int_t st = 0; st < AliMUONConstants::NTrackingCh()/2; st++) {
+    if (fSegmentsPtr[st]) fSegmentsPtr[st]->Clear();
+    fNSegments[st] = 0;
+  }
+  return;
 }
 
-//________________________________________________________
-void chfill(Int_t &id, Float_t &x, Float_t &y, Float_t &w)
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::ResetTracks(void)
 {
-  //
-  // fill histo like hfill in fortran
-    char name[5];
-    sprintf(name,"h%d",id);
-    TH1F *h1 = (TH1F*) gDirectory->Get(name);
-    h1->Fill(x);
+  // To reset the TClonesArray of reconstructed tracks
+  if (fRecTracksPtr) fRecTracksPtr->Delete();
+  // Delete in order that the Track destructors are called,
+  // hence the space for the TClonesArray of pointers to TrackHit's is freed
+  fNRecTracks = 0;
+  return;
 }
 
-//_________________________________________________________
-void chfill2(Int_t &id, Float_t &x, Float_t &y, Float_t &w)
+
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::ResetTrackHits(void)
 {
-  //
-  // 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);
+  // To reset the TClonesArray of hits on reconstructed tracks
+  if (fRecTrackHitsPtr) fRecTrackHitsPtr->Clear();
+  fNRecTrackHits = 0;
+  return;
 }
 
-//__________________________________________
-void chf1(Int_t &id, Float_t &x, Float_t &w)
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::MakeEventToBeReconstructed(void)
 {
-  //
-  // fill histo like hf1 in fortran
-    char name[5];
-    sprintf(name,"h%d",id);
-    TH1F *h1 = (TH1F*) gDirectory->Get(name);
-    h1->Fill(x,w);
+  // To make the list of hits to be reconstructed,
+  // either from the track ref. hits or from the raw clusters
+  // according to the parameter set for the reconstructor
+//   TString evfoldname = AliConfig::GetDefaultEventFolderName();//to be interfaced properly
+  
+//   AliRunLoader* rl = AliRunLoader::GetRunLoader(evfoldname);
+//   if (rl == 0x0)
+//    {
+//      Error("MakeEventToBeReconstructed",
+//            "Can not find Run Loader in Event Folder named %s.",
+//            evfoldname.Data());
+//      return;
+//    }
+//   AliLoader* gime = rl->GetLoader("MUONLoader");
+//   if (gime == 0x0)
+//    {
+//      Error("MakeEventToBeReconstructed","Can not get MUON Loader from Run Loader.");
+//      return;
+//    }
+  AliRunLoader *runLoader = fLoader->GetRunLoader();
+
+  AliDebug(1,"Enter MakeEventToBeReconstructed");
+  //AZ ResetHitsForRec();
+  // Reconstruction from raw clusters
+  // AliMUON *MUON  = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
+  // Security on MUON ????
+  // TreeR assumed to be be "prepared" in calling function
+  // by "MUON->GetTreeR(nev)" ????
+  TTree *treeR = fLoader->TreeR();
+
+  //AZ? fMUONData->SetTreeAddress("RC");
+  AddHitsForRecFromRawClusters(treeR);
+  // No sorting: it is done automatically in the previous function
+  
+  AliDebug(1,"End of MakeEventToBeReconstructed");
+    if (AliLog::GetGlobalDebugLevel() > 0) {
+      AliDebug(1, Form("NHitsForRec: %d",fNHitsForRec));
+      for (Int_t ch = 0; ch < AliMUONConstants::NTrackingCh(); ch++) {
+       AliDebug(1, Form("Chamber(0...): %d",ch));
+       AliDebug(1, Form("NHitsForRec: %d", fNHitsForRecPerChamber[ch]));
+       AliDebug(1, Form("Index(first HitForRec): %d", fIndexOfFirstHitForRecPerChamber[ch]));
+       for (Int_t hit = fIndexOfFirstHitForRecPerChamber[ch];
+            hit < fIndexOfFirstHitForRecPerChamber[ch] + fNHitsForRecPerChamber[ch];
+            hit++) {
+         AliDebug(1, Form("HitForRec index(0...): %d",hit));
+         ((*fHitsForRecPtr)[hit])->Dump();
+      }
+    }
+  }
+  return;
 }
 
-//_________________
-void hist_create()
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::SortHitsForRecWithIncreasingChamber()
 {
-  //
-  // 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.);
+  // Sort HitsForRec's in increasing order with respect to chamber number.
+  // Uses the function "Compare".
+  // Update the information for HitsForRec per chamber too.
+  Int_t ch, nhits, prevch;
+  fHitsForRecPtr->Sort();
+  for (ch = 0; ch < AliMUONConstants::NTrackingCh(); ch++) {
+    fNHitsForRecPerChamber[ch] = 0;
+    fIndexOfFirstHitForRecPerChamber[ch] = 0;
+  }
+  prevch = 0; // previous chamber
+  nhits = 0; // number of hits in current chamber
+  // Loop over HitsForRec
+  for (Int_t hit = 0; hit < fNHitsForRec; hit++) {
+    // chamber number (0...)
+    ch = ((AliMUONHitForRec*)  ((*fHitsForRecPtr)[hit]))->GetChamberNumber();
+    // increment number of hits in current chamber
+    (fNHitsForRecPerChamber[ch])++;
+    // update index of first HitForRec in current chamber
+    // if chamber number different from previous one
+    if (ch != prevch) {
+      fIndexOfFirstHitForRecPerChamber[ch] = hit;
+      prevch = ch;
+    }
+  }
+  return;
 }
 
-//_____________________________________________________________________________
-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::AddHitsForRecFromRawClusters(TTree* TR)
 {
-  //
-  // 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];
+  // To add to the list of hits for reconstruction all the raw clusters
+  // No condition added, like in Fortran TRACKF_STAT,
+  // on the radius between RMin and RMax.
+  AliMUONHitForRec *hitForRec;
+  AliMUONRawCluster *clus;
+  Int_t iclus, nclus, nTRentries;
+  TClonesArray *rawclusters;
+  AliDebug(1,"Enter AddHitsForRecFromRawClusters");
+
+  if (fTrackMethod != 3) { //AZ
+    fMUONData->SetTreeAddress("RC"); //AZ
+    nTRentries = Int_t(TR->GetEntries());
+    if (nTRentries != 1) {
+      AliError(Form("nTRentries = %d not equal to 1 ",nTRentries));
+      exit(0);
     }
-    gAliNtupleGlobal->Fill();   
+    fLoader->TreeR()->GetEvent(0); // only one entry  
+  }
+
+  // Loop over tracking chambers
+  for (Int_t ch = 0; ch < AliMUONConstants::NTrackingCh(); ch++) {
+    // number of HitsForRec to 0 for the chamber
+    fNHitsForRecPerChamber[ch] = 0;
+    // index of first HitForRec for the chamber
+    if (ch == 0) fIndexOfFirstHitForRecPerChamber[ch] = 0;
+    else fIndexOfFirstHitForRecPerChamber[ch] = fNHitsForRec;
+    rawclusters =fMUONData->RawClusters(ch);
+//     pMUON->ResetRawClusters();
+//     TR->GetEvent((Int_t) (TR->GetEntries()) - 1); // to be checked ????
+    nclus = (Int_t) (rawclusters->GetEntries());
+    // Loop over (cathode correlated) raw clusters
+    for (iclus = 0; iclus < nclus; iclus++) {
+      clus = (AliMUONRawCluster*) rawclusters->UncheckedAt(iclus);
+      // new AliMUONHitForRec from raw cluster
+      // and increment number of AliMUONHitForRec's (total and in chamber)
+      hitForRec = new ((*fHitsForRecPtr)[fNHitsForRec]) AliMUONHitForRec(clus);
+      fNHitsForRec++;
+      (fNHitsForRecPerChamber[ch])++;
+      // more information into HitForRec
+      //  resolution: info should be already in raw cluster and taken from it ????
+      //hitForRec->SetBendingReso2(fBendingResolution * fBendingResolution);
+      //hitForRec->SetNonBendingReso2(fNonBendingResolution * fNonBendingResolution);
+      hitForRec->SetBendingReso2(clus->GetErrY() * clus->GetErrY());
+      hitForRec->SetNonBendingReso2(clus->GetErrX() * clus->GetErrX());
+      //  original raw cluster
+      hitForRec->SetChamberNumber(ch);
+      hitForRec->SetHitNumber(iclus);
+      // Z coordinate of the raw cluster (cm)
+      hitForRec->SetZ(clus->GetZ(0));
+      if (AliLog::GetGlobalDebugLevel() > 1) {
+       cout << "chamber (0...): " << ch <<
+         " raw cluster (0...): " << iclus << endl;
+       clus->Dump();
+       cout << "AliMUONHitForRec number (1...): " << fNHitsForRec << endl;
+       hitForRec->Dump();}
+    } // end of cluster loop
+  } // end of chamber loop
+  SortHitsForRecWithIncreasingChamber(); 
+  return;
 }
 
-//________________
-void hist_closed()
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::MakeSegments(void)
 {
-  //
-  // write histos and ntuple to "reconst.root" file
-  gAliFileGlobal->Write();
+  // To make the list of segments in all stations,
+  // from the list of hits to be reconstructed
+  AliDebug(1,"Enter MakeSegments");
+  //AZ ResetSegments();
+  // Loop over stations
+  Int_t nb = (fTrackMethod != 1) ? 3 : 0; //AZ
+  for (Int_t st = nb; st < AliMUONConstants::NTrackingCh()/2; st++) 
+    MakeSegmentsPerStation(st); 
+  if (AliLog::GetGlobalDebugLevel() > 1) {
+    cout << "end of MakeSegments" << endl;
+    for (Int_t st = 0; st < AliMUONConstants::NTrackingCh()/2; st++) {
+      cout << "station(0...): " << st
+          << "  Segments: " << fNSegments[st]
+          << endl;
+      for (Int_t seg = 0;
+          seg < fNSegments[st];
+          seg++) {
+       cout << "Segment index(0...): " << seg << endl;
+       ((*fSegmentsPtr[st])[seg])->Dump();
+      }
+    }
+  }
+  return;
 }
 
-//________________________________________________________________________
-void trackf_read_fit(Int_t &ievr, Int_t &nev, Int_t &nhittot1, Int_t *izch, Double_t *xgeant, Double_t *ygeant) 
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::MakeSegmentsPerStation(Int_t Station)
 {
+  // To make the list of segments in station number "Station" (0...)
+  // from the list of hits to be reconstructed.
+  // Updates "fNSegments"[Station].
+  // Segments in stations 4 and 5 are sorted
+  // according to increasing absolute value of "impact parameter"
+  AliMUONHitForRec *hit1Ptr, *hit2Ptr;
+  AliMUONSegment *segment;
+  Bool_t last2st;
+  Double_t bendingSlope, distBend, distNonBend, extBendCoor, extNonBendCoor,
+      impactParam = 0., maxImpactParam = 0., minImpactParam = 0.; // =0 to avoid compilation warnings.
+  AliDebug(1,Form("Enter MakeSegmentsPerStation (0...) %d",Station));
+  // first and second chambers (0...) in the station
+  Int_t ch1 = 2 * Station;
+  Int_t ch2 = ch1 + 1;
+  // variable true for stations downstream of the dipole:
+  // Station(0..4) equal to 3 or 4
+  if ((Station == 3) || (Station == 4)) {
+    last2st = kTRUE;
+    // maximum impact parameter (cm) according to fMinBendingMomentum...
+    maxImpactParam =
+      TMath::Abs(GetImpactParamFromBendingMomentum(fMinBendingMomentum));
+    // minimum impact parameter (cm) according to fMaxBendingMomentum...
+    minImpactParam =
+      TMath::Abs(GetImpactParamFromBendingMomentum(fMaxBendingMomentum));
+  }
+  else last2st = kFALSE;
+  // extrapolation factor from Z of first chamber to Z of second chamber
+  // dZ to be changed to take into account fine structure of chambers ????
+  Double_t extrapFact;
+  // index for current segment
+  Int_t segmentIndex = 0;
+  // Loop over HitsForRec in the first chamber of the station
+  for (Int_t hit1 = fIndexOfFirstHitForRecPerChamber[ch1];
+       hit1 < fIndexOfFirstHitForRecPerChamber[ch1] + fNHitsForRecPerChamber[ch1];
+       hit1++) {
+    // pointer to the HitForRec
+    hit1Ptr = (AliMUONHitForRec*) ((*fHitsForRecPtr)[hit1]);
+    // extrapolation,
+    // on the straight line joining the HitForRec to the vertex (0,0,0),
+    // to the Z of the second chamber of the station
+    // Loop over HitsForRec in the second chamber of the station
+    for (Int_t hit2 = fIndexOfFirstHitForRecPerChamber[ch2];
+        hit2 < fIndexOfFirstHitForRecPerChamber[ch2] + fNHitsForRecPerChamber[ch2];
+        hit2++) {
+      // pointer to the HitForRec
+      hit2Ptr = (AliMUONHitForRec*) ((*fHitsForRecPtr)[hit2]);
+      // absolute values of distances, in bending and non bending planes,
+      // between the HitForRec in the second chamber
+      // and the previous extrapolation
+      extrapFact = hit2Ptr->GetZ()/ hit1Ptr->GetZ();
+      extBendCoor = extrapFact * hit1Ptr->GetBendingCoor();
+      extNonBendCoor = extrapFact * hit1Ptr->GetNonBendingCoor();
+      distBend = TMath::Abs(hit2Ptr->GetBendingCoor() - extBendCoor);
+      distNonBend = TMath::Abs(hit2Ptr->GetNonBendingCoor() - extNonBendCoor);
+      if (last2st) {
+       // bending slope
+       if ( hit1Ptr->GetZ() - hit2Ptr->GetZ() != 0.0 ) {
+         bendingSlope = (hit1Ptr->GetBendingCoor() - hit2Ptr->GetBendingCoor()) /
+           (hit1Ptr->GetZ() - hit2Ptr->GetZ());
+         // absolute value of impact parameter
+         impactParam =
+           TMath::Abs(hit1Ptr->GetBendingCoor() - hit1Ptr->GetZ() * bendingSlope);
+        } 
+        else {
+          AliWarning("hit1Ptr->GetZ() = hit2Ptr->GetZ(): impactParam set to maxImpactParam");
+          impactParam = maxImpactParam;   
+        }   
+      }
+      // check for distances not too large,
+      // and impact parameter not too big if stations downstream of the dipole.
+      // Conditions "distBend" and "impactParam" correlated for these stations ????
+      if ((distBend < fSegmentMaxDistBending[Station]) &&
+         (distNonBend < fSegmentMaxDistNonBending[Station]) &&
+         (!last2st || (impactParam < maxImpactParam)) &&
+         (!last2st || (impactParam > minImpactParam))) {
+       // make new segment
+       segment = new ((*fSegmentsPtr[Station])[segmentIndex])
+         AliMUONSegment(hit1Ptr, hit2Ptr);
+       // update "link" to this segment from the hit in the first chamber
+       if (hit1Ptr->GetNSegments() == 0)
+         hit1Ptr->SetIndexOfFirstSegment(segmentIndex);
+       hit1Ptr->SetNSegments(hit1Ptr->GetNSegments() + 1);
+       if (AliLog::GetGlobalDebugLevel() > 1) {
+         cout << "segmentIndex(0...): " << segmentIndex
+              << "  distBend: " << distBend
+              << "  distNonBend: " << distNonBend
+              << endl;
+         segment->Dump();
+         cout << "HitForRec in first chamber" << endl;
+         hit1Ptr->Dump();
+         cout << "HitForRec in second chamber" << endl;
+         hit2Ptr->Dump();
+       };
+       // increment index for current segment
+       segmentIndex++;
+      }
+    } //for (Int_t hit2
+  } // for (Int_t hit1...
+  fNSegments[Station] = segmentIndex;
+  // Sorting according to "impact parameter" if station(1..5) 4 or 5,
+  // i.e. Station(0..4) 3 or 4, using the function "Compare".
+  // After this sorting, it is impossible to use
+  // the "fNSegments" and "fIndexOfFirstSegment"
+  // of the HitForRec in the first chamber to explore all segments formed with it.
+  // Is this sorting really needed ????
+  if ((Station == 3) || (Station == 4)) (fSegmentsPtr[Station])->Sort();
+  AliDebug(1,Form("Station: %d  NSegments:  %d ", Station, fNSegments[Station]));
+  return;
+}
 
-  // introduce aliroot variables in fortran common 
-  // tracking study from geant hits 
-  //
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::MakeTracks(void)
+{
+  // To make the tracks,
+  // from the list of segments and points in all stations
+  AliDebug(1,"Enter MakeTracks");
+  // The order may be important for the following Reset's
+  //AZ ResetTracks();
+  //AZ ResetTrackHits();
+  if (fTrackMethod != 1) { //AZ - Kalman filter
+    MakeTrackCandidatesK();
+    if (fRecTracksPtr->GetEntriesFast() == 0) return;
+    // Follow tracks in stations(1..) 3, 2 and 1
+    FollowTracksK();
+    // Remove double tracks
+    RemoveDoubleTracksK();
+    // Propagate tracks to the vertex thru absorber
+    GoToVertex();
+    // Fill AliMUONTrack data members
+    FillMUONTrack();
+  } else { 
+    // Look for candidates from at least 3 aligned points in stations(1..) 4 and 5
+    MakeTrackCandidates();
+    // Follow tracks in stations(1..) 3, 2 and 1
+    FollowTracks();
+    // Remove double tracks
+    RemoveDoubleTracks();
+    UpdateTrackParamAtHit();
+    UpdateHitForRecAtHit();
+  }
+  return;
+}
 
-  AliMUON *pMUON  = (AliMUON*) gAlice->GetModule("MUON");
-  TTree *treeH = gAlice->TreeH();
-  Int_t ntracks = (Int_t)treeH->GetEntries();
-  cout<<"ntrack="<<ntracks<<endl;
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::ValidateTracksWithTrigger(void)
+{
+  // Try to match track from tracking system with trigger track
+  AliMUONTrack *track;
+  TClonesArray *recTriggerTracks;
+  
+  fMUONData->SetTreeAddress("RL");
+  fMUONData->GetRecTriggerTracks();
+  recTriggerTracks = fMUONData->RecTriggerTracks();
 
-  nhittot1 = 0;
+  track = (AliMUONTrack*) fRecTracksPtr->First();
+  while (track) {
+    track->MatchTriggerTrack(recTriggerTracks);
+    track = (AliMUONTrack*) fRecTracksPtr->After(track);
+  }
 
-//  Loop over tracks
-  for (Int_t track=0; track<ntracks;track++) {
-      gAlice->ResetHits();
-      treeH->GetEvent(track);
-      
-      if (pMUON)  {
-
-//  Loop over hits
-         for(AliMUONHit* mHit=(AliMUONHit*)pMUON->FirstHit(-1); 
-             mHit;
-             mHit=(AliMUONHit*)pMUON->NextHit()) 
-         {
-             if (mHit->fChamber > 10) continue;
-             TClonesArray *fPartArray = gAlice->Particles();
-             Int_t ftrack = mHit->Track();
-             Int_t id = ((TParticle*) fPartArray->UncheckedAt(ftrack))->GetPdgCode();
-             
-             if (id==kMuonPlus||id==kMuonMinus) {
-                 xgeant[nhittot1]   = mHit->Y();
-                 ygeant[nhittot1]   = mHit->X();
-                 izch[nhittot1]     = mHit->fChamber;
-//               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();    
 }
 
-//______________________________________________________________________________
-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) 
+  //__________________________________________________________________________
+Bool_t AliMUONTrackReconstructor::MakeTriggerTracks(void)
 {
-  //
-  // introduce aliroot variables in fortran common 
-  // tracking study from geant hits 
-  //
+    // To make the trigger tracks from Local Trigger
+  AliDebug(1, "Enter MakeTriggerTracks");
+    
+    Int_t nTRentries;
+    Long_t gloTrigPat;
+    TClonesArray *localTrigger;
+    TClonesArray *globalTrigger;
+    AliMUONLocalTrigger *locTrg;
+    AliMUONGlobalTrigger *gloTrg;
+
+    TTree* treeR = fLoader->TreeR();
+    
+    // Loading MUON subsystem
+    AliMUON * pMUON = (AliMUON *) gAlice->GetDetector("MUON");
 
-  AliMUON *pMUON  = (AliMUON*) gAlice->GetModule("MUON");
-  
-  //  TTree *treeK = gAlice->TreeK();
-  TTree *treeH = gAlice->TreeH();
-  Int_t ntracks = (Int_t)treeH->GetEntries();
-  cout<<"ntrack="<<ntracks<<endl;
+    nTRentries = Int_t(treeR->GetEntries());
+     
+    treeR->GetEvent(0); // only one entry  
+
+    if (!(fMUONData->IsTriggerBranchesInTree())) {
+      AliWarning(Form("Trigger information is not avalaible, nTRentries = %d not equal to 1",nTRentries));
+      return kFALSE;
+    }
+
+    fMUONData->SetTreeAddress("TC");
+    fMUONData->GetTrigger();
 
-  Int_t maxidg = 0;
-  Int_t nres=0;
+    // global trigger for trigger pattern
+    gloTrigPat = 0;
+    globalTrigger = fMUONData->GlobalTrigger(); 
+    gloTrg = (AliMUONGlobalTrigger*)globalTrigger->UncheckedAt(0);
+    if (gloTrg)
+      gloTrigPat = gloTrg->GetGlobalPattern();
   
-//
-//  Loop over tracks
-//
 
-  for (Int_t track=0; track<ntracks;track++) {
-      gAlice->ResetHits();
-      treeH->GetEvent(track);
+    // local trigger for tracking 
+    localTrigger = fMUONData->LocalTrigger();    
+    Int_t nlocals = (Int_t) (localTrigger->GetEntries());
+
+    Float_t z11 = AliMUONConstants::DefaultChamberZ(10);
+    Float_t z21 = AliMUONConstants::DefaultChamberZ(12);
+
+    Float_t y11 = 0.;
+    Int_t stripX21 = 0;
+    Float_t y21 = 0.;
+    Float_t x11 = 0.;
+
+    for (Int_t i=0; i<nlocals; i++) { // loop on Local Trigger
+      locTrg = (AliMUONLocalTrigger*)localTrigger->UncheckedAt(i);     
+
+      AliDebug(1, "AliMUONTrackReconstructor::MakeTriggerTrack using NEW trigger \n");
+      AliMUONTriggerCircuitNew * circuit = 
+         &(pMUON->TriggerCircuitNew(locTrg->LoCircuit()-1)); // -1 !!!
+      y11 = circuit->GetY11Pos(locTrg->LoStripX()); 
+      stripX21 = locTrg->LoStripX()+locTrg->LoDev()+1;
+      y21 = circuit->GetY21Pos(stripX21);      
+      x11 = circuit->GetX11Pos(locTrg->LoStripY());
       
-      if (pMUON)  {
-//
-//  Loop over hits
-//
-         for(AliMUONHit* mHit=(AliMUONHit*)pMUON->FirstHit(-1); 
-             mHit;
-             mHit=(AliMUONHit*)pMUON->NextHit()) 
-         {
-             if (maxidg<=20000) {
-               
-               if (mHit->fChamber > 10) continue;
-               TClonesArray *fPartArray = gAlice->Particles();
-               TParticle *particle;
-               Int_t ftrack = mHit->Track();
-               Int_t id = ((TParticle*) fPartArray->UncheckedAt(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->fCyHit;            // Px/P of hit
-                   cy[maxidg]     = mHit->fCxHit;            // Py/P of hit
-                   cz[maxidg]     = mHit->fCzHit;            // Pz/P of hit
-                   izch[maxidg]   = mHit->fChamber; 
-                   /*      
-                   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->fPTot;          // P of hit 
-                   
-                   particle = (TParticle*) fPartArray->UncheckedAt(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=((TParticle*) fPartArray->UncheckedAt(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 = ((TParticle*) fPartArray->UncheckedAt(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++) {
+      AliDebug(1, Form(" MakeTriggerTrack %d %d %d %d %d %f %f %f \n",i,locTrg->LoCircuit(),
+                      locTrg->LoStripX(),locTrg->LoStripX()+locTrg->LoDev()+1,locTrg->LoStripY(),y11, y21, x11));
+      
+      Float_t thetax = TMath::ATan2( x11 , z11 );
+      Float_t thetay = TMath::ATan2( (y21-y11) , (z21-z11) );
       
-      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->fChamber > 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->fCyHit;         // Px/P of hit
-           cy[maxidg]     = mHit->fCxHit;         // Py/P of hit
-           cz[maxidg]     = mHit->fCzHit;         // Pz/P of hit
-           izch[maxidg]   = mHit->fChamber;       // chamber number
-           ptotg[maxidg]  = mHit->fPTot;          // 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();      
+      fTriggerTrack->SetX11(x11);
+      fTriggerTrack->SetY11(y11);
+      fTriggerTrack->SetThetax(thetax);
+      fTriggerTrack->SetThetay(thetay);
+      fTriggerTrack->SetGTPattern(gloTrigPat);
+            
+      fMUONData->AddRecTriggerTrack(*fTriggerTrack);
+    } // end of loop on Local Trigger
+    return kTRUE;    
+}
 
+  //__________________________________________________________________________
+Int_t AliMUONTrackReconstructor::MakeTrackCandidatesWithTwoSegments(AliMUONSegment *BegSegment)
+{
+  // To make track candidates with two segments in stations(1..) 4 and 5,
+  // the first segment being pointed to by "BegSegment".
+  // Returns the number of such track candidates.
+  Int_t endStation, iEndSegment, nbCan2Seg;
+  AliMUONSegment *endSegment;
+  AliMUONSegment *extrapSegment = NULL;
+  AliMUONTrack *recTrack;
+  Double_t mcsFactor;
+  AliDebug(1,"Enter MakeTrackCandidatesWithTwoSegments");
+  // Station for the end segment
+  endStation = 7 - (BegSegment->GetHitForRec1())->GetChamberNumber() / 2;
+  // multiple scattering factor corresponding to one chamber
+  mcsFactor = 0.0136 /
+    GetBendingMomentumFromImpactParam(BegSegment->GetBendingImpact());
+  mcsFactor    = fChamberThicknessInX0 * mcsFactor * mcsFactor;
+  // linear extrapolation to end station
+  // number of candidates with 2 segments to 0
+  nbCan2Seg = 0;
+  // Loop over segments in the end station
+  for (iEndSegment = 0; iEndSegment < fNSegments[endStation]; iEndSegment++) {
+    // pointer to segment
+    endSegment = (AliMUONSegment*) ((*fSegmentsPtr[endStation])[iEndSegment]);
+    // test compatibility between current segment and "extrapSegment"
+    // 4 because 4 quantities in chi2
+    extrapSegment =
+      BegSegment->CreateSegmentFromLinearExtrapToStation(endSegment->GetZ(), mcsFactor);
+    if ((endSegment->
+        NormalizedChi2WithSegment(extrapSegment,
+                                  fMaxSigma2Distance)) <= 4.0) {
+      // both segments compatible:
+      // make track candidate from "begSegment" and "endSegment"
+      AliDebug(2,Form("TrackCandidate with Segment %d in Station(0..) %d", iEndSegment, endStation));
+      // flag for both segments in one track:
+      // to be done in track constructor ????
+      BegSegment->SetInTrack(kTRUE);
+      endSegment->SetInTrack(kTRUE);
+      recTrack = new ((*fRecTracksPtr)[fNRecTracks])
+       AliMUONTrack(BegSegment, endSegment, this);
+      fNRecTracks++;
+      if (AliLog::GetGlobalDebugLevel() > 1) recTrack->RecursiveDump();
+      // increment number of track candidates with 2 segments
+      nbCan2Seg++;
+    }
+    delete extrapSegment; // should not delete HitForRec's it points to !!!!
+  } // for (iEndSegment = 0;...
+  return nbCan2Seg;
 }
 
-//________________________________________________________________________
-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) 
+  //__________________________________________________________________________
+Int_t AliMUONTrackReconstructor::MakeTrackCandidatesWithOneSegmentAndOnePoint(AliMUONSegment *BegSegment)
+{
+  // To make track candidates with one segment and one point
+  // in stations(1..) 4 and 5,
+  // the segment being pointed to by "BegSegment".
+  Int_t ch, ch1, ch2, endStation, iHit, iHitMax, iHitMin, nbCan1Seg1Hit;
+  AliMUONHitForRec *extrapHitForRec= NULL;
+  AliMUONHitForRec *hit;
+  AliMUONTrack *recTrack;
+  Double_t mcsFactor;
+  AliDebug(1,"Enter MakeTrackCandidatesWithOneSegmentAndOnePoint");
+  // station for the end point
+  endStation = 7 - (BegSegment->GetHitForRec1())->GetChamberNumber() / 2;
+  // multiple scattering factor corresponding to one chamber
+  mcsFactor = 0.0136 /
+    GetBendingMomentumFromImpactParam(BegSegment->GetBendingImpact());
+  mcsFactor    = fChamberThicknessInX0 * mcsFactor * mcsFactor;
+  // first and second chambers(0..) in the end station
+  ch1 = 2 * endStation;
+  ch2 = ch1 + 1;
+  // number of candidates to 0
+  nbCan1Seg1Hit = 0;
+  // Loop over chambers of the end station
+  for (ch = ch2; ch >= ch1; ch--) {
+    // limits for the hit index in the loop
+    iHitMin = fIndexOfFirstHitForRecPerChamber[ch];
+    iHitMax = iHitMin + fNHitsForRecPerChamber[ch];
+    // Loop over HitForRec's in the chamber
+    for (iHit = iHitMin; iHit < iHitMax; iHit++) {
+      // pointer to HitForRec
+      hit = (AliMUONHitForRec*) ((*fHitsForRecPtr)[iHit]);
+      // test compatibility between current HitForRec and "extrapHitForRec"
+      // 2 because 2 quantities in chi2
+      // linear extrapolation to chamber
+      extrapHitForRec =
+       BegSegment->CreateHitForRecFromLinearExtrapToChamber( hit->GetZ(), mcsFactor);
+      if ((hit->
+          NormalizedChi2WithHitForRec(extrapHitForRec,
+                                      fMaxSigma2Distance)) <= 2.0) {
+       // both HitForRec's compatible:
+       // make track candidate from begSegment and current HitForRec
+       AliDebug(2, Form("TrackCandidate with HitForRec  %d in Chamber(0..) %d", iHit, ch));
+       // flag for beginning segments in one track:
+       // to be done in track constructor ????
+       BegSegment->SetInTrack(kTRUE);
+       recTrack = new ((*fRecTracksPtr)[fNRecTracks])
+         AliMUONTrack(BegSegment, hit, this);
+       // the right place to eliminate "double counting" ???? how ????
+       fNRecTracks++;
+       if (AliLog::GetGlobalDebugLevel() > 1) recTrack->RecursiveDump();
+       // increment number of track candidates
+       nbCan1Seg1Hit++;
+      }
+      delete extrapHitForRec;
+    } // for (iHit = iHitMin;...
+  } // for (ch = ch2;...
+  return nbCan1Seg1Hit;
+}
 
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::MakeTrackCandidates(void)
 {
-    //
-    // introduce aliroot variables in fortran common 
-    // tracking study from reconstructed points 
-    //
-    AliMUON *pMUON  = (AliMUON*) gAlice->GetModule("MUON");
-    
-    cout<<"numero de l'evenement "<<nev<<endl;
-    
-    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);
-//
-    
-    Int_t mult1, mult2;
-    
-    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) {
-                   TClonesArray *fPartArray = gAlice->Particles();
-                   gAlice->ResetHits();
-                   gAlice->TreeH()->GetEvent(itrack);
-                   TClonesArray *pMUONhits  = pMUON->Hits();
-                   AliMUONHit* mHit;
-                   mHit=(AliMUONHit*) (pMUONhits->UncheckedAt(ihit));
-                   Int_t id = (Int_t) mHit->fParticle;
-                   xgeant[mpoi] = mHit->Y();          
-                   ygeant[mpoi] = mHit->X(); 
-                   if (id == kMuonPlus)  itypg[mpoi]=5;
-                   if (id == kMuonMinus) itypg[mpoi]=6;
-                   TParticle *particle;
-                   particle = (TParticle*) 
-                       (fPartArray->UncheckedAt(mHit->Track()));
-                   TParticle* particleM=(TParticle*) 
-                       (fPartArray->UncheckedAt(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;
+  // To make track candidates
+  // with at least 3 aligned points in stations(1..) 4 and 5
+  // (two Segment's or one Segment and one HitForRec)
+  Int_t begStation, iBegSegment, nbCan1Seg1Hit, nbCan2Seg;
+  AliMUONSegment *begSegment;
+  AliDebug(1,"Enter MakeTrackCandidates");
+  // Loop over stations(1..) 5 and 4 for the beginning segment
+  for (begStation = 4; begStation > 2; begStation--) {
+    // Loop over segments in the beginning station
+    for (iBegSegment = 0; iBegSegment < fNSegments[begStation]; iBegSegment++) {
+      // pointer to segment
+      begSegment = (AliMUONSegment*) ((*fSegmentsPtr[begStation])[iBegSegment]);
+      AliDebug(2,Form("Look for TrackCandidate's with Segment %d  in Station(0..) %d", iBegSegment, begStation));
+      // Look for track candidates with two segments,
+      // "begSegment" and all compatible segments in other station.
+      // Only for beginning station(1..) 5
+      // because candidates with 2 segments have to looked for only once.
+      if (begStation == 4)
+       nbCan2Seg = MakeTrackCandidatesWithTwoSegments(begSegment);
+      // Look for track candidates with one segment and one point,
+      // "begSegment" and all compatible HitForRec's in other station.
+      // Only if "begSegment" does not belong already to a track candidate.
+      // Is that a too strong condition ????
+      if (!(begSegment->GetInTrack()))
+       nbCan1Seg1Hit = MakeTrackCandidatesWithOneSegmentAndOnePoint(begSegment);
+    } // for (iBegSegment = 0;...
+  } // for (begStation = 4;...
+  return;
+}
+
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::FollowTracks(void)
+{
+  // Follow tracks in stations(1..) 3, 2 and 1
+  // too long: should be made more modular !!!!
+  AliMUONHitForRec *bestHit, *extrapHit, *hit;
+  AliMUONSegment *bestSegment, *extrapSegment, *segment;
+  AliMUONTrack *track, *nextTrack;
+  AliMUONTrackParam *trackParam1, trackParam[2], trackParamVertex;
+  // -1 to avoid compilation warnings
+  Int_t ch = -1, chInStation, chBestHit = -1, iHit, iSegment, station, trackIndex; 
+  Double_t bestChi2, chi2, dZ1, dZ2, dZ3, maxSigma2Distance, mcsFactor;
+  Double_t bendingMomentum, chi2Norm = 0.;
+
+  // local maxSigma2Distance, for easy increase in testing
+  maxSigma2Distance = fMaxSigma2Distance;
+  AliDebug(2,"Enter FollowTracks");
+  // Loop over track candidates
+  track = (AliMUONTrack*) fRecTracksPtr->First();
+  trackIndex = -1;
+  while (track) {
+    // Follow function for each track candidate ????
+    trackIndex++;
+    nextTrack = (AliMUONTrack*) fRecTracksPtr->After(track); // prepare next track
+    AliDebug(2,Form("FollowTracks: track candidate(0..): %d", trackIndex));
+    // Fit track candidate
+    track->SetFitMCS(0); // without multiple Coulomb scattering
+    track->SetFitNParam(3); // with 3 parameters (X = Y = 0)
+    track->SetFitStart(0); // from parameters at vertex
+    track->Fit();
+    if (AliLog::GetGlobalDebugLevel()> 2) {
+      cout << "FollowTracks: track candidate(0..): " << trackIndex
+          << " after fit in stations(0..) 3 and 4" << endl;
+      track->RecursiveDump();
+    }
+    // Loop over stations(1..) 3, 2 and 1
+    // something SPECIAL for stations 2 and 1 for majority 3 coincidence ????
+    // otherwise: majority coincidence 2 !!!!
+    for (station = 2; station >= 0; station--) {
+      // Track parameters at first track hit (smallest Z)
+      trackParam1 = ((AliMUONTrackHit*)
+                    (track->GetTrackHitsPtr()->First()))->GetTrackParam();
+      // extrapolation to station
+      trackParam1->ExtrapToStation(station, trackParam);
+      extrapSegment = new AliMUONSegment(); //  empty segment
+      // multiple scattering factor corresponding to one chamber
+      // and momentum in bending plane (not total)
+      mcsFactor = 0.0136 * trackParam1->GetInverseBendingMomentum();
+      mcsFactor        = fChamberThicknessInX0 * mcsFactor * mcsFactor;
+      // Z difference from previous station
+      dZ1 = AliMUONConstants::DefaultChamberZ(2 * station) -
+           AliMUONConstants::DefaultChamberZ(2 * station + 2);
+      // Z difference between the two previous stations
+      dZ2 = AliMUONConstants::DefaultChamberZ(2 * station + 2) -
+           AliMUONConstants::DefaultChamberZ(2 * station + 4);
+      // Z difference between the two chambers in the previous station
+      dZ3 = AliMUONConstants::DefaultChamberZ(2 * station) -
+           AliMUONConstants::DefaultChamberZ(2 * station + 1);
+      extrapSegment->SetBendingCoorReso2(fBendingResolution * fBendingResolution);
+      extrapSegment->
+       SetNonBendingCoorReso2(fNonBendingResolution * fNonBendingResolution);
+      extrapSegment->UpdateFromStationTrackParam
+       (trackParam, mcsFactor, dZ1, dZ2, dZ3, station,
+        trackParam1->GetInverseBendingMomentum());
+      bestChi2 = 5.0;
+      bestSegment = NULL;
+      if (AliLog::GetGlobalDebugLevel() > 2) {
+       cout << "FollowTracks: track candidate(0..): " << trackIndex
+            << " Look for segment in station(0..): " << station << endl;
+      }
+      // Loop over segments in station
+      for (iSegment = 0; iSegment < fNSegments[station]; iSegment++) {
+       // Look for best compatible Segment in station
+       // should consider all possibilities ????
+       // multiple scattering ????
+       // separation in 2 functions: Segment and HitForRec ????
+       segment = (AliMUONSegment*) ((*fSegmentsPtr[station])[iSegment]);
+       // correction of corrected segment (fBendingCoor and fNonBendingCoor)
+       // according to real Z value of "segment" and slopes of "extrapSegment"
+       (&(trackParam[0]))->ExtrapToZ(segment->GetZ());
+       (&(trackParam[1]))->ExtrapToZ(segment->GetZ());
+       extrapSegment->SetBendingCoor((&(trackParam[0]))->GetBendingCoor());
+       extrapSegment->SetNonBendingCoor((&(trackParam[0]))->GetNonBendingCoor());
+       extrapSegment->SetBendingSlope((&(trackParam[0]))->GetBendingSlope());
+       extrapSegment->SetNonBendingSlope((&(trackParam[0]))->GetNonBendingSlope());
+       chi2 = segment->
+         NormalizedChi2WithSegment(extrapSegment, maxSigma2Distance);
+       if (chi2 < bestChi2) {
+         // update best Chi2 and Segment if better found
+         bestSegment = segment;
+         bestChi2 = chi2;
+       }
+      }
+      if (bestSegment) {
+       // best segment found: add it to track candidate
+       (&(trackParam[0]))->ExtrapToZ(bestSegment->GetZ());
+       (&(trackParam[1]))->ExtrapToZ(bestSegment->GetZ());
+       track->AddSegment(bestSegment);
+       // set track parameters at these two TrakHit's
+       track->SetTrackParamAtHit(track->GetNTrackHits() - 2, &(trackParam[0]));
+       track->SetTrackParamAtHit(track->GetNTrackHits() - 1, &(trackParam[1]));
+       AliDebug(3, Form("FollowTracks: track candidate(0..): %d  Added segment in station(0..): %d", trackIndex, station));
+       if (AliLog::GetGlobalDebugLevel()>2) track->RecursiveDump();
+      }
+      else {
+       // No best segment found:
+       // Look for best compatible HitForRec in station:
+       // should consider all possibilities ????
+       // multiple scattering ???? do about like for extrapSegment !!!!
+       extrapHit = new AliMUONHitForRec(); //  empty hit
+       bestChi2 = 3.0;
+       bestHit = NULL;
+       AliDebug(3, Form("FollowTracks: track candidate(0..): %d Segment not found, look for hit in station(0..): %d ", 
+                        trackIndex, station));
        
-       treeR->Reset();
+       // Loop over chambers of the station
+       for (chInStation = 0; chInStation < 2; chInStation++) {
+         ch = 2 * station + chInStation;
+         for (iHit = fIndexOfFirstHitForRecPerChamber[ch];
+              iHit < fIndexOfFirstHitForRecPerChamber[ch] +
+                fNHitsForRecPerChamber[ch];
+              iHit++) {
+           hit = (AliMUONHitForRec*) ((*fHitsForRecPtr)[iHit]);
+           // coordinates of extrapolated hit
+           (&(trackParam[chInStation]))->ExtrapToZ(hit->GetZ());
+           extrapHit->
+             SetBendingCoor((&(trackParam[chInStation]))->GetBendingCoor());
+           extrapHit->
+             SetNonBendingCoor((&(trackParam[chInStation]))->GetNonBendingCoor());
+           // resolutions from "extrapSegment"
+           extrapHit->SetBendingReso2(extrapSegment->GetBendingCoorReso2());
+           extrapHit->SetNonBendingReso2(extrapSegment->GetNonBendingCoorReso2());
+           // Loop over hits in the chamber
+           // condition for hit not already in segment ????
+           chi2 = hit->NormalizedChi2WithHitForRec(extrapHit, maxSigma2Distance);
+           if (chi2 < bestChi2) {
+             // update best Chi2 and HitForRec if better found
+             bestHit = hit;
+             bestChi2 = chi2;
+             chBestHit = chInStation;
+           }
+         }
+       }
+       if (bestHit) {
+         // best hit found: add it to track candidate
+         (&(trackParam[chBestHit]))->ExtrapToZ(bestHit->GetZ());
+         track->AddHitForRec(bestHit);
+         // set track parameters at this TrackHit
+         track->SetTrackParamAtHit(track->GetNTrackHits() - 1,
+                                   &(trackParam[chBestHit]));
+         if (AliLog::GetGlobalDebugLevel() > 2) {
+           cout << "FollowTracks: track candidate(0..): " << trackIndex
+                << " Added hit in station(0..): " << station << endl;
+           track->RecursiveDump();
+         }
+       }
+       else {
+         // Remove current track candidate
+         // and corresponding TrackHit's, ...
+         track->Remove();
+         delete extrapSegment;
+         delete extrapHit;
+         break; // stop the search for this candidate:
+         // exit from the loop over station
+       }
+       delete extrapHit;
+      }
+      delete extrapSegment;
+      // Sort track hits according to increasing Z
+      track->GetTrackHitsPtr()->Sort();
+      // Update track parameters at first track hit (smallest Z)
+      trackParam1 = ((AliMUONTrackHit*)
+                    (track->GetTrackHitsPtr()->First()))->GetTrackParam();
+      bendingMomentum = 0.;
+      if (TMath::Abs(trackParam1->GetInverseBendingMomentum()) > 0.)
+       bendingMomentum = TMath::Abs(1/(trackParam1->GetInverseBendingMomentum()));
+      // Track removed if bendingMomentum not in window [min, max]
+      if ((bendingMomentum < fMinBendingMomentum) || (bendingMomentum > fMaxBendingMomentum)) {
+       track->Remove();
+       break; // stop the search for this candidate:
+       // exit from the loop over station 
+      }
+      // Track fit
+      // with multiple Coulomb scattering if all stations
+      if (station == 0) track->SetFitMCS(1);
+      // without multiple Coulomb scattering if not all stations
+      else track->SetFitMCS(0);
+      track->SetFitNParam(5);  // with 5 parameters (momentum and position)
+      track->SetFitStart(1);  // from parameters at first hit
+      track->Fit();
+      Double_t numberOfDegFree = (2.0 * track->GetNTrackHits() - 5);
+      if (numberOfDegFree > 0) {
+        chi2Norm =  track->GetFitFMin() / numberOfDegFree;
+      } else {
+       chi2Norm = 1.e10;
+      }
+      // Track removed if normalized chi2 too high
+      if (chi2Norm > fMaxChi2) {
+       track->Remove();
+       break; // stop the search for this candidate:
+       // exit from the loop over station 
+      }
+      if (AliLog::GetGlobalDebugLevel() > 2) {
+       cout << "FollowTracks: track candidate(0..): " << trackIndex
+            << " after fit from station(0..): " << station << " to 4" << endl;
+       track->RecursiveDump();
+      }
+      // Track extrapolation to the vertex through the absorber (Branson)
+      // after going through the first station
+      if (station == 0) {
+       trackParamVertex = *trackParam1;
+       (&trackParamVertex)->ExtrapToVertex(0.,0.,0.);
+       track->SetTrackParamAtVertex(&trackParamVertex);
+       if (AliLog::GetGlobalDebugLevel() > 0) {
+         cout << "FollowTracks: track candidate(0..): " << trackIndex
+              << " after extrapolation to vertex" << endl;
+         track->RecursiveDump();
+       }
+      }
+    } // for (station = 2;...
+    // go really to next track
+    track = nextTrack;
+  } // while (track)
+  // Compression of track array (necessary after Remove ????)
+  fRecTracksPtr->Compress();
+  return;
+}
 
-       gAliFileGlobal->cd();
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::RemoveDoubleTracks(void)
+{
+  // To remove double tracks.
+  // Tracks are considered identical
+  // if they have at least half of their hits in common.
+  // Among two identical tracks, one keeps the track with the larger number of hits
+  // or, if these numbers are equal, the track with the minimum Chi2.
+  AliMUONTrack *track1, *track2, *trackToRemove;
+  Bool_t identicalTracks;
+  Int_t hitsInCommon, nHits1, nHits2;
+  identicalTracks = kTRUE;
+  while (identicalTracks) {
+    identicalTracks = kFALSE;
+    // Loop over first track of the pair
+    track1 = (AliMUONTrack*) fRecTracksPtr->First();
+    while (track1 && (!identicalTracks)) {
+      nHits1 = track1->GetNTrackHits();
+      // Loop over second track of the pair
+      track2 = (AliMUONTrack*) fRecTracksPtr->After(track1);
+      while (track2 && (!identicalTracks)) {
+       nHits2 = track2->GetNTrackHits();
+       // number of hits in common between two tracks
+       hitsInCommon = track1->HitsInCommon(track2);
+       // check for identical tracks
+       if ((4 * hitsInCommon) >= (nHits1 + nHits2)) {
+         identicalTracks = kTRUE;
+         // decide which track to remove
+         if (nHits1 > nHits2) trackToRemove = track2;
+         else if (nHits1 < nHits2) trackToRemove = track1;
+         else if ((track1->GetFitFMin()) < (track2->GetFitFMin()))
+           trackToRemove = track2;
+         else trackToRemove = track1;
+         // remove it
+         trackToRemove->Remove();
+       }
+       track2 = (AliMUONTrack*) fRecTracksPtr->After(track2);
+      } // track2
+      track1 = (AliMUONTrack*) fRecTracksPtr->After(track1);
+    } // track1
+  }
+  return;
+}
 
-    } // if pMUON
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::UpdateTrackParamAtHit()
+{
+  // Set track parameters after track fitting. Fill fTrackParamAtHit of AliMUONTrack's
+  AliMUONTrack *track;
+  AliMUONTrackHit *trackHit;
+  AliMUONTrackParam *trackParam;
+  track = (AliMUONTrack*) fRecTracksPtr->First();
+  while (track) {
+    trackHit = (AliMUONTrackHit*) (track->GetTrackHitsPtr())->First();
+    while (trackHit) {
+      trackParam = trackHit->GetTrackParam();
+      track->AddTrackParamAtHit(trackParam);
+      trackHit = (AliMUONTrackHit*) (track->GetTrackHitsPtr())->After(trackHit); 
+    } // trackHit    
+    track = (AliMUONTrack*) fRecTracksPtr->After(track);
+  } // track
+  return;
 }
 
-//____________________________________________________________________________
-void 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)
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::UpdateHitForRecAtHit()
 {
-  //
-  //  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.
+  // Set cluster parameterss after track fitting. Fill fHitForRecAtHit of AliMUONTrack's
+  AliMUONTrack *track;
+  AliMUONTrackHit *trackHit;
+  AliMUONHitForRec *hitForRec;
+  track = (AliMUONTrack*) fRecTracksPtr->First();
+  while (track) {
+    trackHit = (AliMUONTrackHit*) (track->GetTrackHitsPtr())->First();
+    while (trackHit) {
+      hitForRec = trackHit->GetHitForRecPtr();
+      track->AddHitForRecAtHit(hitForRec);
+      trackHit = (AliMUONTrackHit*) (track->GetTrackHitsPtr())->After(trackHit); 
+    } // trackHit    
+    track = (AliMUONTrack*) fRecTracksPtr->After(track);
+  } // track
+  return;
+}
 
-  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);
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::FillMUONTrack()
+{
+  // Set track parameters at hits for Kalman track. Fill fTrackParamAtHit of AliMUONTrack's
+  AliMUONTrackK *track;
+  track = (AliMUONTrackK*) fRecTracksPtr->First();
+  while (track) {
+    track->FillMUONTrack();
+    track = (AliMUONTrackK*) fRecTracksPtr->After(track);
+  } 
+  return;
+}
+
+  //__________________________________________________________________________
+void AliMUONTrackReconstructor::EventDump(void)
+{
+  // Dump reconstructed event (track parameters at vertex and at first hit),
+  // and the particle parameters
+
+  AliMUONTrack *track;
+  AliMUONTrackParam *trackParam, *trackParam1;
+  Double_t bendingSlope, nonBendingSlope, pYZ;
+  Double_t pX, pY, pZ, x, y, z, c;
+  Int_t np, trackIndex, nTrackHits;
+  AliDebug(1,"****** enter EventDump ******");
+  AliDebug(1, Form("Number of Reconstructed tracks : %d", fNRecTracks)); 
   
-  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);
-  }   
+  fRecTracksPtr->Compress(); // for simple loop without "Next" since no hole
+  // Loop over reconstructed tracks
+  for (trackIndex = 0; trackIndex < fNRecTracks; trackIndex++) {
+    if (fTrackMethod != 1) continue; //AZ - skip the rest for now
+    AliDebug(1, Form("track number: %d", trackIndex));
+    // function for each track for modularity ????
+    track = (AliMUONTrack*) ((*fRecTracksPtr)[trackIndex]);
+    nTrackHits = track->GetNTrackHits();
+    AliDebug(1, Form("Number of track hits: %d ", nTrackHits));
+    // track parameters at Vertex
+    trackParam = track->GetTrackParamAtVertex();
+    x = trackParam->GetNonBendingCoor();
+    y = trackParam->GetBendingCoor();
+    z = trackParam->GetZ();
+    bendingSlope = trackParam->GetBendingSlope();
+    nonBendingSlope = trackParam->GetNonBendingSlope();
+    pYZ = 1/TMath::Abs(trackParam->GetInverseBendingMomentum());
+    pZ = pYZ/TMath::Sqrt(1+bendingSlope*bendingSlope);
+    pX = pZ * nonBendingSlope;
+    pY = pZ * bendingSlope;
+    c = TMath::Sign(1.0, trackParam->GetInverseBendingMomentum());
+    AliDebug(1, Form("Track parameters at Vertex z= %f: X= %f Y= %f pX= %f pY= %f pZ= %f c= %f\n",
+                    z, x, y, pX, pY, pZ, c));
+
+    // track parameters at first hit
+    trackParam1 = ((AliMUONTrackHit*)
+                  (track->GetTrackHitsPtr()->First()))->GetTrackParam();
+    x = trackParam1->GetNonBendingCoor();
+    y = trackParam1->GetBendingCoor();
+    z = trackParam1->GetZ();
+    bendingSlope = trackParam1->GetBendingSlope();
+    nonBendingSlope = trackParam1->GetNonBendingSlope();
+    pYZ = 1/TMath::Abs(trackParam1->GetInverseBendingMomentum());
+    pZ = pYZ/TMath::Sqrt(1.0 + bendingSlope * bendingSlope);
+    pX = pZ * nonBendingSlope;
+    pY = pZ * bendingSlope;
+    c = TMath::Sign(1.0, trackParam1->GetInverseBendingMomentum());
+    AliDebug(1, Form("track parameters at z= %f: X= %f Y= %f pX= %f pY= %f pZ= %f c= %f\n",
+                    z, x, y, pX, pY, pZ, c));
+  }
+  // informations about generated particles NO !!!!!!!!
   
-  delete gMinuit;
+//    for (Int_t iPart = 0; iPart < np; iPart++) {
+//      p = gAlice->Particle(iPart);
+//      printf(" particle %d: type= %d px= %f py= %f pz= %f pdg= %d\n",
+//        iPart, p->GetPdgCode(), p->Px(), p->Py(), p->Pz(), p->GetPdgCode());    
+//    }
+  return;
 }
-          
-//________________________________________________________________________________
-void fcnf(Int_t &npar, Double_t *grad, Double_t &fval, Double_t *pest, Int_t iflag)
+
+
+//__________________________________________________________________________
+void AliMUONTrackReconstructor::EventDumpTrigger(void)
 {
-  //
-  // function called by trackf_fit
-      Int_t futil = 0;
-      fcn(npar,grad,fval,pest,iflag,futil);
+  // Dump reconstructed trigger event 
+  // and the particle parameters
+    
+  AliMUONTriggerTrack *triggertrack ;
+  Int_t nTriggerTracks = fMUONData->RecTriggerTracks()->GetEntriesFast();
+  AliDebug(1, "****** enter EventDumpTrigger ******");
+  AliDebug(1, Form("Number of Reconstructed tracks : %d ",  nTriggerTracks));
+  
+  // Loop over reconstructed tracks
+  for (Int_t trackIndex = 0; trackIndex < nTriggerTracks; trackIndex++) {
+    triggertrack = (AliMUONTriggerTrack*)fMUONData->RecTriggerTracks()->At(trackIndex);
+      printf(" trigger track number %i x11=%f y11=%f thetax=%f thetay=%f \n",
+            trackIndex,
+            triggertrack->GetX11(),triggertrack->GetY11(),
+            triggertrack->GetThetax(),triggertrack->GetThetay());      
+  } 
 }
 
-//____________________________________________________________________________
-void 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)
+//__________________________________________________________________________
+void AliMUONTrackReconstructor::MakeTrackCandidatesK(void)
 {
-  // 
-  // 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);
+  // To make initial tracks for Kalman filter from the list of segments
+  Int_t istat, iseg;
+  AliMUONSegment *segment;
+  AliMUONTrackK *trackK;
+
+  AliDebug(1,"Enter MakeTrackCandidatesK");
+
+  AliMUONTrackK a(this, fHitsForRecPtr);
+  // Loop over stations(1...) 5 and 4
+  for (istat=4; istat>=3; istat--) {
+    // Loop over segments in the station
+    for (iseg=0; iseg<fNSegments[istat]; iseg++) {
+      // Transform segments to tracks and evaluate covariance matrix
+      segment = (AliMUONSegment*) ((*fSegmentsPtr[istat])[iseg]);
+      trackK = new ((*fRecTracksPtr)[fNRecTracks++]) AliMUONTrackK(segment);
+    } // for (iseg=0;...)
+  } // for (istat=4;...)
+  return;
+}
 
-      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);
+//__________________________________________________________________________
+void AliMUONTrackReconstructor::FollowTracksK(void)
+{
+  // Follow tracks using Kalman filter
+  Bool_t ok;
+  Int_t icand, ichamBeg = 0, ichamEnd, chamBits;
+  Double_t zDipole1, zDipole2;
+  AliMUONTrackK *trackK;
+  AliMUONHitForRec *hit;
+  AliMUONRawCluster *clus;
+  TClonesArray *rawclusters;
+  clus = 0; rawclusters = 0;
+
+  zDipole1 = GetSimpleBPosition() + GetSimpleBLength()/2;
+  zDipole2 = zDipole1 - GetSimpleBLength();
+
+  // Print hits
+  trackK = (AliMUONTrackK*) ((*fRecTracksPtr)[0]);
+
+  if (trackK->DebugLevel() > 0) {
+    for (Int_t i1=0; i1<fNHitsForRec; i1++) {
+      hit = (AliMUONHitForRec*) ((*fHitsForRecPtr)[i1]);
+      printf(" Hit # %d %10.4f %10.4f %10.4f",
+             hit->GetChamberNumber(), hit->GetBendingCoor(),
+             hit->GetNonBendingCoor(), hit->GetZ());
  
-      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);
+      // from raw clusters
+      rawclusters = fMUONData->RawClusters(hit->GetChamberNumber());
+      clus = (AliMUONRawCluster*) rawclusters->UncheckedAt(hit->
+                                                          GetHitNumber());
+      printf(" %d", clus->GetTrack(1));
+      if (clus->GetTrack(2) != -1) printf(" %d \n", clus->GetTrack(2));
+      else printf("\n");
+     
+    }
+  } // if (trackK->DebugLevel() > 0)
+
+  icand = -1;
+  Int_t nSeeds;
+  nSeeds = fNRecTracks; // starting number of seeds
+  // Loop over track candidates
+  while (icand < fNRecTracks-1) {
+    icand ++;
+    if (trackK->DebugLevel()>0) cout << " *** Kalman track candidate No. " << icand << endl;
+    trackK = (AliMUONTrackK*) ((*fRecTracksPtr)[icand]);
+    if (trackK->GetRecover() < 0) continue; // failed track
+
+    // Discard candidate which will produce the double track
+    /*
+    if (icand > 0) {
+      ok = CheckCandidateK(icand,nSeeds);
+      if (!ok) {
+        trackK->SetRecover(-1); // mark candidate to be removed
+        continue;
+      }
+    }
+    */
+
+    ok = kTRUE;
+    if (trackK->GetRecover() == 0) 
+      hit = (AliMUONHitForRec*) trackK->GetTrackHits()->Last(); // last hit
+    else 
+      hit = trackK->GetHitLastOk(); // hit where track stopped
+
+    if (hit) ichamBeg = hit->GetChamberNumber();
+    ichamEnd = 0;
+    // Check propagation direction
+    if (!hit) { ichamBeg = ichamEnd; AliFatal(" ??? "); }
+    else if (trackK->GetTrackDir() < 0) {
+      ichamEnd = 9; // forward propagation
+      ok = trackK->KalmanFilter(ichamBeg,ichamEnd,kFALSE,zDipole1,zDipole2);
+      if (ok) {
+        ichamBeg = ichamEnd;
+        ichamEnd = 6; // backward propagation
+       // Change weight matrix and zero fChi2 for backpropagation
+        trackK->StartBack();
+       trackK->SetTrackDir(1);
+        ok = trackK->KalmanFilter(ichamBeg,ichamEnd,kTRUE,zDipole1,zDipole2);
+        ichamBeg = ichamEnd;
+        ichamEnd = 0;
+      }
+    } else {
+      if (trackK->GetBPFlag()) {
+       // backpropagation
+        ichamEnd = 6; // backward propagation
+       // Change weight matrix and zero fChi2 for backpropagation
+        trackK->StartBack();
+        ok = trackK->KalmanFilter(ichamBeg,ichamEnd,kTRUE,zDipole1,zDipole2);
+        ichamBeg = ichamEnd;
+        ichamEnd = 0;
+      }
+    }
+
+    if (ok) {
+      trackK->SetTrackDir(1);
+      trackK->SetBPFlag(kFALSE);
+      ok = trackK->KalmanFilter(ichamBeg,ichamEnd,kFALSE,zDipole1,zDipole2);
+    }
+    if (!ok) { trackK->SetRecover(-1); continue; } // mark candidate to be removed
 
-     delete gMinuit;
+    // Apply smoother
+    if (trackK->GetRecover() >= 0) {
+      ok = trackK->Smooth();
+      if (!ok) trackK->SetRecover(-1); // mark candidate to be removed
+    }
+
+    // Majority 3 of 4 in first 2 stations
+    if (!ok) continue;
+    chamBits = 0;
+    Double_t chi2max = 0;
+    for (Int_t i=0; i<trackK->GetNTrackHits(); i++) {
+      hit = (AliMUONHitForRec*) (*trackK->GetTrackHits())[i];
+      chamBits |= BIT(hit->GetChamberNumber());
+      if (trackK->GetChi2PerPoint(i) > chi2max) chi2max = trackK->GetChi2PerPoint(i);
+    }
+    if (!((chamBits&3)==3 || (chamBits>>2&3)==3) && chi2max > 25) {
+      //trackK->Recover();
+      trackK->SetRecover(-1); //mark candidate to be removed
+      continue;
+    }
+    if (ok) trackK->SetTrackQuality(0); // compute "track quality"
+  } // while
+
+  for (Int_t i=0; i<fNRecTracks; i++) {
+    trackK = (AliMUONTrackK*) ((*fRecTracksPtr)[i]);
+    if (trackK->GetRecover() < 0) fRecTracksPtr->RemoveAt(i);
+  }
+
+  // Compress TClonesArray
+  fRecTracksPtr->Compress();
+  fNRecTracks = fRecTracksPtr->GetEntriesFast();
+  return;
+}
+
+//__________________________________________________________________________
+Bool_t AliMUONTrackReconstructor::CheckCandidateK(Int_t icand, Int_t nSeeds) const
+{
+  // Discards track candidate if it will produce the double track (having
+  // the same seed segment hits as hits of a good track found before)
+  AliMUONTrackK *track1, *track2;
+  AliMUONHitForRec *hit1, *hit2, *hit;
+
+  track1 = (AliMUONTrackK*) ((*fRecTracksPtr)[icand]);
+  hit1 = (AliMUONHitForRec*) (*track1->GetTrackHits())[0]; // 1'st hit
+  hit2 = (AliMUONHitForRec*) (*track1->GetTrackHits())[1]; // 2'nd hit
+
+  for (Int_t i=0; i<icand; i++) {
+    track2 = (AliMUONTrackK*) ((*fRecTracksPtr)[i]);
+    //if (track2->GetRecover() < 0) continue;
+    if (track2->GetRecover() < 0 && icand >= nSeeds) continue;
+
+    if (track1->GetStartSegment() == track2->GetStartSegment()) {
+      return kFALSE;
+    } else {
+      Int_t nSame = 0;
+      for (Int_t j=0; j<track2->GetNTrackHits(); j++) {
+        hit = (AliMUONHitForRec*) (*track2->GetTrackHits())[j];
+        if (hit == hit1 || hit == hit2) {
+          nSame++;
+          if (nSame == 2) return kFALSE;
+        }
+      } // for (Int_t j=0;
+    }
+  } // for (Int_t i=0;
+  return kTRUE;
 }
 
-//____________________________________________________________________
-void fcnfitf(Int_t &npar, Double_t *grad, Double_t &fval, Double_t *xval, Int_t iflag)
+//__________________________________________________________________________
+void AliMUONTrackReconstructor::RemoveDoubleTracksK(void)
 {
-  //
-  // function called by prec_fit 
-      Int_t futil = 0;
-      fcnfit(npar,grad,fval,xval,iflag,futil);
+  // Removes double tracks (sharing more than half of their hits). Keeps
+  // the track with higher quality
+  AliMUONTrackK *track1, *track2, *trackToKill;
+
+  // Sort tracks according to their quality
+  fRecTracksPtr->Sort();
+
+  // Loop over first track of the pair
+  track1 = (AliMUONTrackK*) fRecTracksPtr->First();
+  Int_t debug = track1->DebugLevel();
+  while (track1) {
+    // Loop over second track of the pair
+    track2 = (AliMUONTrackK*) fRecTracksPtr->After(track1);
+    while (track2) {
+      // Check whether or not to keep track2
+      if (!track2->KeepTrack(track1)) {
+        if (debug >= 0) cout << " Killed track: " << 1/(*track2->GetTrackParameters())(4,0) <<
+         " " << track2->GetTrackQuality() << endl;
+        trackToKill = track2;
+        track2 = (AliMUONTrackK*) fRecTracksPtr->After(track2);
+        trackToKill->Kill();
+        fRecTracksPtr->Compress();
+      } else track2 = (AliMUONTrackK*) fRecTracksPtr->After(track2);
+    } // track2
+    track1 = (AliMUONTrackK*) fRecTracksPtr->After(track1);
+  } // track1
+
+  fNRecTracks = fRecTracksPtr->GetEntriesFast();
+  if (debug >= 0) cout << " Number of Kalman tracks: " << fNRecTracks << endl;
+}
+
+//__________________________________________________________________________
+void AliMUONTrackReconstructor::GoToVertex(void)
+{
+  // Propagates track to the vertex thru absorber
+  // (using Branson correction for now)
+
+  Double_t zVertex;
+  zVertex = 0;
+  for (Int_t i=0; i<fNRecTracks; i++) {
+    //((AliMUONTrackK*)(*fRecTracksPtr)[i])->Branson();
+    ((AliMUONTrackK*)(*fRecTracksPtr)[i])->SetTrackQuality(1); // compute Chi2
+    //((AliMUONTrackK*)(*fRecTracksPtr)[i])->GoToZ(zVertex); // w/out absorber
+    ((AliMUONTrackK*)(*fRecTracksPtr)[i])->GoToVertex(1); // with absorber
+  }
+}
+
+//__________________________________________________________________________
+void AliMUONTrackReconstructor::SetTrackMethod(Int_t iTrackMethod)
+{
+  // Set track method and recreate track container if necessary
+  
+  fTrackMethod = TMath::Min (iTrackMethod, 3);
+  fTrackMethod = TMath::Max (fTrackMethod, 1);
+  if (fTrackMethod != 1) {
+    if (fRecTracksPtr) delete fRecTracksPtr;
+    fRecTracksPtr = new TClonesArray("AliMUONTrackK", 10);
+    if (fTrackMethod == 2) cout << " *** Tracking with the Kalman filter *** " << endl;
+    else cout << " *** Combined cluster / track finder ***" << endl;
+  } else cout << " *** Original tracking *** " << endl;
+
 }