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