]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TRD/AliTRDrawStream.cxx
Correct the baseline subtraction in clusterizer
[u/mrichter/AliRoot.git] / TRD / AliTRDrawStream.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: AliTRDrawStream.cxx 27797 2008-08-05 14:37:22Z cblume $ */
17
18 ///////////////////////////////////////////////////////////////////////////////
19 //                                                                           //
20 // This class provides access to TRD digits in raw data.                     //
21 //                                                                           //
22 // It loops over all TRD digits in the raw data given by the AliRawReader.   //
23 // The Next method goes to the next digit. If there are no digits left       //
24 // it returns kFALSE.                                                        //
25 // Several getters provide information about the current digit.              //
26 //                                                                           //
27 // Author: M. Ploskon (ploskon@ikf.uni-frankfurt.de)                         //
28 // Author: MinJung Kweon (minjung@physi.uni-heidelberg.de)                   //
29 //                                                                           //
30 ///////////////////////////////////////////////////////////////////////////////
31
32 #include "TString.h"
33 #include "TFile.h"
34 //#include "TTreeStream.h"
35
36 #include "AliTRDrawStream.h"
37 #include "AliTRDgeometry.h"
38 #include "AliTRDfeeParam.h"
39 #include "AliTRDdigitsManager.h"
40 #include "AliTRDarrayDictionary.h"
41 #include "AliTRDarrayADC.h"
42 #include "AliTRDSignalIndex.h"
43 #include "AliTRDdigitsParam.h"
44 #include "AliTRDrawTPStream.h"
45
46 //#include "AliLog.h"
47 #include "AliRawReader.h"
48
49 #define END_OF_TRACKLET_MARKEROLD 0xaaaaaaaa
50 #define END_OF_TRACKLET_MARKERNEW 0x10001000
51 #define ENDOFRAWDATAMARKER 0x00000000
52 #define WORD_SIZE sizeof(UInt_t)             // size of a word in bytes
53 #define EXTRA_LEAD_WORDS 24
54 #define CDH_WORDS 8
55
56 #define IS_BIT_SET(w,b) ( ((w) >> (b)) & 0x1 )     // 1 if bit b is set in word w
57 #define GET_VALUE_AT(w,m,s) (( (w) >> (s)) & (m) ) // get value of word w rshifted by s and mask with m
58
59 // SM index word masks:
60 #define SM_HEADER_SIZE(w) GET_VALUE_AT(w,0xffff,16) 
61 #define TRACKLETS_ENABLED(w) IS_BIT_SET(w,5)
62 #define STACK_MASK(w) ((w) & 0x1f)
63
64 // Stack word masks
65 #define STACK_HEADER_SIZE(w) GET_VALUE_AT(w,0xffff,16)
66 #define STACK_LINK_WORD(w) ((w) & 0xfff)
67 #define LINK0_DATA_TYPE_FLAG(w) (GET_VALUE_AT(w,0x3,4) == (0x0) ? 0 : 1)  // 0 if physics data
68 #define LINK1_DATA_TYPE_FLAG(w) (GET_VALUE_AT(w,0x3,20) == (0x0) ? 0 : 1) // 0 if physics data
69 #define LINK0_MONITOR_FLAG(w) (GET_VALUE_AT(w,0xf,0) == (0x0) ? 0 : 1)    // 0 if OK
70 #define LINK1_MONITOR_FLAG(w) (GET_VALUE_AT(w,0xf,16) == (0x0) ? 0 : 1)   // 0 if OK
71
72 // HC word masks
73 #define HC_HEADER_MASK_ERR(w) ( ((w) & (0x3)) == (0x1) ? 0 : 1) // 0 if OK
74
75 // HC word 0
76 #define HC_SPECIAL_RAW_VERSION(w) IS_BIT_SET(w,31)
77 #define HC_MAJOR_RAW_VERSION(w) GET_VALUE_AT(w,0x7f,24)
78 #define HC_MAJOR_RAW_VERSION_OPT(w) GET_VALUE_AT(w,0x7,24)
79 #define HC_MINOR_RAW_VERSION(w) GET_VALUE_AT(w,0x7f,17)
80 #define HC_EXTRA_WORDS(w) GET_VALUE_AT(w,0x7,14)
81 #define HC_DCS_BOARD(w) GET_VALUE_AT(w,0xfff<<20,20)
82 #define HC_SM_NUMBER(w) GET_VALUE_AT(w,0x1f,9)
83 #define HC_LAYER_NUMBER(w) GET_VALUE_AT(w,0x7,6)
84 #define HC_STACK_NUMBER(w) GET_VALUE_AT(w,0x7,3)
85 #define HC_SIDE_NUMBER(w) IS_BIT_SET(w,2)
86
87 // HC word 1
88 #define HC_NTIMEBINS(w) GET_VALUE_AT(w,0x3f,26)
89 #define HC_BUNCH_CROSS_COUNTER(w) GET_VALUE_AT(w,0xffff,10)
90 #define HC_PRETRIGGER_COUNTER(w) GET_VALUE_AT(w,0xf,6)
91 #define HC_PRETRIGGER_PHASE(w) GET_VALUE_AT(w,0xf,2)
92
93 // MCM word and ADC mask
94 #define MCM_HEADER_MASK_ERR(w) ( ((w) & (0xf)) == (0xc) ? 0 : 1)  // 0 if OK
95 #define MCM_ADCMASK_MASK_ERR(w) ( ((w) & (0xf)) == (0xc) ? 0 : 1) // 0 if OK
96 #define MCM_MCM_NUMBER(w) GET_VALUE_AT(w,0x0f,24)
97 #define MCM_ROB_NUMBER(w) GET_VALUE_AT(w,0x7,28)
98 #define MCM_EVENT_COUNTER(w) GET_VALUE_AT(w,0x00fffff,4)
99 #define MCM_ADCMASK_VAL(w) GET_VALUE_AT(w,0x1fffff,4)
100 #define MCM_ADCMASK_NADC(w) GET_VALUE_AT(w,0x1f,25)
101
102 #define MCM_DUMMY_ADCMASK_VAL 0x015fffffc  // updated 
103 #define ADCDATA_VAL1 0x2                   // updated 
104 #define ADCDATA_VAL2 0x3                   // updated 
105
106 #define ADC_WORD_MASK(w) ((w) & 0x3)
107
108 //--------------------------------------------------------
109 ClassImp(AliTRDrawStream)
110
111 Bool_t AliTRDrawStream::fgExtraSkip = kFALSE;
112 Bool_t AliTRDrawStream::fgSkipCDH = kFALSE;
113 Bool_t AliTRDrawStream::fgWarnError = kTRUE;
114 Bool_t AliTRDrawStream::fgCleanDataOnly = kFALSE;
115 Bool_t AliTRDrawStream::fgDebugFlag = kTRUE;
116 Bool_t AliTRDrawStream::fgEnableMemoryReset = kTRUE;
117 Bool_t AliTRDrawStream::fgStackNumberChecker = kTRUE;
118 Bool_t AliTRDrawStream::fgStackLinkNumberChecker = kFALSE;
119 Bool_t AliTRDrawStream::fgSkipData = kTRUE;
120 Bool_t AliTRDrawStream::fgEnableDecodeConfigData = kFALSE;
121 Int_t AliTRDrawStream::fgDumpHead = -1;
122 Int_t AliTRDrawStream::fgEmptySignals[] = 
123   {
124     -1, -1, -1, -1, -1,  -1, -1, -1, -1, -1,  -1, -1, -1, -1, -1
125     -1, -1, -1, -1, -1,  -1, -1, -1, -1, -1,  -1, -1, -1, -1, -1
126   };
127 Short_t AliTRDrawStream::fgMCMordering[] =
128   {
129     12, 13, 14, 15, 8, 9, 10, 11, 4, 5, 6, 7, 0, 1, 2, 3 
130   };
131 Short_t AliTRDrawStream::fgROBordering[] =
132   {
133     0, 1, 2, 3
134   };
135 Int_t  AliTRDrawStream::fgLastHC = -1;
136 Int_t  AliTRDrawStream::fgLastROB = -1;
137 Int_t  AliTRDrawStream::fgLastIndex = -1;
138 Int_t  AliTRDrawStream::fgDumpingSM = -1;
139 Int_t  AliTRDrawStream::fgDumpingStack = -1;
140 Int_t  AliTRDrawStream::fgDumpingLayer = -1;
141 Int_t  AliTRDrawStream::fgDumpingROB = -1;
142 Int_t  AliTRDrawStream::fgDumpingMCM = -1;
143 Bool_t  AliTRDrawStream::fgDumpingEnable = kFALSE;
144
145
146 AliTRDrawStream::AliTRDrawStream()
147   : AliTRDrawStreamBase()
148   , fSM()
149   , fStack(0)
150   , fHC(0)
151   , fLastHC(0)
152   , fMCM(0)
153   , fADC(0)
154   , fpPos(0)
155   , fpBegin(0)
156   , fpEnd(0)
157   , fWordLength(0)
158   , fIsGlobalDigitsParamSet(kFALSE)
159   , fStackNumber(-1)
160   , fStackLinkNumber(-1)
161   , fhcMCMcounter(0)
162   , fmcmADCcounter(0)
163   , fLinkTrackletCounter(-1)
164   , fEndOfTrackletCount(-1)
165   , fNWordsCounter(-1)
166   , fMaskADCword(0)
167   , fTbinADC(0)
168   , fDecodedADCs(-1)
169   , fEventCounter(0)
170   , fLastEventCounter(0)
171   , fSharedPadsOn(kTRUE)
172   , fMaxADCgeom(0)
173   , fBufferRead(0)
174   , fGeometry(0)
175   , fRawReader(0)
176   , fTRDfeeParam(0)
177 {
178   //
179   // default constructor
180   //
181   if (Init() == kFALSE) {
182     AliWarning("Unable to Init.");    
183   }
184 }
185
186 //--------------------------------------------------------
187 AliTRDrawStream::AliTRDrawStream(AliRawReader *rawReader)
188   : AliTRDrawStreamBase(rawReader)
189   , fSM()
190   , fStack(0)
191   , fHC(0)
192   , fLastHC(0)
193   , fMCM(0)
194   , fADC(0)
195   , fpPos(0)
196   , fpBegin(0)
197   , fpEnd(0)
198   , fWordLength(0)
199   , fIsGlobalDigitsParamSet(kFALSE)
200   , fStackNumber(-1)
201   , fStackLinkNumber(-1)
202   , fhcMCMcounter(0)
203   , fmcmADCcounter(0)
204   , fLinkTrackletCounter(-1)
205   , fEndOfTrackletCount(-1)
206   , fNWordsCounter(-1)
207   , fMaskADCword(0)
208   , fTbinADC(0)
209   , fDecodedADCs(-1)
210   , fEventCounter(0)
211   , fLastEventCounter(0)
212   , fSharedPadsOn(kTRUE)
213   , fMaxADCgeom(0)
214   , fBufferRead(0)
215   , fGeometry(0)
216   , fRawReader(rawReader)
217   , fTRDfeeParam(0)
218 {
219   //
220   // default constructor
221   //
222   if (fRawReader) {
223     if (Init() == kFALSE) {
224       AliWarning("Unable to Init. Try setting up the reader with SetReader or buffer with Init(void *, UInt_t )");    
225     }
226   }
227   else {
228     AliWarning("Unable to setup reader. Use SetReader(AliRawReader*).");
229   }
230 }
231
232 //------------------------------------------------------------
233
234 AliTRDrawStream::AliTRDrawStream(const AliTRDrawStream& /*st*/)
235   : AliTRDrawStreamBase()
236   , fSM()
237   , fStack(0)
238   , fHC(0)
239   , fLastHC(0)
240   , fMCM(0)
241   , fADC(0)
242   , fpPos(0)
243   , fpBegin(0)
244   , fpEnd(0)
245   , fWordLength(0)
246   , fIsGlobalDigitsParamSet(kFALSE)
247   , fStackNumber(-1)
248   , fStackLinkNumber(-1)
249   , fhcMCMcounter(0)
250   , fmcmADCcounter(0)
251   , fLinkTrackletCounter(-1)
252   , fEndOfTrackletCount(-1)
253   , fNWordsCounter(-1)
254   , fMaskADCword(0)
255   , fTbinADC(0)
256   , fDecodedADCs(-1)
257   , fEventCounter(0)
258   , fLastEventCounter(0)
259   , fSharedPadsOn(kTRUE)
260   , fMaxADCgeom(0)
261   , fBufferRead(0)
262   , fGeometry(0)
263   , fRawReader(0)
264   , fTRDfeeParam(0)
265 {
266   //
267   // Copy constructor
268   // 
269   AliError("Not implemeneted.");
270 }
271
272 //------------------------------------------------------------
273 Bool_t AliTRDrawStream::SetRawVersion(Int_t fraw)
274 {
275   //
276   // function provided for backward compatibility
277   //
278   AliWarning("Raw data version is read from raw data stream! No point of setting it in here.");
279   fraw = 0; // avoid warnings
280
281   return kFALSE;
282 }
283
284 //------------------------------------------------------------
285 AliTRDrawStream::~AliTRDrawStream()
286 {
287   //
288   // destructor
289   //
290   delete fGeometry;
291 }
292
293 //------------------------------------------------------------
294 AliTRDrawStream & AliTRDrawStream::operator=(const AliTRDrawStream &)
295 {
296   //
297   // we are not using this functionality
298   //
299   AliFatal("May not use.");
300
301   return *this;
302 }
303
304 //___________________________________________________________
305 void AliTRDrawStream::SwapOnEndian()
306 {
307   //
308   // Check the endian and swap if needed
309   //
310   int itemp = 1;
311   char* ptemp = (char*) &itemp;
312   if (ptemp[0] != 1) {
313     if (fgDebugFlag) AliDebug(8, "Swapping.");
314
315     fpPos = fpBegin;
316     UInt_t iutmp = 0;
317     while (fpPos < fpEnd) {
318       fpPos += 1;
319       iutmp = (((*fpPos & 0x000000ffU) << 24) | ((*fpPos & 0x0000ff00U) <<  8) |
320              ((*fpPos & 0x00ff0000U) >>  8) | ((*fpPos & 0xff000000U) >> 24));
321       // here we override the value in the buffer!
322       *fpPos = iutmp;   
323     }
324     fpPos = fpBegin;
325   }
326 }
327
328 //------------------------------------------------------------
329 Bool_t AliTRDrawStream::DumpWords(UInt_t *px, UInt_t iw, UInt_t marker)
330 {
331   //
332   // dump given number of words for debugging
333   //
334   TString tsreturn = Form("\n[ Dump Sequence at 0x%08x ] : ", px);
335   for (UInt_t i = 0; i < iw; i++) {
336      if ( iw != 0 && px + iw > fpEnd) return kFALSE;
337
338      if (i % 8 == 0) tsreturn += "\n                              ";
339      if (marker != 0 && marker == px[i]) tsreturn += Form(" *>0x%08x<* ", px[i]);
340      else tsreturn += Form("0x%08x ", px[i]);
341   }
342   tsreturn += "\n";
343
344   AliInfo(tsreturn.Data());
345
346   return kTRUE;
347 }
348
349 //------------------------------------------------------------
350 Bool_t AliTRDrawStream::SkipWords(UInt_t iw)
351 {
352   //
353   // Skip words corresponding to iw
354   //
355   if ( fpPos + iw < fpEnd ) {
356     fpPos += iw;
357     return kTRUE;
358   }
359   else {
360     if (fgWarnError) AliWarning(Form("Skip %d words failed. %d available", iw, fpEnd - fpPos - 1));
361     return kFALSE;
362   }
363
364   return kTRUE;
365 }
366
367 //------------------------------------------------------------
368 Bool_t AliTRDrawStream::SetReader(AliRawReader * reader)
369 {
370   //
371   // Set reader pointer
372   //
373   if (reader != 0) {
374     fRawReader = reader;
375     if (fRawReader) {
376       return Init();
377     }
378     else {
379       AliWarning("Unable to setup reader.");
380       return kFALSE;
381     }
382   }
383   else {
384     AliWarning("AliRawReader argument is 0.");
385     fRawReader = 0;
386   }
387
388   return kFALSE;
389 }
390
391 //------------------------------------------------------------
392 Int_t AliTRDrawStream::NextBuffer()
393 {
394   //
395   // return -1 if no more buffers available
396   // return  0 DecodeSM failed (clean data required for example) but still maybe more data to come
397   // return  1 DecodeSM OK
398   // 
399   if (fRawReader != 0) {
400     UChar_t *buffer = 0;
401     UInt_t length = 0;
402     Bool_t kBufferSet = fRawReader->ReadNextData(buffer);
403     if (kBufferSet == kTRUE) {
404       if (fgDebugFlag)  AliDebug(9, "Buffer is set.");
405       length = fRawReader->GetDataSize();
406       if (fgExtraSkip == kTRUE) {
407         buffer += EXTRA_LEAD_WORDS * WORD_SIZE;
408         length -= EXTRA_LEAD_WORDS * WORD_SIZE;
409       }
410
411       if (fgSkipCDH == kTRUE) {
412         buffer += CDH_WORDS * WORD_SIZE;
413         length -= CDH_WORDS * WORD_SIZE;
414       }
415
416       if (length > 0) {
417         if (fgDebugFlag)  AliDebug(9, Form("Buffer length : %d", length));
418         if (fgEnableMemoryReset) ResetMemory(); //[mj]
419         if (DecodeSM((void*)buffer, length) == kTRUE)
420           return 1;
421         else
422           return 0;
423       }
424     }
425     else {
426       return -1;
427     }
428   }
429
430   return -1;
431 }
432
433 //------------------------------------------------------------
434 void AliTRDrawStream::ResetCounters()
435 {
436   //
437   // reset some global counters
438   //
439   fBufferRead = kFALSE; // read buffer if it is false (important to read buffer)
440
441   fStackNumber = 0;
442   fStackLinkNumber = 0;
443   fDecodedADCs = 0;
444
445   fSM.fActiveStacks = 0;
446   fSM.fNexpectedHalfChambers = 0;
447
448   fLinkTrackletCounter = 0;
449   fLastEventCounter = 0;
450   fEventCounter = 0;
451 }
452
453 //------------------------------------------------------------
454 void AliTRDrawStream::ResetIterators()
455 {
456   //
457   // reset data which should be reset every sm
458   //
459   fStackNumber = 0;     // reset for Next() function 
460   fStackLinkNumber = 0; // reset for Next() function
461   fhcMCMcounter = 0;  
462   fmcmADCcounter = 0;
463 }
464
465 //------------------------------------------------------------
466 void AliTRDrawStream::ResetPerSM()
467 {
468   //
469   // reset every SM
470   //
471   fSM.fHeaderSize = 0;
472   fSM.fTrackletEnable = kFALSE;
473   fSM.fCorrupted = 0;
474   fSM.fNexpectedHalfChambers = 0;
475   fSM.fNexpectedHalfChambers = 0;
476   fSM.fClean = kTRUE;
477   fSM.fPos = NULL;
478   for (Int_t i=0; i<5; i++){
479     fSM.fStackActive[i] = kFALSE;
480   }
481 }     
482
483 //------------------------------------------------------------
484 void AliTRDrawStream::ResetPerStack()
485 {
486   //
487   // reset every Stack
488   //
489   fStack->fHeaderSize = 0;
490   fStack->fActiveLinks = 0;
491   fStack->fPos = NULL;
492   for (Int_t i=0; i<12; i++){
493     fStack->fLinksActive[i] = kFALSE;
494     fStack->fLinksDataType[i] = 0;
495     fStack->fLinksMonitor[i] = 0;
496     fStack->fLinkMonitorError[i] = 0;
497   }
498 }
499
500 //------------------------------------------------------------
501 void AliTRDrawStream::ResetPerHC()
502 {
503   //
504   // reset every HC
505   //
506   fEventCounter = 0;
507   fHC->fTrackletError = 0;
508   fHC->fNTracklets = 0;
509   fHC->fSpecialRawV = 0;
510   fHC->fRawVMajor = 0;
511   fHC->fRawVMajorOpt = 0;
512   fHC->fRawVMinor = 0;
513   fHC->fNExtraWords = 0;
514   fHC->fDCSboard = 0;
515   fHC->fSM = 0;
516   fHC->fStack = 0;
517   fHC->fLayer = 0;
518   fHC->fSide = 0;
519   fHC->fTimeBins = 0;
520   fHC->fBunchCrossCounter = 0;
521   fHC->fPreTriggerCounter = 0;
522   fHC->fPreTriggerPhase = 0;
523   fHC->fDET = 0;
524   fHC->fROC = 0;
525   fHC->fRowMax = 0;
526   fHC->fColMax = 0;
527   fHC->fMCMmax = 0;
528   fHC->fH0Corrupted = 0;
529   fHC->fH1Corrupted = 0;
530   fHC->fCorrupted = 0;
531 }
532
533 //------------------------------------------------------------
534 void AliTRDrawStream::ResetPerMCM()
535 {
536   //
537   // reset every MCM 
538   //
539   fMCM->fROB = 0;
540   fMCM->fMCM = 0;
541   fMCM->fROW = 0;
542   fMCM->fEvCounter = 0;
543   fMCM->fADCMask = 0;
544   fMCM->fADCMaskWord = 0;
545   fMCM->fADCmax = 0;
546   fMCM->fADCcount = 0;
547   fMCM->fMCMADCWords = 0;
548   fMCM->fSingleADCwords = 0;
549   fMCM->fMCMhdCorrupted = 0;
550   fMCM->fADCmaskCorrupted = 0;
551   fMCM->fCorrupted = 0;
552   fMCM->fPos = NULL;
553   fMCM->fAdcDataPos = NULL;
554   fMCM->fADCcounter = 0;
555
556   memset(fMCM->fADCchannel, 0, TRDMAXADC*sizeof(UInt_t));
557 }
558
559 //------------------------------------------------------------
560 void AliTRDrawStream::ResetPerADC()
561 {
562   //
563   // reset every ADC 
564   //
565   fADC->fPos = NULL;
566   fADC->fADCnumber = 0;
567   fADC->fExtendedCOL = 0;
568   fADC->fCOL = 0;
569   fADC->fIsShared = kTRUE;
570   fADC->fCorrupted = 0;
571
572   //memset(fADC->fSignals, 0, GetNumberOfTimeBins()*sizeof(Int_t));
573   memset(fADC->fSignals, 0, TRDMAXTBINS*sizeof(Int_t)); 
574 }
575
576 //------------------------------------------------------------
577 void AliTRDrawStream::ResetMemory()
578 {                 
579   //              
580   // initialize all the data members to prevent read data from memory for previous buffer 
581   //              
582   ResetPerSM();
583   for (Int_t istack=0; istack<5; istack++){
584      fStack = &fSM.fStacks[istack];
585      ResetPerStack();
586      for (Int_t ilink=0; ilink<12; ilink++){
587         fHC = &fStack->fHalfChambers[ilink];
588         ResetPerHC();
589         for (Int_t imcm=0; imcm<TRDMAXMCM; imcm++){
590            fMCM = &fHC->fMCMs[imcm];
591            ResetPerMCM();
592            for (Int_t iadc=0; iadc<TRDMAXADC; iadc++){
593               fADC = &fMCM->fADCs[iadc];
594               ResetPerADC();
595            } // iadc
596         } // imcm
597      } // ilink     
598   } // istack
599 }         
600
601 //------------------------------------------------------------
602 Bool_t AliTRDrawStream::Next()
603 {
604   //
605   // returns with true on next adc read
606   // returns false on errors and end of buffer
607   // 
608   if (fBufferRead) {
609     while (fStackNumber < 5 && fSM.fActiveStacks > 0) {
610       if (fSM.fStackActive[fStackNumber] == kTRUE) {
611         fStack = &fSM.fStacks[fStackNumber];
612         while (fStackLinkNumber < 12) {
613           if (fStack->fLinksActive[fStackLinkNumber] == kTRUE && fStack->fLinksMonitor[fStackLinkNumber] == 0) {
614             fHC = &fStack->fHalfChambers[fStackLinkNumber];
615             if (!fHC) {
616               AliError(Form("HC missing at stack %d link %d", fStackNumber, fStackLinkNumber));
617               return kFALSE;
618             }
619             if (fHC->fCorrupted == 0 && (fHC->fH0Corrupted == 0 && fHC->fH1Corrupted == 0) | !fgSkipData) { // if HC data corrupted(in any case), we don't read data at all from this HC 
620               while (fhcMCMcounter < fHC->fMCMmax) {
621                 fMCM = &fHC->fMCMs[fhcMCMcounter];
622                 if (!fMCM) {
623                   AliError(Form("HC missing at stack %d link %d atMCMslot %d", 
624                   fStackNumber, fStackLinkNumber, fhcMCMcounter));
625                   return kFALSE;
626                 }
627                 while(fmcmADCcounter < fMCM->fADCmax) {
628                   fADC = &fMCM->fADCs[fmcmADCcounter];
629                   if (!fADC) {
630                     AliError(Form("ADC missing at stack %d link %d MCMslot %d ADCslot %d", 
631                             fStackNumber, fStackLinkNumber, fhcMCMcounter, fmcmADCcounter));
632                     return kFALSE;
633                   }
634                   fmcmADCcounter++;
635                   if (fSharedPadsOn) {
636                     return kTRUE;
637                   }
638                   else {
639                     if (fADC->fIsShared == kFALSE)
640                       return kTRUE;
641                   }
642                 } // while fmcmADCcounter
643                 fhcMCMcounter++;
644                 fmcmADCcounter = 0; // next MCM should go through all active ADCs - start from 0
645               } // while fhcMCMcounter
646             } // if HC OK
647           } // if link active
648           fStackLinkNumber++;
649           fhcMCMcounter = 0; // next stack link (HC) should go through all active MCMs - start from 0
650         } // while fStackLinkNumber
651       } // if stack active
652       fStackNumber++;
653       fStackLinkNumber = 0; // next stack should go through all links - start from 0
654     } // while fStackNumber
655   } // if fBufferRead
656
657   // in case rawreader manages the mem buffers, go for the next buffer 
658   if (fRawReader) {
659     Int_t nextBuff = NextBuffer();
660     while (nextBuff != -1) {
661       if (nextBuff > 0) {
662         fBufferRead = kTRUE;
663         return Next();        
664       }
665       nextBuff = NextBuffer();
666     }
667   }
668
669   return kFALSE;
670 }
671
672 //------------------------------------------------------------
673 Int_t AliTRDrawStream::NextChamber(AliTRDdigitsManager *const digitsManager, UInt_t **trackletContainer, UShort_t **errorCodeContainer) 
674 {
675   //
676   // Fills single chamber digit array 
677   // Return value is the detector number
678   //
679   AliTRDarrayADC *digits = 0;
680   AliTRDarrayDictionary *track0 = 0;
681   AliTRDarrayDictionary *track1 = 0;
682   AliTRDarrayDictionary *track2 = 0; 
683   AliTRDSignalIndex *indexes = 0;
684   AliTRDdigitsParam *digitsparam = 0;
685
686   // Loop through the digits
687   Int_t lastdet = -1;
688   Int_t det     = -1;
689   Int_t lastside = -1; 
690   Int_t side     = -1;
691   Int_t it = 0;
692   Int_t ntracklets = 0;
693
694   if (trackletContainer) { 
695     for (Int_t i = 0; i < 2; i++) 
696       for (Int_t j = 0; j < MAXTRACKLETSPERHC; j++) 
697          trackletContainer[i][j] = 0; 
698   }
699
700   while (Next()) {
701     det    = GetDet();
702     side   = GetSide();
703
704     if (trackletContainer) {
705       if ((det + side*AliTRDgeometry::kNdet) != (lastdet + lastside*AliTRDgeometry::kNdet)) {
706         if (det != lastdet) {
707           if (lastdet != -1) {
708             fmcmADCcounter--; 
709             return lastdet;
710           }
711         }
712         ntracklets = GetNTracklets();
713         if (ntracklets > 0) memcpy(trackletContainer[side], GetTrackletWords(), sizeof(UInt_t) * ntracklets); //copy tracklet words to trackletContainer array
714         lastside = side; 
715       } 
716     } 
717
718     if (det != lastdet) {
719       // If new detector found
720       if (lastdet == -1) {
721         lastdet = det;
722         fLastHC = fHC;
723       }
724       else {
725         fmcmADCcounter--; 
726         fHC = fLastHC ;
727         return lastdet;
728       }
729
730       if (det < 0 || det >= AliTRDgeometry::kNdet) {
731         if (fSM.fClean == kTRUE) {
732           AliError(Form("Strange Det Number %d BUT event buffer seems to be clean.", det));
733         }
734         else {
735           AliError(Form("Strange Det Number %d. Event buffer marked NOT clean!", det));
736         }
737         continue;
738       }
739
740       // Add a container for the digits of this detector
741       digits = (AliTRDarrayADC *) digitsManager->GetDigits(det);
742
743       if (digitsManager->UsesDictionaries()) {
744         track0 = (AliTRDarrayDictionary *) digitsManager->GetDictionary(det,0);
745         track1 = (AliTRDarrayDictionary *) digitsManager->GetDictionary(det,1);
746         track2 = (AliTRDarrayDictionary *) digitsManager->GetDictionary(det,2);
747       }
748
749       if (!digits) {
750         if (fSM.fClean == kTRUE) {
751           AliError(Form("Unable to get digits for det %d BUT event buffer seems to be clean.", det));
752         }
753         else {
754           AliError(Form("Unable to get digits for det %d. Event buffer is NOT clean!", det));
755         }
756         return -1;
757       }
758
759       Int_t rowMax = GetRowMax();
760       Int_t colMax = GetColMax();
761       Int_t ntbins = GetNumberOfTimeBins();
762
763       // Set number of timebin into digitparam
764       if (!fIsGlobalDigitsParamSet){
765         digitsparam = (AliTRDdigitsParam *) digitsManager->GetDigitsParam();
766         digitsparam->SetCheckOCDB(kFALSE);
767         digitsparam->SetNTimeBins(ntbins);
768         digitsparam->SetADCbaseline(10);\r\r
769         digitsparam->SetPretiggerPhase(det,GetPreTriggerPhase());\r\r
770         fIsGlobalDigitsParamSet = kTRUE;
771       }
772       if(!digitsparam){ \r\r
773         digitsparam = (AliTRDdigitsParam *) digitsManager->GetDigitsParam();
774         digitsparam->SetPretiggerPhase(det,GetPreTriggerPhase());\r\r
775       }\r\r
776
777       // Allocate memory space for the digits buffer
778       if (digits->GetNtime() == 0) {
779         digits->Allocate(rowMax, colMax, ntbins);
780         if (digitsManager->UsesDictionaries()) {
781           track0->Allocate(rowMax, colMax, ntbins);
782           track1->Allocate(rowMax, colMax, ntbins);
783           track2->Allocate(rowMax, colMax, ntbins);
784         }
785       }
786
787       indexes = digitsManager->GetIndexes(det);
788       indexes->SetSM(GetSM());
789       indexes->SetStack(GetStack());
790       indexes->SetLayer(GetLayer());
791       indexes->SetDetNumber(det);
792       if (indexes->IsAllocated() == kFALSE)
793         indexes->Allocate(rowMax, colMax, ntbins);
794     }
795
796     // ntimebins data are ready to read
797     for (it = 0; it < GetNumberOfTimeBins(); it++) {
798        if (GetSignals()[it] > 0) {
799
800          if (fSharedPadsOn) 
801            digits->SetDataByAdcCol(GetRow(), GetExtendedCol(), it, GetSignals()[it]);
802          else 
803            digits->SetData(GetRow(), GetCol(), it, GetSignals()[it]);
804
805          indexes->AddIndexRC(GetRow(), GetCol());
806          if (digitsManager->UsesDictionaries()) {
807            track0->SetData(GetRow(), GetCol(), it, 0);
808            track1->SetData(GetRow(), GetCol(), it, 0);
809            track2->SetData(GetRow(), GetCol(), it, 0);
810          }
811        }
812     } // it
813   } // while Next()
814
815   return det;
816 }
817
818 //------------------------------------------------------------
819 Bool_t AliTRDrawStream::Init()
820 {
821   //
822   // Initialize geometry and fee parameters 
823   //
824   TDirectory *saveDir = gDirectory; 
825   
826   if (!fGeometry) {
827     fGeometry = new AliTRDgeometry();
828     if (!fGeometry) {
829       AliError("Geometry FAILED!");
830       return kFALSE;
831     }
832   }
833
834   fTRDfeeParam = AliTRDfeeParam::Instance();
835   if (!fTRDfeeParam) {
836     AliError("AliTRDfeeParam FAILED!");
837     return kFALSE;
838   }
839
840   fMaxADCgeom = (Int_t)fGeometry->ADCmax();
841
842   ResetCounters(); // fBufferRead is set to kFALSE - important
843
844   saveDir->cd();
845
846   return kTRUE;
847 }
848
849 //------------------------------------------------------------
850 Bool_t AliTRDrawStream::InitBuffer(void * const buffer, UInt_t length)
851 {
852   // 
853   // set initial information about the buffer
854   //
855   if (fgDebugFlag)  AliDebug(5, Form("Equipment ID: %d",fRawReader->GetEquipmentId()));
856   if (fRawReader->GetEquipmentId()<1024 || fRawReader->GetEquipmentId()>1041) // tmp protection
857     return kFALSE; 
858
859   if (WORD_SIZE == 0) {
860     AliFatal("Strange word size. size of UInt_t == 0");
861     return kFALSE;
862   }
863
864   ResetCounters();
865
866   fpBegin = (UInt_t *)buffer;
867   fWordLength = length/WORD_SIZE;
868   fpEnd = fpBegin + fWordLength;
869   fpPos = fpBegin;
870
871   if (fpBegin == 0 || length <= 0) {
872     AliError(Form("Buffer size or pointer is strange. pointer to the buffer is 0x%08x of size %d", fpBegin, length));
873     return kFALSE;
874   }
875
876   SwapOnEndian();
877
878   if (fgDumpHead >= 0) {
879     if ( fgDumpHead == 0 ) { // dump all words
880       AliInfo(Form("---------- Dumping all words from the beginnig of the buffer ----------"));
881       if (DumpWords(fpBegin, fWordLength) == kFALSE) AliError("Dump failed. Not enough data.");
882     } 
883     else {
884       AliInfo(Form("---------- Dumping %u words from the beginnig of the buffer ----------",fgDumpHead));
885       if (DumpWords(fpBegin, fgDumpHead) == kFALSE) AliError("Dump failed. Not enough data.");
886     }
887     AliInfo(Form("---------- Dumping ended ----------------------------------------------"));
888   }
889
890   return kTRUE;
891 }
892
893 //------------------------------------------------------------
894 Bool_t AliTRDrawStream::DecodeGTUheader()
895 {
896   // Decode Supermodule Index Word
897   DecodeSMInfo(fpPos, &fSM);
898
899   if (fgDebugFlag)  AliDebug(5, DumpSMInfo(&fSM));
900
901   fpPos++;
902   if (fpPos < fpEnd) {
903     // fSM.fHeaderSize represent additional Supermodule header size which contains additional information regarding hardware design.
904     // For the moment, we skip decoding these words 
905     if (SkipWords(fSM.fHeaderSize) == kTRUE) {
906       for (Int_t istack = 0; istack < 5; istack++) {
907          if (fSM.fStackActive[istack] == kFALSE)
908            continue;
909
910          fStack = &fSM.fStacks[istack];
911
912          // Decode Stack Index Word of given stack
913          DecodeStackInfo(fpPos, fStack);
914          fpPos++;
915
916          fSM.fNexpectedHalfChambers += fStack->fActiveLinks;
917         
918          if (fgDebugFlag)  AliDebug(5, DumpStackInfo(fStack));
919         
920          if (SkipWords(fStack->fHeaderSize-6) == kFALSE) { // 6 is the 6 stack header words for 12 links 
921            if (fRawReader) fRawReader->AddMajorErrorLog(kDecodeStackInfo, "Stack header words missing");
922            return kFALSE;
923          }
924          for (Int_t iword=0; iword<6; iword++) { // decode 6 stack header words
925             // Decode Stack Header Word of given stack
926             DecodeStackHeader(fpPos, fStack, iword); 
927             fpPos++;
928          }
929       }
930     }
931     else {
932       return kFALSE;
933     }
934   }
935   else {
936     if (fgWarnError) AliWarning("No additional sm headers and stack index words present.");
937     if (fRawReader) fRawReader->AddMajorErrorLog(kDecodeStackInfo, "Stack info missing");
938       return kFALSE;
939   }
940
941   if (fpPos < fpEnd) {
942     if (fgDebugFlag)  AliDebug(5, "GTU headers are OK.");
943   }
944   else {
945     if (fgWarnError) AliWarning("No data just after GTU headers.");
946     if (fRawReader) fRawReader->AddMajorErrorLog(kMissingData, "Missing sm data");
947       return kFALSE;
948   }
949
950   if (fgDebugFlag)  AliDebug(5, Form("Expected half chambers from GTU header: %d", fSM.fNexpectedHalfChambers));
951
952   return kTRUE;
953 }
954
955 //------------------------------------------------------------
956 Bool_t AliTRDrawStream::DecodeSM(void * const buffer, UInt_t length)
957 {
958   //
959   // decode one sm data in buffer
960   //
961   ResetIterators(); 
962
963   fSM.fClean = kTRUE;
964   if (InitBuffer(buffer, length) == kFALSE) {
965     if (fgWarnError) AliError("InitBuffer failed.");      
966       fSM.fClean = kFALSE;
967       return kFALSE;
968   }
969
970   if (DecodeGTUheader()== kFALSE)
971     return kFALSE;
972
973   for (Int_t istack = 0; istack < 5; istack++) {
974      fStackNumber = istack; 
975      if (fSM.fStackActive[istack] == kFALSE)
976        continue;
977       
978      fStack = &fSM.fStacks[istack];
979
980      fgLastHC  = -1; // to check rob number odering 
981      for (Int_t ilink = 0; ilink < 12; ilink++) {
982         fStackLinkNumber = ilink; 
983         if (fStack->fLinksActive[ilink] == kFALSE)
984           continue;
985
986         // check GTU link monitor 
987         if (!(fStack->fLinksDataType[ilink] == 0 && fStack->fLinksMonitor[ilink] == 0)) {
988           fStack->fLinkMonitorError[ilink] = 1;
989           SeekEndOfData(); // skip this HC data if GTU link monitor report error
990           fStack->fLinkMonitorError[ilink] += fNWordsCounter; // counts words of given hc having link monitor error
991           continue; 
992         }
993
994         if (fpPos >= fpEnd) {
995           if (fRawReader) fRawReader->AddMajorErrorLog(kLinkDataMissing, "Link data missing");        
996           if (fgWarnError) AliError("Link data missing.");      
997           fSM.fClean = kFALSE;
998           break;
999         }
1000
1001         fHC = &fStack->fHalfChambers[ilink];
1002         ResetPerHC();
1003
1004         if (fSM.fTrackletEnable == kTRUE) {
1005           if (DecodeTracklets() == kFALSE) {
1006             fSM.fClean = kFALSE;
1007             SeekEndOfData();
1008
1009             if (fgWarnError) {
1010               AliError(Form("Tracklet decoding failed stack %d link %d", fStackNumber, fStackLinkNumber));
1011             }
1012             continue;
1013           }
1014         }
1015
1016         if (fpPos >= fpEnd) {
1017           if (fRawReader) fRawReader->AddMajorErrorLog(kHCdataMissing, "HC data missing");        
1018           if (fgWarnError) AliError("HC data missing.");      
1019           fSM.fClean = kFALSE;
1020           break;
1021         }
1022     
1023         fgLastROB   = -1; // to check mcm number odering 
1024         fgLastIndex = -1 ; // to check mcm number odering 
1025         if (DecodeHC() == kFALSE) {
1026           fSM.fClean = kFALSE;
1027           if (fHC->fCorrupted < 16)  SeekEndOfData(); // In case that we meet END_OF_TRACKLET_MARKERNEW 
1028                                                       // during ADC data decoding or MCM header decoding
1029                                                       // we don't seek ENDOFRAWDATAMARKER
1030           if (fgWarnError) {
1031             AliError(Form("Failed HC : %s", DumpHCinfoH0(fHC)));
1032             AliError(Form("Failed HC : %s", DumpHCinfoH1(fHC)));
1033           }
1034                 
1035           continue;
1036         }
1037         else {
1038           SeekEndOfData(); // make sure that finish off with the end of data markers
1039         }
1040      } // ilink
1041   } // istack
1042
1043   ResetIterators(); // need to do it again for Next() function 
1044
1045   if (fSM.fClean == kTRUE)
1046     return kTRUE;
1047   
1048   if (fgCleanDataOnly && (fSM.fClean == kFALSE)) {
1049     if (fgWarnError) {
1050       AliWarning("Buffer with errors. Returning FALSE.");
1051       AliWarning(Form("--- Failed SM : %s ---", DumpSMInfo(&fSM)));
1052     }
1053     fSM.fActiveStacks = 0; // Next() will not give data
1054     return kFALSE;
1055   }
1056
1057   return kTRUE;
1058 }
1059
1060 //------------------------------------------------------------
1061 Int_t AliTRDrawStream::DecodeSM()
1062 {
1063   //
1064   // decode SM data in case AliRawReader is in use
1065   //    
1066   if (fRawReader) {
1067     Int_t nextBuff = NextBuffer();
1068     while (nextBuff != -1) {
1069       if (nextBuff > 0)
1070         return nextBuff;        
1071       nextBuff = NextBuffer();
1072     }
1073     return -1;
1074   }
1075   else {
1076     AliWarning("AliRawReader not set.");
1077   }
1078
1079   return kFALSE;
1080 }
1081
1082 //------------------------------------------------------------
1083 Int_t AliTRDrawStream::DecodeSM(AliRawReader *reader)
1084 {
1085   //
1086   // decode SM with the AliRawReader
1087   //
1088   if (reader != 0) {
1089     fRawReader = reader;
1090     return DecodeSM();
1091   }
1092   else {
1093     AliWarning("Argument AliRawReader is 0.");
1094   }
1095
1096   return kFALSE;
1097 }
1098
1099 //------------------------------------------------------------
1100 Bool_t AliTRDrawStream::SeekEndOfData()
1101 {
1102   //
1103   // go to end of data marker
1104   //
1105   Int_t fEndOfDataCount = 0;
1106   fNWordsCounter = 0;
1107
1108   while ( *fpPos != ENDOFRAWDATAMARKER && fpPos < fpEnd ) {
1109     fpPos++;
1110     fNWordsCounter++;
1111   }
1112   while (*fpPos == ENDOFRAWDATAMARKER && fpPos < fpEnd ) {
1113     fEndOfDataCount++;
1114     fpPos++;      
1115   }
1116   
1117   return kTRUE;
1118 }
1119
1120 //------------------------------------------------------------
1121 Bool_t AliTRDrawStream::SkipMCMdata(UInt_t iw)
1122 {
1123   //
1124   // skip mcm data words due to corruption 
1125   //
1126   if (fgDebugFlag) AliDebug(11,Form("Skip %d words due to MCM header corruption.",iw));
1127   UInt_t iwcounter = 0;  
1128   while ( *fpPos != ENDOFRAWDATAMARKER && iwcounter < iw) {
1129     if ( *fpPos == END_OF_TRACKLET_MARKERNEW) {
1130       if (fgDebugFlag) AliDebug(11,"Met END_OF_TRACKLET_MARKERNEW");
1131       fMCM->fCorrupted += 16;
1132       fHC->fCorrupted += 16;
1133       return kFALSE;
1134     } 
1135     fpPos++;
1136     iwcounter++; 
1137   }
1138
1139   if (iwcounter == iw) {
1140     fpPos++;
1141     return kTRUE;
1142   }
1143
1144   if (fgDebugFlag) AliDebug(11,"Met ENDOFRAWDATAMARKER");
1145
1146   return kFALSE;
1147 }
1148
1149 //------------------------------------------------------------
1150 Bool_t AliTRDrawStream::SeekNextMCMheader()
1151 {
1152   //
1153   // go to mcm marker
1154   //
1155   fpPos++;
1156
1157   while ( *fpPos != ENDOFRAWDATAMARKER && fpPos < fpEnd ) {
1158     if (MCM_HEADER_MASK_ERR(*fpPos) == 0 && MCM_HEADER_MASK_ERR(*(fpPos+1)) == 0) {      
1159       if (fgDebugFlag) AliDebug(11,Form("^^^ Found : Pos 0x%08x : Val 0x%08x", fpPos, *fpPos));
1160       return kTRUE;
1161     }
1162     if ( *fpPos == END_OF_TRACKLET_MARKERNEW) {
1163       fMCM->fCorrupted += 16;
1164       fHC->fCorrupted += 16;
1165       return kFALSE;
1166     } 
1167     fpPos++;
1168   }
1169
1170   SeekEndOfData();
1171
1172   return kFALSE;
1173 }
1174
1175 //------------------------------------------------------------
1176 Bool_t AliTRDrawStream::DecodeTracklets()
1177 {
1178   //
1179   // decode tracklets
1180   //
1181   fLinkTrackletCounter = 0;
1182   fEndOfTrackletCount = 0;
1183   fHC->fNTracklets = 0;
1184
1185   for (Int_t i = 0; i < MAXTRACKLETSPERHC; i++) 
1186      fHC->fTrackletWords[i] = 0; 
1187
1188   if (fgDebugFlag)  AliDebug(10, Form("Decode tracklets at 0x%08x : 0x%08x", fpPos, *fpPos));
1189
1190   while ( *fpPos != END_OF_TRACKLET_MARKEROLD && *fpPos != END_OF_TRACKLET_MARKERNEW && fpPos < fpEnd ) {
1191     if (fgDebugFlag)  AliDebug(10, Form("Tracklet found at 0x%08x : 0x%08x", fpPos, *fpPos));
1192
1193     fLinkTrackletCounter++;
1194
1195     if (fLinkTrackletCounter > MAXTRACKLETSPERHC) {
1196       if (fgDebugFlag) AliDebug(11,Form("Max number of tracklets exceeded %d > %d.", 
1197                                         fLinkTrackletCounter, MAXTRACKLETSPERHC));
1198       if (fRawReader) fRawReader->AddMajorErrorLog(kTrackletOverflow,"Too many tracklets"); 
1199       fHC->fTrackletError = 1;
1200       return kFALSE;
1201     }
1202
1203     fHC->fTrackletWords[fLinkTrackletCounter-1] = UInt_t(*fpPos); //store tracklet words into array  
1204     fHC->fNTracklets = fLinkTrackletCounter;
1205     fpPos++;
1206   }
1207
1208   while ( ( *fpPos == END_OF_TRACKLET_MARKEROLD || *fpPos == END_OF_TRACKLET_MARKERNEW ) && fpPos < fpEnd ) {
1209     if (fgDebugFlag)  AliDebug(10, Form("EoTracklets found at 0x%08x : 0x%08x", fpPos, *fpPos));
1210
1211     fEndOfTrackletCount++;
1212     fpPos++;
1213   }
1214
1215   if ( fEndOfTrackletCount < 2 ) {
1216     if (fgDebugFlag) AliDebug(11,"End of tracklets word missing"); 
1217     if (fRawReader) fRawReader->AddMajorErrorLog(kEOTrackeltsMissing, "End of tracklets word missing"); 
1218     fHC->fTrackletError += 2;
1219     return kFALSE;
1220   }
1221
1222   return kTRUE;
1223 }
1224
1225 //------------------------------------------------------------
1226 Bool_t AliTRDrawStream::IsRowValid()
1227 {
1228   //
1229   // check if the row number is in valid range
1230   //
1231   if ( (fHC->fStack == 2 && fMCM->fROW >= fGeometry->RowmaxC0()) ||
1232       (fHC->fStack != 2 && fMCM->fROW >= fGeometry->RowmaxC1()) || fMCM->fROW < 0 ) {
1233     if (fgDebugFlag) AliDebug(11,Form("SM%d L%dS%d: Wrong Padrow (%d) fROB=%d, fSIDE=%d, fMCM=%02d"
1234                                       , fHC->fSM, fHC->fLayer, fHC->fStack, fMCM->fROW, fMCM->fROB, fHC->fSide, fMCM->fMCM ));
1235     return kFALSE;
1236   }
1237
1238   return kTRUE;
1239 }
1240
1241 //------------------------------------------------------------
1242 Bool_t AliTRDrawStream::IsMCMheaderOK()
1243 {
1244   //
1245   // check the mcm header
1246   //
1247   if (fgLastROB != fMCM->fROB) {
1248     fgLastIndex = 0;
1249     if (fgLastROB== -1) fgLastROB = fMCM->fROB;
1250   }
1251   else {
1252     Int_t matchingcounter = 0; 
1253     for (Int_t i=fgLastIndex+1; i<16; i++) {
1254        if ( fMCM->fMCM == fgMCMordering[i] ) {
1255          fgLastIndex = i;
1256          matchingcounter++;
1257          break;
1258        }
1259     }
1260     if (matchingcounter == 0) {  
1261       fMCM->fMCMhdCorrupted += 2;
1262       AliDebug(11,Form("MCM number from last MCM is larger: MCM # from last MCM %d,  MCM # from current MCM %d \n",(fMCM-1)->fMCM, fMCM->fMCM));
1263     }
1264   }
1265
1266   if ( fgLastHC == fHC->fLayer*2 + fHC->fSide ) {
1267     if ( fMCM->fROB < (fMCM-1)->fROB ) {
1268       fMCM->fMCMhdCorrupted += 2;
1269       AliDebug(11,Form("ROB number from last MCM is larger: ROB # from last MCM %d,  ROB # from current MCM %d \n",(fMCM-1)->fROB, fMCM->fROB));
1270     }
1271     else fgLastROB = fMCM->fROB; 
1272   }
1273
1274   fgLastHC = fHC->fLayer*2 + fHC->fSide; 
1275
1276   /*
1277   // this check will come back later again when we have "patched MCM map"
1278   int expectedROB = -1;
1279   if(!fHC->fSide) expectedROB = int(fHC->fMCMmax/16)*2;
1280   else expectedROB = int(fHC->fMCMmax/16)*2 + 1;
1281   int expectedMCM = 4*(3-int((fHC->fMCMmax%16)/4)) + fHC->fMCMmax%4;
1282
1283   if ( expectedROB != fMCM->fROB || expectedMCM != fMCM->fMCM)
1284     {
1285       fMCM->fMCMhdCorrupted += 2;
1286       AliDebug(11,Form("ROB expected %d ROB read %d,  MCM expected %d MCM read %d\n",expectedROB, fMCM->fROB, expectedMCM, fMCM->fMCM));
1287     }
1288   */
1289
1290   // below two conditions are redundant  
1291   /*
1292   if ( fMCM->fMCM < 0 || fMCM->fMCM > 15 || fMCM->fROB < 0 || fMCM->fROB > 7 ) 
1293     {
1294       fMCM->fMCMhdCorrupted += 8;  // need to assign new number
1295       if (fgDebugFlag) AliDebug(11,Form("ROB or MCM number is out of range. %s\n", DumpMCMinfo(fMCM)));
1296     }
1297   if (IsRowValid() == kFALSE)
1298     {
1299       fMCM->fMCMhdCorrupted += 16; // need to assign new number
1300     }
1301   */  
1302     
1303   if (fEventCounter == 0) {
1304     fEventCounter = fMCM->fEvCounter;
1305   }
1306
1307   if (fEventCounter != fMCM->fEvCounter) {
1308     fMCM->fMCMhdCorrupted += 4;      
1309     if (fgDebugFlag) AliDebug(11,Form("Event number(%d) of current MCM is different from that(%d) of reference MCM %s.\n"
1310                                       , fMCM->fEvCounter, fEventCounter, DumpMCMinfo(fMCM)));
1311   }
1312
1313   if (fEventCounter < fLastEventCounter) {
1314     fMCM->fMCMhdCorrupted += 8;      
1315     if (fgDebugFlag) AliDebug(11,Form("Event from the past? Current %d Last %d %s.\n", fEventCounter, fLastEventCounter, DumpMCMinfo(fMCM)));
1316   }
1317
1318   if ( fMCM->fADCmaskCorrupted > 0 )
1319     return kFALSE;
1320
1321   if ( fMCM->fMCMhdCorrupted > 0 )
1322     return kFALSE;
1323
1324   return kTRUE;
1325 }
1326
1327 //------------------------------------------------------------
1328 Bool_t AliTRDrawStream::DecodeMCMheader()
1329 {
1330   //
1331   // decode the mcm header
1332   //
1333   DecodeMCMheader(fpPos, fMCM); 
1334
1335   if (fgDumpingEnable) { 
1336     if (fMCM->fMCM == fgDumpingMCM) {
1337       if (fMCM->fROB == fgDumpingROB && fHC->fLayer == fgDumpingLayer) {
1338         if (fHC->fSM == fgDumpingSM && fHC->fStack == fgDumpingStack) {
1339           if (fgDebugFlag) {
1340             AliDebug(5,DumpHCinfoH0(fHC));
1341             AliDebug(5,DumpMCMinfo(fMCM));
1342           }
1343           DumpWords(fpPos, 212);
1344         }  
1345       }
1346     }
1347   }
1348
1349   if (fHC->fCorrupted >= 16) {
1350     fpPos--; 
1351     return kFALSE;
1352   }
1353
1354   fMCM->fROW = fTRDfeeParam->GetPadRowFromMCM(fMCM->fROB, fMCM->fMCM); 
1355
1356   if ((fHC->fRawVMajor > 2 && fHC->fRawVMajor <5) || ((fHC->fRawVMajor & 32) == 32)) { //cover old and new version definition of ZS data
1357     fpPos++;
1358     if ( fpPos < fpEnd ) {
1359       DecodeMask(fpPos, fMCM); 
1360       if (fHC->fCorrupted >= 16) {
1361         fpPos--; 
1362         return kFALSE;
1363       }
1364       MCMADCwordsWithTbins(fHC->fTimeBins, fMCM);
1365       fMCM->fAdcDataPos = fpPos + 1;
1366     }
1367     else {
1368       if (fgDebugFlag) AliDebug(11,"Expected ADC mask word. Fail due to buffer END.");    
1369       if (fRawReader) fRawReader->AddMajorErrorLog(kMCMADCMaskMissing,"Missing"); 
1370       fHC->fCorrupted += 32;
1371       return kFALSE;
1372     }
1373   }
1374   else {
1375     UInt_t dummyMask = MCM_DUMMY_ADCMASK_VAL;
1376     DecodeMask(&dummyMask, fMCM); 
1377     MCMADCwordsWithTbins(fHC->fTimeBins, fMCM);
1378     fMCM->fAdcDataPos = fpPos + 1;
1379   }
1380
1381   if (fgDebugFlag) { 
1382     AliDebug(6, DumpMCMinfo(fMCM));
1383     AliDebug(7, DumpMCMadcMask(fMCM));
1384   }
1385
1386   if (IsMCMheaderOK() == kFALSE)
1387     return kFALSE;
1388     
1389   return kTRUE;
1390 }
1391
1392 //------------------------------------------------------------
1393 Bool_t AliTRDrawStream::IsHCheaderOK()
1394 {
1395   //
1396   // check insanity of half chamber header
1397   //
1398   if (fHC->fStack < 0 || fHC->fStack > 4) {
1399     if (fgDebugFlag) AliDebug(11,Form("Wrong Stack %d", fHC->fStack));
1400       return kFALSE;
1401   }
1402
1403   if (fHC->fLayer < 0 || fHC->fLayer >= AliTRDgeometry::kNlayer) {
1404     if (fgDebugFlag) AliDebug(11,Form("Wrong layer %d", fHC->fLayer));
1405       return kFALSE;
1406   }
1407
1408   if (fHC->fSide < 0 || fHC->fSide > 1) {
1409     if (fgDebugFlag) AliDebug(11,Form("Wrong Side %d", fHC->fSide));
1410       return kFALSE;
1411   }
1412
1413   if (fgStackNumberChecker) {
1414     if (fHC->fStack != fStackNumber) {
1415       if (fgDebugFlag) AliDebug(11,Form("Missmatch: Stack number between HC header %d and GTU link mask %d", 
1416                                         fHC->fStack, fStackNumber));
1417       fStackNumber = -1;
1418       return kFALSE;
1419     }
1420   }
1421
1422   if (fgStackLinkNumberChecker) {
1423     if (fHC->fLayer * 2 + fHC->fSide != fStackLinkNumber) {
1424     // let it make flexible to consider known fiber swapping
1425     //if ((fHC->fLayer * 2 != fStackLinkNumber) && (fHC->fLayer * 2 != fStackLinkNumber - 1)) { 
1426       if (fgDebugFlag) AliDebug(11,Form("Missmatch: Layer number between HC header %d and GTU link mask %d | %s", 
1427                                         fHC->fLayer, fStackLinkNumber, DumpStackInfo(fStack)));
1428       fStackLinkNumber = -1;
1429       return kFALSE;      
1430     }
1431   }
1432
1433   // SLOW GEOM : consistancy check with geometry
1434   fHC->fDET = fGeometry->GetDetector(fHC->fLayer, fHC->fStack, fHC->fSM);
1435   if (fHC->fDET < 0 || fHC->fDET >= AliTRDgeometry::kNdet) {
1436     if (fgDebugFlag) AliDebug(11,Form("Wrong detector %d", fHC->fDET));      
1437     if (fRawReader) fRawReader->AddMajorErrorLog(kHCHeaderWrongDet, "Wrong Det");       
1438     return kFALSE;
1439   }
1440
1441   if (fHC->fSM != fGeometry->GetSector(fHC->fDET) || fHC->fSM <0 || fHC->fSM >= AliTRDgeometry::kNsector) {
1442     if (fgDebugFlag) AliDebug(11,Form("Wrong SM(sector) %d (Geometry says: %d) Stack=%d Layer=%d Det=%d", 
1443                                       fHC->fSM, fGeometry->GetSector(fHC->fDET), fHC->fStack, fHC->fLayer, fHC->fDET));
1444     if (fRawReader) fRawReader->AddMajorErrorLog(kHCHeaderWrongSM, "Wrong SM");       
1445     return kFALSE;
1446   }
1447
1448   fHC->fROC    = fGeometry->GetDetectorSec(fHC->fLayer, fHC->fStack);
1449   if (fHC->fROC < 0) {
1450     if (fRawReader) fRawReader->AddMajorErrorLog(kHCHeaderWrongROC, "Wrong ROC");       
1451     return kFALSE;
1452   }
1453
1454   fHC->fRowMax = fGeometry->GetRowMax(fHC->fLayer, fHC->fStack, fHC->fSM);
1455   if (fHC->fRowMax < 1) {
1456     if (fRawReader) fRawReader->AddMajorErrorLog(kHCHeaderWrongROC, "Wrong ROC Row Max");       
1457     return kFALSE;
1458   }
1459
1460   fHC->fColMax = fGeometry->GetColMax(fHC->fROC);
1461   if (fHC->fColMax < 1) {
1462     if (fRawReader) fRawReader->AddMajorErrorLog(kHCHeaderWrongROC, "Wrong ROC Col Max");       
1463     return kFALSE;
1464   }
1465   
1466   return kTRUE;
1467 }
1468
1469 //------------------------------------------------------------
1470 Bool_t AliTRDrawStream::DecodeHCheader()
1471 {  
1472   //
1473   // decode the half chamber header
1474   //
1475   if (DecodeHCwordH0(fpPos, fHC) == kFALSE)
1476     return kFALSE;
1477     
1478   if (fHC->fNExtraWords > 0) {
1479     fpPos++;
1480     if (fpPos < fpEnd) {
1481       if (DecodeHCwordH1(fpPos, fHC) == kFALSE)
1482         return kFALSE;
1483     }
1484     else {
1485       if (fgDebugFlag) AliDebug(11,"Expected HC header word 1. Fail due to buffer END.");
1486       if (fRawReader) fRawReader->AddMajorErrorLog(kHCWordMissing,"Next HC word 1 (count from 0) missing"); 
1487       return kFALSE;
1488     }
1489   }
1490
1491   if (fgDebugFlag)  AliDebug(5, DumpHCinfoH0(fHC));
1492   if (fgDebugFlag)  AliDebug(5, DumpHCinfoH1(fHC));
1493
1494   fHC->fDET = -1;
1495   if (IsHCheaderOK() == kFALSE) {
1496     fHC->fH0Corrupted += 2;
1497     if (fgDebugFlag) AliDebug(11,Form("H0 Header Insane. Word 0x%08x", *fHC->fPos));
1498       return kFALSE;
1499   }
1500   
1501   return kTRUE;
1502 }
1503
1504 //------------------------------------------------------------
1505 Bool_t AliTRDrawStream::DecodeHC()
1506 {
1507   //
1508   // decode hc header and data
1509   //
1510   if (DecodeHCheader() == kFALSE) {
1511     if (fgWarnError) AliWarning(Form("HC Header decode failed. H0 Error: %d H1 Error: %d",fHC->fH0Corrupted,fHC->fH1Corrupted));
1512     if (fRawReader) fRawReader->AddMajorErrorLog(kHCHeaderCorrupt, "HC header corrupted"); 
1513     return kFALSE;
1514   }
1515   else {
1516     fpPos++;
1517     if (fpPos >= fpEnd) {
1518       fHC->fCorrupted += 1;
1519       if (fgDebugFlag) AliDebug(11,"No MCM data? Not enough data in the buffer.");
1520       if (fRawReader) fRawReader->AddMajorErrorLog(kMCMdataMissing, "MCM data missing"); 
1521       return kFALSE;
1522     }
1523   }
1524
1525   if ((fHC->fRawVMajor & 64) == 64) { // test pattern data
1526     AliTRDrawTPStream *tpStream = new AliTRDrawTPStream(fHC->fRawVMajorOpt, fpPos);
1527     if (tpStream->DecodeTPdata() == kFALSE) {
1528       if (fgWarnError) AliError("failed to decode test pattern data");
1529         return kFALSE; 
1530     }
1531     return kTRUE;
1532   } 
1533
1534   fHC->fMCMmax = 0;
1535   while (*fpPos != ENDOFRAWDATAMARKER && fpPos < fpEnd) {
1536     if (fHC->fMCMmax > TRDMAXMCM) {
1537       fHC->fCorrupted += 2;
1538       if (fgDebugFlag) AliDebug(11,"More mcm data than expected!");
1539       if (fRawReader) fRawReader->AddMajorErrorLog(kMCMoverflow, "Too many mcms found!"); 
1540       return kFALSE;
1541     }
1542
1543     fMCM = &fHC->fMCMs[fHC->fMCMmax];
1544
1545     if (DecodeMCMheader() == kFALSE) {
1546       if (fHC->fCorrupted < 4) fHC->fCorrupted += 4; // benchmark hc data corruption as 4
1547     
1548       if (fgSkipData == kTRUE || fHC->fCorrupted >= 16) { // stop HC data reading
1549         fHC->fMCMmax++; 
1550         return kFALSE;
1551       } 
1552           
1553       fHC->fMCMmax++; // increase mcm counter to match with expected rob/mcm number
1554
1555       // in case we decide to keep reading data, skip this mcm data and find next mcm header 
1556       if (fMCM->fADCmaskCorrupted < 2) {
1557         if (SkipMCMdata(fMCM->fADCcount*fMCM->fSingleADCwords) == kFALSE)
1558           return kFALSE;
1559         continue;
1560       }
1561       else {
1562         if (SeekNextMCMheader() == kFALSE)
1563           return kFALSE;
1564         continue;
1565       }
1566     }
1567
1568     fHC->fMCMmax++;
1569
1570     if (fMCM->fADCmax > 0) {
1571       fpPos++;
1572       if (fpPos >= fpEnd) {
1573         fMCM->fCorrupted += 1;
1574         if (fHC->fCorrupted < 4) fHC->fCorrupted += 4; // benchmark hc data corruption as 4
1575         if (fgDebugFlag)  AliDebug(9, Form("Buffer short of data. ADC data expected."));    
1576         return kFALSE;
1577       }
1578
1579       for (Int_t iadc = 0; iadc < fMCM->fADCmax; iadc++) {
1580          fADC = &fMCM->fADCs[iadc];
1581          fADC->fADCnumber = fMCM->fADCchannel[iadc];
1582          if (fgDebugFlag)  AliDebug(9, Form("This is ADC %d of %d. ADC number is %d.", 
1583                                             iadc+1, fMCM->fADCmax, fMCM->fADCchannel[iadc]));
1584          if (fpPos + fMCM->fSingleADCwords >= fpEnd) {
1585            fMCM->fCorrupted += 2;
1586            if (fHC->fCorrupted < 4) fHC->fCorrupted += 4; // benchmark hc data corruption as 4
1587            if (fgDebugFlag) AliDebug(11,"ADC (10 words) expected. Not enough data in the buffer.");
1588            return kFALSE;
1589          }
1590
1591          if (fHC->fRawVMajor < 64) { // normal(real) ADC data
1592            if (fHC->fTimeBins < 31) {
1593              if (DecodeADC() == kFALSE) {
1594                if (fMCM->fCorrupted < 4) fMCM->fCorrupted += 4; // benchmark mcm data corruption as 4
1595                if (fHC->fCorrupted < 4) fHC->fCorrupted += 4;   // benchmark hc data corruption as 4
1596                if (fADC->fIsShared && fADC->fCorrupted == 32) { // check if we are out of the det when the pad is shared
1597                  fADC->fExtendedCOL = -1;
1598                  fADC->fCOL = -1;
1599                  fpPos = fADC->fPos + fMCM->fSingleADCwords;
1600                }
1601                else {
1602                  if (fgDebugFlag) AliDebug(11,Form("ADC decode failed."));
1603                  if (fgSkipData == kTRUE || fHC->fCorrupted >= 16) 
1604                    return kFALSE; // stop HC data reading
1605                }
1606              }
1607            }
1608            else if (fHC->fTimeBins > 32) {
1609              if (DecodeADCExtended() == kFALSE) { // decoding TRAP data with ZS and more than 32 samples
1610                if (fMCM->fCorrupted < 4) fMCM->fCorrupted += 4; // benchmark mcm data corruption as 4
1611                if (fHC->fCorrupted < 4) fHC->fCorrupted += 4;   // benchmark hc data corruption as 4
1612                if (fADC->fIsShared && fADC->fCorrupted == 32) { // check if we are out of the det when the pad is shared
1613                  fADC->fExtendedCOL = -1;
1614                  fADC->fCOL = -1;
1615                  fpPos = fADC->fPos + fMCM->fSingleADCwords;
1616                }
1617                else {
1618                  if (fgDebugFlag) AliDebug(11,Form("ADC decode failed."));
1619                  if (fgSkipData == kTRUE || fHC->fCorrupted >= 16)
1620                    return kFALSE; // stop HC data reading
1621                }
1622              }
1623            }
1624            else { // nsamples = 31, 32 are not implemented in the TRAP and should never happen  
1625              if (fgWarnError) AliError("nsamples are 31 or 32. These are not implemented in the TRAP and should never happen!"); 
1626            }
1627          } // if fHC->fRawVMajor
1628          else { // test pattern data
1629            if (fgWarnError) AliError("These are test pattern data. You need other reader"); // will be served in other class
1630          }
1631       } // for iadc 
1632     } // if fMCM->fADCmax
1633     else {
1634       fpPos++;
1635     }
1636   }//while eof data
1637
1638   if (fpPos >= fpEnd) {
1639     if (fgDebugFlag) AliDebug(11,"We are at the end of buffer. There should be one more word left.");
1640     return kFALSE;
1641   }
1642
1643   return kTRUE;
1644 }
1645
1646 //------------------------------------------------------------
1647 Bool_t AliTRDrawStream::DecodeADC()
1648 {
1649   //
1650   // decode single ADC channel
1651   //
1652
1653   UInt_t commonAdditive = AliTRDrawStreamBase::fgCommonAdditive;
1654
1655   fADC->fCorrupted = 0;
1656   if(fADC->fADCnumber%2==1) fMaskADCword = ADC_WORD_MASK(ADCDATA_VAL1);
1657   if(fADC->fADCnumber%2==0) fMaskADCword = ADC_WORD_MASK(ADCDATA_VAL2);
1658
1659   fADC->fPos = fpPos;
1660   fTbinADC = 0;
1661
1662   for (Int_t i = 0; i < GetNumberOfTimeBins(); i++)
1663   //for (Int_t i = 0; i < TRDMAXTBINS; i++)
1664     fADC->fSignals[i] = 0;
1665
1666   for (Int_t iw = 0; iw < fMCM->fSingleADCwords; iw++) {
1667      if (HC_HEADER_MASK_ERR(*fpPos) == 0 || *fpPos == END_OF_TRACKLET_MARKERNEW) {
1668        if (fgWarnError) AliError(Form("There should be ADC data. We meet HC header or END_OF_TRACKLET_MARKER 0x%08x",*fpPos));
1669        fADC->fCorrupted += 16;
1670        fHC->fCorrupted += 16; 
1671        fpPos--;
1672        return kFALSE;
1673      }
1674      if (fMaskADCword != ADC_WORD_MASK(*fpPos)) {
1675        fADC->fCorrupted += 1;
1676        if (fgDebugFlag) AliDebug(11,Form("Wrong ADC data mask! ADC channel number: %02d [Expected mask: 0x%08x  Current mask: 0x%08x] MCM= %s Error : %d",
1677                                          fADC->fADCnumber, fMaskADCword, ADC_WORD_MASK(*fpPos),DumpMCMinfo(fMCM),fADC->fCorrupted));
1678        fpPos++;
1679        continue;
1680      }
1681
1682      // here we subtract the baseline ( == common additive)
1683      fADC->fSignals[fTbinADC + 0] = ((*fpPos & 0x00000ffc) >>  2) - commonAdditive;
1684      fADC->fSignals[fTbinADC + 1] = ((*fpPos & 0x003ff000) >> 12) - commonAdditive;
1685      fADC->fSignals[fTbinADC + 2] = ((*fpPos & 0xffc00000) >> 22) - commonAdditive;
1686
1687      fTbinADC += 3;
1688      fpPos++;
1689   } // iw
1690
1691   if (fADC->fADCnumber <= 1 || fADC->fADCnumber == fMaxADCgeom - 1) {
1692     fADC->fIsShared = kTRUE;
1693   }
1694   else {
1695     fADC->fIsShared = kFALSE;
1696   }
1697
1698     fADC->fExtendedCOL = fTRDfeeParam->GetExtendedPadColFromADC(fMCM->fROB, fMCM->fMCM, fADC->fADCnumber);
1699     fADC->fCOL = fTRDfeeParam->GetPadColFromADC(fMCM->fROB, fMCM->fMCM, fADC->fADCnumber);
1700
1701   if (fADC->fCOL >= fHC->fColMax || fADC->fCOL < 0) {
1702     if (fADC->fIsShared == kFALSE) {
1703       fADC->fCorrupted += 32;
1704       if (fgDebugFlag) AliDebug(11,Form("Wrong column! ADCnumber %d MaxIs %d Col %d MaxIs %d MCM= %s", 
1705                                         fADC->fADCnumber, fMaxADCgeom, fADC->fCOL, fHC->fColMax, DumpMCMinfo(fMCM)));
1706     }
1707     //else {
1708     // we are out of the det when the pad is shared
1709     //if (fgDebugFlag) AliDebug(11, Form("Column out of the detector! ADCnumber %d MaxIs %d Col %d MaxIs %d MCM= %s", 
1710     //             fADC->fADCnumber, fMaxADCgeom, fADC->fCOL, fHC->fColMax, DumpMCMinfo(fMCM)));
1711     //fADC->fCorrupted += 32;
1712     //}
1713   }
1714
1715   if (fADC->fCorrupted > 0) {
1716     return kFALSE;
1717   }
1718
1719   fDecodedADCs++;
1720
1721   return kTRUE;
1722 }
1723
1724 //------------------------------------------------------------
1725 Bool_t AliTRDrawStream::DecodeADCExtended()
1726 {
1727   //
1728   // decode single ADC channel
1729   //
1730
1731   UInt_t commonAdditive = AliTRDrawStreamBase::fgCommonAdditive;
1732
1733   fADC->fCorrupted = 0;
1734   if(fADC->fADCnumber%2==1) fMaskADCword = ADC_WORD_MASK(ADCDATA_VAL1);
1735   if(fADC->fADCnumber%2==0) fMaskADCword = ADC_WORD_MASK(ADCDATA_VAL2);
1736
1737   fADC->fPos = fpPos;
1738
1739   fTbinADC = ((*fpPos & 0x000000fc) >>  2);
1740   fMCM->fSingleADCwords  = ((*fpPos & 0x00000f00) >>  8);
1741   fADC->fSignals[fTbinADC] = ((*fpPos & 0x003ff000) >> 12) - commonAdditive;
1742   fADC->fSignals[fTbinADC+1] = ((*fpPos & 0xffc00000) >> 22) - commonAdditive;
1743
1744   fpPos++; 
1745   for (Int_t iw = 0; iw < fMCM->fSingleADCwords-1; iw++) { // it goes up to fMCM->fSingleADCwords-1 since the first word was already decoded above
1746      if (HC_HEADER_MASK_ERR(*fpPos) == 0 || *fpPos == END_OF_TRACKLET_MARKERNEW) {
1747        if (fgWarnError) AliError(Form("There should be ADC data. We meet HC header or END_OF_TRACKLET_MARKER 0x%08x",*fpPos));
1748        fADC->fCorrupted += 16;
1749        fHC->fCorrupted += 16; 
1750        fpPos--;
1751        return kFALSE;
1752      }
1753      if (fMaskADCword != ADC_WORD_MASK(*fpPos)) {
1754        fADC->fCorrupted += 1;
1755        if (fgDebugFlag) AliDebug(11,Form("Wrong ADC data mask! ADC channel number: %02d [Expected mask: 0x%08x  Current mask: 0x%08x] MCM= %s Error : %d",
1756                                          fADC->fADCnumber, fMaskADCword, ADC_WORD_MASK(*fpPos),DumpMCMinfo(fMCM),fADC->fCorrupted));
1757        fpPos++;
1758        continue;
1759      }
1760
1761      // here we subtract the baseline ( == common additive)
1762      fADC->fSignals[fTbinADC + 2] = ((*fpPos & 0x00000ffc) >>  2) - commonAdditive;
1763      fADC->fSignals[fTbinADC + 3] = ((*fpPos & 0x003ff000) >> 12) - commonAdditive;
1764      fADC->fSignals[fTbinADC + 4] = ((*fpPos & 0xffc00000) >> 22) - commonAdditive;
1765
1766      fTbinADC += 3;
1767      fpPos++;
1768   } // iw
1769
1770 //  for(int i=0; i )
1771 //  printf();
1772
1773
1774   if (fADC->fADCnumber <= 1 || fADC->fADCnumber == fMaxADCgeom - 1) {
1775     fADC->fIsShared = kTRUE;
1776   }
1777   else {
1778     fADC->fIsShared = kFALSE;
1779   }
1780
1781   fADC->fExtendedCOL = fTRDfeeParam->GetExtendedPadColFromADC(fMCM->fROB, fMCM->fMCM, fADC->fADCnumber);
1782     fADC->fCOL = fTRDfeeParam->GetPadColFromADC(fMCM->fROB, fMCM->fMCM, fADC->fADCnumber);
1783
1784   if (fADC->fCOL >= fHC->fColMax || fADC->fCOL < 0) {
1785     if (fADC->fIsShared == kFALSE) {
1786       fADC->fCorrupted += 32;
1787       if (fgDebugFlag) AliDebug(11,Form("Wrong column! ADCnumber %d MaxIs %d Col %d MaxIs %d MCM= %s", 
1788                                         fADC->fADCnumber, fMaxADCgeom, fADC->fCOL, fHC->fColMax, DumpMCMinfo(fMCM)));
1789     }
1790   }
1791
1792   if (fADC->fCorrupted > 0) {
1793     return kFALSE;
1794   }
1795
1796   fDecodedADCs++;
1797
1798   return kTRUE;
1799 }
1800
1801 //--------------------------------------------------------
1802 void AliTRDrawStream::DecodeSMInfo(const UInt_t *word, struct AliTRDrawSM *sm) const
1803 {
1804   //
1805   // Decode Supermodule Index Word
1806   // The Supermodule Index Word is a 32-Bit word wit following structure
1807   // ssssssss ssssssss vvvv rrrr r d t mmmm
1808   // s: Size of the Supermodule Header, v: Supermodule Header Version, r: Reserved for future use
1809   // d: Track Data Enabled Bit, t: Tracklet Data Enabled Bit, m: Stack Mask 
1810   //
1811   sm->fPos = (UInt_t*)word; 
1812
1813   UInt_t vword = *word;
1814   sm->fHeaderSize = SM_HEADER_SIZE(vword);
1815     
1816   if (TRACKLETS_ENABLED(vword) > 0)
1817     sm->fTrackletEnable = kTRUE;
1818   else
1819     sm->fTrackletEnable = kFALSE;
1820     
1821   UInt_t stackMask = STACK_MASK(vword);
1822   sm->fActiveStacks = 0;
1823   for (Int_t i = 0; i < 5; i++) {
1824      if (IS_BIT_SET(stackMask,i) > 0) {
1825        sm->fStackActive[i] = kTRUE;
1826        sm->fActiveStacks++;
1827      }
1828      else {
1829        sm->fStackActive[i] = kFALSE;
1830      }
1831   }
1832 }
1833
1834 //--------------------------------------------------------
1835 const char *AliTRDrawStream::DumpSMInfo(const struct AliTRDrawSM *sm)
1836 {
1837   //
1838   // Get SM structure into a const char
1839   //
1840   return Form("[ SM Info 0x%08x] : Hsize %d TrackletEnable %d Stacks %d %d %d %d %d",
1841               *sm->fPos, sm->fHeaderSize, sm->fTrackletEnable,
1842               sm->fStackActive[0], sm->fStackActive[1], sm->fStackActive[2],
1843               sm->fStackActive[3], sm->fStackActive[4]);      
1844 }
1845
1846 //--------------------------------------------------------
1847 void AliTRDrawStream::DecodeStackInfo(const UInt_t *word, struct AliTRDrawStack *st) const
1848 {
1849   //
1850   // Decode Stack #i Index Word
1851   // The Stack #i Index Word is a 32-Bit word wit following structure
1852   // ssssssss ssssssss vvvv mmmm mmmmmmmm
1853   // s: Size of the Stack #i Header, v: Supermodule Header Version, m: Link Mask
1854   //
1855   st->fPos = (UInt_t*)word;
1856       
1857   UInt_t vword = *word;
1858   st->fHeaderSize = STACK_HEADER_SIZE(vword);
1859
1860   UInt_t linkMask = STACK_LINK_WORD(vword);
1861   st->fActiveLinks = 0;
1862   for (Int_t i = 0; i < 12; i++) {
1863      if (IS_BIT_SET(linkMask,i) > 0) {
1864        st->fLinksActive[i] = kTRUE;
1865        st->fActiveLinks++;
1866      }
1867      else {
1868        st->fLinksActive[i] = kFALSE;
1869      }
1870   }
1871 }
1872   
1873 //--------------------------------------------------------
1874 void AliTRDrawStream::DecodeStackHeader(const UInt_t *word, struct AliTRDrawStack *st, Int_t iword) const
1875 {
1876   //
1877   // decode gtu header for stack info
1878   //
1879   st->fPos = (UInt_t*)word;
1880      
1881   UInt_t vword = *word;
1882   st->fLinksDataType[2*iword]    = LINK0_DATA_TYPE_FLAG(vword);
1883   st->fLinksMonitor[2*iword]     = LINK0_MONITOR_FLAG(vword);
1884   st->fLinksDataType[2*iword+1]  = LINK1_DATA_TYPE_FLAG(vword);
1885   st->fLinksMonitor[2*iword+1]   = LINK1_MONITOR_FLAG(vword);
1886 }
1887
1888 //--------------------------------------------------------
1889 const char *AliTRDrawStream::DumpStackInfo(const struct AliTRDrawStack *st)
1890 {
1891   //
1892   // format the string with the stack info
1893   //
1894
1895   return Form("[ Stack Info 0x%08x ] : Hsize %d Links Active %d %d %d %d %d %d %d %d %d %d %d %d",
1896               *st->fPos, st->fHeaderSize,
1897               st->fLinksActive[0], st->fLinksActive[1], st->fLinksActive[2], st->fLinksActive[3],
1898               st->fLinksActive[4], st->fLinksActive[5], st->fLinksActive[6], st->fLinksActive[7],
1899               st->fLinksActive[8], st->fLinksActive[9], st->fLinksActive[10], st->fLinksActive[11]);
1900 }
1901
1902 //--------------------------------------------------------
1903 Bool_t AliTRDrawStream::DecodeHCwordH0(const UInt_t *word, struct AliTRDrawHC *hc) const
1904 {
1905   //
1906   // decode the hc header word 0
1907   //
1908   UInt_t vword = *word;
1909   hc->fPos[0] = (UInt_t*)word;
1910
1911   hc->fH0Corrupted = HC_HEADER_MASK_ERR(vword);
1912   if (hc->fH0Corrupted > 0) {
1913     if (fgDebugFlag) AliDebug(11,Form("H0 Header Mask Error. Word 0x%08x", *fHC->fPos));
1914     return kFALSE;
1915   }
1916
1917   hc->fSpecialRawV =  HC_SPECIAL_RAW_VERSION(vword);
1918   hc->fRawVMajor = HC_MAJOR_RAW_VERSION(vword);
1919   hc->fRawVMajorOpt = HC_MAJOR_RAW_VERSION_OPT(vword); 
1920   hc->fRawVMinor = HC_MINOR_RAW_VERSION(vword);
1921   hc->fNExtraWords = HC_EXTRA_WORDS(vword);
1922   hc->fDCSboard = HC_DCS_BOARD(vword);
1923   hc->fSM = HC_SM_NUMBER(vword);
1924   hc->fStack = HC_STACK_NUMBER(vword);
1925   hc->fLayer = HC_LAYER_NUMBER(vword);
1926   hc->fSide = HC_SIDE_NUMBER(vword);
1927
1928
1929   return kTRUE;
1930 }
1931
1932 //--------------------------------------------------------
1933 Bool_t AliTRDrawStream::DecodeHCwordH1(const UInt_t *word, struct AliTRDrawHC *hc) const
1934 {
1935   //
1936   // decode the hc header word 1
1937   //
1938   UInt_t vword = *word;
1939
1940   hc->fH1Corrupted = HC_HEADER_MASK_ERR(vword);
1941   if (hc->fH1Corrupted > 0) {
1942     if (fgDebugFlag) AliDebug(11,Form("H1 Header Mask Error. Word 0x%08x", *fHC->fPos));
1943     return kFALSE;
1944   }
1945
1946   hc->fTimeBins = HC_NTIMEBINS(vword);
1947   hc->fBunchCrossCounter = HC_BUNCH_CROSS_COUNTER(vword);
1948   hc->fPreTriggerCounter = HC_PRETRIGGER_COUNTER(vword);
1949   hc->fPreTriggerPhase = HC_PRETRIGGER_PHASE(vword);
1950
1951   hc->fPos[1] = (UInt_t*)word;
1952
1953   return kTRUE;
1954 }
1955   
1956 //--------------------------------------------------------
1957 const char *AliTRDrawStream::DumpHCinfoH0(const struct AliTRDrawHC *hc)
1958 {
1959   //
1960   // dump the hc header word 0
1961   //
1962   if (!hc)
1963     return Form("Unable to dump. Null received as parameter!?!");
1964   else
1965     return Form("[ HC[0] at 0x%08x ] : 0x%08x Info is : RawV %d SM %d Stack %d Layer %d Side %d DCSboard %d",
1966                 hc->fPos[0], (hc->fPos[0]) ? *(hc->fPos[0]) : 0, hc->fRawVMajor, hc->fSM, hc->fStack, hc->fLayer, hc->fSide, hc->fDCSboard);
1967 }
1968
1969 //--------------------------------------------------------
1970 const char *AliTRDrawStream::DumpHCinfoH1(const struct AliTRDrawHC *hc)
1971 {
1972   //
1973   // dump the hc header word 1
1974   //
1975   if (!hc)
1976     return Form("Unable to dump. Null received as parameter!?!");
1977   else
1978     return Form("[ HC[1] at 0x%08x ] : 0x%08x Info is : TBins %d BCcount %d PreTrigCount %d PreTrigPhase %d",
1979                 hc->fPos[1], (hc->fPos[1]) ? *(hc->fPos[1]) : 0, hc->fTimeBins, hc->fBunchCrossCounter, hc->fPreTriggerCounter, hc->fPreTriggerPhase);
1980 }
1981
1982 //--------------------------------------------------------
1983 void AliTRDrawStream::DecodeMCMheader(const UInt_t *word, struct AliTRDrawMCM *mcm) const
1984 {
1985   //
1986   // decode the mcm header
1987   //
1988   UInt_t vword = *word;
1989
1990   if (vword == END_OF_TRACKLET_MARKERNEW) {
1991     if (fgWarnError) AliError(Form("There should be MCM header. We meet END_OF_TRACKLET_MARKER 0x%08x",vword));
1992     mcm->fMCMhdCorrupted += 16;
1993     fHC->fCorrupted += 16; //to finish data reading of this HC
1994   }
1995
1996   mcm->fMCMhdCorrupted = MCM_HEADER_MASK_ERR(vword); //if MCM header mask has error
1997   if (fgDebugFlag && mcm->fMCMhdCorrupted != 0) AliDebug(11,Form("Wrong MCM header mask 0x%08x.\n", *fpPos));
1998
1999   mcm->fROB = MCM_ROB_NUMBER(vword);
2000   mcm->fMCM = MCM_MCM_NUMBER(vword);
2001   mcm->fEvCounter = MCM_EVENT_COUNTER(vword);
2002   mcm->fPos = (UInt_t*)word;
2003 }
2004
2005 //--------------------------------------------------------
2006 UInt_t AliTRDrawStream::GetMCMadcMask(const UInt_t *word, struct AliTRDrawMCM *mcm) const
2007 {
2008   //
2009   // get the adc mask
2010   //
2011   UInt_t vword = *word;
2012
2013   mcm->fADCmax    = 0;
2014   mcm->fADCMask   = 0;
2015   mcm->fADCcount  = 0;
2016   mcm->fADCMaskWord = vword;
2017
2018   if (vword == END_OF_TRACKLET_MARKERNEW) {
2019     if (fgWarnError) AliError(Form("There should be MCMadcMask. We meet END_OF_TRACKLET_MARKER 0x%08x",vword));
2020     mcm->fADCmaskCorrupted += 16;
2021     fHC->fCorrupted += 16; //to finish data reading of this HC
2022   }
2023
2024   if ( MCM_ADCMASK_MASK_ERR(vword) == 0 ) {
2025     mcm->fADCMask  = MCM_ADCMASK_VAL(vword);
2026     mcm->fADCcount = MCM_ADCMASK_NADC(~vword);
2027   }
2028   else {
2029     mcm->fADCMask = 0xffffffff;
2030     mcm->fADCmaskCorrupted = 1; // mcm adc mask error
2031     if (fgDebugFlag) AliDebug(11,Form("Wrong ADC Mask word 0x%08x.\n", *fpPos));
2032   }
2033
2034   return mcm->fADCMask;
2035 }
2036
2037 //--------------------------------------------------------
2038 void AliTRDrawStream::DecodeMask(const UInt_t *word, struct AliTRDrawMCM *mcm) const
2039 {
2040   //
2041   // decode the adc mask - adcs to be read out
2042   //
2043   mcm->fMCMADCWords = 0;
2044   mcm->fSingleADCwords = 0;
2045   mcm->fADCmax = 0;
2046   mcm->fADCMask = GetMCMadcMask(word, mcm);
2047
2048   if (mcm->fADCMask > 0) {
2049     for (Int_t i = 0; i < TRDMAXADC; i++) {
2050        mcm->fADCchannel[mcm->fADCmax] = 0;
2051        if ( IS_BIT_SET(mcm->fADCMask,i) ) {
2052          mcm->fADCchannel[mcm->fADCmax] = i;
2053          mcm->fADCmax++;
2054        }
2055     }
2056   }
2057   if (mcm->fADCcount != mcm->fADCmax && fHC->fRawVMajor >= 32) { // backward compatibility
2058     mcm->fADCmaskCorrupted += 2; 
2059     if (fgDebugFlag) AliDebug(11,Form("ADC counts from ADCMask are different %d %d : ADCMask word 0x%08x\n", mcm->fADCcount, mcm->fADCmax, *fMCM->fPos));
2060   }
2061 }
2062
2063 //--------------------------------------------------------
2064 void AliTRDrawStream::MCMADCwordsWithTbins(UInt_t fTbins, struct AliTRDrawMCM *mcm) const
2065 {
2066   //
2067   //  count the expected mcm words for a given tbins
2068   //
2069   mcm->fMCMADCWords = ( mcm->fADCmax ) * ( fTbins / 3 );
2070   mcm->fSingleADCwords = 0;
2071   if (mcm->fADCmax > 0) {
2072     mcm->fSingleADCwords = mcm->fMCMADCWords/mcm->fADCmax;
2073   }
2074   if (fTbins > 32) mcm->fSingleADCwords = 10; // if the timebin is more than 30, then fix the number of adc words to 10
2075 }
2076   
2077 //--------------------------------------------------------
2078 const char *AliTRDrawStream::DumpMCMinfo(const struct AliTRDrawMCM *mcm)
2079 {
2080   //
2081   // mcm info in a string
2082   //
2083   if (!mcm)
2084     return Form("Unable to dump. Null received as parameter!?!");
2085   else
2086     return Form("[ MCM 0x%08x ] : ROB %d MCM %d EvCounter %d", *(mcm->fPos), mcm->fROB, mcm->fMCM, mcm->fEvCounter);
2087 }
2088   
2089 //--------------------------------------------------------
2090 const char *AliTRDrawStream::DumpMCMadcMask(const struct AliTRDrawMCM *mcm)
2091 {
2092   //
2093   // mcm adc mask in a string
2094   //
2095   if (!mcm)
2096     return Form("Unable to dump. Null received as parameter!?!");
2097
2098   TString tsreturn = Form("[Word] : 0x%08x => [Mask] : 0x%08x : ", mcm->fADCMaskWord, mcm->fADCMask);
2099   for (Int_t i = 0; i < TRDMAXADC; i++) {
2100      tsreturn += Form("%d ", mcm->fADCchannel[i]);
2101   }
2102   tsreturn += "";
2103   return tsreturn.Data();
2104 }
2105