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