]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - MUON/AliMUONEventReconstructor.cxx
Tracks reconstruction using NewIO
[u/mrichter/AliRoot.git] / MUON / AliMUONEventReconstructor.cxx
index 156fce85bdd6eb3211970267a8532d3e8ba7e70a..d1025adf685633a2edd836ed91bea3d2ec00c066 100644 (file)
  * provided "as is" without express or implied warranty.                  *
  **************************************************************************/
 
-/*
-$Log$
-Revision 1.5  2000/06/30 10:15:48  gosset
-Changes to EventReconstructor...:
-precision fit with multiple Coulomb scattering;
-extrapolation to vertex with Branson correction in absorber (JPC)
+/* $Id$ */
 
-Revision 1.4  2000/06/27 14:11:36  gosset
-Corrections against violations of coding conventions
-
-Revision 1.3  2000/06/16 07:27:08  gosset
-To remove problem in running RuleChecker, like in MUON-dev
-
-Revision 1.1.2.5  2000/06/16 07:00:26  gosset
-To remove problem in running RuleChecker
-
-Revision 1.1.2.4  2000/06/12 08:00:07  morsch
-Dummy streamer to solve CINT compilation problem (to be investigated !)
-
-Revision 1.1.2.3  2000/06/09 20:59:57  morsch
-Make includes consistent with new file structure.
-
-Revision 1.1.2.2  2000/06/09 12:58:05  gosset
-Removed comment beginnings in Log sections of .cxx files
-Suppressed most violations of coding rules
-
-Revision 1.1.2.1  2000/06/07 14:44:53  gosset
-Addition of files for track reconstruction in C++
-*/
-
-//__________________________________________________________________________
+////////////////////////////////////
 //
 // MUON event reconstructor in ALICE
 //
@@ -57,42 +29,35 @@ Addition of files for track reconstruction in C++
 // * MakeEventToBeReconstructed to build the array of hits to be reconstructed
 // * MakeSegments to build the segments
 // * MakeTracks to build the tracks
-//__________________________________________________________________________
+//
+////////////////////////////////////
 
-#include <iostream.h>
+#include <Riostream.h> // for cout
+#include <stdlib.h> // for exit()
 
-#include <TRandom.h>
-#include <TFile.h>
+#include <TTree.h>
 
-#include "AliCallf77.h" 
-#include "AliMUONEventReconstructor.h"
 #include "AliMUON.h"
+#include "AliMUONChamber.h"
+#include "AliMUONEventReconstructor.h"
 #include "AliMUONHitForRec.h"
-#include "AliMUONSegment.h"
-#include "AliMUONHit.h"
 #include "AliMUONRawCluster.h"
+#include "AliMUONRecoEvent.h"
+#include "AliMUONSegment.h"
 #include "AliMUONTrack.h"
-#include "AliMUONChamber.h"
 #include "AliMUONTrackHit.h"
-#include "AliRun.h"
-#include "TParticle.h"
-
-#ifndef WIN32 
-# define initfield initfield_
-# define reco_gufld reco_gufld_
-#else 
-# define initfield INITFIELD
-# define reco_gufld RECO_GUFLD
-#endif 
-
-extern "C"
-{
-void type_of_call initfield();
-void type_of_call reco_gufld(Double_t *Coor, Double_t *Field);
-}
+#include "AliMagF.h"
+#include "AliRun.h" // for gAlice
+#include "AliConfig.h"
+#include "AliRunLoader.h"
+#include "AliLoader.h"
+#include "AliMUONTrackK.h" //AZ
+#include <TMatrixD.h> //AZ
 
 //************* Defaults parameters for reconstruction
 static const Double_t kDefaultMinBendingMomentum = 3.0;
+static const Double_t kDefaultMaxBendingMomentum = 500.0;
+static const Double_t kDefaultMaxChi2 = 100.0;
 static const Double_t kDefaultMaxSigma2Distance = 16.0;
 static const Double_t kDefaultBendingResolution = 0.01;
 static const Double_t kDefaultNonBendingResolution = 0.144;
@@ -118,6 +83,7 @@ AliMUONEventReconstructor::AliMUONEventReconstructor(void)
 {
   // Constructor for class AliMUONEventReconstructor
   SetReconstructionParametersToDefaults();
+  fTrackMethod = 1; //AZ - tracking method (1-default, 2-Kalman)
   // Memory allocation for the TClonesArray of hits for reconstruction
   // Is 10000 the right size ????
   fHitsForRecPtr = new TClonesArray("AliMUONHitForRec", 10000);
@@ -132,36 +98,48 @@ AliMUONEventReconstructor::AliMUONEventReconstructor(void)
   // Is 10 the right size ????
   fRecTracksPtr = new TClonesArray("AliMUONTrack", 10);
   fNRecTracks = 0; // really needed or GetEntriesFast sufficient ????
+  // Memory allocation for the TClonesArray of hits on reconstructed tracks
+  // Is 100 the right size ????
+  fRecTrackHitsPtr = new TClonesArray("AliMUONTrack", 100);
+  fNRecTrackHits = 0; // really needed or GetEntriesFast sufficient ????
 
-  // Initialize magnetic field
-  // using Fortran subroutine INITFIELD in "reco_muon.F".
-  // Should rather use AliMagF ???? and remove prototyping ...
-  initfield();
-  // Impression de quelques valeurs
-  Double_t coor[3], field[3];
-  coor[0] = 50.0;
-  coor[1] = 50.0;
-  coor[2] = 950.0;
-  reco_gufld(coor, field);
-  cout << "coor: " << coor[0] << ", " << coor[1] << ", " << coor[2] << endl;
-  cout << "field: " << field[0] << ", " << field[1] << ", " << field[2] << endl;
-  coor[2] = -950.0;
-  reco_gufld(coor, field);
-  cout << "coor: " << coor[0] << ", " << coor[1] << ", " << coor[2] << endl;
-  cout << "field: " << field[0] << ", " << field[1] << ", " << field[2] << endl;
-  coor[2] = -950.0;
+  // 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]);
+  // See how to get fSimple(BValue, BLength, BPosition)
+  // automatically calculated from the actual magnetic field ????
 
   if (fPrintLevel >= 0) {
-    cout << "AliMUONEventReconstructor constructed with defaults" << endl; Dump();}
+    cout << "AliMUONEventReconstructor constructed with defaults" << endl; Dump();
+    cout << endl << "Magnetic field from root file:" << endl;
+    gAlice->Field()->Dump();
+    cout << endl;
+  }
+  
+  // Initializions for GEANT background events
+  fBkgGeantFile = 0;
+  fBkgGeantTK = 0;
+  fBkgGeantParticles = 0;
+  fBkgGeantTH = 0;
+  fBkgGeantHits = 0;
+  fBkgGeantEventNumber = -1;
+  
+  // Initialize to 0 pointers to RecoEvent, tree and tree file
+  fRecoEvent = 0;
+  fEventTree = 0;
+  fTreeFile  = 0;
+  
   return;
 }
 
-AliMUONEventReconstructor::AliMUONEventReconstructor (const AliMUONEventReconstructor& Reconstructor)
+AliMUONEventReconstructor::AliMUONEventReconstructor (const AliMUONEventReconstructor& Reconstructor):TObject(Reconstructor)
 {
   // Dummy copy constructor
 }
 
-AliMUONEventReconstructor & AliMUONEventReconstructor::operator=(const AliMUONEventReconstructor& Reconstructor)
+AliMUONEventReconstructor & AliMUONEventReconstructor::operator=(const AliMUONEventReconstructor& /*Reconstructor*/)
 {
   // Dummy assignment operator
     return *this;
@@ -171,6 +149,12 @@ AliMUONEventReconstructor & AliMUONEventReconstructor::operator=(const AliMUONEv
 AliMUONEventReconstructor::~AliMUONEventReconstructor(void)
 {
   // Destructor for class AliMUONEventReconstructor
+  if (fTreeFile) {
+     fTreeFile->Close();
+     delete fTreeFile;
+  }
+//  if (fEventTree) delete fEventTree;
+  if (fRecoEvent) delete fRecoEvent;
   delete fHitsForRecPtr; // Correct destruction of everything ???? or delete [] ????
   for (Int_t st = 0; st < kMaxMuonTrackingStations; st++)
     delete fSegmentsPtr[st]; // Correct destruction of everything ????
@@ -183,6 +167,8 @@ void AliMUONEventReconstructor::SetReconstructionParametersToDefaults(void)
   // Set reconstruction parameters to default values
   // Would be much more convenient with a structure (or class) ????
   fMinBendingMomentum = kDefaultMinBendingMomentum;
+  fMaxBendingMomentum = kDefaultMaxBendingMomentum;
+  fMaxChi2 = kDefaultMaxChi2;
   fMaxSigma2Distance = kDefaultMaxSigma2Distance;
 
   AliMUON *pMUON = (AliMUON*) gAlice->GetModule("MUON");
@@ -195,14 +181,10 @@ void AliMUONEventReconstructor::SetReconstructionParametersToDefaults(void)
     if (ch < 4) fRMin[ch] = TMath::Abs((&(pMUON->Chamber(ch)))->Z()) *
                  2.0 * TMath::Pi() / 180.0;
     else fRMin[ch] = 30.0;
+    // maximum radius at 10 degrees and Z of chamber
+    fRMax[ch] = TMath::Abs((&(pMUON->Chamber(ch)))->Z()) *
+                 10.0 * TMath::Pi() / 180.0;
   }
-  // maximum radius
-  // like in TRACKF_STAT (10 degrees ????)
-  fRMax[0] = fRMax[1] = 91.5;
-  fRMax[2] = fRMax[3] = 122.5;
-  fRMax[4] = fRMax[5] = 158.3;
-  fRMax[6] = fRMax[7] = 260.0;
-  fRMax[8] = fRMax[9] = 260.0;
 
   // ******** Parameters for making segments
   // should be parametrized ????
@@ -212,13 +194,19 @@ void AliMUONEventReconstructor::SetReconstructionParametersToDefaults(void)
   // SIGCUT*DYMAX(IZ)
   for (Int_t st = 0; st < kMaxMuonTrackingStations; st++)
     fSegmentMaxDistNonBending[st] = 5. * 0.22;
-  // Maximum distance in bending plane
-  // values from TRACKF_STAT corresponding to (J psi 20cm)
-  fSegmentMaxDistBending[0] = 1.5;
-  fSegmentMaxDistBending[1] = 1.5;
-  fSegmentMaxDistBending[2] = 3.0;
-  fSegmentMaxDistBending[3] = 6.0;
-  fSegmentMaxDistBending[4] = 6.0;
+  // 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] = 1.5 *
+    ((&(pMUON->Chamber(1)))->Z() - (&(pMUON->Chamber(0)))->Z()) / 20.0;
+  fSegmentMaxDistBending[1] = 1.5 *
+    ((&(pMUON->Chamber(3)))->Z() - (&(pMUON->Chamber(2)))->Z()) / 20.0;
+  fSegmentMaxDistBending[2] = 3.0 *
+    ((&(pMUON->Chamber(5)))->Z() - (&(pMUON->Chamber(4)))->Z()) / 20.0;
+  fSegmentMaxDistBending[3] = 6.0 *
+    ((&(pMUON->Chamber(7)))->Z() - (&(pMUON->Chamber(6)))->Z()) / 20.0;
+  fSegmentMaxDistBending[4] = 6.0 *
+    ((&(pMUON->Chamber(9)))->Z() - (&(pMUON->Chamber(8)))->Z()) / 20.0;
   
   fBendingResolution = kDefaultBendingResolution;
   fNonBendingResolution = kDefaultNonBendingResolution;
@@ -233,23 +221,23 @@ void AliMUONEventReconstructor::SetReconstructionParametersToDefaults(void)
 }
 
 //__________________________________________________________________________
-Double_t AliMUONEventReconstructor::GetImpactParamFromBendingMomentum(Double_t BendingMomentum)
+Double_t AliMUONEventReconstructor::GetImpactParamFromBendingMomentum(Double_t BendingMomentum) const
 {
   // Returns impact parameter at vertex in bending plane (cm),
   // from the signed bending momentum "BendingMomentum" in bending plane (GeV/c),
   // using simple values for dipole magnetic field.
-  // The sign is the sign of the charge.
+  // The sign of "BendingMomentum" is the sign of the charge.
   return (-0.0003 * fSimpleBValue * fSimpleBLength * fSimpleBPosition /
          BendingMomentum);
 }
 
 //__________________________________________________________________________
-Double_t AliMUONEventReconstructor::GetBendingMomentumFromImpactParam(Double_t ImpactParam)
+Double_t AliMUONEventReconstructor::GetBendingMomentumFromImpactParam(Double_t ImpactParam) const
 {
   // Returns signed bending momentum in bending plane (GeV/c),
+  // the sign being the sign of the charge for particles moving forward in Z,
   // from the impact parameter "ImpactParam" at vertex in bending plane (cm),
   // using simple values for dipole magnetic field.
-  // The sign is the sign of the charge.
   return (-0.0003 * fSimpleBValue * fSimpleBLength * fSimpleBPosition /
          ImpactParam);
 }
@@ -394,27 +382,69 @@ void AliMUONEventReconstructor::ResetSegments(void)
 void AliMUONEventReconstructor::ResetTracks(void)
 {
   // To reset the TClonesArray of reconstructed tracks
-  if (fRecTracksPtr) fRecTracksPtr->Clear();
+  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 AliMUONEventReconstructor::ResetTrackHits(void)
+{
+  // To reset the TClonesArray of hits on reconstructed tracks
+  if (fRecTrackHitsPtr) fRecTrackHitsPtr->Clear();
+  fNRecTrackHits = 0;
+  return;
+}
+
   //__________________________________________________________________________
 void AliMUONEventReconstructor::MakeEventToBeReconstructed(void)
 {
   // To make the list of hits to be reconstructed,
   // either from the GEANT hits or from the raw clusters
   // according to the parameter set for the reconstructor
+  TString evfoldname = AliConfig::fgkDefaultEventFolderName;//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;
+   }
+  
   if (fPrintLevel >= 1) cout << "enter MakeEventToBeReconstructed" << endl;
   ResetHitsForRec();
   if (fRecGeantHits == 1) {
     // Reconstruction from GEANT hits
     // Back to the signal file
-    ((gAlice->TreeK())->GetCurrentFile())->cd();
-    // Signal hits
-    // AliMUON *MUON  = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
-    // Security on MUON ????
-    AddHitsForRecFromGEANT(gAlice->TreeH());
+      TTree* treeH = gime->TreeH();
+      if (treeH == 0x0)
+       {
+         Int_t retval = gime->LoadHits();
+         if ( retval)
+          {
+            Error("MakeEventToBeReconstructed","Error occured while loading hits.");
+            return;
+          }
+         treeH = gime->TreeH();
+         if (treeH == 0x0)
+          {
+           Error("MakeEventToBeReconstructed","Can not get TreeH");
+           return;
+          }
+       }
+    
+    AddHitsForRecFromGEANT(treeH);
+    
     // Background hits
     AddHitsForRecFromBkgGEANT(fBkgGeantTH, fBkgGeantHits);
     // Sort HitsForRec in increasing order with respect to chamber number
@@ -426,7 +456,7 @@ void AliMUONEventReconstructor::MakeEventToBeReconstructed(void)
     // Security on MUON ????
     // TreeR assumed to be be "prepared" in calling function
     // by "MUON->GetTreeR(nev)" ????
-    TTree *treeR = gAlice->TreeR();
+    TTree *treeR = gime->TreeR();
     AddHitsForRecFromRawClusters(treeR);
     // No sorting: it is done automatically in the previous function
   }
@@ -454,6 +484,7 @@ void AliMUONEventReconstructor::AddHitsForRecFromGEANT(TTree *TH)
 {
   // To add to the list of hits for reconstruction
   // the GEANT signal hits from a hit tree TH.
+  Int_t hitBits, chamBits; //AZ
   if (fPrintLevel >= 2)
     cout << "enter AddHitsForRecFromGEANT with TH: " << TH << endl;
   if (TH == NULL) return;
@@ -464,16 +495,31 @@ void AliMUONEventReconstructor::AddHitsForRecFromGEANT(TTree *TH)
   Int_t ntracks = (Int_t) TH->GetEntries();
   if (fPrintLevel >= 2)
     cout << "ntracks: " << ntracks << endl;
+  fMuons = 0; //AZ
   for (Int_t track = 0; track < ntracks; track++) {
     gAlice->ResetHits();
     TH->GetEvent(track);
     // Loop over hits
     Int_t hit = 0;
+    hitBits = 0; // AZ
+    chamBits = 0; // AZ
+    Int_t itrack = track; //AZ
     for (AliMUONHit* mHit = (AliMUONHit*) pMUON->FirstHit(-1); 
         mHit;
         mHit = (AliMUONHit*) pMUON->NextHit(), hit++) {
-      NewHitForRecFromGEANT(mHit,track, hit, 1);
+      Int_t ipart = TMath::Abs ((Int_t) mHit->Particle()); //AZ
+      //itrack = mHit->Track(); //AZ
+      //AZNewHitForRecFromGEANT(mHit,track, hit, 1);
+      if (NewHitForRecFromGEANT(mHit,track, hit, 1) && ipart == 13
+      //if (NewHitForRecFromGEANT(mHit,itrack-1, hit, 1) && ipart == 13 
+          && itrack <= 2) chamBits |= BIT(mHit->Chamber()-1); //AZ - set bit
     } // end of hit loop
+    if (chamBits&3 && chamBits>>2&3 && chamBits>>4&3 && chamBits>>6&3 && 
+        chamBits>>8&3 && ((chamBits>>6&3)==3 || (chamBits>>8&3)==3)) 
+      fMuons += 1; //AZ
+    //if (chamBits&3 && chamBits>>2&3 && chamBits>>4&3 && chamBits>>6&3 && 
+    //      chamBits>>8&3 && ((chamBits>>6&3)==3 || (chamBits>>8&3)==3) && 
+    //      ((chamBits&3)==3 || (chamBits>>2&3)==3)) fMuons += 1;
   } // end of track loop
   return;
 }
@@ -519,16 +565,17 @@ AliMUONHitForRec* AliMUONEventReconstructor::NewHitForRecFromGEANT(AliMUONHit* H
   // like in Fortran TRACKF_STAT.
   AliMUONHitForRec* hitForRec;
   Double_t bendCoor, nonBendCoor, radius;
-  Int_t chamber = Hit->fChamber - 1; // chamber(0...)
+  Int_t chamber = Hit->Chamber() - 1; // chamber(0...)
   // only in tracking chambers (fChamber starts at 1)
   if (chamber >= kMaxMuonTrackingChambers) return NULL;
   // only if hit is efficient (keep track for checking ????)
   if (gRandom->Rndm() > fEfficiency) return NULL;
   // only if radius between RMin and RMax
-  bendCoor = Hit->fY;
-  nonBendCoor = Hit->fX;
+  bendCoor = Hit->Y();
+  nonBendCoor = Hit->X();
   radius = TMath::Sqrt((bendCoor * bendCoor) + (nonBendCoor * nonBendCoor));
-  if ((radius < fRMin[chamber]) || (radius > fRMax[chamber])) return NULL;
+  // This cut is not needed with a realistic chamber geometry !!!!
+//   if ((radius < fRMin[chamber]) || (radius > fRMax[chamber])) return NULL;
   // new AliMUONHitForRec from GEANT hit and increment number of AliMUONHitForRec's
   hitForRec = new ((*fHitsForRecPtr)[fNHitsForRec]) AliMUONHitForRec(Hit);
   fNHitsForRec++;
@@ -536,6 +583,9 @@ AliMUONHitForRec* AliMUONEventReconstructor::NewHitForRecFromGEANT(AliMUONHit* H
   hitForRec->SetBendingCoor(bendCoor + gRandom->Gaus(0., fBendingResolution));
   hitForRec->SetNonBendingCoor(nonBendCoor
                               + gRandom->Gaus(0., fNonBendingResolution));
+//   // !!!! without smearing
+//   hitForRec->SetBendingCoor(bendCoor);
+//   hitForRec->SetNonBendingCoor(nonBendCoor);
   // more information into HitForRec
   //  resolution: angular effect to be added here ????
   hitForRec->SetBendingReso2(fBendingResolution * fBendingResolution);
@@ -639,11 +689,40 @@ void AliMUONEventReconstructor::AddHitsForRecFromRawClusters(TTree* TR)
   // on the radius between RMin and RMax.
   AliMUONHitForRec *hitForRec;
   AliMUONRawCluster *clus;
-  Int_t iclus, nclus;
+  Int_t iclus, nclus, nTRentries;
   TClonesArray *rawclusters;
   if (fPrintLevel >= 1) cout << "enter AddHitsForRecFromRawClusters" << endl;
-  AliMUON *pMUON  = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
-  // Security on MUON ????
+
+  TString evfoldname = AliConfig::fgkDefaultEventFolderName;//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;
+   }
+   // Loading AliRun master
+  rl->LoadgAlice();
+  gAlice = rl->GetAliRun();
+
+  // Loading MUON subsystem
+  AliMUON * pMUON = (AliMUON *) gAlice->GetDetector("MUON");
+
+  nTRentries = Int_t(TR->GetEntries());
+  if (nTRentries != 1) {
+    cout << "Error in AliMUONEventReconstructor::AddHitsForRecFromRawClusters"
+        << endl;
+    cout << "nTRentries = " << nTRentries << " not equal to 1" << endl;
+    exit(0);
+  }
+  gime->TreeR()->GetEvent(0); // only one entry  
   // Loop over tracking chambers
   for (Int_t ch = 0; ch < kMaxMuonTrackingChambers; ch++) {
     // number of HitsForRec to 0 for the chamber
@@ -651,9 +730,9 @@ void AliMUONEventReconstructor::AddHitsForRecFromRawClusters(TTree* TR)
     // index of first HitForRec for the chamber
     if (ch == 0) fIndexOfFirstHitForRecPerChamber[ch] = 0;
     else fIndexOfFirstHitForRecPerChamber[ch] = fNHitsForRec;
-    rawclusters = pMUON->RawClustAddress(ch);
-    pMUON->ResetRawClusters();
-    TR->GetEvent((Int_t) (TR->GetEntries()) - 1); // to be checked ????
+    rawclusters = pMUON->GetMUONData()->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++) {
@@ -670,9 +749,8 @@ void AliMUONEventReconstructor::AddHitsForRecFromRawClusters(TTree* TR)
       //  original raw cluster
       hitForRec->SetChamberNumber(ch);
       hitForRec->SetHitNumber(iclus);
-      // Z coordinate of the chamber (cm) with sign opposite to GEANT sign
-      // could (should) be more exact from chamber geometry ???? 
-      hitForRec->SetZ(-(&(pMUON->Chamber(ch)))->Z());
+      // Z coordinate of the raw cluster (cm)
+      hitForRec->SetZ(clus->fZ[0]);
       if (fPrintLevel >= 10) {
        cout << "chamber (0...): " << ch <<
          " raw cluster (0...): " << iclus << endl;
@@ -681,6 +759,7 @@ void AliMUONEventReconstructor::AddHitsForRecFromRawClusters(TTree* TR)
        hitForRec->Dump();}
     } // end of cluster loop
   } // end of chamber loop
+  SortHitsForRecWithIncreasingChamber(); //AZ 
   return;
 }
 
@@ -692,7 +771,9 @@ void AliMUONEventReconstructor::MakeSegments(void)
   if (fPrintLevel >= 1) cout << "enter MakeSegments" << endl;
   ResetSegments();
   // Loop over stations
-  for (Int_t st = 0; st < kMaxMuonTrackingStations; st++)
+  Int_t nb = (fTrackMethod == 2) ? 3 : 0; //AZ
+  //AZ for (Int_t st = 0; st < kMaxMuonTrackingStations; st++)
+  for (Int_t st = nb; st < kMaxMuonTrackingStations; st++) //AZ
     MakeSegmentsPerStation(st); 
   if (fPrintLevel >= 10) {
     cout << "end of MakeSegments" << endl;
@@ -723,7 +804,7 @@ void AliMUONEventReconstructor::MakeSegmentsPerStation(Int_t Station)
   AliMUONSegment *segment;
   Bool_t last2st;
   Double_t bendingSlope, distBend, distNonBend, extBendCoor, extNonBendCoor,
-    impactParam, maxImpactParam;
+      impactParam = 0., maxImpactParam = 0., minImpactParam = 0.; // =0 to avoid compilation warnings.
   AliMUON *pMUON  = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
   if (fPrintLevel >= 1)
     cout << "enter MakeSegmentsPerStation (0...) " << Station << endl;
@@ -737,6 +818,9 @@ void AliMUONEventReconstructor::MakeSegmentsPerStation(Int_t Station)
     // 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
@@ -773,14 +857,15 @@ void AliMUONEventReconstructor::MakeSegmentsPerStation(Int_t Station)
          (hit1Ptr->GetZ() - hit2Ptr->GetZ());
        // absolute value of impact parameter
        impactParam =
-         TMath::Abs(hit1Ptr->GetBendingCoor() - hit2Ptr->GetZ() * bendingSlope);
+         TMath::Abs(hit1Ptr->GetBendingCoor() - hit1Ptr->GetZ() * bendingSlope);
       }
       // check for distances not too large,
       // and impact parameter not too big if stations downstream of the dipole.
       // Conditions "distBend" and "impactParam" correlated for these stations ????
       if ((distBend < fSegmentMaxDistBending[Station]) &&
          (distNonBend < fSegmentMaxDistNonBending[Station]) &&
-         (!last2st || (impactParam < maxImpactParam))) {
+         (!last2st || (impactParam < maxImpactParam)) &&
+         (!last2st || (impactParam > minImpactParam))) {
        // make new segment
        segment = new ((*fSegmentsPtr[Station])[segmentIndex])
          AliMUONSegment(hit1Ptr, hit2Ptr);
@@ -823,11 +908,25 @@ void AliMUONEventReconstructor::MakeTracks(void)
   // To make the tracks,
   // from the list of segments and points in all stations
   if (fPrintLevel >= 1) cout << "enter MakeTracks" << endl;
+  // The order may be important for the following Reset's
   ResetTracks();
-  // 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();
+  ResetTrackHits();
+  if (fTrackMethod == 2) { //AZ - Kalman filter
+    MakeTrackCandidatesK();
+    // Follow tracks in stations(1..) 3, 2 and 1
+    FollowTracksK();
+    // Remove double tracks
+    RemoveDoubleTracksK();
+    // Propagate tracks to the vertex thru absorber
+    GoToVertex();
+  } else { //AZ
+    // 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();
+  }
   return;
 }
 
@@ -969,7 +1068,7 @@ void AliMUONEventReconstructor::MakeTrackCandidates(void)
       // because candidates with 2 segments have to looked for only once.
       if (begStation == 4)
        nbCan2Seg = MakeTrackCandidatesWithTwoSegments(begSegment);
-      // Look for track candidates with one segments and one point,
+      // 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 ????
@@ -985,12 +1084,14 @@ void AliMUONEventReconstructor::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;
+  AliMUONHitForRec *bestHit, *extrapHit, *extrapCorrHit, *hit;
+  AliMUONSegment *bestSegment, *extrapSegment, *extrapCorrSegment, *segment;
   AliMUONTrack *track, *nextTrack;
   AliMUONTrackParam *trackParam1, trackParam[2], trackParamVertex;
-  Int_t ch, chInStation, chBestHit, iHit, iSegment, station, trackIndex;
+  // -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.;
   AliMUON *pMUON = (AliMUON*) gAlice->GetModule("MUON"); // necessary ????
   // local maxSigma2Distance, for easy increase in testing
   maxSigma2Distance = fMaxSigma2Distance;
@@ -1005,12 +1106,14 @@ void AliMUONEventReconstructor::FollowTracks(void)
     nextTrack = (AliMUONTrack*) fRecTracksPtr->After(track); // prepare next track
     if (fPrintLevel >= 2)
       cout << "FollowTracks: track candidate(0..): " << trackIndex << endl;
-    // Fit track candidate from vertex at X = Y = 0 
-    track->SetFitMCS(0);  // fit without Multiple Scattering
-    track->Fit(track->GetTrackParamAtVertex(), 3);
+    // 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 (fPrintLevel >= 10) {
       cout << "FollowTracks: track candidate(0..): " << trackIndex
-          << " after fit in stations(1..) 4 and 5" << endl;
+          << " after fit in stations(0..) 3 and 4" << endl;
       track->RecursiveDump();
     }
     // Loop over stations(1..) 3, 2 and 1
@@ -1023,6 +1126,7 @@ void AliMUONEventReconstructor::FollowTracks(void)
       // extrapolation to station
       trackParam1->ExtrapToStation(station, trackParam);
       extrapSegment = new AliMUONSegment(); //  empty segment
+      extrapCorrSegment = new AliMUONSegment(); //  empty corrected segment
       // multiple scattering factor corresponding to one chamber
       // and momentum in bending plane (not total)
       mcsFactor = 0.0136 * trackParam1->GetInverseBendingMomentum();
@@ -1042,6 +1146,14 @@ void AliMUONEventReconstructor::FollowTracks(void)
       extrapSegment->UpdateFromStationTrackParam
        (trackParam, mcsFactor, dZ1, dZ2, dZ3, station,
         trackParam1->GetInverseBendingMomentum());
+      // same thing for corrected segment
+      // better to use copy constructor, after checking that it works properly !!!!
+      extrapCorrSegment->SetBendingCoorReso2(fBendingResolution * fBendingResolution);
+      extrapCorrSegment->
+       SetNonBendingCoorReso2(fNonBendingResolution * fNonBendingResolution);
+      extrapCorrSegment->UpdateFromStationTrackParam
+       (trackParam, mcsFactor, dZ1, dZ2, dZ3, station,
+        trackParam1->GetInverseBendingMomentum());
       bestChi2 = 5.0;
       bestSegment = NULL;
       if (fPrintLevel >= 10) {
@@ -1055,7 +1167,20 @@ void AliMUONEventReconstructor::FollowTracks(void)
        // multiple scattering ????
        // separation in 2 functions: Segment and HitForRec ????
        segment = (AliMUONSegment*) ((*fSegmentsPtr[station])[iSegment]);
-       chi2 = segment->NormalizedChi2WithSegment(extrapSegment, maxSigma2Distance);
+       // correction of corrected segment (fBendingCoor and fNonBendingCoor)
+       // according to real Z value of "segment" and slopes of "extrapSegment"
+       extrapCorrSegment->
+         SetBendingCoor(extrapSegment->GetBendingCoor() +
+                        extrapSegment->GetBendingSlope() *
+                        (segment->GetHitForRec1()->GetZ() -
+                         (&(pMUON->Chamber(2 * station)))->Z()));
+       extrapCorrSegment->
+         SetNonBendingCoor(extrapSegment->GetNonBendingCoor() +
+                           extrapSegment->GetNonBendingSlope() *
+                           (segment->GetHitForRec1()->GetZ() -
+                            (&(pMUON->Chamber(2 * station)))->Z()));
+       chi2 = segment->
+         NormalizedChi2WithSegment(extrapCorrSegment, maxSigma2Distance);
        if (chi2 < bestChi2) {
          // update best Chi2 and Segment if better found
          bestSegment = segment;
@@ -1080,6 +1205,7 @@ void AliMUONEventReconstructor::FollowTracks(void)
        // should consider all possibilities ????
        // multiple scattering ???? do about like for extrapSegment !!!!
        extrapHit = new AliMUONHitForRec(); //  empty hit
+       extrapCorrHit = new AliMUONHitForRec(); //  empty corrected hit
        bestChi2 = 3.0;
        bestHit = NULL;
        if (fPrintLevel >= 10) {
@@ -1097,13 +1223,33 @@ void AliMUONEventReconstructor::FollowTracks(void)
          // resolutions from "extrapSegment"
          extrapHit->SetBendingReso2(extrapSegment->GetBendingCoorReso2());
          extrapHit->SetNonBendingReso2(extrapSegment->GetNonBendingCoorReso2());
+         // same things for corrected hit
+         // better to use copy constructor, after checking that it works properly !!!!
+         extrapCorrHit->
+           SetBendingCoor((&(trackParam[chInStation]))->GetBendingCoor());
+         extrapCorrHit->
+           SetNonBendingCoor((&(trackParam[chInStation]))->GetNonBendingCoor());
+         extrapHit->SetBendingReso2(extrapSegment->GetBendingCoorReso2());
+         extrapHit->SetNonBendingReso2(extrapSegment->GetNonBendingCoorReso2());
          // Loop over hits in the chamber
-         ch = 2 * station + ch;
+         ch = 2 * station + chInStation;
          for (iHit = fIndexOfFirstHitForRecPerChamber[ch];
               iHit < fIndexOfFirstHitForRecPerChamber[ch] +
                 fNHitsForRecPerChamber[ch];
               iHit++) {
            hit = (AliMUONHitForRec*) ((*fHitsForRecPtr)[iHit]);
+           // correction of corrected hit (fBendingCoor and fNonBendingCoor)
+           // according to real Z value of "hit" and slopes of right "trackParam"
+           extrapCorrHit->
+             SetBendingCoor((&(trackParam[chInStation]))->GetBendingCoor() +
+                            (&(trackParam[chInStation]))->GetBendingSlope() *
+                            (hit->GetZ() -
+                             (&(trackParam[chInStation]))->GetZ()));
+           extrapCorrHit->
+             SetNonBendingCoor((&(trackParam[chInStation]))->GetNonBendingCoor() +
+                               (&(trackParam[chInStation]))->GetNonBendingSlope() *
+                               (hit->GetZ() -
+                                (&(trackParam[chInStation]))->GetZ()));
            // condition for hit not already in segment ????
            chi2 = hit->NormalizedChi2WithHitForRec(extrapHit, maxSigma2Distance);
            if (chi2 < bestChi2) {
@@ -1117,7 +1263,7 @@ void AliMUONEventReconstructor::FollowTracks(void)
        if (bestHit) {
          // best hit found: add it to track candidate
          track->AddHitForRec(bestHit);
-         // set track parameters at these two TrackHit's
+         // set track parameters at this TrackHit
          track->SetTrackParamAtHit(track->GetNTrackHits() - 1,
                                    &(trackParam[chBestHit]));
          if (fPrintLevel >= 10) {
@@ -1127,44 +1273,71 @@ void AliMUONEventReconstructor::FollowTracks(void)
          }
        }
        else {
-         // Remove current track candidate and update fNRecTracks
-         // To be checked: recursive delete of TrackHit's !!!!
-         // For cleaner implementation: call track->Remove()
-         // to be coded, with all cleanings,
-         // including links between HitForRec's and TrackHit's !!!!
-         fRecTracksPtr->Remove(track);
-         fNRecTracks--;
+         // Remove current track candidate
+         // and corresponding TrackHit's, ...
+         track->Remove();
          delete extrapSegment;
+         delete extrapCorrSegment;
+         delete extrapHit;
+         delete extrapCorrHit;
          break; // stop the search for this candidate:
          // exit from the loop over station
        }
+       delete extrapHit;
+       delete extrapCorrHit;
       }
       delete extrapSegment;
+      delete extrapCorrSegment;
       // 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();
-      // Track fit from first track hit varying X and Y,
+      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->Fit(trackParam1, 5);
+      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 (fPrintLevel >= 10) {
        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();
        track->SetTrackParamAtVertex(&trackParamVertex);
-      }
-      if (fPrintLevel >= 1) {
-       cout << "FollowTracks: track candidate(0..): " << trackIndex
-            << " after extrapolation to vertex" << endl;
-       track->RecursiveDump();
+       if (fPrintLevel >= 1) {
+         cout << "FollowTracks: track candidate(0..): " << trackIndex
+              << " after extrapolation to vertex" << endl;
+         track->RecursiveDump();
+       }
       }
     } // for (station = 2;...
     // go really to next track
@@ -1175,6 +1348,50 @@ void AliMUONEventReconstructor::FollowTracks(void)
   return;
 }
 
+  //__________________________________________________________________________
+void AliMUONEventReconstructor::RemoveDoubleTracks(void)
+{
+  // To remove double tracks.
+  // Tracks are considered identical
+  // if they have at least half of their hits in common.
+  // Among two identical tracks, one keeps the track with the larger number of hits
+  // or, if these numbers are equal, the track with the minimum Chi2.
+  AliMUONTrack *track1, *track2, *trackToRemove;
+  Bool_t identicalTracks;
+  Int_t hitsInCommon, nHits1, nHits2;
+  identicalTracks = kTRUE;
+  while (identicalTracks) {
+    identicalTracks = kFALSE;
+    // Loop over first track of the pair
+    track1 = (AliMUONTrack*) fRecTracksPtr->First();
+    while (track1 && (!identicalTracks)) {
+      nHits1 = track1->GetNTrackHits();
+      // Loop over second track of the pair
+      track2 = (AliMUONTrack*) fRecTracksPtr->After(track1);
+      while (track2 && (!identicalTracks)) {
+       nHits2 = track2->GetNTrackHits();
+       // number of hits in common between two tracks
+       hitsInCommon = track1->HitsInCommon(track2);
+       // check for identical tracks
+       if ((4 * hitsInCommon) >= (nHits1 + nHits2)) {
+         identicalTracks = kTRUE;
+         // decide which track to remove
+         if (nHits1 > nHits2) trackToRemove = track2;
+         else if (nHits1 < nHits2) trackToRemove = track1;
+         else if ((track1->GetFitFMin()) < (track2->GetFitFMin()))
+           trackToRemove = track2;
+         else trackToRemove = track1;
+         // remove it
+         trackToRemove->Remove();
+       }
+       track2 = (AliMUONTrack*) fRecTracksPtr->After(track2);
+      } // track2
+      track1 = (AliMUONTrack*) fRecTracksPtr->After(track1);
+    } // track1
+  }
+  return;
+}
+
   //__________________________________________________________________________
 void AliMUONEventReconstructor::EventDump(void)
 {
@@ -1183,8 +1400,6 @@ void AliMUONEventReconstructor::EventDump(void)
 
   AliMUONTrack *track;
   AliMUONTrackParam *trackParam, *trackParam1;
-  TClonesArray *particles; // pointer to the particle list
-  TParticle *p;
   Double_t bendingSlope, nonBendingSlope, pYZ;
   Double_t pX, pY, pZ, x, y, z, c;
   Int_t np, trackIndex, nTrackHits;
@@ -1196,6 +1411,7 @@ void AliMUONEventReconstructor::EventDump(void)
   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
     if (fPrintLevel >= 1)
       cout << " track number: " << trackIndex << endl;
     // function for each track for modularity ????
@@ -1237,19 +1453,278 @@ void AliMUONEventReconstructor::EventDump(void)
             z, x, y, pX, pY, pZ, c);
   }
   // informations about generated particles
-  particles = gAlice->Particles();
-  np = particles->GetEntriesFast();
+  np = gAlice->GetNtrack();
   printf(" **** number of generated particles: %d  \n", np);
   
-  for (Int_t iPart = 0; iPart < np; iPart++) {
-    p = (TParticle*) particles->UncheckedAt(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());    
+//    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 AliMUONEventReconstructor::FillEvent()
+{
+// Create a new AliMUONRecoEvent, fill its track list, then add it as a
+// leaf in the Event branch of TreeRecoEvent tree
+   cout << "Enter FillEvent() ...\n";
+
+   if (!fRecoEvent) {
+      fRecoEvent = new AliMUONRecoEvent();
+   } else {
+      fRecoEvent->Clear();
+   }
+   //save current directory
+   TDirectory *current =  gDirectory;
+   if (!fTreeFile)  fTreeFile  = new TFile("tree_reco.root", "RECREATE");
+   if (!fEventTree) fEventTree = new TTree("TreeRecoEvent", "MUON reconstructed events");
+   //AZif (fRecoEvent->MakeDumpTracks(fRecTracksPtr)) {
+   if (fRecoEvent->MakeDumpTracks(fMuons, fRecTracksPtr, this)) { //AZ
+      if (fPrintLevel > 1) fRecoEvent->EventInfo();
+      TBranch *branch = fEventTree->GetBranch("Event");
+      if (!branch) branch = fEventTree->Branch("Event", "AliMUONRecoEvent", &fRecoEvent, 64000);
+      branch->SetAutoDelete();
+      fTreeFile->cd();
+      fEventTree->Fill();
+      fTreeFile->Write();
+   }
+   // restore directory
+   current->cd();
+}
+
+//__________________________________________________________________________
+void AliMUONEventReconstructor::MakeTrackCandidatesK(void)
+{
+  // To make initial tracks for Kalman filter from the list of segments
+  Int_t istat, iseg;
+  AliMUONSegment *segment;
+  AliMUONTrackK *trackK;
+
+  if (fPrintLevel >= 1) cout << "enter MakeTrackCandidatesK" << endl;
+  // Reset the TClonesArray of reconstructed tracks
+  if (fRecTracksPtr) fRecTracksPtr->Delete();
+  // Delete in order that the Track destructors are called,
+  // hence the space for the TClonesArray of pointers to TrackHit's is freed
+  fNRecTracks = 0;
+
+  AliMUONTrackK a(this, fHitsForRecPtr); // bad idea ???
+  // Loop over stations(1...) 5 and 4
+  for (istat=4; istat>=3; istat--) {
+    // Loop over segments in the station
+    for (iseg=0; iseg<fNSegments[istat]; iseg++) {
+      // Transform segments to tracks and evaluate covariance matrix
+      segment = (AliMUONSegment*) ((*fSegmentsPtr[istat])[iseg]);
+      trackK = new ((*fRecTracksPtr)[fNRecTracks]) AliMUONTrackK(segment);
+      fNRecTracks++;
+    } // for (iseg=0;...)
+  } // for (istat=4;...)
+  return;
+}
+
+//__________________________________________________________________________
+void AliMUONEventReconstructor::FollowTracksK(void)
+{
+  // Follow tracks using Kalman filter
+  Bool_t Ok;
+  Int_t icand, ichamBeg, ichamEnd, chamBits;
+  Double_t zDipole1, zDipole2;
+  AliMUONTrackK *trackK;
+  AliMUONHitForRec *hit;
+  AliMUONRawCluster *clus;
+  TClonesArray *rawclusters;
+  AliMUON *pMUON;
+  clus = 0; rawclusters = 0;
+
+  zDipole1 = GetSimpleBPosition() - GetSimpleBLength()/2;
+  zDipole2 = zDipole1 + GetSimpleBLength();
+
+  // Print hits
+  pMUON  = (AliMUON*) gAlice->GetModule("MUON");
+  for (Int_t i1=0; i1<fNHitsForRec; i1++) {
+    hit = (AliMUONHitForRec*) ((*fHitsForRecPtr)[i1]);
+    //if (hit->GetTHTrack() > 1 || hit->GetGeantSignal() == 0) continue;
+    /*
+    cout << " Hit #" << hit->GetChamberNumber() << " ";
+    cout << hit->GetBendingCoor() << " ";
+    cout << hit->GetNonBendingCoor() << " ";
+    cout << hit->GetZ() << " ";
+    cout << hit->GetGeantSignal() << " ";
+    cout << hit->GetTHTrack() << endl;
+    */
+    /*
+    printf(" Hit # %d %10.4f %10.4f %10.4f",
+           hit->GetChamberNumber(), hit->GetBendingCoor(),
+           hit->GetNonBendingCoor(), hit->GetZ());
+    if (fRecGeantHits) {
+      // from GEANT hits
+      printf(" %3d %3d \n", hit->GetGeantSignal(), hit->GetTHTrack());
+    } else {
+      // from raw clusters
+      rawclusters = pMUON->RawClustAddress(hit->GetChamberNumber());
+      clus = (AliMUONRawCluster*) rawclusters->UncheckedAt(hit->
+                                               GetHitNumber());
+      printf("%3d", clus->fTracks[1]-1);
+      if (clus->fTracks[2] != 0) printf("%3d \n", clus->fTracks[2]-1);
+      else printf("\n");
+    }
+    */
+  }
+
+  icand = -1;
+  Int_t nSeeds = fNRecTracks; // starting number of seeds
+  // Loop over track candidates
+  while (icand < fNRecTracks-1) {
+    icand ++;
+    trackK = (AliMUONTrackK*) ((*fRecTracksPtr)[icand]);
+
+    // Discard candidate which will produce the double track
+    if (icand > 0) {
+      Ok = CheckCandidateK(icand,nSeeds);
+      if (!Ok) {
+        //trackK->SetRecover(-1); // mark candidate to be removed
+        //continue;
+      }
+    }
+
+    Ok = kTRUE;
+    if (trackK->GetRecover() == 0) hit = (AliMUONHitForRec*) 
+                                   trackK->GetHitOnTrack()->Last(); // last hit
+    else hit = (AliMUONHitForRec*) (*trackK->GetHitOnTrack())[1]; // 2'nd hit
+    ichamBeg = hit->GetChamberNumber();
+    ichamEnd = 0;
+    // Check propagation direction
+    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();
+        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->SetTrackQuality(0); // compute "track quality"
+    else trackK->SetRecover(-1); // mark candidate to be removed
+
+    // Majority 3 of 4 in first 2 stations
+    chamBits = 0;
+    for (Int_t i=0; i<trackK->GetNTrackHits(); i++) {
+      hit = (AliMUONHitForRec*) (*trackK->GetHitOnTrack())[i];
+      chamBits |= BIT(hit->GetChamberNumber()-1);
+    }
+    //if (!((chamBits&3)==3 || (chamBits>>2&3)==3)) trackK->SetRecover(-1); 
+                                 //mark candidate to be removed
+  } // 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;
 }
 
-void AliMUONEventReconstructor::Streamer(TBuffer &R__b)
+//__________________________________________________________________________
+Bool_t AliMUONEventReconstructor::CheckCandidateK(Int_t icand, Int_t nSeeds)
 {
-    ;
+  // Discards track candidate if it will produce the double track (having
+  // the same seed segment hits as hits of a good track found before)
+  AliMUONTrackK *track1, *track2;
+  AliMUONHitForRec *hit1, *hit2, *hit;
+
+  track1 = (AliMUONTrackK*) ((*fRecTracksPtr)[icand]);
+  hit1 = (AliMUONHitForRec*) (*track1->GetHitOnTrack())[0]; // 1'st hit
+  hit2 = (AliMUONHitForRec*) (*track1->GetHitOnTrack())[1]; // 2'nd hit
+
+  for (Int_t i=0; i<icand; i++) {
+    track2 = (AliMUONTrackK*) ((*fRecTracksPtr)[i]);
+    //if (track2->GetRecover() < 0) continue;
+    if (track2->GetRecover() < 0 && icand >= nSeeds) continue;
+
+    if (track1->GetStartSegment() == track2->GetStartSegment()) {
+      return kFALSE;
+    } else {
+      Int_t nSame = 0;
+      for (Int_t j=0; j<track2->GetNTrackHits(); j++) {
+        hit = (AliMUONHitForRec*) (*track2->GetHitOnTrack())[j];
+        if (hit == hit1 || hit == hit2) {
+          nSame++;
+          if (nSame == 2) return kFALSE;
+        }
+      } // for (Int_t j=0;
+    }
+  } // for (Int_t i=0;
+  return kTRUE;
+}
+
+//__________________________________________________________________________
+void AliMUONEventReconstructor::RemoveDoubleTracksK(void)
+{
+  // 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();
+  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)) {
+        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();
+  cout << " Number of Kalman tracks: " << fNRecTracks << endl;
+}
+
+//__________________________________________________________________________
+void AliMUONEventReconstructor::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])->GoToZ(zVertex); // w/out absorber
+    ((AliMUONTrackK*)(*fRecTracksPtr)[i])->SetTrackQuality(1); // compute Chi2
+    ((AliMUONTrackK*)(*fRecTracksPtr)[i])->GoToVertex(); // with absorber
+  }
 }