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