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