Merge branch 'master' of https://git.cern.ch/reps/AliRoot
[u/mrichter/AliRoot.git] / TRD / AliTRDrawStream.cxx
index b2a1adb..cf31aca 100644 (file)
 //  Decoding data from the TRD raw stream                                 //
 //  and translation into ADC values, on-line tracklets and tracks         //
 //                                                                        //
+//  CRC checks rely on boost, and are enabled only when TRD_RAW_CRC       //
+//  is defined                                                            //
+//                                                                        //
+//  Additional debug features can be enabled by defining TRD_RAW_DEBUG    //
+//                                                                        //
 //  Author: J. Klein (jochen.klein@cern.ch)                               //
 //                                                                        //
 ////////////////////////////////////////////////////////////////////////////
 #include <cstdio>
 #include <cstdarg>
 
+#if defined(TRD_RAW_CRC)
+#include <boost/crc.hpp>
+#endif
+
 #include "TClonesArray.h"
 #include "TTree.h"
 
 #include "AliLog.h"
 #include "AliRawReader.h"
+#include "AliTRDcalibDB.h"
 #include "AliTRDdigitsManager.h"
 #include "AliTRDdigitsParam.h"
+#include "AliTRDcalibDB.h"
+#include "AliTRDmcmSim.h"
 #include "AliTRDtrapConfig.h"
 #include "AliTRDarrayADC.h"
 #include "AliTRDarrayDictionary.h"
 #include "AliTRDSignalIndex.h"
 #include "AliTRDtrackletWord.h"
+#include "AliTRDtrackletMCM.h"
 #include "AliESDTrdTrack.h"
-#include "AliTreeLoader.h"
-#include "AliLoader.h"
 
 #include "AliTRDrawStream.h"
 
-// temporary
-#include "AliRunLoader.h"
-
 ClassImp(AliTRDrawStream)
 
 // some static information
@@ -60,14 +68,16 @@ const Int_t  AliTRDrawStream::fgkNsectors = 18;
 const Int_t  AliTRDrawStream::fgkNtriggers = 12;
 const UInt_t AliTRDrawStream::fgkDataEndmarker     = 0x00000000;
 const UInt_t AliTRDrawStream::fgkTrackletEndmarker = 0x10001000;
+const UInt_t AliTRDrawStream::fgkStackEndmarker[] = { 0xe0d01000, 0xe0d10000 };
 
 const char* AliTRDrawStream::fgkErrorMessages[] = {
   "Unknown error",
   "Link monitor active",
-  "Pretrigger counter mismatch",
+  "Event counter mismatch",
   "not a TRD equipment (1024-1041)",
   "Invalid Stack header",
   "Invalid detector number",
+  "Invalid pad row",
   "No digits could be retrieved from the digitsmanager",
   "HC header mismatch",
   "HC check bits wrong",
@@ -80,7 +90,8 @@ const char* AliTRDrawStream::fgkErrorMessages[] = {
   "Missing ADC data",
   "Missing expected ADC channels",
   "Missing MCM headers",
-  "Missing TP data"
+  "Missing TP data",
+  "CRC mismatch"
 };
 
 Int_t AliTRDrawStream::fgErrorDebugLevel[] = {
@@ -90,8 +101,9 @@ Int_t AliTRDrawStream::fgErrorDebugLevel[] = {
   1,
   0,
   1,
+  0,
   1,
-  1,
+  0,
   1,
   2,
   1,
@@ -102,6 +114,7 @@ Int_t AliTRDrawStream::fgErrorDebugLevel[] = {
   1,
   1,
   1,
+  0,
   0
 };
 
@@ -112,6 +125,7 @@ AliTRDrawStream::ErrorBehav_t AliTRDrawStream::fgErrorBehav[] = {
   AliTRDrawStream::kAbort,
   AliTRDrawStream::kAbort,
   AliTRDrawStream::kAbort,
+  AliTRDrawStream::kDiscardMCM,
   AliTRDrawStream::kAbort,
   AliTRDrawStream::kDiscardHC,
   AliTRDrawStream::kDiscardHC,
@@ -124,6 +138,7 @@ AliTRDrawStream::ErrorBehav_t AliTRDrawStream::fgErrorBehav[] = {
   AliTRDrawStream::kTolerate,
   AliTRDrawStream::kTolerate,
   AliTRDrawStream::kTolerate,
+  AliTRDrawStream::kTolerate,
   AliTRDrawStream::kTolerate
 };
 
@@ -152,12 +167,21 @@ AliTRDrawStream::AliTRDrawStream(AliRawReader *rawReader) :
   fCurrTrgHeaderAvail(0),
   fCurrTrgHeaderReadout(0),
   fCurrTrkHeaderAvail(0),
+  fCurrStackEndmarkerAvail(0),
   fCurrEvType(0),
   fCurrTriggerEnable(0),
   fCurrTriggerFired(0),
   fCurrTrackEnable(0),
   fCurrTrackletEnable(0),
   fCurrStackMask(0),
+#ifdef TRD_RAW_DEBUG
+  fCurrL0Count(),
+  fCurrL1aCount(),
+  fCurrL1rCount(),
+  fCurrL2aCount(),
+  fCurrL2rCount(),
+  fCurrL0offset(),
+#endif
   fCurrTrkHeaderIndexWord(0x0),
   fCurrTrkHeaderSize(0x0),
   fCurrTrkFlags(0x0),
@@ -175,6 +199,10 @@ AliTRDrawStream::AliTRDrawStream(AliRawReader *rawReader) :
   fCurrLinkMonitorFlags(0x0),
   fCurrLinkDataTypeFlags(0x0),
   fCurrLinkDebugFlags(0x0),
+  fCurrMatchFlagsSRAM(),
+  fCurrMatchFlagsPostBP(),
+  fCurrChecksumStack(),
+  fCurrChecksumSIU(0),
   fCurrSpecial(-1),
   fCurrMajor(-1),
   fCurrMinor(-1),
@@ -186,14 +214,14 @@ AliTRDrawStream::AliTRDrawStream(AliRawReader *rawReader) :
   fCurrHC(-1),
   fCurrCheck(-1),
   fCurrNtimebins(-1),
-  fCurrBC(-1),
   fCurrPtrgCnt(-1),
   fCurrPtrgPhase(-1),
+#ifdef TRD_RAW_DEBUG
+  fCurrBC(),
+#endif
   fNDumpMCMs(0),
-  fTrackletArray(0x0),
   fAdcArray(0x0),
   fSignalIndex(0x0),
-  fTrackletTree(0x0),
   fTracklets(0x0),
   fTracks(0x0),
   fMarkers(0x0)
@@ -206,6 +234,13 @@ AliTRDrawStream::AliTRDrawStream(AliRawReader *rawReader) :
   fCurrTrgHeaderIndexWord = new UInt_t[fgkNtriggers];
   fCurrTrgHeaderSize      = new UInt_t[fgkNtriggers];
   fCurrTrgFlags           = new UInt_t[fgkNsectors];
+#ifdef TRD_RAW_DEBUG
+  fCurrL0Count            = new UInt_t[fgkNsectors];
+  fCurrL1aCount           = new UInt_t[fgkNsectors];
+  fCurrL1rCount           = new UInt_t[fgkNsectors];
+  fCurrL2aCount           = new UInt_t[fgkNsectors];
+  fCurrL2rCount           = new UInt_t[fgkNsectors];
+#endif
   fCurrStackIndexWord     = new UInt_t[fgkNstacks];
   fCurrStackHeaderSize    = new UInt_t[fgkNstacks];
   fCurrStackHeaderVersion = new UInt_t[fgkNstacks];
@@ -213,7 +248,7 @@ AliTRDrawStream::AliTRDrawStream(AliRawReader *rawReader) :
   fCurrCleanCheckout      = new UInt_t[fgkNstacks];
   fCurrBoardId            = new UInt_t[fgkNstacks];
   fCurrHwRevTMU           = new UInt_t[fgkNstacks];
-  fCurrLinkMonitorFlags   = new UInt_t[fgkNstacks * fgkNlinks];
+  fCurrLinkMonitorFlags   = new UInt_t[fgkNsectors * fgkNstacks * fgkNlinks];
   fCurrLinkDataTypeFlags  = new UInt_t[fgkNstacks * fgkNlinks];
   fCurrLinkDebugFlags     = new UInt_t[fgkNstacks * fgkNlinks];
   for (Int_t iSector = 0; iSector < fgkNsectors; iSector++)
@@ -221,9 +256,6 @@ AliTRDrawStream::AliTRDrawStream(AliRawReader *rawReader) :
   for (Int_t i = 0; i < 100; i++)
     fDumpMCM[i] = 0;
 
-  // preparing TClonesArray
-  fTrackletArray = new TClonesArray("AliTRDtrackletWord", 256);
-
   // setting up the error tree
   fErrors = new TTree("errorStats", "Error statistics");
   fErrors->SetDirectory(0x0);
@@ -259,7 +291,7 @@ AliTRDrawStream::~AliTRDrawStream()
   delete [] fCurrLinkDebugFlags;
 }
 
-Bool_t AliTRDrawStream::ReadEvent(TTree *trackletTree)
+Bool_t AliTRDrawStream::ReadEvent()
 {
   // read the current event from the raw reader and fill it to the digits manager
 
@@ -268,9 +300,6 @@ Bool_t AliTRDrawStream::ReadEvent(TTree *trackletTree)
     return kFALSE;
   }
 
-  // tracklet output
-  ConnectTracklets(trackletTree);
-
   // some preparations
   fDigitsParam = 0x0;
 
@@ -297,10 +326,32 @@ Bool_t AliTRDrawStream::ReadEvent(TTree *trackletTree)
     if (fCurrTrailerReadout)
       ReadGTUTrailer();
 
+#ifdef TRD_RAW_CRC
+    boost::crc_optimal<16, 0x8005, 0, 0, false, false>      checksumStack[5];
+    boost::crc_optimal<32, 0x04C11DB7, 0, 0, false, false>  checksumSIU;
+    checksumSIU.reset();
+
+    // process CDH, replace size with 0xffffffff
+    UInt_t temp = 0xffffffff;
+    checksumSIU.process_bytes(&temp, sizeof(UInt_t));
+    UInt_t *data = (UInt_t*) fRawReader->GetDataHeader();
+    checksumSIU.process_bytes(&data[1], 7*sizeof(UInt_t));
+    // process payload including everything but the SIU checksum
+    checksumSIU.process_bytes(buffer, fRawReader->GetDataSize()-4);
+
+    if (checksumSIU() != fCurrChecksumSIU) {
+      EquipmentError(kCRCmismatch, "SIU data - recalc: 0x%08x - 0x%08x", fCurrChecksumSIU, checksumSIU());
+    }
+#endif
+
     // loop over all active links
     AliDebug(2, Form("Stack mask 0x%02x", fCurrStackMask));
     for (Int_t iStack = 0; iStack < fgkNstacks; iStack++) {
       fCurrSlot = iStack;
+#ifdef TRD_RAW_CRC
+      checksumStack[iStack].reset();
+#endif
+
       if ((fCurrStackMask & (1 << fCurrSlot)) == 0)
        continue;
 
@@ -312,20 +363,40 @@ Bool_t AliTRDrawStream::ReadEvent(TTree *trackletTree)
        if ((fCurrLinkMask[fCurrSlot] & (1 << fCurrLink)) == 0)
          continue;
 
+#ifdef TRD_RAW_CRC
+       UInt_t *start = fPayloadCurr;
+#endif
+       Int_t   size  = 0;
+
        fErrorFlags = 0;
        // check for link monitor error flag
-       if (fCurrLinkMonitorFlags[fCurrSlot*fgkNlinks + fCurrLink] != 0) {
+       if (fCurrLinkMonitorFlags[(((fCurrEquipmentId - kDDLOffset) * fgkNstacks) + fCurrSlot) * fgkNlinks + fCurrLink] != 0) {
          LinkError(kLinkMonitor);
          if (fgErrorBehav[kLinkMonitor] == kTolerate)
-           ReadLinkData();
+           size += ReadLinkData();
        }
        else
          // read the data from one HC
-         ReadLinkData();
+         size += ReadLinkData();
 
        // read all data endmarkers
-       SeekNextLink();
+       size += SeekNextLink();
+
+#ifdef TRD_RAW_CRC
+       // always use data for CRC calculation
+       // (even if link monitor active)
+       UShort_t crc = CalcLinkChecksum(start, size);
+       checksumStack[iStack].process_bytes(&crc, sizeof(UShort_t));
+#endif
+      }
+#ifdef TRD_RAW_CRC
+      if (fDigitsManager && (checksumStack[iStack]() != fCurrChecksumStack[fCurrEquipmentId - kDDLOffset][iStack])) {
+       StackError(kCRCmismatch, "data - recalc: 0x%04x - 0x%04x", fCurrChecksumStack[fCurrEquipmentId - kDDLOffset][iStack], checksumStack[iStack]());
       }
+#endif
+
+      // continue with next stack
+      SeekNextStack();
     }
   }
 
@@ -383,22 +454,6 @@ Int_t AliTRDrawStream::NextChamber(AliTRDdigitsManager *digMgr)
 
   fErrorFlags = 0;
 
-  // tracklet output preparation
-  TTree *trklTree = 0x0;
-  AliRunLoader *rl = AliRunLoader::Instance();
-  AliLoader* trdLoader = rl ? rl->GetLoader("TRDLoader") : NULL;
-  AliDataLoader *trklLoader = trdLoader ? trdLoader->GetDataLoader("tracklets") : NULL;
-  if (trklLoader) {
-    AliTreeLoader *trklTreeLoader = (AliTreeLoader*) trklLoader->GetBaseLoader("tracklets-raw");
-    if (trklTreeLoader)
-      trklTree = trklTreeLoader->Tree();
-    else
-      trklTree = trklLoader->Tree();
-  }
-
-  if (fTrackletTree != trklTree)
-    ConnectTracklets(trklTree);
-
   if (!fRawReader) {
     AliError("No raw reader available");
     return -1;
@@ -412,8 +467,14 @@ Int_t AliTRDrawStream::NextChamber(AliTRDdigitsManager *digMgr)
     while ((fCurrSlot < fgkNstacks) &&
           (((fCurrStackMask & (1 << fCurrSlot)) == 0) ||
            ((fCurrLinkMask[fCurrSlot] & (1 << fCurrLink))) == 0)) {
+      if ((fCurrStackMask & (1 << fCurrSlot)) == 0) {
+       ++fCurrSlot;
+       fCurrSlot = 0;
+       continue;
+      }
       fCurrLink++;
       if (fCurrLink >= fgkNlinks) {
+       SeekNextStack();
        fCurrLink = 0;
        fCurrSlot++;
       }
@@ -424,7 +485,7 @@ Int_t AliTRDrawStream::NextChamber(AliTRDdigitsManager *digMgr)
   fCurrHC   = (fCurrEquipmentId - kDDLOffset) * fgkNlinks * fgkNstacks +
     fCurrSlot * fgkNlinks + fCurrLink;
 
-  if (fCurrLinkMonitorFlags[fCurrSlot*fgkNlinks + fCurrLink] != 0) {
+  if (fCurrLinkMonitorFlags[(((fCurrEquipmentId - kDDLOffset) * fgkNstacks) + fCurrSlot) * fgkNlinks + fCurrLink] != 0) {
     LinkError(kLinkMonitor);
     if (fgErrorBehav[kLinkMonitor] == kTolerate)
       ReadLinkData();
@@ -441,7 +502,7 @@ Int_t AliTRDrawStream::NextChamber(AliTRDdigitsManager *digMgr)
     fCurrLink++;
     fCurrHC++;
     if (fCurrLinkMask[fCurrSlot] & (1 << fCurrLink)) {
-      if (fCurrLinkMonitorFlags[fCurrSlot*fgkNlinks + fCurrLink] != 0) {
+      if (fCurrLinkMonitorFlags[(((fCurrEquipmentId - kDDLOffset) * fgkNstacks) + fCurrSlot) * fgkNlinks + fCurrLink] != 0) {
        LinkError(kLinkMonitor);
        if (fgErrorBehav[kLinkMonitor] == kTolerate)
          ReadLinkData();
@@ -453,13 +514,19 @@ Int_t AliTRDrawStream::NextChamber(AliTRDdigitsManager *digMgr)
     }
   }
 
-  //??? to check
   do {
-    fCurrLink++;
-    if (fCurrLink >= fgkNlinks) {
+    if ((fCurrStackMask & (1 << fCurrSlot)) == 0) {
       fCurrLink = 0;
       fCurrSlot++;
     }
+    else {
+      fCurrLink++;
+      if (fCurrLink >= fgkNlinks) {
+       SeekNextStack();
+       fCurrLink = 0;
+       fCurrSlot++;
+      }
+    }
   } while ((fCurrSlot < fgkNstacks) &&
           (((fCurrStackMask & (1 << fCurrSlot)) == 0) ||
            ((fCurrLinkMask[fCurrSlot] & (1 << fCurrLink))) == 0));
@@ -536,6 +603,7 @@ Int_t AliTRDrawStream::ReadSmHeader()
   fCurrTrackletEnable         = ((*fPayloadCurr) >>  5) &    0x1;
   fCurrStackMask              = ((*fPayloadCurr)      ) &   0x1f;
   fCurrHwRev                  = (fPayloadCurr[1] >> 12) & 0xffff;
+  fCurrStackEndmarkerAvail    = 0;
 
   switch (fCurrSmHeaderVersion) {
   case 0xb:
@@ -558,6 +626,27 @@ Int_t AliTRDrawStream::ReadSmHeader()
     fCurrTrgFlags[fCurrEquipmentId-kDDLOffset] = fCurrTriggerFired;
     break;
 
+  case 0xd:
+    fCurrTrailerReadout = ((*fPayloadCurr) >> 10) &    0x1;
+    fCurrTrgHeaderAvail = 1;
+    fCurrTrgHeaderReadout = ((*fPayloadCurr) >>  9) &    0x1;
+    fCurrEvType         = ((*fPayloadCurr) >>  7) &    0x3;
+    fCurrTrkHeaderAvail = fCurrTrackEnable;
+    fCurrTriggerEnable  = (fPayloadCurr[2] >>  8) &  0xfff;
+    fCurrTriggerFired   = (fPayloadCurr[2] >>  20) &  0xfff;
+    fCurrTrgFlags[fCurrEquipmentId-kDDLOffset] = fCurrTriggerFired;
+    fCurrStackEndmarkerAvail    = 1;
+#ifdef TRD_RAW_DEBUG
+    if (fCurrSmHeaderSize > 7) {
+      fCurrL0Count[fCurrEquipmentId-kDDLOffset]  = fPayloadCurr[3];
+      fCurrL1aCount[fCurrEquipmentId-kDDLOffset] = fPayloadCurr[4];
+      fCurrL1rCount[fCurrEquipmentId-kDDLOffset] = fPayloadCurr[5];
+      fCurrL2aCount[fCurrEquipmentId-kDDLOffset] = fPayloadCurr[6];
+      fCurrL2rCount[fCurrEquipmentId-kDDLOffset] = fPayloadCurr[7];
+    }
+#endif
+    break;
+
   default:
     AliError(Form("unknown SM header version: 0x%x", fCurrSmHeaderVersion));
   }
@@ -635,6 +724,7 @@ Int_t AliTRDrawStream::DecodeGTUtracks()
 
            trk->SetFlags(0);
            trk->SetReserved(0);
+           trk->SetLabel(-3);
 
            Float_t pt = (((Int_t) (trackWord & 0xffff) ^ 0x8000) - 0x8000)/128.;
            if (TMath::Abs(pt) > 0.1) {
@@ -689,10 +779,11 @@ Int_t AliTRDrawStream::DecodeGTUtracks()
 
            trk->SetFlags(0);
            trk->SetReserved(0);
+           trk->SetLabel(-3);
 
            Float_t pt = (((Int_t) (trackWord & 0xffff) ^ 0x8000) - 0x8000)/128.;
            if (TMath::Abs(pt) > 0.1) {
-             trk->SetA((Int_t) (0.15*51625./100./pt / 160e-4 * 2));
+             trk->SetA((Int_t) (-0.15*51625./100./pt / 160e-4 * 2));
            }
          }
         }
@@ -717,6 +808,8 @@ Int_t AliTRDrawStream::DecodeGTUtracks()
        if ((idx == 0) &&
            ((fPayloadCurr[iWord] & 0xfffff0f0) == 0x13370000)) {
          fastWord = fPayloadCurr[iWord];
+         if (fastWord & (1 << 13))
+           fCurrTrgFlags[sector] |= 1 << (stack+11);
          AliDebug(1, Form("stack %i: fast trigger word: 0x%08x", stack, fastWord));
          continue;
        }
@@ -744,6 +837,7 @@ Int_t AliTRDrawStream::DecodeGTUtracks()
 
            trk->SetFlags(0);
            trk->SetReserved(0);
+           trk->SetLabel(-3);
 
            Float_t pt = (((Int_t) (trackWord & 0xffff) ^ 0x8000) - 0x8000)/128.;
            if (TMath::Abs(pt) > 0.1) {
@@ -813,6 +907,7 @@ Int_t AliTRDrawStream::DecodeGTUtracks()
 
            trk->SetFlags(0);
            trk->SetReserved(0);
+           trk->SetLabel(-3);
 
            Float_t pt = (((Int_t) (trackWord & 0xffff) ^ 0x8000) - 0x8000)/128.;
            if (TMath::Abs(pt) > 0.1) {
@@ -883,6 +978,7 @@ Int_t AliTRDrawStream::DecodeGTUtracks()
 
            trk->SetFlags(0);
            trk->SetReserved(0);
+           trk->SetLabel(-3);
 
            Float_t pt = (((Int_t) (trackWord & 0xffff) ^ 0x8000) - 0x8000)/128.;
            if (TMath::Abs(pt) > 0.1) {
@@ -946,6 +1042,7 @@ Int_t AliTRDrawStream::ReadTrackingHeader(Int_t stack)
            trk->SetC( (((trackWord >> 8)  &  0xffff) ^  0x8000) -  0x8000);
            trk->SetPID((trackWord >>  0) & 0xff);
            trk->SetStack(stack);
+           trk->SetLabel(-3);
 
            // now compare the track word with the one generated from the ESD information
            if (trackWord != trk->GetTrackWord(0)) {
@@ -957,7 +1054,7 @@ Int_t AliTRDrawStream::ReadTrackingHeader(Int_t stack)
        else {
          // done marker (so far only used to set trigger flag)
          fCurrTrgFlags[fCurrEquipmentId-kDDLOffset] |= 1 << (27 + stack);
-         fCurrTrkFlags[(fCurrEquipmentId-kDDLOffset)*fgkNstacks + fCurrStack] = trackWord;
+         fCurrTrkFlags[(fCurrEquipmentId-kDDLOffset)*fgkNstacks + stack] = trackWord;
 
          AliDebug(2, Form("tracking done marker: 0x%016llx, trigger flags: 0x%08x",
                           trackWord, fCurrTrgFlags[fCurrEquipmentId-kDDLOffset]));
@@ -977,7 +1074,8 @@ Int_t AliTRDrawStream::ReadTrackingHeader(Int_t stack)
          AliESDTrdTrack *trk = (AliESDTrdTrack*) (*fTracks)[trackIndex];
 
          trk->SetFlags((trackWord >> 52) & 0x7ff);
-         trk->SetReserved((trackWord >> 49) & 0x7);
+         trk->SetFlagsTiming((trackWord >> 51) & 0x1);
+         trk->SetReserved((trackWord >> 49) & 0x3);
          trk->SetY((trackWord >> 36) & 0x1fff);
          trk->SetTrackletIndex((trackWord >>  0) & 0x3f, 0);
          trk->SetTrackletIndex((trackWord >>  6) & 0x3f, 1);
@@ -986,6 +1084,10 @@ Int_t AliTRDrawStream::ReadTrackingHeader(Int_t stack)
          trk->SetTrackletIndex((trackWord >> 24) & 0x3f, 4);
          trk->SetTrackletIndex((trackWord >> 30) & 0x3f, 5);
 
+         if (trk->GetFlagsTiming() == 0) {
+           AliError(Form("*** track not in time: 0x%016llx", trk->GetExtendedTrackWord(0)));
+         }
+
          if (trackWord != trk->GetExtendedTrackWord(0)) {
            AliError(Form("extended track word 0x%016llx does not match the read one 0x%016llx",
                          trk->GetExtendedTrackWord(0), trackWord));
@@ -1048,12 +1150,16 @@ Int_t AliTRDrawStream::ReadStackHeader(Int_t stack)
   AliDebug(1, DumpRaw(Form("stack %i header", stack), fPayloadCurr, fCurrStackHeaderSize[stack]));
 
   if (fPayloadCurr - fPayloadStart >= fPayloadSize - (Int_t) fCurrStackHeaderSize[stack]) {
-    LinkError(kStackHeaderInvalid, "Stack index header aborted");
+    EquipmentError(kStackHeaderInvalid, "Stack index header %i incomplete", stack);
+    // dumping stack header
+    AliError(DumpRaw(Form("stack %i header", stack), fPayloadCurr, fCurrStackHeaderSize[stack]));
+
     return -1;
   }
 
   switch (fCurrStackHeaderVersion[stack]) {
   case 0xa:
+  case 0xb:
     if (fCurrStackHeaderSize[stack] < 8) {
       LinkError(kStackHeaderInvalid, "Stack header smaller than expected!");
       return -1;
@@ -1065,18 +1171,18 @@ Int_t AliTRDrawStream::ReadStackHeader(Int_t stack)
 
     for (Int_t iLayer = 0; iLayer < 6; iLayer++) {
       // A side
-      fCurrLinkMonitorFlags  [stack*fgkNlinks + iLayer*2]      = fPayloadCurr[iLayer+2] & 0xf;
-      fCurrLinkDataTypeFlags [stack*fgkNlinks + iLayer*2]      = (fPayloadCurr[iLayer+2] >> 4) & 0x3;
-      fCurrLinkDebugFlags    [stack*fgkNlinks + iLayer*2]      = (fPayloadCurr[iLayer+2] >> 12) & 0xf;
+      fCurrLinkMonitorFlags  [((fCurrEquipmentId - kDDLOffset) * fgkNstacks + stack) *fgkNlinks + iLayer*2] = fPayloadCurr[iLayer+2] & 0xf;
+      fCurrLinkDataTypeFlags [stack * fgkNlinks + iLayer*2]      = (fPayloadCurr[iLayer+2] >> 4) & 0x3;
+      fCurrLinkDebugFlags    [stack * fgkNlinks + iLayer*2]      = (fPayloadCurr[iLayer+2] >> 12) & 0xf;
       // B side
-      fCurrLinkMonitorFlags  [stack*fgkNlinks + iLayer*2 + 1]  = (fPayloadCurr[iLayer+2] >> 16) & 0xf;
-      fCurrLinkDataTypeFlags [stack*fgkNlinks + iLayer*2 + 1]  = (fPayloadCurr[iLayer+2] >> 20) & 0x3;
-      fCurrLinkDebugFlags    [stack*fgkNlinks + iLayer*2 + 1]  = (fPayloadCurr[iLayer+2] >> 28) & 0xf;
+      fCurrLinkMonitorFlags  [((fCurrEquipmentId - kDDLOffset) * fgkNstacks + stack) *fgkNlinks + iLayer*2 + 1] = (fPayloadCurr[iLayer+2] >> 16) & 0xf;
+      fCurrLinkDataTypeFlags [stack * fgkNlinks + iLayer*2 + 1]  = (fPayloadCurr[iLayer+2] >> 20) & 0x3;
+      fCurrLinkDebugFlags    [stack * fgkNlinks + iLayer*2 + 1]  = (fPayloadCurr[iLayer+2] >> 28) & 0xf;
     }
     break;
 
   default:
-    LinkError(kStackHeaderInvalid, "Invalid Stack Header version %x", fCurrStackHeaderVersion[stack]);
+    EquipmentError(kStackHeaderInvalid, "Invalid Stack Header version %x", fCurrStackHeaderVersion[stack]);
   }
 
   fPayloadCurr += fCurrStackHeaderSize[stack];
@@ -1091,18 +1197,42 @@ Int_t AliTRDrawStream::ReadGTUTrailer()
   UInt_t* trailer = fPayloadStart + fPayloadSize -1;
 
   // look for the trailer index word from the end
-  for (Int_t iWord = 0; iWord < fPayloadSize; iWord++) {
-    if ((fPayloadStart[fPayloadSize-1-iWord] & 0xffff) == 0x1f51) {
+  for (Int_t iWord = 0; iWord < fPayloadSize-2; iWord++) {
+    if ((fPayloadStart[fPayloadSize-3-iWord] == fgkStackEndmarker[0]) &&
+       (fPayloadStart[fPayloadSize-2-iWord] == fgkStackEndmarker[1]) &&
+       ((fPayloadStart[fPayloadSize-1-iWord] & 0xfff) == 0xf51)) {
       trailer = fPayloadStart + fPayloadSize - 1 - iWord;
       break;
     }
   }
 
-  if (((*trailer) & 0xffff) == 0x1f51) {
+  if (((*trailer) & 0xfff) == 0xf51) {
     UInt_t trailerIndexWord = (*trailer);
     Int_t trailerSize = (trailerIndexWord >> 16) & 0xffff;
+    // Int_t trailerVersion = (trailerIndexWord >> 12) & 0xf;
     AliDebug(2, DumpRaw("GTU trailer", trailer, trailerSize+1));
     // parse the trailer
+    if (trailerSize >= 4) {
+      // match flags from GTU
+      fCurrMatchFlagsSRAM[fCurrEquipmentId-kDDLOffset]     = (trailer[1] >>  0) &    0x1f;
+      fCurrMatchFlagsPostBP[fCurrEquipmentId-kDDLOffset]   = (trailer[1] >>  5) &    0x1f;
+      // individual checksums
+      fCurrChecksumStack[fCurrEquipmentId - kDDLOffset][0]   = (trailer[1] >> 16) &  0xffff;
+      fCurrChecksumStack[fCurrEquipmentId - kDDLOffset][1]   = (trailer[2] >>  0) &  0xffff;
+      fCurrChecksumStack[fCurrEquipmentId - kDDLOffset][2]   = (trailer[2] >> 16) &  0xffff;
+      fCurrChecksumStack[fCurrEquipmentId - kDDLOffset][3]   = (trailer[3] >>  0) &  0xffff;
+      fCurrChecksumStack[fCurrEquipmentId - kDDLOffset][4]   = (trailer[3] >> 16) &  0xffff;
+      fCurrChecksumSIU        = trailer[trailerSize];
+
+      if ((fCurrMatchFlagsSRAM[fCurrEquipmentId-kDDLOffset] & fCurrStackMask) != fCurrStackMask)
+       EquipmentError(kCRCmismatch, "CRC mismatch SRAM: 0x%02x", fCurrMatchFlagsSRAM[fCurrEquipmentId-kDDLOffset]);
+      if ((fCurrMatchFlagsPostBP[fCurrEquipmentId-kDDLOffset] & fCurrStackMask) != fCurrStackMask)
+       EquipmentError(kCRCmismatch, "CRC mismatch BP: 0x%02x", fCurrMatchFlagsPostBP[fCurrEquipmentId-kDDLOffset]);
+
+    }
+    else {
+      LinkError(kUnknown, "Invalid GTU trailer");
+    }
   }
   else
     EquipmentError(kUnknown, "trailer index marker mismatch");
@@ -1123,15 +1253,16 @@ Int_t AliTRDrawStream::ReadLinkData()
 
   if (fMarkers)
     new ((*fMarkers)[fMarkers->GetEntriesFast()])
-      AliTRDrawStreamError(-kHCactive, fCurrEquipmentId-kDDLOffset, fCurrStack, fCurrLink);
+      AliTRDrawStreamError(-kHCactive, fCurrEquipmentId-kDDLOffset, fCurrSlot, fCurrLink);
 
   if (fErrorFlags & kDiscardHC)
     return count;
 
-  //??? add check whether tracklets are enabled
-  count += ReadTracklets();
-  if (fErrorFlags & kDiscardHC)
-    return count;
+  if (fCurrTrackletEnable) {
+    count += ReadTracklets();
+    if (fErrorFlags & kDiscardHC)
+      return count;
+  }
 
   AliDebug(1, DumpRaw("HC header", fPayloadCurr, 4, 0x00000000));
   count += ReadHcHeader();
@@ -1153,13 +1284,13 @@ Int_t AliTRDrawStream::ReadLinkData()
        count += fPayloadCurr - startPos;
 
        // feeding TRAP config
-       AliTRDtrapConfig *trapcfg = AliTRDtrapConfig::Instance();
-       trapcfg->ReadPackedConfig(fCurrHC, startPos, fPayloadCurr - startPos);
+       AliTRDtrapConfig *trapcfg = AliTRDcalibDB::Instance()->GetTrapConfig();
+       AliTRDmcmSim::ReadPackedConfig(trapcfg, fCurrHC, startPos, fPayloadCurr - startPos);
       }
       else {
        Int_t tpmode = fCurrMajor & 0x7;
        AliDebug(1, Form("Checking testpattern (mode %i) data", tpmode));
-       ReadTPData(tpmode);
+       count += ReadTPData(tpmode);
       }
     }
     else {
@@ -1229,6 +1360,9 @@ Int_t AliTRDrawStream::ReadLinkData()
     fStats.fBytesRead                                            += count * sizeof(UInt_t);
   }
 
+  if ((fErrorFlags & kDiscardHC) && fAdcArray)
+    fAdcArray->SetDataInvalid(); // invalidate the data
+
   return count;
 }
 
@@ -1236,29 +1370,27 @@ Int_t AliTRDrawStream::ReadTracklets()
 {
   // read the tracklets from one HC
 
-  fTrackletArray->Clear();
+  Int_t nTracklets = 0;
 
   UInt_t *start = fPayloadCurr;
   while (*(fPayloadCurr) != fgkTrackletEndmarker &&
-        fPayloadCurr - fPayloadStart < fPayloadSize) {
-    new ((*fTrackletArray)[fTrackletArray->GetEntriesFast()]) AliTRDtrackletWord(*(fPayloadCurr), fCurrHC);
+        *(fPayloadCurr) != fgkStackEndmarker[0] &&
+        *(fPayloadCurr) != fgkStackEndmarker[1] &&
+        fPayloadCurr - fPayloadStart < (fPayloadSize - 1)) {
+    ++nTracklets;
+    if (fTracklets)
+      new ((*fTracklets)[fTracklets->GetEntriesFast()]) AliTRDtrackletWord(*(fPayloadCurr), fCurrHC);
 
     fPayloadCurr++;
   }
 
-  if (fTrackletArray->GetEntriesFast() > 0) {
-    AliDebug(1, Form("Found %i tracklets in %i %i %i (ev. %i)", fTrackletArray->GetEntriesFast(),
+  if (nTracklets > 0) {
+    AliDebug(1, Form("Found %i tracklets in %i %i %i (ev. %i)", nTracklets,
                     (fCurrEquipmentId-kDDLOffset), fCurrSlot, fCurrLink, fRawReader->GetEventIndex()));
     if (fCurrSm > -1 && fCurrSm < 18) {
-      fStats.fStatsSector[fCurrSm].fStatsHC[fCurrHC%60].fNTracklets += fTrackletArray->GetEntriesFast();
-      fStats.fStatsSector[fCurrSm].fNTracklets                      += fTrackletArray->GetEntriesFast();
+      fStats.fStatsSector[fCurrSm].fStatsHC[fCurrHC%60].fNTracklets += nTracklets;
+      fStats.fStatsSector[fCurrSm].fNTracklets                      += nTracklets;
     }
-    if (fTrackletTree)
-      fTrackletTree->Fill();
-    if (fTracklets)
-      for (Int_t iTracklet = 0; iTracklet < fTrackletArray->GetEntriesFast(); iTracklet++) {
-       new ((*fTracklets)[fTracklets->GetEntriesFast()]) AliTRDtrackletWord(*((AliTRDtrackletWord*)(*fTrackletArray)[iTracklet]));
-      }
   }
 
   // loop over remaining tracklet endmarkers
@@ -1277,8 +1409,12 @@ Int_t AliTRDrawStream::ReadHcHeader()
   AliDebug(1, Form("HC header: 0x%08x", *fPayloadCurr));
   UInt_t *start = fPayloadCurr;
   // check not to be at the data endmarker
-  if (*fPayloadCurr == fgkDataEndmarker)
+  if (*fPayloadCurr == fgkDataEndmarker ||
+      *(fPayloadCurr) == fgkStackEndmarker[0] ||
+      *(fPayloadCurr) == fgkStackEndmarker[1]) {
+    LinkError(kHCmismatch, "found endmarker where HC header should be");
     return 0;
+  }
 
   fCurrSpecial    = (*fPayloadCurr >> 31) & 0x1;
   fCurrMajor      = (*fPayloadCurr >> 24) & 0x7f;
@@ -1305,7 +1441,9 @@ Int_t AliTRDrawStream::ReadHcHeader()
 
   if (fCurrAddHcWords > 0) {
     fCurrNtimebins = (fPayloadCurr[1] >> 26) & 0x3f;
-    fCurrBC = (fPayloadCurr[1] >> 10) & 0xffff;
+#ifdef TRD_RAW_DEBUG
+    fCurrBC[fCurrHC] = (fPayloadCurr[1] >> 10) & 0xffff;
+#endif
     fCurrPtrgCnt = (fPayloadCurr[1] >> 6) & 0xf;
     fCurrPtrgPhase = (fPayloadCurr[1] >> 2) & 0xf;
   }
@@ -1321,6 +1459,7 @@ Int_t AliTRDrawStream::ReadTPData(Int_t mode)
   // evcnt checking missing
   Int_t cpu = 0;
   Int_t cpufromchannel[] = {0, 0, 0, 0, 0,  1, 1, 1, 1, 1,  2, 2, 2, 2, 2,  3, 3, 3, 3, 3, 3};
+  Int_t evno  = -1;
   Int_t evcnt = 0;
   Int_t count = 0;
   Int_t mcmcount = -1;
@@ -1343,23 +1482,42 @@ Int_t AliTRDrawStream::ReadTPData(Int_t mode)
     mcmcount++;
 
     // ----- checking for proper readout order - ROB -----
+    fCurrRobPos = ROB(*fPayloadCurr);
     if (GetROBReadoutPos(ROB(*fPayloadCurr) / 2) >= lastrobpos) {
+      if (GetROBReadoutPos(ROB(*fPayloadCurr) / 2) > lastrobpos)
+       lastmcmpos = -1;
       lastrobpos = GetROBReadoutPos(ROB(*fPayloadCurr) / 2);
     }
     else {
       ROBError(kPosUnexp, Form("#%i after #%i in readout order", GetROBReadoutPos(ROB(*fPayloadCurr) / 2), lastrobpos));
     }
-    fCurrRobPos = ROB(*fPayloadCurr);
 
     // ----- checking for proper readout order - MCM -----
-    if (GetMCMReadoutPos(MCM(*fPayloadCurr)) >= (lastmcmpos + 1) % 16) {
+    fCurrMcmPos = MCM(*fPayloadCurr);
+    if (GetMCMReadoutPos(MCM(*fPayloadCurr)) > lastmcmpos) {
       lastmcmpos = GetMCMReadoutPos(MCM(*fPayloadCurr));
     }
     else {
       MCMError(kPosUnexp, Form("#%i after #%i in readout order", GetMCMReadoutPos(MCM(*fPayloadCurr)), lastmcmpos));
     }
-    fCurrMcmPos = MCM(*fPayloadCurr);
 
+    if (EvNo(*fPayloadCurr) != (evno & 0xfffff)) {
+      if (evno == -1) {
+       evno = EvNo(*fPayloadCurr);
+      }
+      else {
+       MCMError(kEvCntMismatch, "%i <-> %i", evno, EvNo(*fPayloadCurr));
+#ifdef TRD_RAW_DEBUG
+       if (fCurrL0offset[fCurrHC/2] != 0)
+         LinkError(kEvCntMismatch, "offset for %i %i %i changed from %i to %i = %i - %i",
+                   fCurrEquipmentId, fCurrSlot, fCurrLink/2, fCurrL0offset[fCurrHC/2],
+                   EvNo(*fPayloadCurr) - fCurrL0Count[fCurrEquipmentId-kDDLOffset],
+                   EvNo(*fPayloadCurr), fCurrL0Count[fCurrEquipmentId-kDDLOffset]);
+       fCurrL0offset[fCurrHC/2] = EvNo(*fPayloadCurr) - fCurrL0Count[fCurrEquipmentId-kDDLOffset];
+       evno = fCurrL0Count[fCurrEquipmentId-kDDLOffset] + fCurrL0offset[fCurrHC/2];
+#endif
+      }
+    }
 
     fPayloadCurr++;
 
@@ -1416,13 +1574,17 @@ Int_t AliTRDrawStream::ReadTPData(Int_t mode)
 
        if (diff != 0) {
          MCMError(kTPmismatch,
-                  "Seen 0x%08x, expected 0x%08x, diff: 0x%08x (0x%02x) - word %2i (cpu %i, ch %i)",
-                  *fPayloadCurr, expword, diff, 0xff & (diff | diff >> 8 | diff >> 16 | diff >> 24),
+                  "Seen 0x%08x, expected 0x%08x, diff: 0x%08x, 0x%04x, 0x%02x - word %2i (cpu %i, ch %i)",
+                  *fPayloadCurr, expword, diff,
+                  0xffff & (diff | diff >> 16),
+                  0xff & (diff | diff >> 8 | diff >> 16 | diff >> 24),
                   wordcount, cpu, channelcount);;
        }
        fPayloadCurr++;
        count++;
        wordcount++;
+       if (*fPayloadCurr == fgkDataEndmarker)
+         return (fPayloadCurr - start);
       }
       channelcount++;
     }
@@ -1466,6 +1628,8 @@ Int_t AliTRDrawStream::ReadZSData()
   timebins = fNtimebins;
 
   while (*(fPayloadCurr) != fgkDataEndmarker &&
+        *(fPayloadCurr) != fgkStackEndmarker[0] &&
+        *(fPayloadCurr) != fgkStackEndmarker[1] &&
         fPayloadCurr - fPayloadStart < fPayloadSize) {
 
     // ----- Checking MCM Header -----
@@ -1473,6 +1637,7 @@ Int_t AliTRDrawStream::ReadZSData()
     UInt_t *startPosMCM = fPayloadCurr;
 
     // ----- checking for proper readout order - ROB -----
+    fCurrRobPos = ROB(*fPayloadCurr);
     if (GetROBReadoutPos(ROB(*fPayloadCurr) / 2) >= lastrobpos) {
       if (GetROBReadoutPos(ROB(*fPayloadCurr) / 2) > lastrobpos)
        lastmcmpos = -1;
@@ -1482,9 +1647,9 @@ Int_t AliTRDrawStream::ReadZSData()
       ROBError(kPosUnexp, Form("#%i after #%i and #%i in readout order",
                               GetROBReadoutPos(ROB(*fPayloadCurr) / 2), lastrobpos, GetROBReadoutPos(fCurrRobPos)));
     }
-    fCurrRobPos = ROB(*fPayloadCurr);
 
     // ----- checking for proper readout order - MCM -----
+    fCurrMcmPos = MCM(*fPayloadCurr);
     if (GetMCMReadoutPos(MCM(*fPayloadCurr)) > lastmcmpos) {
       lastmcmpos = GetMCMReadoutPos(MCM(*fPayloadCurr));
     }
@@ -1492,13 +1657,34 @@ Int_t AliTRDrawStream::ReadZSData()
       MCMError(kPosUnexp, Form("#%i after #%i and #%i in readout order",
                               GetMCMReadoutPos(MCM(*fPayloadCurr)), lastmcmpos, GetMCMReadoutPos(fCurrMcmPos)));
     }
-    fCurrMcmPos = MCM(*fPayloadCurr);
 
-    if (EvNo(*fPayloadCurr) != evno) {
-      if (evno == -1)
+#ifdef TRD_RAW_DEBUG
+    if (fCurrL0Count[fCurrEquipmentId-kDDLOffset] > 0) {
+      evno = fCurrL0Count[fCurrEquipmentId-kDDLOffset] + fCurrL0offset[fCurrHC/2];
+    }
+    fCurrEvCount[fCurrEquipmentId-kDDLOffset] = EvNo(*fPayloadCurr);
+#endif
+
+    if (EvNo(*fPayloadCurr) != (evno & 0xfffff)) {
+      if (evno == -1) {
        evno = EvNo(*fPayloadCurr);
+      }
       else {
-       MCMError(kPtrgCntMismatch, "%i <-> %i", evno, EvNo(*fPayloadCurr));
+       MCMError(kEvCntMismatch, "exp <-> SM: %i <-> %i", evno & 0xfffff, EvNo(*fPayloadCurr));
+#ifdef TRD_RAW_DEBUG
+       Int_t prevOffset = fCurrL0offset[fCurrHC/2];
+       fCurrL0offset[fCurrHC/2] = (- fCurrL0Count[fCurrEquipmentId-kDDLOffset] + EvNo(*fPayloadCurr)) % (1 << 20);
+       if (fCurrL0offset[fCurrHC/2] < 0)
+         fCurrL0offset[fCurrHC/2] += 0xfffff;
+       evno = (fCurrL0Count[fCurrEquipmentId-kDDLOffset] + fCurrL0offset[fCurrHC/2]) & 0xfffff;
+       if (prevOffset != 0)
+         LinkError(kEvCntMismatch, "offset for %i %i %i changed from %i to %i = %i - %i",
+                   fCurrEquipmentId, fCurrSlot, fCurrLink/2,
+                   prevOffset,
+                   fCurrL0offset[fCurrHC/2],
+                   fCurrL0Count[fCurrEquipmentId-kDDLOffset],
+                   EvNo(*fPayloadCurr));
+#endif
       }
     }
     Int_t adccoloff = AdcColOffset(*fPayloadCurr);
@@ -1506,6 +1692,13 @@ Int_t AliTRDrawStream::ReadZSData()
     Int_t row = Row(*fPayloadCurr);
     fPayloadCurr++;
 
+    if ((row > 11) && (fCurrStack == 2)) {
+      MCMError(kInvalidPadRow, "Data in padrow > 11 for stack 2");
+    }
+
+    if (fErrorFlags & (kDiscardHC | kDiscardDDL))
+      break;
+
     // ----- Reading ADC channels -----
     AliDebug(2, DumpAdcMask("ADC mask: ", *fPayloadCurr));
 
@@ -1584,16 +1777,20 @@ Int_t AliTRDrawStream::ReadZSData()
          }
        }
 
-       // filling the actual timebin data
-       int tb2 = 0x3ff & *fPayloadCurr >> 22;
-       int tb1 = 0x3ff & *fPayloadCurr >> 12;
-       int tb0 = 0x3ff & *fPayloadCurr >> 2;
-       if (adcwc != 0 || fCurrNtimebins <= 30)
-         fAdcArray->SetDataByAdcCol(row, adccol, currentTimebin++, tb0);
-       else
-         tb0 = -1;
-       fAdcArray->SetDataByAdcCol(row, adccol, currentTimebin++, tb1);
-       fAdcArray->SetDataByAdcCol(row, adccol, currentTimebin++, tb2);
+       if ((fErrorFlags & kDiscardMCM) == 0) {
+         // filling the actual timebin data
+         int tb2 = 0x3ff & (*fPayloadCurr >> 22);
+         int tb1 = 0x3ff & (*fPayloadCurr >> 12);
+         int tb0 = 0x3ff & (*fPayloadCurr >>  2);
+         if (adcwc != 0 || fCurrNtimebins <= 30)
+           fAdcArray->SetDataByAdcCol(row, adccol, currentTimebin++, tb0);
+         else
+           tb0 = -1;
+         if (currentTimebin < fCurrNtimebins)
+           fAdcArray->SetDataByAdcCol(row, adccol, currentTimebin++, tb1);
+         if (currentTimebin < fCurrNtimebins)
+           fAdcArray->SetDataByAdcCol(row, adccol, currentTimebin++, tb2);
+       }
 
        adcwc++;
        fPayloadCurr++;
@@ -1674,28 +1871,40 @@ Int_t AliTRDrawStream::ReadNonZSData()
     AliDebug(2, Form("MCM header: 0x%08x", *fPayloadCurr));
 
     // ----- checking for proper readout order - ROB -----
+    fCurrRobPos = ROB(*fPayloadCurr);
     if (GetROBReadoutPos(ROB(*fPayloadCurr) / 2) >= lastrobpos) {
+      if (GetROBReadoutPos(ROB(*fPayloadCurr) / 2) > lastrobpos)
+       lastmcmpos = -1;
       lastrobpos = GetROBReadoutPos(ROB(*fPayloadCurr) / 2);
     }
     else {
       ROBError(kPosUnexp, Form("#%i after #%i in readout order", GetROBReadoutPos(ROB(*fPayloadCurr) / 2), lastrobpos));
     }
-    fCurrRobPos = ROB(*fPayloadCurr);
 
     // ----- checking for proper readout order - MCM -----
-    if (GetMCMReadoutPos(MCM(*fPayloadCurr)) >= (lastmcmpos + 1) % 16) {
+    fCurrMcmPos = MCM(*fPayloadCurr);
+    if (GetMCMReadoutPos(MCM(*fPayloadCurr)) > lastmcmpos) {
       lastmcmpos = GetMCMReadoutPos(MCM(*fPayloadCurr));
     }
     else {
       MCMError(kPosUnexp, Form("#%i after #%i in readout order", GetMCMReadoutPos(MCM(*fPayloadCurr)), lastmcmpos));
     }
-    fCurrMcmPos = MCM(*fPayloadCurr);
 
-    if (EvNo(*fPayloadCurr) != evno) {
-      if (evno == -1)
+    if (EvNo(*fPayloadCurr) != (evno & 0xfffff)) {
+      if (evno == -1) {
        evno = EvNo(*fPayloadCurr);
+      }
       else {
-       MCMError(kPtrgCntMismatch, "%i <-> %i", evno, EvNo(*fPayloadCurr));
+       MCMError(kEvCntMismatch, "%i <-> %i", evno, EvNo(*fPayloadCurr));
+#ifdef TRD_RAW_DEBUG
+       if (fCurrL0offset[fCurrHC/2] != 0)
+         LinkError(kEvCntMismatch, "offset for %i %i %i changed from %i to %i = %i - %i",
+                   fCurrEquipmentId, fCurrSlot, fCurrLink/2, fCurrL0offset[fCurrHC/2],
+                   EvNo(*fPayloadCurr) - fCurrL0Count[fCurrEquipmentId-kDDLOffset],
+                   EvNo(*fPayloadCurr), fCurrL0Count[fCurrEquipmentId-kDDLOffset]);
+       fCurrL0offset[fCurrHC/2] = EvNo(*fPayloadCurr) - fCurrL0Count[fCurrEquipmentId-kDDLOffset];
+       evno = fCurrL0Count[fCurrEquipmentId-kDDLOffset] + fCurrL0offset[fCurrHC/2];
+#endif
       }
     }
 
@@ -1706,9 +1915,15 @@ Int_t AliTRDrawStream::ReadNonZSData()
     Int_t adccoloff = AdcColOffset(*fPayloadCurr);
     Int_t padcoloff = PadColOffset(*fPayloadCurr);
     Int_t row = Row(*fPayloadCurr);
-
     fPayloadCurr++;
 
+    if ((row > 11) && (fCurrStack == 2)) {
+      MCMError(kInvalidPadRow, "Data in padrow > 11 for stack 2");
+    }
+
+    if (fErrorFlags & (kDiscardHC | kDiscardDDL))
+      break;
+
     // ----- reading marked ADC channels -----
     while (channelcount < channelcountExp &&
           *(fPayloadCurr) != fgkDataEndmarker) {
@@ -1741,16 +1956,20 @@ Int_t AliTRDrawStream::ReadNonZSData()
          }
        }
 
-       // filling the actual timebin data
-       int tb2 = 0x3ff & *fPayloadCurr >> 22;
-       int tb1 = 0x3ff & *fPayloadCurr >> 12;
-       int tb0 = 0x3ff & *fPayloadCurr >> 2;
-       if (adcwc != 0 || fCurrNtimebins <= 30)
-         fAdcArray->SetDataByAdcCol(row, adccol, currentTimebin++, tb0);
-       else
-         tb0 = -1;
-       fAdcArray->SetDataByAdcCol(row, adccol, currentTimebin++, tb1);
-       fAdcArray->SetDataByAdcCol(row, adccol, currentTimebin++, tb2);
+       if ((fErrorFlags & kDiscardMCM) == 0) {
+         // filling the actual timebin data
+         int tb2 = 0x3ff & (*fPayloadCurr >> 22);
+         int tb1 = 0x3ff & (*fPayloadCurr >> 12);
+         int tb0 = 0x3ff & (*fPayloadCurr >>  2);
+         if (adcwc != 0 || fCurrNtimebins <= 30)
+           fAdcArray->SetDataByAdcCol(row, adccol, currentTimebin++, tb0);
+         else
+           tb0 = -1;
+         if (currentTimebin < fCurrNtimebins)
+           fAdcArray->SetDataByAdcCol(row, adccol, currentTimebin++, tb1);
+         if (currentTimebin < fCurrNtimebins)
+           fAdcArray->SetDataByAdcCol(row, adccol, currentTimebin++, tb2);
+       }
 
        adcwc++;
        fPayloadCurr++;
@@ -1782,6 +2001,67 @@ Int_t AliTRDrawStream::ReadNonZSData()
   return (fPayloadCurr - start);
 }
 
+#ifdef TRD_RAW_CRC
+UShort_t AliTRDrawStream::CalcLinkChecksum(UInt_t *data, Int_t size)
+{
+  // calculate the CRC for the data from this link
+  // must not change the pointers to the data
+
+  // always count two endmarkers
+  Int_t nEndmarkers = 0;
+  for (Int_t i = 0; i < size; i++) {
+    if (data[size-1 - i] != fgkDataEndmarker)
+      break;
+    nEndmarkers++;
+  }
+
+  size = size - (nEndmarkers-2);
+
+  boost::crc_optimal<16, 0x8005, 0, 0, false, false> checksumLink;
+
+  checksumLink.reset();
+  checksumLink.process_bytes(data, size*sizeof(UInt_t));
+  return checksumLink();
+}
+#else
+UShort_t AliTRDrawStream::CalcLinkChecksum(UInt_t * /* data */, Int_t /* size */)
+{
+  // checksum calculation relies on boost,
+  // we return 0 if we cannot calculate it
+
+  AliError("Checksum calculation relies on boost CRC implementation!");
+
+  return 0;
+}
+#endif
+
+Int_t AliTRDrawStream::SeekNextStack()
+{
+  // proceed in raw data stream till the next stack
+
+  if (!fCurrStackEndmarkerAvail)
+    return 0;
+
+  UInt_t *start = fPayloadCurr;
+
+  // read until data endmarkers
+  while ((fPayloadCurr - fPayloadStart < fPayloadSize-1) &&
+        ((fPayloadCurr[0] != fgkStackEndmarker[0]) ||
+         (fPayloadCurr[1] != fgkStackEndmarker[1])))
+    fPayloadCurr++;
+
+  if ((fPayloadCurr - start) != 0)
+    StackError(kUnknown, "skipped %i words to reach stack endmarker", fPayloadCurr - start);
+
+  AliDebug(2, Form("stack endmarker: 0x%08x 0x%08x", fPayloadCurr[0], fPayloadCurr[1]));
+
+  // goto next stack
+  fPayloadCurr++;
+  fPayloadCurr++;
+
+  return (fPayloadCurr-start);
+}
+
 Int_t AliTRDrawStream::SeekNextLink()
 {
   // proceed in raw data stream till the next link
@@ -1790,6 +2070,8 @@ Int_t AliTRDrawStream::SeekNextLink()
 
   // read until data endmarkers
   while (fPayloadCurr - fPayloadStart < fPayloadSize &&
+        ((fPayloadCurr[0] != fgkStackEndmarker[0]) ||
+         (fPayloadCurr[1] != fgkStackEndmarker[1])) &&
         *fPayloadCurr != fgkDataEndmarker)
     fPayloadCurr++;
 
@@ -1801,27 +2083,6 @@ Int_t AliTRDrawStream::SeekNextLink()
   return (fPayloadCurr - start);
 }
 
-Bool_t AliTRDrawStream::ConnectTracklets(TTree *trklTree)
-{
-  // connect the tracklet tree used to store the tracklet output
-
-  fTrackletTree = trklTree;
-  if (!fTrackletTree)
-    return kTRUE;
-
-  if (!fTrackletTree->GetBranch("hc"))
-    fTrackletTree->Branch("hc", &fCurrHC, "hc/I");
-  else
-    fTrackletTree->SetBranchAddress("hc", &fCurrHC);
-
-  if (!fTrackletTree->GetBranch("trkl"))
-    fTrackletTree->Branch("trkl", &fTrackletArray);
-  else
-    fTrackletTree->SetBranchAddress("trkl", &fTrackletArray);
-
-  return kTRUE;
-}
-
 
 void AliTRDrawStream::EquipmentError(ErrorCode_t err, const char *const msg, ...)
 {
@@ -2037,7 +2298,7 @@ Bool_t AliTRDrawStream::DumpingMCM(Int_t det, Int_t rob, Int_t mcm)  const
   return kFALSE;
 }
 
-TString AliTRDrawStream::DumpRaw(TString title, UInt_t *start, Int_t length, UInt_t endmarker)
+TString AliTRDrawStream::DumpRaw(TString title, const UInt_t *start, Int_t length, UInt_t endmarker)
 {
   // dump raw data
 
@@ -2098,3 +2359,115 @@ AliTRDrawStream::AliTRDrawStreamError::AliTRDrawStreamError(Int_t error, Int_t s
   // ctor
 
 }
+
+void AliTRDrawStream::SortTracklets(TClonesArray *trklArray, TList &sortedTracklets, Int_t *indices)
+{
+  // sort tracklets for referencing from GTU tracks
+
+  if (!trklArray)
+    return;
+
+  Int_t nTracklets = trklArray->GetEntriesFast();
+
+  Int_t lastHC = -1;
+  for (Int_t iTracklet = 0; iTracklet < nTracklets; iTracklet++) {
+    AliTRDtrackletBase *trkl = (AliTRDtrackletBase*) ((*trklArray)[iTracklet]);
+    Int_t hc = trkl->GetHCId();
+    if ((hc < 0) || (hc >= 1080)) {
+      AliErrorClass(Form("HC for tracklet: 0x%08x out of range: %i", trkl->GetTrackletWord(), trkl->GetHCId()));
+      continue;
+    }
+    AliDebugClass(5, Form("hc: %4i : 0x%08x z: %2i", hc, trkl->GetTrackletWord(), trkl->GetZbin()));
+    if (hc != lastHC) {
+      AliDebugClass(2, Form("set tracklet index for HC %i to %i", hc, iTracklet));
+      indices[hc] = iTracklet + 1;
+      lastHC = hc;
+    }
+  }
+
+  for (Int_t iDet = 0; iDet < 540; iDet++) {
+    Int_t trklIndexA = indices[2*iDet + 0] - 1;
+    Int_t trklIndexB = indices[2*iDet + 1] - 1;
+    Int_t trklIndex  = sortedTracklets.GetEntries();
+    AliTRDtrackletBase *trklA = trklIndexA > -1 ? (AliTRDtrackletBase*) ((*trklArray)[trklIndexA]) : 0x0;
+    AliTRDtrackletBase *trklB = trklIndexB > -1 ? (AliTRDtrackletBase*) ((*trklArray)[trklIndexB]) : 0x0;
+    AliTRDtrackletBase *trklNext = 0x0;
+    while (trklA != 0x0 || trklB != 0x0) {
+      AliDebugClass(5, Form("det %i - A: %i/%i -> %p, B: %i/%i -> %p",
+                      iDet, trklIndexA, nTracklets, trklA, trklIndexB, nTracklets, trklB));
+      if (trklA == 0x0) {
+       trklNext = trklB;
+       trklIndexB++;
+       trklB = trklIndexB < nTracklets ? (AliTRDtrackletBase*) ((*trklArray)[trklIndexB]) : 0x0;
+       if (trklB && trklB->GetHCId() != 2*iDet + 1)
+         trklB = 0x0;
+      }
+      else if (trklB == 0x0) {
+       trklNext = trklA;
+       trklIndexA++;
+       trklA = trklIndexA < nTracklets ? (AliTRDtrackletBase*) ((*trklArray)[trklIndexA]) : 0x0;
+       if (trklA && trklA->GetHCId() != 2*iDet)
+         trklA = 0x0;
+      }
+      else {
+       if (trklA->GetZbin() <= trklB->GetZbin()) {
+         trklNext = trklA;
+         trklIndexA++;
+         trklA = trklIndexA < nTracklets ? (AliTRDtrackletBase*) ((*trklArray)[trklIndexA]) : 0x0;
+         if (trklA && trklA->GetHCId() != 2*iDet)
+           trklA = 0x0;
+       }
+       else {
+         trklNext = trklB;
+         trklIndexB++;
+         trklB = trklIndexB < nTracklets ? (AliTRDtrackletBase*) ((*trklArray)[trklIndexB]) : 0x0;
+         if (trklB && trklB->GetHCId() != 2*iDet + 1)
+           trklB = 0x0;
+       }
+      }
+      if (trklNext) {
+       sortedTracklets.Add(trklNext);
+
+      }
+    }
+
+    // updating tracklet indices as in output
+    if (sortedTracklets.GetEntries() != trklIndex) {
+      indices[2*iDet + 0] = trklIndex;
+      indices[2*iDet + 1] = sortedTracklets.GetEntries();
+    } else {
+      indices[2*iDet + 0] = indices[2*iDet + 1] = -1;
+    }
+  }
+}
+
+void AliTRDrawStream::AssignTracklets(AliESDTrdTrack *trdTrack, Int_t *trackletIndex, Int_t refIndex[6])
+{
+  UInt_t mask  = trdTrack->GetLayerMask();
+  UInt_t stack = trdTrack->GetStack();
+
+  for (Int_t iLayer = 0; iLayer < 6; iLayer++) {
+    refIndex[iLayer] = -1;
+
+    if (mask & (1 << iLayer)) {
+
+      Int_t det = trdTrack->GetSector()*30 + stack*6 + iLayer;
+      Int_t idx = trdTrack->GetTrackletIndex(iLayer);
+
+      if ((det < 0) || (det > 539)) {
+       AliErrorClass(Form("Invalid detector no. from track: %i", 2*det));
+       continue;
+      }
+      if (trackletIndex[2*det] >= 0) {
+       if ((trackletIndex[2*det] + idx > -1) &&
+           (trackletIndex[2*det] + idx < trackletIndex[2*det+1])) {
+         refIndex[iLayer] = trackletIndex[2*det] + idx;
+       } else {
+         AliErrorClass(Form("Requested tracklet index %i out of range", idx));
+       }
+      } else {
+       AliErrorClass(Form("Non-existing tracklets requested in det %i", det));
+      }
+    }
+  }
+}