]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - EMCAL/AliEMCALClusterizerv1.cxx
Updated version.
[u/mrichter/AliRoot.git] / EMCAL / AliEMCALClusterizerv1.cxx
index 883445e2deffb8fb50b2fa18be5277ec7827c8cf..2a321ebfbb4f7cdbfcc60dda145afe4cc2904b15 100644 (file)
  * about the suitability of this software for any purpose. It is          *
  * provided "as is" without express or implied warranty.                  *
  **************************************************************************/
  * about the suitability of this software for any purpose. It is          *
  * provided "as is" without express or implied warranty.                  *
  **************************************************************************/
-/* $Id$ */
-
-/* $Log:
-   1 October 2000. Yuri Kharlov:
-     AreNeighbours()
-     PPSD upper layer is considered if number of layers>1
 
 
-   18 October 2000. Yuri Kharlov:
-     AliEMCALClusterizerv1()
-     CPV clusterizing parameters added
+/* $Id$ */
 
 
-     MakeClusters()
-     After first PPSD digit remove EMC digits only once
-*/
-//*-- Author: Yves Schutz (SUBATECH)  & Dmitri Peressounko (SUBATECH & Kurchatov Institute)
+//-- Author: Yves Schutz (SUBATECH)  & Dmitri Peressounko (SUBATECH & Kurchatov Institute)
+//  August 2002 Yves Schutz: clone PHOS as closely as possible and intoduction
+//                           of new  IO (à la PHOS)
+//  Mar 2007, Aleksei Pavlinov - new algoritmh of pseudo clusters
 //////////////////////////////////////////////////////////////////////////////
 //  Clusterization class. Performs clusterization (collects neighbouring active cells) and 
 //  unfolds the clusters having several local maxima.  
 //////////////////////////////////////////////////////////////////////////////
 //  Clusterization class. Performs clusterization (collects neighbouring active cells) and 
 //  unfolds the clusters having several local maxima.  
 //               // time - print benchmarking results
 
 // --- ROOT system ---
 //               // time - print benchmarking results
 
 // --- ROOT system ---
-
-#include "TROOT.h" 
-#include "TFile.h" 
-#include "TFolder.h" 
-#include "TMath.h" 
-#include "TMinuit.h"
-#include "TTree.h" 
-#include "TSystem.h" 
-#include "TBenchmark.h"
+#include <cassert>
+
+class TROOT;
+#include <TH1.h>
+#include <TFile.h> 
+class TFolder;
+#include <TMath.h> 
+#include <TMinuit.h>
+#include <TTree.h> 
+class TSystem; 
+#include <TBenchmark.h>
+#include <TBrowser.h>
+#include <TROOT.h>
 
 // --- Standard library ---
 
 
 // --- Standard library ---
 
-#include <iostream.h>
-#include <iomanip.h>
 
 // --- AliRoot header files ---
 
 // --- AliRoot header files ---
-
+#include "AliRunLoader.h"
+#include "AliRun.h"
+#include "AliESD.h"
 #include "AliEMCALClusterizerv1.h"
 #include "AliEMCALClusterizerv1.h"
+#include "AliEMCALRecPoint.h"
 #include "AliEMCALDigit.h"
 #include "AliEMCALDigitizer.h"
 #include "AliEMCALDigit.h"
 #include "AliEMCALDigitizer.h"
-#include "AliEMCALTowerRecPoint.h"
 #include "AliEMCAL.h"
 #include "AliEMCAL.h"
-#include "AliEMCALGetter.h"
-#include "AliRun.h"
+#include "AliEMCALGeometry.h"
+#include "AliEMCALRecParam.h"
+#include "AliEMCALReconstructor.h"
+#include "AliCDBManager.h"
+#include "AliCaloCalibPedestal.h"
+#include "AliEMCALCalibData.h"
+class AliCDBStorage;
+#include "AliCDBEntry.h"
 
 ClassImp(AliEMCALClusterizerv1)
 
 ClassImp(AliEMCALClusterizerv1)
-  
+
 //____________________________________________________________________________
 //____________________________________________________________________________
-  AliEMCALClusterizerv1::AliEMCALClusterizerv1() : AliEMCALClusterizer()
+AliEMCALClusterizerv1::AliEMCALClusterizerv1()
+  : AliEMCALClusterizer(),
+    fGeom(0),
+    fDefaultInit(kFALSE),
+    fToUnfold(kFALSE),
+    fNumberOfECAClusters(0),fCalibData(0),fCaloPed(0),
+    fADCchannelECA(0.),fADCpedestalECA(0.),fECAClusteringThreshold(0.),fECALocMaxCut(0.),
+    fECAW0(0.),fTimeCut(1.),fTimeMin(-1.),fTimeMax(1.),fMinECut(0.)
 {
 {
-  // default ctor (to be used mainly by Streamer)
+  // ctor with the indication of the file where header Tree and digits Tree are stored
   
   
-  InitParameters() ; 
-  fDefaultInit = kTRUE ; 
+  Init() ;
 }
 
 //____________________________________________________________________________
 }
 
 //____________________________________________________________________________
-AliEMCALClusterizerv1::AliEMCALClusterizerv1(const char* headerFile,const char* name)
-:AliEMCALClusterizer(headerFile, name)
+AliEMCALClusterizerv1::AliEMCALClusterizerv1(AliEMCALGeometry* geometry)
+  : AliEMCALClusterizer(),
+    fGeom(geometry),
+    fDefaultInit(kFALSE),
+    fToUnfold(kFALSE),
+    fNumberOfECAClusters(0),fCalibData(0), fCaloPed(0),
+    fADCchannelECA(0.),fADCpedestalECA(0.),fECAClusteringThreshold(0.),fECALocMaxCut(0.),
+    fECAW0(0.),fTimeCut(1.),fTimeMin(-1.),fTimeMax(1.),fMinECut(0.)
 {
   // ctor with the indication of the file where header Tree and digits Tree are stored
 {
   // ctor with the indication of the file where header Tree and digits Tree are stored
-  
-  InitParameters() ; 
-  fDefaultInit = kFALSE ; 
-  Init() ;
+  // use this contructor to avoid usage of Init() which uses runloader
+  // change needed by HLT - MP
+
+  // Note for the future: the use on runloader should be avoided or optional at least
+  // another way is to make Init virtual and protected at least such that the deriving classes can overload
+  // Init() ;
+  //
+
+  if (!fGeom)
+    {
+      AliFatal("Geometry not initialized.");
+    }
 
 }
 
 }
+
 //____________________________________________________________________________
 //____________________________________________________________________________
-  AliEMCALClusterizerv1::~AliEMCALClusterizerv1()
+AliEMCALClusterizerv1::AliEMCALClusterizerv1(AliEMCALGeometry* geometry, AliEMCALCalibData * calib, AliCaloCalibPedestal * caloped)
+: AliEMCALClusterizer(),
+fGeom(geometry),
+fDefaultInit(kFALSE),
+fToUnfold(kFALSE),
+fNumberOfECAClusters(0),fCalibData(calib), fCaloPed(caloped),
+fADCchannelECA(0.),fADCpedestalECA(0.),fECAClusteringThreshold(0.),fECALocMaxCut(0.),
+fECAW0(0.),fTimeCut(1.),fTimeMin(-1.),fTimeMax(1.),fMinECut(0.)
 {
 {
-  // dtor
-  // fDefaultInit = kTRUE if Clusterizer created by default ctor (to get just the parameters)
-  
-  if (!fDefaultInit) {
-    AliEMCALGetter * gime = AliEMCALGetter::GetInstance() ; 
-    
-    // remove the task from the folder list
-    gime->RemoveTask("C",GetName()) ;
-    
-    // remove the RecPoints from the folder list
-    TString name(GetName()) ; 
-    name.Remove(name.Index(":")) ; 
-    gime->RemoveObjects("D", name) ;  //  Digits
-    gime->RemoveObjects("RT", name) ; // TowerRecPoints
-    gime->RemoveObjects("RP", name) ; // PreShoRecPoints
-    
-    // Delete gAlice
-    gime->CloseFile() ; 
-    
-  }
+       // ctor, geometry and calibration are initialized elsewhere.
+       
+       if (!fGeom)
+               AliFatal("Geometry not initialized.");
+                       
 }
 
 }
 
+
 //____________________________________________________________________________
 //____________________________________________________________________________
-const TString AliEMCALClusterizerv1::BranchName() const 
-{  
-  TString branchName(GetName() ) ;
-  branchName.Remove(branchName.Index(Version())-1) ;
-  return branchName ;
+  AliEMCALClusterizerv1::~AliEMCALClusterizerv1()
+{
+  // dtor
 }
 
 //____________________________________________________________________________
 }
 
 //____________________________________________________________________________
-Float_t  AliEMCALClusterizerv1::Calibrate(Int_t amp, Bool_t inpresho) const
+Float_t  AliEMCALClusterizerv1::Calibrate(const Float_t amp, const Float_t time, const Int_t absId) 
 {
 {
-  if ( inpresho ) // calibrate as pre shower
-     return -fADCpedestalPreSho + amp * fADCchannelPreSho ; 
+  // Convert digitized amplitude into energy.
+  // Calibration parameters are taken from calibration data base for raw data,
+  // or from digitizer parameters for simulated data.
+
+  if(fCalibData){
+    
+    if (fGeom==0)
+      AliFatal("Did not get geometry from EMCALLoader") ;
+    
+    Int_t iSupMod = -1;
+    Int_t nModule = -1;
+    Int_t nIphi   = -1;
+    Int_t nIeta   = -1;
+    Int_t iphi    = -1;
+    Int_t ieta    = -1;
+    
+    Bool_t bCell = fGeom->GetCellIndex(absId, iSupMod, nModule, nIphi, nIeta) ;
+    if(!bCell) {
+      fGeom->PrintGeometry();
+      Error("Calibrate()"," Wrong cell id number : %i", absId);
+      assert(0);
+    }
 
 
-  else //calibrate as tower 
-    return -fADCpedestalTower + amp * fADCchannelTower ;                
+    fGeom->GetCellPhiEtaIndexInSModule(iSupMod,nModule,nIphi, nIeta,iphi,ieta);
+         
+       // Check if channel is bad (dead or hot), in this case return 0.        
+       // Gustavo: 15-12-09 In case of RAW data this selection is already done, but not in simulation.
+       // for the moment keep it here but remember to do the selection at the sdigitizer level 
+       // and remove it from here
+       Int_t channelStatus = (Int_t)(fCaloPed->GetDeadMap(iSupMod))->GetBinContent(ieta,iphi);
+       if(channelStatus == AliCaloCalibPedestal::kHot || channelStatus == AliCaloCalibPedestal::kDead) {
+                 AliDebug(2,Form("Tower from SM %d, ieta %d, iphi %d is BAD : status %d !!!",iSupMod,ieta,iphi, channelStatus));
+                 return 0;
+       }
+       //Check if time is too large or too small, indication of a noisy channel, remove in this case
+       if(time > fTimeMax || time < fTimeMin) return 0;
+         
+    fADCchannelECA  = fCalibData->GetADCchannel (iSupMod,ieta,iphi);
+    fADCpedestalECA = fCalibData->GetADCpedestal(iSupMod,ieta,iphi);
+  
+   return -fADCpedestalECA + amp * fADCchannelECA ;        
+  }
+  else //Return energy with default parameters if calibration is not available
+    return -fADCpedestalECA + amp * fADCchannelECA ; 
+  
 }
 }
+
 //____________________________________________________________________________
 //____________________________________________________________________________
-void AliEMCALClusterizerv1::Exec(Option_t * option)
+void AliEMCALClusterizerv1::Digits2Clusters(Option_t * option)
 {
 {
-  // Steering method
-
-  if( strcmp(GetName(), "")== 0 ) 
-    Init() ;
+  // Steering method to perform clusterization for the current event 
+  // in AliEMCALLoader
 
   if(strstr(option,"tim"))
     gBenchmark->Start("EMCALClusterizer"); 
   
   if(strstr(option,"print"))
     Print("") ; 
 
   if(strstr(option,"tim"))
     gBenchmark->Start("EMCALClusterizer"); 
   
   if(strstr(option,"print"))
     Print("") ; 
+  //Get calibration parameters from file or digitizer default values.
+  GetCalibrationParameters() ;
 
 
-  gAlice->GetEvent(0) ;
-  
- //check, if the branch with name of this" already exits?
-  TObjArray * lob = (TObjArray*)gAlice->TreeR()->GetListOfBranches() ;
-  TIter next(lob) ; 
-  TBranch * branch = 0 ;  
-  Bool_t emcaltowerfound = kFALSE, emcalpreshofound = kFALSE, clusterizerfound = kFALSE ; 
-
-  TString branchname = GetName() ;
-  branchname.Remove(branchname.Index(Version())-1) ;
-  
-  while ( (branch = (TBranch*)next()) && (!emcaltowerfound || !emcalpreshofound || !clusterizerfound) ) {
-    if ( (strcmp(branch->GetName(), "EMCALTowerRP")==0) && (strcmp(branch->GetTitle(), branchname.Data())==0) ) 
-      emcaltowerfound = kTRUE ;
-    
-    else if ( (strcmp(branch->GetName(), "EMCALPreShoRP")==0) && (strcmp(branch->GetTitle(), branchname.Data())==0) ) 
-      emcalpreshofound = kTRUE ;
-   
-    else if ((strcmp(branch->GetName(), "AliEMCALClusterizer")==0) && (strcmp(branch->GetTitle(), GetName())==0) ) 
-      clusterizerfound = kTRUE ; 
-  }
-
-  if ( emcalpreshofound || emcaltowerfound || clusterizerfound ) {
-    cerr << "WARNING: AliEMCALClusterizer::Exec -> Tower(PreSho)RecPoints and/or Clusterizer branch with name " 
-        << branchname.Data() << " already exits" << endl ;
-    return ; 
-  }       
+  //Get dead channel map from file or digitizer default values.
+  GetCaloCalibPedestal() ;
+       
+  fNumberOfECAClusters = 0;
 
 
-  AliEMCALGetter * gime = AliEMCALGetter::GetInstance() ;
-  Int_t nevents = (Int_t) gAlice->TreeE()->GetEntries() ;
-  Int_t ievent ;
+  MakeClusters() ;  //only the real clusters
 
 
-  for(ievent = 0; ievent < nevents; ievent++){
+  if(fToUnfold)
+    MakeUnfolding() ;
 
 
-    if(ievent == 0)
-      GetCalibrationParameters() ;
+  Int_t index ;
 
 
-    fNumberOfTowerClusters = fNumberOfPreShoClusters = 0 ;
-   
-    gime->Event(ievent,"D") ;
-        
-    MakeClusters() ;
-    
-    if(fToUnfold)
-      MakeUnfolding() ;
+  //Evaluate position, dispersion and other RecPoint properties for EC section                      
+  for(index = 0; index < fRecPoints->GetEntries(); index++) {
+      dynamic_cast<AliEMCALRecPoint *>(fRecPoints->At(index))->EvalAll(fECAW0,fDigitsArr) ;
+         //For each rec.point set the distance to the nearest bad crystal
+         dynamic_cast<AliEMCALRecPoint *>(fRecPoints->At(index))->EvalDistanceToBadChannels(fCaloPed);
+  }
 
 
-    WriteRecPoints(ievent) ;
+  fRecPoints->Sort() ;
 
 
-    if(strstr(option,"deb"))  
-      PrintRecPoints(option) ;
+  for(index = 0; index < fRecPoints->GetEntries(); index++) {
+    (dynamic_cast<AliEMCALRecPoint *>(fRecPoints->At(index)))->SetIndexInList(index) ;
+    (dynamic_cast<AliEMCALRecPoint *>(fRecPoints->At(index)))->Print();
+  }
 
 
-    //increment the total number of digits per run 
-    fRecPointsInRun += gime->TowerRecPoints()->GetEntriesFast() ;  
-    fRecPointsInRun += gime->PreShowerRecPoints()->GetEntriesFast() ;  
- }
+  fTreeR->Fill();
   
   
+  if(strstr(option,"deb") || strstr(option,"all"))  
+    PrintRecPoints(option) ;
+
+  AliDebug(1,Form("EMCAL Clusterizer found %d Rec Points",fRecPoints->GetEntriesFast()));
+
+  fRecPoints->Delete();
+
   if(strstr(option,"tim")){
     gBenchmark->Stop("EMCALClusterizer");
   if(strstr(option,"tim")){
     gBenchmark->Stop("EMCALClusterizer");
-    cout << "AliEMCALClusterizer:" << endl ;
-    cout << "  took " << gBenchmark->GetCpuTime("EMCALClusterizer") << " seconds for Clusterizing " 
-        <<  gBenchmark->GetCpuTime("EMCALClusterizer")/nevents << " seconds per event " << endl ;
-    cout << endl ;
-  }
-  
+    printf("Exec took %f seconds for Clusterizing", 
+          gBenchmark->GetCpuTime("EMCALClusterizer"));
+  }    
 }
 
 //____________________________________________________________________________
 }
 
 //____________________________________________________________________________
-Bool_t AliEMCALClusterizerv1::FindFit(AliEMCALTowerRecPoint * emcRP, AliEMCALDigit ** maxAt, Float_t * maxAtEnergy,
-                                   Int_t nPar, Float_t * fitparameters) const
-{ 
-  // Calls TMinuit to fit the energy distribution of a cluster with several maxima 
-  // The initial values for fitting procedure are set equal to the positions of local maxima.
-  // Cluster will be fitted as a superposition of nPar/3 electromagnetic showers
+Bool_t AliEMCALClusterizerv1::FindFit(AliEMCALRecPoint * recPoint, AliEMCALDigit ** maxAt, 
+                                     const Float_t* maxAtEnergy,
+                                     Int_t nPar, Float_t * fitparameters) const
+{
+  // Calls TMinuit to fit the energy distribution of a cluster with several maxima
+  // The initial values for fitting procedure are set equal to the
+  // positions of local maxima.       
+  // Cluster will be fitted as a superposition of nPar/3
+  // electromagnetic showers
 
 
-  AliEMCALGetter * gime = AliEMCALGetter::GetInstance() ; 
-  TClonesArray * digits = gime->Digits() ; 
-  
+  if (fGeom==0) AliFatal("Did not get geometry from EMCALLoader");
+       
+  if(!gMinuit)
+     gMinuit = new TMinuit(100) ;
 
   gMinuit->mncler();                     // Reset Minuit's list of paramters
   gMinuit->SetPrintLevel(-1) ;           // No Printout
 
   gMinuit->mncler();                     // Reset Minuit's list of paramters
   gMinuit->SetPrintLevel(-1) ;           // No Printout
-  gMinuit->SetFCN(AliEMCALClusterizerv1::UnfoldingChiSquare) ;  
-                                         // To set the address of the minimization function 
-
+  gMinuit->SetFCN(AliEMCALClusterizerv1::UnfoldingChiSquare) ;
+  // To set the address of the minimization function
   TList * toMinuit = new TList();
   TList * toMinuit = new TList();
-  toMinuit->AddAt(emcRP,0) ;
-  toMinuit->AddAt(digits,1) ;
-  
+  toMinuit->AddAt(recPoint,0) ;
+  toMinuit->AddAt(fDigitsArr,1) ;
+  toMinuit->AddAt(fGeom,2) ;
+
   gMinuit->SetObjectFit(toMinuit) ;         // To tranfer pointer to UnfoldingChiSquare
 
   // filling initial values for fit parameters
   AliEMCALDigit * digit ;
 
   gMinuit->SetObjectFit(toMinuit) ;         // To tranfer pointer to UnfoldingChiSquare
 
   // filling initial values for fit parameters
   AliEMCALDigit * digit ;
 
-  Int_t ierflg  = 0; 
+  Int_t ierflg  = 0;
   Int_t index   = 0 ;
   Int_t nDigits = (Int_t) nPar / 3 ;
 
   Int_t iDigit ;
 
   Int_t index   = 0 ;
   Int_t nDigits = (Int_t) nPar / 3 ;
 
   Int_t iDigit ;
 
-  AliEMCALGeometry * geom = gime->EMCALGeometry() ; 
-
   for(iDigit = 0; iDigit < nDigits; iDigit++){
   for(iDigit = 0; iDigit < nDigits; iDigit++){
-    digit = maxAt[iDigit]; 
+    digit = maxAt[iDigit];
+    Double_t x = 0.;
+    Double_t y = 0.;
+    Double_t z = 0.;
 
 
-    Int_t relid[4] ;
-    Float_t x = 0.;
-    Float_t z = 0.;
-    geom->AbsToRelNumbering(digit->GetId(), relid) ;
-    geom->PosInAlice(relid, x, z) ;
+    fGeom->RelPosCellInSModule(digit->GetId(), y, x, z);
 
     Float_t energy = maxAtEnergy[iDigit] ;
 
     gMinuit->mnparm(index, "x",  x, 0.1, 0, 0, ierflg) ;
 
     Float_t energy = maxAtEnergy[iDigit] ;
 
     gMinuit->mnparm(index, "x",  x, 0.1, 0, 0, ierflg) ;
-    index++ ;   
-    if(ierflg != 0){ 
-      cout << "EMCAL Unfolding>  Unable to set initial value for fit procedure : x = " << x << endl ;
+    index++ ;
+    if(ierflg != 0){
+      Error("FindFit", "EMCAL Unfolding  Unable to set initial value for fit procedure : x = %f", x ) ;
       return kFALSE;
     }
     gMinuit->mnparm(index, "z",  z, 0.1, 0, 0, ierflg) ;
       return kFALSE;
     }
     gMinuit->mnparm(index, "z",  z, 0.1, 0, 0, ierflg) ;
-    index++ ;   
+    index++ ;
     if(ierflg != 0){
     if(ierflg != 0){
-      cout << "EMCAL Unfolding>  Unable to set initial value for fit procedure : z = " << z << endl ;
+      Error("FindFit", "EMCAL Unfolding  Unable to set initial value for fit procedure : z = %f", z) ;
       return kFALSE;
     }
     gMinuit->mnparm(index, "Energy",  energy , 0.05*energy, 0., 4.*energy, ierflg) ;
       return kFALSE;
     }
     gMinuit->mnparm(index, "Energy",  energy , 0.05*energy, 0., 4.*energy, ierflg) ;
-    index++ ;   
+    index++ ;
     if(ierflg != 0){
     if(ierflg != 0){
-      cout << "EMCAL Unfolding>  Unable to set initial value for fit procedure : energy = " << energy << endl ;      
+      Error("FindFit", "EMCAL Unfolding  Unable to set initial value for fit procedure : energy = %f", energy) ;
       return kFALSE;
     }
   }
 
       return kFALSE;
     }
   }
 
-  Double_t p0 = 0.1 ; // "Tolerance" Evaluation stops when EDM = 0.0001*p0 ; The number of function call slightly
-                      //  depends on it. 
-  Double_t p1 = 1.0 ;
+  Double_t p0 = 0.1 ; // "Tolerance" Evaluation stops when EDM = 0.0001*p0 ; 
+                      // The number of function call slightly depends on it.
+  //Double_t p1 = 1.0 ;
   Double_t p2 = 0.0 ;
 
   Double_t p2 = 0.0 ;
 
-  gMinuit->mnexcm("SET STR", &p2, 0, ierflg) ;   // force TMinuit to reduce function calls  
-  gMinuit->mnexcm("SET GRA", &p1, 1, ierflg) ;   // force TMinuit to use my gradient  
+  gMinuit->mnexcm("SET STR", &p2, 0, ierflg) ;   // force TMinuit to reduce function calls
+  //  gMinuit->mnexcm("SET GRA", &p1, 1, ierflg) ;   // force TMinuit to use my gradient
   gMinuit->SetMaxIterations(5);
   gMinuit->mnexcm("SET NOW", &p2 , 0, ierflg) ;  // No Warnings
   gMinuit->SetMaxIterations(5);
   gMinuit->mnexcm("SET NOW", &p2 , 0, ierflg) ;  // No Warnings
+  gMinuit->mnexcm("MIGRAD", &p0, 0, ierflg) ;    // minimize
 
 
-  gMinuit->mnexcm("MIGRAD", &p0, 0, ierflg) ;    // minimize 
-
-  if(ierflg == 4){  // Minimum not found   
-    cout << "EMCAL Unfolding>  Fit not converged, cluster abandoned "<< endl ;      
+  if(ierflg == 4){  // Minimum not found
+    Error("FindFit", "EMCAL Unfolding  Fit not converged, cluster abandoned " ) ;
     return kFALSE ;
     return kFALSE ;
-  }            
+  }
   for(index = 0; index < nPar; index++){
     Double_t err ;
     Double_t val ;
     gMinuit->GetParameter(index, val, err) ;    // Returns value and error of parameter index
     fitparameters[index] = val ;
   for(index = 0; index < nPar; index++){
     Double_t err ;
     Double_t val ;
     gMinuit->GetParameter(index, val, err) ;    // Returns value and error of parameter index
     fitparameters[index] = val ;
-   }
+  }
 
   delete toMinuit ;
   return kTRUE;
 
   delete toMinuit ;
   return kTRUE;
@@ -319,765 +353,570 @@ Bool_t AliEMCALClusterizerv1::FindFit(AliEMCALTowerRecPoint * emcRP, AliEMCALDig
 //____________________________________________________________________________
 void AliEMCALClusterizerv1::GetCalibrationParameters() 
 {
 //____________________________________________________________________________
 void AliEMCALClusterizerv1::GetCalibrationParameters() 
 {
-  AliEMCALGetter * gime = AliEMCALGetter::GetInstance() ;
-  TString branchname = GetName() ;
-  branchname.Remove(branchname.Index(Version())-1) ;
-
-  AliEMCALDigitizer * dig = gime->Digitizer(branchname) ;
+  // Set calibration parameters:
+  // if calibration database exists, they are read from database,
+  // otherwise, they are taken from digitizer.
+  //
+  // It is a user responsilibity to open CDB before reconstruction, 
+  // for example: 
+  // AliCDBStorage* storage = AliCDBManager::Instance()->GetStorage("local://CalibDB");
+
+  //Check if calibration is stored in data base
+
+  if(!fCalibData)
+    {
+      AliCDBEntry *entry = (AliCDBEntry*) 
+       AliCDBManager::Instance()->Get("EMCAL/Calib/Data");
+      if (entry) fCalibData =  (AliEMCALCalibData*) entry->GetObject();
+    }
+  
+  if(!fCalibData)
+    AliFatal("Calibration parameters not found in CDB!");
+}
 
 
-  fADCchannelTower   = dig->GetTowerchannel() ;
-  fADCpedestalTower  = dig->GetTowerpedestal();
+//____________________________________________________________________________
+void AliEMCALClusterizerv1::GetCaloCalibPedestal() 
+{
+       // Set calibration parameters:
+       // if calibration database exists, they are read from database,
+       // otherwise, they are taken from digitizer.
+       //
+       // It is a user responsilibity to open CDB before reconstruction, 
+       // for example: 
+       // AliCDBStorage* storage = AliCDBManager::Instance()->GetStorage("local://CalibDB");
+       
+       //Check if calibration is stored in data base
+       
+       if(!fCaloPed)
+    {
+               AliCDBEntry *entry = (AliCDBEntry*) 
+               AliCDBManager::Instance()->Get("EMCAL/Calib/Pedestals");
+               if (entry) fCaloPed =  (AliCaloCalibPedestal*) entry->GetObject();
+    }
+       
+       if(!fCaloPed)
+               AliFatal("Pedestal info not found in CDB!");
+       
+}
 
 
-  fADCchannelPreSho  = dig->GetPreShochannel() ;
-  fADCpedestalPreSho = dig->GetPreShopedestal() ; 
 
 
-}
 //____________________________________________________________________________
 void AliEMCALClusterizerv1::Init()
 {
   // Make all memory allocations which can not be done in default constructor.
   // Attach the Clusterizer task to the list of EMCAL tasks
   
 //____________________________________________________________________________
 void AliEMCALClusterizerv1::Init()
 {
   // Make all memory allocations which can not be done in default constructor.
   // Attach the Clusterizer task to the list of EMCAL tasks
   
-  if ( strcmp(GetTitle(), "") == 0 )
-    SetTitle("galice.root") ;
-
-  TString branchname = GetName() ;
-  branchname.Remove(branchname.Index(Version())-1) ;
+  AliRunLoader *rl = AliRunLoader::Instance();
+  if (rl->GetAliRun() && rl->GetAliRun()->GetDetector("EMCAL"))
+    fGeom = dynamic_cast<AliEMCAL*>(rl->GetAliRun()->GetDetector("EMCAL"))->GetGeometry();
+  else 
+    fGeom =  AliEMCALGeometry::GetInstance(AliEMCALGeometry::GetDefaultGeometryName());
 
 
-  AliEMCALGetter * gime = AliEMCALGetter::GetInstance(GetTitle(), branchname, "update") ; 
-  if ( gime == 0 ) {
-    cerr << "ERROR: AliEMCALClusterizerv1::Init -> Could not obtain the Getter object !" << endl ; 
-    return ;
-  } 
-    
-  const AliEMCALGeometry * geom = gime->EMCALGeometry() ;
-  fNTowers = geom->GetNZ() *  geom->GetNPhi() ;
+  AliDebug(1,Form("geom %p",fGeom));
 
   if(!gMinuit) 
     gMinuit = new TMinuit(100) ;
 
 
   if(!gMinuit) 
     gMinuit = new TMinuit(100) ;
 
-  gime->PostClusterizer(this) ;
-  // create a folder on the white board 
-  gime->PostRecPoints(branchname ) ;
-
-  gime->PostDigits(branchname) ;
-  gime->PostDigitizer(branchname) ;
-  
 }
 
 //____________________________________________________________________________
 void AliEMCALClusterizerv1::InitParameters()
 }
 
 //____________________________________________________________________________
 void AliEMCALClusterizerv1::InitParameters()
-{
-  fNumberOfPreShoClusters = fNumberOfTowerClusters = 0 ; 
+{ 
+  // Initializes the parameters for the Clusterizer
+  fNumberOfECAClusters = 0;
 
 
-  
-  fPreShoClusteringThreshold  = 0.0001;
-  fTowerClusteringThreshold   = 0.2;   
-  
-  fTowerLocMaxCut  = 0.03 ;
-  fPreShoLocMaxCut = 0.03 ;
-  
-  fW0     = 4.5 ;
-  fW0CPV  = 4.0 ;
+  fCalibData               = 0 ;
+  fCaloPed                 = 0 ;
+       
+  const AliEMCALRecParam* recParam = AliEMCALReconstructor::GetRecParam();
+  if(!recParam) {
+    AliFatal("Reconstruction parameters for EMCAL not set!");
+  } else {
+    fECAClusteringThreshold = recParam->GetClusteringThreshold();
+    fECAW0                  = recParam->GetW0();
+    fMinECut                = recParam->GetMinECut();    
+    fToUnfold               = recParam->GetUnfold();
+    if(fToUnfold) AliWarning("Cluster Unfolding ON. Implementing only for eta=0 case!!!"); 
+    fECALocMaxCut           = recParam->GetLocMaxCut();
+    fTimeCut                = recParam->GetTimeCut();
+    fTimeMin                = recParam->GetTimeMin();
+    fTimeMax                = recParam->GetTimeMax();
+
+    AliDebug(1,Form("Reconstruction parameters: fECAClusteringThreshold=%.3f GeV, fECAW=%.3f, fMinECut=%.3f GeV, fToUnfold=%d, fECALocMaxCut=%.3f GeV, fTimeCut=%e s,fTimeMin=%e s,fTimeMax=%e s",
+                   fECAClusteringThreshold,fECAW0,fMinECut,fToUnfold,fECALocMaxCut,fTimeCut, fTimeMin, fTimeMax));
+  }
 
 
-  fTimeGate = 1.e-8 ; 
-  
-  fToUnfold = kFALSE ;
-  
-  fHeaderFileName     = GetTitle() ; 
-  fDigitsBranchTitle  = GetName() ;
-  
-  TString clusterizerName( GetName()) ; 
-  if (clusterizerName.IsNull() ) 
-    clusterizerName = "Default" ; 
-  clusterizerName.Append(":") ; 
-  clusterizerName.Append(Version()) ; 
-  SetName(clusterizerName) ;
-  fRecPointsInRun          = 0 ; 
 }
 
 //____________________________________________________________________________
 }
 
 //____________________________________________________________________________
-Int_t AliEMCALClusterizerv1::AreNeighbours(AliEMCALDigit * d1, AliEMCALDigit * d2)const
+Int_t AliEMCALClusterizerv1::AreNeighbours(AliEMCALDigit * d1, AliEMCALDigit * d2, Bool_t & shared) const
 {
 {
-  // Gives the neighbourness of two digits = 0 are not neighbour but continue searching 
-  //                                       = 1 are neighbour
-  //                                       = 2 are not neighbour but do not continue searching
-  // neighbours are defined as digits having at least a common vertex 
-  // The order of d1 and d2 is important: first (d1) should be a digit already in a cluster 
-  //                                      which is compared to a digit (d2)  not yet in a cluster  
+       // Gives the neighbourness of two digits = 0 are not neighbour ; continue searching 
+       //                                       = 1 are neighbour
+       //                                       = 2 is in different SM; continue searching 
+       // In case it is in different SM, but same phi rack, check if neigbours at eta=0
+       // neighbours are defined as digits having at least a common side 
+       // The order of d1 and d2 is important: first (d1) should be a digit already in a cluster 
+       //                                      which is compared to a digit (d2)  not yet in a cluster  
+       
+       static Int_t nSupMod1=0, nModule1=0, nIphi1=0, nIeta1=0, iphi1=0, ieta1=0;
+       static Int_t nSupMod2=0, nModule2=0, nIphi2=0, nIeta2=0, iphi2=0, ieta2=0;
+       static Int_t rowdiff, coldiff;
 
 
-   AliEMCALGeometry * geom = AliEMCALGetter::GetInstance()->EMCALGeometry() ;
+       shared = kFALSE;
+       
+       fGeom->GetCellIndex(d1->GetId(), nSupMod1,nModule1,nIphi1,nIeta1);
+       fGeom->GetCellIndex(d2->GetId(), nSupMod2,nModule2,nIphi2,nIeta2);
+       fGeom->GetCellPhiEtaIndexInSModule(nSupMod1,nModule1,nIphi1,nIeta1, iphi1,ieta1);
+       fGeom->GetCellPhiEtaIndexInSModule(nSupMod2,nModule2,nIphi2,nIeta2, iphi2,ieta2);
+       
+       //If different SM, check if they are in the same phi, then consider cells close to eta=0 as neighbours; May 2010
+       if(nSupMod1 != nSupMod2 ) {
+               //Check if the 2 SM are in the same PHI position (0,1), (2,3), ...
+               Float_t smPhi1 = fGeom->GetEMCGeometry()->GetPhiCenterOfSM(nSupMod1);
+               Float_t smPhi2 = fGeom->GetEMCGeometry()->GetPhiCenterOfSM(nSupMod2);
+               
+               if(!TMath::AreEqualAbs(smPhi1, smPhi2, 1e-3)) return 2; //Not phi rack equal, not neighbours
+                               
+               // In case of a shared cluster, index of SM in C side, columns start at 48 and ends at 48*2
+               // C Side impair SM, nSupMod%2=1; A side pair SM nSupMod%2=0
+               if(nSupMod1%2) ieta1+=AliEMCALGeoParams::fgkEMCALCols;
+               else           ieta2+=AliEMCALGeoParams::fgkEMCALCols;
+               
+               shared = kTRUE; // maybe a shared cluster, we know this later, set it for the moment.
+               
+       }//Different SM, same phi
+       
+       rowdiff = TMath::Abs(iphi1 - iphi2);  
+       coldiff = TMath::Abs(ieta1 - ieta2) ;  
 
 
-  Int_t rv = 0 ; 
+       // neighbours with at least common side; May 11, 2007
+       if ((coldiff==0 && TMath::Abs(rowdiff)==1) || (rowdiff==0 && TMath::Abs(coldiff)==1)) {  
+       //Diagonal?
+       //if ((coldiff==0 && TMath::Abs(rowdiff==1)) || (rowdiff==0 && TMath::Abs(coldiff==1)) || (TMath::Abs(rowdiff)==1 && TMath::Abs(coldiff==1))) rv = 1;
+       
+       if (gDebug == 2) 
+               printf("AliEMCALClusterizerv1::AreNeighbours(): id1=%d, (row %d, col %d) ; id2=%d, (row %d, col %d), shared %d \n",
+                               d1->GetId(), iphi1,ieta1, d2->GetId(), iphi2,ieta2, shared);   
+       
+               return 1;
+       }//Neighbours
+       else {
+               shared = kFALSE;
+               return 2 ; 
+       }//Not neighbours
+}
 
 
-  Int_t relid1[4] ; 
-  geom->AbsToRelNumbering(d1->GetId(), relid1) ; 
+//____________________________________________________________________________
+void AliEMCALClusterizerv1::MakeClusters()
+{
+  // Steering method to construct the clusters stored in a list of Reconstructed Points
+  // A cluster is defined as a list of neighbour digits
+  // Mar 03, 2007 by PAI
 
 
-  Int_t relid2[4] ; 
-  geom->AbsToRelNumbering(d2->GetId(), relid2) ; 
-  if ( (relid1[0] == relid2[0]) && (relid1[1]==relid2[1]) ) { // inside the same EMCAL Arm 
-    Int_t rowdiff = TMath::Abs( relid1[2] - relid2[2] ) ;  
-    Int_t coldiff = TMath::Abs( relid1[3] - relid2[3] ) ;  
-    
-    if (( coldiff <= 1 )  && ( rowdiff <= 1 )){
-      if((relid1[1] != 0) || (TMath::Abs(d1->GetTime() - d2->GetTime() ) < fTimeGate))
-      rv = 1 ; 
-    }
-    else {
-      if((relid2[2] > relid1[2]) && (relid2[3] > relid1[3]+1)) 
-       rv = 2; //  Difference in row numbers is too large to look further 
-    }
+  if (fGeom==0) AliFatal("Did not get geometry from EMCALLoader");
 
 
-  } 
-  else {
-    
-    if( (relid1[0] < relid2[0]) || (relid1[1] != relid2[1]) )  
-      rv=2 ;
+  fRecPoints->Clear();
 
 
+  // Set up TObjArray with pointers to digits to work on 
+  TObjArray *digitsC = new TObjArray();
+  TIter nextdigit(fDigitsArr);
+  AliEMCALDigit *digit;
+  while ( (digit = dynamic_cast<AliEMCALDigit*>(nextdigit())) ) {
+    digitsC->AddLast(digit);
   }
 
   }
 
-  return rv ; 
-}
+  double e = 0.0, ehs = 0.0;
+  TIter nextdigitC(digitsC);
+  while ( (digit = dynamic_cast<AliEMCALDigit *>(nextdigitC())) ) { // clean up digits
+    e = Calibrate(digit->GetAmplitude(), digit->GetTime(),digit->GetId());//Time or TimeR?
+    if ( e < fMinECut) //|| digit->GetTimeR() > fTimeCut ) // time window of cell checked in calibrate
+      digitsC->Remove(digit);
+    else    
+      ehs += e;
+  } 
+  AliDebug(1,Form("MakeClusters: Number of digits %d  -> (e %f), ehs %f\n",
+                 fDigitsArr->GetEntries(),fMinECut,ehs));
+
+  nextdigitC.Reset();
+
+  while ( (digit = dynamic_cast<AliEMCALDigit *>(nextdigitC())) ) { // scan over the list of digitsC
+    TArrayI clusterECAdigitslist(fDigitsArr->GetEntries());
+
+    if(fGeom->CheckAbsCellId(digit->GetId()) && (Calibrate(digit->GetAmplitude(), digit->GetTime(),digit->GetId()) > fECAClusteringThreshold  ) ){
+      // start a new Tower RecPoint
+      if(fNumberOfECAClusters >= fRecPoints->GetSize()) fRecPoints->Expand(2*fNumberOfECAClusters+1) ;
+
+      AliEMCALRecPoint *recPoint = new  AliEMCALRecPoint("") ; 
+      fRecPoints->AddAt(recPoint, fNumberOfECAClusters) ;
+      recPoint = dynamic_cast<AliEMCALRecPoint *>(fRecPoints->At(fNumberOfECAClusters)) ; 
+      fNumberOfECAClusters++ ; 
+
+      recPoint->SetClusterType(AliESDCaloCluster::kEMCALClusterv1);
+
+      recPoint->AddDigit(*digit, Calibrate(digit->GetAmplitude(), digit->GetTime(),digit->GetId()),kFALSE) ; //Time or TimeR?
+      TObjArray clusterDigits;
+      clusterDigits.AddLast(digit);    
+      digitsC->Remove(digit) ; 
+
+      AliDebug(1,Form("MakeClusters: OK id = %d, ene = %f , cell.th. = %f \n", digit->GetId(),
+      Calibrate(digit->GetAmplitude(),digit->GetTime(),digit->GetId()), fECAClusteringThreshold));  //Time or TimeR?
+         Float_t time = digit->GetTime();//Time or TimeR?
+      // Grow cluster by finding neighbours
+      TIter nextClusterDigit(&clusterDigits);
+      while ( (digit = dynamic_cast<AliEMCALDigit*>(nextClusterDigit())) ) { // scan over digits in cluster 
+        TIter nextdigitN(digitsC); 
+        AliEMCALDigit *digitN = 0; // digi neighbor
+        while ( (digitN = (AliEMCALDigit *)nextdigitN()) ) { // scan over all digits to look for neighbours
+                       
+                       //Do not add digits with too different time 
+                       Bool_t shared = kFALSE;//cluster shared by 2 SuperModules?
+                       if(TMath::Abs(time - digitN->GetTime()) > fTimeCut ) continue; //Time or TimeR?
+                       if (AreNeighbours(digit, digitN, shared)==1) {      // call (digit,digitN) in THAT order !!!!! 
+                               recPoint->AddDigit(*digitN, Calibrate(digitN->GetAmplitude(), digitN->GetTime(), digitN->GetId()),shared) ;//Time or TimeR?
+                               clusterDigits.AddLast(digitN) ; 
+                               digitsC->Remove(digitN) ; 
+                       } // if(ineb==1)
+               } // scan over digits
+      } // scan over digits already in cluster
+       
+      if(recPoint)
+        AliDebug(2,Form("MakeClusters: %d digitd, energy %f \n", clusterDigits.GetEntries(), recPoint->GetEnergy())); 
+    } // If seed found
+  } // while digit 
 
 
+  delete digitsC ;
+  
+  AliDebug(1,Form("total no of clusters %d from %d digits",fNumberOfECAClusters,fDigitsArr->GetEntriesFast())); 
+}
 
 //____________________________________________________________________________
 
 //____________________________________________________________________________
-Bool_t AliEMCALClusterizerv1::IsInTower(AliEMCALDigit * digit) const
+void AliEMCALClusterizerv1::MakeUnfolding()
 {
 {
-  // Tells if (true) or not (false) the digit is in a EMCAL-Tower 
-  Bool_t rv = kFALSE ; 
-  if (!digit->IsInPreShower()) 
-    rv = kTRUE; 
-  return rv ; 
+  // Unfolds clusters using the shape of an ElectroMagnetic shower
+  // Performs unfolding of all clusters
+               
+  if(fNumberOfECAClusters > 0){
+    if (fGeom==0)
+      AliFatal("Did not get geometry from EMCALLoader") ;
+    Int_t nModulesToUnfold = fGeom->GetNCells();
+
+    Int_t numberofNotUnfolded = fNumberOfECAClusters ;
+    Int_t index ;
+    for(index = 0 ; index < numberofNotUnfolded ; index++){
+
+      AliEMCALRecPoint * recPoint = dynamic_cast<AliEMCALRecPoint *>( fRecPoints->At(index) ) ;
+
+      TVector3 gpos;
+      Int_t absId;
+      recPoint->GetGlobalPosition(gpos);
+      fGeom->GetAbsCellIdFromEtaPhi(gpos.Eta(),gpos.Phi(),absId);
+      if(absId > nModulesToUnfold)
+        break ;
+
+      Int_t nMultipl = recPoint->GetMultiplicity() ;
+      AliEMCALDigit ** maxAt = new AliEMCALDigit*[nMultipl] ;
+      Float_t * maxAtEnergy = new Float_t[nMultipl] ;
+      Int_t nMax = recPoint->GetNumberOfLocalMax(maxAt, maxAtEnergy,fECALocMaxCut,fDigitsArr) ;
+
+      if( nMax > 1 ) {     // if cluster is very flat (no pronounced maximum) then nMax = 0
+        UnfoldCluster(recPoint, nMax, maxAt, maxAtEnergy) ;
+        fRecPoints->Remove(recPoint);
+        fRecPoints->Compress() ;
+        index-- ;
+        fNumberOfECAClusters-- ;
+        numberofNotUnfolded-- ;
+      }
+      else{
+        recPoint->SetNExMax(1) ; //Only one local maximum
+      }
+
+      delete[] maxAt ;
+      delete[] maxAtEnergy ;
+    }
+  }
+  // End of Unfolding of clusters
 }
 
 //____________________________________________________________________________
 }
 
 //____________________________________________________________________________
-Bool_t AliEMCALClusterizerv1::IsInPreShower(AliEMCALDigit * digit) const
-{
-  // Tells if (true) or not (false) the digit is in a EMCAL-PreShower
-  Bool_t rv = kFALSE ; 
-  if (digit->IsInPreShower()) 
-    rv = kTRUE; 
-  return rv ; 
+Double_t  AliEMCALClusterizerv1::ShowerShape(Double_t x, Double_t y)
+{ 
+  // Shape of the shower
+  // If you change this function, change also the gradient evaluation in ChiSquare()
+
+  Double_t r = sqrt(x*x+y*y);
+  Double_t r133  = TMath::Power(r, 1.33) ;
+  Double_t r669  = TMath::Power(r, 6.69) ;
+  Double_t shape = TMath::Exp( -r133 * (1. / (1.57 + 0.0860 * r133) - 0.55 / (1 + 0.000563 * r669) ) ) ;
+  return shape ;
 }
 
 //____________________________________________________________________________
 }
 
 //____________________________________________________________________________
-void AliEMCALClusterizerv1::WriteRecPoints(Int_t event)
+void  AliEMCALClusterizerv1::UnfoldCluster(AliEMCALRecPoint * iniTower, 
+                                          Int_t nMax, 
+                                          AliEMCALDigit ** maxAt, 
+                                          Float_t * maxAtEnergy)
 {
 {
+  // Performs the unfolding of a cluster with nMax overlapping showers 
+  Int_t nPar = 3 * nMax ;
+  Float_t * fitparameters = new Float_t[nPar] ;
 
 
-  // Creates new branches with given title
-  // fills and writes into TreeR.
-
-  AliEMCALGetter *gime = AliEMCALGetter::GetInstance() ; 
-  TObjArray * towerRecPoints = gime->TowerRecPoints(BranchName()) ; 
-  TObjArray * preshoRecPoints = gime->PreShowerRecPoints(BranchName()) ; 
-  TClonesArray * digits = gime->Digits(BranchName()) ; 
-  TTree * treeR ; 
-
-  if (!gAlice->TreeR() ) 
-    gAlice->MakeTree("R", fSplitFile);
-  treeR = gAlice->TreeR() ;
-    
-    Int_t index ;
-  //Evaluate position, dispersion and other RecPoint properties...
-  for(index = 0; index < towerRecPoints->GetEntries(); index++)
-    (dynamic_cast<AliEMCALTowerRecPoint *>(towerRecPoints->At(index)))->EvalAll(fW0,digits) ;
+  if (fGeom==0)
+    AliFatal("Did not get geometry from EMCALLoader") ;
 
 
-  towerRecPoints->Sort() ;
+  Bool_t rv = FindFit(iniTower, maxAt, maxAtEnergy, nPar, fitparameters) ;
+  if( !rv ) {
+    // Fit failed, return and remove cluster
+    iniTower->SetNExMax(-1) ;
+    delete[] fitparameters ;
+    return ;
+  }
 
 
-  for(index = 0; index < towerRecPoints->GetEntries(); index++)
-    (dynamic_cast<AliEMCALTowerRecPoint *>(towerRecPoints->At(index)))->SetIndexInList(index) ;
+  // create unfolded rec points and fill them with new energy lists
+  // First calculate energy deposited in each sell in accordance with
+  // fit (without fluctuations): efit[]
+  // and later correct this number in acordance with actual energy
+  // deposition
 
 
-  towerRecPoints->Expand(towerRecPoints->GetEntriesFast()) ; 
+  Int_t nDigits = iniTower->GetMultiplicity() ;
+  Float_t * efit = new Float_t[nDigits] ;
+  Double_t xDigit=0.,yDigit=0.,zDigit=0. ;
+  Float_t xpar=0.,zpar=0.,epar=0.  ;
 
 
-  //Now the same for pre shower
-  for(index = 0; index < preshoRecPoints->GetEntries(); index++)
-    (dynamic_cast<AliEMCALRecPoint *>(preshoRecPoints->At(index)))->EvalAll(fW0CPV,digits)  ;
+  AliEMCALDigit * digit = 0 ;
+  Int_t * digitsList = iniTower->GetDigitsList() ;
 
 
-  preshoRecPoints->Sort() ;
+  Int_t iparam ;
+  Int_t iDigit ;
+  for(iDigit = 0 ; iDigit < nDigits ; iDigit ++){
+    digit = dynamic_cast<AliEMCALDigit*>( fDigitsArr->At(digitsList[iDigit] ) ) ;
+    fGeom->RelPosCellInSModule(digit->GetId(), yDigit, xDigit, zDigit);
+    efit[iDigit] = 0;
+
+    iparam = 0 ;
+    while(iparam < nPar ){
+      xpar = fitparameters[iparam] ;
+      zpar = fitparameters[iparam+1] ;
+      epar = fitparameters[iparam+2] ;
+      iparam += 3 ;
+      efit[iDigit] += epar * ShowerShape(xDigit - xpar,zDigit - zpar) ;
+    }
+  }
 
 
-  for(index = 0; index < preshoRecPoints->GetEntries(); index++)
-    (dynamic_cast<AliEMCALRecPoint *>(preshoRecPoints->At(index)))->SetIndexInList(index) ;
 
 
-  preshoRecPoints->Expand(preshoRecPoints->GetEntriesFast()) ;
-  
-  //Make branches in TreeR for RecPoints and Clusterizer
-  
-  Int_t bufferSize = 32000 ;    
-  Int_t splitlevel = 0 ;
+  // Now create new RecPoints and fill energy lists with efit corrected to fluctuations
+  // so that energy deposited in each cell is distributed between new clusters proportionally
+  // to its contribution to efit
 
 
-  //First Tower branch
-  TBranch * emcBranch = treeR->Branch("EMCALTowerRP","TObjArray",&towerRecPoints,bufferSize,splitlevel);
-  emcBranch->SetTitle(BranchName());
+  Float_t * energiesList = iniTower->GetEnergiesList() ;
+  Float_t ratio ;
 
 
-    
-  //Now Pre Shower branch 
-  TBranch * cpvBranch = treeR->Branch("EMCALPreShoRP","TObjArray",&preshoRecPoints,bufferSize,splitlevel);
-  cpvBranch->SetTitle(BranchName());
+  iparam = 0 ;
+  while(iparam < nPar ){
+    xpar = fitparameters[iparam] ;
+    zpar = fitparameters[iparam+1] ;
+    epar = fitparameters[iparam+2] ;
+    iparam += 3 ;
 
 
-    
-  //And Finally  clusterizer branch
-  AliEMCALClusterizerv1 * cl = (AliEMCALClusterizerv1*)gime->Clusterizer(BranchName()) ;
-  TBranch * clusterizerBranch = treeR->Branch("AliEMCALClusterizer","AliEMCALClusterizerv1",
-                                             &cl,bufferSize,splitlevel);
-  clusterizerBranch->SetTitle(BranchName());
+    AliEMCALRecPoint * recPoint = 0 ;
 
 
-  emcBranch        ->Fill() ;
-  cpvBranch        ->Fill() ;
-  clusterizerBranch->Fill() ;
+    if(fNumberOfECAClusters >= fRecPoints->GetSize())
+      fRecPoints->Expand(2*fNumberOfECAClusters) ;
 
 
-  treeR->AutoSave() ; //Write(0,kOverwrite) ;  
-  
-}
+    (*fRecPoints)[fNumberOfECAClusters] = new AliEMCALRecPoint("") ;
+    recPoint = dynamic_cast<AliEMCALRecPoint *>( fRecPoints->At(fNumberOfECAClusters) ) ;
+    fNumberOfECAClusters++ ;
+    recPoint->SetNExMax((Int_t)nPar/3) ;
 
 
-//____________________________________________________________________________
-void AliEMCALClusterizerv1::MakeClusters()
-{
-  // Steering method to construct the clusters stored in a list of Reconstructed Points
-  // A cluster is defined as a list of neighbour digits
-  
-  TString branchName(GetName()) ; 
-  branchName.Remove(branchName.Index(Version())-1) ; 
-  
-  AliEMCALGetter * gime = AliEMCALGetter::GetInstance() ; 
-  
-  TObjArray * towerRecPoints  = gime->TowerRecPoints(branchName) ; 
-  TObjArray * preshoRecPoints = gime->PreShowerRecPoints(branchName) ; 
-  towerRecPoints->Delete() ;
-  preshoRecPoints->Delete() ;
-  
-  TClonesArray * digits = gime->Digits(branchName) ; 
-  TClonesArray * digitsC =  dynamic_cast<TClonesArray*>(digits->Clone()) ;
-  
-  
-  // Clusterization starts  
-  
-  TIter nextdigit(digitsC) ; 
-  AliEMCALDigit * digit ; 
-  Bool_t notremoved = kTRUE ;
-  
-  while ( (digit = dynamic_cast<AliEMCALDigit *>(nextdigit())) ) { // scan over the list of digitsC
-    AliEMCALRecPoint * clu = 0 ; 
-    
-    TArrayI clusterdigitslist(1500) ;   
-    Int_t index ;
-    if (( IsInTower (digit)  && Calibrate(digit->GetAmp(),digit->IsInPreShower()) > fTowerClusteringThreshold  ) || 
-        ( IsInPreShower (digit) && Calibrate(digit->GetAmp(),digit->IsInPreShower()) > fPreShoClusteringThreshold  ) ) {
-      
-      Int_t iDigitInCluster = 0 ; 
-      
-      if  ( IsInTower(digit) ) {   
-       // start a new Tower RecPoint
-       if(fNumberOfTowerClusters >= towerRecPoints->GetSize()) 
-         towerRecPoints->Expand(2*fNumberOfTowerClusters+1) ;
-       
-       towerRecPoints->AddAt(new  AliEMCALTowerRecPoint(""), fNumberOfTowerClusters) ;
-       clu = dynamic_cast<AliEMCALTowerRecPoint *>(towerRecPoints->At(fNumberOfTowerClusters)) ; 
-       fNumberOfTowerClusters++ ; 
-       clu->AddDigit(*digit, Calibrate(digit->GetAmp(),digit->IsInPreShower())) ; 
-       clusterdigitslist[iDigitInCluster] = digit->GetIndexInList() ;  
-       iDigitInCluster++ ; 
-       digitsC->Remove(digit) ; 
-       
-      } else { 
-       
-       // start a new Pre Shower cluster
-       if(fNumberOfPreShoClusters >= preshoRecPoints->GetSize()) 
-         preshoRecPoints->Expand(2*fNumberOfPreShoClusters+1);
-       
-       preshoRecPoints->AddAt(new AliEMCALTowerRecPoint(""), fNumberOfPreShoClusters) ;
-       
-       clu =  dynamic_cast<AliEMCALTowerRecPoint *>(preshoRecPoints->At(fNumberOfPreShoClusters))  ;  
-       fNumberOfPreShoClusters++ ; 
-       clu->AddDigit(*digit, Calibrate(digit->GetAmp(),digit->IsInPreShower() ) );     
-       clusterdigitslist[iDigitInCluster] = digit->GetIndexInList()  ; 
-       iDigitInCluster++ ; 
-       digitsC->Remove(digit) ; 
-       nextdigit.Reset() ;
-       
-       // Here we remove remaining Tower digits, which cannot make a cluster
-       
-       if( notremoved ) { 
-         while( ( digit = dynamic_cast<AliEMCALDigit *>(nextdigit()) ) ) {
-           if( IsInTower(digit) )
-             digitsC->Remove(digit) ;
-           else 
-             break ; 
-         }
-         notremoved = kFALSE ;
-       }
-       
-      } // else        
-      
-      nextdigit.Reset() ;
-      
-      AliEMCALDigit * digitN ; 
-      index = 0 ;
-      while (index < iDigitInCluster){ // scan over digits already in cluster 
-       digit =  (AliEMCALDigit*)digits->At(clusterdigitslist[index])  ;      
-       index++ ; 
-        while ( (digitN = (AliEMCALDigit *)nextdigit()) ) { // scan over the reduced list of digits 
-         Int_t ineb = AreNeighbours(digit, digitN);       // call (digit,digitN) in THAT oder !!!!!
-         switch (ineb ) {
-          case 0 :   // not a neighbour
-           break ;
-         case 1 :   // are neighbours 
-           clu->AddDigit(*digitN, Calibrate( digitN->GetAmp(), digitN->IsInPreShower() ) ) ;
-           clusterdigitslist[iDigitInCluster] = digitN->GetIndexInList() ; 
-           iDigitInCluster++ ; 
-           digitsC->Remove(digitN) ;
-           break ;
-          case 2 :   // too far from each other
-           goto endofloop;   
-         } // switch
-         
-       } // while digitN
-       
-      endofloop: ;
-       nextdigit.Reset() ; 
-       
-      } // loop over cluster     
-      
-    } // energy theshold  
-    
-    
-  } // while digit
-  
-  delete digitsC ;
-  
-}
+    Float_t eDigit ;
+    for(iDigit = 0 ; iDigit < nDigits ; iDigit ++){
+      digit = dynamic_cast<AliEMCALDigit*>( fDigitsArr->At( digitsList[iDigit] ) ) ;
+      fGeom->RelPosCellInSModule(digit->GetId(), yDigit, xDigit, zDigit);
 
 
-//____________________________________________________________________________
-void AliEMCALClusterizerv1::MakeUnfolding()
-{
-  Fatal("AliEMCALClusterizerv1::MakeUnfolding", "--> Unfolding not implemented") ;
-  
-//   // Unfolds clusters using the shape of an ElectroMagnetic shower
-//   // Performs unfolding of all EMC/CPV clusters
-
-//   AliEMCALGetter * gime = AliEMCALGetter::GetInstance() ; 
-  
-//   const AliEMCALGeometry * geom = gime->EMCALGeometry() ;
-//   TObjArray * emcRecPoints = gime->TowerRecPoints() ; 
-//   TObjArray * cpvRecPoints = gime->PreShoRecPoints() ; 
-//   TClonesArray * digits = gime->Digits() ; 
-  
-//   // Unfold first EMC clusters 
-//   if(fNumberOfTowerClusters > 0){
-
-//     Int_t nModulesToUnfold = geom->GetNModules() ; 
-
-//     Int_t numberofNotUnfolded = fNumberOfTowerClusters ; 
-//     Int_t index ;   
-//     for(index = 0 ; index < numberofNotUnfolded ; index++){
-      
-//       AliEMCALTowerRecPoint * emcRecPoint = (AliEMCALTowerRecPoint *) emcRecPoints->At(index) ;
-//       if(emcRecPoint->GetEMCALMod()> nModulesToUnfold)
-//     break ;
-      
-//       Int_t nMultipl = emcRecPoint->GetMultiplicity() ; 
-//       Int_t * maxAt = new Int_t[nMultipl] ;
-//       Float_t * maxAtEnergy = new Float_t[nMultipl] ;
-//       Int_t nMax = emcRecPoint->GetNumberOfLocalMax(maxAt, maxAtEnergy,fTowerLocMaxCut,digits) ;
-      
-//       if( nMax > 1 ) {     // if cluster is very flat (no pronounced maximum) then nMax = 0       
-//     UnfoldCluster(emcRecPoint, nMax, maxAt, maxAtEnergy) ;
-//     emcRecPoints->Remove(emcRecPoint); 
-//     emcRecPoints->Compress() ;
-//     index-- ;
-//     fNumberOfTowerClusters -- ;
-//     numberofNotUnfolded-- ;
-//       }
-      
-//       delete[] maxAt ; 
-//       delete[] maxAtEnergy ; 
-//     }
-//   } 
-//   // Unfolding of EMC clusters finished
-
-
-//   // Unfold now CPV clusters
-//   if(fNumberOfPreShoClusters > 0){
-    
-//     Int_t nModulesToUnfold = geom->GetNModules() ;
-
-//     Int_t numberofPreShoNotUnfolded = fNumberOfPreShoClusters ;     
-//     Int_t index ;   
-//     for(index = 0 ; index < numberofPreShoNotUnfolded ; index++){
-      
-//       AliEMCALRecPoint * recPoint = (AliEMCALRecPoint *) cpvRecPoints->At(index) ;
-
-//       if(recPoint->GetEMCALMod()> nModulesToUnfold)
-//     break ;
-      
-//       AliEMCALTowerRecPoint * emcRecPoint = (AliEMCALTowerRecPoint*) recPoint ; 
-      
-//       Int_t nMultipl = emcRecPoint->GetMultiplicity() ; 
-//       Int_t * maxAt = new Int_t[nMultipl] ;
-//       Float_t * maxAtEnergy = new Float_t[nMultipl] ;
-//       Int_t nMax = emcRecPoint->GetNumberOfLocalMax(maxAt, maxAtEnergy,fPreShoLocMaxCut,digits) ;
-      
-//       if( nMax > 1 ) {     // if cluster is very flat (no pronounced maximum) then nMax = 0       
-//     UnfoldCluster(emcRecPoint, nMax, maxAt, maxAtEnergy) ;
-//     cpvRecPoints->Remove(emcRecPoint); 
-//     cpvRecPoints->Compress() ;
-//     index-- ;
-//     numberofPreShoNotUnfolded-- ;
-//     fNumberOfPreShoClusters-- ;
-//       }
-      
-//       delete[] maxAt ; 
-//       delete[] maxAtEnergy ; 
-//     } 
-//   }
-//   //Unfolding of PreSho clusters finished
-  
-}
-
-//____________________________________________________________________________
-Double_t  AliEMCALClusterizerv1::ShowerShape(Double_t r)
-{ 
-  // Shape of the shower (see EMCAL TDR)
-  // If you change this function, change also the gradient evaluation in ChiSquare()
-
-  Double_t r4    = r*r*r*r ;
-  Double_t r295  = TMath::Power(r, 2.95) ;
-  Double_t shape = TMath::Exp( -r4 * (1. / (2.32 + 0.26 * r4) + 0.0316 / (1 + 0.0652 * r295) ) ) ;
-  return shape ;
-}
-
-//____________________________________________________________________________
-void  AliEMCALClusterizerv1::UnfoldCluster(AliEMCALTowerRecPoint * iniTower, 
-                                                Int_t nMax, 
-                                                AliEMCALDigit ** maxAt, 
-                                                Float_t * maxAtEnergy)
-{
-  // Performs the unfolding of a cluster with nMax overlapping showers 
-  
-  Fatal("AliEMCALClusterizerv1::UnfoldCluster", "--> Unfolding not implemented") ;
-
- //  AliEMCALGetter * gime = AliEMCALGetter::GetInstance() ; 
-//   const AliEMCALGeometry * geom = gime->EMCALGeometry() ;
-//   const TClonesArray * digits = gime->Digits() ; 
-//   TObjArray * emcRecPoints = gime->TowerRecPoints() ; 
-//   TObjArray * cpvRecPoints = gime->PreShoRecPoints() ; 
-
-//   Int_t nPar = 3 * nMax ;
-//   Float_t * fitparameters = new Float_t[nPar] ;
-
-//   Bool_t rv = FindFit(iniTower, maxAt, maxAtEnergy, nPar, fitparameters) ;
-//   if( !rv ) {
-//     // Fit failed, return and remove cluster
-//     delete[] fitparameters ; 
-//     return ;
-//   }
-
-//   // create ufolded rec points and fill them with new energy lists
-//   // First calculate energy deposited in each sell in accordance with fit (without fluctuations): efit[]
-//   // and later correct this number in acordance with actual energy deposition
-
-//   Int_t nDigits = iniTower->GetMultiplicity() ;  
-//   Float_t * efit = new Float_t[nDigits] ;
-//   Float_t xDigit=0.,zDigit=0.,distance=0. ;
-//   Float_t xpar=0.,zpar=0.,epar=0.  ;
-//   Int_t relid[4] ;
-//   AliEMCALDigit * digit = 0 ;
-//   Int_t * emcDigits = iniTower->GetDigitsList() ;
-
-//   Int_t iparam ;
-//   Int_t iDigit ;
-//   for(iDigit = 0 ; iDigit < nDigits ; iDigit ++){
-//     digit = (AliEMCALDigit*) digits->At(emcDigits[iDigit] ) ;   
-//     geom->AbsToRelNumbering(digit->GetId(), relid) ;
-//     geom->RelPosInModule(relid, xDigit, zDigit) ;
-//     efit[iDigit] = 0;
-
-//     iparam = 0 ;    
-//     while(iparam < nPar ){
-//       xpar = fitparameters[iparam] ;
-//       zpar = fitparameters[iparam+1] ;
-//       epar = fitparameters[iparam+2] ;
-//       iparam += 3 ;
-//       distance = (xDigit - xpar) * (xDigit - xpar) + (zDigit - zpar) * (zDigit - zpar)  ;
-//       distance =  TMath::Sqrt(distance) ;
-//       efit[iDigit] += epar * ShowerShape(distance) ;
-//     }
-//   }
-  
-
-//   // Now create new RecPoints and fill energy lists with efit corrected to fluctuations
-//   // so that energy deposited in each cell is distributed betwin new clusters proportionally
-//   // to its contribution to efit
+      ratio = epar * ShowerShape(xDigit - xpar,zDigit - zpar) / efit[iDigit] ;
+      eDigit = energiesList[iDigit] * ratio ;
+      recPoint->AddDigit( *digit, eDigit, kFALSE ) ; //FIXME, need to study the shared case
+    }
+  }
 
 
-//   Float_t * emcEnergies = iniTower->GetEnergiesList() ;
-//   Float_t ratio ;
+  delete[] fitparameters ;
+  delete[] efit ;
 
 
-//   iparam = 0 ;
-//   while(iparam < nPar ){
-//     xpar = fitparameters[iparam] ;
-//     zpar = fitparameters[iparam+1] ;
-//     epar = fitparameters[iparam+2] ;
-//     iparam += 3 ;    
-    
-//     AliEMCALTowerRecPoint * emcRP = 0 ;  
-
-//     if(iniTower->IsTower()){ //create new entries in fTowerRecPoints...
-      
-//       if(fNumberOfTowerClusters >= emcRecPoints->GetSize())
-//     emcRecPoints->Expand(2*fNumberOfTowerClusters) ;
-      
-//       (*emcRecPoints)[fNumberOfTowerClusters] = new AliEMCALTowerRecPoint("") ;
-//       emcRP = (AliEMCALTowerRecPoint *) emcRecPoints->At(fNumberOfTowerClusters);
-//       fNumberOfTowerClusters++ ;
-//     }
-//     else{//create new entries in fPreShoRecPoints
-//       if(fNumberOfPreShoClusters >= cpvRecPoints->GetSize())
-//     cpvRecPoints->Expand(2*fNumberOfPreShoClusters) ;
-      
-//       (*cpvRecPoints)[fNumberOfPreShoClusters] = new AliEMCALPreShoRecPoint("") ;
-//       emcRP = (AliEMCALTowerRecPoint *) cpvRecPoints->At(fNumberOfPreShoClusters);
-//       fNumberOfPreShoClusters++ ;
-//     }
-    
-//     Float_t eDigit ;
-//     for(iDigit = 0 ; iDigit < nDigits ; iDigit ++){
-//       digit = (AliEMCALDigit*) digits->At( emcDigits[iDigit] ) ; 
-//       geom->AbsToRelNumbering(digit->GetId(), relid) ;
-//       geom->RelPosInModule(relid, xDigit, zDigit) ;
-//       distance = (xDigit - xpar) * (xDigit - xpar) + (zDigit - zpar) * (zDigit - zpar)  ;
-//       distance =  TMath::Sqrt(distance) ;
-//       ratio = epar * ShowerShape(distance) / efit[iDigit] ; 
-//       eDigit = emcEnergies[iDigit] * ratio ;
-//       emcRP->AddDigit( *digit, eDigit ) ;
-//     }       
-//   }
-//   delete[] fitparameters ; 
-//   delete[] efit ; 
-  
 }
 
 //_____________________________________________________________________________
 }
 
 //_____________________________________________________________________________
-void AliEMCALClusterizerv1::UnfoldingChiSquare(Int_t & nPar, Double_t * Grad, Double_t & fret, Double_t * x, Int_t iflag)
+void AliEMCALClusterizerv1::UnfoldingChiSquare(Int_t & nPar, Double_t * Grad,
+                                              Double_t & fret,
+                                              Double_t * x, Int_t iflag)
 {
   // Calculates the Chi square for the cluster unfolding minimization
   // Number of parameters, Gradient, Chi squared, parameters, what to do
 
 {
   // Calculates the Chi square for the cluster unfolding minimization
   // Number of parameters, Gradient, Chi squared, parameters, what to do
 
-  abort() ; 
- //  Fatal("AliEMCALClusterizerv1::UnfoldingChiSquare","-->Unfolding not implemented") ;
+  TList * toMinuit = dynamic_cast<TList*>( gMinuit->GetObjectFit() ) ;
 
 
-//   TList * toMinuit = (TList*) gMinuit->GetObjectFit() ;
+  AliEMCALRecPoint * recPoint = dynamic_cast<AliEMCALRecPoint*>( toMinuit->At(0) )  ;
+  TClonesArray * digits = dynamic_cast<TClonesArray*>( toMinuit->At(1) )  ;
+  // A bit buggy way to get an access to the geometry
+  // To be revised!
+  AliEMCALGeometry *geom = dynamic_cast<AliEMCALGeometry *>(toMinuit->At(2));
 
 
-//   AliEMCALTowerRecPoint * emcRP = (AliEMCALTowerRecPoint*) toMinuit->At(0)  ;
-//   TClonesArray * digits = (TClonesArray*)toMinuit->At(1)  ;
+  Int_t * digitsList     = recPoint->GetDigitsList() ;
 
 
+  Int_t nOdigits = recPoint->GetDigitsMultiplicity() ;
 
 
-  
-//   //  AliEMCALTowerRecPoint * emcRP = (AliEMCALTowerRecPoint *) gMinuit->GetObjectFit() ; // TowerRecPoint to fit
+  Float_t * energiesList = recPoint->GetEnergiesList() ;
 
 
-//   Int_t * emcDigits     = emcRP->GetDigitsList() ;
+  fret = 0. ;
+  Int_t iparam ;
 
 
-//   Int_t nOdigits = emcRP->GetDigitsMultiplicity() ; 
+  if(iflag == 2)
+    for(iparam = 0 ; iparam < nPar ; iparam++)
+      Grad[iparam] = 0 ; // Will evaluate gradient
 
 
-//   Float_t * emcEnergies = emcRP->GetEnergiesList() ;
+  Double_t efit ;
 
 
-//   const AliEMCALGeometry * geom = AliEMCALGetter::GetInstance()->EMCALGeometry() ; 
-//   fret = 0. ;     
-//   Int_t iparam ;
+  AliEMCALDigit * digit ;
+  Int_t iDigit ;
 
 
-//   if(iflag == 2)
-//     for(iparam = 0 ; iparam < nPar ; iparam++)    
-//       Grad[iparam] = 0 ; // Will evaluate gradient
-  
-//   Double_t efit ;    
-
-//   AliEMCALDigit * digit ;
-//   Int_t iDigit ;
-
-//   for( iDigit = 0 ; iDigit < nOdigits ; iDigit++) {
-
-//     digit = (AliEMCALDigit*) digits->At( emcDigits[iDigit] ) ; 
-
-//     Int_t relid[4] ;
-//     Float_t xDigit ;
-//     Float_t zDigit ;
-
-//     geom->AbsToRelNumbering(digit->GetId(), relid) ;
-
-//     geom->RelPosInModule(relid, xDigit, zDigit) ;
-
-//      if(iflag == 2){  // calculate gradient
-//        Int_t iParam = 0 ;
-//        efit = 0 ;
-//        while(iParam < nPar ){
-//      Double_t distance = (xDigit - x[iParam]) * (xDigit - x[iParam]) ;
-//      iParam++ ; 
-//      distance += (zDigit - x[iParam]) * (zDigit - x[iParam]) ; 
-//      distance = TMath::Sqrt( distance ) ; 
-//      iParam++ ;      
-//      efit += x[iParam] * ShowerShape(distance) ;
-//      iParam++ ;
-//        }
-//        Double_t sum = 2. * (efit - emcEnergies[iDigit]) / emcEnergies[iDigit] ; // Here we assume, that sigma = sqrt(E) 
-//        iParam = 0 ;
-//        while(iParam < nPar ){
-//      Double_t xpar = x[iParam] ;
-//      Double_t zpar = x[iParam+1] ;
-//      Double_t epar = x[iParam+2] ;
-//      Double_t dr = TMath::Sqrt( (xDigit - xpar) * (xDigit - xpar) + (zDigit - zpar) * (zDigit - zpar) );
-//      Double_t shape = sum * ShowerShape(dr) ;
-//      Double_t r4 = dr*dr*dr*dr ;
-//      Double_t r295 = TMath::Power(dr,2.95) ;
-//      Double_t deriv =-4. * dr*dr * ( 2.32 / ( (2.32 + 0.26 * r4) * (2.32 + 0.26 * r4) ) +
-//                                      0.0316 * (1. + 0.0171 * r295) / ( ( 1. + 0.0652 * r295) * (1. + 0.0652 * r295) ) ) ;
-        
-//      Grad[iParam] += epar * shape * deriv * (xpar - xDigit) ;  // Derivative over x    
-//      iParam++ ; 
-//      Grad[iParam] += epar * shape * deriv * (zpar - zDigit) ;  // Derivative over z         
-//      iParam++ ; 
-//      Grad[iParam] += shape ;                                  // Derivative over energy             
-//      iParam++ ; 
-//        }
-//      }
-//      efit = 0;
-//      iparam = 0 ;
-
-//      while(iparam < nPar ){
-//        Double_t xpar = x[iparam] ;
-//        Double_t zpar = x[iparam+1] ;
-//        Double_t epar = x[iparam+2] ;
-//        iparam += 3 ;
-//        Double_t distance = (xDigit - xpar) * (xDigit - xpar) + (zDigit - zpar) * (zDigit - zpar)  ;
-//        distance =  TMath::Sqrt(distance) ;
-//        efit += epar * ShowerShape(distance) ;
-//      }
-
-//      fret += (efit-emcEnergies[iDigit])*(efit-emcEnergies[iDigit])/emcEnergies[iDigit] ; 
-//      // Here we assume, that sigma = sqrt(E)
-//   }
+  for( iDigit = 0 ; iDigit < nOdigits ; iDigit++) {
+
+    digit = dynamic_cast<AliEMCALDigit*>( digits->At( digitsList[iDigit] ) );
+
+    Double_t xDigit=0 ;
+    Double_t zDigit=0 ;
+    Double_t yDigit=0 ;//not used yet, assumed to be 0
+
+    geom->RelPosCellInSModule(digit->GetId(), yDigit, xDigit, zDigit);
+
+    if(iflag == 2){  // calculate gradient
+      Int_t iParam = 0 ;
+      efit = 0 ;
+      while(iParam < nPar ){
+        Double_t dx = (xDigit - x[iParam]) ;
+        iParam++ ;
+        Double_t dz = (zDigit - x[iParam]) ;
+        iParam++ ;
+        efit += x[iParam] * ShowerShape(dx,dz) ;
+        iParam++ ;
+      }
+      Double_t sum = 2. * (efit - energiesList[iDigit]) / energiesList[iDigit] ; // Here we assume, that sigma = sqrt(E)
+      iParam = 0 ;
+      while(iParam < nPar ){
+        Double_t xpar = x[iParam] ;
+        Double_t zpar = x[iParam+1] ;
+        Double_t epar = x[iParam+2] ;
+        Double_t dr = TMath::Sqrt( (xDigit - xpar) * (xDigit - xpar) + (zDigit - zpar) * (zDigit - zpar) );
+        Double_t shape = sum * ShowerShape(xDigit - xpar,zDigit - zpar) ;
+        Double_t r133 =  TMath::Power(dr, 1.33);
+        Double_t r669 = TMath::Power(dr,6.69);
+        Double_t deriv =-1.33 * TMath::Power(dr,0.33)*dr * ( 1.57 / ( (1.57 + 0.0860 * r133) * (1.57 + 0.0860 * r133) )
+                                                             - 0.55 / (1 + 0.000563 * r669) / ( (1 + 0.000563 * r669) * (1 + 0.000563 * r669) ) ) ;
+
+        Grad[iParam] += epar * shape * deriv * (xpar - xDigit) ;  // Derivative over x
+        iParam++ ;
+        Grad[iParam] += epar * shape * deriv * (zpar - zDigit) ;  // Derivative over z
+        iParam++ ;
+        Grad[iParam] += shape ;                                  // Derivative over energy
+       iParam++ ;
+      }
+    }
+    efit = 0;
+    iparam = 0 ;
 
 
-}
 
 
+    while(iparam < nPar ){
+      Double_t xpar = x[iparam] ;
+      Double_t zpar = x[iparam+1] ;
+      Double_t epar = x[iparam+2] ;
+      iparam += 3 ;
+      efit += epar * ShowerShape(xDigit - xpar,zDigit - zpar) ;
+    }
+
+    fret += (efit-energiesList[iDigit])*(efit-energiesList[iDigit])/energiesList[iDigit] ;
+    // Here we assume, that sigma = sqrt(E) 
+  }
+}
 //____________________________________________________________________________
 //____________________________________________________________________________
-void AliEMCALClusterizerv1::Print(Option_t * option)const
+void AliEMCALClusterizerv1::Print(Option_t * /*option*/)const
 {
   // Print clusterizer parameters
 
 {
   // Print clusterizer parameters
 
+  TString message("\n") ; 
+  
   if( strcmp(GetName(), "") !=0 ){
     
     // Print parameters
  
   if( strcmp(GetName(), "") !=0 ){
     
     // Print parameters
  
-    TString taskName(GetName()) ; 
-    taskName.ReplaceAll(Version(), "") ;
-
-    cout << "---------------"<< taskName.Data() << " " << GetTitle()<< "-----------" << endl 
-        << "Clusterizing digits from the file: " << fHeaderFileName.Data() << endl 
-        << "                           Branch: " << fDigitsBranchTitle.Data() << endl 
-        << endl 
-        << "                       EMC Clustering threshold = " << fTowerClusteringThreshold << endl
-        << "                       EMC Local Maximum cut    = " << fTowerLocMaxCut << endl
-        << "                       EMC Logarothmic weight   = " << fW0 << endl
-        << endl
-        << "                       CPV Clustering threshold = " << fPreShoClusteringThreshold << endl
-        << "                       CPV Local Maximum cut    = " << fPreShoLocMaxCut << endl
-       << "                       CPV Logarothmic weight   = " << fW0CPV << endl
-        << endl ;
+    TString taskName(Version()) ;
+    
+    printf("--------------- "); 
+    printf("%s",taskName.Data()) ; 
+    printf(" "); 
+    printf("Clusterizing digits: "); 
+    printf("\n                       ECA Local Maximum cut    = %f", fECALocMaxCut); 
+    printf("\n                       ECA Logarithmic weight   = %f", fECAW0); 
     if(fToUnfold)
     if(fToUnfold)
-      cout << " Unfolding on " << endl ;
+      printf("\nUnfolding on\n");
     else
     else
-      cout << " Unfolding off " << endl ;
+      printf("\nUnfolding off\n");
     
     
-    cout << "------------------------------------------------------------------" <<endl ;
+    printf("------------------------------------------------------------------"); 
   }
   else
   }
   else
-    cout << " AliEMCALClusterizerv1 not initialized " << endl ;
+    printf("AliEMCALClusterizerv1 not initialized ") ;
 }
 }
+
 //____________________________________________________________________________
 void AliEMCALClusterizerv1::PrintRecPoints(Option_t * option)
 {
   // Prints list of RecPoints produced at the current pass of AliEMCALClusterizer
 //____________________________________________________________________________
 void AliEMCALClusterizerv1::PrintRecPoints(Option_t * option)
 {
   // Prints list of RecPoints produced at the current pass of AliEMCALClusterizer
-
-  TObjArray * towerRecPoints = AliEMCALGetter::GetInstance()->TowerRecPoints() ; 
-  TObjArray * preshoRecPoints = AliEMCALGetter::GetInstance()->PreShowerRecPoints() ; 
-
-  cout << "AliEMCALClusterizerv1: : event "<<gAlice->GetEvNumber() << endl ;
-  cout << "       Found "<< towerRecPoints->GetEntriesFast() << " TOWER Rec Points and " 
-          << preshoRecPoints->GetEntriesFast() << " PRE SHOWER RecPoints" << endl ;
-
-  fRecPointsInRun +=  towerRecPoints->GetEntriesFast() ; 
-  fRecPointsInRun +=  preshoRecPoints->GetEntriesFast() ; 
+  if(strstr(option,"deb")) {
+    printf("PrintRecPoints: Clusterization result:") ; 
+  
+    printf("           Found %d ECA Rec Points\n ", 
+        fRecPoints->GetEntriesFast()) ; 
+  }
 
   if(strstr(option,"all")) {
 
   if(strstr(option,"all")) {
-
-    cout << "Tower clusters " << endl ;
-    cout << " Index  Ene(MeV)   Multi  Module     phi     r  theta    Lambda 1   Lambda 2  # of prim  Primaries list "      <<  endl;      
-    
-    Int_t index ;
-    for (index = 0 ; index < towerRecPoints->GetEntries() ; index++) {
-      AliEMCALTowerRecPoint * rp = dynamic_cast<AliEMCALTowerRecPoint * >(towerRecPoints->At(index)) ; 
-      TVector3  globalpos;  
-      rp->GetGlobalPosition(globalpos);
-      Float_t lambda[2]; 
-      rp->GetElipsAxis(lambda);
-      Int_t * primaries; 
-      Int_t nprimaries;
-      primaries = rp->GetPrimaries(nprimaries);
-
-      cout << setw(4) << rp->GetIndexInList() << "   " 
-          << setw(7) << setprecision(3) << rp->GetEnergy() << "      "
-          << setw(3) << rp->GetMultiplicity() << "      " 
-          << setw(1) << rp->GetEMCALArm() << "     " 
-          << setw(5) << setprecision(4) << globalpos.X() << "  " 
-          << setw(5) << setprecision(4) << globalpos.Y() << "  " 
-          << setw(5) << setprecision(4) << globalpos.Z() << "     "
-          << setw(4) << setprecision(2) << lambda[0]  << "  "
-          << setw(4) << setprecision(2) << lambda[1]  << "  "
-          << setw(2) << nprimaries << "  " ;
-     
-      for (Int_t iprimary=0; iprimary<nprimaries; iprimary++)
-       cout << setw(4) <<   primaries[iprimary] << "  "  ;
-      cout << endl ;    
+    if(strstr(option,"deb")) {
+      printf("\n-----------------------------------------------------------------------\n") ;
+      printf("Clusters in ECAL section\n") ;
+      printf("Index    Ene(GeV) Multi Module     GX    GY   GZ  lX    lY   lZ   Dispersion Lambda 1   Lambda 2  # of prim  Primaries list\n") ;
     }
     }
+   Int_t index =0;
 
 
-    //Now plot Pre shower recPoints
-
-    cout << "-----------------------------------------------------------------------"<<endl ;
-
-    cout << "PreShower clusters " << endl ;
-    cout << " Index  Ene(MeV)   Multi  Module     phi     r  theta    Lambda 1   Lambda 2  # of prim  Primaries list "      <<  endl;      
-    
-    for (index = 0 ; index < preshoRecPoints->GetEntries() ; index++) {
-      AliEMCALTowerRecPoint * rp = dynamic_cast<AliEMCALTowerRecPoint *>(preshoRecPoints->At(index)) ; 
+    for (index = 0 ; index < fRecPoints->GetEntries() ; index++) {
+      AliEMCALRecPoint * rp = dynamic_cast<AliEMCALRecPoint * >(fRecPoints->At(index)) ; 
       TVector3  globalpos;  
       TVector3  globalpos;  
-      rp->GetGlobalPosition(globalpos);
+      //rp->GetGlobalPosition(globalpos);
+      TVector3  localpos;  
+      rp->GetLocalPosition(localpos);
       Float_t lambda[2]; 
       rp->GetElipsAxis(lambda);
       Int_t * primaries; 
       Int_t nprimaries;
       primaries = rp->GetPrimaries(nprimaries);
       Float_t lambda[2]; 
       rp->GetElipsAxis(lambda);
       Int_t * primaries; 
       Int_t nprimaries;
       primaries = rp->GetPrimaries(nprimaries);
-
-      cout << setw(4) << rp->GetIndexInList() << "   " 
-          << setw(7) << setprecision(3) << rp->GetEnergy() << "      "
-          << setw(3) << rp->GetMultiplicity() << "      " 
-          << setw(1) << rp->GetEMCALArm() << "     " 
-          << setw(5) << setprecision(4) << globalpos.X() << "  " 
-          << setw(5) << setprecision(4) << globalpos.Y() << "  " 
-          << setw(5) << setprecision(4) << globalpos.Z() << "     "
-          << setw(4) << setprecision(2) << lambda[0]  << "  "
-          << setw(4) << setprecision(2) << lambda[1]  << "  "
-          << setw(2) << nprimaries << "  " ;
-     
-      for (Int_t iprimary=0; iprimary<nprimaries; iprimary++)
-       cout << setw(4) <<   primaries[iprimary] << "  "  ;
-      cout << endl ;    
+      if(strstr(option,"deb")) 
+      printf("\n%6d  %8.4f  %3d     %4.1f    %4.1f %4.1f  %4.1f %4.1f %4.1f    %4.1f   %4f  %4f    %2d     : ", 
+            rp->GetIndexInList(), rp->GetEnergy(), rp->GetMultiplicity(),
+            globalpos.X(), globalpos.Y(), globalpos.Z(), localpos.X(), localpos.Y(), localpos.Z(), 
+            rp->GetDispersion(), lambda[0], lambda[1], nprimaries) ; 
+      if(strstr(option,"deb")){ 
+        for (Int_t iprimary=0; iprimary<nprimaries; iprimary++) {
+         printf("%d ", primaries[iprimary] ) ; 
+        }
+      }
     }
 
     }
 
-    cout << "-----------------------------------------------------------------------"<<endl ;
+    if(strstr(option,"deb"))
+    printf("\n-----------------------------------------------------------------------\n");
   }
 }
 
   }
 }
 
+//___________________________________________________________________
+void  AliEMCALClusterizerv1::PrintRecoInfo()
+{
+  printf(" AliEMCALClusterizerv1::PrintRecoInfo() : version %s \n", Version() );
+
+}