]> git.uio.no Git - u/mrichter/AliRoot.git/blob - MUON/AliMUONClusterFinderAZ.cxx
From Artur:
[u/mrichter/AliRoot.git] / MUON / AliMUONClusterFinderAZ.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16 /* $Id$ */
17
18 // Clusterizer class developped by A. Zinchenko (Dubna)
19
20 #include <stdlib.h>
21 #include <Riostream.h>
22 #include <TROOT.h>
23 #include <TCanvas.h>
24 #include <TLine.h>
25 #include <TTree.h>
26 #include <TH2.h>
27 #include <TView.h>
28 #include <TStyle.h>
29 #include <TMinuit.h>
30 #include <TMatrixD.h>
31
32 #include "AliMUONClusterFinderAZ.h"
33 #include "AliHeader.h"
34 #include "AliRun.h"
35 #include "AliMUON.h"
36 #include "AliMUONChamber.h"
37 #include "AliMUONDigit.h"
38 #include "AliMUONHit.h"
39 #include "AliMUONChamber.h"
40 #include "AliMUONRawCluster.h"
41 #include "AliMUONClusterInput.h"
42 #include "AliMUONPixel.h"
43 #include "AliMC.h"
44 #include "AliMUONLoader.h"
45 #include "AliLog.h"
46
47 ClassImp(AliMUONClusterFinderAZ)
48  
49  const Double_t AliMUONClusterFinderAZ::fgkCouplMin = 1.e-3; // threshold on coupling 
50  AliMUONClusterFinderAZ* AliMUONClusterFinderAZ::fgClusterFinder = 0x0;
51  TMinuit* AliMUONClusterFinderAZ::fgMinuit = 0x0;
52 //FILE *lun1 = fopen("nxny.dat","w");
53
54 //_____________________________________________________________________________
55 AliMUONClusterFinderAZ::AliMUONClusterFinderAZ(Bool_t draw, Int_t iReco)
56   : AliMUONClusterFinderVS()
57 {
58 // Constructor
59   for (Int_t i=0; i<4; i++) {fHist[i] = 0;}
60   //fMuonDigits = 0;
61   fSegmentation[1] = fSegmentation[0] = 0; 
62   //AZ fgClusterFinder = 0x0;
63   //AZ fgMinuit = 0x0; 
64   if (!fgClusterFinder) fgClusterFinder = this;
65   if (!fgMinuit) fgMinuit = new TMinuit(8);
66   fDraw = draw;
67   fReco = iReco;
68   fPixArray = new TObjArray(20); 
69   fDebug = 0; //0;
70   if (draw) fDebug = 1;
71 }
72
73 //_____________________________________________________________________________
74 AliMUONClusterFinderAZ::AliMUONClusterFinderAZ(const AliMUONClusterFinderAZ& rhs)
75   : AliMUONClusterFinderVS(rhs)
76 {
77 // Protected copy constructor
78
79   AliFatal("Not implemented.");
80 }
81
82 //_____________________________________________________________________________
83 AliMUONClusterFinderAZ::~AliMUONClusterFinderAZ()
84 {
85   // Destructor
86   delete fgMinuit; fgMinuit = 0; delete fPixArray; fPixArray = 0;
87 }
88
89 //_____________________________________________________________________________
90 void AliMUONClusterFinderAZ::FindRawClusters()
91 {
92 // To provide the same interface as in AliMUONClusterFinderVS
93
94   ResetRawClusters(); //AZ
95   EventLoop (gAlice->GetHeader()->GetEvent(), AliMUONClusterInput::Instance()->Chamber());
96 }
97
98 //_____________________________________________________________________________
99 void AliMUONClusterFinderAZ::EventLoop(Int_t nev=0, Int_t ch=0)
100 {
101 // Loop over digits
102   
103   static Int_t nev0 = -1, ch0 = -1;
104   if (fDraw) {
105     // Find requested event and chamber 
106     if (nev < nev0) return;
107     else if (nev == nev0 && ch < ch0) return;
108   }
109   nev0 = nev;
110   ch0 = ch;
111
112   AliMUON *pMuon = (AliMUON*) gAlice->GetModule("MUON");
113   AliMUONChamber *iChamber = &(pMuon->Chamber(ch));
114   //fSegmentation[0] = iChamber->SegmentationModel(1);
115   //fSegmentation[1] = iChamber->SegmentationModel(2);
116   fResponse = iChamber->ResponseModel();
117   fSegmentation[0] = AliMUONClusterInput::Instance()->Segmentation2(0);
118   fSegmentation[1] = AliMUONClusterInput::Instance()->Segmentation2(1);
119   //AZ fResponse = AliMUONClusterInput::Instance()->Response();
120     
121   Int_t ndigits[2]={9,9}, nShown[2]={0};
122   for (Int_t i=0; i<2; i++) {
123     for (Int_t j=0; j<fgkDim; j++) {fUsed[i][j]=kFALSE;}
124   }
125
126 next:
127   if (ndigits[0] == nShown[0] && ndigits[1] == nShown[1]) {
128     // No more clusters
129     if (fReco) return;
130     //AZ ch0++;
131     return; // next chamber
132   }
133   Float_t xpad, ypad, zpad, zpad0;
134   Bool_t first = kTRUE;
135   if (fDebug) cout << " *** Event # " << nev << " chamber: " << ch << endl;
136   fnPads[0] = fnPads[1] = 0;
137   for (Int_t i=0; i<fgkDim; i++) {fPadIJ[1][i] = 0;}
138
139   for (Int_t iii = 0; iii<2; iii++) { 
140     Int_t cath = TMath::Odd(iii);
141     ndigits[cath] = AliMUONClusterInput::Instance()->NDigits(cath); //AZ
142     if (!ndigits[0] && !ndigits[1]) return;
143     if (ndigits[cath] == 0) continue;
144     if (fDebug) cout << " ndigits: " << ndigits[cath] << " " << cath << endl;
145
146     AliMUONDigit  *mdig;
147     Int_t digit;
148
149     Bool_t eEOC = kTRUE; // end-of-cluster
150     for (digit = 0; digit < ndigits[cath]; digit++) {
151       mdig = AliMUONClusterInput::Instance()->Digit(cath,digit); 
152       if (first) {
153         // Find first unused pad
154         if (fUsed[cath][digit]) continue;
155         fSegmentation[cath]->GetPadC(fInput->DetElemId(),mdig->PadX(),mdig->PadY(),xpad,ypad,zpad0);
156       } else {
157         if (fUsed[cath][digit]) continue;
158         fSegmentation[cath]->GetPadC(fInput->DetElemId(),mdig->PadX(),mdig->PadY(),xpad,ypad,zpad);
159         if (TMath::Abs(zpad-zpad0) > 0.1) continue; // different slats
160         // Find a pad overlapping with the cluster
161         if (!Overlap(cath,mdig)) continue;
162       }
163       // Add pad - recursive call
164       AddPad(cath,digit);
165       //AZ !!!!!! Temporary fix of St1 overlap regions !!!!!!!! 
166       if (cath && ch < 2) {
167         Int_t npads = fnPads[0] + fnPads[1] - 1;
168         Int_t cath1 = fPadIJ[0][npads];
169         Int_t idig = TMath::Nint (fXyq[5][npads]);
170         mdig = AliMUONClusterInput::Instance()->Digit(cath1,idig);
171         fSegmentation[cath1]->GetPadC(fInput->DetElemId(),mdig->PadX(),mdig->PadY(),xpad,ypad,zpad);
172         if (TMath::Abs(zpad-zpad0) > 0.1) zpad0 = zpad;
173       } 
174       eEOC = kFALSE;
175       if (digit >= 0) break;
176     }
177     if (first && eEOC) {
178       // No more unused pads 
179       if (cath == 0) continue; // on cathode #0 - check #1
180       else return; // No more clusters
181     }
182     if (eEOC) break; // cluster found
183     first = kFALSE;
184     if (fDebug) cout << " nPads: " << fnPads[cath] << " " << nShown[cath]+fnPads[cath] << " " << cath << endl;
185   } // for (Int_t iii = 0;
186
187   fZpad = zpad0;
188   if (fDraw) DrawCluster(nev0, ch0); 
189
190   // Use MLEM for cluster finder
191   Int_t nMax = 1, localMax[100], maxPos[100];
192   Double_t maxVal[100];
193   
194   if (CheckPrecluster(nShown)) {
195     BuildPixArray();
196     if (fnPads[0]+fnPads[1] > 50) nMax = FindLocalMaxima(localMax, maxVal);
197     if (nMax > 1) TMath::Sort(nMax, maxVal, maxPos, kTRUE); // in decreasing order
198     Int_t iSimple = 0, nInX = -1, nInY;
199     PadsInXandY(nInX, nInY);
200     if (fDebug) cout << "Pads in X and Y: " << nInX << " " << nInY << endl;
201     if (nMax == 1 && nInX < 4 && nInY < 4) iSimple = 0; //1; // simple cluster
202     for (Int_t i=0; i<nMax; i++) {
203       if (nMax > 1) FindCluster(localMax, maxPos[i]);
204       if (!MainLoop(iSimple)) cout << " MainLoop failed " << endl;
205       if (i < nMax-1) {
206         for (Int_t j=0; j<fnPads[0]+fnPads[1]; j++) {
207           if (fPadIJ[1][j] == 0) continue; // pad charge was not modified
208           fPadIJ[1][j] = 0;
209           fXyq[2][j] = fXyq[6][j]; // use backup charge value
210         }
211       }
212     }
213   }
214   if (fReco || Next(nev0, ch0)) goto next;
215 }
216
217 //_____________________________________________________________________________
218 void AliMUONClusterFinderAZ::DrawCluster(Int_t nev0, Int_t ch0)
219 {
220   // Draw preclusters
221   TCanvas *c1 = 0;
222   TView *view = 0;
223   TH2F *hist = 0;
224   Double_t p1[3]={0}, p2[3];
225   if (!gPad) {
226     c1 = new TCanvas("c1","Clusters",0,0,600,700);
227     //c1->SetFillColor(10);
228     c1->Divide(1,2);
229     new TCanvas("c2","Mlem",700,0,600,350);
230   } else {
231     c1 = (TCanvas*) gROOT->GetListOfCanvases()->FindObject("c1");
232   }    
233
234   Int_t ntracks = 0;
235
236   // Get pointer to Alice detectors
237   AliMUON *muon  = (AliMUON*) gAlice->GetModule("MUON");
238   if (!muon) return;
239
240   //Loaders
241   AliRunLoader *rl = AliRunLoader::GetRunLoader();
242   AliLoader *gime = rl->GetLoader("MUONLoader");
243   AliMUONData *data = ((AliMUONLoader*)gime)->GetMUONData();
244
245   gime->LoadHits("READ"); 
246   TTree *treeH = gime->TreeH();
247   ntracks = (Int_t) treeH->GetEntries();
248   cout << " nev         " << nev0 << " ntracks " << ntracks << endl;
249   gime->LoadRecPoints("READ"); 
250   TTree *treeR = data->TreeR();
251   if (treeR) {
252     data->SetTreeAddress("RC");
253     data->GetRawClusters();
254   }
255     
256   TLine *line[99]={0};
257   Int_t nLine = 0;
258   char hName[4];
259   for (Int_t cath = 0; cath<2; cath++) {
260     // Build histograms
261     if (fHist[cath*2]) {fHist[cath*2]->Delete(); fHist[cath*2] = 0;}
262     if (fHist[cath*2+1]) {fHist[cath*2+1]->Delete(); fHist[cath*2+1] = 0;}
263     if (fnPads[cath] == 0) continue; // cluster on one cathode only
264     Float_t wxMin=999, wxMax=0, wyMin=999, wyMax=0; 
265     Int_t minDx=0, maxDx=0, minDy=0, maxDy=0;
266     for (Int_t i=0; i<fnPads[0]+fnPads[1]; i++) {
267       if (fPadIJ[0][i] != cath) continue;
268       if (fXyq[3][i] < wxMin) {wxMin = fXyq[3][i]; minDx = i;}
269       if (fXyq[3][i] > wxMax) {wxMax = fXyq[3][i]; maxDx = i;}
270       if (fXyq[4][i] < wyMin) {wyMin = fXyq[4][i]; minDy = i;}
271       if (fXyq[4][i] > wyMax) {wyMax = fXyq[4][i]; maxDy = i;}
272     }
273     cout << minDx << maxDx << minDy << maxDy << endl;
274     Int_t nx, ny, padSize;
275     Float_t xmin=9999, xmax=-9999, ymin=9999, ymax=-9999;
276     if (TMath::Nint(fXyq[3][minDx]*1000) == TMath::Nint(fXyq[3][maxDx]*1000) &&
277         TMath::Nint(fXyq[4][minDy]*1000) == TMath::Nint(fXyq[4][maxDy]*1000)) {
278       // the same segmentation
279       cout << " Same" << endl;
280       cout << fXyq[3][minDx] << " " << fXyq[3][maxDx] << " " << fXyq[4][minDy] << " " << fXyq[4][maxDy] << endl;
281       for (Int_t i=0; i<fnPads[0]+fnPads[1]; i++) {
282         if (fPadIJ[0][i] != cath) continue;
283         if (fXyq[0][i] < xmin) xmin = fXyq[0][i];
284         if (fXyq[0][i] > xmax) xmax = fXyq[0][i];
285         if (fXyq[1][i] < ymin) ymin = fXyq[1][i];
286         if (fXyq[1][i] > ymax) ymax = fXyq[1][i];
287       }
288       xmin -= fXyq[3][minDx]; xmax += fXyq[3][minDx];
289       ymin -= fXyq[4][minDy]; ymax += fXyq[4][minDy];
290       nx = TMath::Nint ((xmax-xmin)/wxMin/2);
291       ny = TMath::Nint ((ymax-ymin)/wyMin/2);
292       cout << xmin << " " << xmax << " " << nx << " " << ymin << " " << ymax << " " << ny << endl;
293       sprintf(hName,"h%d",cath*2);
294       fHist[cath*2] = new TH2F(hName,"cluster",nx,xmin,xmax,ny,ymin,ymax);
295       //cout << fHist[cath*2] << " " << fnPads[cath] << endl;
296       for (Int_t i=0; i<fnPads[0]+fnPads[1]; i++) {
297         if (fPadIJ[0][i] != cath) continue;
298         fHist[cath*2]->Fill(fXyq[0][i],fXyq[1][i],fXyq[2][i]);
299         //cout << fXyq[0][i] << fXyq[1][i] << fXyq[2][i] << endl;
300       }
301     } else {
302       // different segmentation in the cluster
303       cout << " Different" << endl;
304       cout << fXyq[3][minDx] << " " << fXyq[3][maxDx] << " " << fXyq[4][minDy] << " " << fXyq[4][maxDy] << endl;
305       Int_t nOK = 0;
306       Int_t indx, locMin, locMax;
307       if (TMath::Nint(fXyq[3][minDx]*1000) != TMath::Nint(fXyq[3][maxDx]*1000)) {
308         // different segmentation along x
309         indx = 0;
310         locMin = minDx;
311         locMax = maxDx;
312       } else {
313         // different segmentation along y
314         indx = 1;
315         locMin = minDy;
316         locMax = maxDy;
317       }
318       Int_t loc = locMin;
319       for (Int_t i=0; i<2; i++) {
320         // loop over different pad sizes
321         if (i>0) loc = locMax;
322         padSize = TMath::Nint(fXyq[indx+3][loc]*1000);
323         xmin = 9999; xmax = -9999; ymin = 9999; ymax = -9999;
324         for (Int_t j=0; j<fnPads[0]+fnPads[1]; j++) {
325           if (fPadIJ[0][j] != cath) continue;
326           if (TMath::Nint(fXyq[indx+3][j]*1000) != padSize) continue;
327           nOK++;
328           xmin = TMath::Min (xmin,fXyq[0][j]);
329           xmax = TMath::Max (xmax,fXyq[0][j]);
330           ymin = TMath::Min (ymin,fXyq[1][j]);
331           ymax = TMath::Max (ymax,fXyq[1][j]);
332         }
333         xmin -= fXyq[3][loc]; xmax += fXyq[3][loc];
334         ymin -= fXyq[4][loc]; ymax += fXyq[4][loc];
335         nx = TMath::Nint ((xmax-xmin)/fXyq[3][loc]/2);
336         ny = TMath::Nint ((ymax-ymin)/fXyq[4][loc]/2);
337         sprintf(hName,"h%d",cath*2+i);
338         fHist[cath*2+i] = new TH2F(hName,"cluster",nx,xmin,xmax,ny,ymin,ymax);
339         for (Int_t j=0; j<fnPads[0]+fnPads[1]; j++) {
340           if (fPadIJ[0][j] != cath) continue;
341           if (TMath::Nint(fXyq[indx+3][j]*1000) != padSize) continue;
342           fHist[cath*2+i]->Fill(fXyq[0][j],fXyq[1][j],fXyq[2][j]);
343         }
344       } // for (Int_t i=0;
345       if (nOK != fnPads[cath]) cout << " *** Too many segmentations: nPads, nOK " << fnPads[cath] << " " << nOK << endl;
346     } // if (TMath::Nint(fXyq[3][minDx]*1000)
347   } // for (Int_t cath = 0;
348         
349   // Draw histograms and coordinates
350   for (Int_t cath=0; cath<2; cath++) {
351     if (cath == 0) ModifyHistos();
352     if (fnPads[cath] == 0) continue; // cluster on one cathode only
353     if (fDraw) {
354       c1->cd(cath+1);
355       gPad->SetTheta(55);
356       gPad->SetPhi(30);
357       Double_t x, y, x0, y0, r1=999, r2=0;
358       if (fHist[cath*2+1]) {
359         // 
360         x0 = fHist[cath*2]->GetXaxis()->GetXmin() - 1000*TMath::Cos(30*TMath::Pi()/180);
361         y0 = fHist[cath*2]->GetYaxis()->GetXmin() - 1000*TMath::Sin(30*TMath::Pi()/180);
362         r1 = 0;
363         Int_t ihist=cath*2;
364         for (Int_t iy=1; iy<=fHist[ihist]->GetNbinsY(); iy++) {
365           y = fHist[ihist]->GetYaxis()->GetBinCenter(iy) 
366             + fHist[ihist]->GetYaxis()->GetBinWidth(iy);
367           for (Int_t ix=1; ix<=fHist[ihist]->GetNbinsX(); ix++) {
368             if (fHist[ihist]->GetCellContent(ix,iy) > 0.1) {
369               x = fHist[ihist]->GetXaxis()->GetBinCenter(ix)
370                 + fHist[ihist]->GetXaxis()->GetBinWidth(ix);
371               r1 = TMath::Max (r1,TMath::Sqrt((x-x0)*(x-x0)+(y-y0)*(y-y0)));
372             }
373           }
374         }
375         ihist = cath*2 + 1 ;
376         for (Int_t iy=1; iy<=fHist[ihist]->GetNbinsY(); iy++) {
377           y = fHist[ihist]->GetYaxis()->GetBinCenter(iy)
378             + fHist[ihist]->GetYaxis()->GetBinWidth(iy);
379           for (Int_t ix=1; ix<=fHist[ihist]->GetNbinsX(); ix++) {
380             if (fHist[ihist]->GetCellContent(ix,iy) > 0.1) {
381               x = fHist[ihist]->GetXaxis()->GetBinCenter(ix)
382                 + fHist[ihist]->GetXaxis()->GetBinWidth(ix);
383               r2 = TMath::Max (r2,TMath::Sqrt((x-x0)*(x-x0)+(y-y0)*(y-y0)));
384             }
385           }
386         }
387         cout << r1 << " " << r2 << endl;
388       } // if (fHist[cath*2+1])
389       if (r1 > r2) {
390         //fHist[cath*2]->Draw("lego1");
391         fHist[cath*2]->Draw("lego1Fb");
392         //if (fHist[cath*2+1]) fHist[cath*2+1]->Draw("lego1SameAxisBb");
393         if (fHist[cath*2+1]) fHist[cath*2+1]->Draw("lego1SameAxisBbFb");
394       } else {
395         //fHist[cath*2+1]->Draw("lego1");
396         fHist[cath*2+1]->Draw("lego1Fb");
397         //fHist[cath*2]->Draw("lego1SameAxisBb");
398         fHist[cath*2]->Draw("lego1SameAxisFbBb");
399       }
400       c1->Update();
401     } // if (fDraw)
402   } // for (Int_t cath = 0;
403
404   // Draw generated hits
405   Double_t xNDC[6];
406   hist = fHist[0] ? fHist[0] : fHist[2];
407   p2[2] = hist->GetMaximum();
408   view = 0;
409   if (c1) view = c1->Pad()->GetView();
410   cout << " *** GEANT hits *** " << endl;
411   fnMu = 0;
412   Int_t ix, iy, iok;
413   for (Int_t i=0; i<ntracks; i++) {
414     treeH->GetEvent(i);
415     for (AliMUONHit* mHit=(AliMUONHit*)muon->FirstHit(-1); 
416          mHit;
417          mHit=(AliMUONHit*)muon->NextHit()) {
418       if (mHit->Chamber() != ch0+1) continue;  // chamber number
419       if (TMath::Abs(mHit->Z()-fZpad) > 1) continue; // different slat
420       p2[0] = p1[0] = mHit->X();        // x-pos of hit
421       p2[1] = p1[1] = mHit->Y();        // y-pos
422       if (p1[0] < hist->GetXaxis()->GetXmin() || 
423           p1[0] > hist->GetXaxis()->GetXmax()) continue;
424       if (p1[1] < hist->GetYaxis()->GetXmin() || 
425           p1[1] > hist->GetYaxis()->GetXmax()) continue;
426       // Check if track comes thru pads with signal
427       iok = 0;
428       for (Int_t ihist=0; ihist<4; ihist++) {
429         if (!fHist[ihist]) continue;
430         ix = fHist[ihist]->GetXaxis()->FindBin(p1[0]);
431         iy = fHist[ihist]->GetYaxis()->FindBin(p1[1]);
432         if (fHist[ihist]->GetCellContent(ix,iy) > 0.5) {iok = 1; break;}
433       }
434       if (!iok) continue;
435       gStyle->SetLineColor(1);
436       if (TMath::Abs((Int_t)mHit->Particle()) == 13) {
437         gStyle->SetLineColor(4);
438         if (fnMu < 2) {
439           fxyMu[fnMu][0] = p1[0];
440           fxyMu[fnMu++][1] = p1[1];
441         }
442       }     
443       if (fDebug) printf(" X=%10.4f, Y=%10.4f, Z=%10.4f\n",p1[0],p1[1],mHit->Z());
444       if (view) {
445         // Take into account track angles
446         p2[0] += mHit->Tlength() * TMath::Sin(mHit->Theta()/180*TMath::Pi()) 
447                                  * TMath::Cos(mHit->Phi()/180*TMath::Pi()) / 2;
448         p2[1] += mHit->Tlength() * TMath::Sin(mHit->Theta()/180*TMath::Pi()) 
449                                  * TMath::Sin(mHit->Phi()/180*TMath::Pi()) / 2;
450         view->WCtoNDC(p1, &xNDC[0]);
451         view->WCtoNDC(p2, &xNDC[3]);
452         for (Int_t ipad=1; ipad<3; ipad++) {
453           c1->cd(ipad);
454           //c1->DrawLine(xpad[0],xpad[1],xpad[3],xpad[4]);
455           line[nLine] = new TLine(xNDC[0],xNDC[1],xNDC[3],xNDC[4]);
456           line[nLine++]->Draw();
457         }
458       }
459     } // for (AliMUONHit* mHit=
460   } // for (Int_t i=0; i<ntracks;
461
462   // Draw reconstructed coordinates
463   TClonesArray *listMUONrawclust = data->RawClusters(ch0);
464   AliMUONRawCluster *mRaw;
465   gStyle->SetLineColor(3);
466   cout << " *** Reconstructed hits *** " << endl;
467   if (listMUONrawclust) {
468     for (Int_t i=0; i<listMUONrawclust ->GetEntries(); i++) {
469       mRaw = (AliMUONRawCluster*)listMUONrawclust ->UncheckedAt(i);
470       if (TMath::Abs(mRaw->GetZ(0)-fZpad) > 1) continue; // different slat
471       p2[0] = p1[0] = mRaw->GetX(0);        // x-pos of hit
472       p2[1] = p1[1] = mRaw->GetY(0);        // y-pos
473       if (p1[0] < hist->GetXaxis()->GetXmin() || 
474           p1[0] > hist->GetXaxis()->GetXmax()) continue;
475       if (p1[1] < hist->GetYaxis()->GetXmin() || 
476           p1[1] > hist->GetYaxis()->GetXmax()) continue;
477       /*
478         treeD->GetEvent(cath);
479         cout << mRaw->fMultiplicity[0] << mRaw->fMultiplicity[1] << endl;
480         for (Int_t j=0; j<mRaw->fMultiplicity[cath]; j++) {
481         Int_t digit = mRaw->fIndexMap[j][cath];
482         cout << ((AliMUONDigit*)fMuonDigits->UncheckedAt(digit))->Signal() << endl;
483         }
484       */
485       // Check if track comes thru pads with signal
486       iok = 0;
487       for (Int_t ihist=0; ihist<4; ihist++) {
488         if (!fHist[ihist]) continue;
489         ix = fHist[ihist]->GetXaxis()->FindBin(p1[0]);
490         iy = fHist[ihist]->GetYaxis()->FindBin(p1[1]);
491         if (fHist[ihist]->GetCellContent(ix,iy) > 0.5) {iok = 1; break;}
492       }
493       if (!iok) continue;
494       if (fDebug) printf(" X=%10.4f, Y=%10.4f, Z=%10.4f\n",p1[0],p1[1],mRaw->GetZ(0));
495       if (view) {
496         view->WCtoNDC(p1, &xNDC[0]);
497         view->WCtoNDC(p2, &xNDC[3]);
498         for (Int_t ipad=1; ipad<3; ipad++) {
499           c1->cd(ipad);
500           line[nLine] = new TLine(xNDC[0],xNDC[1],xNDC[3],xNDC[4]);
501           line[nLine++]->Draw();
502         }
503       }
504     } // for (Int_t i=0; i<listMUONrawclust ->GetEntries();
505   } // if (listMUONrawclust)
506   c1->Update();
507 }
508
509 //_____________________________________________________________________________
510 Int_t AliMUONClusterFinderAZ::Next(Int_t &nev0, Int_t &ch0)
511 {
512   // What to do next?
513   // File
514   FILE *lun = 0;
515   //lun = fopen("pull.dat","w");
516
517   for (Int_t i=0; i<fnMu; i++) {
518     // Check again if muon come thru the used pads (due to extra splitting)
519     for (Int_t j=0; j<fnPads[0]+fnPads[1]; j++) {
520       if (TMath::Abs(fxyMu[i][0]-fXyq[0][j])<fXyq[3][j] && 
521           TMath::Abs(fxyMu[i][1]-fXyq[1][j])<fXyq[4][j]) {
522         if (fDebug) printf("%12.3e %12.3e %12.3e %12.3e\n",fxyMu[i][2],fxyMu[i][3],fxyMu[i][4],fxyMu[i][5]);
523         if (lun) fprintf(lun,"%4d %2d %12.3e %12.3e %12.3e %12.3e\n",nev0,ch0,fxyMu[i][2],fxyMu[i][3],fxyMu[i][4],fxyMu[i][5]);
524         break;
525       }
526     }
527   } // for (Int_t i=0; i<fnMu;
528
529   // What's next?
530   char command[8];
531   cout << " What is next? " << endl;
532   command[0] = ' '; 
533   gets(command);
534   if (command[0] == 'n' || command[0] == 'N') {nev0++; ch0 = 0; } // next event
535   else if (command[0] == 'q' || command[0] == 'Q') { if (lun) fclose(lun); } // exit display 
536   else if (command[0] == 'c' || command[0] == 'C') sscanf(command+1,"%d",&ch0); // new chamber
537   else if (command[0] == 'e' || command[0] == 'E') { sscanf(command+1,"%d",&nev0); ch0 = 0; } // new event
538   else return 1; // Next precluster
539   return 0;
540 }
541
542
543 //_____________________________________________________________________________
544 void AliMUONClusterFinderAZ::ModifyHistos(void)
545 {
546   // Modify histograms to bring them to (approximately) the same size
547   Int_t nhist = 0;
548   Float_t hlim[4][4], hbin[4][4]; // first index - xmin, xmax, ymin, ymax
549
550   Float_t binMin[4] = {999,999,999,999};
551
552   for (Int_t i = 0; i < 4; i++) {
553     if (!fHist[i]) {
554       hlim[0][i] = hlim[2][i] = 999;
555       hlim[1][i] = hlim[3][i] = -999;
556       continue;
557     }
558     hlim[0][i] = fHist[i]->GetXaxis()->GetXmin(); // xmin
559     hlim[1][i] = fHist[i]->GetXaxis()->GetXmax(); // xmax
560     hlim[2][i] = fHist[i]->GetYaxis()->GetXmin(); // ymin
561     hlim[3][i] = fHist[i]->GetYaxis()->GetXmax(); // ymax
562     hbin[0][i] = hbin[1][i] = fHist[i]->GetXaxis()->GetBinWidth(1);
563     hbin[2][i] = hbin[3][i] = fHist[i]->GetYaxis()->GetBinWidth(1);
564     binMin[0] = TMath::Min(binMin[0],hbin[0][i]);
565     binMin[2] = TMath::Min(binMin[2],hbin[2][i]);
566     nhist++;
567   }
568   binMin[1] = binMin[0];
569   binMin[3] = binMin[2];
570   cout << " Nhist: " << nhist << endl;
571
572   // Adjust histo limits for cathode with different segmentation
573   for (Int_t i = 0; i < 4; i+=2) {
574     if (!fHist[i+1]) continue;
575     Int_t imin, imax, i1 = i + 1;
576     for (Int_t lim = 0; lim < 4; lim++) {
577       while (1) {
578         if (hlim[lim][i] < hlim[lim][i1]) {
579           imin = i;
580           imax = i1;
581         } else {
582           imin = i1;
583           imax = i;
584         }
585         if (TMath::Abs(hlim[lim][imin]-hlim[lim][imax])<0.01*binMin[lim]) break;
586         if (lim == 0 || lim == 2) {
587           // find lower limit
588           hlim[lim][imax] -= hbin[lim][imax];
589         } else {
590           // find upper limit
591           hlim[lim][imin] += hbin[lim][imin];
592         }
593       } // while (1)
594     }
595   }
596     
597
598   Int_t imnmx = 0, nExtra = 0;
599   for (Int_t lim = 0; lim < 4; lim++) {
600     if (lim == 0 || lim == 2) imnmx = TMath::LocMin(4,hlim[lim]); // find lower limit
601     else imnmx = TMath::LocMax(4,hlim[lim]); // find upper limit
602
603     // Adjust histogram limit
604     for (Int_t i = 0; i < 4; i++) {
605       if (!fHist[i]) continue;
606       nExtra = TMath::Nint ((hlim[lim][imnmx]-hlim[lim][i]) / hbin[lim][i]);
607       hlim[lim][i] += nExtra * hbin[lim][i];
608     }
609   }
610     
611   // Rebuild histograms 
612   TH2F *hist = 0;
613   Int_t nx, ny;
614   Double_t x, y, cont, cmax=0;
615   char hName[4];
616   for (Int_t ihist=0; ihist<4; ihist++) {
617     if (!fHist[ihist]) continue;
618     nx = TMath::Nint((hlim[1][ihist]-hlim[0][ihist])/hbin[0][ihist]);
619     ny = TMath::Nint((hlim[3][ihist]-hlim[2][ihist])/hbin[2][ihist]);
620     cout << ihist << " " << hlim[0][ihist] << " " << hlim[1][ihist] << " " << nx;
621     cout << " " << hlim[2][ihist] << " " << hlim[3][ihist] << " " << ny << endl;
622     sprintf(hName,"hh%d",ihist);
623     hist =  new TH2F(hName,"hist",nx,hlim[0][ihist],hlim[1][ihist],ny,hlim[2][ihist],hlim[3][ihist]);
624     for (Int_t i=1; i<=fHist[ihist]->GetNbinsX(); i++) {
625       x = fHist[ihist]->GetXaxis()->GetBinCenter(i);
626       for (Int_t j=1; j<=fHist[ihist]->GetNbinsY(); j++) {
627         y = fHist[ihist]->GetYaxis()->GetBinCenter(j);
628         cont = fHist[ihist]->GetCellContent(i,j);
629         hist->Fill(x,y,cont);
630       }
631     }
632     cmax = TMath::Max (cmax,hist->GetMaximum());
633     sprintf(hName,"%s%d",fHist[ihist]->GetName(),ihist);
634     fHist[ihist]->Delete();
635     fHist[ihist] = new TH2F(*hist);
636     fHist[ihist]->SetName(hName);
637     fHist[ihist]->SetNdivisions(505,"Z");
638     hist->Delete(); 
639   }
640   if (fDebug) printf("%f \n",cmax);
641
642   for (Int_t ihist=0; ihist<4; ihist++) {
643     if (!fHist[ihist]) continue;
644     fHist[ihist]->SetMaximum(cmax);
645     fHist[ihist]->SetMinimum(0);
646   }
647 }
648
649 //_____________________________________________________________________________
650 void AliMUONClusterFinderAZ::AddPad(Int_t cath, Int_t digit)
651 {
652   // Add pad to the cluster
653   //AZ AliMUONDigit *mdig = (AliMUONDigit*)fMuonDigits->UncheckedAt(digit);
654   AliMUONDigit *mdig = AliMUONClusterInput::Instance()->Digit(cath,digit); //AZ
655
656   Int_t charge = mdig->Signal();
657   // get the center of the pad
658   Float_t xpad, ypad, zpad0; //, zpad;
659   fSegmentation[cath]->GetPadC(fInput->DetElemId(),mdig->PadX(),mdig->PadY(),xpad,ypad,zpad0);
660   
661   Int_t   isec = fSegmentation[cath]->Sector(fInput->DetElemId(),mdig->PadX(), mdig->PadY());
662   Int_t nPads = fnPads[0] + fnPads[1];
663   fXyq[0][nPads] = xpad;
664   fXyq[1][nPads] = ypad;
665   fXyq[2][nPads] = charge;
666   fXyq[3][nPads] = fSegmentation[cath]->Dpx(fInput->DetElemId(),isec)/2;
667   fXyq[4][nPads] = fSegmentation[cath]->Dpy(fInput->DetElemId(),isec)/2;
668   fXyq[5][nPads] = digit;
669   fXyq[6][nPads] = 0;
670   fPadIJ[0][nPads] = cath;
671   fPadIJ[1][nPads] = 0;
672   fUsed[cath][digit] = kTRUE;
673   if (fDebug) printf(" bbb %d %d %f %f %f %f %f %d\n", nPads, cath, xpad, ypad, zpad0, fXyq[3][nPads]*2, fXyq[4][nPads]*2, charge);
674   fnPads[cath]++;
675
676   // Check neighbours
677   Int_t nn, ix, iy, xList[10], yList[10];
678   AliMUONDigit  *mdig1;
679
680   //AZ Int_t ndigits = fMuonDigits->GetEntriesFast();
681   Int_t ndigits = AliMUONClusterInput::Instance()->NDigits(cath); //AZ
682   fSegmentation[cath]->Neighbours(fInput->DetElemId(),mdig->PadX(),mdig->PadY(),&nn,xList,yList); 
683   for (Int_t in=0; in<nn; in++) {
684     ix=xList[in];
685     iy=yList[in];
686     for (Int_t digit1 = 0; digit1 < ndigits; digit1++) {
687       if (digit1 == digit) continue;
688       //AZ mdig1 = (AliMUONDigit*)fMuonDigits->UncheckedAt(digit1);
689       mdig1 = AliMUONClusterInput::Instance()->Digit(cath,digit1); //AZ
690       //AZobsolete if (mdig1->Cathode() != cath) continue;
691       if (!fUsed[cath][digit1] && mdig1->PadX() == ix && mdig1->PadY() == iy) {
692         //AZ--- temporary fix on edges
693         //fSegmentation[cath]->GetPadC(mdig1->PadX(), mdig1->PadY(), xpad, ypad, zpad);
694         //if (TMath::Abs(zpad-zpad0) > 0.5) continue;
695         //AZ---
696         fUsed[cath][digit1] = kTRUE;
697         // Add pad - recursive call
698         AddPad(cath,digit1);
699       }
700     } //for (Int_t digit1 = 0;
701   } // for (Int_t in=0;
702 }
703
704 //_____________________________________________________________________________
705 Bool_t AliMUONClusterFinderAZ::Overlap(Int_t cath, AliMUONDigit *mdig)
706 {
707   // Check if the pad from one cathode overlaps with a pad 
708   // in the precluster on the other cathode
709
710   Float_t xpad, ypad, zpad;
711   fSegmentation[cath]->GetPadC(fInput->DetElemId(),mdig->PadX(),mdig->PadY(),xpad,ypad,zpad);
712   Int_t   isec = fSegmentation[cath]->Sector(fInput->DetElemId(),mdig->PadX(), mdig->PadY());
713
714   Float_t xy1[4], xy12[4];
715   xy1[0] = xpad - fSegmentation[cath]->Dpx(fInput->DetElemId(),isec)/2;
716   xy1[1] = xy1[0] + fSegmentation[cath]->Dpx(fInput->DetElemId(),isec);
717   xy1[2] = ypad - fSegmentation[cath]->Dpy(fInput->DetElemId(),isec)/2;
718   xy1[3] = xy1[2] + fSegmentation[cath]->Dpy(fInput->DetElemId(),isec);
719   //cout << " ok " << fnPads[0]+fnPads[1] << xy1[0] << xy1[1] << xy1[2] << xy1[3] << endl;
720
721   Int_t cath1 = TMath::Even(cath);
722   for (Int_t i=0; i<fnPads[0]+fnPads[1]; i++) {
723     if (fPadIJ[0][i] != cath1) continue;
724     if (Overlap(xy1, i, xy12, 0)) return kTRUE;
725   }
726   return kFALSE;
727 }
728
729 //_____________________________________________________________________________
730 Bool_t AliMUONClusterFinderAZ::Overlap(Float_t *xy1, Int_t iPad, Float_t *xy12, Int_t iSkip)
731 {
732   // Check if the pads xy1 and iPad overlap and return overlap area
733
734   Float_t xy2[4];
735   xy2[0] = fXyq[0][iPad] - fXyq[3][iPad];
736   xy2[1] = fXyq[0][iPad] + fXyq[3][iPad];
737   if (xy1[0] > xy2[1]-1.e-4 || xy1[1] < xy2[0]+1.e-4) return kFALSE;
738   xy2[2] = fXyq[1][iPad] - fXyq[4][iPad];
739   xy2[3] = fXyq[1][iPad] + fXyq[4][iPad];
740   if (xy1[2] > xy2[3]-1.e-4 || xy1[3] < xy2[2]+1.e-4) return kFALSE;
741   if (!iSkip) return kTRUE; // just check overlap (w/out computing the area)
742   xy12[0] = TMath::Max (xy1[0],xy2[0]);
743   xy12[1] = TMath::Min (xy1[1],xy2[1]);
744   xy12[2] = TMath::Max (xy1[2],xy2[2]);
745   xy12[3] = TMath::Min (xy1[3],xy2[3]);
746   return kTRUE;
747 }
748
749 //_____________________________________________________________________________
750 /*
751 Bool_t AliMUONClusterFinderAZ::Overlap(Int_t i, Int_t j, Float_t *xy12, Int_t iSkip)
752 {
753   // Check if the pads i and j overlap and return overlap area
754
755   Float_t xy1[4], xy2[4];
756   return Overlap(xy1, xy2, xy12, iSkip);
757 }
758 */
759 //_____________________________________________________________________________
760 Bool_t AliMUONClusterFinderAZ::CheckPrecluster(Int_t *nShown)
761 {
762   // Check precluster in order to attempt to simplify it (mostly for
763   // two-cathode preclusters)
764
765   Int_t i1, i2, cath=0, digit=0;
766   Float_t xy1[4], xy12[4];
767   
768   Int_t npad = fnPads[0] + fnPads[1];
769   if (npad == 1) { 
770     // Disregard one-pad clusters (leftovers from splitting)
771     nShown[0] += fnPads[0]; 
772     nShown[1] += fnPads[1]; 
773     return kFALSE;
774   }
775
776   // If pads have the same size take average of pads on both cathodes 
777   Int_t sameSize = (fnPads[0] && fnPads[1]) ? 1 : 0;
778   if (sameSize) {
779     Double_t xSize = -1, ySize = 0;
780     for (Int_t i=0; i<npad; i++) {
781       if (fXyq[2][i] < 0) continue;
782       if (xSize < 0) { xSize = fXyq[3][i]; ySize = fXyq[4][i]; }
783       if (TMath::Abs(xSize-fXyq[3][i]) > 1.e-4 ||  TMath::Abs(ySize-fXyq[4][i]) > 1.e-4) { sameSize = 0; break; }
784     }
785   } // if (sameSize)
786   if (sameSize && fnPads[0] == 1 && fnPads[1] == 1) sameSize = 0; //AZ
787   if (sameSize && (fnPads[0] >= 2 || fnPads[1] >= 2)) {
788     nShown[0] += fnPads[0];
789     nShown[1] += fnPads[1];
790     fnPads[0] = fnPads[1] = 0;
791     Int_t div;
792     for (Int_t i=0; i<npad; i++) {
793       if (fXyq[2][i] < 0) continue; // used pad
794       fXyq[2][fnPads[0]] = fXyq[2][i];
795       div = 1;
796       cath = fPadIJ[0][i];
797       for (Int_t j=i+1; j<npad; j++) {
798         if (fPadIJ[0][j] == fPadIJ[0][i]) continue; // same cathode
799         if (TMath::Abs(fXyq[0][j]-fXyq[0][i]) > 1.e-4) continue;
800         if (TMath::Abs(fXyq[1][j]-fXyq[1][i]) > 1.e-4) continue;
801         fXyq[2][fnPads[0]] += fXyq[2][j];
802         div = 2;
803         fXyq[2][j] = -2;
804         if (cath) fXyq[5][fnPads[0]] = fXyq[5][j]; // save digit number for cath 0
805         break;
806       }
807       // Flag that the digit from the other cathode
808       if (cath && div == 1) fXyq[5][fnPads[0]] = -fXyq[5][i] - 1; 
809       // If low pad charge take the other equal to 0 
810       if (div == 1 && fXyq[2][fnPads[0]] < fResponse->ZeroSuppression() + 1.5*3) div = 2;
811       fXyq[2][fnPads[0]] /= div;
812       fXyq[0][fnPads[0]] = fXyq[0][i];
813       fXyq[1][fnPads[0]] = fXyq[1][i];
814       fPadIJ[0][fnPads[0]++] = 0;
815     }
816   } // if (sameSize)
817
818   // Check if one-cathode precluster
819   i1 = fnPads[0]!=0 ? 0 : 1;
820   i2 = fnPads[1]!=0 ? 1 : 0;
821
822   if (i1 != i2) { // two-cathode 
823
824     Int_t *flags = new Int_t[npad];
825     for (Int_t i=0; i<npad; i++) { flags[i] = 0; }
826
827     // Check pad overlaps
828     for (Int_t i=0; i<npad; i++) {
829       if (fPadIJ[0][i] != i1) continue;
830       xy1[0] = fXyq[0][i] - fXyq[3][i];
831       xy1[1] = fXyq[0][i] + fXyq[3][i];
832       xy1[2] = fXyq[1][i] - fXyq[4][i];
833       xy1[3] = fXyq[1][i] + fXyq[4][i];
834       for (Int_t j=0; j<npad; j++) {
835         if (fPadIJ[0][j] != i2) continue;
836         if (!Overlap(xy1, j, xy12, 0)) continue;
837         flags[i] = flags[j] = 1; // mark overlapped pads
838       } // for (Int_t j=0;
839     } // for (Int_t i=0;
840
841     // Check if all pads overlap
842     Int_t nFlags=0;
843     for (Int_t i=0; i<npad; i++) {
844       if (flags[i]) continue;
845       nFlags ++;
846       if (fDebug) cout << i << " " << fPadIJ[0][i] << endl;
847     }
848     if (fDebug && nFlags) cout << " nFlags = " << nFlags << endl;
849     //if (nFlags > 2 || (Float_t)nFlags / npad > 0.2) { // why 2 ??? - empirical choice
850     if (nFlags > 1) {
851       for (Int_t i=0; i<npad; i++) {
852         if (flags[i]) continue;
853         digit = TMath::Nint (fXyq[5][i]);
854         cath = fPadIJ[0][i];
855         fUsed[cath][digit] = kFALSE; // release pad
856         fXyq[2][i] = -2;
857         fnPads[cath]--;
858       }
859     } // if (nFlags > 2)
860
861     // Check correlations of cathode charges
862     if (fnPads[0] && fnPads[1]) { // two-cathode
863       Double_t sum[2]={0};
864       Int_t over[2] = {1, 1};
865       for (Int_t i=0; i<npad; i++) {
866         cath = fPadIJ[0][i];
867         if (fXyq[2][i] > 0) sum[cath] += fXyq[2][i];
868         //AZ if (fXyq[2][i] > fResponse->MaxAdc()-1) over[cath] = 0;
869         if (fXyq[2][i] > fResponse->Saturation()-1) over[cath] = 0;
870       }
871       if (fDebug) cout << " Total charge: " << sum[0] << " " << sum[1] << endl;
872       if ((over[0] || over[1]) && TMath::Abs(sum[0]-sum[1])/(sum[0]+sum[1])*2 > 1) { // 3 times difference
873         if (fDebug) cout << " Release " << endl;
874         // Big difference
875         cath = sum[0]>sum[1] ? 0 : 1;
876         Int_t imax = 0;
877         Double_t cmax=-1;
878         Double_t *dist = new Double_t[npad];
879         for (Int_t i=0; i<npad; i++) {
880           if (fPadIJ[0][i] != cath) continue;
881           if (fXyq[2][i] < cmax) continue;
882           cmax = fXyq[2][i];
883           imax = i;
884         }
885         // Arrange pads according to their distance to the max, 
886         // normalized to the pad size
887         for (Int_t i=0; i<npad; i++) {
888           dist[i] = 0;
889           if (fPadIJ[0][i] != cath) continue;
890           if (i == imax) continue; 
891           if (fXyq[2][i] < 0) continue;
892           dist[i] = (fXyq[0][i]-fXyq[0][imax])*(fXyq[0][i]-fXyq[0][imax])/
893                      fXyq[3][imax]/fXyq[3][imax]/4;
894           dist[i] += (fXyq[1][i]-fXyq[1][imax])*(fXyq[1][i]-fXyq[1][imax])/
895                       fXyq[4][imax]/fXyq[4][imax]/4;
896           dist[i] = TMath::Sqrt (dist[i]);
897         }
898         TMath::Sort(npad, dist, flags, kFALSE); // in increasing order
899         Int_t indx;
900         Double_t xmax = -1;
901         for (Int_t i=0; i<npad; i++) {
902           indx = flags[i];
903           if (fPadIJ[0][indx] != cath) continue;
904           if (fXyq[2][indx] < 0) continue;
905           if (fXyq[2][indx] <= cmax || TMath::Abs(dist[indx]-xmax)<1.e-3) {
906             // Release pads
907             if (TMath::Abs(dist[indx]-xmax)<1.e-3) 
908                 cmax = TMath::Max((Double_t)(fXyq[2][indx]),cmax);
909             else cmax = fXyq[2][indx];
910             xmax = dist[indx];
911             digit = TMath::Nint (fXyq[5][indx]);
912             fUsed[cath][digit] = kFALSE; 
913             fXyq[2][indx] = -2;
914             fnPads[cath]--;
915             // xmax = dist[i]; // Bug?
916           } else {
917             // Check pad overlaps once more
918             for (Int_t i=0; i<npad; i++) flags[i] = 0; 
919             for (Int_t i=0; i<npad; i++) {
920               if (fXyq[2][i] < 0) continue;
921               if (fPadIJ[0][i] != i1) continue;
922               xy1[0] = fXyq[0][i] - fXyq[3][i];
923               xy1[1] = fXyq[0][i] + fXyq[3][i];
924               xy1[2] = fXyq[1][i] - fXyq[4][i];
925               xy1[3] = fXyq[1][i] + fXyq[4][i];
926               for (Int_t j=0; j<npad; j++) {
927                 if (fXyq[2][j] < 0) continue;
928                 if (fPadIJ[0][j] != i2) continue;
929                 if (!Overlap(xy1, j, xy12, 0)) continue;
930                 flags[i] = flags[j] = 1; // mark overlapped pads
931               } // for (Int_t j=0;
932             } // for (Int_t i=0;
933             nFlags=0;
934             for (Int_t i=0; i<npad; i++) {
935               if (fXyq[2][i] < 0 || flags[i]) continue;
936               nFlags ++;
937             }
938             if (nFlags == fnPads[0] + fnPads[1]) {
939               // No overlap
940               for (Int_t i=0; i<npad; i++) {
941                 if (fXyq[2][i] < 0 || fPadIJ[0][i] != cath) continue;
942                 fXyq[2][i] = -2;
943                 fnPads[cath]--;
944               }
945             }
946             break;
947           }
948         } 
949         delete [] dist; dist = 0;
950       } // TMath::Abs(sum[0]-sum[1])...
951     } // if (fnPads[0] && fnPads[1])
952     delete [] flags; flags = 0;
953   } // if (i1 != i2) 
954
955   if (!sameSize) { nShown[0] += fnPads[0]; nShown[1] += fnPads[1]; }
956
957   // Move released pads to the right
958   Int_t beg = 0, end = npad-1, padij;
959   Double_t xyq;
960   while (beg < end) {
961     if (fXyq[2][beg] > 0) { beg++; continue; }
962     for (Int_t j=end; j>beg; j--) {
963       if (fXyq[2][j] < 0) continue;
964       end = j - 1;
965       for (Int_t j1=0; j1<2; j1++) {
966         padij = fPadIJ[j1][beg]; 
967         fPadIJ[j1][beg] = fPadIJ[j1][j];
968         fPadIJ[j1][j] = padij;
969       }
970       for (Int_t j1=0; j1<6; j1++) {
971         xyq = fXyq[j1][beg]; 
972         fXyq[j1][beg] = fXyq[j1][j];
973         fXyq[j1][j] = xyq;
974       }
975       break;
976     } // for (Int_t j=end;
977     beg++;
978   } // while
979   npad = fnPads[0] + fnPads[1];
980   if (npad > 500) { cout << " ***** Too large cluster. Give up. " << npad << endl; return kFALSE; }
981   // Back up charge value
982   for (Int_t j=0; j<npad; j++) fXyq[6][j] = fXyq[2][j];
983
984   return kTRUE;
985 }
986
987 //_____________________________________________________________________________
988 void AliMUONClusterFinderAZ::BuildPixArray()
989 {
990   // Build pixel array for MLEM method
991   
992   Int_t nPix=0, i1, i2;
993   Float_t xy1[4], xy12[4];
994   AliMUONPixel *pixPtr=0;
995
996   Int_t npad = fnPads[0] + fnPads[1];
997
998   // One cathode is empty
999   i1 = fnPads[0]!=0 ? 0 : 1;
1000   i2 = fnPads[1]!=0 ? 1 : 0;
1001
1002   // Build array of pixels on anode plane
1003   if (i1 == i2) { // one-cathode precluster
1004     for (Int_t j=0; j<npad; j++) {
1005       pixPtr = new AliMUONPixel();
1006       for (Int_t i=0; i<2; i++) {
1007         pixPtr->SetCoord(i, fXyq[i][j]); // pixel coordinates
1008         pixPtr->SetSize(i, fXyq[i+3][j]); // pixel size
1009       }
1010       pixPtr->SetCharge(fXyq[2][j]); // charge
1011       fPixArray->Add((TObject*)pixPtr);
1012       nPix++;
1013     }
1014   } else { // two-cathode precluster    
1015     for (Int_t i=0; i<npad; i++) {
1016       if (fPadIJ[0][i] != i1) continue;
1017       xy1[0] = fXyq[0][i] - fXyq[3][i];
1018       xy1[1] = fXyq[0][i] + fXyq[3][i];
1019       xy1[2] = fXyq[1][i] - fXyq[4][i];
1020       xy1[3] = fXyq[1][i] + fXyq[4][i];
1021       for (Int_t j=0; j<npad; j++) {
1022         if (fPadIJ[0][j] != i2) continue;
1023         if (!Overlap(xy1, j, xy12, 1)) continue;
1024         pixPtr = new AliMUONPixel();
1025         for (Int_t k=0; k<2; k++) {
1026           pixPtr->SetCoord(k, (xy12[2*k]+xy12[2*k+1])/2); // pixel coordinates
1027           pixPtr->SetSize(k, xy12[2*k+1]-pixPtr->Coord(k)); // size
1028         }
1029         pixPtr->SetCharge(TMath::Min (fXyq[2][i],fXyq[2][j])); //charge
1030         fPixArray->Add((TObject*)pixPtr);
1031         //cout << nPix << " " << pixPtr->Coord(0) << " " << pixPtr->Size(0) << " " << pixPtr->Coord(1) << " " << pixPtr->Size(1) << " " << pixPtr->Charge() << endl;
1032         nPix++;
1033       } // for (Int_t j=0;
1034     } // for (Int_t i=0;
1035   } // else
1036
1037   Float_t wxmin=999, wymin=999;
1038   for (Int_t i=0; i<npad; i++) {
1039     //if (fPadIJ[0][i] == i1) wymin = TMath::Min (wymin,fXyq[4][i]);
1040     //if (fPadIJ[0][i] == i2) wxmin = TMath::Min (wxmin,fXyq[3][i]);
1041     wymin = TMath::Min (wymin,fXyq[4][i]);
1042     wxmin = TMath::Min (wxmin,fXyq[3][i]);
1043   }
1044   if (fDebug) cout << wxmin << " " << wymin << endl;
1045
1046   // Check if small pixel X-size
1047   AdjustPixel(wxmin, 0);
1048   // Check if small pixel Y-size
1049   AdjustPixel(wymin, 1);
1050   // Check if large pixel size
1051   AdjustPixel(wxmin, wymin);
1052
1053   // Remove discarded pixels
1054   for (Int_t i=0; i<nPix; i++) {
1055     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
1056     //pixPtr->Print();
1057     if (pixPtr->Charge() < 1) { fPixArray->RemoveAt(i); delete pixPtr; }// discarded pixel
1058   }
1059   fPixArray->Compress();
1060   nPix = fPixArray->GetEntriesFast();
1061
1062   if (nPix > npad) {
1063     if (fDebug) cout << nPix << endl;
1064     // Too many pixels - sort and remove pixels with the lowest signal
1065     fPixArray->Sort();
1066     for (Int_t i=npad; i<nPix; i++) {
1067       pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
1068       //pixPtr->Print();
1069       fPixArray->RemoveAt(i);
1070       delete pixPtr;
1071     }
1072     nPix = npad;
1073   } // if (nPix > npad)
1074
1075   // Set pixel charges to the same value (for MLEM)
1076   for (Int_t i=0; i<nPix; i++) {
1077     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
1078     //pixPtr->SetCharge(10);
1079     if (fDebug) cout << i+1 << " " << pixPtr->Coord(0) << " " << pixPtr->Coord(1) << " " << pixPtr->Size(0) << " " << pixPtr->Size(1) << endl;
1080   }
1081 }
1082
1083 //_____________________________________________________________________________
1084 void AliMUONClusterFinderAZ::AdjustPixel(Float_t width, Int_t ixy)
1085 {
1086   // Check if some pixels have small size (adjust if necessary)
1087
1088   AliMUONPixel *pixPtr, *pixPtr1 = 0;
1089   Int_t ixy1 = TMath::Even(ixy);
1090   Int_t nPix = fPixArray->GetEntriesFast();
1091
1092   for (Int_t i=0; i<nPix; i++) {
1093     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
1094     if (pixPtr->Charge() < 1) continue; // discarded pixel
1095     if (pixPtr->Size(ixy)-width < -1.e-4) {
1096       // try to merge 
1097       if (fDebug) cout << i << " Small X or Y: " << ixy << " " << pixPtr->Size(ixy) << " " << width << " " << pixPtr->Coord(0) << " " << pixPtr->Coord(1) << endl;
1098       for (Int_t j=i+1; j<nPix; j++) {
1099         pixPtr1 = (AliMUONPixel*) fPixArray->UncheckedAt(j);
1100         if (pixPtr1->Charge() < 1) continue; // discarded pixel
1101         if (TMath::Abs(pixPtr1->Size(ixy)-width) < 1.e-4) continue; // right size 
1102         if (TMath::Abs(pixPtr1->Coord(ixy1)-pixPtr->Coord(ixy1)) > 1.e-4) continue; // different rows/columns
1103         if (TMath::Abs(pixPtr1->Coord(ixy)-pixPtr->Coord(ixy)) < 2*width) {
1104           // merge
1105           //AZ-problem in slats for new segment. pixPtr->SetCoord(ixy, (pixPtr->Coord(ixy)+pixPtr1->Coord(ixy))/2);
1106           Double_t tmp = pixPtr->Coord(ixy) + pixPtr1->Size(ixy) * 
1107             TMath::Sign (1., pixPtr1->Coord(ixy) - pixPtr->Coord(ixy));
1108           pixPtr->SetCoord(ixy, tmp);
1109           pixPtr->SetSize(ixy, width);
1110           pixPtr->SetCharge(TMath::Min (pixPtr->Charge(),pixPtr1->Charge()));
1111           pixPtr1->SetCharge(0);
1112           pixPtr1 = 0;
1113           break;
1114         }
1115       } // for (Int_t j=i+1;
1116       //if (!pixPtr1) { cout << " I am here!" << endl; pixPtr->SetSize(ixy, width); } // ???
1117       //else if (pixPtr1->Charge() > 0.5 || i == nPix-1) {
1118       if (pixPtr1 || i == nPix-1) {
1119         // edge pixel - just increase its size
1120         if (fDebug) cout << " Edge ..." << endl; 
1121         for (Int_t j=0; j<fnPads[0]+fnPads[1]; j++) {
1122           //if (fPadIJ[0][j] != ixy1) continue;
1123           if (TMath::Abs(pixPtr->Coord(ixy1)-fXyq[ixy1][j]) > 1.e-4) continue;
1124           if (pixPtr->Coord(ixy) < fXyq[ixy][j]) 
1125             //pixPtr->Shift(ixy, -pixPtr->Size(ixy));
1126             pixPtr->Shift(ixy, pixPtr->Size(ixy)-width);
1127           //else pixPtr->Shift(ixy, pixPtr->Size(ixy));
1128           else pixPtr->Shift(ixy, -pixPtr->Size(ixy)+width);
1129           pixPtr->SetSize(ixy, width);
1130           break;
1131         }
1132       }
1133     } // if (pixPtr->Size(ixy)-width < -1.e-4)
1134   } // for (Int_t i=0; i<nPix;
1135   return;
1136 }
1137   
1138 //_____________________________________________________________________________
1139 void AliMUONClusterFinderAZ::AdjustPixel(Float_t wxmin, Float_t wymin)
1140 {
1141   // Check if some pixels have large size (adjust if necessary)
1142
1143   Int_t nx, ny;
1144   Int_t nPix = fPixArray->GetEntriesFast();
1145   AliMUONPixel *pixPtr, *pixPtr1, pix;
1146
1147   // Check if large pixel size
1148   for (Int_t i=0; i<nPix; i++) {
1149     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
1150     if (pixPtr->Charge() < 1) continue; // discarded pixel
1151     if (pixPtr->Size(0)-wxmin > 1.e-4 || pixPtr->Size(1)-wymin > 1.e-4) {
1152       if (fDebug) cout << " Different " << pixPtr->Size(0) << " " << wxmin << " " << pixPtr->Size(1) << " " << wymin << endl;
1153       pix = *pixPtr;
1154       nx = TMath::Nint (pix.Size(0)/wxmin);
1155       ny = TMath::Nint (pix.Size(1)/wymin);
1156       pix.Shift(0, -pix.Size(0)-wxmin);
1157       pix.Shift(1, -pix.Size(1)-wymin);
1158       pix.SetSize(0, wxmin);
1159       pix.SetSize(1, wymin);
1160       for (Int_t ii=0; ii<nx; ii++) {
1161         pix.Shift(0, wxmin*2);
1162         for (Int_t jj=0; jj<ny; jj++) {
1163           pix.Shift(1, wymin*2);
1164           pixPtr1 = new AliMUONPixel(pix);
1165           fPixArray->Add((TObject*)pixPtr1);
1166         }
1167       }
1168       pixPtr->SetCharge(0);
1169     }
1170   } // for (Int_t i=0; i<nPix;
1171   return;
1172 }
1173
1174 //_____________________________________________________________________________
1175 Bool_t AliMUONClusterFinderAZ::MainLoop(Int_t iSimple)
1176 {
1177   // Repeat MLEM algorithm until pixel size becomes sufficiently small
1178   
1179   TH2D *mlem;
1180
1181   Int_t ix, iy;
1182   //Int_t nn, xList[10], yList[10];
1183   Int_t nPix = fPixArray->GetEntriesFast();
1184   AliMUONPixel *pixPtr = 0;
1185   Double_t *coef = 0, *probi = 0; 
1186   AddVirtualPad(); // add virtual pads if necessary
1187   Int_t npadTot = fnPads[0] + fnPads[1], npadOK = 0;
1188   for (Int_t i=0; i<npadTot; i++) if (fPadIJ[1][i] == 0) npadOK++;
1189
1190   while (1) {
1191
1192     mlem = (TH2D*) gROOT->FindObject("mlem");
1193     if (mlem) mlem->Delete();
1194     // Calculate coefficients
1195     if (fDebug) cout << " nPix, npadTot, npadOK " << nPix << " " << npadTot << " " << npadOK << endl;
1196
1197     // Calculate coefficients and pixel visibilities
1198     coef = new Double_t [npadTot*nPix];
1199     probi = new Double_t [nPix];
1200     for (Int_t ipix=0; ipix<nPix; ipix++) probi[ipix] = 0;
1201     Int_t indx = 0, indx1 = 0, cath = 0;
1202
1203     for (Int_t j=0; j<npadTot; j++) {
1204       indx = j*nPix;
1205       if (fPadIJ[1][j] == 0) {
1206         cath = fPadIJ[0][j];
1207         fSegmentation[cath]->GetPadI(fInput->DetElemId(),fXyq[0][j],fXyq[1][j],fZpad,ix,iy);
1208         fSegmentation[cath]->SetPad(fInput->DetElemId(),ix,iy);
1209         /*
1210           fSegmentation[cath]->Neighbours(fInput->DetElemId(),ix,iy,&nn,xList,yList); 
1211           if (nn != 4) {
1212           cout << nn << ": ";
1213           for (Int_t i=0; i<nn; i++) {cout << xList[i] << " " << yList[i] << ", ";}
1214           cout << endl;
1215           }
1216         */
1217       }
1218
1219       for (Int_t ipix=0; ipix<nPix; ipix++) {
1220         indx1 = indx + ipix;
1221         if (fPadIJ[1][j] < 0) { coef[indx1] = 0; continue; }
1222         pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(ipix);
1223         fSegmentation[cath]->SetHit(fInput->DetElemId(),pixPtr->Coord(0),pixPtr->Coord(1),fZpad);
1224         coef[indx1] = fResponse->IntXY(fInput->DetElemId(),fSegmentation[cath]);
1225         probi[ipix] += coef[indx1];
1226       } // for (Int_t ipix=0;
1227     } // for (Int_t j=0;
1228     for (Int_t ipix=0; ipix<nPix; ipix++) if (probi[ipix] < 0.01) pixPtr->SetCharge(0); // "invisible" pixel
1229
1230     // MLEM algorithm
1231     Mlem(coef, probi, 15);
1232
1233     Double_t xylim[4] = {999, 999, 999, 999};
1234     for (Int_t ipix=0; ipix<nPix; ipix++) {
1235       pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(ipix);
1236       for (Int_t i=0; i<4; i++) 
1237         xylim[i] = TMath::Min (xylim[i], (i%2 ? -1 : 1)*pixPtr->Coord(i/2));
1238       //cout << ipix+1; pixPtr->Print();
1239     }
1240     for (Int_t i=0; i<4; i++) {
1241       xylim[i] -= pixPtr->Size(i/2); if (fDebug) cout << (i%2 ? -1 : 1)*xylim[i] << " "; }
1242     if (fDebug) cout << endl;
1243
1244     // Adjust histogram to approximately the same limits as for the pads
1245     // (for good presentation)
1246     //*
1247     Float_t xypads[4];
1248     if (fHist[0]) {
1249       xypads[0] = fHist[0]->GetXaxis()->GetXmin();
1250       xypads[1] = -fHist[0]->GetXaxis()->GetXmax();
1251       xypads[2] = fHist[0]->GetYaxis()->GetXmin();
1252       xypads[3] = -fHist[0]->GetYaxis()->GetXmax();
1253       for (Int_t i=0; i<4; i++) {
1254         while(1) {
1255           if (xylim[i] < xypads[i]) break;
1256           xylim[i] -= 2*pixPtr->Size(i/2);
1257         }
1258       }
1259     } // if (fHist[0])
1260     //*/
1261     Int_t nx = TMath::Nint ((-xylim[1]-xylim[0])/pixPtr->Size(0)/2);
1262     Int_t ny = TMath::Nint ((-xylim[3]-xylim[2])/pixPtr->Size(1)/2);
1263     
1264     mlem = new TH2D("mlem","mlem",nx,xylim[0],-xylim[1],ny,xylim[2],-xylim[3]);
1265     for (Int_t ipix=0; ipix<nPix; ipix++) {
1266       pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(ipix);
1267       mlem->Fill(pixPtr->Coord(0),pixPtr->Coord(1),pixPtr->Charge());
1268     }
1269     //gPad->GetCanvas()->cd(3);
1270     if (fDraw) {
1271       ((TCanvas*)gROOT->FindObject("c2"))->cd();
1272       gPad->SetTheta(55);
1273       gPad->SetPhi(30);
1274       //mlem->SetFillColor(19);
1275       mlem->Draw("lego1Fb");
1276       gPad->Update();
1277       gets((char*)&ix);
1278     }
1279
1280     // Check if the total charge of pixels is too low
1281     Double_t qTot = 0;
1282     for (Int_t i=0; i<nPix; i++) {
1283       pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
1284       qTot += pixPtr->Charge();
1285     }
1286     //AZif (qTot < 1.e-4 || npadOK < 3 && qTot < 50) {
1287     if (qTot < 1.e-4 || npadOK < 3 && qTot < 7) {
1288       delete [] coef; delete [] probi; coef = 0; probi = 0;
1289       fPixArray->Delete(); 
1290       for (Int_t i=0; i<npadTot; i++) if (fPadIJ[1][i] == 0) fPadIJ[1][i] = -1;
1291       return kFALSE; 
1292     }
1293
1294     // Plot data - expectation
1295     /*
1296     Double_t x, y, cont;
1297     for (Int_t j=0; j<npadTot; j++) {
1298       Double_t sum1 = 0;
1299       for (Int_t i=0; i<nPix; i++) {
1300         // Caculate expectation
1301         pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
1302         sum1 += pixPtr->Charge()*coef[j*nPix+i];
1303       }
1304       //AZsum1 = TMath::Min (sum1,(Double_t)fResponse->MaxAdc());
1305       sum1 = TMath::Min (sum1,(Double_t)fResponse->Saturation());
1306       x = fXyq[0][j];
1307       y = fXyq[1][j];
1308       cath = fPadIJ[0][j];
1309       Int_t ihist = cath*2;
1310       ix = fHist[ihist]->GetXaxis()->FindBin(x);
1311       iy = fHist[ihist]->GetYaxis()->FindBin(y);
1312       cont = fHist[ihist]->GetCellContent(ix,iy);
1313       if (cont == 0 && fHist[ihist+1]) {
1314         ihist += 1;
1315         ix = fHist[ihist]->GetXaxis()->FindBin(x);
1316         iy = fHist[ihist]->GetYaxis()->FindBin(y);
1317       }
1318       fHist[ihist]->SetBinContent(ix,iy,fXyq[2][j]-sum1);
1319     }
1320     ((TCanvas*)gROOT->FindObject("c1"))->cd(1);
1321     //gPad->SetTheta(55);
1322     //gPad->SetPhi(30);
1323     //mlem->Draw("lego1");
1324     gPad->Modified();
1325     ((TCanvas*)gROOT->FindObject("c1"))->cd(2);
1326     gPad->Modified();
1327     */
1328
1329     if (iSimple) {
1330       // Simple cluster - skip further passes thru EM-procedure
1331       fxyMu[0][6] = fxyMu[1][6] = 9999;
1332       Simple();
1333       delete [] coef; delete [] probi; coef = 0; probi = 0;
1334       fPixArray->Delete(); 
1335       return kTRUE;
1336     }
1337
1338     // Calculate position of the center-of-gravity around the maximum pixel
1339     Double_t xyCOG[2];
1340     FindCOG(mlem, xyCOG);
1341
1342     if (TMath::Min(pixPtr->Size(0),pixPtr->Size(1)) < 0.07 && pixPtr->Size(0) > pixPtr->Size(1)) break;
1343     //if (TMath::Min(pixPtr->Size(0),pixPtr->Size(1)) < 0.007 && pixPtr->Size(0) > pixPtr->Size(1)) break;
1344     //if (TMath::Min(pixPtr->Size(0),pixPtr->Size(1)) >= 0.07 || pixPtr->Size(0) < pixPtr->Size(1)) {
1345     // Sort pixels according to the charge
1346     fPixArray->Sort();
1347     /*
1348     for (Int_t i=0; i<nPix; i++) {
1349       pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
1350       cout << i+1; pixPtr->Print();
1351     }
1352     */
1353     Double_t pixMin = 0.01*((AliMUONPixel*)fPixArray->UncheckedAt(0))->Charge();
1354     pixMin = TMath::Min (pixMin,50.);
1355
1356     // Decrease pixel size and shift pixels to make them centered at 
1357     // the maximum one
1358     indx = (pixPtr->Size(0)>pixPtr->Size(1)) ? 0 : 1;
1359     Double_t width = 0, shift[2]={0};
1360     ix = 1;
1361     for (Int_t i=0; i<4; i++) xylim[i] = 999;
1362     Int_t nPix1 = nPix; nPix = 0;
1363     for (Int_t ipix=0; ipix<nPix1; ipix++) {
1364       pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(ipix);
1365       if (nPix >= npadOK) { // too many pixels already
1366         fPixArray->RemoveAt(ipix); 
1367         delete pixPtr; 
1368         continue;
1369       }
1370       if (pixPtr->Charge() < pixMin) { // low charge
1371         fPixArray->RemoveAt(ipix); 
1372         delete pixPtr; 
1373         continue;
1374       }
1375       for (Int_t i=0; i<2; i++) {
1376         if (!i) {
1377           pixPtr->SetCharge(10);
1378           pixPtr->SetSize(indx, pixPtr->Size(indx)/2);
1379           width = -pixPtr->Size(indx);
1380           pixPtr->Shift(indx, width);
1381           // Shift pixel position
1382           if (ix) {
1383             ix = 0;
1384             for (Int_t j=0; j<2; j++) {
1385               shift[j] = pixPtr->Coord(j) - xyCOG[j];
1386               shift[j] -= ((Int_t)(shift[j]/pixPtr->Size(j)/2))*pixPtr->Size(j)*2;
1387             }
1388             //cout << ipix << " " << i << " " << shift[0] << " " << shift[1] << endl;
1389           } // if (ix)
1390           pixPtr->Shift(0, -shift[0]);
1391           pixPtr->Shift(1, -shift[1]);
1392         } else {
1393           pixPtr = new AliMUONPixel(*pixPtr);
1394           pixPtr->Shift(indx, -2*width);
1395           fPixArray->Add((TObject*)pixPtr);
1396         } // else
1397         //pixPtr->Print();
1398         for (Int_t i=0; i<4; i++) 
1399           xylim[i] = TMath::Min (xylim[i], (i%2 ? -1 : 1)*pixPtr->Coord(i/2));
1400       } // for (Int_t i=0; i<2;
1401       nPix += 2;
1402     } // for (Int_t ipix=0;
1403
1404     fPixArray->Compress();
1405     nPix = fPixArray->GetEntriesFast();
1406
1407     // Remove excessive pixels
1408     if (nPix > npadOK) {
1409       for (Int_t ipix=npadOK; ipix<nPix; ipix++) { 
1410         pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(ipix);
1411         fPixArray->RemoveAt(ipix); 
1412         delete pixPtr;
1413       }
1414     } else {
1415       pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(0);
1416       // add pixels if the maximum is at the limit of pixel area
1417       // start from Y-direction
1418       Int_t j = 0;
1419       for (Int_t i=3; i>-1; i--) {
1420         if (nPix < npadOK && 
1421             TMath::Abs((i%2 ? -1 : 1)*xylim[i]-xyCOG[i/2]) < pixPtr->Size(i/2)) {
1422           pixPtr = new AliMUONPixel(*pixPtr);
1423           pixPtr->SetCoord(i/2, xyCOG[i/2]+(i%2 ? 2:-2)*pixPtr->Size(i/2));
1424           j = TMath::Even (i/2);
1425           pixPtr->SetCoord(j, xyCOG[j]);
1426           fPixArray->Add((TObject*)pixPtr);
1427           nPix++;
1428         }
1429       }
1430     } // else    
1431
1432     fPixArray->Compress();
1433     nPix = fPixArray->GetEntriesFast();
1434     delete [] coef; delete [] probi; coef = 0; probi = 0;
1435   } // while (1)
1436
1437   // remove pixels with low signal or low visibility
1438   // Cuts are empirical !!!
1439   Double_t thresh = TMath::Max (mlem->GetMaximum()/100.,1.);
1440   thresh = TMath::Min (thresh,50.);
1441   Double_t cmax = -1, charge = 0;
1442   for (Int_t i=0; i<nPix; i++) cmax = TMath::Max (cmax,probi[i]); 
1443   //cout << thresh << " " << cmax << " " << cmax*0.9 << endl;
1444   // Mark pixels which should be removed
1445   for (Int_t i=0; i<nPix; i++) {
1446     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
1447     charge = pixPtr->Charge();
1448     if (charge < thresh) pixPtr->SetCharge(-charge);
1449     //else if (cmax > 1.91) {
1450     //  if (probi[i] < 1.9) pixPtr->SetCharge(-charge);
1451     //}
1452     //AZ else if (probi[i] < cmax*0.9) pixPtr->SetCharge(-charge);
1453     else if (probi[i] < cmax*0.8) pixPtr->SetCharge(-charge);
1454     //cout << i << " " << pixPtr->Coord(0) << " " << pixPtr->Coord(1) << " " << charge << " " << probi[i] << endl;
1455   }
1456   // Move charge of removed pixels to their nearest neighbour (to keep total charge the same)
1457   Int_t near = 0;
1458   for (Int_t i=0; i<nPix; i++) {
1459     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
1460     charge = pixPtr->Charge();
1461     if (charge > 0) continue;
1462     near = FindNearest(pixPtr);
1463     pixPtr->SetCharge(0);
1464     probi[i] = 0; // make it "invisible"
1465     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(near);
1466     pixPtr->SetCharge(pixPtr->Charge() + (-charge));
1467   }
1468   Mlem(coef,probi,2);
1469   // Update histogram
1470   for (Int_t i=0; i<nPix; i++) {
1471     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
1472     ix = mlem->GetXaxis()->FindBin(pixPtr->Coord(0));
1473     iy = mlem->GetYaxis()->FindBin(pixPtr->Coord(1));
1474     mlem->SetBinContent(ix, iy, pixPtr->Charge());
1475   }
1476   if (fDraw) {
1477     ((TCanvas*)gROOT->FindObject("c2"))->cd();
1478     gPad->SetTheta(55);
1479     gPad->SetPhi(30);
1480     mlem->Draw("lego1Fb");
1481     gPad->Update();
1482   }
1483
1484   fxyMu[0][6] = fxyMu[1][6] = 9999;
1485   // Try to split into clusters
1486   Bool_t ok = kTRUE;
1487   if (mlem->GetSum() < 1) ok = kFALSE;
1488   else Split(mlem, coef);
1489   delete [] coef; delete [] probi; coef = 0; probi = 0;
1490   fPixArray->Delete(); 
1491   return ok;
1492 }
1493
1494 //_____________________________________________________________________________
1495 void AliMUONClusterFinderAZ::Mlem(Double_t *coef, Double_t *probi, Int_t nIter)
1496 {
1497   // Use MLEM to find pixel charges
1498   
1499   Int_t nPix = fPixArray->GetEntriesFast();
1500   Int_t npad = fnPads[0] + fnPads[1];
1501   Double_t *probi1 = new Double_t [nPix];
1502   Double_t probMax = 0;
1503   Int_t indx, indx1;
1504   AliMUONPixel *pixPtr;
1505
1506   for (Int_t ipix=0; ipix<nPix; ipix++) if (probi[ipix] > probMax) probMax = probi[ipix];
1507   for (Int_t iter=0; iter<nIter; iter++) {
1508     // Do iterations
1509     for (Int_t ipix=0; ipix<nPix; ipix++) {
1510       // Correct each pixel
1511       if (probi[ipix] < 0.01) continue; // skip "invisible" pixel
1512       Double_t sum = 0;
1513       //probi1[ipix] = probi[ipix];
1514       probi1[ipix] = probMax;
1515       for (Int_t j=0; j<npad; j++) {
1516         if (fPadIJ[1][j] < 0) continue; 
1517         Double_t sum1 = 0;
1518         indx1 = j*nPix;
1519         indx = indx1 + ipix;
1520         for (Int_t i=0; i<nPix; i++) {
1521           // Caculate expectation
1522           pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
1523           sum1 += pixPtr->Charge()*coef[indx1+i];
1524         } // for (Int_t i=0;
1525         //AZ if (fXyq[2][j] > fResponse->MaxAdc()-1 && sum1 > fResponse->MaxAdc()) { probi1[ipix] -= coef[indx]; continue; } // correct for pad charge overflows
1526         if (fXyq[2][j] > fResponse->Saturation()-1 && sum1 > fResponse->Saturation()) { probi1[ipix] -= coef[indx]; continue; } // correct for pad charge overflows
1527         //cout << sum1 << " " << fXyq[2][j] << " " << coef[j*nPix+ipix] << endl;
1528         if (coef[indx] > 1.e-6) sum += fXyq[2][j]*coef[indx]/sum1;
1529       } // for (Int_t j=0;
1530       pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(ipix);
1531       if (probi1[ipix] > 1.e-6) pixPtr->SetCharge(pixPtr->Charge()*sum/probi1[ipix]);
1532     } // for (Int_t ipix=0;
1533   } // for (Int_t iter=0;
1534   delete [] probi1;
1535   return;
1536 }
1537
1538 //_____________________________________________________________________________
1539 void AliMUONClusterFinderAZ::FindCOG(TH2D *mlem, Double_t *xyc)
1540 {
1541   // Calculate position of the center-of-gravity around the maximum pixel
1542
1543   Int_t ixmax, iymax, ix, nsumx=0, nsumy=0, nsum=0;
1544   Int_t i1 = -9, j1 = -9;
1545   mlem->GetMaximumBin(ixmax,iymax,ix);
1546   Int_t nx = mlem->GetNbinsX();
1547   Int_t ny = mlem->GetNbinsY();
1548   Double_t thresh = mlem->GetMaximum()/10;
1549   Double_t x, y, cont, xq=0, yq=0, qq=0;
1550
1551   for (Int_t i=TMath::Max(1,iymax-1); i<=TMath::Min(ny,iymax+1); i++) {
1552   //for (Int_t i=TMath::Max(1,iymax-9); i<=TMath::Min(ny,iymax+9); i++) {
1553     y = mlem->GetYaxis()->GetBinCenter(i);
1554     for (Int_t j=TMath::Max(1,ixmax-1); j<=TMath::Min(nx,ixmax+1); j++) {
1555     //for (Int_t j=TMath::Max(1,ixmax-9); j<=TMath::Min(nx,ixmax+9); j++) {
1556       cont = mlem->GetCellContent(j,i);
1557       if (cont < thresh) continue;
1558       if (i != i1) {i1 = i; nsumy++;}
1559       if (j != j1) {j1 = j; nsumx++;}
1560       x = mlem->GetXaxis()->GetBinCenter(j);
1561       xq += x*cont;
1562       yq += y*cont;
1563       qq += cont;
1564       nsum++;
1565     }
1566   }
1567
1568   Double_t cmax = 0;
1569   Int_t i2 = 0, j2 = 0;
1570   x = y = 0;
1571   if (nsumy == 1) {
1572     // one bin in Y - add one more (with the largest signal)
1573     for (Int_t i=TMath::Max(1,iymax-1); i<=TMath::Min(ny,iymax+1); i++) {
1574       if (i == iymax) continue;
1575       for (Int_t j=TMath::Max(1,ixmax-1); j<=TMath::Min(nx,ixmax+1); j++) {
1576         cont = mlem->GetCellContent(j,i);
1577         if (cont > cmax) {
1578           cmax = cont;
1579           x = mlem->GetXaxis()->GetBinCenter(j);
1580           y = mlem->GetYaxis()->GetBinCenter(i);
1581           i2 = i;
1582           j2 = j;
1583         }
1584       }
1585     }
1586     xq += x*cmax;
1587     yq += y*cmax;
1588     qq += cmax;
1589     if (i2 != i1) nsumy++;
1590     if (j2 != j1) nsumx++;
1591     nsum++;
1592   } // if (nsumy == 1)
1593
1594   if (nsumx == 1) {
1595     // one bin in X - add one more (with the largest signal)
1596     cmax = x = y = 0;
1597     for (Int_t j=TMath::Max(1,ixmax-1); j<=TMath::Min(nx,ixmax+1); j++) {
1598       if (j == ixmax) continue;
1599       for (Int_t i=TMath::Max(1,iymax-1); i<=TMath::Min(ny,iymax+1); i++) {
1600         cont = mlem->GetCellContent(j,i);
1601         if (cont > cmax) {
1602           cmax = cont;
1603           x = mlem->GetXaxis()->GetBinCenter(j);
1604           y = mlem->GetYaxis()->GetBinCenter(i);
1605           i2 = i;
1606           j2 = j;
1607         }
1608       }
1609     }
1610     xq += x*cmax;
1611     yq += y*cmax;
1612     qq += cmax;
1613     if (i2 != i1) nsumy++;
1614     if (j2 != j1) nsumx++;
1615     nsum++;
1616   } // if (nsumx == 1)
1617
1618   xyc[0] = xq/qq; xyc[1] = yq/qq;
1619   if (fDebug) cout << xyc[0] << " " << xyc[1] << " " << qq << " " << nsum << " " << nsumx << " " << nsumy << endl;
1620   return;
1621 }
1622
1623 //_____________________________________________________________________________
1624 Int_t AliMUONClusterFinderAZ::FindNearest(AliMUONPixel *pixPtr0)
1625 {
1626   // Find the pixel nearest to the given one
1627   // (algorithm may be not very efficient)
1628
1629   Int_t nPix = fPixArray->GetEntriesFast(), imin = 0;
1630   Double_t rmin = 99999, dx = 0, dy = 0, r = 0;
1631   Double_t xc = pixPtr0->Coord(0), yc = pixPtr0->Coord(1);
1632   AliMUONPixel *pixPtr;
1633
1634   for (Int_t i=0; i<nPix; i++) {
1635     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
1636     if (pixPtr->Charge() < 0.5) continue;
1637     dx = (xc - pixPtr->Coord(0)) / pixPtr->Size(0);
1638     dy = (yc - pixPtr->Coord(1)) / pixPtr->Size(1);
1639     r = dx *dx + dy * dy;
1640     if (r < rmin) { rmin = r; imin = i; }
1641   }
1642   return imin;
1643 }
1644
1645 //_____________________________________________________________________________
1646 void AliMUONClusterFinderAZ::Split(TH2D *mlem, Double_t *coef)
1647 {
1648   // The main steering function to work with clusters of pixels in anode
1649   // plane (find clusters, decouple them from each other, merge them (if
1650   // necessary), pick up coupled pads, call the fitting function)
1651   
1652   Int_t nx = mlem->GetNbinsX();
1653   Int_t ny = mlem->GetNbinsY();
1654   Int_t nPix = fPixArray->GetEntriesFast();
1655
1656   Bool_t *used = new Bool_t[ny*nx];
1657   Double_t cont;
1658   Int_t nclust = 0, indx, indx1;
1659
1660   for (Int_t i=0; i<ny*nx; i++) used[i] = kFALSE; 
1661
1662   TObjArray *clusters[200]={0};
1663   TObjArray *pix;
1664
1665   // Find clusters of histogram bins (easier to work in 2-D space)
1666   for (Int_t i=1; i<=ny; i++) {
1667     for (Int_t j=1; j<=nx; j++) {
1668       indx = (i-1)*nx + j - 1;
1669       if (used[indx]) continue;
1670       cont = mlem->GetCellContent(j,i);
1671       if (cont < 0.5) continue;
1672       pix = new TObjArray(20);
1673       used[indx] = 1;
1674       pix->Add(BinToPix(mlem,j,i));
1675       AddBin(mlem, i, j, 0, used, pix); // recursive call
1676       if (nclust >= 200) AliFatal(" Too many clusters !!!");
1677       clusters[nclust++] = pix;
1678     } // for (Int_t j=1; j<=nx; j++) {
1679   } // for (Int_t i=1; i<=ny;
1680   if (fDebug) cout << nclust << endl;
1681   delete [] used; used = 0;
1682   
1683   // Compute couplings between clusters and clusters to pads
1684   Int_t npad = fnPads[0] + fnPads[1];
1685
1686   // Write out some information for algorithm development
1687   Int_t cath=0, npadx[2]={0}, npady[2]={0};
1688   Double_t xlow[2]={9999,9999}, xhig[2]={-9999,-9999};
1689   Double_t ylow[2]={9999,9999}, yhig[2]={-9999,-9999};
1690   for (Int_t j=0; j<npad; j++) {
1691     if (fXyq[3][j] < 0) continue; // exclude virtual pads
1692     cath = fPadIJ[0][j];
1693     if (fXyq[0][j] < xlow[cath]-0.001) { 
1694       if (fXyq[0][j]+fXyq[3][j] <= xlow[cath] && npadx[cath]) npadx[cath]++;
1695       xlow[cath] = fXyq[0][j];
1696     }
1697     if (fXyq[0][j] > xhig[cath]+0.001) { 
1698       if (fXyq[0][j]-fXyq[3][j] >= xhig[cath]) npadx[cath]++; 
1699       xhig[cath] = fXyq[0][j]; 
1700     }
1701     if (fXyq[1][j] < ylow[cath]-0.001) { 
1702       if (fXyq[1][j]+fXyq[4][j] <= ylow[cath] && npady[cath]) npady[cath]++;
1703       ylow[cath] = fXyq[1][j];
1704     }
1705     if (fXyq[1][j] > yhig[cath]+0.001) { 
1706       if (fXyq[1][j]-fXyq[4][j] >= yhig[cath]) npady[cath]++;
1707       yhig[cath] = fXyq[1][j]; 
1708     }
1709   }
1710   //if (lun1) fprintf(lun1," %4d %2d %3d %3d %3d %3d \n",gAlice->GetHeader()->GetEvent(),AliMUONClusterInput::Instance()->Chamber(), npadx[0], npadx[1], npady[0], npady[1]);
1711
1712   // Exclude pads with overflows
1713   for (Int_t j=0; j<npad; j++) {
1714     //AZ if (fXyq[2][j] > fResponse->MaxAdc()-1) fPadIJ[1][j] = -5;
1715     if (fXyq[2][j] > fResponse->Saturation()-1) fPadIJ[1][j] = -5;
1716     else fPadIJ[1][j] = 0;
1717   }
1718
1719   // Compute couplings of clusters to pads
1720   TMatrixD *aijclupad = new TMatrixD(nclust,npad);
1721   *aijclupad = 0;
1722   Int_t npxclu;
1723   for (Int_t iclust=0; iclust<nclust; iclust++) {
1724     pix = clusters[iclust];
1725     npxclu = pix->GetEntriesFast();
1726     for (Int_t i=0; i<npxclu; i++) {
1727       indx = fPixArray->IndexOf(pix->UncheckedAt(i));
1728       for (Int_t j=0; j<npad; j++) {
1729         if (fPadIJ[1][j] < 0 && fPadIJ[1][j] != -5) continue;
1730         if (coef[j*nPix+indx] < fgkCouplMin) continue;
1731         (*aijclupad)(iclust,j) += coef[j*nPix+indx];
1732       }
1733     }
1734   }
1735   // Compute couplings between clusters
1736   TMatrixD *aijcluclu = new TMatrixD(nclust,nclust);
1737   *aijcluclu = 0;
1738   for (Int_t iclust=0; iclust<nclust; iclust++) {
1739     for (Int_t j=0; j<npad; j++) {
1740       // Exclude overflows
1741       if (fPadIJ[1][j] < 0) continue;
1742       if ((*aijclupad)(iclust,j) < fgkCouplMin) continue;
1743       for (Int_t iclust1=iclust+1; iclust1<nclust; iclust1++) {
1744         if ((*aijclupad)(iclust1,j) < fgkCouplMin) continue;
1745         (*aijcluclu)(iclust,iclust1) += 
1746           TMath::Sqrt ((*aijclupad)(iclust,j)*(*aijclupad)(iclust1,j));
1747       }
1748     }
1749   }
1750   for (Int_t iclust=0; iclust<nclust; iclust++) {
1751     for (Int_t iclust1=iclust+1; iclust1<nclust; iclust1++) {
1752       (*aijcluclu)(iclust1,iclust) = (*aijcluclu)(iclust,iclust1);
1753     }
1754   }
1755
1756   if (fDebug && nclust > 1) aijcluclu->Print();
1757
1758   // Find groups of coupled clusters
1759   used = new Bool_t[nclust];
1760   for (Int_t i=0; i<nclust; i++) used[i] = kFALSE;
1761   Int_t *clustNumb = new Int_t[nclust];
1762   Int_t nCoupled, nForFit, minGroup[3], clustFit[3], nfit = 0;
1763   Double_t parOk[8];
1764
1765   for (Int_t igroup=0; igroup<nclust; igroup++) {
1766     if (used[igroup]) continue;
1767     used[igroup] = kTRUE;
1768     clustNumb[0] = igroup;
1769     nCoupled = 1;
1770     // Find group of coupled clusters
1771     AddCluster(igroup, nclust, aijcluclu, used, clustNumb, nCoupled); // recursive
1772     if (fDebug) {
1773       cout << " nCoupled: " << nCoupled << endl;
1774       for (Int_t i=0; i<nCoupled; i++) cout << clustNumb[i] << " "; cout << endl; 
1775     }
1776     fnCoupled = nCoupled;
1777
1778     while (nCoupled > 0) {
1779
1780       if (nCoupled < 4) {
1781         nForFit = nCoupled;
1782         for (Int_t i=0; i<nCoupled; i++) clustFit[i] = clustNumb[i];
1783       } else {
1784         // Too many coupled clusters to fit - try to decouple them
1785         // Find the lowest coupling of 1, 2, min(3,nLinks/2) pixels with 
1786         // all the others in the group 
1787         for (Int_t j=0; j<3; j++) minGroup[j] = -1;
1788         Double_t coupl = MinGroupCoupl(nCoupled, clustNumb, aijcluclu, minGroup);
1789
1790         // Flag clusters for fit
1791         nForFit = 0;
1792         while (minGroup[nForFit] >= 0 && nForFit < 3) {
1793           if (fDebug) cout << clustNumb[minGroup[nForFit]] << " ";
1794           clustFit[nForFit] = clustNumb[minGroup[nForFit]];
1795           clustNumb[minGroup[nForFit]] -= 999;
1796           nForFit++;
1797         }
1798         if (fDebug) cout << nForFit << " " << coupl << endl;
1799       } // else
1800
1801       // Select pads for fit. 
1802       if (SelectPad(nCoupled, nForFit, clustNumb, clustFit, aijclupad) < 3 && nCoupled > 1) {
1803         // Deselect pads
1804         for (Int_t j=0; j<npad; j++) {
1805           if (TMath::Abs(fPadIJ[1][j]) == 1) fPadIJ[1][j] = 0;
1806           if (TMath::Abs(fPadIJ[1][j]) == -9) fPadIJ[1][j] = -5;
1807         }
1808         // Merge the failed cluster candidates (with too few pads to fit) with 
1809         // the one with the strongest coupling
1810         Merge(nForFit, nCoupled, clustNumb, clustFit, clusters, aijcluclu, aijclupad);
1811       } else {
1812         // Do the fit
1813         nfit = Fit(nForFit, clustFit, clusters, parOk);
1814       }
1815
1816       // Subtract the fitted charges from pads with strong coupling and/or
1817       // return pads for further use
1818       UpdatePads(nfit, parOk);
1819
1820       // Mark used pads
1821       for (Int_t j=0; j<npad; j++) {
1822         if (fPadIJ[1][j] == 1) fPadIJ[1][j] = -1;
1823         if (fPadIJ[1][j] == -9) fPadIJ[1][j] = -5;
1824       }
1825
1826       // Sort the clusters (move to the right the used ones)
1827       Int_t beg = 0, end = nCoupled - 1;
1828       while (beg < end) {
1829         if (clustNumb[beg] >= 0) { beg++; continue; }
1830         for (Int_t j=end; j>beg; j--) {
1831           if (clustNumb[j] < 0) continue;
1832           end = j - 1;
1833           indx = clustNumb[beg];
1834           clustNumb[beg] = clustNumb[j];
1835           clustNumb[j] = indx;
1836           break;
1837         }
1838         beg++;
1839       }
1840
1841       nCoupled -= nForFit;
1842       if (nCoupled > 3) {
1843         // Remove couplings of used clusters
1844         for (Int_t iclust=nCoupled; iclust<nCoupled+nForFit; iclust++) {
1845           indx = clustNumb[iclust] + 999;
1846           for (Int_t iclust1=0; iclust1<nCoupled; iclust1++) {
1847             indx1 = clustNumb[iclust1];
1848             (*aijcluclu)(indx,indx1) = (*aijcluclu)(indx1,indx) = 0;
1849           }
1850         }
1851
1852         // Update the remaining clusters couplings (exclude couplings from 
1853         // the used pads)
1854         for (Int_t j=0; j<npad; j++) {
1855           if (fPadIJ[1][j] != -1) continue;
1856           for (Int_t iclust=0; iclust<nCoupled; iclust++) {
1857             indx = clustNumb[iclust];
1858             if ((*aijclupad)(indx,j) < fgkCouplMin) continue;
1859             for (Int_t iclust1=iclust+1; iclust1<nCoupled; iclust1++) {
1860               indx1 = clustNumb[iclust1];
1861               if ((*aijclupad)(indx1,j) < fgkCouplMin) continue;
1862               // Check this
1863               (*aijcluclu)(indx,indx1) -= 
1864                 TMath::Sqrt ((*aijclupad)(indx,j)*(*aijclupad)(indx1,j));
1865               (*aijcluclu)(indx1,indx) = (*aijcluclu)(indx,indx1);
1866             }
1867           }
1868           fPadIJ[1][j] = -8;
1869         } // for (Int_t j=0; j<npad;
1870       } // if (nCoupled > 3)
1871     } // while (nCoupled > 0)
1872   } // for (Int_t igroup=0; igroup<nclust;
1873
1874   //delete aij_clu; aij_clu = 0; delete aijclupad; aijclupad = 0;
1875   aijcluclu->Delete(); aijclupad->Delete();
1876   for (Int_t iclust=0; iclust<nclust; iclust++) {
1877     pix = clusters[iclust]; 
1878     pix->Clear();
1879     delete pix; pix = 0;
1880   }
1881   delete [] clustNumb; clustNumb = 0; delete [] used; used = 0;
1882 }
1883
1884 //_____________________________________________________________________________
1885 void AliMUONClusterFinderAZ::AddBin(TH2D *mlem, Int_t ic, Int_t jc, Int_t mode, Bool_t *used, TObjArray *pix)
1886 {
1887   // Add a bin to the cluster
1888
1889   Int_t nx = mlem->GetNbinsX();
1890   Int_t ny = mlem->GetNbinsY();
1891   Double_t cont1, cont = mlem->GetCellContent(jc,ic);
1892   AliMUONPixel *pixPtr = 0;
1893
1894   for (Int_t i=TMath::Max(ic-1,1); i<=TMath::Min(ic+1,ny); i++) {
1895     for (Int_t j=TMath::Max(jc-1,1); j<=TMath::Min(jc+1,nx); j++) {
1896       if (i != ic && j != jc) continue;
1897       if (used[(i-1)*nx+j-1]) continue;
1898       cont1 = mlem->GetCellContent(j,i);
1899       if (mode && cont1 > cont) continue;
1900       used[(i-1)*nx+j-1] = kTRUE;
1901       if (cont1 < 0.5) continue;
1902       if (pix) pix->Add(BinToPix(mlem,j,i)); 
1903       else {
1904         pixPtr = new AliMUONPixel (mlem->GetXaxis()->GetBinCenter(j), 
1905                                    mlem->GetYaxis()->GetBinCenter(i), 0, 0, cont1);
1906         fPixArray->Add((TObject*)pixPtr);
1907       }
1908       AddBin(mlem, i, j, mode, used, pix); // recursive call
1909     }
1910   }
1911 }
1912
1913 //_____________________________________________________________________________
1914 TObject* AliMUONClusterFinderAZ::BinToPix(TH2D *mlem, Int_t jc, Int_t ic)
1915 {
1916   // Translate histogram bin to pixel 
1917   
1918   Double_t yc = mlem->GetYaxis()->GetBinCenter(ic);
1919   Double_t xc = mlem->GetXaxis()->GetBinCenter(jc);
1920   
1921   Int_t nPix = fPixArray->GetEntriesFast();
1922   AliMUONPixel *pixPtr;
1923
1924   // Compare pixel and bin positions
1925   for (Int_t i=0; i<nPix; i++) {
1926     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
1927     if (pixPtr->Charge() < 0.5) continue;
1928     if (TMath::Abs(pixPtr->Coord(0)-xc)<1.e-4 && TMath::Abs(pixPtr->Coord(1)-yc)<1.e-4) return (TObject*) pixPtr;
1929   }
1930   AliWarning(Form(" Something wrong ??? %f %f ", xc, yc));
1931   return NULL;
1932 }
1933
1934 //_____________________________________________________________________________
1935 void AliMUONClusterFinderAZ::AddCluster(Int_t ic, Int_t nclust, TMatrixD *aijcluclu, Bool_t *used, Int_t *clustNumb, Int_t &nCoupled)
1936 {
1937   // Add a cluster to the group of coupled clusters
1938
1939   for (Int_t i=0; i<nclust; i++) {
1940     if (used[i]) continue;
1941     if ((*aijcluclu)(i,ic) < fgkCouplMin) continue;
1942     used[i] = kTRUE;
1943     clustNumb[nCoupled++] = i;
1944     AddCluster(i, nclust, aijcluclu, used, clustNumb, nCoupled);
1945   }
1946 }
1947
1948 //_____________________________________________________________________________
1949 Double_t AliMUONClusterFinderAZ::MinGroupCoupl(Int_t nCoupled, Int_t *clustNumb, TMatrixD *aijcluclu, Int_t *minGroup)
1950 {
1951   // Find group of clusters with minimum coupling to all the others
1952
1953   Int_t i123max = TMath::Min(3,nCoupled/2); 
1954   Int_t indx, indx1, indx2, indx3, nTot = 0;
1955   Double_t *coupl1 = 0, *coupl2 = 0, *coupl3 = 0;
1956
1957   for (Int_t i123=1; i123<=i123max; i123++) {
1958
1959     if (i123 == 1) {
1960       coupl1 = new Double_t [nCoupled];
1961       for (Int_t i=0; i<nCoupled; i++) coupl1[i] = 0;
1962     }
1963     else if (i123 == 2) {
1964       nTot = nCoupled*nCoupled;
1965       coupl2 = new Double_t [nTot];
1966       for (Int_t i=0; i<nTot; i++) coupl2[i] = 9999;
1967     } else {
1968       nTot = nTot*nCoupled;
1969       coupl3 = new Double_t [nTot];
1970       for (Int_t i=0; i<nTot; i++) coupl3[i] = 9999;
1971     } // else
1972
1973     for (Int_t i=0; i<nCoupled; i++) {
1974       indx1 = clustNumb[i];
1975       for (Int_t j=i+1; j<nCoupled; j++) {
1976         indx2 = clustNumb[j];
1977         if (i123 == 1) {
1978           coupl1[i] += (*aijcluclu)(indx1,indx2);
1979           coupl1[j] += (*aijcluclu)(indx1,indx2);
1980         } 
1981         else if (i123 == 2) {
1982           indx = i*nCoupled + j;
1983           coupl2[indx] = coupl1[i] + coupl1[j];
1984           coupl2[indx] -= 2 * ((*aijcluclu)(indx1,indx2));
1985         } else {
1986           for (Int_t k=j+1; k<nCoupled; k++) {
1987             indx3 = clustNumb[k];
1988             indx = i*nCoupled*nCoupled + j*nCoupled + k;
1989             coupl3[indx] = coupl2[i*nCoupled+j] + coupl1[k];
1990             coupl3[indx] -= 2 * ((*aijcluclu)(indx1,indx3)+(*aijcluclu)(indx2,indx3));
1991           }
1992         } // else
1993       } // for (Int_t j=i+1;
1994     } // for (Int_t i=0;
1995   } // for (Int_t i123=1;
1996
1997   // Find minimum coupling
1998   Double_t couplMin = 9999;
1999   Int_t locMin = 0;
2000
2001   for (Int_t i123=1; i123<=i123max; i123++) {
2002     if (i123 == 1) {
2003       locMin = TMath::LocMin(nCoupled, coupl1);
2004       couplMin = coupl1[locMin];
2005       minGroup[0] = locMin;
2006       delete [] coupl1; coupl1 = 0;
2007     } 
2008     else if (i123 == 2) {
2009       locMin = TMath::LocMin(nCoupled*nCoupled, coupl2);
2010       if (coupl2[locMin] < couplMin) {
2011         couplMin = coupl2[locMin];
2012         minGroup[0] = locMin/nCoupled;
2013         minGroup[1] = locMin%nCoupled;
2014       }
2015       delete [] coupl2; coupl2 = 0;
2016     } else {
2017       locMin = TMath::LocMin(nTot, coupl3);
2018       if (coupl3[locMin] < couplMin) {
2019         couplMin = coupl3[locMin];
2020         minGroup[0] = locMin/nCoupled/nCoupled;
2021         minGroup[1] = locMin%(nCoupled*nCoupled)/nCoupled;
2022         minGroup[2] = locMin%nCoupled;
2023       }
2024       delete [] coupl3; coupl3 = 0;
2025     } // else
2026   } // for (Int_t i123=1;
2027   return couplMin;
2028 }
2029
2030 //_____________________________________________________________________________
2031 Int_t AliMUONClusterFinderAZ::SelectPad(Int_t nCoupled, Int_t nForFit, Int_t *clustNumb, Int_t *clustFit, TMatrixD *aijclupad)
2032 {
2033   // Select pads for fit. If too many coupled clusters, find pads giving 
2034   // the strongest coupling with the rest of clusters and exclude them from the fit.
2035
2036   Int_t npad = fnPads[0] + fnPads[1];
2037   Double_t *padpix = 0;
2038
2039   if (nCoupled > 3) {
2040     padpix = new Double_t[npad];
2041     for (Int_t i=0; i<npad; i++) padpix[i] = 0; 
2042   }
2043
2044   Int_t nOK = 0, indx, indx1;
2045   for (Int_t iclust=0; iclust<nForFit; iclust++) {
2046     indx = clustFit[iclust];
2047     for (Int_t j=0; j<npad; j++) {
2048       if ((*aijclupad)(indx,j) < fgkCouplMin) continue;
2049       if (fPadIJ[1][j] == -5) fPadIJ[1][j] = -9; // flag overflow
2050       if (fPadIJ[1][j] < 0) continue; // exclude overflows and used pads
2051       if (!fPadIJ[1][j]) { fPadIJ[1][j] = 1; nOK++; } // pad to be used in fit
2052       if (nCoupled > 3) {
2053         // Check other clusters
2054         for (Int_t iclust1=0; iclust1<nCoupled; iclust1++) {
2055           indx1 = clustNumb[iclust1];
2056           if (indx1 < 0) continue;
2057           if ((*aijclupad)(indx1,j) < fgkCouplMin) continue;
2058           padpix[j] += (*aijclupad)(indx1,j);
2059         }
2060       } // if (nCoupled > 3)
2061     } // for (Int_t j=0; j<npad;
2062   } // for (Int_t iclust=0; iclust<nForFit
2063   if (nCoupled < 4) return nOK;
2064
2065   Double_t aaa = 0;
2066   for (Int_t j=0; j<npad; j++) {
2067     if (padpix[j] < fgkCouplMin) continue;
2068     if (fDebug) cout << j << " " << padpix[j] << " " << fXyq[0][j] << " " << fXyq[1][j] << endl;
2069     aaa += padpix[j];
2070     fPadIJ[1][j] = -1; // exclude pads with strong coupling to the other clusters
2071     nOK--;
2072   }
2073   delete [] padpix; padpix = 0;
2074   return nOK;
2075 }
2076   
2077 //_____________________________________________________________________________
2078 void AliMUONClusterFinderAZ::Merge(Int_t nForFit, Int_t nCoupled, Int_t *clustNumb, Int_t *clustFit, TObjArray **clusters, TMatrixD *aijcluclu, TMatrixD *aijclupad)
2079 {
2080   // Merge the group of clusters with the one having the strongest coupling with them
2081
2082   Int_t indx, indx1, npxclu, npxclu1, imax=0;
2083   TObjArray *pix, *pix1;
2084   Double_t couplMax;
2085
2086   for (Int_t icl=0; icl<nForFit; icl++) {
2087     indx = clustFit[icl];
2088     pix = clusters[indx];
2089     npxclu = pix->GetEntriesFast();
2090     couplMax = -1;
2091     for (Int_t icl1=0; icl1<nCoupled; icl1++) {
2092       indx1 = clustNumb[icl1];
2093       if (indx1 < 0) continue;
2094       if ((*aijcluclu)(indx,indx1) > couplMax) {
2095         couplMax = (*aijcluclu)(indx,indx1);
2096         imax = indx1;
2097       }
2098     } // for (Int_t icl1=0;
2099     /*if (couplMax < fgkCouplMin) {
2100       cout << " Oops " << couplMax << endl;
2101       aijcluclu->Print();
2102       cout << icl << " " << indx << " " << npxclu << " " << nLinks << endl;
2103       ::exit(0);
2104       }*/
2105     // Add to it
2106     pix1 = clusters[imax];
2107     npxclu1 = pix1->GetEntriesFast();
2108     // Add pixels 
2109     for (Int_t i=0; i<npxclu; i++) { pix1->Add(pix->UncheckedAt(i)); pix->RemoveAt(i); }
2110     if (fDebug) cout << " New number of pixels: " << npxclu1 << " " << pix1->GetEntriesFast() << endl;
2111     //Add cluster-to-cluster couplings
2112     //aijcluclu->Print();
2113     for (Int_t icl1=0; icl1<nCoupled; icl1++) {
2114       indx1 = clustNumb[icl1];
2115       if (indx1 < 0 || indx1 == imax) continue;
2116       (*aijcluclu)(indx1,imax) += (*aijcluclu)(indx,indx1);
2117       (*aijcluclu)(imax,indx1) = (*aijcluclu)(indx1,imax);
2118     }
2119     (*aijcluclu)(indx,imax) = (*aijcluclu)(imax,indx) = 0;
2120     //aijcluclu->Print();
2121     //Add cluster-to-pad couplings
2122     for (Int_t j=0; j<fnPads[0]+fnPads[1]; j++) {
2123       if (fPadIJ[1][j] < 0 && fPadIJ[1][j] != -5) continue; // exclude used pads
2124       (*aijclupad)(imax,j) += (*aijclupad)(indx,j);
2125       (*aijclupad)(indx,j) = 0;
2126     }
2127   } // for (Int_t icl=0; icl<nForFit;
2128 }
2129
2130 //_____________________________________________________________________________
2131 Int_t AliMUONClusterFinderAZ::Fit(Int_t nfit, Int_t *clustFit, TObjArray **clusters, Double_t *parOk)
2132 {
2133   // Find selected clusters to selected pad charges
2134   
2135   TH2D *mlem = (TH2D*) gROOT->FindObject("mlem");
2136   //Int_t nx = mlem->GetNbinsX();
2137   //Int_t ny = mlem->GetNbinsY();
2138   Double_t xmin = mlem->GetXaxis()->GetXmin() - mlem->GetXaxis()->GetBinWidth(1);
2139   Double_t xmax = mlem->GetXaxis()->GetXmax() + mlem->GetXaxis()->GetBinWidth(1);
2140   Double_t ymin = mlem->GetYaxis()->GetXmin() - mlem->GetYaxis()->GetBinWidth(1);
2141   Double_t ymax = mlem->GetYaxis()->GetXmax() + mlem->GetYaxis()->GetBinWidth(1);
2142   //Double_t qmin = 0, qmax = 1;
2143   Double_t step[3]={0.01,0.002,0.02}, xPad = 0, yPad = 99999;
2144   Double_t qPad[2] = {0}, xyqPad[2] = {0};
2145
2146   // Number of pads to use and number of virtual pads
2147   Int_t npads = 0, nVirtual = 0;
2148   for (Int_t i=0; i<fnPads[0]+fnPads[1]; i++) {
2149     if (fPadIJ[1][i] == -9 || fPadIJ[1][i] == 1) {
2150       if (fPadIJ[0][i]) xyqPad[1] += fXyq[0][i] * fXyq[2][i];
2151       else xyqPad[0] += fXyq[1][i] * fXyq[2][i];
2152       qPad[fPadIJ[0][i]] += fXyq[2][i];
2153     }
2154     if (fXyq[3][i] < 0) nVirtual++;
2155     if (fPadIJ[1][i] != 1) continue;
2156     if (fXyq[3][i] > 0) npads++;
2157     if (yPad > 9999) { xPad = fXyq[0][i]; yPad = fXyq[1][i]; }
2158     //if (fPadIJ[0][i]) xPad = fXyq[0][i];
2159   }
2160   if (fDebug) {
2161     for (Int_t i=0; i<nfit; i++) {cout << i+1 << " " << clustFit[i] << " ";}
2162     cout << nfit << endl;
2163     cout << " Number of pads to fit: " << npads << endl;
2164   }
2165   fNpar = 0;
2166   fQtot = 0;
2167   if (npads < 2) return 0; 
2168
2169   Int_t digit = 0, nfit0 = nfit;
2170   AliMUONDigit *mdig = 0;
2171   Int_t tracks[3] = {-1, -1, -1};
2172   for (Int_t cath=0; cath<2; cath++) {  
2173     for (Int_t i=0; i<fnPads[0]+fnPads[1]; i++) {
2174       if (fPadIJ[0][i] != cath) continue;
2175       if (fPadIJ[1][i] != 1) continue;
2176       if (fXyq[3][i] < 0) continue; // exclude virtual pads
2177       digit = TMath::Nint (fXyq[5][i]);
2178       if (digit >= 0) mdig = fInput->Digit(cath,digit);
2179       else mdig = fInput->Digit(TMath::Even(cath),-digit-1);
2180       //if (!mdig) mdig = fInput->Digit(TMath::Even(cath),digit);
2181       if (!mdig) continue; // protection for cluster display
2182       if (mdig->Hit() >= 0) {
2183         if (tracks[0] < 0) {
2184           tracks[0] = mdig->Hit();
2185           tracks[1] = mdig->Track(0);
2186         } else if (mdig->Track(0) < tracks[1]) {
2187           tracks[0] = mdig->Hit();
2188           tracks[1] = mdig->Track(0);
2189         }
2190       }
2191       //AZif (mdig->Track(1)) {
2192       if (mdig->Track(1) >= 0 && mdig->Track(1) != tracks[1]) {
2193         if (tracks[2] < 0) tracks[2] = mdig->Track(1);
2194         else tracks[2] = TMath::Min (tracks[2], mdig->Track(1));
2195       }
2196       //if (!mdig) break;
2197       //cout << mdig->Hit() << " " << mdig->Track(0) << " " << mdig->Track(1) <<endl;
2198     } // for (Int_t i=0;
2199   } // for (Int_t cath=0;
2200   //cout << tracks[0] << " " << tracks[1] << " " << tracks[2] <<endl;
2201   
2202   // Get number of pads in X and Y 
2203   Int_t nInX = 0, nInY;
2204   PadsInXandY(nInX, nInY);
2205
2206   // Take cluster maxima as fitting seeds
2207   TObjArray *pix;
2208   AliMUONPixel *pixPtr;
2209   Int_t npxclu;
2210   Double_t cont, cmax = 0, xseed = 0, yseed = 0, errOk[8], qq = 0;
2211   Double_t xyseed[3][2], qseed[3], xy_Cand[3][2] = {{0},{0}}, sig_Cand[3][2] = {{0},{0}};
2212
2213   for (Int_t ifit=1; ifit<=nfit; ifit++) {
2214     cmax = 0;
2215     pix = clusters[clustFit[ifit-1]];
2216     npxclu = pix->GetEntriesFast();
2217     //qq = 0;
2218     for (Int_t clu=0; clu<npxclu; clu++) {
2219       pixPtr = (AliMUONPixel*) pix->UncheckedAt(clu);
2220       cont = pixPtr->Charge();
2221       fQtot += cont;
2222       if (cont > cmax) { 
2223         cmax = cont; 
2224         xseed = pixPtr->Coord(0);
2225         yseed = pixPtr->Coord(1);
2226       }
2227       qq += cont;
2228       /*
2229       xy_Cand[ifit-1][0] += pixPtr->Coord(0) * cont;
2230       xy_Cand[ifit-1][1] += pixPtr->Coord(1) * cont;
2231       sig_Cand[ifit-1][0] += pixPtr->Coord(0) * pixPtr->Coord(0) * cont;
2232       sig_Cand[ifit-1][1] += pixPtr->Coord(1) * pixPtr->Coord(1) * cont;
2233       */
2234       xy_Cand[0][0] += pixPtr->Coord(0) * cont;
2235       xy_Cand[0][1] += pixPtr->Coord(1) * cont;
2236       sig_Cand[0][0] += pixPtr->Coord(0) * pixPtr->Coord(0) * cont;
2237       sig_Cand[0][1] += pixPtr->Coord(1) * pixPtr->Coord(1) * cont;
2238     }
2239     xyseed[ifit-1][0] = xseed;
2240     xyseed[ifit-1][1] = yseed;
2241     qseed[ifit-1] = cmax;
2242     /*
2243     xy_Cand[ifit-1][0] /= qq; // <x>
2244     xy_Cand[ifit-1][1] /= qq; // <y>
2245     sig_Cand[ifit-1][0] = sig_Cand[ifit-1][0]/qq - xy_Cand[ifit-1][0]*xy_Cand[ifit-1][0]; // <x^2> - <x>^2
2246     sig_Cand[ifit-1][0] = sig_Cand[ifit-1][0] > 0 ? TMath::Sqrt (sig_Cand[ifit-1][0]) : 0;
2247     sig_Cand[ifit-1][1] = sig_Cand[ifit-1][1]/qq - xy_Cand[ifit-1][1]*xy_Cand[ifit-1][1]; // <y^2> - <y>^2
2248     sig_Cand[ifit-1][1] = sig_Cand[ifit-1][1] > 0 ? TMath::Sqrt (sig_Cand[ifit-1][1]) : 0;
2249     cout << xy_Cand[ifit-1][0] << " " << xy_Cand[ifit-1][1] << " " << sig_Cand[ifit-1][0] << " " << sig_Cand[ifit-1][1] << endl;
2250     */
2251   } // for (Int_t ifit=1;
2252
2253   xy_Cand[0][0] /= qq; // <x>
2254   xy_Cand[0][1] /= qq; // <y>
2255   sig_Cand[0][0] = sig_Cand[0][0]/qq - xy_Cand[0][0]*xy_Cand[0][0]; // <x^2> - <x>^2
2256   sig_Cand[0][0] = sig_Cand[0][0] > 0 ? TMath::Sqrt (sig_Cand[0][0]) : 0;
2257   sig_Cand[0][1] = sig_Cand[0][1]/qq - xy_Cand[0][1]*xy_Cand[0][1]; // <y^2> - <y>^2
2258   sig_Cand[0][1] = sig_Cand[0][1] > 0 ? TMath::Sqrt (sig_Cand[0][1]) : 0;
2259   if (fDebug) cout << xy_Cand[0][0] << " " << xy_Cand[0][1] << " " << sig_Cand[0][0] << " " << sig_Cand[0][1] << endl;
2260
2261   Int_t nDof, maxSeed[3];
2262   Double_t fmin, chi2o = 9999, chi2n;
2263
2264   // Try to fit with one-track hypothesis, then 2-track. If chi2/dof is 
2265   // lower, try 3-track (if number of pads is sufficient).
2266   
2267   TMath::Sort(nfit, qseed, maxSeed, kTRUE); // in decreasing order
2268   nfit = TMath::Min (nfit, (npads + 1) / 3);
2269   if (nfit > 1) {
2270     if (nInX < 3 && nInY < 3 || nInX == 3 && nInY < 3 || nInX < 3 && nInY == 3) nfit = 1; // not enough pads in each direction
2271   }
2272   //if (nfit > 1) nfit --;
2273   // One pad per direction 
2274   //if (nInX == 1) { step[0] /= 1; xyseed[0][0] = xPad; }
2275   //if (nInY == 1) { step[1] /= 1; xyseed[0][1] = yPad; }
2276
2277   Double_t *gin = 0, func0, func1, param[8], param0[2][8], deriv[2][8], step0[8];
2278   Double_t shift[8], stepMax, derMax, parmin[8], parmax[8], func2[2], shift0;
2279   Double_t delta[8], scMax, dder[8], estim, shiftSave = 0;
2280   Int_t min, max, nCall = 0, memory[8] = {0}, nLoop, idMax = 0, iestMax = 0, nFail;
2281   Double_t rad, dist[3] = {0};
2282
2283   for (Int_t iseed=0; iseed<nfit; iseed++) {
2284
2285     if (iseed) { for (Int_t j=0; j<fNpar; j++) param[j] = parOk[j]; } // for bounded params
2286     for (Int_t j=0; j<3; j++) step0[fNpar+j] = shift[fNpar+j] = step[j];
2287     param[fNpar] = xyseed[maxSeed[iseed]][0];
2288     parmin[fNpar] = xmin; 
2289     parmax[fNpar++] = xmax; 
2290     param[fNpar] = xyseed[maxSeed[iseed]][1];
2291     parmin[fNpar] = ymin; 
2292     parmax[fNpar++] = ymax; 
2293     if (fNpar > 2) {
2294       param[fNpar] = fNpar == 4 ? 0.5 : 0.3;
2295       parmin[fNpar] = 0; 
2296       parmax[fNpar++] = 1; 
2297     }
2298
2299     // Try new algorithm
2300     min = nLoop = 1; stepMax = func2[1] = derMax = 999999; nFail = 0;
2301
2302     while (1) {
2303       max = !min;
2304       Fcn1(fNpar, gin, func0, param, 1); nCall++;
2305       //cout << " Func: " << func0 << endl;
2306
2307       func2[max] = func0;
2308       for (Int_t j=0; j<fNpar; j++) {
2309         param0[max][j] = param[j];
2310         delta[j] = step0[j];
2311         param[j] += delta[j] / 10;
2312         if (j > 0) param[j-1] -= delta[j-1] / 10;
2313         Fcn1(fNpar, gin, func1, param, 1); nCall++;
2314         deriv[max][j] = (func1 - func0) / delta[j] * 10; // first derivative
2315         //cout << j << " " << deriv[max][j] << endl;
2316         dder[j] = param0[0][j] != param0[1][j] ? (deriv[0][j] - deriv[1][j]) / 
2317                                                  (param0[0][j] - param0[1][j]) : 0; // second derivative
2318       }
2319       param[fNpar-1] -= delta[fNpar-1] / 10;
2320       if (nCall > 2000) break;
2321
2322       min = func2[0] < func2[1] ? 0 : 1;
2323       nFail = min == max ? 0 : nFail + 1;
2324
2325       stepMax = derMax = estim = 0;
2326       for (Int_t j=0; j<fNpar; j++) { 
2327         // Estimated distance to minimum
2328         shift0 = shift[j];
2329         if (nLoop == 1) shift[j] = TMath::Sign (step0[j], -deriv[max][j]); // first step
2330         else if (TMath::Abs(deriv[0][j]) < 1.e-3 && TMath::Abs(deriv[1][j]) < 1.e-3) shift[j] = 0;
2331         else if (deriv[min][j]*deriv[!min][j] > 0 && TMath::Abs(deriv[min][j]) > TMath::Abs(deriv[!min][j])
2332                  //|| TMath::Abs(deriv[0][j]-deriv[1][j]) < 1.e-3) {
2333           || TMath::Abs(deriv[0][j]-deriv[1][j]) < 1.e-3 || TMath::Abs(dder[j]) < 1.e-6) {
2334           shift[j] = -TMath::Sign (shift[j], (func2[0]-func2[1]) * (param0[0][j]-param0[1][j]));
2335           if (min == max) { 
2336             if (memory[j] > 1) { shift[j] *= 2; } //cout << " Memory " << memory[j] << " " << shift[j] << endl; }
2337             memory[j]++;
2338           }
2339         } else {
2340           shift[j] = dder[j] != 0 ? -deriv[min][j] / dder[j] : 0;
2341           memory[j] = 0;
2342         }
2343         if (TMath::Abs(shift[j])/step0[j] > estim) { 
2344           estim = TMath::Abs(shift[j])/step0[j];
2345           iestMax = j;
2346         }
2347
2348         // Too big step
2349         if (TMath::Abs(shift[j])/step0[j] > 10) shift[j] = TMath::Sign(10.,shift[j]) * step0[j]; // 
2350
2351         // Failed to improve minimum
2352         if (min != max) {
2353           memory[j] = 0;
2354           param[j] = param0[min][j];
2355           if (TMath::Abs(shift[j]+shift0) > 0.1*step0[j]) shift[j] = (shift[j] + shift0) / 2;
2356           else shift[j] /= -2;
2357         } 
2358
2359         // Too big step
2360         if (TMath::Abs(shift[j]*deriv[min][j]) > func2[min]) 
2361           shift[j] = TMath::Sign (func2[min]/deriv[min][j], shift[j]);
2362
2363         // Introduce step relaxation factor
2364         if (memory[j] < 3) {
2365           scMax = 1 + 4 / TMath::Max(nLoop/2.,1.);
2366           if (TMath::Abs(shift0) > 0 && TMath::Abs(shift[j]/shift0) > scMax) 
2367             shift[j] = TMath::Sign (shift0*scMax, shift[j]);
2368         }
2369         param[j] += shift[j]; 
2370         //AZ Check parameter limits 27-12-2004
2371         if (param[j] < parmin[j]) { 
2372           shift[j] = parmin[j] - param[j]; 
2373           param[j] = parmin[j]; 
2374         } else if (param[j] > parmax[j]) {
2375           shift[j] = parmax[j] - param[j];
2376           param[j] = parmax[j];
2377         }
2378         //cout << " xxx " << j << " " << shift[j] << " " << param[j] << endl;
2379         stepMax = TMath::Max (stepMax, TMath::Abs(shift[j]/step0[j]));
2380         if (TMath::Abs(deriv[min][j]) > derMax) {
2381           idMax = j;
2382           derMax = TMath::Abs (deriv[min][j]);
2383         }
2384       } // for (Int_t j=0; j<fNpar;
2385       //cout << max << " " << func2[min] << " " << derMax << " " << stepMax << " " << estim << " " << iestMax << " " << nCall << endl;
2386       if (estim < 1 && derMax < 2 || nLoop > 150) break; // minimum was found
2387
2388       nLoop++;
2389       // Check for small step
2390       if (shift[idMax] == 0) { shift[idMax] = step0[idMax]/10; param[idMax] += shift[idMax]; continue; }
2391       if (!memory[idMax] && derMax > 0.5 && nLoop > 10) {
2392         //cout << " ok " << deriv[min][idMax] << " " << deriv[!min][idMax] << " " << dder[idMax]*shift[idMax] << " " << shift[idMax] << endl;
2393         if (dder[idMax] != 0 && TMath::Abs(deriv[min][idMax]/dder[idMax]/shift[idMax]) > 10) {
2394           if (min == max) dder[idMax] = -dder[idMax];
2395           shift[idMax] = -deriv[min][idMax] / dder[idMax] / 10; 
2396           param[idMax] += shift[idMax];
2397           stepMax = TMath::Max (stepMax, TMath::Abs(shift[idMax])/step0[idMax]);
2398           //cout << shift[idMax] << " " << param[idMax] << endl;
2399           if (min == max) shiftSave = shift[idMax];
2400         }
2401         if (nFail > 10) {
2402           param[idMax] -= shift[idMax];
2403           shift[idMax] = 4 * shiftSave * (gRandom->Rndm(0) - 0.5);
2404           param[idMax] += shift[idMax];
2405           //cout << shift[idMax] << endl;
2406         }
2407       }      
2408     } // while (1)
2409     fmin = func2[min];
2410
2411     nDof = npads - fNpar + nVirtual;
2412     if (!nDof) nDof++;
2413     chi2n = fmin / nDof;
2414     if (fDebug) cout << " Chi2 " << chi2n << " " << fNpar << endl;
2415
2416     if (chi2n*1.2+1.e-6 > chi2o ) { fNpar -= 3; break; }
2417
2418     // Save parameters and errors
2419
2420     if (nInX == 1 && qPad[1] > 1) {
2421       // One pad per direction 
2422       xPad = xyqPad[1] / qPad[1]; // take COG for this case
2423       for (Int_t i=0; i<fNpar; i++) if (i == 0 || i == 2 || i == 5) param0[min][i] = xPad;
2424     }
2425     if (nInY == 1 && qPad[0] > 1) {
2426       // One pad per direction 
2427       yPad = xyqPad[0] / qPad[0]; // take COG for this case
2428       for (Int_t i=0; i<fNpar; i++) if (i == 1 || i == 3 || i == 6) param0[min][i] = yPad;
2429     }
2430
2431     /*
2432     if (iseed > 0) {
2433       // Find distance to the nearest neighbour
2434       dist[0] = dist[1] = TMath::Sqrt ((param0[min][0]-param0[min][2])*
2435                                        (param0[min][0]-param0[min][2])
2436                                       +(param0[min][1]-param0[min][3])*
2437                                        (param0[min][1]-param0[min][3]));
2438       if (iseed > 1) {
2439         dist[2] = TMath::Sqrt ((param0[min][0]-param0[min][5])*
2440                                (param0[min][0]-param0[min][5])
2441                               +(param0[min][1]-param0[min][6])*
2442                                (param0[min][1]-param0[min][6]));
2443         rad = TMath::Sqrt ((param0[min][2]-param0[min][5])*
2444                            (param0[min][2]-param0[min][5])
2445                           +(param0[min][3]-param0[min][6])*
2446                            (param0[min][3]-param0[min][6]));
2447         if (dist[2] < dist[0]) dist[0] = dist[2];
2448         if (rad < dist[1]) dist[1] = rad;
2449         if (rad < dist[2]) dist[2] = rad;
2450       }
2451       cout << dist[0] << " " << dist[1] << " " << dist[2] << endl;
2452       if (dist[TMath::LocMin(iseed+1,dist)] < 1.) { fNpar -= 3; break; }
2453     }
2454     */
2455
2456     for (Int_t i=0; i<fNpar; i++) {
2457       parOk[i] = param0[min][i];
2458       errOk[i] = fmin;
2459       // Bounded params
2460       parOk[i] = TMath::Max (parOk[i], parmin[i]);
2461       parOk[i] = TMath::Min (parOk[i], parmax[i]);
2462     }
2463
2464     chi2o = chi2n;
2465     if (fmin < 0.1) break; // !!!???
2466   } // for (Int_t iseed=0; 
2467
2468   if (fDebug) {
2469     for (Int_t i=0; i<fNpar; i++) {
2470       //if (i == 4 || i == 7) continue;
2471       if (i == 4 || i == 7) {
2472         if (i == 7 || i == 4 && fNpar < 7) cout << parOk[i] << endl;
2473         else cout << parOk[i] * (1-parOk[7]) << endl;
2474         continue;
2475       }
2476       cout << parOk[i] << " " << errOk[i] << endl;
2477     }
2478   }
2479   nfit = (fNpar + 1) / 3;
2480   dist[0] = dist[1] = dist[2] = 0;
2481
2482   if (nfit > 1) {
2483     // Find distance to the nearest neighbour
2484     dist[0] = dist[1] = TMath::Sqrt ((parOk[0]-parOk[2])*
2485                                      (parOk[0]-parOk[2])
2486                                     +(parOk[1]-parOk[3])*
2487                                      (parOk[1]-parOk[3]));
2488     if (nfit > 2) {
2489       dist[2] = TMath::Sqrt ((parOk[0]-parOk[5])*
2490                              (parOk[0]-parOk[5])
2491                             +(parOk[1]-parOk[6])*
2492                              (parOk[1]-parOk[6]));
2493       rad = TMath::Sqrt ((parOk[2]-parOk[5])*
2494                          (parOk[2]-parOk[5])
2495                         +(parOk[3]-parOk[6])*
2496                          (parOk[3]-parOk[6]));
2497       if (dist[2] < dist[0]) dist[0] = dist[2];
2498       if (rad < dist[1]) dist[1] = rad;
2499       if (rad < dist[2]) dist[2] = rad;
2500     }
2501   }
2502
2503   Int_t indx, imax;
2504   fnPads[1] -= nVirtual;
2505   if (fReco) {
2506     Double_t coef = 0;
2507     //for (Int_t j=0; j<nfit; j++) {
2508     for (Int_t j=nfit-1; j>=0; j--) {
2509       indx = j<2 ? j*2 : j*2+1;  
2510       if (nfit == 1) coef = 1;
2511       else coef = j==nfit-1 ? parOk[indx+2] : 1-coef;
2512       coef = TMath::Max (coef, 0.);
2513       if (nfit == 3 && j < 2) coef = j==1 ? coef*parOk[indx+2] : coef - parOk[7];
2514       coef = TMath::Max (coef, 0.);
2515       AddRawCluster (parOk[indx], parOk[indx+1], coef*fQtot, errOk[indx], nfit0+10*nfit, tracks,
2516                      //sig_Cand[maxSeed[j]][0], sig_Cand[maxSeed[j]][1]);
2517                      //sig_Cand[0][0], sig_Cand[0][1], dist[j]);
2518                      sig_Cand[0][0], sig_Cand[0][1], dist[TMath::LocMin(nfit,dist)]);
2519     }
2520     return nfit;
2521   } 
2522   for (Int_t i=0; i<fnMu; i++) {
2523     cmax = fxyMu[i][6];
2524     for (Int_t j=0; j<nfit; j++) {
2525       indx = j<2 ? j*2 : j*2+1;  
2526       rad = (fxyMu[i][0]-parOk[indx])*(fxyMu[i][0]-parOk[indx]) +
2527             (fxyMu[i][1]-parOk[indx+1])*(fxyMu[i][1]-parOk[indx+1]);
2528       if (rad < cmax) {
2529         cmax = rad; 
2530         imax = indx;
2531         fxyMu[i][6] = cmax;
2532         fxyMu[i][2] = parOk[imax] - fxyMu[i][0];
2533         fxyMu[i][4] = parOk[imax+1] - fxyMu[i][1];
2534         fxyMu[i][3] = errOk[imax];
2535         fxyMu[i][5] = errOk[imax+1];
2536       }
2537     }      
2538   }
2539   return nfit;
2540 }  
2541
2542 //_____________________________________________________________________________
2543 void AliMUONClusterFinderAZ::Fcn1(Int_t & /*npar*/, Double_t * /*gin*/, Double_t &f, Double_t *par, Int_t /*iflag*/)
2544 {
2545   // Fit for one track
2546   //AZ for Muinuit AliMUONClusterFinderAZ& c = *(AliMUONClusterFinderAZ::fgClusterFinder);    
2547   AliMUONClusterFinderAZ& c = *this; //AZ
2548   
2549   Int_t cath, ix, iy, indx, npads=0;
2550   Double_t charge, delta, coef=0, chi2=0, qTot = 0;
2551   for (Int_t j=0; j<c.fnPads[0]+c.fnPads[1]; j++) {
2552     if (c.fPadIJ[1][j] != 1) continue;
2553     cath = c.fPadIJ[0][j];
2554     if (c.fXyq[3][j] > 0) npads++; // exclude virtual pads
2555     qTot += c.fXyq[2][j];
2556     c.fSegmentation[cath]->GetPadI(fInput->DetElemId(),c.fXyq[0][j],c.fXyq[1][j],c.fZpad,ix,iy);
2557     c.fSegmentation[cath]->SetPad(fInput->DetElemId(),ix,iy);
2558     charge = 0;
2559     for (Int_t i=c.fNpar/3; i>=0; i--) { // sum over tracks
2560       indx = i<2 ? 2*i : 2*i+1;
2561       c.fSegmentation[cath]->SetHit(fInput->DetElemId(),par[indx],par[indx+1],c.fZpad);
2562       //charge += c.fResponse->IntXY(fInput->DetElemId(),c.fSegmentation[cath])*par[icl*3+2];
2563       if (c.fNpar == 2) coef = 1;
2564       else coef = i==c.fNpar/3 ? par[indx+2] : 1-coef;
2565       coef = TMath::Max (coef, 0.);
2566       if (c.fNpar == 8 && i < 2) coef = i==1 ? coef*par[indx+2] : coef - par[7];
2567       coef = TMath::Max (coef, 0.);
2568       charge += c.fResponse->IntXY(fInput->DetElemId(),c.fSegmentation[cath])*coef;
2569     }
2570     charge *= c.fQtot;
2571     //if (c.fXyq[2][j] > c.fResponse->MaxAdc()-1 && charge > 
2572     //  c.fResponse->MaxAdc()) charge = c.fResponse->MaxAdc(); 
2573     delta = charge - c.fXyq[2][j];
2574     delta *= delta;
2575     delta /= c.fXyq[2][j];
2576     //if (cath) delta /= 5; // just for test
2577     chi2 += delta;
2578   } // for (Int_t j=0;
2579   f = chi2; 
2580   Double_t qAver = qTot/npads; //(c.fnPads[0]+c.fnPads[1]);
2581   f = chi2/qAver;
2582 }
2583
2584 //_____________________________________________________________________________
2585 void AliMUONClusterFinderAZ::UpdatePads(Int_t /*nfit*/, Double_t *par)
2586 {
2587   // Subtract the fitted charges from pads with strong coupling
2588
2589   Int_t cath, ix, iy, indx;
2590   Double_t charge, coef=0;
2591   for (Int_t j=0; j<fnPads[0]+fnPads[1]; j++) {
2592     if (fPadIJ[1][j] != -1) continue;
2593     if (fNpar != 0) {
2594       cath = fPadIJ[0][j];
2595       fSegmentation[cath]->GetPadI(fInput->DetElemId(),fXyq[0][j],fXyq[1][j],fZpad,ix,iy);
2596       fSegmentation[cath]->SetPad(fInput->DetElemId(),ix,iy);
2597       charge = 0;
2598       for (Int_t i=fNpar/3; i>=0; i--) { // sum over tracks
2599         indx = i<2 ? 2*i : 2*i+1;
2600         fSegmentation[cath]->SetHit(fInput->DetElemId(),par[indx],par[indx+1],fZpad);
2601         if (fNpar == 2) coef = 1;
2602         else coef = i==fNpar/3 ? par[indx+2] : 1-coef;
2603         coef = TMath::Max (coef, 0.);
2604         if (fNpar == 8 && i < 2) coef = i==1 ? coef*par[indx+2] : coef - par[7];
2605         coef = TMath::Max (coef, 0.);
2606         charge += fResponse->IntXY(fInput->DetElemId(),fSegmentation[cath])*coef;
2607       }
2608       charge *= fQtot;
2609       fXyq[2][j] -= charge;
2610     } // if (fNpar != 0)
2611     if (fXyq[2][j] > fResponse->ZeroSuppression()) fPadIJ[1][j] = 0; // return pad for further using
2612   } // for (Int_t j=0;
2613 }  
2614
2615 //_____________________________________________________________________________
2616 Bool_t AliMUONClusterFinderAZ::TestTrack(Int_t /*t*/) const {
2617 // Test if track was user selected
2618   return kTRUE;
2619   /*
2620     if (fTrack[0]==-1 || fTrack[1]==-1) {
2621         return kTRUE;
2622     } else if (t==fTrack[0] || t==fTrack[1]) {
2623         return kTRUE;
2624     } else {
2625         return kFALSE;
2626     }
2627   */
2628 }
2629
2630 //_____________________________________________________________________________
2631 void AliMUONClusterFinderAZ::AddRawCluster(Double_t x, Double_t y, Double_t qTot, Double_t fmin, Int_t nfit, Int_t *tracks, Double_t /*sigx*/, Double_t /*sigy*/, Double_t /*dist*/)
2632 {
2633   //
2634   // Add a raw cluster copy to the list
2635   //
2636   if (qTot <= 0.501) return; 
2637   AliMUONRawCluster cnew;
2638   AliMUON *pMUON=(AliMUON*)gAlice->GetModule("MUON");
2639   pMUON=0; //AZ
2640   //pMUON->AddRawCluster(fInput->Chamber(),c); 
2641
2642   Int_t cath, npads[2] = {0}, nover[2] = {0};
2643   for (Int_t j=0; j<fnPads[0]+fnPads[1]; j++) {
2644     cath = fPadIJ[0][j];
2645     // There was an overflow
2646     if (fPadIJ[1][j] == -9) nover[cath]++;
2647     if (fPadIJ[1][j] != 1 && fPadIJ[1][j] != -9) continue;
2648     cnew.SetMultiplicity(cath,cnew.GetMultiplicity(cath)+1);
2649     if (fXyq[2][j] > cnew.GetPeakSignal(cath)) cnew.SetPeakSignal(cath,TMath::Nint (fXyq[2][j]));
2650     //cnew.SetCharge(cath,cnew.GetCharge(cath) + TMath::Nint (fXyq[2][j]));
2651     cnew.SetContrib(npads[cath],cath,fXyq[2][j]);
2652     cnew.SetIndex(npads[cath],cath,TMath::Nint (fXyq[5][j])+10000*fInput->DetElemId());
2653     npads[cath]++;
2654   }
2655
2656   cnew.SetClusterType(nover[0] + nover[1] * 100);
2657   for (Int_t j=0; j<3; j++) cnew.SetTrack(j,tracks[j]);
2658
2659   for (cath=0; cath<2; cath++) {
2660     cnew.SetX(cath, x);
2661     cnew.SetY(cath, y);
2662     cnew.SetZ(cath, fZpad);
2663     cnew.SetCharge(cath, TMath::Nint(qTot));
2664     //cnew.SetPeakSignal(cath,20);
2665     //cnew.SetMultiplicity(cath, 5);
2666     cnew.SetNcluster(cath, nfit);
2667     cnew.SetChi2(cath, fmin); //0.;1
2668   } 
2669   // Evaluate measurement errors
2670   //AZ Errors(&cnew);
2671
2672   cnew.SetGhost(nfit); //cnew.SetX(1,sigx); cnew.SetY(1,sigy); cnew.SetZ(1,dist);
2673   //cnew.fClusterType=cnew.PhysicsContribution();
2674   //AZ pMUON->GetMUONData()->AddRawCluster(AliMUONClusterInput::Instance()->Chamber(),cnew); 
2675   new((*fRawClusters)[fNRawClusters++]) AliMUONRawCluster(cnew); //AZ
2676   if (fDebug) cout << fNRawClusters << " " << AliMUONClusterInput::Instance()->Chamber() << endl;
2677   //fNPeaks++;
2678 }
2679
2680 //_____________________________________________________________________________
2681 Int_t AliMUONClusterFinderAZ::FindLocalMaxima(Int_t *localMax, Double_t *maxVal)
2682 {
2683   // Find local maxima in pixel space for large preclusters in order to
2684   // try to split them into smaller pieces (to speed up the MLEM procedure)
2685
2686   TH2D *hist = (TH2D*) gROOT->FindObject("anode");
2687   if (hist) hist->Delete();
2688
2689   Double_t xylim[4] = {999, 999, 999, 999};
2690   Int_t nPix = fPixArray->GetEntriesFast();
2691   AliMUONPixel *pixPtr = 0;
2692   for (Int_t ipix=0; ipix<nPix; ipix++) {
2693     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(ipix);
2694     for (Int_t i=0; i<4; i++) 
2695          xylim[i] = TMath::Min (xylim[i], (i%2 ? -1 : 1)*pixPtr->Coord(i/2));
2696   }
2697   for (Int_t i=0; i<4; i++) xylim[i] -= pixPtr->Size(i/2); 
2698
2699   Int_t nx = TMath::Nint ((-xylim[1]-xylim[0])/pixPtr->Size(0)/2);
2700   Int_t ny = TMath::Nint ((-xylim[3]-xylim[2])/pixPtr->Size(1)/2);
2701   hist = new TH2D("anode","anode",nx,xylim[0],-xylim[1],ny,xylim[2],-xylim[3]);
2702   for (Int_t ipix=0; ipix<nPix; ipix++) {
2703     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(ipix);
2704     hist->Fill(pixPtr->Coord(0), pixPtr->Coord(1), pixPtr->Charge());
2705   }
2706   if (fDraw) {
2707     ((TCanvas*)gROOT->FindObject("c2"))->cd();
2708     gPad->SetTheta(55);
2709     gPad->SetPhi(30);
2710     hist->Draw("lego1Fb");
2711     gPad->Update();
2712     int ia;
2713     cin >> ia;
2714   }
2715
2716   Int_t nMax = 0, indx;
2717   Int_t *isLocalMax = new Int_t[ny*nx];
2718   for (Int_t i=0; i<ny*nx; i++) isLocalMax[i] = 0;
2719
2720   for (Int_t i=1; i<=ny; i++) {
2721     indx = (i-1) * nx;
2722     for (Int_t j=1; j<=nx; j++) {
2723       if (hist->GetCellContent(j,i) < 0.5) continue;
2724       //if (isLocalMax[indx+j-1] < 0) continue;
2725       if (isLocalMax[indx+j-1] != 0) continue;
2726       FlagLocalMax(hist, i, j, isLocalMax);
2727     }
2728   }
2729
2730   for (Int_t i=1; i<=ny; i++) {
2731     indx = (i-1) * nx;
2732     for (Int_t j=1; j<=nx; j++) {
2733       if (isLocalMax[indx+j-1] > 0) { 
2734         localMax[nMax] = indx + j - 1; 
2735         maxVal[nMax++] = hist->GetCellContent(j,i);
2736         if (nMax > 99) AliFatal(" Too many local maxima !!!");
2737       }
2738     }
2739   }
2740   if (fDebug) cout << " Local max: " << nMax << endl;
2741   delete [] isLocalMax; isLocalMax = 0;
2742   return nMax;
2743 }
2744
2745 //_____________________________________________________________________________
2746 void AliMUONClusterFinderAZ::FlagLocalMax(TH2D *hist, Int_t i, Int_t j, Int_t *isLocalMax)
2747 {
2748   // Flag pixels (whether or not local maxima)
2749
2750   Int_t nx = hist->GetNbinsX();
2751   Int_t ny = hist->GetNbinsY();
2752   Int_t cont = TMath::Nint (hist->GetCellContent(j,i));
2753   Int_t cont1 = 0;
2754
2755   for (Int_t i1=i-1; i1<i+2; i1++) {
2756     if (i1 < 1 || i1 > ny) continue;
2757     for (Int_t j1=j-1; j1<j+2; j1++) {
2758       if (j1 < 1 || j1 > nx) continue;
2759       if (i == i1 && j == j1) continue;
2760       cont1 = TMath::Nint (hist->GetCellContent(j1,i1));
2761       if (cont < cont1) { isLocalMax[(i-1)*nx+j-1] = -1; return; }
2762       else if (cont > cont1) isLocalMax[(i1-1)*nx+j1-1] = -1;
2763       else { // the same charge
2764         isLocalMax[(i-1)*nx+j-1] = 1; 
2765         if (isLocalMax[(i1-1)*nx+j1-1] == 0) {
2766           FlagLocalMax(hist, i1, j1, isLocalMax);
2767           if (isLocalMax[(i1-1)*nx+j1-1] < 0) { isLocalMax[(i-1)*nx+j-1] = -1; return; }
2768           else isLocalMax[(i1-1)*nx+j1-1] = -1;
2769         }
2770       } 
2771     }
2772   }
2773   isLocalMax[(i-1)*nx+j-1] = 1; // local maximum
2774 }
2775
2776 //_____________________________________________________________________________
2777 void AliMUONClusterFinderAZ::FindCluster(Int_t *localMax, Int_t iMax)
2778 {
2779   // Find pixel cluster around local maximum #iMax and pick up pads
2780   // overlapping with it
2781
2782   TH2D *hist = (TH2D*) gROOT->FindObject("anode");
2783   Int_t nx = hist->GetNbinsX();
2784   Int_t ny = hist->GetNbinsY();
2785   Int_t ic = localMax[iMax] / nx + 1;
2786   Int_t jc = localMax[iMax] % nx + 1;
2787   Bool_t *used = new Bool_t[ny*nx];
2788   for (Int_t i=0; i<ny*nx; i++) used[i] = kFALSE;
2789
2790   // Drop all pixels from the array - pick up only the ones from the cluster
2791   fPixArray->Delete();
2792
2793   Double_t wx = hist->GetXaxis()->GetBinWidth(1)/2; 
2794   Double_t wy = hist->GetYaxis()->GetBinWidth(1)/2;  
2795   Double_t yc = hist->GetYaxis()->GetBinCenter(ic);
2796   Double_t xc = hist->GetXaxis()->GetBinCenter(jc);
2797   Double_t cont = hist->GetCellContent(jc,ic);
2798   AliMUONPixel *pixPtr = new AliMUONPixel (xc, yc, wx, wy, cont);
2799   fPixArray->Add((TObject*)pixPtr);
2800   used[(ic-1)*nx+jc-1] = kTRUE;
2801   AddBin(hist, ic, jc, 1, used, (TObjArray*)0); // recursive call
2802
2803   Int_t nPix = fPixArray->GetEntriesFast(), npad = fnPads[0] + fnPads[1];
2804   for (Int_t i=0; i<nPix; i++) {
2805     ((AliMUONPixel*)fPixArray->UncheckedAt(i))->SetSize(0,wx); 
2806     ((AliMUONPixel*)fPixArray->UncheckedAt(i))->SetSize(1,wy); 
2807   }
2808   if (fDebug) cout << iMax << " " << nPix << endl;
2809
2810   Float_t xy[4], xy12[4];
2811   // Pick up pads which overlap with found pixels
2812   for (Int_t i=0; i<npad; i++) fPadIJ[1][i] = -1;
2813   for (Int_t i=0; i<nPix; i++) {
2814     pixPtr = (AliMUONPixel*) fPixArray->UncheckedAt(i);
2815     for (Int_t j=0; j<4; j++) 
2816       xy[j] = pixPtr->Coord(j/2) + (j%2 ? 1 : -1)*pixPtr->Size(j/2);
2817     for (Int_t j=0; j<npad; j++) 
2818       if (Overlap(xy, j, xy12, 0)) fPadIJ[1][j] = 0; // flag for use
2819   }
2820
2821   delete [] used; used = 0;
2822 }
2823
2824 //_____________________________________________________________________________
2825 AliMUONClusterFinderAZ&  
2826 AliMUONClusterFinderAZ::operator=(const AliMUONClusterFinderAZ& rhs)
2827 {
2828 // Protected assignement operator
2829
2830   if (this == &rhs) return *this;
2831
2832   AliFatal("Not implemented.");
2833     
2834   return *this;  
2835 }    
2836           
2837 //_____________________________________________________________________________
2838 void AliMUONClusterFinderAZ::AddVirtualPad()
2839 {
2840   // Add virtual pad (with small charge) to improve fit for some
2841   // clusters (when pad with max charge is at the extreme of the cluster)
2842
2843   // Get number of pads in X and Y-directions
2844   Int_t nInX = -1, nInY;
2845   PadsInXandY(nInX, nInY);
2846   //return;
2847
2848   //nInY = npady[0];
2849   //nInX = npadx[1] ? npadx[1] : npadx[0];
2850   // Add virtual pads only if number of pads per direction == 2
2851   //if (!npadx[1] && npady[0] != 2 && npadx[0] != 2) return 0; // one-sided
2852   //if (npadx[1] && npady[0] != 2 && npadx[1] != 2) return 0;
2853   if (nInX != 2 && nInY != 2) return;
2854
2855   // Find pads with max charge
2856   Int_t maxpad[2][2] = {{-1, -1}, {-1, -1}}, cath;
2857   Double_t sigmax[2] = {0}, aamax[2] = {0};
2858   for (Int_t j=0; j<fnPads[0]+fnPads[1]; j++) {
2859     if (fPadIJ[1][j] != 0) continue;
2860     cath = fPadIJ[0][j];
2861     if (fXyq[2][j] > sigmax[cath]) {
2862       maxpad[cath][1] = maxpad[cath][0];
2863       aamax[cath] = sigmax[cath];
2864       sigmax[cath] = fXyq[2][j];
2865       maxpad[cath][0] = j;
2866     }
2867   }
2868   if (maxpad[0][0] >= 0 && maxpad[0][1] < 0 || maxpad[1][0] >= 0 && maxpad[1][1] < 0) {
2869     for (Int_t j=0; j<fnPads[0]+fnPads[1]; j++) {
2870       if (fPadIJ[1][j] != 0) continue;
2871       cath = fPadIJ[0][j];
2872       if (j == maxpad[cath][0] || j == maxpad[cath][1]) continue;
2873       if (fXyq[2][j] > aamax[cath]) {
2874         aamax[cath] = fXyq[2][j];
2875         maxpad[cath][1] = j;
2876       }
2877     }
2878   }
2879   // Check for mirrors (side X on cathode 0) 
2880   Bool_t mirror = kFALSE;
2881   if (maxpad[0][0] >= 0 && maxpad[1][0] >= 0) 
2882     mirror = fXyq[3][maxpad[0][0]] < fXyq[4][maxpad[0][0]]; 
2883
2884   // Find neughbours of pads with max charges
2885   Int_t nn, xList[10], yList[10], ix0, iy0, ix, iy, neighb;
2886   for (cath=0; cath<2; cath++) {
2887     if (!cath && maxpad[0][0] < 0) continue; // one-sided cluster - cathode 1
2888     if (cath && maxpad[1][0] < 0) break; // one-sided cluster - cathode 0
2889     if (maxpad[1][0] >= 0) {
2890       if (!mirror) {
2891         if (!cath && nInY != 2) continue;
2892         //AZ if (cath && nInX != 2) continue;
2893         if (cath && nInX != 2 && (maxpad[0][0] >= 0 || nInY != 2)) continue;
2894       } else {
2895         if (!cath && nInX != 2) continue;
2896         if (cath && nInY != 2 && (maxpad[0][0] >= 0 || nInX != 2)) continue;
2897       }
2898     }
2899
2900     Int_t iAddX = 0, iAddY = 0, ix1 = 0, iy1 = 0, iMuon = 0, iPad = 0;
2901     if (maxpad[0][0] < 0) iPad = 1;
2902
2903     // This part of code to take care of edge effect (problems in MC)
2904     Float_t spr_x = fResponse->SigmaIntegration()*fResponse->ChargeSpreadX();
2905     Float_t spr_y = fResponse->SigmaIntegration()*fResponse->ChargeSpreadY();
2906     Double_t rmin = 9999, rad2;
2907     Int_t border = 0, iYlow = 0;
2908
2909     if (!fReco) {
2910       for (Int_t i=0; i<2; i++) {
2911         rad2 = (fXyq[0][maxpad[iPad][0]]-fxyMu[i][0]) * (fXyq[0][maxpad[iPad][0]]-fxyMu[i][0]);
2912         rad2 += (fXyq[1][maxpad[iPad][0]]-fxyMu[i][1]) * (fXyq[1][maxpad[iPad][0]]-fxyMu[i][1]);
2913         if (rad2 < rmin) { iMuon = i; rmin = rad2; }
2914       }
2915       fSegmentation[cath]->FirstPad(fInput->DetElemId(),(Float_t)fxyMu[iMuon][0], (Float_t)fxyMu[iMuon][1], fZpad, spr_x, spr_y);  
2916       if (fSegmentation[cath]->Sector(fInput->DetElemId(),fSegmentation[cath]->Ix(),fSegmentation[cath]->Iy()) <= 0) {
2917         fSegmentation[cath]->NextPad(fInput->DetElemId());
2918         border = 1; 
2919         iYlow = fSegmentation[cath]->Iy();
2920       }
2921     }
2922     
2923     for (iPad=0; iPad<2; iPad++) {
2924       if (iPad && !iAddX && !iAddY) break;
2925       if (iPad && fXyq[2][maxpad[cath][1]] / sigmax[cath] < 0.5) break;
2926
2927       Int_t neighbx = 0, neighby = 0;
2928       fSegmentation[cath]->GetPadI(fInput->DetElemId(),fXyq[0][maxpad[cath][iPad]],fXyq[1][maxpad[cath][iPad]],fZpad,ix0,iy0);
2929       fSegmentation[cath]->Neighbours(fInput->DetElemId(),ix0,iy0,&nn,xList,yList); 
2930       Float_t zpad; //, xpad, ypad;
2931       for (Int_t j=0; j<nn; j++) {
2932         /*
2933         if (border && yList[j] < iYlow) { xList[j] = yList[j] = 0; continue; }
2934         fSegmentation[cath]->GetPadC(fInput->DetElemId(),xList[j],yList[j],xpad,ypad,zpad);
2935         if (TMath::Abs(xpad) < 1 && TMath::Abs(ypad) < 1) 
2936           { xList[j] = yList[j] = 0; continue; } // strange case (something with pad mapping)
2937         */
2938         if (TMath::Abs(xList[j]-ix0) == 1 || TMath::Abs(xList[j]*ix0) == 1) neighbx++;
2939         if (TMath::Abs(yList[j]-iy0) == 1 || TMath::Abs(yList[j]*iy0) == 1) neighby++;
2940       }
2941       if (!mirror) {
2942         if (cath) neighb = neighbx; 
2943         else neighb = neighby;
2944         if (maxpad[0][0] < 0) neighb += neighby;
2945         else if (maxpad[1][0] < 0) neighb += neighbx;
2946       } else {
2947         if (!cath) neighb = neighbx; 
2948         else neighb = neighby;
2949         if (maxpad[0][0] < 0) neighb += neighbx;
2950         else if (maxpad[1][0] < 0) neighb += neighby;
2951       }
2952
2953       for (Int_t j=0; j<fnPads[0]+fnPads[1]; j++) {
2954         if (fPadIJ[0][j] != cath) continue;
2955         fSegmentation[cath]->GetPadI(fInput->DetElemId(),fXyq[0][j],fXyq[1][j],fZpad,ix,iy);
2956         if (iy == iy0 && ix == ix0) continue; 
2957         for (Int_t k=0; k<nn; k++) {
2958           if (xList[k] != ix || yList[k] != iy) continue;
2959           if (!mirror) {
2960             if ((!cath || maxpad[0][0] < 0) && 
2961                 (TMath::Abs(iy-iy0) == 1 || TMath::Abs(iy*iy0) == 1)) {
2962               xList[k] = yList[k] = 0; 
2963               neighb--;
2964               break;
2965             }
2966             if ((cath || maxpad[1][0] < 0) && 
2967                 (TMath::Abs(ix-ix0) == 1 || TMath::Abs(ix*ix0) == 1)) {
2968               xList[k] = yList[k] = 0; 
2969               neighb--;
2970             }
2971           } else {
2972             if ((!cath || maxpad[0][0] < 0) && 
2973                 (TMath::Abs(ix-ix0) == 1 || TMath::Abs(ix*ix0) == 1)) {
2974               xList[k] = yList[k] = 0; 
2975               neighb--;
2976               break;
2977             }
2978             if ((cath || maxpad[1][0] < 0) && 
2979                 (TMath::Abs(iy-iy0) == 1 || TMath::Abs(iy*iy0) == 1)) {
2980               xList[k] = yList[k] = 0; 
2981               neighb--;
2982             }
2983           }
2984           break;
2985         } // for (Int_t k=0; k<nn;
2986         if (!neighb) break;
2987       } // for (Int_t j=0; j<fnPads[0]+fnPads[1];
2988       if (!neighb) continue;
2989       
2990       // Add virtual pad
2991       Int_t npads, isec;
2992       isec = 0;
2993       for (Int_t j=0; j<nn; j++) {
2994         if (xList[j] == 0 && yList[j] == 0) continue;
2995         npads = fnPads[0] + fnPads[1];
2996         fPadIJ[0][npads] = cath;
2997         fPadIJ[1][npads] = 0;
2998         ix = xList[j]; 
2999         iy = yList[j];
3000         if (TMath::Abs(ix-ix0) == 1 || TMath::Abs(ix*ix0) == 1) {
3001           if (iy != iy0) continue; // new segmentation - check
3002           if (nInX != 2) continue; // new
3003           if (!mirror) {
3004             if (!cath && maxpad[1][0] >= 0) continue;
3005             //if (maxpad[1][0] < 0 && nInX != 2) continue;
3006           } else {
3007             if (cath && maxpad[0][0] >= 0) continue;
3008             //if (maxpad[0][0] < 0 && nInX != 2) continue;
3009           }
3010           if (iPad && !iAddX) continue;
3011           fSegmentation[cath]->GetPadC(fInput->DetElemId(),ix,iy,fXyq[0][npads],fXyq[1][npads],zpad);
3012           if (ix1 == ix0) continue;
3013           //if (iPad && ix1 == ix0) continue;
3014           //if (iPad && TMath::Abs(fXyq[0][npads]-fXyq[0][iAddX]) < fXyq[3][iAddX]) continue;
3015           //if (TMath::Abs(fXyq[0][npads]) < 1 && TMath::Abs(fXyq[1][npads]) < 1) continue; // strange case (something with pad mapping)
3016           if (maxpad[1][0] < 0 || mirror && maxpad[0][0] >= 0) {
3017             if (!iPad) fXyq[2][npads] = TMath::Min (sigmax[0]/100, 5.);
3018             else fXyq[2][npads] = TMath::Min (aamax[0]/100, 5.);
3019           }
3020           else {
3021             if (!iPad) fXyq[2][npads] = TMath::Min (sigmax[1]/100, 5.);
3022             else fXyq[2][npads] = TMath::Min (aamax[1]/100, 5.);
3023           }
3024           fXyq[2][npads] = TMath::Max (fXyq[2][npads], (float)1);
3025           //fXyq[2][npads] = 1; 
3026           //isec = fSegmentation[cath]->Sector(fInput->DetElemId(),ix, iy);
3027           //fXyq[3][npads] = fSegmentation[cath]->Dpx(fInput->DetElemId(),isec)/2;
3028           fXyq[3][npads] = -2; // flag
3029           fnPads[1]++;
3030           iAddX = npads;
3031           if (fDebug) cout << " ***** Add virtual pad in X ***** " << fXyq[2][npads] 
3032                            << " " << fXyq[0][npads] << " " << fXyq[1][npads] << endl;
3033           ix1 = ix0;
3034           continue;
3035         } 
3036         if (nInY != 2) continue;
3037         if (!mirror && cath && maxpad[0][0] >= 0) continue;
3038         if (mirror && !cath && maxpad[1][0] >= 0) continue;
3039         if (TMath::Abs(iy-iy0) == 1 || TMath::Abs(iy*iy0) == 1) {
3040           if (ix != ix0) continue; // new segmentation - check
3041           if (iPad && !iAddY) continue;
3042           fSegmentation[cath]->GetPadC(fInput->DetElemId(),ix,iy,fXyq[0][npads],fXyq[1][npads],zpad);
3043           if (iy1 == iy0) continue;
3044           //if (iPad && iy1 == iy0) continue;
3045           //if (iPad && TMath::Abs(fXyq[1][npads]-fXyq[1][iAddY]) < fXyq[4][iAddY]) continue;
3046           //if (TMath::Abs(fXyq[0][npads]) < 1 && TMath::Abs(fXyq[1][npads]) < 1) continue; // strange case (something with pad mapping)
3047           if (maxpad[0][0] < 0 || mirror && maxpad[1][0] >= 0) {
3048             if (!iPad) fXyq[2][npads] = TMath::Min (sigmax[1]/20, 5.);
3049             else fXyq[2][npads] = TMath::Min (aamax[1]/20, 5.);
3050           }
3051           else {
3052             if (!iPad) fXyq[2][npads] = TMath::Min (sigmax[0]/20, 5.);
3053             else fXyq[2][npads] = TMath::Min (aamax[0]/20, 5.);
3054           }
3055           fXyq[2][npads] = TMath::Max (fXyq[2][npads], (float)1);
3056           //isec = fSegmentation[cath]->Sector(fInput->DetElemId(),ix, iy);
3057           //fXyq[4][npads] = fSegmentation[cath]->Dpy(isec)/2;
3058           fXyq[3][npads] = -2; // flag
3059           fnPads[1]++;
3060           iAddY = npads;
3061           if (fDebug) cout << " ***** Add virtual pad in Y ***** " << fXyq[2][npads] 
3062                            << " " << fXyq[0][npads] << " " << fXyq[1][npads] << endl;
3063           iy1 = iy0;
3064         }
3065       } // for (Int_t j=0; j<nn;
3066     } // for (Int_t iPad=0;
3067   } // for (cath=0; cath<2;
3068   return;
3069 }
3070
3071 //_____________________________________________________________________________
3072 void AliMUONClusterFinderAZ::PadsInXandY(Int_t &nInX, Int_t &nInY)
3073 {
3074   // Find number of pads in X and Y-directions (excluding virtual ones and
3075   // overflows)
3076
3077   static Int_t nXsaved = 0, nYsaved = 0;
3078   nXsaved = nYsaved = 0;
3079   //if (nInX >= 0) {nInX = nXsaved; nInY = nYsaved; return; }
3080   Double_t xlow[2] = {9999,9999}, xhig[2] = {-9999,-9999};
3081   Double_t ylow[2] = {9999,9999}, yhig[2] = {-9999,-9999};
3082   Int_t nx, ny, cath, npadx[2] = {0}, npady[2] = {0};
3083   for (Int_t j=0; j<fnPads[0]+fnPads[1]; j++) {
3084     //if (fPadIJ[1][j] != 0) continue;
3085     //if (fXyq[3][j] < 0) continue; // virtual pad
3086     if (nInX < 0 && fPadIJ[1][j] != 0) continue; // before fit
3087     else if (nInX == 0 && fPadIJ[1][j] != 1) continue; // fit - exclude overflows
3088     else if (nInX > 0 && fPadIJ[1][j] != 1 && fPadIJ[1][j] != -9) continue; // exclude non-marked
3089     //AZif (fXyq[2][j] > fResponse->MaxAdc()-1) continue;
3090     if (nInX <= 0 && fXyq[2][j] > fResponse->Saturation()-1) continue; // skip overflows
3091     cath = fPadIJ[0][j];
3092     nx = ny = 0;
3093     if (fXyq[0][j] < xlow[cath]-0.001) { xlow[cath] = fXyq[0][j]; nx++; }
3094     if (fXyq[1][j] < ylow[cath]-0.001) { ylow[cath] = fXyq[1][j]; ny++; }
3095     if (fXyq[0][j] > xhig[cath]+0.001) { xhig[cath] = fXyq[0][j]; nx++; }
3096     if (fXyq[1][j] > yhig[cath]+0.001) { yhig[cath] = fXyq[1][j]; ny++; }
3097     if (nx % 2 || !npadx[cath]) npadx[cath]++; 
3098     if (ny % 2 || !npady[cath]) npady[cath]++;
3099   }
3100   //nInY = nYsaved == npady[0] ? npady[0] : npady[1];
3101   //nInX = nXsaved == npadx[1] ? npadx[1] : npadx[0];
3102   nInY = TMath::Max (npady[0], npady[1]);
3103   nInX = TMath::Max (npadx[0], npadx[1]);
3104   //nInY = npady[0] > 0 ? npady[0] : npady[1];
3105   //nInX = npadx[1] > 0 ? npadx[1] : npadx[0];
3106 }
3107
3108 //_____________________________________________________________________________
3109 void AliMUONClusterFinderAZ::Simple()
3110 {
3111   // Process simple cluster (small number of pads) without EM-procedure
3112
3113   Int_t nForFit = 1, clustFit[1] = {1}, nfit;
3114   Double_t parOk[3] = {0.}; 
3115   TObjArray *clusters[1]; 
3116   clusters[1] = fPixArray;
3117   for (Int_t i=0; i<fnPads[0]+fnPads[1]; i++) fPadIJ[1][i] = 1;
3118   
3119   nfit = Fit(nForFit, clustFit, clusters, parOk);
3120 }
3121
3122 //_____________________________________________________________________________
3123 void AliMUONClusterFinderAZ::Errors(AliMUONRawCluster *clus)
3124 {
3125   // Correct reconstructed coordinates for some clusters and evaluate errors
3126
3127   Double_t qTot = clus->GetCharge(0), fmin = clus->GetChi2(0);
3128   Double_t xreco = clus->GetX(0), yreco = clus->GetY(0), zreco = clus->GetZ(0);
3129   Double_t sigmax[2] = {0};
3130
3131   Int_t nInX = 1, nInY, maxdig[2] ={-1, -1}, digit, cath1, isec;
3132   PadsInXandY(nInX, nInY);
3133
3134   // Find pad with maximum signal
3135   for (Int_t cath = 0; cath < 2; cath++) {
3136     for (Int_t j = 0; j < clus->GetMultiplicity(cath); j++) {
3137       cath1 = cath;
3138       digit = clus->GetIndex(j, cath);
3139       if (digit < 0) { cath1 = TMath::Even(cath); digit = -digit - 1; } // from the other cathode
3140
3141       if (clus->GetContrib(j,cath) > sigmax[cath1]) {
3142         sigmax[cath1] = clus->GetContrib(j,cath);
3143         maxdig[cath1] = digit;
3144       }
3145     }
3146   }
3147
3148   // Size of pad with maximum signal and reco coordinate distance from the pad center
3149   AliMUONDigit *mdig = 0;
3150   Double_t wx[2], wy[2], dxc[2], dyc[2];
3151   Float_t xpad, ypad, zpad;
3152   Int_t ix, iy;
3153   for (Int_t cath = 0; cath < 2; cath++) {
3154     if (maxdig[cath] < 0) continue;
3155     mdig = fInput->Digit(cath,maxdig[cath]);
3156     isec = fSegmentation[cath]->Sector(fInput->DetElemId(),mdig->PadX(), mdig->PadY());
3157     wx[cath] = fSegmentation[cath]->Dpx(fInput->DetElemId(),isec);
3158     wy[cath] = fSegmentation[cath]->Dpy(fInput->DetElemId(),isec);
3159     fSegmentation[cath]->GetPadI(fInput->DetElemId(),xreco, yreco, zreco, ix, iy);
3160     isec = fSegmentation[cath]->Sector(fInput->DetElemId(),ix,iy);
3161     if (isec > 0) {
3162       fSegmentation[cath]->GetPadC(fInput->DetElemId(), ix, iy, xpad, ypad, zpad);
3163       dxc[cath] = xreco - xpad;
3164       dyc[cath] = yreco - ypad;
3165     }
3166   }
3167
3168   // Check if pad with max charge at the edge (number of neughbours)
3169   Int_t nn, xList[10], yList[10], neighbx[2][2] = {{0,0}, {0,0}}, neighby[2][2]= {{0,0}, {0,0}};
3170   for (Int_t cath = 0; cath < 2; cath++) {
3171     if (maxdig[cath] < 0) continue;
3172     mdig = fInput->Digit(cath,maxdig[cath]);
3173     fSegmentation[cath]->Neighbours(fInput->DetElemId(),mdig->PadX(),mdig->PadY(),&nn,xList,yList); 
3174     isec = fSegmentation[cath]->Sector(fInput->DetElemId(),mdig->PadX(), mdig->PadY());
3175     //*??
3176     Float_t spr_x = fResponse->SigmaIntegration() * fResponse->ChargeSpreadX();
3177     Float_t spr_y = fResponse->SigmaIntegration() * fResponse->ChargeSpreadY();
3178     //fSegmentation[cath]->FirstPad(fInput->DetElemId(),muons[ihit][1], muons[ihit][2], muons[ihit][3], spr_x, spr_y);  
3179     fSegmentation[cath]->FirstPad(fInput->DetElemId(),xreco, yreco, zreco, spr_x, spr_y);  
3180     Int_t border = 0;
3181     if (fSegmentation[cath]->Sector(fInput->DetElemId(),fSegmentation[cath]->Ix(),fSegmentation[cath]->Iy()) <= 0) {
3182       fSegmentation[cath]->NextPad(fInput->DetElemId());
3183       border = 1;
3184     } 
3185     //*/
3186     for (Int_t j=0; j<nn; j++) {
3187       if (border && yList[j] < fSegmentation[cath]->Iy()) continue;
3188       fSegmentation[cath]->GetPadC (fInput->DetElemId(), xList[j], yList[j], xpad, ypad, zpad);
3189       //cout << ch << " " << xList[j] << " " << yList[j] << " " << border << " " << x << " " << y << " " << xpad << " " << ypad << endl;
3190       if (TMath::Abs(xpad) < 1 && TMath::Abs(ypad) < 1) continue;
3191       if (xList[j] == mdig->PadX()-1 || mdig->PadX() == 1 && 
3192           xList[j] == -1) neighbx[cath][0] = 1;
3193       else if (xList[j] == mdig->PadX()+1 || mdig->PadX() == -1 && 
3194                xList[j] == 1) neighbx[cath][1] = 1;
3195       if (yList[j] == mdig->PadY()-1 || mdig->PadY() == 1 &&
3196           yList[j] == -1) neighby[cath][0] = 1;
3197       else if (yList[j] == mdig->PadY()+1 || mdig->PadY() == -1 &&
3198                yList[j] == 1) neighby[cath][1] = 1;
3199     } // for (Int_t j=0; j<nn;
3200     if (neighbx[cath][0] && neighbx[cath][1]) neighbx[cath][0] = 0;
3201     else if (neighbx[cath][1]) neighbx[cath][0] = -1;
3202     else neighbx[cath][0] = 1;
3203     if (neighby[cath][0] && neighby[cath][1]) neighby[cath][0] = 0;
3204     else if (neighby[cath][1]) neighby[cath][0] = -1;
3205     else neighby[cath][0] = 1;
3206   }
3207
3208   Int_t iOver = clus->GetClusterType();
3209   // One-sided cluster
3210   if (!clus->GetMultiplicity(0)) {
3211     neighby[0][0] = neighby[1][0];
3212     wy[0] = wy[1];
3213     if (iOver < 99) iOver += 100 * iOver;
3214     dyc[0] = dyc[1];
3215   } else if (!clus->GetMultiplicity(1)) {
3216     neighbx[1][0] = neighbx[0][0];
3217     wx[1] = wx[0];
3218     if (iOver < 99) iOver += 100 * iOver;
3219     dxc[1] = dxc[0];
3220   }
3221
3222   // Apply corrections and evaluate errors
3223   Double_t errY, errX;
3224   Errors(nInY, nInX, neighby[0][0],neighbx[1][0], fmin, wy[0]*10, wx[1]*10, iOver, 
3225          dyc[0], dxc[1], qTot, yreco, xreco, errY, errX);
3226   errY = TMath::Max (errY, 0.01);
3227   //errY = 0.01;
3228   //errX = TMath::Max (errX, 0.144);
3229   clus->SetX(0, xreco); clus->SetY(0, yreco);
3230   clus->SetX(1, errX); clus->SetY(1, errY);
3231 }
3232
3233 //_____________________________________________________________________________
3234 void AliMUONClusterFinderAZ::Errors(Int_t ny, Int_t nx, Int_t iby, Int_t ibx, Double_t fmin,
3235                                     Double_t wy, Double_t wx, Int_t iover, 
3236                                     Double_t dyc, Double_t /*dxc*/, Double_t qtot, 
3237                                     Double_t &yrec, Double_t &xrec, Double_t &erry, Double_t &errx)
3238 {
3239   // Correct reconstructed coordinates for some clusters and evaluate errors
3240
3241     erry = 0.01;
3242     errx = 0.144;
3243     Int_t iovery = iover % 100;
3244     Double_t corr = 0;
3245
3246 /* ---> Ny = 1 */
3247     if (ny == 1) {
3248       if (iby != 0) {
3249         // edge effect 
3250         yrec += iby * (0.1823+0.2008)/2;
3251         erry = 0.04587;
3252       } else {
3253         // Find "effective pad width" 
3254         Double_t width = 0.218 / (1.31e-4 * TMath::Exp (2.688 * TMath::Log(qtot)) + 1) * 2;
3255         width = TMath::Min (width, 0.4);
3256         erry = width / TMath::Sqrt(12.);
3257         erry = TMath::Max (erry, 0.01293);
3258       }
3259       goto x; //return;
3260     }
3261
3262 /* ---> "Bad" fit */
3263     if (fmin > 0.4) {
3264       erry = 0.1556;
3265       if (ny == 5) erry = 0.06481;
3266       goto x; //return;
3267     }
3268
3269 /* ---> By != 0 */
3270     if (iby != 0) {
3271       if (ny > 2) {
3272         erry = 0.00417; //0.01010
3273       } else {
3274         // ny = 2 
3275         if (dyc * iby > -0.05) {
3276           Double_t dyc2 = dyc * dyc;
3277           if (iby < 0) {
3278             corr = 0.019 - 0.602 * dyc + 8.739 * dyc2 - 44.209 * dyc2 * dyc;
3279             corr = TMath::Min (corr, TMath::Abs(-0.25-dyc));
3280             yrec -= corr;
3281             //dyc -= corr;
3282             erry = 0.00814;
3283           } else {
3284             corr = 0.006 + 0.300 * dyc + 6.147 * dyc2 + 42.039 * dyc2 * dyc;
3285             corr = TMath::Min (corr, 0.25-dyc);
3286             yrec += corr;
3287             //dyc += corr;
3288             erry = 0.01582;
3289           }
3290         } else {
3291           erry = (0.00303 + 0.00296) / 2;
3292         }
3293       }
3294       goto x; //return;
3295     }
3296
3297 /* ---> Overflows */
3298     if (iovery != 0) {
3299       if (qtot < 3000) {
3300         erry = 0.0671;
3301       } else {
3302         if (iovery > 1) {
3303           erry = 0.09214;
3304         } else if (TMath::Abs(wy - 5) < 0.1) {
3305           erry = 0.061; //0.06622
3306         } else {
3307           erry = 0.00812; // 0.01073 
3308         }
3309       }
3310       goto x; //return;
3311     }
3312
3313 /* ---> "Good" but very high signal */
3314     if (qtot > 4000) {
3315       if (TMath::Abs(wy - 4) < 0.1) {
3316         erry = 0.00117;
3317       } else if (fmin < 0.03 && qtot < 6000) {
3318         erry = 0.01003;
3319       } else {
3320         erry = 0.1931;
3321       }
3322       goto x; //return;
3323     }
3324
3325 /* ---> "Good" clusters */
3326     if (ny > 3) {
3327       if (TMath::Abs(wy - 5) < 0.1) {
3328         erry = 0.0011; //0.00304 
3329       } else if (qtot < 400.) {
3330         erry = 0.0165;
3331       } else {
3332         erry = 0.00135; // 0.00358 
3333       }
3334     } else if (ny == 3) {
3335       if (TMath::Abs(wy - 4) < 0.1) {
3336         erry = 35.407 / (1 + TMath::Exp(5.511*TMath::Log(qtot/265.51))) + 11.564;
3337         //erry = 83.512 / (1 + TMath::Exp(3.344*TMath::Log(qtot/211.58))) + 12.260;
3338       } else {
3339         erry = 147.03 / (1 + TMath::Exp(1.713*TMath::Log(qtot/73.151))) + 9.575;
3340         //erry = 91.743 / (1 + TMath::Exp(2.332*TMath::Log(qtot/151.67))) + 11.453;
3341       }
3342       erry *= 1.e-4;
3343     } else {
3344       // ny = 2 
3345       if (TMath::Abs(wy - 4) < 0.1) {
3346         erry = 60.800 / (1 + TMath::Exp(3.305*TMath::Log(qtot/104.53))) + 11.702;
3347         //erry = 73.128 / (1 + TMath::Exp(5.676*TMath::Log(qtot/120.93))) + 17.839;
3348       } else {
3349         erry = 117.98 / (1 + TMath::Exp(2.005*TMath::Log(qtot/37.649))) + 21.431;
3350         //erry = 99.066 / (1 + TMath::Exp(4.900*TMath::Log(qtot/107.57))) + 25.315;
3351       }
3352       erry *= 1.e-4;
3353     }
3354     //return;
3355
3356  x:
3357 /* ---> X-coordinate */
3358 /* ---> Y-side */    
3359     if (wx > 11) { 
3360       errx = 0.0036;
3361       xrec -= 0.1385;
3362       return;
3363     }
3364 /* ---> Nx = 1 */
3365     if (nx == 1) {
3366       if (TMath::Abs(wx - 6) < 0.1) {
3367         if (qtot < 40) errx = 0.1693;
3368         else errx = 0.06241;
3369       } else if (TMath::Abs(wx - 7.5) < 0.1) {
3370         if (qtot < 40) errx = 0.2173;
3371         else errx = 0.07703;
3372       } else if (TMath::Abs(wx - 10) < 0.1) {
3373         if (ibx == 0) {
3374           if (qtot < 40) errx = 0.2316;
3375           else errx = 0.1426;
3376         } else {
3377           xrec += (0.2115 + 0.1942) / 2 * ibx;
3378           errx = 0.1921;
3379         }
3380       }
3381       return;
3382     }
3383 /* ---> "Bad" fit */
3384     if (fmin > 0.5) {
3385       errx = 0.1591;
3386       return;
3387     }
3388 /* ---> Bx != 0 */
3389     if (ibx != 0) {
3390       if (ibx > 0) { errx = 0.06761; xrec -= 0.03832; }
3391       else { errx = 0.06653; xrec += 0.02581; }
3392       return;
3393     }
3394 /* ---> Overflows */
3395     if (iover != 0) {
3396       if (TMath::Abs(wx - 6) < 0.1) errx = 0.06979;
3397       else if (TMath::Abs(wx - 7.5) < 0.1) errx = 0.1089;
3398       else if (TMath::Abs(wx - 10) < 0.1) errx = 0.09847;
3399       return;
3400     }
3401 /* ---> Good */
3402     if (TMath::Abs(wx - 6) < 0.1) errx = 0.06022;
3403     else if (TMath::Abs(wx - 7.5) < 0.1) errx = 0.07247;
3404     else if (TMath::Abs(wx - 10) < 0.1) errx = 0.07359;
3405 }
3406