]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TRD/AliTRDrawStreamTB.cxx
Interface to pad status map in clusterizer
[u/mrichter/AliRoot.git] / TRD / AliTRDrawStreamTB.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16 /* $Id$ */
17
18 ///////////////////////////////////////////////////////////////////////////////
19 //                                                                           //
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 "AliTRDrawStreamTB.h"
36 #include "AliTRDgeometry.h"
37 #include "AliTRDfeeParam.h"
38 #include "AliTRDdigitsManager.h"
39 #include "AliTRDdataArrayS.h"
40 #include "AliTRDdataArrayI.h"
41 #include "AliTRDSignalIndex.h"
42 #include "AliTRDReconstructor.h"
43 #include "AliTRDrecoParam.h"
44
45 #include "AliLog.h"
46 #include "AliRawReader.h"
47
48 #define END_OF_TRACKLET_MARKEROLD 0xaaaaaaaa
49 #define END_OF_TRACKLET_MARKERNEW 0x10001000
50 #define ENDOFRAWDATAMARKER 0x00000000
51 #define ENDBITS 0x03
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
68 // HC word masks
69 //#define HC_HEADER_MASK_ERR(w) ( ((w) & (0x80000003)) == (0x80000001) ? 0 : 1) // 0 if OK!!!
70 #define HC_HEADER_MASK_ERR(w) ( ((w) & (0x3)) == (0x1) ? 0 : 1) // 0 if OK!!!
71
72 // HC word 0
73 #define HC_SPECIAL_RAW_VERSION(w) IS_BIT_SET(w,31)
74 #define HC_MAJOR_RAW_VERSION(w) GET_VALUE_AT(w,0x7f,24)
75 #define HC_MAJOR_RAW_VERSION_OPT(w) GET_VALUE_AT(w,0x7,24)
76 #define HC_MINOR_RAW_VERSION(w) GET_VALUE_AT(w,0x7f,17)
77 #define HC_EXTRA_WORDS(w) GET_VALUE_AT(w,0x7,14)
78 #define HC_DCS_BOARD(w) GET_VALUE_AT(w,0xfff<<20,20)
79 #define HC_SM_NUMBER(w) GET_VALUE_AT(w,0x1f,9)
80 #define HC_LAYER_NUMBER(w) GET_VALUE_AT(w,0x7,6)
81 #define HC_STACK_NUMBER(w) GET_VALUE_AT(w,0x7,3)
82 #define HC_SIDE_NUMBER(w) IS_BIT_SET(w,2)
83
84 // HC word 1
85 #define HC_NTIMEBINS(w) GET_VALUE_AT(w,0x3f,26)
86 #define HC_BUNCH_CROSS_COUNTER(w) GET_VALUE_AT(w,0xffff,10)
87 #define HC_PRETRIGGER_COUNTER(w) GET_VALUE_AT(w,0xf,6)
88 #define HC_PRETRIGGER_PHASE(w) GET_VALUE_AT(w,0xf,6)
89
90 //--------------------------------------------------------
91
92 // MCM word and ADC mask
93 #define MCM_HEADER_MASK_ERR(w) ( ((w) & (0xf)) == (0xc) ? 0 : 1) // 0 if OK!!!
94 #define MCM_ADCMASK_MASK_ERR(w) ( ((w) & (0xf)) == (0xc) ? 0 : 1) // 0 if OK!!!
95 #define MCM_MCM_NUMBER(w) GET_VALUE_AT(w,0x0f,24)
96 #define MCM_ROB_NUMBER(w) GET_VALUE_AT(w,0x7,28)
97 #define MCM_EVENT_COUNTER(w) GET_VALUE_AT(w,0x00fffff,4)
98 #define MCM_ADCMASK_VAL(w) GET_VALUE_AT(w,0x1fffff,4)
99 #define MCM_ADCMASK_NADC(w) GET_VALUE_AT(w,0x1f,25)
100
101 #define MCM_DUMMY_ADCMASK_VAL 0x015fffffc  // updated 
102 //#define MCM_DUMMY_ADCMASK_VAL 0x001fffffc 
103 //--------------------------------------------------------
104
105 #define MAX_TRACKLETS_PERHC 256 // max number of tracklets per HC - large number for now
106
107 //--------------------------------------------------------
108 #define ADC_WORD_MASK(w) ((w) & 0x3)
109 //--------------------------------------------------------
110
111
112 ClassImp(AliTRDrawStreamTB)
113
114 Bool_t AliTRDrawStreamTB::fgExtraSkip = kFALSE;
115 Bool_t AliTRDrawStreamTB::fgSkipCDH = kFALSE;
116 Bool_t AliTRDrawStreamTB::fgWarnError = kTRUE;
117 Bool_t AliTRDrawStreamTB::fgCleanDataOnly = kTRUE;
118 Bool_t AliTRDrawStreamTB::fgDebugFlag = kTRUE;
119 Bool_t AliTRDrawStreamTB::fgDebugStreamFlag = kFALSE;
120 Bool_t AliTRDrawStreamTB::fgStackNumberChecker = kTRUE;
121 Bool_t AliTRDrawStreamTB::fgStackLinkNumberChecker = kTRUE;
122 Bool_t AliTRDrawStreamTB::fgSkipData = kTRUE;
123 TTreeSRedirector *AliTRDrawStreamTB::fgDebugStreamer = 0;
124 UInt_t AliTRDrawStreamTB::fgStreamEventCounter = 0;
125 UInt_t AliTRDrawStreamTB::fgFirstEquipmentID = 0;
126 UInt_t AliTRDrawStreamTB::fgDumpHead = 0;
127 Int_t  AliTRDrawStreamTB::fgCommonAdditive = 0;
128 Int_t AliTRDrawStreamTB::fgEmptySignals[] = 
129   {
130     -1, -1, -1, -1, -1,  -1, -1, -1, -1, -1,  -1, -1, -1, -1, -1
131     -1, -1, -1, -1, -1,  -1, -1, -1, -1, -1,  -1, -1, -1, -1, -1
132   };
133
134 AliTRDrawStreamTB::AliTRDrawStreamTB()
135   : AliTRDrawStreamBase()
136 //: TObject()
137   , fSM()
138   , fStack(0)
139   , fHC(0)
140   , fMCM(0)
141   , fADC(0)
142   , fpPos(0)
143   , fpBegin(0)
144   , fpEnd(0)
145   , fWordLength(0)
146   , fEquipmentID(0)
147   , fStackNumber(-1)
148   , fStackLinkNumber(-1)
149   , fhcMCMcounter(0)
150   , fmcmADCcounter(0)
151   , fLinkTrackletCounter(-1)
152   , fEndOfTrackletCount(-1)
153   , fMaskADCword(0)
154   , fTbinADC(0)
155   , fDecodedADCs(-1)
156   , fEventCounter(0)
157   , fLastEventCounter(0)
158   , fSharedPadsOn(kFALSE)
159   , fMaxADCgeom(0)
160   , fGeometry(0)
161   , fRawReader(0)
162   , fTRDfeeParam(0)
163   , fDebugStreamOwned(kFALSE)
164 {
165   //
166   // default constructor
167   //
168
169   if (Init() == kFALSE)
170     {
171       AliWarning("Unable to Init.");      
172     }
173 }
174
175 //--------------------------------------------------------
176 AliTRDrawStreamTB::AliTRDrawStreamTB(AliRawReader *rawReader)
177   : AliTRDrawStreamBase(rawReader)
178 //: TObject()
179   , fSM()
180   , fStack(0)
181   , fHC(0)
182   , fMCM(0)
183   , fADC(0)
184   , fpPos(0)
185   , fpBegin(0)
186   , fpEnd(0)
187   , fWordLength(0)
188   , fEquipmentID(0)
189   , fStackNumber(-1)
190   , fStackLinkNumber(-1)
191   , fhcMCMcounter(0)
192   , fmcmADCcounter(0)
193   , fLinkTrackletCounter(-1)
194   , fEndOfTrackletCount(-1)
195   , fMaskADCword(0)
196   , fTbinADC(0)
197   , fDecodedADCs(-1)
198   , fEventCounter(0)
199   , fLastEventCounter(0)
200   , fSharedPadsOn(kFALSE)
201   , fMaxADCgeom(0)
202   , fGeometry(0)
203   , fRawReader(rawReader)
204   , fTRDfeeParam(0)
205   , fDebugStreamOwned(kFALSE)
206 {
207   //
208   // default constructor
209   //
210   if (fRawReader)
211     {     
212       if (Init() == kFALSE)
213         {
214           AliWarning("Unable to Init. Try setting up the reader with SetReader or buffer with Init(void *, UInt_t )");    
215         }
216     }
217   else
218     {
219       AliWarning("Unable to setup reader. Use SetReader(AliRawReader*).");
220     }
221 }
222
223 //------------------------------------------------------------
224
225 AliTRDrawStreamTB::AliTRDrawStreamTB(const AliTRDrawStreamTB& /*st*/)
226   : AliTRDrawStreamBase()
227 //: TObject()
228   , fSM()
229   , fStack(0)
230   , fHC(0)
231   , fMCM(0)
232   , fADC(0)
233   , fpPos(0)
234   , fpBegin(0)
235   , fpEnd(0)
236   , fWordLength(0)
237   , fEquipmentID(0)
238   , fStackNumber(-1)
239   , fStackLinkNumber(-1)
240   , fhcMCMcounter(0)
241   , fmcmADCcounter(0)
242   , fLinkTrackletCounter(-1)
243   , fEndOfTrackletCount(-1)
244   , fMaskADCword(0)
245   , fTbinADC(0)
246   , fDecodedADCs(-1)
247   , fEventCounter(0)
248   , fLastEventCounter(0)
249   , fSharedPadsOn(kFALSE)
250   , fMaxADCgeom(0)
251   , fGeometry(0)
252   , fRawReader(0)
253   , fTRDfeeParam(0)
254   , fDebugStreamOwned(kFALSE)
255 {
256   //
257   // Copy constructor
258   // 
259   AliError("Not implemeneted.");
260 }
261
262 //------------------------------------------------------------
263 Bool_t AliTRDrawStreamTB::SetRawVersion(Int_t fraw)
264 {
265   //
266   // function provided for backward compatibility
267   //
268   AliWarning("Raw data version is read from raw data stream! No point of setting it in here.");
269   fraw = 0; // avoid warnings
270   return kFALSE;
271 }
272
273 //------------------------------------------------------------
274 AliTRDrawStreamTB::~AliTRDrawStreamTB()
275 {
276   //
277   // destructor
278   //
279   delete fGeometry;
280
281   if (fDebugStreamOwned == kTRUE)
282     {
283       if (fgDebugStreamer)
284         {
285           delete fgDebugStreamer;
286           fgDebugStreamer = 0;
287         }
288     }
289 }
290
291 //------------------------------------------------------------
292
293 AliTRDrawStreamTB &
294 AliTRDrawStreamTB::operator=(const AliTRDrawStreamTB &)
295 {
296   //
297   // we are not using this functionality
298   //
299   AliFatal("May not use.");
300   return *this;
301 }
302
303 //------------------------------------------------------------
304
305 void    
306 AliTRDrawStreamTB::EnableDebug(TTreeSRedirector *debugStream)
307 {
308   //
309   // replace the current debug streamer or create a new one if owned
310   //
311
312   if (debugStream == 0)
313     {
314       if (fDebugStreamOwned == kTRUE)
315         {
316           if (fgDebugStreamer)
317             delete fgDebugStreamer;
318         }
319
320       fDebugStreamOwned = kTRUE;
321       fgDebugStreamer    = new TTreeSRedirector("TRDrawDataDebug.root");
322       fgStreamEventCounter = 0;
323
324     }
325   else
326     {
327       if (fDebugStreamOwned == kTRUE)
328         {
329           if (fgDebugStreamer)
330             delete fgDebugStreamer;
331         }
332
333       fgDebugStreamer = debugStream;
334       fDebugStreamOwned = kFALSE;
335     }
336 }
337
338 //___________________________________________________________
339 void 
340 AliTRDrawStreamTB::SwapOnEndian()
341 {
342   //
343   // Check the endian and swap if needed
344   //
345
346   int itemp = 1;
347   char* ptemp = (char*) &itemp;
348   if (ptemp[0] != 1)
349     {
350       // need to swap...
351       if (fgDebugFlag) AliDebug(8, "Swapping.");
352
353       fpPos = fpBegin;
354       UInt_t iutmp = 0;
355       while (fpPos < fpEnd)
356         {
357           fpPos += 1;
358           iutmp = (((*fpPos & 0x000000ffU) << 24) | ((*fpPos & 0x0000ff00U) <<  8) |
359                    ((*fpPos & 0x00ff0000U) >>  8) | ((*fpPos & 0xff000000U) >> 24));
360           // here we override the value in the buffer!
361           *fpPos = iutmp;         
362         }
363       fpPos = fpBegin;
364     }
365 }
366
367 //------------------------------------------------------------
368 void 
369 AliTRDrawStreamTB::DumpErrorCount()
370 {
371   //
372   // print the error statistics into the stdout
373   //
374
375   ;
376   //   AliInfo(Form("Error counts: HC0 %d HC1 %d MCM %d ADCmask %d ADC %d", 
377   //           fHC->fH0ErrorCounter,  fHC->fH1ErrorCounter, fMCM->fErrorCounter, fMCM->fMaskErrorCounter, adc.fErrorCounter));
378 }
379
380 //------------------------------------------------------------
381 Bool_t 
382 AliTRDrawStreamTB::DumpWords(UInt_t *px, UInt_t iw, UInt_t marker)
383 {
384   //
385   // skip few words
386   // note: can be made faster
387   //
388     
389   TString tsreturn = Form("\n[ Dump Sequence at 0x%08x ] : ", px);
390   for (UInt_t i = 0; i < iw; i++)
391     {
392       if (px + iw >= fpEnd)
393         return kFALSE;
394
395       if (i % 8 == 0)
396         tsreturn += "\n                              ";
397       if (marker != 0 && marker == px[i])
398         tsreturn += Form(" *>0x%08x<* ", px[i]);
399       else
400         tsreturn += Form("0x%08x ", px[i]);
401     }
402   tsreturn += "\n";
403
404   AliInfo(tsreturn.Data());
405
406   return kTRUE;
407 }
408
409 //------------------------------------------------------------
410 Bool_t 
411 AliTRDrawStreamTB::SkipWords(UInt_t iw)
412 {
413   //
414   // skip few words
415   // note: can be made faster
416   //
417   
418   if ( fpPos + iw < fpEnd )
419     {
420       fpPos += iw;
421       return kTRUE;
422     }
423   else
424     {
425       if (fgWarnError) AliWarning(Form("Skip %d words failed. %d available", iw, fpEnd - fpPos - 1));
426       if (fgDebugStreamer)
427         {
428           TTreeSRedirector &cstream = *fgDebugStreamer;
429           cstream << "SkipWords"
430                   << "Event=" << fgStreamEventCounter
431                   << ".nwords=" << iw
432 //                << ".read=" << (Char_t*)(fpPos - fpBegin)
433 //                << ".togo=" << (Char_t*)(fpEnd - fpPos)
434 //                << ".length=" << (Char_t*)(fpEnd - fpBegin)
435                   << "\n";
436         }
437       return kFALSE;
438     }
439
440   return kTRUE;
441 }
442
443 //------------------------------------------------------------
444 Bool_t 
445 AliTRDrawStreamTB::SetReader(AliRawReader *reader)
446 {
447   //
448   //
449   //
450
451   if (reader != 0)
452     {
453       fRawReader = reader;
454       if (fRawReader)
455         {         
456           return Init();
457         }
458       else
459         {
460           AliWarning("Unable to setup reader.");
461           return kFALSE;
462         }
463     }
464   else
465     {
466       AliWarning("AliRawReader argument is 0.");
467       fRawReader = 0;
468     }
469
470   return kFALSE;
471 }
472
473 //------------------------------------------------------------
474 Int_t 
475 AliTRDrawStreamTB::NextBuffer()
476 {
477   //
478   // return -1 if no more buffers available
479   // return 0 DecodeSM failed (clean data required for example) but still maybe more data to come
480   // return 1 DecodeSM OK
481   // 
482
483   if (fRawReader != 0)
484     {
485       UChar_t *buffer = 0;
486       UInt_t length = 0;
487       Bool_t kBufferSet = fRawReader->ReadNextData(buffer);
488       if (kBufferSet == kTRUE)
489         {
490           if (fgDebugFlag)  AliDebug(9, "Buffer is set.");
491           length = fRawReader->GetDataSize();
492           if (fgExtraSkip == kTRUE)
493             {
494               buffer += EXTRA_LEAD_WORDS * WORD_SIZE;
495               length -= EXTRA_LEAD_WORDS * WORD_SIZE;
496             }
497
498           if (fgSkipCDH == kTRUE)
499             {
500               buffer += CDH_WORDS * WORD_SIZE;
501               length -= CDH_WORDS * WORD_SIZE;        
502             }
503
504           if (length > 0)
505             {
506               if (fgDebugFlag)  AliDebug(9, Form("Buffer length : %d", length));
507               //return InitBuffer((void*)buffer, length);
508               if (DecodeSM((void*)buffer, length) == kTRUE)
509                 return 1;
510               else
511                 return 0;
512             }
513         }
514       else
515         {
516           return -1;
517         }
518     }
519
520   return -1;
521 }
522
523 //------------------------------------------------------------
524 void 
525 AliTRDrawStreamTB::ResetCounters()
526 {
527   //
528   // reset some global counters
529   //
530
531   fStackNumber = 0;
532   fStackLinkNumber = 0;
533
534   fDecodedADCs = 0;
535
536   fSM.fActiveStacks = 0;
537   fSM.fNexpectedHalfChambers = 0;
538
539   fLinkTrackletCounter = 0;
540
541   fLastEventCounter = 0;
542   fEventCounter = 0;
543 }
544
545 //------------------------------------------------------------
546 void 
547 AliTRDrawStreamTB::ResetIterators()
548 {
549   //
550   // reset the data iterators used in the Next()
551   //
552   fStackNumber = 0;
553   fStackLinkNumber = 0;
554   fhcMCMcounter = 0;  
555   fmcmADCcounter = 0;
556 }
557
558 //------------------------------------------------------------
559
560 Bool_t 
561 AliTRDrawStreamTB::Next()
562 {
563   //
564   // returns with true on next adc read
565   // returns false on errors and end of buffer
566   // 
567
568   while (fStackNumber < 5 && fSM.fActiveStacks > 0)
569     {
570       if(fSM.fStackActive[fStackNumber] == kTRUE)
571         {
572           fStack = &fSM.fStacks[fStackNumber];
573           while (fStackLinkNumber < 12)
574             {
575               if (fStack->fLinksActive[fStackLinkNumber] == kTRUE)
576                 {
577                   fHC = &fStack->fHalfChambers[fStackLinkNumber];
578                   if (!fHC)
579                     {
580                       AliError(Form("Super Strange. HC missing at stack %d link %d", fStackNumber, fStackLinkNumber));
581                       return kFALSE;
582                     }
583                   if (fHC->fCorrupted == 0)
584                     {
585                       while (fhcMCMcounter < fHC->fMCMmax)
586                         {
587                           fMCM = &fHC->fMCMs[fhcMCMcounter];
588                           if (!fMCM)
589                             {
590                               AliError(Form("Super Strange. HC missing at stack %d link %d atMCMslot %d", 
591                                             fStackNumber, fStackLinkNumber, fhcMCMcounter));
592                               return kFALSE;
593                             }
594                           while(fmcmADCcounter < fMCM->fADCmax)
595                             {
596                               fADC = &fMCM->fADCs[fmcmADCcounter];
597                               if (!fADC)
598                                 {
599                                   AliError(Form("Super Strange. ADC missing at stack %d link %d MCMslot %d ADCslot %d", 
600                                                 fStackNumber, fStackLinkNumber, fhcMCMcounter, fmcmADCcounter));
601                                   return kFALSE;
602                                 }
603                               fmcmADCcounter++;
604                               if (fSharedPadsOn)
605                                 {
606                                   return kTRUE;
607                                 }
608                               else
609                                 {
610                                   if (fADC->fIsShared == kFALSE)
611                                     return kTRUE;
612                                 }
613                             } //while adc in MCM
614                           fhcMCMcounter++;
615                           // next MCM should go through all active ADCs
616                           fmcmADCcounter = 0;
617                         } // while mcm
618                     } // if HC OK
619                 }// if link active
620               fStackLinkNumber++;
621               // next stack link (HC) should go through all active MCMs
622               fhcMCMcounter = 0;
623             }// while links
624         }// if stack active
625       fStackNumber++;
626       // next stack should go through all links - start from 0
627       fStackLinkNumber = 0;
628     }
629
630   // in case rawreader manages the mem buffers
631   // lets go for the next buffer
632   if (fRawReader)
633     {
634       Int_t nextBuff = NextBuffer();
635       while (nextBuff != -1)
636         {
637           if (nextBuff > 0)
638             return Next();                
639           nextBuff = NextBuffer();
640         }
641     }
642
643   return kFALSE;
644 }
645
646 //------------------------------------------------------------
647
648 Int_t 
649 AliTRDrawStreamTB::NextChamber(AliTRDdigitsManager *digitsManager)
650 {
651   //
652   // Fills single chamber digit array 
653   // Return value is the detector number
654   //
655
656   AliTRDdataArrayS *digits = 0;
657   AliTRDdataArrayI *track0 = 0;
658   AliTRDdataArrayI *track1 = 0;
659   AliTRDdataArrayI *track2 = 0; 
660   AliTRDSignalIndex *indexes = 0;
661
662   // Get the ADC baseline
663   Int_t adcBaseline = 0;
664   if (!AliTRDReconstructor::RecoParam())
665     {
666       AliError("RecoParam does not exist\n");
667       return 0;
668     }
669   else 
670     {
671       adcBaseline = ((Int_t) AliTRDReconstructor::RecoParam()->GetADCbaseline());
672     }
673
674   // Loop through the digits
675   Int_t lastdet = -1;
676   Int_t det     = -1;
677   //   Int_t returnDet = -1;
678   Int_t it = 0;
679   while (Next()) 
680     {      
681       det    = GetDet();
682     
683       if (det != lastdet) 
684         { 
685           // If new detector found
686           if (lastdet == -1)
687             {
688               lastdet = det;
689             }
690           else
691             {
692               return lastdet;
693             }
694
695           if (det < 0 || det >= AliTRDgeometry::kNdet)
696             {
697               if (fSM.fClean == kTRUE)
698                 {
699                   AliError(Form("Strange Det Number %d BUT event buffer seems to be clean.", det));
700                 }
701               else
702                 {
703                   AliError(Form("Strange Det Number %d. Event buffer marked NOT clean!", det));
704                 }
705               continue;
706             }
707
708           // Add a container for the digits of this detector
709           digits = (AliTRDdataArrayS *) digitsManager->GetDigits(det);
710           if (digitsManager->UsesDictionaries()) 
711             {
712               track0 = (AliTRDdataArrayI *) digitsManager->GetDictionary(det,0);
713               track1 = (AliTRDdataArrayI *) digitsManager->GetDictionary(det,1);
714               track2 = (AliTRDdataArrayI *) digitsManager->GetDictionary(det,2);
715             }
716
717           if (!digits)
718             {
719               if (fSM.fClean == kTRUE)
720                 {
721                   AliError(Form("Unable to get digits for det %d BUT event buffer seems to be clean.", det));
722                 }
723               else
724                 {
725                   AliError(Form("Unable to get digits for det %d. Event buffer is NOT clean!", det));
726                 }
727               return -1;
728               //continue;
729             }
730
731           Int_t rowMax = GetRowMax();
732           Int_t colMax = GetColMax();
733           Int_t ntbins = GetNumberOfTimeBins();
734
735           // Allocate memory space for the digits buffer
736           if (digits->GetNtime() == 0) 
737             {
738               digits->Allocate(rowMax, colMax, ntbins);
739               if (digitsManager->UsesDictionaries()) 
740                 {
741                   track0->Allocate(rowMax, colMax, ntbins);
742                   track1->Allocate(rowMax, colMax, ntbins);
743                   track2->Allocate(rowMax, colMax, ntbins);
744                 }
745             }
746
747           indexes = digitsManager->GetIndexes(det);
748           indexes->SetSM(GetSM());
749           indexes->SetStack(GetStack());
750           indexes->SetLayer(GetLayer());
751           indexes->SetDetNumber(det);
752           if (indexes->IsAllocated() == kFALSE)
753             indexes->Allocate(rowMax, colMax, ntbins);
754         }
755     
756       // ntimebins data are ready to read
757       for (it = 0; it < GetNumberOfTimeBins(); it++)
758         {
759           if ((GetSignals()[it] - adcBaseline) > 0)
760             {
761               digits->SetDataUnchecked(GetRow(), GetCol(), it, GetSignals()[it] - adcBaseline);
762               
763               indexes->AddIndexTBin(GetRow(), GetCol(), it);
764               if (digitsManager->UsesDictionaries()) 
765                 {
766                   track0->SetDataUnchecked(GetRow(), GetCol(), it, 0);
767                   track1->SetDataUnchecked(GetRow(), GetCol(), it, 0);
768                   track2->SetDataUnchecked(GetRow(), GetCol(), it, 0);
769                 }
770             }
771         } // tbins
772     }// while Next()
773
774   // what happens if the last HC is turned off?
775   return det;
776   //return -1;
777 }
778
779 //------------------------------------------------------------
780 Bool_t
781 AliTRDrawStreamTB::Init()
782 {
783   //
784   // general init
785   //
786
787   TDirectory *saveDir = gDirectory; 
788   
789   if (!fGeometry) 
790     {
791       fGeometry = new AliTRDgeometry();
792     }
793   
794   if (!fGeometry) 
795     {
796       AliError("Geometry FAILED!");
797       return kFALSE;
798     }
799
800   fTRDfeeParam = AliTRDfeeParam::Instance();
801   if (!fTRDfeeParam)
802     {
803       AliError("AliTRDfeeParam FAILED!");
804       return kFALSE;
805     }
806
807   fMaxADCgeom = (Int_t)fGeometry->ADCmax();
808
809   // common additive is moved to be static for temp solution
810   // common additive should be delivered in the HC word 2 (3rd word)
811   //fCommonAdditive = 10;
812
813   ResetCounters();
814
815   if (fgDebugStreamFlag == kTRUE)
816     {
817       if (!fgDebugStreamer)
818         {
819           fgDebugStreamer    = new TTreeSRedirector("TRDrawDataDebug.root");
820           fgStreamEventCounter = 0;
821       
822           if (fgDebugStreamer)
823             {
824               AliInfo(Form("Debug Streamer Initialized! Remember to delete! %s::DeleteDebugStream()", this->IsA()->GetName()));
825               //fDebugStreamOwned = kTRUE;
826             }
827           else
828             {
829               AliError("Unable to init debug stream");
830             }
831         }
832     }
833
834   // in case rawreader manages the mem buffers
835   // lets go for the next buffer
836   if (fRawReader)
837     {
838       Int_t nextBuff = NextBuffer();
839       while (nextBuff != -1)
840         {
841           if (nextBuff > 0)
842             return kTRUE;
843           nextBuff = NextBuffer();
844         }
845     }
846
847   saveDir->cd();
848
849   return kTRUE;
850 }
851
852 void AliTRDrawStreamTB::DeleteDebugStream()
853 {
854   // 
855   // static helper function
856   //
857
858   if (fgDebugStreamer)
859     {
860       delete fgDebugStreamer;
861       fgDebugStreamer = 0;
862     }
863   
864 }
865
866 //------------------------------------------------------------
867 Bool_t 
868 AliTRDrawStreamTB::InitBuffer(void *buffer, UInt_t length)
869 {
870   // 
871   // init the class before reading from the buffer
872   // and read SM heading info:
873   // -- super module header
874   // -- stack headers + link status words
875   //
876
877   // not in the pre scan mode
878   //get Equipment ID 
879   if(fgStreamEventCounter == 0) fgFirstEquipmentID = fRawReader->GetEquipmentId();
880   fEquipmentID = fRawReader->GetEquipmentId(); 
881   //fgStreamEventCounter++;
882   if(fEquipmentID == fgFirstEquipmentID) fgStreamEventCounter++;
883
884   
885   ResetCounters();
886
887   fpBegin = (UInt_t *)buffer;
888
889   if (WORD_SIZE == 0)
890     {
891       AliFatal("Strange! Size of UInt_t == 0");
892       return kFALSE;
893     }
894
895   fWordLength = length/WORD_SIZE;
896   fpEnd = fpBegin + fWordLength;
897   fpPos = fpBegin;
898
899   if (fpBegin == 0 || length <= 0)
900     {
901       AliError(Form("This will not work! Pointer to the buffer is 0x%08x of size %d", fpBegin, length));
902       return kFALSE;
903     }
904
905   SwapOnEndian();
906
907   if (fgDumpHead > 0)
908     {
909       AliInfo("------------------------------------------------");
910       if (DumpWords(fpBegin, fgDumpHead) == kFALSE)
911         {
912           AliError("Dump failed. Not enough data.");      
913         }
914       AliInfo("------------------------------------------------");
915     }
916
917   //decode SM
918   DecodeSMInfo(fpPos, &fSM);
919
920   if (fgDebugFlag)  AliDebug(5, DumpSMInfo(&fSM));
921
922   fpPos++;
923   if (fpPos < fpEnd)
924     {   
925       if (SkipWords(fSM.fHeaderSize) == kTRUE)
926         {
927           //decode stacks info
928           //for (Int_t istack = 0; istack < fSM.fActiveStacks; istack++)
929           for (Int_t istack = 0; istack < 5; istack++)
930             {
931               if (fSM.fStackActive[istack] == kFALSE)
932                 continue;
933
934               fStack = &fSM.fStacks[istack];
935               DecodeStackInfo(fpPos, fStack);
936               fpPos++;
937
938               fSM.fNexpectedHalfChambers += fStack->fActiveLinks;
939               
940               if (fgDebugFlag)  AliDebug(5, DumpStackInfo(fStack));
941               
942               if (SkipWords(fStack->fHeaderSize) == kFALSE)
943                 {
944                   if (fRawReader) fRawReader->AddMajorErrorLog(kDecodeStackInfo, "Stack head words missing");
945                   return kFALSE;
946                 }
947             }
948         }
949       else
950         {
951           return kFALSE;
952         }
953     }
954   else
955     {
956       if (fgWarnError) AliWarning("No Stack info present. Strange.");
957       if (fRawReader) fRawReader->AddMajorErrorLog(kDecodeStackInfo, "Stack info missing");
958       return kFALSE;
959     }
960
961   if (fgDebugFlag)  AliDebug(5, Form("Expected half chambers : %d", fSM.fNexpectedHalfChambers));
962   
963   //fpPos++;
964   if (fpPos < fpEnd)
965     {
966       if (fgDebugFlag)  AliDebug(5, "Init OK.");
967     }
968   else
969     {
970       if (fgWarnError) AliWarning("No data just after init. Strange.");
971       if (fRawReader) fRawReader->AddMajorErrorLog(kMissingData, "Missing data");
972       return kFALSE;
973     }
974
975   return kTRUE;
976 }
977
978 //------------------------------------------------------------
979 Bool_t 
980 AliTRDrawStreamTB::DecodeSM(void *buffer, UInt_t length)
981 {
982   //
983   // decode all sm at once
984   // still here for devel and debug
985   //
986   
987   //memset(&fSM, 0, sizeof(fSM));
988
989   ResetIterators();
990
991   fSM.fClean = kTRUE;
992   if (InitBuffer(buffer, length) == kTRUE)
993     {
994       // no we are already set!
995       // fpPos++;      
996     }
997   else
998     {
999       if (fgWarnError) AliError("--- INIT failed. ---------------");      
1000       fSM.fClean = kFALSE;
1001       return kFALSE;
1002     }
1003
1004   //decode data here
1005   //fSM.fActiveStacks
1006   for (Int_t istack = 0; istack < 5; istack++)
1007     {
1008       fStackNumber = istack;
1009       if (fSM.fStackActive[istack] == kFALSE)
1010         continue;
1011       
1012       fStack = &fSM.fStacks[istack];
1013
1014       //fStack[istack].fActiveLinks // max is 12
1015       for (Int_t ilink = 0; ilink < 12; ilink++)
1016         {
1017           fStackLinkNumber = ilink;
1018           if (fStack->fLinksActive[ilink] == kFALSE)
1019             continue;
1020
1021           if (fpPos >= fpEnd)
1022             {
1023               if (fRawReader) fRawReader->AddMajorErrorLog(kLinkDataMissing, "Link data missing");            
1024               fSM.fClean = kFALSE;
1025               break;
1026             }
1027
1028           fHC = &fStack->fHalfChambers[ilink];
1029
1030           if (fgDebugStreamer)
1031             {
1032               TTreeSRedirector &cstream = *fgDebugStreamer;
1033                cstream << "LINKDataStream"
1034                   << "Event=" << fgStreamEventCounter
1035                   << ".equipID=" << fEquipmentID
1036                   << ".stack=" << fStackNumber
1037                   << ".link=" << fStackLinkNumber
1038                   << "\n";
1039             }
1040
1041
1042           if (fSM.fTrackletEnable == kTRUE)
1043             {
1044               if (DecodeTracklets() == kFALSE)
1045                 {
1046                   if (fgDebugStreamer)
1047                     {
1048                       TTreeSRedirector &cstream = *fgDebugStreamer;
1049                       cstream << "TrackletDecodeError"
1050                               << "Event=" << fgStreamEventCounter
1051                               << ".Stack=" << fStackNumber
1052                               << ".Link=" << fStackLinkNumber
1053                               << ".EndOfTrackletCount=" << fEndOfTrackletCount
1054                               << "\n";
1055                     }
1056                   
1057                   fSM.fClean = kFALSE;
1058                   SeekEndOfData();
1059
1060                   if (fgWarnError) 
1061                     {
1062                       AliError(Form("Failed stack %d link %d", fStackNumber, fStackLinkNumber));
1063                       AliError(Form("Debug Event Counter : %d", fgStreamEventCounter)); 
1064                     }
1065                   continue;
1066                   //return kFALSE;
1067                 }
1068             }
1069
1070           if (fpPos >= fpEnd)
1071             {
1072               if (fRawReader) fRawReader->AddMajorErrorLog(kHCdataMissing, "HC data missing");        
1073               fSM.fClean = kFALSE;
1074               break;
1075             }
1076           
1077           if (DecodeHC() == kFALSE)
1078             {
1079               fSM.fClean = kFALSE;
1080               if (fgWarnError) 
1081                 {
1082                   AliError(Form("Dumping Words for Debugging Purpose =========================>")); 
1083                   DumpWords(fpPos-8, 16); 
1084                   AliError(Form("Dumping Done!")); 
1085                 }
1086               if (fHC->fCorrupted < 16)  SeekEndOfData(); // In case that we meet END_OF_TRACKLET_MARKERNEW during ADC data decoding or MCM header decoding
1087                                                           // we don't seek ENDOFRAWDATAMARKER
1088
1089               if (fgWarnError) 
1090                 {
1091                   AliError(Form("Failed HC : %s", DumpHCinfoH0(fHC)));
1092                   AliError(Form("Failed HC : %s", DumpHCinfoH1(fHC)));
1093                   AliError(Form("Debug Event Counter : %d\n\n\n", fgStreamEventCounter)); 
1094                 }
1095                       
1096               continue;
1097               //return kFALSE;
1098             }
1099           else
1100             {
1101               SeekEndOfData(); // make sure that finish off with the end of data markers
1102             }
1103
1104         } // ilink
1105     } // istack
1106
1107   // for next()
1108   ResetIterators();
1109
1110   if (fSM.fClean == kTRUE)
1111     return kTRUE;
1112   
1113   if (fgCleanDataOnly && (fSM.fClean == kFALSE))
1114     {
1115       if (fgWarnError) 
1116         {
1117           AliWarning("Buffer with errors. Returning FALSE.");
1118           AliWarning(Form("--- Failed SM : %s ---", DumpSMInfo(&fSM)));
1119         }
1120       fSM.fActiveStacks = 0; // Next will not give data
1121       return kFALSE;
1122     }
1123
1124   return kTRUE;
1125 }
1126
1127 //------------------------------------------------------------
1128 Int_t 
1129 AliTRDrawStreamTB::DecodeSM()
1130 {
1131   //
1132   // decode SM data in case AliRawReader is in use
1133
1134   if (fRawReader)
1135     {      
1136       Int_t nextBuff = NextBuffer();
1137       while (nextBuff != -1)
1138         {
1139           if (nextBuff > 0)
1140             return nextBuff;              
1141           nextBuff = NextBuffer();
1142         }
1143       return -1;
1144     }
1145   else
1146     {
1147       AliWarning("AliRawReader not set.");
1148     }
1149   return kFALSE;
1150 }
1151
1152 //------------------------------------------------------------
1153 Int_t 
1154 AliTRDrawStreamTB::DecodeSM(AliRawReader *reader)
1155 {
1156   //
1157   // decode SM with the AliRawReader
1158   //
1159   if (reader != 0)
1160     {
1161       fRawReader = reader;
1162       return DecodeSM();
1163     }
1164   else
1165     {
1166       AliWarning("Argument AliRawReader is 0.");
1167     }
1168   return kFALSE;
1169 }
1170
1171 //------------------------------------------------------------
1172 Bool_t 
1173 AliTRDrawStreamTB::SeekEndOfData()
1174 {
1175   //
1176   // go to end of data marker
1177   //
1178   Int_t fEndOfDataCount = 0;
1179
1180   while ( *fpPos != ENDOFRAWDATAMARKER && fpPos < fpEnd )
1181     {
1182       fpPos++;
1183     }
1184   
1185   while (*fpPos == ENDOFRAWDATAMARKER && fpPos < fpEnd )
1186     {
1187       fEndOfDataCount++;
1188       fpPos++;      
1189     }
1190   
1191 //   if (fEndOfDataCount == 0)
1192 //     {
1193 //       if (fgWarnError) AliWarning("End of buffer reached first. No end of data marker?");
1194 //       return kFALSE;
1195 //     }
1196
1197   return kTRUE;
1198 }
1199
1200 //------------------------------------------------------------
1201 Bool_t 
1202 AliTRDrawStreamTB::SeekNextMCMheader()
1203 {
1204   //
1205   // go to mcm marker
1206   //
1207
1208   // move back to the mcm pos
1209   fpPos = fMCM->fPos + 1;
1210
1211   while ( *fpPos != ENDOFRAWDATAMARKER && fpPos < fpEnd )
1212     {
1213       if (MCM_HEADER_MASK_ERR(*fpPos) == 0)      
1214         {
1215           if (fgWarnError) AliWarning(Form("^^^ Found : Pos 0x%08x : Val 0x%08x", fpPos, *fpPos));
1216           return kTRUE;
1217         }
1218       fpPos++;
1219     }
1220
1221   SeekEndOfData();
1222   return kFALSE;
1223 }
1224
1225 //------------------------------------------------------------
1226
1227 Bool_t 
1228 AliTRDrawStreamTB::DecodeTracklets()
1229 {
1230   //
1231   // decode tracklets
1232   //
1233
1234   fLinkTrackletCounter = 0;
1235   fEndOfTrackletCount = 0;
1236
1237   if (fgDebugFlag)  AliDebug(10, Form("Decode tracklets at 0x%08x : 0x%08x", fpPos, *fpPos));
1238
1239   while ( *fpPos != END_OF_TRACKLET_MARKEROLD && *fpPos != END_OF_TRACKLET_MARKERNEW && fpPos < fpEnd )
1240     {
1241
1242       if (fgDebugFlag)  AliDebug(10, Form("Tracklet found at 0x%08x : 0x%08x", fpPos, *fpPos));
1243
1244       fLinkTrackletCounter++;
1245
1246       if (fLinkTrackletCounter > MAX_TRACKLETS_PERHC)
1247         {
1248           if (fgWarnError) AliWarning(Form("Max number of tracklets exceeded %d > %d. Something is wrong with the input data!", 
1249                           fLinkTrackletCounter, MAX_TRACKLETS_PERHC));
1250           /*
1251           if (fgWarnError)
1252             {
1253               AliError(Form("Dumping Words for Debugging Purpose =========================>"));
1254               DumpWords(fpPos-300, 320);
1255               AliError(Form("Dumping Done!"));
1256             }
1257           */
1258
1259           if (fRawReader) fRawReader->AddMajorErrorLog(kTrackletOverflow,"Too many tracklets"); 
1260           return kFALSE;
1261         }
1262
1263       if (fgDebugStreamer)
1264         {
1265           // jan!
1266           unsigned pid;
1267           unsigned row;
1268           signed defl;
1269           signed ypos;
1270           
1271           double deflm;
1272           double yposm;
1273           
1274           unsigned long val;
1275           
1276           val = *fpPos;
1277
1278           pid = val >> 24;
1279           row = (val >> 20) & 0xF;
1280           defl = (val >> 13) & 0x7F;
1281           defl = defl << 25 >> 25;
1282           ypos = val & 0x1FFF;
1283           ypos = ypos << 19 >> 19;
1284           
1285           deflm = defl * 140.0e-6; /* m */
1286           yposm = ypos * 160.0e-6; /* m */
1287           
1288           TTreeSRedirector &cstream = *fgDebugStreamer;
1289           cstream << "MCMtracklets"
1290                   << "Event=" << fgStreamEventCounter
1291                   << ".stack=" << fStackNumber
1292                   << ".link=" << fStackLinkNumber
1293                   << ".pid=" << pid
1294                   << ".row=" << row
1295                   << ".defl=" << defl
1296                   << ".ypos=" << ypos
1297                   << ".deflm=" << deflm
1298                   << ".yposm=" << yposm
1299                   << "\n";
1300         }
1301       fpPos++;
1302     }
1303
1304   while ( ( *fpPos == END_OF_TRACKLET_MARKEROLD || *fpPos == END_OF_TRACKLET_MARKERNEW ) && fpPos < fpEnd )
1305     {
1306       if (fgDebugFlag)  AliDebug(10, Form("EoTracklets found at 0x%08x : 0x%08x", fpPos, *fpPos));
1307
1308       fEndOfTrackletCount++;
1309       fpPos++;
1310     }
1311
1312   if ( fEndOfTrackletCount < 2 )
1313     {
1314       if (fRawReader) fRawReader->AddMajorErrorLog(kEOTrackeltsMissing, "End of tracklets word missing"); 
1315       return kFALSE;
1316     }
1317
1318   return kTRUE;
1319 }
1320
1321 //------------------------------------------------------------
1322 Bool_t 
1323 AliTRDrawStreamTB::IsRowValid()
1324 {
1325   //SLOW GEOM
1326   if ( (fHC->fStack == 2 && fMCM->fROW >= fGeometry->RowmaxC0()) ||
1327        (fHC->fStack != 2 && fMCM->fROW >= fGeometry->RowmaxC1()) || fMCM->fROW < 0 ) 
1328     {
1329       if (fgWarnError) AliWarning(Form("SM%d L%dS%d: Wrong Padrow (%d) fROB=%d, fSIDE=%d, fMCM=%02d"
1330                       , fHC->fSM, fHC->fLayer, fHC->fStack, fMCM->fROW, fMCM->fROB, fHC->fSide, fMCM->fMCM ));
1331       if (fRawReader) fRawReader->AddMajorErrorLog(kWrongPadrow, "Wrong Row");
1332       return kFALSE;
1333     }
1334   return kTRUE;
1335 }
1336
1337 //------------------------------------------------------------
1338 Bool_t 
1339 AliTRDrawStreamTB::IsMCMheaderOK()
1340 {
1341   //
1342   // check the mcm header
1343   //
1344
1345   if ( fMCM->fCorrupted > 1 )
1346     {
1347       if (fRawReader) fRawReader->AddMajorErrorLog(kMCMheaderCorrupted,"ADC mask Corrupted"); 
1348       if (fgWarnError) AliWarning(Form("Wrong ADC Mask word 0x%08x %s. Error : %d\n", *fMCM->fPos, DumpMCMadcMask(fMCM), fMCM->fCorrupted));
1349       return kFALSE;
1350     }
1351
1352   if ( fMCM->fCorrupted > 0 )
1353     {
1354       if (fRawReader) fRawReader->AddMajorErrorLog(kMCMheaderCorrupted,"Corrupted"); 
1355       if (fgWarnError) AliWarning(Form("Wrong MCM word 0x%08x %s. Error : %d\n", *fMCM->fPos, DumpMCMinfo(fMCM), fMCM->fCorrupted));
1356       return kFALSE;
1357     }
1358
1359   if ( fMCM->fMCM < 0 || fMCM->fMCM > 15 || fMCM->fROB < 0 || fMCM->fROB > 7 ) 
1360     {
1361       if (fRawReader) fRawReader->AddMajorErrorLog(kWrongMCMorROB,"Wrong ROB or MCM"); 
1362       if (fgWarnError) AliWarning(Form("Wrong fMCM or fROB. %s\n", DumpMCMinfo(fMCM)));
1363       return kFALSE;
1364     }
1365
1366   if (IsRowValid() == kFALSE)
1367     return kFALSE;
1368
1369   return kTRUE;
1370 }
1371
1372 //------------------------------------------------------------
1373 Bool_t 
1374 AliTRDrawStreamTB::IsMCMevCounterOK()
1375 {
1376   //
1377   // Check the MCM event counter
1378   //
1379
1380   if (fEventCounter == 0)
1381     {
1382       fEventCounter = fMCM->fEvCounter;
1383     }
1384
1385   if (fEventCounter < fLastEventCounter)
1386     {
1387       fMCM->fCorrupted += 4;
1388       if (fgWarnError) AliWarning(Form("Event from the past? Current %d Last %d %s. Error : %d\n", fEventCounter, fLastEventCounter, DumpMCMinfo(fMCM), fMCM->fCorrupted));
1389       if (fRawReader) fRawReader->AddMajorErrorLog(kMCMeventMissmatch, "Wrong MCM event counter ? Past-Future");
1390       return kFALSE;
1391     }
1392
1393   if (fEventCounter != fMCM->fEvCounter)
1394     {
1395       fMCM->fCorrupted += 4;
1396       if (fgWarnError) AliWarning(Form("Event missmatch? FirstMCMs %d ThisMCMs %d %s. Error : %d\n", fEventCounter, fMCM->fEvCounter, DumpMCMinfo(fMCM), fMCM->fCorrupted));
1397       if (fRawReader) fRawReader->AddMajorErrorLog(kMCMeventMissmatch, "Wrong MCM event counter ?");
1398       return kFALSE;
1399     }
1400
1401   return kTRUE;
1402 }
1403
1404 //------------------------------------------------------------
1405 Bool_t 
1406 AliTRDrawStreamTB::DecodeMCMheader()
1407 {
1408   //
1409   // decode the mcm header
1410   //
1411
1412   DecodeMCMheader(fpPos, fMCM); 
1413   if (fHC->fCorrupted >= 16)
1414     {
1415       fpPos--; 
1416       return kFALSE;
1417     }
1418
1419   fMCM->fROW = fTRDfeeParam->GetPadRowFromMCM(fMCM->fROB, fMCM->fMCM); 
1420
1421   if ((fHC->fRawVMajor > 2 && fHC->fRawVMajor <5) || (fHC->fRawVMajor > 31 && fHC->fRawVMajor < 64)) //cover old and new version definition of ZS data
1422     {
1423       fpPos++;
1424       if ( fpPos < fpEnd )
1425         {
1426           DecodeMask(fpPos, fMCM); 
1427           if (fHC->fCorrupted >= 16)
1428             {
1429               fpPos--; 
1430               return kFALSE;
1431             }
1432           MCMADCwordsWithTbins(fHC->fTimeBins, fMCM);
1433           fMCM->fAdcDataPos = fpPos + 1;
1434         }
1435       else
1436         {
1437           if (fgWarnError) AliWarning("Expected ADC mask word. Fail due to buffer END.");         
1438           if (fRawReader) fRawReader->AddMajorErrorLog(kMCMADCMaskMissing,"Missing"); 
1439           return kFALSE;
1440         }
1441     }
1442   else
1443     {
1444       UInt_t dummyMask = MCM_DUMMY_ADCMASK_VAL;
1445       DecodeMask(&dummyMask, fMCM); 
1446       MCMADCwordsWithTbins(fHC->fTimeBins, fMCM);
1447       fMCM->fAdcDataPos = fpPos + 1;
1448     }
1449
1450   if (fgDebugFlag)  
1451     {
1452       AliDebug(6, DumpMCMinfo(fMCM));
1453       AliDebug(7, DumpMCMadcMask(fMCM));
1454     }
1455
1456   if (IsMCMheaderOK() == kFALSE)
1457       return kFALSE;
1458
1459   if (IsMCMevCounterOK() == kFALSE) 
1460       return kFALSE;
1461     
1462   return kTRUE;
1463 }
1464
1465 //------------------------------------------------------------
1466 Bool_t 
1467 AliTRDrawStreamTB::IsHCheaderOK()
1468 {
1469   //
1470   // check the half chamber header
1471   //
1472
1473   if (fHC->fCorrupted > 0)
1474     {
1475       if (fgWarnError) AliWarning(Form("Wrong HC Header word. Word 0x%08x Error : %d", *fHC->fPos, fHC->fCorrupted));
1476       if (fRawReader) fRawReader->AddMajorErrorLog(kHCHeaderCorrupt, "Corrupted"); 
1477
1478       return kFALSE;
1479     }
1480
1481   if (fHC->fStack < 0 || fHC->fStack > 4)
1482     {
1483       if (fgWarnError) AliWarning(Form("Wrong Stack %d", fHC->fStack));
1484       if (fRawReader) fRawReader->AddMajorErrorLog(kHCHeaderWrongStack, "Wrong Stack");       
1485       return kFALSE;
1486     }
1487
1488   if (fgStackNumberChecker)
1489     {
1490      if (fHC->fStack != fStackNumber) 
1491        {
1492         if (fgWarnError) AliWarning(Form("Missmatch: Stack in HC header %d HW-stack %d", 
1493                                        fHC->fStack, fStackNumber));
1494         if (fRawReader) fRawReader->AddMajorErrorLog(kHCHeaderWrongStack, "Stack-HWstack");       
1495         fStackNumber = -1;
1496         return kFALSE;
1497      }
1498     }
1499
1500   if (fHC->fLayer < 0 || fHC->fLayer >= AliTRDgeometry::kNplan)
1501     {
1502       if (fgWarnError) AliWarning(Form("Wrong plane(layer) %d", fHC->fLayer));
1503       if (fRawReader) fRawReader->AddMajorErrorLog(kHCHeaderWrongLayer, "Wrong Plane"); 
1504       return kFALSE;
1505     }
1506
1507   if (fgStackLinkNumberChecker)
1508     {
1509
1510       if ((fHC->fLayer * 2 != fStackLinkNumber) && (fHC->fLayer * 2 != fStackLinkNumber - 1)) 
1511         {
1512           if (fgWarnError) AliWarning(Form("Missmatch: plane(layer) in HCheader %d HW-Link %d | %s", 
1513                                        fHC->fLayer, fStackLinkNumber, DumpStackInfo(fStack)));
1514           if (fRawReader) fRawReader->AddMajorErrorLog(kHCHeaderWrongLayer, "Plane-Link missmatch"); 
1515           fStackLinkNumber = -1;
1516           return kFALSE;      
1517         }
1518     }
1519
1520   if (fHC->fSide < 0 || fHC->fSide > 1)
1521     {
1522       if (fgWarnError) AliWarning(Form("Wrong Side %d", fHC->fSide));
1523       if (fRawReader) fRawReader->AddMajorErrorLog(kHCHeaderWrongSide, "Wrong Side");       
1524       return kFALSE;
1525     }
1526   
1527   // SLOW GEOM
1528   fHC->fDET = fGeometry->GetDetector(fHC->fLayer, fHC->fStack, fHC->fSM);
1529   if (fHC->fDET < 0 || fHC->fDET >= AliTRDgeometry::kNdet)
1530     {
1531       if (fgWarnError) AliWarning(Form("Wrong detector %d", fHC->fDET));      
1532       if (fRawReader) fRawReader->AddMajorErrorLog(kHCHeaderWrongDet, "Wrong Det");       
1533       return kFALSE;
1534     }
1535
1536   // SLOW GEOM
1537   // this check fails - raw data inconsistent with geometry?
1538   if (fHC->fSM != fGeometry->GetSector(fHC->fDET)
1539       || fHC->fSM <0 || fHC->fSM >= AliTRDgeometry::kNsect)
1540     {
1541       if (fgWarnError) AliWarning(Form("Wrong SM(sector) %d (Geometry says: %d) Stack=%d Layer=%d Det=%d", 
1542                                        fHC->fSM, fGeometry->GetSector(fHC->fDET),
1543                                        fHC->fStack, fHC->fLayer, fHC->fDET));      
1544       if (fRawReader) fRawReader->AddMajorErrorLog(kHCHeaderWrongSM, "Wrong SM");       
1545       return kFALSE;
1546     }
1547
1548   // SLOW GEOM
1549   // CPU EXPENSIVE!!!
1550   fHC->fROC    = fGeometry->GetDetectorSec(fHC->fLayer, fHC->fStack);
1551   if (fHC->fROC < 0)
1552     {
1553       if (fRawReader) fRawReader->AddMajorErrorLog(kHCHeaderWrongROC, "Wrong ROC");       
1554       return kFALSE;
1555     }
1556
1557   fHC->fRowMax = fGeometry->GetRowMax(fHC->fLayer, fHC->fStack, fHC->fSM);
1558   if (fHC->fRowMax < 1)
1559     {
1560       if (fRawReader) fRawReader->AddMajorErrorLog(kHCHeaderWrongROC, "Wrong ROC Row Max");       
1561       return kFALSE;
1562     }
1563
1564   fHC->fColMax = fGeometry->GetColMax(fHC->fROC);
1565   if (fHC->fColMax < 1)
1566     {
1567       if (fRawReader) fRawReader->AddMajorErrorLog(kHCHeaderWrongROC, "Wrong ROC Col Max");       
1568       return kFALSE;
1569     }
1570   // extra - not needed
1571   //   if (fHC->fSM <0 || fHC->fSM >= AliTRDgeometry::kNsect)
1572   //     {
1573   //       if (fgWarnError) AliWarning(Form("Wrong SM(sector) %d (Geometry says: %d) Stack=%d Layer=%d", 
1574   //                  fHC->fSM, fGeometry->GetDetectorSec(fHC->fLayer, fHC->fStack),
1575   //                  fHC->fStack, fHC->fLayer));      
1576   //       return kFALSE;
1577   //     }
1578   
1579   return kTRUE;
1580 }
1581
1582 //------------------------------------------------------------
1583 Bool_t 
1584 AliTRDrawStreamTB::DecodeHCheader()
1585 {  
1586   //
1587   // decode the half chamber header
1588   //
1589
1590   DecodeHCwordH0(fpPos, fHC);
1591     
1592   if (fHC->fNExtraWords > 0)
1593     {
1594       fpPos++;
1595       if (fpPos < fpEnd)
1596         {
1597           DecodeHCwordH1(fpPos, fHC);
1598         }
1599       else
1600         {
1601           if (fgWarnError) AliWarning("Expected HC header word 1. Fail due to buffer END.");
1602           if (fRawReader) fRawReader->AddMajorErrorLog(kHCWordMissing,"Next HC word 1 (count from 0) missing"); 
1603           return kFALSE;
1604         }
1605     }
1606
1607   if (fgDebugFlag)  AliDebug(5, DumpHCinfoH0(fHC));
1608   if (fgDebugFlag)  AliDebug(5, DumpHCinfoH1(fHC));
1609
1610   fHC->fDET = -1;
1611   if (IsHCheaderOK() == kFALSE)
1612     {
1613       fHC->fCorrupted +=4;
1614       return kFALSE;
1615     }
1616   
1617   return kTRUE;
1618 }
1619
1620 //------------------------------------------------------------
1621 Bool_t 
1622 AliTRDrawStreamTB::DecodeHC()
1623 {
1624   //
1625   // decode the hc data
1626   // function for devel & debug
1627   //
1628
1629   if (DecodeHCheader() == kFALSE)
1630     {
1631       if (fgDebugStreamer)
1632         {
1633           TTreeSRedirector &cstream = *fgDebugStreamer;
1634           cstream << "HCDecodeError"
1635                   << "Event=" << fgStreamEventCounter
1636                   << ".stack=" << fStackNumber
1637                   << ".link=" << fStackLinkNumber
1638                   << ".hcCorrupted=" << fHC->fCorrupted
1639                   << ".hcRVmajor=" << fHC->fRawVMajor
1640                   << ".hcDCSboard=" << fHC->fDCSboard
1641                   << ".hcSM=" << fHC->fSM
1642                   << ".hcStack=" << fHC->fStack
1643                   << ".hcLayer=" << fHC->fLayer
1644                   << ".hcSide=" << fHC->fSide
1645                   << ".hcTbins=" << fHC->fTimeBins
1646                   << ".hcBunchCross=" << fHC->fBunchCrossCounter
1647                   << ".hcPreTrig=" << fHC->fPreTriggerCounter
1648                   << ".hcPreTrigPh=" << fHC->fPreTriggerPhase
1649                   << ".hcDet=" << fHC->fDET
1650                   << ".hcROC=" << fHC->fROC
1651                   << ".hcRowMax=" << fHC->fRowMax
1652                   << ".hcColMax=" << fHC->fColMax
1653                   << "\n";
1654         }
1655       
1656       if (fgWarnError) AliWarning("Header decode failed.");
1657       return kFALSE;
1658     }
1659   else
1660     {
1661       fpPos++;
1662       if (fpPos >= fpEnd)
1663         {
1664           if (fgWarnError) AliWarning("No MCM data? Not enough data in the buffer.");
1665           if (fRawReader) fRawReader->AddMajorErrorLog(kMCMdataMissing, "MCM data missing"); 
1666           return kFALSE;
1667         }
1668     }
1669
1670   fHC->fMCMmax = 0;
1671   while (*fpPos != ENDOFRAWDATAMARKER && fpPos < fpEnd)
1672     {
1673       if (fHC->fMCMmax > TRD_MAX_MCM)
1674         {
1675           if (fgWarnError) AliWarning("More mcm data than expected!");
1676           if (fRawReader) fRawReader->AddMajorErrorLog(kMCMoverflow, "Too many mcms found!"); 
1677           return kFALSE;
1678         }
1679
1680       fMCM = &fHC->fMCMs[fHC->fMCMmax];
1681
1682       if (DecodeMCMheader() == kFALSE)
1683         {
1684           if (fgDebugStreamer)
1685             {
1686               TTreeSRedirector &cstream = *fgDebugStreamer;
1687               cstream << "MCMDecodeError"
1688                       << "Event=" << fgStreamEventCounter
1689                       << ".stack=" << fStackNumber
1690                       << ".link=" << fStackLinkNumber
1691                       << ".hcDCSboard=" << fHC->fDCSboard
1692                       << ".hcSM=" << fHC->fSM
1693                       << ".hcStack=" << fHC->fStack
1694                       << ".hcLayer=" << fHC->fLayer
1695                       << ".hcSide=" << fHC->fSide
1696                       << ".hcBunchCross=" << fHC->fBunchCrossCounter
1697                       << ".hcPreTrig=" << fHC->fPreTriggerCounter
1698                       << ".hcPreTrigPh=" << fHC->fPreTriggerPhase
1699                       << ".hcDet=" << fHC->fDET
1700
1701                       << ".mcmCorrupted=" << fMCM->fCorrupted
1702                       << ".mcmROB=" << fMCM->fROB
1703                       << ".mcmMCM=" << fMCM->fMCM
1704                       << ".mcmADCMaskWord=" << fMCM->fADCMaskWord
1705                       << ".mcmEventCounter=" << fMCM->fEvCounter
1706
1707                       << ".fEventCounter=" << fEventCounter 
1708                       << ".fLastEventCounter=" << fLastEventCounter
1709                       << "\n";
1710             }
1711           
1712           if (fgSkipData == kTRUE || fHC->fCorrupted >= 16) 
1713             return kFALSE; //if(true), keep reading next words even previous words were corrupted - debugging purpose 
1714         }
1715
1716       fHC->fMCMmax++;
1717
1718       if (fMCM->fADCmax > 0)
1719         {
1720           fpPos++;
1721           if (fpPos >= fpEnd)
1722             {
1723               if (fgDebugFlag)  AliDebug(9, Form("Buffer short of data. ADC data expected."));    
1724               if (fRawReader) fRawReader->AddMajorErrorLog(kADCdataMissing, "ADC data missing"); 
1725             }
1726
1727           unsigned long randVal, iniVal, expectedVal;
1728           Int_t endbits = ENDBITS;
1729
1730           for (Int_t iadc = 0; iadc < fMCM->fADCmax; iadc++)
1731             {
1732               fADC = &fMCM->fADCs[iadc];
1733               fADC->fADCnumber = fMCM->fADCchannel[iadc];
1734
1735               if (fgDebugFlag)  AliDebug(9, Form("This is ADC %d of %d. ADC number is %d.", 
1736                                                 iadc+1, fMCM->fADCmax, fMCM->fADCchannel[iadc]));
1737
1738               if (fpPos + fMCM->fSingleADCwords >= fpEnd)
1739                 {
1740                   if (fgDebugStreamer)
1741                     {
1742                       TTreeSRedirector &cstream = *fgDebugStreamer;
1743                       Int_t ierr = -99;
1744                       cstream << "ADCDecodeError"
1745                               << "Event=" << fgStreamEventCounter
1746                               << ".hcSM=" << fHC->fSM
1747                               << ".hcStack=" << fHC->fStack
1748                               << ".hcLayer=" << fHC->fLayer
1749                               << ".hcSide=" << fHC->fSide
1750                               << ".hcDet=" << fHC->fDET
1751                               << ".mcmROB=" << fMCM->fROB
1752                               << ".mcmMCM=" << fMCM->fMCM
1753                               << ".mcmADCMaskWord=" << fMCM->fADCMaskWord
1754                               << ".adcErr=" << ierr
1755                               << ".adcNumber=" << ierr
1756                               << "\n";                  
1757                     }
1758                   
1759                   if (fgWarnError) AliWarning(Form("This is ADC %d of %d. ADC number is %d.", iadc+1, fMCM->fADCmax, fMCM->fADCchannel[iadc]));
1760                   if (fgWarnError) AliWarning("--> ADC (10 words) expected. Not enough data in the buffer.");
1761                   if (fgWarnError) AliWarning(Form("--> ADC mask : %s", DumpMCMadcMask(fMCM)));
1762
1763                   if (fRawReader) fRawReader->AddMajorErrorLog(kADCdataMissing, "ADC data missing - less than expected"); 
1764                   return kFALSE;
1765                 }
1766
1767               if (fHC->fRawVMajor < 64) // normal(real) ADC data
1768                 {
1769                   if (DecodeADC() == kFALSE)
1770                     {
1771                      // check if we are out of the det when the pad is shared
1772                       if (fADC->fIsShared && fADC->fCorrupted == 4)
1773                         {
1774                           fADC->fCOL = -1;
1775                           fpPos = fADC->fPos + fMCM->fSingleADCwords;
1776                         }
1777                       else
1778                         {
1779                           if (fgWarnError) AliWarning(Form("ADC decode failed."));
1780
1781                           if (fgDebugStreamer)
1782                             {
1783                               TTreeSRedirector &cstream = *fgDebugStreamer;
1784                               cstream << "ADCDecodeError"
1785                                   << "Event=" << fgStreamEventCounter
1786                                   << ".hcSM=" << fHC->fSM
1787                                   << ".hcStack=" << fHC->fStack
1788                                   << ".hcLayer=" << fHC->fLayer
1789                                   << ".hcSide=" << fHC->fSide
1790                                   << ".hcDet=" << fHC->fDET
1791                                   << ".mcmROB=" << fMCM->fROB
1792                                   << ".mcmMCM=" << fMCM->fMCM
1793                                   << ".mcmADCMaskWord=" << fMCM->fADCMaskWord
1794                                   << ".adcErr=" << fADC->fCorrupted
1795                                   << ".adcNumber=" << fADC->fADCnumber
1796                                   << "\n";                      
1797                             }
1798                           if (fHC->fCorrupted < 16)
1799                             fpPos = fADC->fPos + fMCM->fSingleADCwords;
1800
1801                           if (fgSkipData == kTRUE || fHC->fCorrupted >= 16) 
1802                              return kFALSE; //if(true), keep reading next words even previous words were corrupted - debugging purpose 
1803                         }
1804                     }
1805                 } 
1806               else // test pattern data
1807                 {
1808                   if (fHC->fRawVMajorOpt == 1) //test pattern 1
1809                     {
1810                       Int_t iCpu = iadc/5;
1811                       if(iadc==20) iCpu = 3;
1812                       if(iadc%5==0 && iadc!=20) randVal = (1 << 9) | (fMCM->fROB << 6) | (fMCM->fMCM << 2) | iCpu;
1813                       if (DecodeADCTP1(&randVal,&endbits) == kFALSE)
1814                         {
1815                           if (fgWarnError) AliWarning(Form("Summary: Test Pattern ADC data are corrupted in channel %d %s\n", iadc, DumpMCMinfo(fMCM)));
1816                           if (fgDebugStreamer)
1817                             {
1818                               TTreeSRedirector &cstream = *fgDebugStreamer;
1819                               cstream << "ADCDecodeError"
1820                                   << "Event=" << fgStreamEventCounter
1821                                   << ".hcSM=" << fHC->fSM
1822                                   << ".hcStack=" << fHC->fStack
1823                                   << ".hcLayer=" << fHC->fLayer
1824                                   << ".hcSide=" << fHC->fSide
1825                                   << ".hcDet=" << fHC->fDET
1826                                   << ".mcmROB=" << fMCM->fROB
1827                                   << ".mcmMCM=" << fMCM->fMCM
1828                                   << ".mcmADCMaskWord=" << fMCM->fADCMaskWord
1829                                   << ".adcErr=" << fADC->fCorrupted
1830                                   << ".adcNumber=" << fADC->fADCnumber
1831                                   << "\n";
1832                             }
1833                           if (fHC->fCorrupted < 16)
1834                             fpPos = fADC->fPos + fMCM->fSingleADCwords;
1835
1836                           if (fgSkipData == kTRUE || fHC->fCorrupted >= 16) 
1837                             return kFALSE; //if(true), keep reading next words even previous words were corrupted - debugging purpose 
1838                         }
1839                     }
1840
1841                   if (fHC->fRawVMajorOpt == 2 || fHC->fRawVMajorOpt == 3) //test pattern 2 or 3
1842                     {
1843                       iniVal = (fHC->fSM << 6) | (fHC->fStack << 0) | (fHC->fLayer << 3);
1844                       iniVal = iniVal + 0x49;
1845                       iniVal = (iniVal << 9) | (fMCM->fROB << 6) | (fMCM->fMCM << 2) | (fMCM->fEvCounter << 20);
1846                       Int_t iCpu = iadc/5;
1847                       if (iadc==20) iCpu = 3;
1848                       if (iadc%5==0 && iadc!=20)
1849                         {
1850                           if (fHC->fRawVMajorOpt == 2) { expectedVal = ((iniVal | iCpu) << 6) + 1; };
1851                           if (fHC->fRawVMajorOpt == 3) { expectedVal = iniVal | iCpu; };
1852                         }
1853                       if (DecodeADCTP23(&expectedVal) == kFALSE)
1854                         {
1855                           if (fgWarnError) AliWarning(Form("Summary: Test Pattern ADC data are corrupted in channel %d %s\n", iadc, DumpMCMinfo(fMCM)));
1856                           if (fgDebugStreamer)
1857                             {
1858                               TTreeSRedirector &cstream = *fgDebugStreamer;
1859                               cstream << "ADCDecodeError"
1860                                   << "Event=" << fgStreamEventCounter
1861                                   << ".hcSM=" << fHC->fSM
1862                                   << ".hcStack=" << fHC->fStack
1863                                   << ".hcLayer=" << fHC->fLayer
1864                                   << ".hcSide=" << fHC->fSide
1865                                   << ".hcDet=" << fHC->fDET
1866                                   << ".mcmROB=" << fMCM->fROB
1867                                   << ".mcmMCM=" << fMCM->fMCM
1868                                   << ".mcmADCMaskWord=" << fMCM->fADCMaskWord
1869                                   << ".adcErr=" << fADC->fCorrupted
1870                                   << ".adcNumber=" << fADC->fADCnumber
1871                                   << "\n";
1872                             }
1873                           if (fHC->fCorrupted < 16)
1874                             fpPos = fADC->fPos + fMCM->fSingleADCwords;
1875
1876                           if (fgSkipData == kTRUE || fHC->fCorrupted >= 16) 
1877                             return kFALSE; //if(true), keep reading next words even previous words were corrupted - debugging purpose 
1878                         }
1879                     }
1880                 }
1881             } 
1882         } 
1883       else
1884         {
1885           fpPos++;
1886         }
1887     }//while eof data
1888
1889   if (fpPos >= fpEnd)
1890     {
1891       if (fgWarnError) AliWarning("We are at the end of buffer. There should be one more word left.");
1892       return kFALSE;
1893     }
1894
1895   return kTRUE;
1896 }
1897 //------------------------------------------------------------
1898
1899 Bool_t
1900 AliTRDrawStreamTB::DecodeADC()
1901 {
1902   //
1903   // decode single ADC channel
1904   //
1905
1906   fADC->fCorrupted = 0;
1907   fMaskADCword = ADC_WORD_MASK(*fpPos);
1908   fADC->fPos = fpPos;
1909   fTbinADC = 0;
1910
1911   for (Int_t i = 0; i < TRD_MAX_TBINS; i++)
1912     fADC->fSignals[i] = 0;
1913
1914   for (Int_t iw = 0; iw < fMCM->fSingleADCwords; iw++)
1915     {
1916       if (HC_HEADER_MASK_ERR(*fpPos) == 0 || *fpPos == END_OF_TRACKLET_MARKERNEW)
1917         {
1918           if (fgWarnError) AliError(Form("There should be ADC data. We meet HC header or END_OF_TRACKLET_MARKER 0x%08x",*fpPos));
1919           fADC->fCorrupted += 16; 
1920           fHC->fCorrupted += 16; 
1921           fpPos--;
1922
1923           return kFALSE;
1924         }
1925       if (fMaskADCword != ADC_WORD_MASK(*fpPos))
1926         {
1927           fADC->fCorrupted += 1;
1928           if (fgWarnError) AliWarning(Form("Mask Change in ADC data Previous word (%d) : 0x%08x Previous mask : 0x%08x Current word(%d) : 0x%08x Current mask : 0x%08x", 
1929                                            iw - 1, *(fpPos-1), fMaskADCword, iw, *fpPos, ADC_WORD_MASK(*fpPos)));
1930           if (fRawReader) fRawReader->AddMajorErrorLog(kADCmaskMissmatch, "Mask change inside single channel"); 
1931           break;
1932         }
1933
1934       // here we subtract the baseline ( == common additive)
1935       fADC->fSignals[fTbinADC + 0] = ((*fpPos & 0x00000ffc) >>  2) - fgCommonAdditive;
1936       fADC->fSignals[fTbinADC + 1] = ((*fpPos & 0x003ff000) >> 12) - fgCommonAdditive;
1937       fADC->fSignals[fTbinADC + 2] = ((*fpPos & 0xffc00000) >> 22) - fgCommonAdditive;
1938
1939       fTbinADC += 3;
1940       fpPos++;
1941     }
1942
1943   if (fADC->fADCnumber <= 1 || fADC->fADCnumber == fMaxADCgeom - 1)
1944     {
1945       fADC->fIsShared = kTRUE;
1946     }
1947   else
1948     {
1949       fADC->fIsShared = kFALSE;
1950     }
1951
1952   if ( fADC->fADCnumber >= fMaxADCgeom - 1)
1953     {
1954       // let us guess the Column
1955       // take the one before last ADC and shift by one column
1956       // later we check if we are inside the limits of the chamber
1957       fADC->fCOL = AliTRDfeeParam::Instance()->GetPadColFromADC(fMCM->fROB, fMCM->fMCM, fADC->fADCnumber - 1);
1958       fADC->fCOL--;
1959     }
1960   else
1961     {
1962       fADC->fCOL = fTRDfeeParam->GetPadColFromADC(fMCM->fROB, fMCM->fMCM, fADC->fADCnumber);
1963     }
1964
1965   if (fADC->fCOL >= fHC->fColMax || fADC->fCOL < 0)
1966     {
1967       if (fADC->fIsShared == kFALSE)
1968         {
1969           fADC->fCorrupted += 2;
1970           if (fgWarnError) AliWarning(Form("Wrong column! ADCnumber %d MaxIs %d Col %d MaxIs %d MCM= %s", 
1971                                            fADC->fADCnumber, fMaxADCgeom, fADC->fCOL, fHC->fColMax, DumpMCMinfo(fMCM)));
1972           if (fRawReader) fRawReader->AddMajorErrorLog(kWrongPadcolumn, "Wrong column");          
1973         }
1974       else
1975         {
1976           // flag it - we are out of the det when the pad is shared
1977           if (fgDebugFlag) AliDebug(10, Form("Column out of the detector! ADCnumber %d MaxIs %d Col %d MaxIs %d MCM= %s", 
1978                                              fADC->fADCnumber, fMaxADCgeom, fADC->fCOL, fHC->fColMax, DumpMCMinfo(fMCM)));
1979           fADC->fCorrupted += 4;
1980         }
1981     }
1982
1983   if (fADC->fCorrupted > 0)
1984     {
1985       return kFALSE;
1986     }
1987
1988   fDecodedADCs++;
1989   return kTRUE;
1990 }
1991 //------------------------------------------------------------
1992
1993 Bool_t
1994 AliTRDrawStreamTB::DecodeADCTP1(unsigned long *randVal, Int_t *endbits)
1995 {
1996   //
1997   // decode test pattern ADC channel
1998   //
1999
2000   unsigned long expected;
2001
2002   fADC->fCorrupted = 0;
2003   fADC->fPos = fpPos;
2004   fTbinADC = 0;
2005
2006   for (Int_t i = 0; i < TRD_MAX_TBINS; i++)
2007      fADC->fSignals[i] = 0;
2008
2009   for (Int_t iw = 0; iw < fMCM->fSingleADCwords; iw++)
2010      {
2011        if (HC_HEADER_MASK_ERR(*fpPos) == 0 || *fpPos == END_OF_TRACKLET_MARKERNEW)
2012          {
2013            if (fgWarnError) AliError(Form("There should be ADC data. We meet HC header or END_OF_TRACKLET_MARKER 0x%08x",*fpPos));
2014            fADC->fCorrupted += 16; 
2015            fHC->fCorrupted += 16; 
2016            fpPos--;
2017
2018            return kFALSE;
2019          }
2020        expected = (AdvancePseudoRandom(randVal) << 2) | *endbits;
2021        expected |= AdvancePseudoRandom(randVal) << 12;
2022        expected |= AdvancePseudoRandom(randVal) << 22;
2023        if (*fpPos != expected)
2024          {
2025            if (fgWarnError) AliError(Form("Error: fpPos=%d, size=%d, found=0x%08lx, expected=0x%08lx",iw, fMCM->fSingleADCwords, *fpPos, expected));
2026            fADC->fCorrupted += 32; //test pattern corrupted
2027          }
2028        fADC->fSignals[fTbinADC + 0] = ((*fpPos & 0x00000ffc) >>  2);
2029        fADC->fSignals[fTbinADC + 1] = ((*fpPos & 0x003ff000) >> 12);
2030        fADC->fSignals[fTbinADC + 2] = ((*fpPos & 0xffc00000) >> 22);
2031
2032        fTbinADC += 3;
2033        fpPos++;
2034      }
2035   *endbits = *endbits ^ 0x01;
2036
2037   if (fADC->fADCnumber <= 1 || fADC->fADCnumber == fMaxADCgeom - 1)
2038     {
2039       fADC->fIsShared = kTRUE;
2040     }
2041   else
2042     {
2043       fADC->fIsShared = kFALSE;
2044     }
2045
2046   if ( fADC->fADCnumber >= fMaxADCgeom - 1)
2047     {
2048       fADC->fCOL = AliTRDfeeParam::Instance()->GetPadColFromADC(fMCM->fROB, fMCM->fMCM, fADC->fADCnumber - 1);
2049       fADC->fCOL--;
2050     }
2051   else
2052     {
2053       fADC->fCOL = fTRDfeeParam->GetPadColFromADC(fMCM->fROB, fMCM->fMCM, fADC->fADCnumber);
2054     }
2055
2056   if (fADC->fCorrupted > 0)
2057     {
2058       return kFALSE;
2059     }
2060
2061   fDecodedADCs++;
2062   return kTRUE;
2063 }
2064 //--------------------------------------------------------
2065
2066 Bool_t
2067 AliTRDrawStreamTB::DecodeADCTP23(unsigned long *expected)
2068 {
2069   //
2070   // decode test pattern ADC channel
2071   //
2072
2073   fADC->fCorrupted = 0;
2074   fADC->fPos = fpPos;
2075   fTbinADC = 0;
2076
2077   for (Int_t i = 0; i < TRD_MAX_TBINS; i++)
2078      fADC->fSignals[i] = 0;
2079
2080   for (Int_t iw = 0; iw < fMCM->fSingleADCwords; iw++)
2081      {
2082        if (*fpPos == END_OF_TRACKLET_MARKERNEW)
2083          {
2084            if (fgWarnError) AliError(Form("There should be ADC data. We meet END_OF_TRACKLET_MARKER 0x%08x",*fpPos));
2085            fADC->fCorrupted += 16; 
2086            fHC->fCorrupted += 16; 
2087            fpPos--;
2088
2089            return kFALSE;
2090          }
2091        if (*fpPos != *expected)
2092          {
2093            if (fgWarnError) 
2094              {
2095                if (fHC->fRawVMajorOpt == 2)
2096                  {
2097                    AliError(Form("Error: fpPos=%d, size=%d, found=0x%08lx, expected=0x%08lx",iw, fMCM->fSingleADCwords, *fpPos, *expected));
2098                    AliError(Form("Found ev.cnt. %ld, expected %ld",   (*fpPos >> 26),            (*expected >> 26)));
2099                    AliError(Form("Found sector  %ld, expected %ld",   (*fpPos >> 21) & 0x1f - 1, (*expected >> 21) & 0x1f - 1));
2100                    AliError(Form("Found layer   %ld, expected %ld",   (*fpPos >> 18) & 0x07 - 1, (*expected >> 18) & 0x07 - 1));
2101                    AliError(Form("Found chamber %ld, expected %ld",   (*fpPos >> 15) & 0x07 - 1, (*expected >> 15) & 0x07 - 1));
2102                    AliError(Form("Found ROB     %ld, expected %ld",   (*fpPos >> 12) & 0x07,     (*expected >> 12) & 0x07));
2103                    AliError(Form("Found MCM     %ld, expected %ld",   (*fpPos >>  8) & 0x0f,     (*expected >>  8) & 0x0f));
2104                    AliError(Form("Found CPU     %ld, expected %ld",   (*fpPos >>  6) & 0x03,     (*expected >>  6) & 0x03));
2105                    AliError(Form("Found counter %ld, expected %ld\n", (*fpPos >>  0) & 0x3f,     (*expected >>  0) & 0xf));
2106                  } 
2107                if (fHC->fRawVMajorOpt == 3)
2108                  {
2109                    AliError(Form("Error: fpPos=%d, size=%d, found=0x%08lx, expected=0x%08lx",iw, fMCM->fSingleADCwords, *fpPos, *expected));
2110                    AliError(Form("Found ev.cnt. %ld, expected %ld",   (*fpPos >> 20),            (*expected >> 20)));
2111                    AliError(Form("Found sector  %ld, expected %ld",   (*fpPos >> 15) & 0x1f - 1, (*expected >> 15) & 0x1f - 1));
2112                    AliError(Form("Found layer   %ld, expected %ld",   (*fpPos >> 12) & 0x07 - 1, (*expected >> 12) & 0x07 - 1));
2113                    AliError(Form("Found chamber %ld, expected %ld",   (*fpPos >>  9) & 0x07 - 1, (*expected >>  9) & 0x07 - 1));
2114                    AliError(Form("Found ROB     %ld, expected %ld",   (*fpPos >>  6) & 0x07,     (*expected >>  6) & 0x07));
2115                    AliError(Form("Found MCM     %ld, expected %ld",   (*fpPos >>  2) & 0x0f,     (*expected >>  2) & 0x0f));
2116                    AliError(Form("Found CPU     %ld, expected %ld\n", (*fpPos >>  0) & 0x03,     (*expected >>  0) & 0x03));
2117                  } 
2118
2119              }
2120            fADC->fCorrupted += 32; //test pattern corrupted
2121          }
2122        fADC->fSignals[fTbinADC + 0] = ((*fpPos & 0x00000ffc) >>  2);
2123        fADC->fSignals[fTbinADC + 1] = ((*fpPos & 0x003ff000) >> 12);
2124        fADC->fSignals[fTbinADC + 2] = ((*fpPos & 0xffc00000) >> 22);
2125
2126        fTbinADC += 3;
2127        fpPos++;
2128        if (fHC->fRawVMajorOpt == 2) (*expected)++; 
2129      }
2130
2131   if (fADC->fADCnumber <= 1 || fADC->fADCnumber == fMaxADCgeom - 1)
2132     {
2133       fADC->fIsShared = kTRUE;
2134     }
2135   else
2136     {
2137       fADC->fIsShared = kFALSE;
2138     }
2139
2140   if ( fADC->fADCnumber >= fMaxADCgeom - 1)
2141     {
2142       fADC->fCOL = AliTRDfeeParam::Instance()->GetPadColFromADC(fMCM->fROB, fMCM->fMCM, fADC->fADCnumber - 1);
2143       fADC->fCOL--;
2144     }
2145   else
2146     {
2147       fADC->fCOL = fTRDfeeParam->GetPadColFromADC(fMCM->fROB, fMCM->fMCM, fADC->fADCnumber);
2148     }
2149
2150   if (fADC->fCorrupted > 0)
2151     {
2152       return kFALSE;
2153     }
2154
2155   fDecodedADCs++;
2156   return kTRUE;
2157 }
2158 //--------------------------------------------------------
2159
2160
2161 void AliTRDrawStreamTB::DecodeSMInfo(const UInt_t *word, struct AliTRDrawSM *sm) const
2162 {
2163   //
2164   // Decode the data *word into SM info structure
2165   //
2166     
2167   sm->fPos = (UInt_t*)word;
2168
2169   // do it once here
2170   UInt_t vword = *word;
2171   sm->fHeaderSize = SM_HEADER_SIZE(vword);
2172     
2173   if (TRACKLETS_ENABLED(vword) > 0)
2174     sm->fTrackletEnable = kTRUE;
2175   else
2176     sm->fTrackletEnable = kFALSE;
2177     
2178   UInt_t stackMask = STACK_MASK(vword);
2179   sm->fActiveStacks = 0;
2180   for (Int_t i = 0; i < 5; i++)
2181     {
2182       //if ((stackMask >> i) & 0x1 > 0)
2183       if (IS_BIT_SET(stackMask,i) > 0)
2184         {
2185           sm->fStackActive[i] = kTRUE;
2186           sm->fActiveStacks++;
2187         }
2188       else
2189         {
2190           sm->fStackActive[i] = kFALSE;
2191         }
2192     }
2193 }
2194
2195 //--------------------------------------------------------
2196 const char *AliTRDrawStreamTB::DumpSMInfo(const struct AliTRDrawSM *sm)
2197 {
2198   //
2199   // Get SM structure into a const char
2200   //
2201     
2202   return Form("[ SM Info 0x%08x] : Hsize %d TrackletEnable %d Stacks %d %d %d %d %d",
2203               *sm->fPos,
2204               sm->fHeaderSize, sm->fTrackletEnable,
2205               sm->fStackActive[0], sm->fStackActive[1], sm->fStackActive[2],
2206               sm->fStackActive[3], sm->fStackActive[4]);      
2207 }
2208
2209 //--------------------------------------------------------
2210 void AliTRDrawStreamTB::DecodeStackInfo(const UInt_t *word, struct AliTRDrawStack *st) const
2211 {
2212   //
2213   // Decode stack info - active links
2214   //
2215
2216   st->fPos = (UInt_t*)word;
2217       
2218   // do it once here
2219   UInt_t vword = *word;
2220   st->fHeaderSize = STACK_HEADER_SIZE(vword);
2221
2222   UInt_t linkMask = STACK_LINK_WORD(vword);
2223   st->fActiveLinks = 0;
2224   for (Int_t i = 0; i < 12; i++)
2225     {
2226       //if (linkMask & (0x1 << i) > 0)
2227       if (IS_BIT_SET(linkMask,i) > 0)
2228         {
2229           st->fLinksActive[i] = kTRUE;
2230           st->fTrackletDecode[i] = kTRUE;
2231           st->fHCDecode[i] = kTRUE;
2232           st->fActiveLinks++;
2233         }
2234       else
2235         {
2236           st->fTrackletDecode[i] = kFALSE;
2237           st->fLinksActive[i] = kFALSE;
2238           st->fHCDecode[i] = kFALSE;
2239         }
2240     }
2241 }
2242   
2243 //--------------------------------------------------------
2244 const char *AliTRDrawStreamTB::DumpStackInfo(const struct AliTRDrawStack *st)
2245 {
2246   //
2247   // format the string with the stack info
2248   //
2249   return Form("[ Stack Info 0x%08x ] : Hsize %d Links Active %d %d %d %d %d %d %d %d %d %d %d %d",
2250               *st->fPos,
2251               st->fHeaderSize,
2252               st->fLinksActive[0], st->fLinksActive[1], st->fLinksActive[2], st->fLinksActive[3],
2253               st->fLinksActive[4], st->fLinksActive[5], st->fLinksActive[6], st->fLinksActive[7],
2254               st->fLinksActive[8], st->fLinksActive[9], st->fLinksActive[10], st->fLinksActive[11]);
2255 }
2256
2257 //--------------------------------------------------------
2258 void AliTRDrawStreamTB::DecodeHCwordH0(const UInt_t *word, struct AliTRDrawHC *hc) const
2259 {
2260   //
2261   // decode the hc header word 0
2262   //
2263
2264   // do it once here
2265   UInt_t vword = *word;
2266
2267   hc->fCorrupted = HC_HEADER_MASK_ERR(vword);
2268   if (hc->fCorrupted > 0)
2269     {
2270       hc->fH0ErrorCounter++;
2271     }
2272
2273   hc->fSpecialRawV =  HC_SPECIAL_RAW_VERSION(vword);
2274   hc->fRawVMajor = HC_MAJOR_RAW_VERSION(vword);
2275   hc->fRawVMajorOpt = HC_MAJOR_RAW_VERSION_OPT(vword); 
2276   hc->fRawVMinor = HC_MINOR_RAW_VERSION(vword);
2277   hc->fNExtraWords = HC_EXTRA_WORDS(vword);
2278   hc->fDCSboard = HC_DCS_BOARD(vword);
2279   hc->fSM = HC_SM_NUMBER(vword);
2280   hc->fStack = HC_STACK_NUMBER(vword);
2281   hc->fLayer = HC_LAYER_NUMBER(vword);
2282   hc->fSide = HC_SIDE_NUMBER(vword);
2283
2284   hc->fPos[0] = (UInt_t*)word;
2285
2286 }
2287
2288 //--------------------------------------------------------
2289 void AliTRDrawStreamTB::DecodeHCwordH1(const UInt_t *word, struct AliTRDrawHC *hc) const
2290 {
2291   //
2292   // 
2293   //
2294
2295   // do it once here
2296   UInt_t vword = *word;
2297
2298   hc->fCorrupted += 2 * HC_HEADER_MASK_ERR(vword);
2299   if (hc->fCorrupted >= 2)
2300     {
2301       hc->fH1ErrorCounter++;
2302     }
2303
2304   hc->fTimeBins = HC_NTIMEBINS(vword);
2305   hc->fBunchCrossCounter = HC_BUNCH_CROSS_COUNTER(vword);
2306   hc->fPreTriggerCounter = HC_PRETRIGGER_COUNTER(vword);
2307   hc->fPreTriggerPhase = HC_PRETRIGGER_PHASE(vword);
2308
2309   hc->fPos[1] = (UInt_t*)word;
2310 }
2311   
2312 //--------------------------------------------------------
2313 const char *AliTRDrawStreamTB::DumpHCinfoH0(const struct AliTRDrawHC *hc)
2314 {
2315   //
2316   // 
2317   //
2318   if (!hc)
2319     return Form("Unable to dump. Null received as parameter!?!");
2320   else
2321     return Form("[ HC[0] at 0x%08x ] : 0x%08x Info is : RawV %d SM %d Stack %d Layer %d Side %d DCSboard %d",
2322                 hc->fPos[0], *(hc->fPos[0]), hc->fRawVMajor, hc->fSM, hc->fStack, hc->fLayer, hc->fSide, hc->fDCSboard);
2323 }
2324
2325 //--------------------------------------------------------
2326 const char *AliTRDrawStreamTB::DumpHCinfoH1(const struct AliTRDrawHC *hc)
2327 {
2328   //
2329   // 
2330   //
2331   if (!hc)
2332     return Form("Unable to dump. Null received as parameter!?!");
2333   else
2334     return Form("[ HC[1] at 0x%08x ] : 0x%08x Info is : TBins %d BCcount %d PreTrigCount %d PreTrigPhase %d",
2335                 hc->fPos[1], *(hc->fPos[1]), hc->fTimeBins, hc->fBunchCrossCounter, hc->fPreTriggerCounter, hc->fPreTriggerPhase);
2336 }
2337
2338 //--------------------------------------------------------
2339 void AliTRDrawStreamTB::DecodeMCMheader(const UInt_t *word, struct AliTRDrawMCM *mcm) const
2340 {
2341   //
2342   // decode the mcm header
2343   //
2344
2345   UInt_t vword = *word;
2346
2347   if (vword == END_OF_TRACKLET_MARKERNEW) 
2348     {
2349       if (fgWarnError) AliError(Form("There should be MCM header. We meet END_OF_TRACKLET_MARKER 0x%08x",vword));
2350       mcm->fCorrupted += 16;
2351       fHC->fCorrupted += 16; //to finish data reading of this HC
2352     }
2353   mcm->fCorrupted = MCM_HEADER_MASK_ERR(vword); //if MCM header mask has error, set mcm->fCorrupted = 1
2354   if (mcm->fCorrupted)
2355     mcm->fErrorCounter++;
2356   mcm->fROB = MCM_ROB_NUMBER(vword);
2357   mcm->fMCM = MCM_MCM_NUMBER(vword);
2358   mcm->fEvCounter = MCM_EVENT_COUNTER(vword);
2359   mcm->fPos = (UInt_t*)word;
2360 }
2361
2362 //--------------------------------------------------------
2363 UInt_t AliTRDrawStreamTB::GetMCMadcMask(const UInt_t *word, struct AliTRDrawMCM *mcm) const
2364 {
2365   //
2366   // get the adc mask
2367   //
2368
2369   UInt_t vword = *word;
2370
2371   mcm->fADCindex  = 0;
2372   mcm->fADCmax    = 0;
2373   mcm->fADCMask   = 0;
2374   mcm->fADCcount  = 0;
2375   mcm->fADCMaskWord = vword;
2376
2377   if (vword == END_OF_TRACKLET_MARKERNEW)
2378     {
2379       if (fgWarnError) AliError(Form("There should be MCMadcMask. We meet END_OF_TRACKLET_MARKER 0x%08x",vword));
2380       mcm->fCorrupted += 16;
2381       fHC->fCorrupted += 16; //to finish data reading of this HC
2382     }
2383
2384   if ( MCM_ADCMASK_MASK_ERR(vword) == 0 )
2385     {
2386       mcm->fADCMask  = MCM_ADCMASK_VAL(vword);
2387       mcm->fADCcount = MCM_ADCMASK_NADC(~vword);
2388     }
2389   else
2390     {
2391       mcm->fADCMask = 0xffffffff;
2392       mcm->fCorrupted += 2;
2393       mcm->fMaskErrorCounter++;
2394     }
2395
2396   return mcm->fADCMask;
2397 }
2398
2399 //--------------------------------------------------------
2400 void AliTRDrawStreamTB::DecodeMask(const UInt_t *word, struct AliTRDrawMCM *mcm) const
2401 {
2402   //
2403   // decode the adc mask - adcs to be read out
2404   //
2405
2406   mcm->fMCMADCWords = 0;
2407   mcm->fSingleADCwords = 0;
2408   mcm->fADCmax = 0;
2409   mcm->fADCMask = GetMCMadcMask(word, mcm);
2410
2411   if (mcm->fADCMask > 0)
2412     {
2413       for (Int_t i = 0; i < TRD_MAX_ADC; i++)
2414         {
2415           mcm->fADCchannel[mcm->fADCmax] = 0;
2416           if( IS_BIT_SET(mcm->fADCMask,i) )
2417             {
2418               mcm->fADCchannel[mcm->fADCmax] = i;
2419               mcm->fADCmax++;
2420             }
2421         }
2422     }
2423   if (mcm->fADCcount != mcm->fADCmax && fHC->fRawVMajor >= 32) // backward compatibility
2424     {
2425       mcm->fCorrupted += 8; 
2426     }
2427 }
2428
2429 //--------------------------------------------------------
2430 void AliTRDrawStreamTB::MCMADCwordsWithTbins(UInt_t fTbins, struct AliTRDrawMCM *mcm) const
2431 {
2432   //
2433   //  count the expected mcm words for a given tbins
2434   //
2435   mcm->fMCMADCWords = ( mcm->fADCmax ) * ( fTbins / 3 );
2436   mcm->fSingleADCwords = 0;
2437   if (mcm->fADCmax > 0)
2438     {
2439       mcm->fSingleADCwords = mcm->fMCMADCWords/mcm->fADCmax;
2440     }
2441 }
2442   
2443 //--------------------------------------------------------
2444 const unsigned long AliTRDrawStreamTB::AdvancePseudoRandom(unsigned long *val) const
2445 {
2446   //
2447   // pseudo random number generator for test pattern data
2448   //
2449   unsigned long currentVal = *val;
2450
2451   *val = ( (*val << 1) | (((*val >> 9) ^ (*val >> 6)) & 1) ) & 0x3FF;
2452   return currentVal;
2453 }
2454
2455 //--------------------------------------------------------
2456 const char *AliTRDrawStreamTB::DumpMCMinfo(const struct AliTRDrawMCM *mcm)
2457 {
2458   //
2459   // mcm info in a string
2460   //
2461   if (!mcm)
2462     return Form("Unable to dump. Null received as parameter!?!");
2463   else
2464     return Form("[ MCM 0x%08x ] : ROB %d MCM %d EvCounter %d", *(mcm->fPos), mcm->fROB, mcm->fMCM, mcm->fEvCounter);
2465 }
2466   
2467 //--------------------------------------------------------
2468 //TString DumpMCMadcMask(const struct AliTRDrawMCMInfo *mcm)
2469 const char *AliTRDrawStreamTB::DumpMCMadcMask(const struct AliTRDrawMCM *mcm)
2470 {
2471   //
2472   // mcm adc mask in a string
2473   //
2474   if (!mcm)
2475     return Form("Unable to dump. Null received as parameter!?!");
2476
2477   TString tsreturn = Form("[Word] : 0x%08x => [Mask] : 0x%08x : ", mcm->fADCMaskWord, mcm->fADCMask);
2478   for (Int_t i = 0; i < 21; i++)
2479     {
2480       tsreturn += Form("%d ", mcm->fADCchannel[i]);
2481     }
2482   tsreturn += "";
2483   return tsreturn.Data();
2484 }