]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - TRD/AliTRDrawData.cxx
extend debug stream to prepare studies of bremsstrahlung detection in
[u/mrichter/AliRoot.git] / TRD / AliTRDrawData.cxx
index 478ece5ceed0517c08c7e4b819832d628e5dcf7f..5eba5586aac6829f2d44a86581f68c648d180dfd 100644 (file)
 //                                                                           //
 ///////////////////////////////////////////////////////////////////////////////
 
-#include <Riostream.h>
+
 #include <TMath.h>
+#include "TClass.h"
 
 #include "AliDAQ.h"
-#include "AliRawDataHeader.h"
+#include "AliRawDataHeaderSim.h"
 #include "AliRawReader.h"
 #include "AliLog.h"
+#include "AliFstream.h"
 
 #include "AliTRDrawData.h"
 #include "AliTRDdigitsManager.h"
 #include "AliTRDgeometry.h"
-#include "AliTRDdataArrayI.h"
-#include "AliTRDRawStream.h"
-#include "AliTRDCommonParam.h"
+#include "AliTRDarrayDictionary.h"
+#include "AliTRDarrayADC.h"
+#include "AliTRDrawStreamBase.h"
+#include "AliTRDrawOldStream.h"
 #include "AliTRDcalibDB.h"
+#include "AliTRDSignalIndex.h"
+#include "AliTRDfeeParam.h"
+#include "AliTRDmcmSim.h"
 
 ClassImp(AliTRDrawData)
 
+Int_t AliTRDrawData::fgRawFormatVersion = AliTRDrawData::kRawNewFormat;
+Int_t AliTRDrawData::fgDataSuppressionLevel = 1;
+
 //_____________________________________________________________________________
 AliTRDrawData::AliTRDrawData()
   :TObject()
-  ,fRawVersion(1)    // Default Raw Data version set here
-  ,fCommonParam(0)
-  ,fCalibration(0)
-  ,fGeo(0)
+  ,fGeo(NULL)
+  ,fFee(NULL)
   ,fNumberOfDDLs(0)
+  ,fSMindexPos(0)
+  ,fStackindexPos(0)
+  ,fEventCounter(0)
 {
   //
   // Default constructor
   //
 
+  fFee = AliTRDfeeParam::Instance();
+  fNumberOfDDLs = AliDAQ::NumberOfDdls("TRD");
+
 }
 
 //_____________________________________________________________________________
 AliTRDrawData::AliTRDrawData(const AliTRDrawData &r)
   :TObject(r)
-  ,fRawVersion(1)    // Default Raw Data version set here
-  ,fCommonParam(0)
-  ,fCalibration(0)
-  ,fGeo(0)
+  ,fGeo(NULL)
+  ,fFee(NULL)
   ,fNumberOfDDLs(0)
+  ,fSMindexPos(0)
+  ,fStackindexPos(0)
+  ,fEventCounter(0)
 {
   //
   // Copy constructor
   //
 
+  fFee = AliTRDfeeParam::Instance();
+  fNumberOfDDLs = AliDAQ::NumberOfDdls("TRD");
+
 }
 
 //_____________________________________________________________________________
@@ -78,22 +95,6 @@ AliTRDrawData::~AliTRDrawData()
 
 }
 
-//_____________________________________________________________________________
-Bool_t AliTRDrawData::SetRawVersion(Int_t v)
-{
-  //
-  // Set the raw data version (Currently only version 0, 1 and 2 are available)
-  //
-
-  if ( (v >= 0) && (v <= 2) ) {
-    fRawVersion = v;
-    return kTRUE;
-  }
-
-  return kFALSE;
-
-}
-
 //_____________________________________________________________________________
 Bool_t AliTRDrawData::Digits2Raw(TTree *digitsTree, TTree *tracks )
 {
@@ -105,8 +106,6 @@ Bool_t AliTRDrawData::Digits2Raw(TTree *digitsTree, TTree *tracks )
   // will be supported in higher version simulator.
   //
 
-  fNumberOfDDLs = AliDAQ::NumberOfDdls("TRD");
-
   AliTRDdigitsManager* digitsManager = new AliTRDdigitsManager();
 
   if (!digitsManager->ReadDigits(digitsTree)) {
@@ -122,16 +121,7 @@ Bool_t AliTRDrawData::Digits2Raw(TTree *digitsTree, TTree *tracks )
 
   fGeo = new AliTRDgeometry();
 
-  fCommonParam = AliTRDCommonParam::Instance();
-  if (!fCommonParam) {
-    AliError("Could not get common params");
-    delete fGeo;
-    delete digitsManager;
-    return kFALSE;
-  }
-
-  fCalibration = AliTRDcalibDB::Instance();
-  if (!fCalibration) {
+  if (!AliTRDcalibDB::Instance()) {
     AliError("Could not get calibration object");
     delete fGeo;
     delete digitsManager;
@@ -139,13 +129,13 @@ Bool_t AliTRDrawData::Digits2Raw(TTree *digitsTree, TTree *tracks )
   }
 
   Int_t retval = kTRUE;
+  Int_t rv     = fFee->GetRAWversion();
 
   // Call appropriate Raw Simulator
-  if      ( fRawVersion == 0 )                    retval = Digits2RawV0(digitsManager); 
-  else if ( fRawVersion > 0 && fRawVersion <= 2 ) retval = Digits2RawVx(digitsManager); 
+  if ( rv > 0 && rv <= 3 ) retval = Digits2Raw(digitsManager); 
   else {
     retval = kFALSE;
-    AliWarning(Form("Unsupported raw version (fRawVersion=%d).",fRawVersion));
+    AliWarning(Form("Unsupported raw version (%d).", rv));
   }
 
   // Cleanup
@@ -157,293 +147,453 @@ Bool_t AliTRDrawData::Digits2Raw(TTree *digitsTree, TTree *tracks )
 }
 
 //_____________________________________________________________________________
-Bool_t AliTRDrawData::Digits2RawV0(AliTRDdigitsManager* digitsManager)
+Bool_t AliTRDrawData::Digits2Raw(AliTRDdigitsManager *digitsManager)
 {
   //
-  // Bogdan's raw simulator (offline use only)
-  //
-  // Convert the digits to raw data byte stream. The output is written
-  // into the the binary files TRD_<DDL number>.ddl.
-  //
-  // The pseudo raw data format is currently defined like this:
-  //
-  //          DDL data header
-  //
-  //          Subevent (= single chamber) header (8 bytes)
-  //                  FLAG
-  //                  Detector number (2 bytes)
-  //                  Number of data bytes (2 bytes)
-  //                  Number of pads with data (2 bytes)
-  //                  1 empty byte
-  //
-  //          Data bank
+  // Raw data simulator for all versions > 0. This is prepared for real data.
+  // This version simulate only raw data with ADC data and not with tracklet.
   //
 
-  const Int_t kSubeventHeaderLength = 8;
-  const Int_t kSubeventDummyFlag    = 0xBB;
-  Int_t       headerSubevent[3];
-
-  ofstream     **outputFile = new ofstream* [fNumberOfDDLs];
-  UInt_t        *bHPosition = new UInt_t    [fNumberOfDDLs];
-  Int_t         *ntotalbyte = new Int_t     [fNumberOfDDLs];
-  Int_t          nbyte = 0;
-  Int_t          npads = 0;
-  unsigned char *bytePtr;
-  unsigned char *headerPtr;
-
-  AliTRDdataArrayI *digits;
-  AliRawDataHeader  header;   // The event header
-
-  // Open the output files
-  for (Int_t iDDL = 0; iDDL < fNumberOfDDLs; iDDL++) {
-
-    char name[20];
-    sprintf(name, "TRD_%d.ddl", iDDL + AliTRDRawStream::kDDLOffset);
-#ifndef __DECCXX
-    outputFile[iDDL] = new ofstream(name, ios::binary);
-#else
-    outputFile[iDDL] = new ofstream(name);
-#endif
-
-    // Write a dummy data header
-    bHPosition[iDDL] = outputFile[iDDL]->tellp();
-    outputFile[iDDL]->write((char *) (& header),sizeof(header));
-    ntotalbyte[iDDL] = 0;
-
-  }
-
-  // Loop through all detectors
-  for (Int_t det = 0; det < AliTRDgeometry::Ndet(); det++) {
-
-    Int_t cham      = fGeo->GetChamber(det);
-    Int_t plan      = fGeo->GetPlane(det);
-    Int_t sect      = fGeo->GetSector(det);
-    Int_t rowMax    = fCommonParam->GetRowMax(plan,cham,sect);
-    Int_t colMax    = fCommonParam->GetColMax(plan);
-    Int_t timeTotal = fCalibration->GetNumberOfTimeBins();
-    Int_t bufferMax = rowMax * colMax * timeTotal;
-    Int_t *buffer   = new Int_t[bufferMax];
-
-    npads   = 0;
-    nbyte   = 0;
-    bytePtr = (unsigned char *) buffer;
-
-    Int_t iDDL = sect;
-
-    // Get the digits array
-    digits = digitsManager->GetDigits(det);
-    digits->Expand();
-    // This is to take care of switched off super modules
-    if (digits->GetNtime() == 0) {
-      continue;
-    }
-
-    // Loop through the detector pixel
-    for (Int_t col = 0; col < colMax; col++) {
-      for (Int_t row = 0; row < rowMax; row++) {
-
-       // Check whether data exists for this pad
-        Bool_t dataflag = kFALSE;
-        for (Int_t time = 0; time < timeTotal; time++) {
-          Int_t data = digits->GetDataUnchecked(row,col,time);
-          if (data) {
-            dataflag = kTRUE;
-            break;
-         }
-       }
+  const Int_t kMaxHcWords = (fGeo->TBmax()/3)
+                          * fGeo->ADCmax()
+                          * fGeo->MCMmax()
+                          * fGeo->ROBmaxC1()/2 
+                          + 100 + 20;
 
-        if (dataflag) {
+  // Buffer to temporary store half chamber data
+  UInt_t     *hcBuffer    = new UInt_t[kMaxHcWords];
+  
+  Bool_t newEvent = kFALSE;  // only for correct readout tree
+  Bool_t newSM    = kFALSE;  // new SM flag, for writing SM index words
+  Bool_t newStack = kFALSE;  // new stack flag, for writing stack index words
 
-          npads++;
+  // sect is same as iDDL, so I use only sect here.
+  for (Int_t sect = 0; sect < fGeo->Nsector(); sect++) { 
 
-         // The pad row number
-          *bytePtr++ = row + 1;
-         // The pad column number
-          *bytePtr++ = col + 1;
-          nbyte += 2;
+    char name[1024];
+    sprintf(name,"TRD_%d.ddl",sect + AliTRDrawOldStream::kDDLOffset);
 
-          Int_t nzero = 0;
-          for (Int_t time = 0; time < timeTotal; time++) {
+    AliFstream* of = new AliFstream(name);
 
-            Int_t data = digits->GetDataUnchecked(row,col,time);
+           // Write a dummy data header
+    AliRawDataHeaderSim  header;  // the event header
+    UInt_t hpos = of->Tellp();
+    of->WriteBuffer((char *) (& header), sizeof(header));
 
-            if (!data) {
-              nzero++;
-              if ((nzero ==       256) || 
-                  (time  == timeTotal-1)) {
-                *bytePtr++ = 0;
-                *bytePtr++ = nzero-1;
-                nbyte += 2;
-                nzero  = 0;
-             }
-           }
-            else {
-              if (nzero) {
-                *bytePtr++ = 0;
-                *bytePtr++ = nzero-1;
-                nbyte += 2;
-                nzero  = 0;
-             }
-              // High byte (MSB always set)
-              *bytePtr++ = ((data >> 8) | 128);
-              // Low byte
-              *bytePtr++ = (data & 0xff);
-              nbyte += 2;
-           }
+    // Reset payload byte size (payload does not include header).
+    Int_t npayloadbyte = 0;
 
-         }
 
-       }
+    if ( fgRawFormatVersion == 0 ){
+    // GTU common data header (5x4 bytes per super module, shows link mask)
+    for( Int_t stack = 0; stack < fGeo->Nstack(); stack++ ) {
+      UInt_t gtuCdh = (UInt_t)(0xe << 28);
+      for( Int_t layer = 0; layer < fGeo->Nlayer(); layer++) {
+    Int_t iDet = fGeo->GetDetector(layer, stack, sect);
 
+    // If chamber status is ok, we assume that the optical link is also OK.
+        // This is shown in the GTU link mask.
+    if ( AliTRDcalibDB::Instance()->GetChamberStatus(iDet) )
+      gtuCdh = gtuCdh | (3 << (2*layer));
       }
-
+      of->WriteBuffer((char *) (& gtuCdh), sizeof(gtuCdh));
+      npayloadbyte += 4;
     }
-
-    // Fill the end of the buffer with zeros
-    while (nbyte % 4) {  
-      *bytePtr++ = 0;
-      nbyte++;
     }
 
-    AliDebug(1,Form("det = %d, nbyte = %d (%d)",det,nbyte,bufferMax));
 
-    // Write the subevent header
-    bytePtr    = (unsigned char *) headerSubevent;
-    headerPtr  = bytePtr;
-    *bytePtr++ = kSubeventDummyFlag;
-    *bytePtr++ = (det   & 0xff);
-    *bytePtr++ = (det   >> 8);
-    *bytePtr++ = (nbyte & 0xff);
-    *bytePtr++ = (nbyte >> 8);
-    *bytePtr++ = (nbyte >> 16);
-    *bytePtr++ = (npads & 0xff);
-    *bytePtr++ = (npads >> 8);
-    outputFile[iDDL]->write((char *) headerPtr,kSubeventHeaderLength);
+    // check the existance of the data
+    // SM index word and Stack index word
+   if ( fgRawFormatVersion == 1 ){
+    UInt_t *iwbuffer = new UInt_t[42]; // index word buffer; max 42 = 2 SM headers + 5*8 stack headers
+    Int_t nheader = 0;
+    UInt_t StackMask = 0x0;
+    Bool_t StackHasData = kFALSE;
+    Bool_t SMHasData = kFALSE;
+    iwbuffer[nheader++] = 0x0001a020;   // SM index words 
+    iwbuffer[nheader++] = 0x10404071;   // SM header
+
+    for ( Int_t stack= 0; stack < fGeo->Nstack(); stack++) {
+        UInt_t LinkMask = 0x0;
+        for( Int_t layer = 0; layer < fGeo->Nlayer(); layer++) {
+            Int_t iDet = fGeo->GetDetector(layer,stack,sect);
+                       AliTRDarrayADC *digits = (AliTRDarrayADC *) digitsManager->GetDigits(iDet);
+            if ( digits->HasData() ) {
+                StackMask = StackMask | ( 1 << stack ); // active stack mask for new stack
+                LinkMask = LinkMask | ( 3 << (2*layer) );    // 3 = 0011
+                StackHasData = kTRUE;
+                SMHasData = kTRUE;
+            } // has data
+        } // loop over layer
+
+        if ( fgDataSuppressionLevel==0 || StackHasData ){
+        //if ( StackHasData ){
+            iwbuffer[nheader++] = 0x0007a000 | LinkMask;    // stack index word + link masks
+            //if (fgDataSuppressionLevel==0) iwbuffer[nheader-1] = 0x0007afff;  // no suppression
+            iwbuffer[nheader++] = 0x04045b01;               // stack header
+            for (Int_t i=0;i<6;i++) iwbuffer[nheader++] = 0x00000000; // 6 dummy words
+            StackHasData = kFALSE;
+        }
+    } // loop over stack
+
+    if ( fgDataSuppressionLevel==0 || SMHasData ){
+        iwbuffer[0] = iwbuffer[0] | StackMask;  // add stack masks to SM index word
+        if (fgDataSuppressionLevel==0) iwbuffer[0] = 0x0001a03f;    // no suppression
+        of->WriteBuffer((char *) iwbuffer, nheader*4);
+        AliDebug(11, Form("SM %d index word: %08x", iwbuffer[0]));
+        AliDebug(11, Form("SM %d header: %08x", iwbuffer[1]));
+    }
+   }
+    // end of SM & stack header ------------------------------------------------------------------------
+    // -------------------------------------------------------------------------------------------------
 
-    // Write the buffer to the file
-    bytePtr = (unsigned char *) buffer;
-    outputFile[iDDL]->write((char *) bytePtr,nbyte);
+    // Prepare chamber data
+    for( Int_t stack = 0; stack < fGeo->Nstack(); stack++) {
+      for( Int_t layer = 0; layer < fGeo->Nlayer(); layer++) {
+
+        Int_t iDet = fGeo->GetDetector(layer,stack,sect);
+        if (iDet == 0){
+            newEvent = kTRUE; // it is expected that each event has at least one tracklet; 
+                                         // this is only needed for correct readout tree
+            fEventCounter++;
+            AliDebug(11, Form("New event!! Event counter: %d",fEventCounter));
+        }
+
+        if ( stack==0 && layer==0 ) newSM = kTRUE;  // new SM flag
+        if ( layer==0 ) newStack = kTRUE;           // new stack flag
+        AliDebug(15, Form("stack : %d, layer : %d, iDec : %d\n",stack,layer,iDet));
+        // Get the digits array
+               AliTRDarrayADC *digits = (AliTRDarrayADC *) digitsManager->GetDigits(iDet);
+        if (fgDataSuppressionLevel==0 || digits->HasData() ) {  // second part is new!! and is for indicating a new event
 
-    ntotalbyte[iDDL] += nbyte + kSubeventHeaderLength;
+               if (digits->HasData()) digits->Expand();
 
-    delete buffer;
+                       Int_t hcwords = 0;
+                       Int_t rv = fFee->GetRAWversion();
 
-  }
 
-  // Update the data headers and close the output files
-  for (Int_t iDDL = 0; iDDL < fNumberOfDDLs; iDDL++) {
+       if ( fgRawFormatVersion == 0 ){
+      // Process A side of the chamber
+         if ( rv >= 1 && rv <= 2 ) {
+            hcwords = ProduceHcDataV1andV2(digits,0,iDet,hcBuffer,kMaxHcWords);
+         }
+         if ( rv == 3 ) { 
+   
+             hcwords = ProduceHcDataV3     (digits,0,iDet,hcBuffer,kMaxHcWords,newEvent);
+             //hcwords = ProduceHcDataV3     (digits,0,iDet,hcBuffer,kMaxHcWords);
+           if(newEvent == kTRUE) newEvent = kFALSE;
+         }
 
-    header.fSize = UInt_t(outputFile[iDDL]->tellp()) - bHPosition[iDDL];
-    header.SetAttribute(0);  // valid data
-    outputFile[iDDL]->seekp(bHPosition[iDDL]);
-    outputFile[iDDL]->write((char *) (&header),sizeof(header));
+          of->WriteBuffer((char *) hcBuffer, hcwords*4);
+          npayloadbyte += hcwords*4;
 
-    outputFile[iDDL]->close();
-    delete outputFile[iDDL];
+      // Process B side of the chamber
+         if ( rv >= 1 && rv <= 2 ) {
+            hcwords = ProduceHcDataV1andV2(digits,1,iDet,hcBuffer,kMaxHcWords);
+         }
+         if ( rv >= 3 ) {
+          
+             hcwords = ProduceHcDataV3     (digits,1,iDet,hcBuffer,kMaxHcWords,newEvent);
+             //hcwords = ProduceHcDataV3     (digits,1,iDet,hcBuffer,kMaxHcWords);
+         }
 
-  }
+          of->WriteBuffer((char *) hcBuffer, hcwords*4);
+          npayloadbyte += hcwords*4;
 
-  delete [] outputFile;
-  delete [] bHPosition;
-  delete [] ntotalbyte;
+    } else { // real data format
 
-  return kTRUE;
-}
+       if (digits->HasData()){
+        // Process A side of the chamber
+        hcwords = ProduceHcData(digits,0,iDet,hcBuffer,kMaxHcWords,newEvent,newSM);
+        //if ( newStack ){
+        //  AssignStackMask(hcBuffer, stack);   // active stack mask for this stack
+        //  hcwords += AddStackIndexWords(hcBuffer, stack, hcwords);
+        //  newStack = kFALSE;
+        //}
+        //if ( newSM ) newSM = kFALSE;
+        if ( newEvent ) newEvent = kFALSE;
+        //AssignLinkMask(hcBuffer, layer);  // active link mask for this layer(2*HC)
+        of->WriteBuffer((char *) hcBuffer, hcwords*4);
+        npayloadbyte += hcwords*4;
+        //for ( Int_t i=0; i<hcwords; i++ ) AliInfo(Form("Buf : %X",hcBuffer[i]));
 
-//_____________________________________________________________________________
-Bool_t AliTRDrawData::Digits2RawVx(AliTRDdigitsManager *digitsManager)
-{
-  //
-  // Raw data simulator for all versions > 0. This is prepared for real data.
-  // This version simulate only raw data with ADC data and not with tracklet.
-  //
+        // Process B side of the chamber
+        hcwords = ProduceHcData(digits,1,iDet,hcBuffer,kMaxHcWords,newEvent,newSM);
+        of->WriteBuffer((char *) hcBuffer, hcwords*4);
+        npayloadbyte += hcwords*4;
+       } else {
+        hcBuffer[hcwords++] = fgkEndOfTrackletMarker;
+        hcBuffer[hcwords++] = fgkEndOfTrackletMarker;
+        hcBuffer[hcwords++] = (1<<31) | (0<<24) | (0<<17) | (1<<14) | (sect<<9) | (layer<<6) | (stack<<3) | (0<<2) | 1;
+        hcBuffer[hcwords++] = (24<<26) | (99<<10) | (15<<6) | (11<<2) | 1;
+        hcBuffer[hcwords++] = kEndofrawdatamarker;
+        hcBuffer[hcwords++] = kEndofrawdatamarker;
+        hcBuffer[hcwords++] = kEndofrawdatamarker;
+        hcBuffer[hcwords++] = kEndofrawdatamarker;
+        npayloadbyte += hcwords*4;
 
-  const Int_t kMaxHcWords = (fGeo->TBmax()/3)*fGeo->ADCmax()*fGeo->MCMmax()*fGeo->ROBmaxC1()/2 + 100 + 20;
+        hcBuffer[hcwords++] = fgkEndOfTrackletMarker;
+        hcBuffer[hcwords++] = fgkEndOfTrackletMarker;
+        hcBuffer[hcwords++] = (1<<31) | (0<<24) | (0<<17) | (1<<14) | (sect<<9) | (layer<<6) | (stack<<3) | (1<<2) | 1;
+        hcBuffer[hcwords++] = (24<<26) | (99<<10) | (15<<6) | (11<<2) | 1;
+        hcBuffer[hcwords++] = kEndofrawdatamarker;
+        hcBuffer[hcwords++] = kEndofrawdatamarker;
+        hcBuffer[hcwords++] = kEndofrawdatamarker;
+        hcBuffer[hcwords++] = kEndofrawdatamarker;
+        npayloadbyte += hcwords*4;
 
-  // Buffer to temporary store half chamber data
-  UInt_t     *hc_buffer   = new UInt_t[kMaxHcWords];
+        of->WriteBuffer((char *) hcBuffer, hcwords*4);
+       }
+    }
 
-  // sect is same as iDDL, so I use only sect here.
-  for (Int_t sect = 0; sect < fGeo->Nsect(); sect++) { 
+    } // has data
 
-    char name[1024];
-    sprintf(name,"TRD_%d.ddl",sect + AliTRDRawStream::kDDLOffset);
+      } // loop over layer
+    } // loop over stack
 
-#ifndef __DECCXX
-    ofstream *of = new ofstream(name, ios::binary);
-#else
-    ofstream *of = new ofstream(name);
-#endif
+    // Complete header
+    header.fSize = UInt_t(of->Tellp()) - hpos;
+    header.SetAttribute(0);  // Valid data
+    of->Seekp(hpos);         // Rewind to header position
+    of->WriteBuffer((char *) (& header), sizeof(header));
+    delete of;
+  }
 
-    // Write a dummy data header
-    AliRawDataHeader  header;  // the event header
-    UInt_t hpos = of->tellp();
-    of->write((char *) (& header), sizeof(header));
+  delete [] hcBuffer;
 
-    // Reset payload byte size (payload does not include header).
-    Int_t npayloadbyte = 0;
+  return kTRUE;
 
-    // GTU common data header (5x4 bytes per super module, shows link mask)
-    for( Int_t cham = 0; cham < fGeo->Ncham(); cham++ ) {
-      UInt_t GtuCdh = (UInt_t)(0xe << 28);
-      for( Int_t plan = 0; plan < fGeo->Nplan(); plan++) {
-       Int_t iDet = fGeo->GetDetector(plan, cham, sect);
-       // If chamber status is ok, we assume that the optical link is also OK.
-        // This is shown in the GTU link mask.
-       if ( fCalibration->GetChamberStatus(iDet) )
-         GtuCdh = GtuCdh | (3 << (2*plan));
-      }
-      of->write((char *) (& GtuCdh), sizeof(GtuCdh));
-      npayloadbyte += 4;
-    }
+}
 
-    // Prepare chamber data
-    for( Int_t cham = 0; cham < fGeo->Ncham(); cham++) {
-      for( Int_t plan = 0; plan < fGeo->Nplan(); plan++) {
+//_____________________________________________________________________________
+void AliTRDrawData::ProduceSMIndexData(UInt_t *buf, Int_t& nw){
+       // 
+       // This function generates 
+       //       1) SM index words : ssssssss ssssssss vvvv rrrr r d t mmmmm
+       //          - s : size of SM header (number of header, default = 0x0001)
+       //          - v : SM header version (default = 0xa)
+       //          - r : reserved for future use (default = 00000)
+       //          - d : track data enabled bit (default = 0)
+       //          - t : tracklet data enabled bit (default = 1)
+       //          - m : stack mask (each bit corresponds a stack, default = 11111)
+       //
+       //       2) SM header : rrr c vvvv vvvvvvvv vvvv rrrr bbbbbbbb
+       //          - r : reserved for future use (default = 000)
+       //          - c : clean check out flag (default = 1)
+       //          - v : hardware design revision (default = 0x0404)
+       //          - r : reserved for future use (default = 0x0)
+       //          - b : physical board ID (default = 0x71)
+       //
+       //       3) stack index words : ssssssss ssssssss vvvv mmmm mmmmmmmm
+       //          - s : size of stack header (number of header, (default = 0x0007)
+       //          - v : header version (default = 0xa)
+       //          - m : link mask (default = 0xfff)
+       //
+       //       4) stack header : vvvvvvvv vvvvvvvv bbbbbbbb rrrr rrr c
+       //          - v : hardware design revision (default = 0x0404)
+       //          - b : physical board ID (default = 0x5b)
+       //          - r : reserved for future use (default = 0000 000)
+       //          - c : clean checkout flag (default = 1)
+       //      
+       //       and 6 dummy words(0x00000000)
+       //
+       
+    //buf[nw++] = 0x0001a03f;   // SM index words
+    fSMindexPos = nw;       // memorize position of the SM index word for re-allocating stack mask
+    buf[nw++] = 0x0001a020; // SM index words
+    buf[nw++] = 0x10404071; // SM header
+
+    fStackindexPos = nw;    // memorize position of the stack index word for future adding
+       /*  
+    for (Int_t istack=0; istack<5; istack++){
+        buf[nw++] = 0x0007afff; // stack index words
+        buf[nw++] = 0x04045b01; // stack header
+        for (Int_t i=0;i<6;i++) buf[nw++] = 0x00000000; // 6 dummy words
+    } // loop over 5 stacks
+       */
+}
 
-        Int_t iDet = fGeo->GetDetector(plan,cham,sect);
+//_____________________________________________________________________________
+void AliTRDrawData::AssignStackMask(UInt_t *buf, Int_t nStack){
+    //
+    // This function re-assign stack mask active(from 0 to 1) in the SM index word
+    //   
+    buf[fSMindexPos] = buf[fSMindexPos] | ( 1 << nStack );
+}
 
-        // Get the digits array
-        AliTRDdataArrayI *digits = digitsManager->GetDigits(iDet);
-        digits->Expand();
+//_____________________________________________________________________________  
+Int_t AliTRDrawData::AddStackIndexWords(UInt_t *buf, Int_t /*nStack*/, Int_t nMax){
+    // 
+    // This function add stack index words and stack header when there is data for the stack
+    //
+    //   1) stack index words : ssssssss ssssssss vvvv mmmm mmmmmmmm 
+    //      - s : size of stack header (number of header, (default = 0x0007)       
+    //      - v : header version (default = 0xa)
+    //      - m : link mask (default = 0xfff)
+    //      - m : link mask (starting value = 0x000)
+    //
+    //   2) stack header : vvvvvvvv vvvvvvvv bbbbbbbb rrrr rrr c
+    //      - v : hardware design revision (default = 0x0404)
+    //      - b : physical board ID (default = 0x5b)
+    //      - r : reserved for future use (default = 0000 000)
+    //      - c : clean checkout flag (default = 1)
+    //  
+    //   and 6 dummy words(0x00000000)
+    //
+
+    Int_t nAddedWords = 0;  // Number of added words
+    if ( ShiftWords(buf, fStackindexPos, 8, nMax)== kFALSE ){
+        AliError("Adding stack header failed.");
+        return 0;
+    }
 
-        Int_t hcwords = 0;
+    buf[fStackindexPos++] = 0x0007a000; // stack index words
+    buf[fStackindexPos++] = 0x04045b01; // stack header
+    for (Int_t i=0;i<6;i++) buf[fStackindexPos++] = 0x00000000; // 6 dummy words 
+    nAddedWords += 8;
 
-        // Process A side of the chamber
-       if ( fRawVersion >= 1 && fRawVersion <= 2 ) hcwords = ProduceHcDataV1andV2(digits,0,iDet,hc_buffer,kMaxHcWords);
-        of->write((char *) hc_buffer, hcwords*4);
-        npayloadbyte += hcwords*4;
+    return nAddedWords;
+}
 
-        // Process B side of the chamber
-       if ( fRawVersion >= 1 && fRawVersion <= 2 ) hcwords = ProduceHcDataV1andV2(digits,1,iDet,hc_buffer,kMaxHcWords);
-        of->write((char *) hc_buffer, hcwords*4);
-        npayloadbyte += hcwords*4;
+//_____________________________________________________________________________
+void AliTRDrawData::AssignLinkMask(UInt_t *buf, Int_t nLayer){
+    //
+    // This function re-assign link mask active(from 0 to 1) in the stack index word
+    //   
+    buf[fStackindexPos-8] = buf[fStackindexPos-8] | ( 3 << (2*nLayer) );    // 3 = 0011 
+}
 
-      }
+//_____________________________________________________________________________ 
+Bool_t AliTRDrawData::ShiftWords(UInt_t *buf, Int_t nStart, Int_t nWords, Int_t nMax){
+    //  
+    // This function shifts n words
+    //
+    //if ( nStart+nWords > sizeof(buf)/sizeof(UInt_t) ){
+    //  AliError("Words shift failed. No more buffer space.");
+    //  return kFALSE;
+    //}
+
+    for ( Int_t iw=nMax; iw>nStart-1; iw--){
+        buf[iw+nWords] = buf[iw];
     }
+    return kTRUE;
+}
 
-    // Complete header
-    header.fSize = UInt_t(of->tellp()) - hpos;
-    header.SetAttribute(0);  // Valid data
-    of->seekp(hpos);         // Rewind to header position
-    of->write((char *) (& header), sizeof(header));
-    of->close();
-    delete of;
+//_____________________________________________________________________________
+Int_t AliTRDrawData::ProduceHcData(AliTRDarrayADC *digits, Int_t side, Int_t det, UInt_t *buf, Int_t maxSize, Bool_t /*newEvent = kFALSE*/, Bool_t /*newSM = kFALSE*/){
+       //
+       // This function can be used for both ZS and NZS data
+       //
+
+       Int_t           nw = 0;                       // Number of written    words
+       Int_t           of = 0;                       // Number of overflowed words
+       Int_t      *tempnw = 0x0;                     // Number of written    words for temp. buffer
+       Int_t      *tempof = 0x0;                     // Number of overflowed words for temp. buffer
+       Int_t        layer = fGeo->GetLayer( det );   // Layer
+       Int_t        stack = fGeo->GetStack( det );   // Stack
+       Int_t         sect = fGeo->GetSector( det );  // Sector (=iDDL)
+       const Int_t kCtype = fGeo->GetStack(det) == 2 ? 0 : 1;                       // Chamber type (0:C0, 1:C1)
+
+       Bool_t tracklet_on = fFee->GetTracklet();     // tracklet simulation active?
+
+       AliDebug(1,Form("Producing raw data for sect=%d layer=%d stack=%d side=%d",sect,layer,stack,side));
+        
+       AliTRDmcmSim* mcm = new AliTRDmcmSim();
+
+       UInt_t *tempBuffer = buf; // tempBuffer used to write ADC data
+                                 // different in case of tracklet writing
+       
+       if (tracklet_on) {
+         tempBuffer = new UInt_t[maxSize];
+          tempnw = new Int_t(0);
+          tempof = new Int_t(0);
+        }
+        else {
+          tempnw = &nw;
+          tempof = &of;
+        }
+
+       WriteIntermediateWordsV2(tempBuffer,*tempnw,*tempof,maxSize,det,side);  //??? no tracklet or NZS
+
+       // scanning direction such, that tracklet-words are sorted in ascending z and then in ascending y order
+       // ROB numbering on chamber and MCM numbering on ROB increase with decreasing z and increasing y
+       for (Int_t iRobRow = 0; iRobRow <= (kCtype + 3)-1; iRobRow++ ) {        // ROB number should be increasing
+          Int_t iRob = iRobRow * 2 + side;
+          // MCM on one ROB
+          for (Int_t iMcmRB = 0; iMcmRB < fGeo->MCMmax(); iMcmRB++ ) {
+            Int_t iMcm = 16 - 4*(iMcmRB/4 + 1) + (iMcmRB%4);
+            
+            mcm->Init(det, iRob, iMcm);
+            mcm->SetData(digits);     // no filtering done here (already done in digitizer)
+           if (tracklet_on) {
+             mcm->Tracklet();
+              Int_t tempNw = mcm->ProduceTrackletStream(&buf[nw], maxSize - nw);
+             if(  tempNw < 0 ) {
+               of += tempNw;
+               nw += maxSize - nw;
+               AliError(Form("Buffer overflow detected. Please increase the buffer size and recompile."));
+             } else {
+               nw += tempNw;
+             }
+           }
+            mcm->ZSMapping();  // Calculate zero suppression mapping
+                               // at the moment it has to be rerun here
+            // Write MCM data to temp. buffer
+            Int_t tempNw = mcm->ProduceRawStream( &tempBuffer[*tempnw], maxSize - *tempnw, fEventCounter );
+            if ( tempNw < 0 ) {
+              *tempof += tempNw;
+              *tempnw += maxSize - nw;
+              AliError(Form("Buffer overflow detected. Please increase the buffer size and recompile."));
+            } else {
+              *tempnw += tempNw;
+            }
+          }
+       }
 
-  }
+        delete mcm;
 
-  delete hc_buffer;
-  return kTRUE;
 
+       // in case of tracklet writing copy temp data to final buffer
+       if (tracklet_on) {
+         if (nw + *tempnw < maxSize) {
+           memcpy(&buf[nw], tempBuffer, *tempnw * sizeof(UInt_t));
+           nw += *tempnw;
+         }
+         else {
+           AliError("Buffer overflow detected");
+         }
+       }
+
+       // Write end of raw data marker
+       if (nw+3 < maxSize) {
+          buf[nw++] = 0x00000000; // fFee->GetRawDataEndmarker(); 
+          buf[nw++] = 0x00000000; // fFee->GetRawDataEndmarker(); 
+          buf[nw++] = 0x00000000; // fFee->GetRawDataEndmarker(); 
+          buf[nw++] = 0x00000000; // fFee->GetRawDataEndmarker(); 
+       } else {
+          of++;
+       }
+       
+        if (tracklet_on) {
+          delete [] tempBuffer;
+          delete tempof;
+          delete tempnw;
+        }
+
+       if (of != 0) {
+          AliError("Buffer overflow. Data is truncated. Please increase buffer size and recompile.");
+       }
+
+       return nw;
 }
 
 //_____________________________________________________________________________
-Int_t AliTRDrawData::ProduceHcDataV1andV2(AliTRDdataArrayI *digits, Int_t side
+Int_t AliTRDrawData::ProduceHcDataV1andV2(AliTRDarrayADC *digits, Int_t side
                                         , Int_t det, UInt_t *buf, Int_t maxSize)
 {
   //
-  // This function simulates: 1) SM-I commissiong data Oct. 06 (fRawVersion == 1).
-  //                          2) Full Raw Production Version   (fRawVersion == 2)
+  // This function simulates: 1) SM-I commissiong data Oct. 06 (Raw Version == 1).
+  //                          2) Full Raw Production Version   (Raw Version == 2)
   //
   // Produce half chamber data (= an ORI data) for the given chamber (det) and side (side)
   // where
@@ -460,17 +610,18 @@ Int_t AliTRDrawData::ProduceHcDataV1andV2(AliTRDdataArrayI *digits, Int_t side
   // the function will finish without crash (this behaviour is similar to the MCM).
   //
 
-  Int_t          nw = 0;                       // Number of written    words
-  Int_t          of = 0;                       // Number of overflowed words
-  Int_t        plan = fGeo->GetPlane( det );   // Plane
-  Int_t        cham = fGeo->GetChamber( det ); // Chamber
-  Int_t        sect = fGeo->GetSector( det );  // Sector (=iDDL)
-  Int_t        nRow = fCommonParam->GetRowMax( plan, cham, sect );
-  Int_t        nCol = fCommonParam->GetColMax( plan );
-  const Int_t nTBin = fCalibration->GetNumberOfTimeBins();
-  Int_t      kCtype = 0;                       // Chamber type (0:C0, 1:C1)
-  Int_t         iEv = 0xA;                     // Event ID. Now fixed to 10, how do I get event id?
-  UInt_t          x = 0;                       // General used number
+  Int_t           nw = 0;                       // Number of written    words
+  Int_t           of = 0;                       // Number of overflowed words
+  Int_t        layer = fGeo->GetLayer( det );   // Layer
+  Int_t        stack = fGeo->GetStack( det );   // Stack
+  Int_t         sect = fGeo->GetSector( det );  // Sector (=iDDL)
+  Int_t         nRow = fGeo->GetRowMax( layer, stack, sect );
+  Int_t         nCol = fGeo->GetColMax( layer );
+  const Int_t kNTBin = AliTRDcalibDB::Instance()->GetNumberOfTimeBins();
+  Int_t       kCtype = 0;                       // Chamber type (0:C0, 1:C1)
+  Int_t          iEv = 0xA;                     // Event ID. Now fixed to 10, how do I get event id?
+  UInt_t           x = 0;                       // General used number
+  Int_t           rv = fFee->GetRAWversion();
 
   // Check the nCol and nRow.
   if ((nCol == 144) && 
@@ -483,24 +634,24 @@ Int_t AliTRDrawData::ProduceHcDataV1andV2(AliTRDdataArrayI *digits, Int_t side
     return 0;
   }
 
-  AliDebug(1,Form("Producing raw data for sect=%d plan=%d cham=%d side=%d"
-                 ,sect,plan,cham,side));
+  AliDebug(1,Form("Producing raw data for sect=%d layer=%d stack=%d side=%d"
+                 ,sect,layer,stack,side));
 
   // Tracklet should be processed here but not implemented yet
 
   // Write end of tracklet marker
   if (nw < maxSize) {
-    buf[nw++] = endoftrackletmarker;
+    buf[nw++] = kEndoftrackletmarker;
   } 
   else {
     of++;
   }
 
   // Half Chamber header
-  if      ( fRawVersion == 1 ) {
+  if      ( rv == 1 ) {
     // Now it is the same version as used in SM-I commissioning.
     Int_t  dcs = det+100;      // DCS Serial (in simulation, it is meaningless
-    x = (dcs<<20) | (sect<<15) | (plan<<12) | (cham<<9) | (side<<8) | 1;
+    x = (dcs<<20) | (sect<<15) | (layer<<12) | (stack<<9) | (side<<8) | 1;
     if (nw < maxSize) {
       buf[nw++] = x; 
     }
@@ -508,11 +659,11 @@ Int_t AliTRDrawData::ProduceHcDataV1andV2(AliTRDdataArrayI *digits, Int_t side
       of++;
     }
   } 
-  else if ( fRawVersion == 2 ) {
-    // h[0] (there are 2 HC header)
+  else if ( rv == 2 ) {
+    // h[0] (there are 3 HC header)
     Int_t minorv = 0;      // The minor version number
-    Int_t add    = 1;      // The number of additional header words to follow
-    x = (1<<31) | (fRawVersion<<24) | (minorv<<17) | (add<<14) | (sect<<9) | (plan<<6) | (cham<<3) | (side<<2) | 1;
+    Int_t add    = 2;      // The number of additional header words to follow
+    x = (1<<31) | (rv<<24) | (minorv<<17) | (add<<14) | (sect<<9) | (layer<<6) | (stack<<3) | (side<<2) | 1;
     if (nw < maxSize) {
       buf[nw++] = x; 
     }
@@ -520,10 +671,26 @@ Int_t AliTRDrawData::ProduceHcDataV1andV2(AliTRDdataArrayI *digits, Int_t side
       of++;
     }
     // h[1]
-    Int_t bc_ctr   = 99; // bunch crossing counter. Here it is set to 99 always for no reason
-    Int_t pt_ctr   = 15; // pretrigger counter. Here it is set to 15 always for no reason
-    Int_t pt_phase = 11; // pretrigger phase. Here it is set to 11 always for no reason
-    x = (bc_ctr<<16) | (pt_ctr<<12) | (pt_phase<<8) | ((nTBin-1)<<2) | 1;
+    Int_t bcCtr   = 99; // bunch crossing counter. Here it is set to 99 always for no reason
+    Int_t ptCtr   = 15; // pretrigger counter. Here it is set to 15 always for no reason
+    Int_t ptPhase = 11; // pretrigger phase. Here it is set to 11 always for no reason
+    x = (bcCtr<<16) | (ptCtr<<12) | (ptPhase<<8) | ((kNTBin-1)<<2) | 1;
+    if (nw < maxSize) {
+      buf[nw++] = x; 
+    }
+    else {
+      of++;
+    }
+    // h[2]
+    Int_t pedSetup       = 1;    // Pedestal filter setup (0:1). Here it is always 1 for no reason
+    Int_t gainSetup      = 1;    // Gain filter setup (0:1). Here it is always 1 for no reason
+    Int_t tailSetup      = 1;    // Tail filter setup (0:1). Here it is always 1 for no reason
+    Int_t xtSetup        = 0;    // Cross talk filter setup (0:1). Here it is always 0 for no reason
+    Int_t nonlinSetup    = 0;    // Nonlinearity filter setup (0:1). Here it is always 0 for no reason
+    Int_t bypassSetup    = 0;    // Filter bypass (for raw data) setup (0:1). Here it is always 0 for no reason
+    Int_t commonAdditive = 10;   // Digital filter common additive (0:63). Here it is always 10 for no reason
+    x = (pedSetup<<31) | (gainSetup<<30) | (tailSetup<<29) | (xtSetup<<28) | (nonlinSetup<<27)
+      | (bypassSetup<<26) | (commonAdditive<<20) | 1;
     if (nw < maxSize) {
       buf[nw++] = x; 
     }
@@ -549,15 +716,15 @@ Int_t AliTRDrawData::ProduceHcDataV1andV2(AliTRDdataArrayI *digits, Int_t side
 
       // ADC data
       for (Int_t iAdc = 0; iAdc < 21; iAdc++ ) {
-       Int_t padcol = fGeo->GetPadCol(iRob, iMcm, iAdc);
-       UInt_t aa = !(iAdc & 1) + 2;
-        UInt_t *a = new UInt_t[nTBin+2];
+       Int_t padcol = fFee->GetPadColFromADC(iRob, iMcm, iAdc);
+       UInt_t aa = !(iAdc & 1) + 2;    // 3 for the even ADC channel , 2 for the odd ADC channel
+        UInt_t *a = new UInt_t[kNTBin+2];
         // 3 timebins are packed into one 32 bits word
-        for (Int_t iT = 0; iT < nTBin; iT+=3) { 
+        for (Int_t iT = 0; iT < kNTBin; iT+=3) { 
           if ((padcol >=    0) && (padcol <  nCol)) {
-           a[iT  ] = ((iT    ) < nTBin ) ? digits->GetDataUnchecked(padrow,padcol,iT    ) : 0;
-           a[iT+1] = ((iT + 1) < nTBin ) ? digits->GetDataUnchecked(padrow,padcol,iT + 1) : 0;
-           a[iT+2] = ((iT + 2) < nTBin ) ? digits->GetDataUnchecked(padrow,padcol,iT + 2) : 0; 
+           a[iT  ] = ((iT    ) < kNTBin ) ? digits->GetData(padrow,padcol,iT    ) : 0;
+           a[iT+1] = ((iT + 1) < kNTBin ) ? digits->GetData(padrow,padcol,iT + 1) : 0;
+           a[iT+2] = ((iT + 2) < kNTBin ) ? digits->GetData(padrow,padcol,iT + 2) : 0; 
          } 
          else {
            a[iT] = a[iT+1] = a[iT+2] = 0; // This happenes at the edge of chamber (should be pedestal! How?)
@@ -573,26 +740,26 @@ Int_t AliTRDrawData::ProduceHcDataV1andV2(AliTRDdataArrayI *digits, Int_t side
         // Diagnostics
         Float_t avg = 0;
         Float_t rms = 0;
-        for (Int_t iT = 0; iT < nTBin; iT++) {
+        for (Int_t iT = 0; iT < kNTBin; iT++) {
           avg += (Float_t) (a[iT]);
        }
-        avg /= (Float_t) nTBin;
-        for (Int_t iT = 0; iT < nTBin; iT++) {
+        avg /= (Float_t) kNTBin;
+        for (Int_t iT = 0; iT < kNTBin; iT++) {
           rms += ((Float_t) (a[iT]) - avg) * ((Float_t) (a[iT]) - avg);
        }
-        rms = TMath::Sqrt(rms / (Float_t) nTBin);
+        rms = TMath::Sqrt(rms / (Float_t) kNTBin);
         if (rms > 1.7) {
           AliDebug(2,Form("Large RMS (>1.7)  (ROB,MCM,ADC)=(%02d,%02d,%02d), avg=%03.1f, rms=%03.1f"
                          ,iRob,iMcm,iAdc,avg,rms));
        }
-        delete a;
+        delete [] a;
       }
     }
   }
 
   // Write end of raw data marker
   if (nw < maxSize) {
-    buf[nw++] = endofeventmarker; 
+    buf[nw++] = kEndofrawdatamarker; 
   }
   else {
     of++;
@@ -606,148 +773,426 @@ Int_t AliTRDrawData::ProduceHcDataV1andV2(AliTRDdataArrayI *digits, Int_t side
 }
 
 //_____________________________________________________________________________
-AliTRDdigitsManager *AliTRDrawData::Raw2Digits(AliRawReader *rawReader)
+
+//Int_t AliTRDrawData::ProduceHcDataV3(AliTRDarrayADC *digits, Int_t side , Int_t det, UInt_t *buf, Int_t maxSize)
+Int_t AliTRDrawData::ProduceHcDataV3(AliTRDarrayADC *digits, Int_t side , Int_t det, UInt_t *buf, Int_t maxSize, Bool_t newEvent = kFALSE)
 {
   //
-  // Read raw data and convert to digits
+  // This function simulates: Raw Version == 3 (Zero Suppression Prototype)
   //
 
-  if ( fRawVersion == 0 ) {
-    return Raw2DigitsV0(rawReader);  // fRawVersion == 0
+  Int_t           nw = 0;                       // Number of written    words
+  Int_t           of = 0;                       // Number of overflowed words
+  Int_t        layer = fGeo->GetLayer( det );   // Layer
+  Int_t        stack = fGeo->GetStack( det );   // Stack
+  Int_t         sect = fGeo->GetSector( det );  // Sector (=iDDL)
+  Int_t         nRow = fGeo->GetRowMax( layer, stack, sect );
+  Int_t         nCol = fGeo->GetColMax( layer );
+  const Int_t kNTBin = AliTRDcalibDB::Instance()->GetNumberOfTimeBins();
+  Int_t       kCtype = 0;                       // Chamber type (0:C0, 1:C1)
+  //Int_t          iEv = 0xA;                     // Event ID. Now fixed to 10, how do I get event id?
+
+
+  Bool_t tracklet_on = fFee->GetTracklet();     // **new**
+
+  // Check the nCol and nRow.
+  if ((nCol == 144) && 
+      (nRow == 16 || nRow == 12)) {
+    kCtype = (nRow-12) / 4;
+  } 
+  else {
+    AliError(Form("This type of chamber is not supported (nRow=%d, nCol=%d)."
+                 ,nRow,nCol));
+    return 0;
+  }
+
+  AliDebug(1,Form("Producing raw data for sect=%d layer=%d stack=%d side=%d"
+                 ,sect,layer,stack,side));
+
+  AliTRDmcmSim** mcm = new AliTRDmcmSim*[(kCtype + 3)*(fGeo->MCMmax())];
+
+  // in case no tracklet-words are processed: write the tracklet-endmarker as well as all additional words immediately and write 
+  // raw-data in one go; if tracklet-processing is enabled, first all tracklet-words of a half-chamber have to be processed before the
+  // additional words (tracklet-endmarker,headers,...)are written. Raw-data is written in a second loop;
+  
+  if (!tracklet_on) {
+      WriteIntermediateWords(buf,nw,of,maxSize,det,side); 
+  }
+  
+  // Scan for ROB and MCM
+  // scanning direction such, that tracklet-words are sorted in ascending z and then in ascending y order
+  // ROB numbering on chamber and MCM numbering on ROB increase with decreasing z and increasing y
+  for (Int_t iRobRow =  (kCtype + 3)-1; iRobRow >= 0; iRobRow-- ) {
+    Int_t iRob = iRobRow * 2 + side;
+    // MCM on one ROB
+    for (Int_t iMcmRB = 0; iMcmRB < fGeo->MCMmax(); iMcmRB++ ) {
+       Int_t iMcm = 16 - 4*(iMcmRB/4 + 1) + (iMcmRB%4);
+       Int_t entry = iRobRow*(fGeo->MCMmax()) + iMcm;
+       
+       mcm[entry] = new AliTRDmcmSim();
+       mcm[entry]->Init( det, iRob, iMcm , newEvent);
+       //mcm[entry]->Init( det, iRob, iMcm);
+       if (newEvent == kTRUE) newEvent = kFALSE; // only one mcm is concerned with new event
+       Int_t padrow = mcm[entry]->GetRow();
+
+       // Copy ADC data to MCM simulator
+       for (Int_t iAdc = 0; iAdc < 21; iAdc++ ) {
+           Int_t padcol = mcm[entry]->GetCol( iAdc );
+           if ((padcol >=    0) && (padcol <  nCol)) {
+               for (Int_t iT = 0; iT < kNTBin; iT++) { 
+                 mcm[entry]->SetData( iAdc, iT, digits->GetData( padrow, padcol, iT) );
+               } 
+           } 
+           else {  // this means it is out of chamber, and masked ADC
+               mcm[entry]->SetDataPedestal( iAdc );
+           }
+       }
+
+       // Simulate process in MCM
+       mcm[entry]->Filter();     // Apply filter
+       mcm[entry]->ZSMapping();  // Calculate zero suppression mapping
+//jkl  mcm[entry]->CopyArrays();
+//jkl  mcm[entry]->GeneratefZSM1Dim();
+//jkl  mcm[entry]->RestoreZeros();
+
+       if (tracklet_on) {
+           mcm[entry]->Tracklet(); 
+           Int_t tempNw =  mcm[entry]->ProduceTrackletStream( &buf[nw], maxSize - nw );
+           //Int_t tempNw = 0;
+           if( tempNw < 0 ) {
+               of += tempNw;
+               nw += maxSize - nw;
+               AliError(Form("Buffer overflow detected. Please increase the buffer size and recompile."));
+           } else {
+               nw += tempNw;
+           }
+       }
+       // no tracklets: write raw-data already in this loop
+       else {
+            // Write MCM data to buffer
+           Int_t tempNw =  mcm[entry]->ProduceRawStream( &buf[nw], maxSize - nw );
+           if( tempNw < 0 ) {
+               of += tempNw;
+               nw += maxSize - nw;
+               AliError(Form("Buffer overflow detected. Please increase the buffer size and recompile."));
+           } else {
+               nw += tempNw;
+           }
+           
+           delete mcm[entry];
+       }
+           
+       
+
+
+       //mcm->DumpData( "trdmcmdata.txt", "RFZS" ); // debugging purpose
+    }
+  }
+
+  // if tracklets are switched on, raw-data can be written only after all tracklets
+  if (tracklet_on) {
+      WriteIntermediateWords(buf,nw,of,maxSize,det,side); 
+  
+  
+      // Scan for ROB and MCM
+      for (Int_t iRobRow =  (kCtype + 3)-1; iRobRow >= 0; iRobRow-- ) {
+         //Int_t iRob = iRobRow * 2 + side;
+         // MCM on one ROB
+         for (Int_t iMcmRB = 0; iMcmRB < fGeo->MCMmax(); iMcmRB++ ) {
+             Int_t iMcm = 16 - 4*(iMcmRB/4 + 1) + (iMcmRB%4);
+             
+             Int_t entry = iRobRow*(fGeo->MCMmax()) + iMcm; 
+             
+             // Write MCM data to buffer
+             Int_t tempNw =  mcm[entry]->ProduceRawStream( &buf[nw], maxSize - nw );
+             if( tempNw < 0 ) {
+                 of += tempNw;
+                 nw += maxSize - nw;
+                 AliError(Form("Buffer overflow detected. Please increase the buffer size and recompile."));
+             } else {
+                 nw += tempNw;
+             }
+             
+             delete mcm[entry];
+         
+         }
+      }
+  }
+
+  delete [] mcm;
+  
+  // Write end of raw data marker
+  if (nw < maxSize) {
+    buf[nw++] = kEndofrawdatamarker; 
   }
   else {
-    return Raw2DigitsVx(rawReader);  // fRawVersion > 0
+    of++;
+  }
+  if (of != 0) {
+    AliError("Buffer overflow. Data is truncated. Please increase buffer size and recompile.");
   }
 
+
+  return nw;
+
 }
 
 //_____________________________________________________________________________
-AliTRDdigitsManager *AliTRDrawData::Raw2DigitsV0(AliRawReader *rawReader)
+AliTRDdigitsManager *AliTRDrawData::Raw2Digits(AliRawReader *rawReader)
 {
   //
-  // Bogdan's raw data reader (for offline only).
+  // Vx of the raw data reading
   //
 
-  AliTRDdataArrayI *digits = 0;
-  AliTRDdataArrayI *track0 = 0;
-  AliTRDdataArrayI *track1 = 0;
-  AliTRDdataArrayI *track2 = 0; 
-
-  AliTRDgeometry *geo = new AliTRDgeometry();
-
-  AliTRDCommonParam* commonParam = AliTRDCommonParam::Instance();
-  if (!commonParam) {
-    AliError("Could not get common parameters");
-    return 0;
-  }
-
-  AliTRDcalibDB* calibration = AliTRDcalibDB::Instance();
-  if (!calibration) {
-    AliError("Could not get calibration object");
-    return 0;
-  }
+  AliTRDarrayADC *digits = 0;
+  AliTRDarrayDictionary *track0 = 0;
+  AliTRDarrayDictionary *track1 = 0;
+  AliTRDarrayDictionary *track2 = 0;  
 
+  //AliTRDSignalIndex *indexes = 0;
   // Create the digits manager
   AliTRDdigitsManager* digitsManager = new AliTRDdigitsManager();
   digitsManager->CreateArrays();
 
-  AliTRDRawStream input(rawReader);
+  AliTRDrawStreamBase *pinput = AliTRDrawStreamBase::GetRawStream(rawReader);
+  AliTRDrawStreamBase &input = *pinput;
+  input.SetRawVersion( fFee->GetRAWversion() ); //<= ADDED by MinJung
 
-  // Loop through the digits
-  while (input.Next()) {
-
-    Int_t det    = input.GetDetector();
-    Int_t npads  = input.GetNPads();
-
-    if (input.IsNewDetector()) {
-
-      if (digits) digits->Compress(1,0);
-      if (track0) track0->Compress(1,0);
-      if (track1) track1->Compress(1,0);
-      if (track2) track2->Compress(1,0);
-
-      AliDebug(2,"Subevent header:");
-      AliDebug(2,Form("\tdet   = %d",det));
-      AliDebug(2,Form("\tnpads = %d",npads));
-
-      // Create the data buffer
-      Int_t cham      = geo->GetChamber(det);
-      Int_t plan      = geo->GetPlane(det);
-      Int_t sect      = geo->GetSector(det);
-      Int_t rowMax    = commonParam->GetRowMax(plan,cham,sect);
-      Int_t colMax    = commonParam->GetColMax(plan);
-      Int_t timeTotal = calibration->GetNumberOfTimeBins();
-
-      // Add a container for the digits of this detector
-      digits = digitsManager->GetDigits(det);
-      track0 = digitsManager->GetDictionary(det,0);
-      track1 = digitsManager->GetDictionary(det,1);
-      track2 = digitsManager->GetDictionary(det,2);
-      // Allocate memory space for the digits buffer
-      if (digits->GetNtime() == 0) {
-        digits->Allocate(rowMax,colMax,timeTotal);
-        track0->Allocate(rowMax,colMax,timeTotal);
-        track1->Allocate(rowMax,colMax,timeTotal);
-        track2->Allocate(rowMax,colMax,timeTotal);
-      }
+  AliInfo(Form("Stream version: %s", input.IsA()->GetName()));
 
+  // Loop through the digits
+  Int_t det    = 0;
+
+  while (det >= 0)
+    {
+      det = input.NextChamber(digitsManager);
+      if (det >= 0)
+       {
+         // get...
+         digits = (AliTRDarrayADC *) digitsManager->GetDigits(det);
+         track0 = (AliTRDarrayDictionary *) digitsManager->GetDictionary(det,0);
+         track1 = (AliTRDarrayDictionary *) digitsManager->GetDictionary(det,1);
+         track2 = (AliTRDarrayDictionary *) digitsManager->GetDictionary(det,2);
+         // and compress
+         if (digits) digits->Compress();  
+         if (track0) track0->Compress();   
+         if (track1) track1->Compress();     
+         if (track2) track2->Compress();
+       }
     }
 
-    digits->SetDataUnchecked(input.GetRow(),input.GetColumn(),
-                            input.GetTime(),input.GetSignal());
-    track0->SetDataUnchecked(input.GetRow(),input.GetColumn(),
-                             input.GetTime(),                0);
-    track1->SetDataUnchecked(input.GetRow(),input.GetColumn(),
-                             input.GetTime(),                0);
-    track2->SetDataUnchecked(input.GetRow(),input.GetColumn(),
-                             input.GetTime(),                0);
+  delete pinput;
+  pinput = NULL;
 
-  }
+  return digitsManager;
+}
 
-  if (digits) digits->Compress(1,0);
-  if (track0) track0->Compress(1,0);
-  if (track1) track1->Compress(1,0);
-  if (track2) track2->Compress(1,0);
 
-  delete geo;
+//_____________________________________________________________________________
+void AliTRDrawData::WriteIntermediateWords(UInt_t* buf, Int_t& nw, Int_t& of, const Int_t& maxSize, const Int_t& det, const Int_t& side) {
+    
+    Int_t        layer = fGeo->GetLayer( det );   // Layer
+    Int_t        stack = fGeo->GetStack( det );   // Stack
+    Int_t         sect = fGeo->GetSector( det );  // Sector (=iDDL)
+    Int_t           rv = fFee->GetRAWversion();
+    const Int_t kNTBin = AliTRDcalibDB::Instance()->GetNumberOfTimeBins();
+    UInt_t           x = 0;
+
+    // Write end of tracklet marker
+    if (nw < maxSize) {
+       buf[nw++] = kEndoftrackletmarker;
+    } 
+    else {
+       of++;
+    }
+    
+  // Half Chamber header
+  // h[0] (there are 3 HC header)
+    Int_t minorv = 0;    // The minor version number
+    Int_t add    = 2;    // The number of additional header words to follow
+    x = (1<<31) | (rv<<24) | (minorv<<17) | (add<<14) | (sect<<9) | (layer<<6) | (stack<<3) | (side<<2) | 1;
+    if (nw < maxSize) {
+       buf[nw++] = x; 
+    }
+    else {
+       of++;
+    }
+    // h[1]
+    Int_t bcCtr   = 99; // bunch crossing counter. Here it is set to 99 always for no reason
+    Int_t ptCtr   = 15; // pretrigger counter. Here it is set to 15 always for no reason
+    Int_t ptPhase = 11; // pretrigger phase. Here it is set to 11 always for no reason
+    x = (bcCtr<<16) | (ptCtr<<12) | (ptPhase<<8) | ((kNTBin-1)<<2) | 1;
+    if (nw < maxSize) {
+       buf[nw++] = x; 
+    }
+    else {
+       of++;
+    }
+    // h[2]
+    Int_t pedSetup       = 1;  // Pedestal filter setup (0:1). Here it is always 1 for no reason
+    Int_t gainSetup      = 1;  // Gain filter setup (0:1). Here it is always 1 for no reason
+    Int_t tailSetup      = 1;  // Tail filter setup (0:1). Here it is always 1 for no reason
+    Int_t xtSetup        = 0;  // Cross talk filter setup (0:1). Here it is always 0 for no reason
+    Int_t nonlinSetup    = 0;  // Nonlinearity filter setup (0:1). Here it is always 0 for no reason
+    Int_t bypassSetup    = 0;  // Filter bypass (for raw data) setup (0:1). Here it is always 0 for no reason
+    Int_t commonAdditive = 10; // Digital filter common additive (0:63). Here it is always 10 for no reason
+    x = (pedSetup<<31) | (gainSetup<<30) | (tailSetup<<29) | (xtSetup<<28) | (nonlinSetup<<27)
+       | (bypassSetup<<26) | (commonAdditive<<20) | 1;
+    if (nw < maxSize) {
+       buf[nw++] = x; 
+    }
+    else {
+       of++;
+    } 
+}
 
-  return digitsManager;
+//_____________________________________________________________________________
+void AliTRDrawData::WriteIntermediateWordsV2(UInt_t* buf, Int_t& nw, Int_t& of, const Int_t& maxSize, const Int_t& det, const Int_t& side) {
+    
+    Int_t        layer = fGeo->GetLayer( det );   // Layer
+    Int_t        stack = fGeo->GetStack( det );   // Stack
+    Int_t         sect = fGeo->GetSector( det );  // Sector (=iDDL)
+    Int_t           rv = fFee->GetRAWversion();
+    const Int_t kNTBin = AliTRDcalibDB::Instance()->GetNumberOfTimeBins();
+       Bool_t tracklet_on = fFee->GetTracklet();
+    UInt_t           x = 0;
+
+    // Write end of tracklet marker
+       if (nw < maxSize){
+        buf[nw++] = fgkEndOfTrackletMarker;
+        buf[nw++] = fgkEndOfTrackletMarker;     // the number of tracklet end marker should be more than 2
+    }
+    else {
+        of++;
+    }
 
+   
+       // Half Chamber header
+       // h[0] (there are 2 HC headers) xmmm mmmm nnnn nnnq qqss sssp ppcc ci01
+       //      , where  x : Raw version speacial number (=1)
+       //                   m : Raw version major number (test pattern, ZS, disable tracklet, 0, options)
+       //                   n : Raw version minor number
+       //                   q : number of addtional header words (default = 1)
+       //                   s : SM sector number (ALICE numbering)
+       //                   p : plane(layer) number
+       //                       c : chamber(stack) number
+       //                       i : side number (0:A, 1:B)
+       Int_t majorv = 0;       // The major version number 
+    Int_t minorv = 0;  // The minor version number
+    Int_t add    = 1;  // The number of additional header words to follow : now 1, previous 2
+       Int_t TP         = 0;   // test pattern (default=0)
+       Int_t ZS         = (rv==3) ? 1 : 0;                     // zero suppression
+       Int_t DT         = (tracklet_on) ? 0 : 1;       // disable tracklet 
+
+       majorv = (TP<<6) | (ZS<<5) | (DT<<4) | 1;       // major version
+
+    x = (1<<31) | (majorv<<24) | (minorv<<17) | (add<<14) | (sect<<9) | (layer<<6) | (stack<<3) | (side<<2) | 1;
+    if (nw < maxSize) buf[nw++] = x; else of++;
+   
+    // h[1]            tttt ttbb bbbb bbbb bbbb bbpp pphh hh01
+       // , where  t : number of time bins
+       //          b : bunch crossing number
+       //          p : pretrigger counter
+       //          h : pretrigger phase
+    Int_t bcCtr   = 99; // bunch crossing counter. Here it is set to 99 always for no reason
+    Int_t ptCtr   = 15; // pretrigger counter. Here it is set to 15 always for no reason
+    Int_t ptPhase = 11; // pretrigger phase. Here it is set to 11 always for no reason
+    //x = (bcCtr<<16) | (ptCtr<<12) | (ptPhase<<8) | ((kNTBin-1)<<2) | 1;      // old format
+    x = ((kNTBin)<<26) | (bcCtr<<10) | (ptCtr<<6) | (ptPhase<<2) | 1;
+    if (nw < maxSize) buf[nw++] = x; else of++;
+  
 }
 
 //_____________________________________________________________________________
-AliTRDdigitsManager *AliTRDrawData::Raw2DigitsVx(AliRawReader *rawReader)
+AliTRDdigitsManager *AliTRDrawData::Raw2DigitsOLD(AliRawReader *rawReader)
 {
-
   //
-  // This is executed for all Raw Data Versions > 0. Raw data is read and filled
-  // into digits array. Next function is not used.
+  // Vx of the raw data reading
   //
 
-  AliTRDdataArrayI  *digits      = 0;
-
-  AliTRDCommonParam *commonParam = AliTRDCommonParam::Instance();
-  if (!commonParam) {
-    AliError("Could not get common params");
-    return 0;
-  }
-
-  AliTRDcalibDB     *calibration = AliTRDcalibDB::Instance();
-  if (!calibration) {
-    AliError("Could not get calibration object");
-    return 0;
-  }
+  AliTRDarrayADC *digits = 0;
+  AliTRDarrayDictionary *track0 = 0;
+  AliTRDarrayDictionary *track1 = 0;
+  AliTRDarrayDictionary *track2 = 0; 
 
+  AliTRDSignalIndex *indexes = 0;
   // Create the digits manager
   AliTRDdigitsManager* digitsManager = new AliTRDdigitsManager();
   digitsManager->CreateArrays();
 
-  AliTRDRawStream input(rawReader, digitsManager, digits);
-  input.SetRawVersion( fRawVersion );
-  input.ReadAll();     // Loop through the digits
+  AliTRDrawOldStream input(rawReader);
+  input.SetRawVersion( fFee->GetRAWversion() );
+  input.Init();
+
+  AliInfo(Form("Stream version: %s", input.IsA()->GetName()));
+
+  // Loop through the digits
+  Int_t lastdet = -1;
+  Int_t det    = 0;
+  Int_t it = 0;
+  while (input.Next()) {
+
+      det    = input.GetDet();
+
+      if (det != lastdet) { // If new detector found
+       
+         lastdet = det;
+
+         if (digits) digits->Compress();
+         if (track0) track0->Compress();       
+         if (track1) track1->Compress();       
+         if (track2) track2->Compress();
+       
+         // Add a container for the digits of this detector
+         digits = (AliTRDarrayADC *) digitsManager->GetDigits(det);
+         track0 = (AliTRDarrayDictionary *) digitsManager->GetDictionary(det,0);
+         track1 = (AliTRDarrayDictionary *) digitsManager->GetDictionary(det,1);
+         track2 = (AliTRDarrayDictionary *) digitsManager->GetDictionary(det,2);
+
+         // Allocate memory space for the digits buffer
+         if (digits->GetNtime() == 0) 
+           {
+             digits->Allocate(input.GetMaxRow(),input.GetMaxCol(), input.GetNumberOfTimeBins());
+             track0->Allocate(input.GetMaxRow(),input.GetMaxCol(), input.GetNumberOfTimeBins());
+             track1->Allocate(input.GetMaxRow(),input.GetMaxCol(), input.GetNumberOfTimeBins());
+             track2->Allocate(input.GetMaxRow(),input.GetMaxCol(), input.GetNumberOfTimeBins());
+           }
+
+         indexes = digitsManager->GetIndexes(det);
+         indexes->SetSM(input.GetSM());
+         indexes->SetStack(input.GetStack());
+         indexes->SetLayer(input.GetLayer());
+         indexes->SetDetNumber(det);
+         if (indexes->IsAllocated() == kFALSE)
+           indexes->Allocate(input.GetMaxRow(), input.GetMaxCol(), input.GetNumberOfTimeBins());
+       }
+    
+      // 3 timebin data are stored per word
+      for (it = 0; it < 3; it++)
+       {
+         if ( input.GetTimeBin() + it < input.GetNumberOfTimeBins() )
+           {
+             if (input.GetSignals()[it] > 0)
+               {
+                 digits->SetData(input.GetRow(), input.GetCol(),input.GetTimeBin() + it, input.GetSignals()[it]);
+
+                 indexes->AddIndexRC(input.GetRow(), input.GetCol());
+                 track0->SetData(input.GetRow(), input.GetCol(), input.GetTimeBin() + it, 0);
+                 track1->SetData(input.GetRow(), input.GetCol(), input.GetTimeBin() + it, 0);
+                 track2->SetData(input.GetRow(), input.GetCol(), input.GetTimeBin() + it, 0);
+               }
+           }
+       }
+  }
 
-  delete digits;
+  if (digits) digits->Compress();
+  if (track0) track0->Compress();        
+  if (track1) track1->Compress();       
+  if (track2) track2->Compress();
 
   return digitsManager;
 
 }
+
+