]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - TRD/AliTRDrawData.cxx
Inserting TMath.h where required by the new version of ROOT
[u/mrichter/AliRoot.git] / TRD / AliTRDrawData.cxx
index 85bdbe1751fccbd0cbd748efc2fce5f710bd09ab..2bf77c2738c347e643ebf6524448281b50ce96af 100644 (file)
  * provided "as is" without express or implied warranty.                  *
  **************************************************************************/
 
-/*
-$Log$
-Revision 1.1.2.1  2002/10/11 07:26:37  hristov
-Updating VirtualMC to v3-09-02
-
-Revision 1.1  2002/09/13 14:33:52  cblume
-Add conversion class to produce fake raw data
-
-*/
+/* $Id$ */
 
 ///////////////////////////////////////////////////////////////////////////////
 //                                                                           //
@@ -29,35 +21,52 @@ Add conversion class to produce fake raw data
 //                                                                           //
 ///////////////////////////////////////////////////////////////////////////////
 
-#include <fstream.h>
+#include <Riostream.h>
+#include <TMath.h>
+
+#include "AliDAQ.h"
+#include "AliRawDataHeader.h"
+#include "AliRawReader.h"
+#include "AliLog.h"
 
 #include "AliTRDrawData.h"
 #include "AliTRDdigitsManager.h"
-#include "AliTRDgeometryFull.h"
-#include "AliTRDparameter.h"
+#include "AliTRDgeometry.h"
 #include "AliTRDdataArrayI.h"
-#include "AliTRDarrayI.h"
+#include "AliTRDRawStream.h"
+#include "AliTRDCommonParam.h"
+#include "AliTRDcalibDB.h"
 
 ClassImp(AliTRDrawData)
 
 //_____________________________________________________________________________
-AliTRDrawData::AliTRDrawData():TObject()
+AliTRDrawData::AliTRDrawData()
+  :TObject()
+  ,fRawVersion(1)
+  ,fCommonParam(0)
+  ,fCalibration(0)
+  ,fGeo(0)
+  ,fNumberOfDDLs(0)
 {
-
-  fDebug         = 0;
-  fDigitsManager = NULL;
+  //
+  // Default constructor
+  //
 
 }
 
 //_____________________________________________________________________________
 AliTRDrawData::AliTRDrawData(const AliTRDrawData &r)
+  :TObject(r)
+  ,fRawVersion(1)
+  ,fCommonParam(0)
+  ,fCalibration(0)
+  ,fGeo(0)
+  ,fNumberOfDDLs(0)
 {
   //
-  // AliTRDrawData copy constructor
+  // Copy constructor
   //
 
-  ((AliTRDrawData &) r).Copy(*this);
-
 }
 
 //_____________________________________________________________________________
@@ -67,70 +76,106 @@ AliTRDrawData::~AliTRDrawData()
   // Destructor
   //
 
-  if (fDigitsManager) {
-    delete fDigitsManager;
-    fDigitsManager = NULL;
-  }
-
 }
 
 //_____________________________________________________________________________
-AliTRDrawData &AliTRDrawData::operator=(const AliTRDrawData &r)
+Bool_t AliTRDrawData::SetRawVersion(Int_t v)
 {
   //
-  // Assignment operator
+  // Set the raw data version
+  // Currently only version 0 and 1 are available.
   //
 
-  if (this != &r) ((AliTRDrawData &) r).Copy(*this);
-  return *this;
+  if ((v == 0) || 
+      (v == 1)) {
+    fRawVersion = v;
+    return kTRUE;
+  }
+
+  return kFALSE;
 
 }
 
 //_____________________________________________________________________________
-void AliTRDrawData::Copy(TObject &r)
+Bool_t AliTRDrawData::Digits2Raw(TTree *digitsTree, TTree *tracks )
 {
   //
-  // Copy function
+  // Initialize necessary parameters and call one
+  // of the raw data simulator selected by SetRawVersion.
+  //
+  // Currently tracklet output is not spported yet and it
+  // will be supported in higher version simulator.
   //
 
-  ((AliTRDrawData &) r).fDebug         = fDebug;
-  ((AliTRDrawData &) r).fDigitsManager = NULL;
+  fNumberOfDDLs = AliDAQ::NumberOfDdls("TRD");
 
-}
+  AliTRDdigitsManager* digitsManager = new AliTRDdigitsManager();
 
-//_____________________________________________________________________________
-Bool_t AliTRDrawData::OpenInput(const Char_t *name)
-{
-  //
-  // Opens a ROOT-file with the TRD digits 
-  //
+  if (!digitsManager->ReadDigits(digitsTree)) {
+    delete digitsManager;
+    return kFALSE;
+  }
 
-  // Create the digits manager
-  if (fDigitsManager) {
-    delete fDigitsManager;
+  if (tracks != NULL) {
+    delete digitsManager;
+    printf("<AliTRDrawData::Digits2Raw> Tracklet input is not supported yet.\n");
+    return kFALSE;
+  }
+
+  fGeo = new AliTRDgeometry();
+
+  fCommonParam = AliTRDCommonParam::Instance();
+  if (!fCommonParam) {
+    AliError("Could not get common params\n");
+    delete fGeo;
+    delete digitsManager;
+    return kFALSE;
+  }
+
+  fCalibration = AliTRDcalibDB::Instance();
+  if (!fCalibration) {
+    AliError("Could not get calibration object\n");
+    delete fGeo;
+    delete digitsManager;
+    return kFALSE;
   }
-  fDigitsManager = new AliTRDdigitsManager();
-  fDigitsManager->SetDebug(fDebug);
 
-  // Open the input file
-  return fDigitsManager->Open(name);
+  Int_t retval = kTRUE;
+
+  // Call appropriate Raw Simulator
+  switch( fRawVersion ) {
+    case 0 : 
+      retval = Digits2RawV0(digitsManager); 
+      break;
+    case 1 : 
+      retval = Digits2RawV1(digitsManager); 
+      break;
+  default: 
+      retval = kFALSE;
+      AliWarning(Form("Unsupported raw version (fRawVersion=%d).\n",fRawVersion));
+    break;
+  }
+
+  // Cleanup
+  delete fGeo;
+  delete digitsManager;
+
+  return retval;
 
 }
 
 //_____________________________________________________________________________
-Bool_t AliTRDrawData::Digit2Raw(const Char_t *name1, const Char_t *name2)
+Bool_t AliTRDrawData::Digits2RawV0(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 <name1> and <name2>.
+  // into the the binary files TRD_<DDL number>.ddl.
   //
   // The pseudo raw data format is currently defined like this:
   //
-  //          LDC header (8 bytes)
-  //                  FLAG
-  //                  LDC no.
-  //                  Number of detectors with data (not yet implemented)
-  //                  5 empty bytes
+  //          DDL data header
   //
   //          Subevent (= single chamber) header (8 bytes)
   //                  FLAG
@@ -142,118 +187,64 @@ Bool_t AliTRDrawData::Digit2Raw(const Char_t *name1, const Char_t *name2)
   //          Data bank
   //
 
-  const Int_t kLDCHeaderLength      = 8;
   const Int_t kSubeventHeaderLength = 8;
-
-  const Int_t kLDCDummyFlag         = 0xAA;
   const Int_t kSubeventDummyFlag    = 0xBB;
+  Int_t       headerSubevent[3];
 
-  int headerLDC[2];
-  int headerSubevent[2];
-
-  Int_t          ntotalbyte[2] = { 0 };
+  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 *byte_p;
-  unsigned char *header_p;
-
-  AliTRDgeometryFull *geo = new AliTRDgeometryFull();
-  AliTRDparameter    *par = new AliTRDparameter("TRDparameter"
-                                               ,"TRD parameter class");
-  AliTRDdataArrayI   *digits;
-
-  if (fDebug) {
-    Info("Digit2Raw","Open the LDC output files %s, %s"
-        ,name1,name2);
-  }
-  ofstream *outputFile1 = new ofstream(name1, ios::out | ios::binary);
-  ofstream *outputFile2 = new ofstream(name2, ios::out | ios::binary);
-  ofstream *outputFile;
+  unsigned char *bytePtr;
+  unsigned char *headerPtr;
 
-  if (!fDigitsManager) {
-    Error("Digit2Raw","No input file open\n");
-    return kFALSE;
-  }
-
-  // Read in the digit arrays
-  if (!fDigitsManager->ReadDigits()) {
-    return kFALSE;
-  }
+  AliTRDdataArrayI *digits;
+  AliRawDataHeader  header;   // The event header
 
-  // Count the number of chambers with data
-  Int_t ndetLDC0 = 0;
-  Int_t ndetLDC1 = 0;
+  // Open the output files
+  for (Int_t iDDL = 0; iDDL < fNumberOfDDLs; iDDL++) {
 
-  if (fDebug > 1) {
-    Info("Digit2Raw","Write the LDC headers");
-  }
+    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 the LDC header 1
-  byte_p    = (unsigned char *) headerLDC;
-  header_p  = byte_p;
-  *byte_p++ = kLDCDummyFlag;
-  *byte_p++ = 1;
-  *byte_p++ = ndetLDC0;
-  *byte_p++ = 0;
-  *byte_p++ = 0;
-  *byte_p++ = 0;
-  *byte_p++ = 0;
-  *byte_p++ = 0;
-  outputFile1->write(header_p,kLDCHeaderLength);
-  ntotalbyte[0] += kLDCHeaderLength;
-
-  if (fDebug > 1) {
-    Info("Digit2Raw","LDC header 0 = %d, %d",headerLDC[0],headerLDC[1]);
-  }
+    // Write a dummy data header
+    bHPosition[iDDL] = outputFile[iDDL]->tellp();
+    outputFile[iDDL]->write((char *) (& header),sizeof(header));
+    ntotalbyte[iDDL] = 0;
 
-  // Write the LDC header 1
-  byte_p    = (unsigned char *) headerLDC;
-  header_p  = byte_p;
-  *byte_p++ = kLDCDummyFlag;
-  *byte_p++ = 2;
-  *byte_p++ = ndetLDC1;
-  *byte_p++ = 0;
-  *byte_p++ = 0;
-  *byte_p++ = 0;
-  *byte_p++ = 0;
-  *byte_p++ = 0;
-  outputFile2->write(header_p,kLDCHeaderLength);
-  ntotalbyte[1] += kLDCHeaderLength;
-
-  if (fDebug > 1) {
-    Info("Digit2Raw","LDC header 1 = %d, %d",headerLDC[0],headerLDC[1]);
   }
 
   // Loop through all detectors
   for (Int_t det = 0; det < AliTRDgeometry::Ndet(); det++) {
 
-    Int_t cham      = geo->GetChamber(det);
-    Int_t plan      = geo->GetPlane(det);
-    Int_t sect      = geo->GetSector(det);
-    Int_t rowMax    = par->GetRowMax(plan,cham,sect);
-    Int_t colMax    = par->GetColMax(plan);
-    Int_t timeMax   = par->GetTimeMax();
-    Int_t bufferMax = rowMax*colMax*timeMax;
-    int  *buffer    = new int[bufferMax];
-
-    npads  = 0;
-    nbyte  = 0;
-    byte_p = (unsigned char *) buffer;
-
-    // Determine the LDC (resp. output file)
-    Int_t ldc;
-    if (sect < 9) {
-      outputFile = outputFile1;
-      ldc = 0;
-    }
-    else {
-      outputFile = outputFile2;
-      ldc = 1;
-    }
+    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 = fDigitsManager->GetDigits(det);
+    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++) {
@@ -261,7 +252,7 @@ Bool_t AliTRDrawData::Digit2Raw(const Char_t *name1, const Char_t *name2)
 
        // Check whether data exists for this pad
         Bool_t dataflag = kFALSE;
-        for (Int_t time = 0; time < timeMax; time++) {
+        for (Int_t time = 0; time < timeTotal; time++) {
           Int_t data = digits->GetDataUnchecked(row,col,time);
           if (data) {
             dataflag = kTRUE;
@@ -274,37 +265,37 @@ Bool_t AliTRDrawData::Digit2Raw(const Char_t *name1, const Char_t *name2)
           npads++;
 
          // The pad row number
-          *byte_p++ = row + 1;
+          *bytePtr++ = row + 1;
          // The pad column number
-          *byte_p++ = col + 1;
+          *bytePtr++ = col + 1;
           nbyte += 2;
 
           Int_t nzero = 0;
-          for (Int_t time = 0; time < timeMax; time++) {
+          for (Int_t time = 0; time < timeTotal; time++) {
 
             Int_t data = digits->GetDataUnchecked(row,col,time);
 
             if (!data) {
               nzero++;
               if ((nzero ==       256) || 
-                  (time  == timeMax-1)) {
-                *byte_p++ = 0;
-                *byte_p++ = nzero-1;
+                  (time  == timeTotal-1)) {
+                *bytePtr++ = 0;
+                *bytePtr++ = nzero-1;
                 nbyte += 2;
                 nzero  = 0;
              }
            }
             else {
               if (nzero) {
-                *byte_p++ = 0;
-                *byte_p++ = nzero-1;
+                *bytePtr++ = 0;
+                *bytePtr++ = nzero-1;
                 nbyte += 2;
                 nzero  = 0;
              }
               // High byte (MSB always set)
-              *byte_p++ = ((data >> 8) | 128);
+              *bytePtr++ = ((data >> 8) | 128);
               // Low byte
-              *byte_p++ = (data & 0xff);
+              *bytePtr++ = (data & 0xff);
               nbyte += 2;
            }
 
@@ -318,236 +309,392 @@ Bool_t AliTRDrawData::Digit2Raw(const Char_t *name1, const Char_t *name2)
 
     // Fill the end of the buffer with zeros
     while (nbyte % 4) {  
-      *byte_p++ = 0;
+      *bytePtr++ = 0;
       nbyte++;
     }
 
-    if (fDebug > 1) {
-      Info("Digit2Raw","LDC = %d, det = %d, nbyte = %d (%d)",ldc,det,nbyte,bufferMax);
-    }
+    AliDebug(1,Form("det = %d, nbyte = %d (%d)",det,nbyte,bufferMax));
 
     // Write the subevent header
-    byte_p    = (unsigned char *) headerSubevent;
-    header_p  = byte_p;
-    *byte_p++ = kSubeventDummyFlag;
-    *byte_p++ = (det   & 0xff);
-    *byte_p++ = (det   >> 8);
-    *byte_p++ = (nbyte & 0xff);
-    *byte_p++ = (nbyte >> 8);
-    *byte_p++ = (npads & 0xff);
-    *byte_p++ = (npads >> 8);
-    *byte_p++ = 0;
-    outputFile->write(header_p,kSubeventHeaderLength);
+    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);
 
     // Write the buffer to the file
-    byte_p = (unsigned char *) buffer;
-    outputFile->write(byte_p,nbyte);
+    bytePtr = (unsigned char *) buffer;
+    outputFile[iDDL]->write((char *) bytePtr,nbyte);
 
-    ntotalbyte[ldc] += nbyte + kSubeventHeaderLength;
+    ntotalbyte[iDDL] += nbyte + kSubeventHeaderLength;
 
     delete buffer;
 
   }
 
-  if (fDebug) {
-    Info("Digit2Raw","Total size: LDC0 = %d, LDC1 = %d",ntotalbyte[0],ntotalbyte[1]);
-  }
+  // Update the data headers and close the output files
+  for (Int_t iDDL = 0; iDDL < fNumberOfDDLs; iDDL++) {
 
-  outputFile1->close();
-  outputFile2->close();
+    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));
 
-  delete geo;
-  delete par;
-  delete outputFile1;
-  delete outputFile2;
+    outputFile[iDDL]->close();
+    delete outputFile[iDDL];
 
-  return kTRUE;
+  }
+
+  delete [] outputFile;
+  delete [] bHPosition;
+  delete [] ntotalbyte;
 
+  return kTRUE;
 }
 
 //_____________________________________________________________________________
-Bool_t AliTRDrawData::Raw2Digit(const Char_t *name1, const Char_t *name2)
+Bool_t AliTRDrawData::Digits2RawV1(AliTRDdigitsManager *digitsManager)
 {
+  //
+  // Raw data simulator version 1.
+  // This version simulate only raw data with ADC data and not with tracklet.
+  // This is close to the SM-I commissiong data format in Oct.2006.
+  //
 
-  const Int_t  kLDCHeaderLength      = 8;
-  const Int_t  kSubeventHeaderLength = 8;
+  // (timebin/3)*nADC*nMCM*nROB + header + tracklet(max 20)
+  const Int_t kMaxHcWords = (60/3)*21*16*4 + 100 + 20;
 
-  const Int_t  kNldc = 2;
-  const Char_t *name = 0;
+  // Buffer to temporary store half chamber data
+  UInt_t     *hc_buffer   = new UInt_t[kMaxHcWords];
 
-  int headerLDC[2];
-  int headerSubevent[2];
+  // sect is same as iDDL, so I use only sect here.
+  for (Int_t sect = 0; sect < fGeo->Nsect(); sect++) { 
 
-  Int_t             npads     = 0;
-  Int_t             nbyte     = 0;
-  unsigned char    *byte_p;
-  ifstream         *inputFile = 0;
-  AliTRDdataArrayI *digits    = 0;
+    char name[1024];
+    sprintf(name,"TRD_%d.ddl",sect + AliTRDRawStream::kDDLOffset);
 
-  AliTRDgeometryFull *geo = new AliTRDgeometryFull();
-  AliTRDparameter    *par = new AliTRDparameter("TRDparameter"
-                                               ,"TRD parameter class");
+#ifndef __DECCXX
+    ofstream *of = new ofstream(name, ios::binary);
+#else
+    ofstream *of = new ofstream(name);
+#endif
 
-  // Create the digits manager
-  if (fDigitsManager) {
-    delete fDigitsManager;
-  }
-  fDigitsManager = new AliTRDdigitsManager();
-  fDigitsManager->SetDebug(fDebug);
-  fDigitsManager->CreateArrays();
+    // Write a dummy data header
+    AliRawDataHeader  header;  // the event header
+    UInt_t hpos = of->tellp();
+    of->write((char *) (& header), sizeof(header));
 
-  for (Int_t ldc = 0; ldc < kNldc; ldc++) {
+    // Reset payload byte size (payload does not include header).
+    Int_t npayloadbyte = 0;
 
-    if      (ldc == 0) {
-      name = name1;
-    }
-    else if (ldc == 1) {
-      name = name2;
-    }
-    if (fDebug) {
-      Info("Raw2Digit","Open the LDC input file %s",name);
-    }
-    inputFile = new ifstream(name, ios::in | ios::binary);
-
-    // Read the LDC header
-    byte_p = (unsigned char *) headerLDC;
-    inputFile->read(byte_p,kLDCHeaderLength);
-
-    if (fDebug > 1) {
-      Info("Raw2Digit","LDC header no. %d:",ldc);
-      Info("Raw2Digit","\tflag   = %d",*byte_p++);
-      Info("Raw2Digit","\tldc no = %d",*byte_p++);
-      Info("Raw2Digit","\tndet   = %d",*byte_p++);
-      Info("Raw2Digit","\tempty  = %d",*byte_p++);
-      Info("Raw2Digit","\tempty  = %d",*byte_p++);
-      Info("Raw2Digit","\tempty  = %d",*byte_p++);
-      Info("Raw2Digit","\tempty  = %d",*byte_p++);
-      Info("Raw2Digit","\tempty  = %d",*byte_p++);
+    // GTU common data header (5x4 bytes shows link mask)
+    for( Int_t cham = 0; cham < fGeo->Ncham(); cham++ ) {
+      UInt_t GtuCdh;
+      GtuCdh = 0x00000FFF;    // Assume all ORI links (12 per stack) are always up
+      of->write((char *) (& GtuCdh), sizeof(GtuCdh));
+      npayloadbyte += 4;
     }
 
-    // Loop through the subevents
-    byte_p = (unsigned char *) headerSubevent;
-    while (inputFile->read(byte_p,kSubeventHeaderLength)) {
-
-      Int_t flag   = *byte_p++;
-      Int_t detl   = *byte_p++;
-      Int_t deth   = *byte_p++;
-      Int_t det    = detl   + (deth   << 8);
-      Int_t nbytel = *byte_p++;
-      Int_t nbyteh = *byte_p++;
-            nbyte  = nbytel + (nbyteh << 8);
-      Int_t npadsl = *byte_p++;
-      Int_t npadsh = *byte_p++;
-            npads  = npadsl + (npadsh << 8);
-      if (fDebug > 2) {
-        Info("Raw2Digit","Subevent header:");
-        Info("Raw2Digit","\tflag  = %d",flag);
-        Info("Raw2Digit","\tdet   = %d",det);
-        Info("Raw2Digit","\tnbyte = %d",nbyte);
-        Info("Raw2Digit","\tnpads = %d",npads);
-        Info("Raw2Digit","\tempty = %d",*byte_p++);
-      }      
+    // Prepare chamber data
+    for( Int_t cham = 0; cham < fGeo->Ncham(); cham++) {
+      for( Int_t plan = 0; plan < fGeo->Nplan(); plan++) {
 
-      // 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    = par->GetRowMax(plan,cham,sect);
-      Int_t colMax    = par->GetColMax(plan);
-      Int_t timeMax   = par->GetTimeMax();
-      Int_t bufferMax = rowMax*colMax*timeMax;
-      int   *buffer   = new int[bufferMax];
-      byte_p          = (unsigned char *) buffer;      
-      memset(buffer,0,bufferMax*sizeof(int));
+        Int_t iDet = fGeo->GetDetector(plan,cham,sect);
+
+        // Get the digits array
+        AliTRDdataArrayI *digits = digitsManager->GetDigits(iDet);
+        digits->Expand();
+
+        Int_t hcwords;
+
+        // Process A side of the chamber
+        hcwords = ProduceHcDataV1(digits,0,iDet,hc_buffer,kMaxHcWords);
+        of->write((char *) hc_buffer, hcwords*4);
+        npayloadbyte += hcwords*4;
+
+        // Process B side of the chamber
+        hcwords = ProduceHcDataV1(digits,1,iDet,hc_buffer,kMaxHcWords);
+        of->write((char *) hc_buffer, hcwords*4);
+        npayloadbyte += hcwords*4;
 
-      // Add a container for the digits of this detector
-      digits = fDigitsManager->GetDigits(det);
-      // Allocate memory space for the digits buffer
-      if (digits->GetNtime() == 0) {
-        digits->Allocate(rowMax,colMax,timeMax);
       }
+    }
 
-      // Read the data   
-      inputFile->read(byte_p,nbyte);
+    // 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 time;
-      Int_t nzero;
-      Int_t data;
-      Int_t low;
-      Int_t high;
-      Int_t signal;
+  }
 
-      // Decompress the data
-      while (nbyte > 0) {
+  delete hc_buffer;
+  return kTRUE;
 
-        // The pad row number
-        Int_t row = (*byte_p++) - 1;
-        // The pad column number
-        Int_t col = (*byte_p++) - 1;
-        nbyte -= 2;
+}
 
-        time = nzero = 0;
+//_____________________________________________________________________________
+Int_t AliTRDrawData::ProduceHcDataV1(AliTRDdataArrayI *digits, Int_t side
+                                   , Int_t det, UInt_t *buf, Int_t maxSize)
+{
+  //
+  // Produce half chamber data (= an ORI data) for the given chamber (det) and side (side)
+  // where
+  //   side=0 means A side with ROB positions 0, 2, 4, 6.
+  //   side=1 means B side with ROB positions 1, 3, 5, 7.
+  //
+  // Chamber type (C0 orC1) is determined by "det" automatically.
+  // Appropriate size of buffer (*buf) must be prepared prior to calling this function.
+  // Pointer to the buffer and its size must be given to "buf" and "maxSize".
+  // Return value is the number of valid data filled in the buffer in unit of 32 bits
+  // UInt_t words.
+  // If buffer size if too small, the data is truncated with the buffer size however
+  // the function will finish without crash (this behaviour is similar to the MCM).
+  //
 
-        while ((time  < timeMax) &&
-               (nbyte >       0)) {
+  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  nMcm = 16;                      // Number of MCMs per ROB (fixed)
+  const Int_t nTBin = fCalibration->GetNumberOfTimeBins();
+  Int_t         dcs = det+100;                 // DCS Serial (in simulation, it's always 
+                                               // chamber ID+1000 without any reason
+  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
+
+  // 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).\n"
+                 ,nRow,nCol));
+    return 0;
+  }
 
-          data = *byte_p++;
-          nbyte--;
+  AliDebug(1,Form("Producing raw data for sect=%d plan=%d cham=%d side=%d"
+                 ,sect,plan,cham,side));
 
-          if (data) {
-            if (!nzero) {
-              // signal for given timebim
-              low    = *byte_p++;
-              high   = data & 127;
-              signal = low + (high << 8);
-              if ((row <       0) || (col <       0) || (time <        0) ||
-                  (row >= rowMax) || (col >= colMax) || (time >= timeMax)) {
-                Error("Raw2Digit"
-                     ,"row=%d(%d) col=%d(%d) time=%d(%d)"
-                    ,row,rowMax,col,colMax,time,timeMax);
-             }
-              else {
-                digits->SetDataUnchecked(row,col,time,signal);
-             }
-              nbyte--;
-              time++;
+  // Tracklet should be processed here but not implemented yet
+
+  // Write end of tracklet marker
+  if (nw < maxSize) {
+    buf[nw++] = 0xAAAAAAAA;
+  } 
+  else {
+    of++;
+  }
+
+  // Half Chamber header
+  // Now it is the same version as used in SM-I commissioning.
+  // It is: (dcs << 20) | (sect << 15) | (plan << 12) | (cham << 9) | (side << 8)
+  x = (dcs << 20) | (sect << 15) | (plan << 12) | (cham << 9) | (side << 8);
+  if (nw < maxSize) {
+    buf[nw++] = x; 
+  }
+  else {
+    of++;
+  }
+
+  // Scan for ROB and MCM
+  for (Int_t iRobRow = 0; iRobRow < (kCtype + 3); iRobRow++ ) {
+    Int_t iRob = iRobRow * 2 + side;
+    for (Int_t iMcm = 0; iMcm < nMcm; iMcm++ ) {
+      Int_t padrow = iRobRow * 4 + iMcm / 4;
+
+      // MCM header
+      x = ((iRob * nMcm + iMcm) << 24) | ((iEv % 0x100000) << 4) | 0xC;
+      if (nw < maxSize) {
+        buf[nw++] = x; 
+      }
+      else {
+        of++;
+      }
+
+      // ADC data
+      for (Int_t iAdc = 0; iAdc < 21; iAdc++ ) {
+        Int_t padcol = (17-(iAdc-2)) + (iMcm % 4)*18 + side*72;
+        UInt_t aa = 2;
+        UInt_t *a = new UInt_t[nTBin+2];
+        // 3 timebins are packed into one 32 bits word
+        for (Int_t iT = 0; iT < nTBin; iT+=3) { 
+          if ((padcol >=    0) && 
+              (padcol <  nCol)) {
+            if ((iT    ) < nTBin ) {
+              a[iT  ] = digits->GetDataUnchecked(padrow,padcol,iT);
            }
             else {
-              time += data + 1;
-              nzero = 0;
+              a[iT  ] = 0;
            }
-         }
-          else {
-            if (!nzero) {
-              nzero = 1;
+            if ((iT + 1) < nTBin ) {
+              a[iT+1] = digits->GetDataUnchecked(padrow,padcol,iT + 1);
+            }
+            else {
+              a[iT+1] = 0;
+           }
+            if ((iT + 2) < nTBin ) {
+              a[iT+2] = digits->GetDataUnchecked(padrow,padcol,iT + 2); 
            }
             else {
-              time++;
-              nzero = 0;
+              a[iT+2] = 0;
            }
+          } 
+          else {
+            a[iT] = a[iT+1] = a[iT+2] = 0; // This happenes at the edge of chamber
+          }
+          x = (a[iT+2] << 22) | (a[iT+1] << 12) | (a[iT] << 2) | aa;
+          if (nw < maxSize) {
+            buf[nw++] = x; 
          }
-
+          else {
+            of++;
+         }
+          if (aa == 2) {
+            aa = 3; 
+          }
+          else {
+            aa = 2;  // aa alternatively changes between 10b and 11b
+         }
+        }
+        // Diagnostics
+        Float_t avg = 0;
+        Float_t rms = 0;
+        for (Int_t iT = 0; iT < nTBin; iT++) {
+          avg += (Float_t) (a[iT]);
        }
-
+        avg /= (Float_t) nTBin;
+        for (Int_t iT = 0; iT < nTBin; iT++) {
+          rms += ((Float_t) (a[iT]) - avg) * ((Float_t) (a[iT]) - avg);
+       }
+        rms = TMath::Sqrt(rms / (Float_t) nTBin);
+        if (rms > 1.7) {
+          AliDebug(1,Form("Large RMS (>1.7)  (ROB,MCM,ADC)=(%02d,%02d,%02d), avg=%03.1f, rms=%03.1f\n"
+                        ,iRob,iMcm,iAdc,avg,rms));
+       }
+        delete a;
       }
+    }
+  }
+
+  // Write end of raw data marker
+  if (nw < maxSize) {
+    buf[nw++] = 0x00000000; 
+  }
+  else {
+    of++;
+  }
+  if (of != 0) {
+    AliWarning("Buffer overflow. Data is truncated. Please increase buffer size and recompile.");
+  }
+
+  return nw;
+
+}
+
+//_____________________________________________________________________________
+AliTRDdigitsManager* AliTRDrawData::Raw2Digits(AliRawReader *rawReader)
+{
+  //
+  // Read the raw data digits and put them into the returned digits manager
+  //
+
+  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\n");
+    return 0;
+  }
+    
+  AliTRDcalibDB* calibration = AliTRDcalibDB::Instance();
+  if (!calibration) {
+    AliError("Could not get calibration object\n");
+    return 0;
+  }
+
+  // Create the digits manager
+  AliTRDdigitsManager* digitsManager = new AliTRDdigitsManager();
+  digitsManager->CreateArrays();
+
+  AliTRDRawStream input(rawReader);
+
+  // Loop through the digits
+  while (input.Next()) {
 
-      digits->Compress(1,0);
+    Int_t det    = input.GetDetector();
+    Int_t npads  = input.GetNPads();
 
-      delete buffer;
+    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();
 
-      byte_p = (unsigned char *) headerSubevent;
+      // 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);
+      }
 
     } 
 
-    inputFile->close();
-    delete inputFile;
-    inputFile = 0;
+    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);
 
   }
 
+  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;
-  delete par;
 
-  return kTRUE;
+  return digitsManager;
 
 }