]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - MUON/AliMUONRawWriter.cxx
Moving the alignment-related static methods from AliAlignObj to the new geometry...
[u/mrichter/AliRoot.git] / MUON / AliMUONRawWriter.cxx
index 3c86898f98c5764ac3b2789d3d2c39e4f9a9e80b..743d5cb4eb1f9c2df0807a75d02bc18afd24757f 100644 (file)
 
 /* $Id$ */
 
-////////////////////////////////////
-//
-// MUON Raw Data generaton in ALICE-MUON
-// This class version 3 (further details could be found in Alice-note)
-//
-// Implemented non-constant buspatch numbers for tracking
-// with correct DDL id (first guess)
-// (Ch. Finck, dec 2005)
-//
-// Digits2Raw:
-// Generates raw data for MUON tracker and finally for trigger
-// Using real mapping (inverse) for tracker
-// For trigger there is no mapping (mapping could be found in AliMUONTriggerCircuit)
-// Ch. Finck, July 04
-// Use memcpy instead of assignment elt by elt
-// Introducing variable DSP numbers, real manu numbers per buspatch for st12
-// Implemented scaler event for Trigger
-// Ch. Finck, Jan. 06
-// Using bus itr in DDL instead of simple incrementation
-// treat correctly the DDL & buspatch for station 3.
-// Using informations from AliMUONTriggerCrateStore for 
-// empty slots and non-notified cards in trigger crates.
-// Ch. Finck, August 06.
-// 
-////////////////////////////////////
+/// \class AliMUONRawWriter
+/// MUON Raw Data generaton in ALICE-MUON
+/// Raw data structure could be found in Alice-note.
+///
+/// Implemented non-constant buspatch numbers for tracking
+/// with correct DDL id (first guess)
+/// (Ch. Finck, dec 2005)
+///
+/// Digits2Raw:
+/// Generates raw data for MUON tracker and finally for trigger
+/// Using real mapping (inverse) for tracker
+/// For trigger there is no mapping (mapping could be found in AliMUONTriggerCircuit)
+/// Ch. Finck, July 04
+/// Use memcpy instead of assignment elt by elt
+/// Introducing variable DSP numbers, real manu numbers per buspatch for st12
+/// Implemented scaler event for Trigger
+/// Ch. Finck, Jan. 06
+/// Using bus itr in DDL instead of simple incrementation
+/// treat correctly the DDL & buspatch for station 3.
+/// Using informations from AliMUONTriggerCrateStore for 
+/// empty slots and non-notified cards in trigger crates.
+/// Ch. Finck, August 06.
+/// Using AliMpDDLStore::GetBusPatchId.
+///
+/// \author Ch. Finck, Feb. 07.
+
 
 #include "AliMUONRawWriter.h"
 
-#include "AliBitPacking.h" 
-#include "AliRawReader.h"
-#include "AliDAQ.h"
-#include "AliLog.h"
-#include "AliMUON.h"
+#include "AliMUONBlockHeader.h"
+#include "AliMUONBusStruct.h"
 #include "AliMUONConstants.h"
-
 #include "AliMUONDarcHeader.h"
-#include "AliMUONRegHeader.h"
-#include "AliMUONLocalStruct.h"
-#include "AliMUONDspHeader.h"
-#include "AliMUONBlockHeader.h"
-
 #include "AliMUONData.h"
 #include "AliMUONDigit.h"
+#include "AliMUONDspHeader.h"
 #include "AliMUONGlobalTrigger.h"
+#include "AliMUONLocalStruct.h"
 #include "AliMUONLocalTrigger.h"
-
-#include "AliMpBusPatch.h"
-#include "AliMUONTriggerCrateStore.h"
-#include "AliMUONTriggerCrate.h"
 #include "AliMUONLocalTriggerBoard.h"
+#include "AliMUONRegionalTrigger.h"
+#include "AliMUONRegHeader.h"
+#include "AliMUONTriggerCrate.h"
+#include "AliMUONTriggerCrateStore.h"
 
+#include "AliMpDDLStore.h"
+#include "AliMpDDL.h"
+#include "AliMpDetElement.h"
 #include "AliMpDEManager.h"
-#include "AliMpPad.h"
+#include "AliMpExMap.h"
+#include "AliMpConstants.h"
 #include "AliMpPlaneType.h"
-#include "AliMpSegFactory.h"
+#include "AliMpSegmentation.h"
 #include "AliMpStationType.h"
 #include "AliMpVSegmentation.h"
 
-#include "TClonesArray.h"
+#include "AliRawReader.h"
+#include "AliBitPacking.h" 
+#include "AliDAQ.h"
+#include "AliLog.h"
+
+#include "TList.h"
 #include "TObjArray.h"
+#include "TStopwatch.h"
+#include <Riostream.h>
 
+/// \cond CLASSIMP
 ClassImp(AliMUONRawWriter) // Class implementation in ROOT context
+/// \endcond
 
-Int_t AliMUONRawWriter::fgManuPerBusSwp1B[12]  = {1, 27, 53, 79, 105, 131, 157, 183, 201, 214, 224, 232};
-Int_t AliMUONRawWriter::fgManuPerBusSwp1NB[12] = {1, 27, 53, 79, 105, 131, 157, 183, 201, 214, 225, 233};
-
-Int_t AliMUONRawWriter::fgManuPerBusSwp2B[12]  = {1, 27, 53, 79, 105, 131, 157, 183, 201, 214, 226, 246};
-Int_t AliMUONRawWriter::fgManuPerBusSwp2NB[12] = {1, 27, 53, 79, 105, 131, 157, 183, 201, 214, 227, 245};
-
+namespace 
+{
+  enum ETimer { kWriteTracker, kWriteTrigger, kDigitLoop, kGetBusPatch, kTest, kLast };
+}
 
 //__________________________________________________________________________
 AliMUONRawWriter::AliMUONRawWriter(AliMUONData* data)
   : TObject(),
     fMUONData(data),
-    fBusArray(new TClonesArray("AliMUONBusStruct",1000)),
     fBlockHeader(new AliMUONBlockHeader()),
     fDspHeader(new AliMUONDspHeader()),
-    fBusStruct(new AliMUONBusStruct()),
     fDarcHeader(new AliMUONDarcHeader()),
     fRegHeader(new AliMUONRegHeader()),
     fLocalStruct(new AliMUONLocalStruct()),
-    fBusPatchManager(new AliMpBusPatch()),
+    fDDLStore(AliMpDDLStore::Instance()),
     fCrateManager(new AliMUONTriggerCrateStore()),
     fScalerEvent(kFALSE),
     fHeader(),
-    fTrackerTimer(),
-    fTriggerTimer(),
-    fMappingTimer(),
-    fSegFactory(new AliMpSegFactory())
+    fTimers(new TStopwatch[kLast])
 
 {
-  //
-  // Standard Constructor
-  //
+  /// Standard Constructor
+
   AliDebug(1,"Standard ctor");
   fFile[0] = fFile[1] = 0x0;  
   fFile[2] = fFile[3] = 0x0;  
 
-  // initialize array
-  fBusArray->SetOwner(kTRUE);
-
   // setting data key to default value (only for writting)
   fBlockHeader->SetDataKey(fBlockHeader->GetDefaultDataKey());
   fDspHeader->SetDataKey(fDspHeader->GetDefaultDataKey());
-  fBusStruct->SetDataKey(fBusStruct->GetDefaultDataKey());
-
-  // bus patch managers
-  fBusPatchManager->ReadBusPatchFile();
 
   // Crate manager
   fCrateManager->ReadFromFile();
 
   // timers
-  fTrackerTimer.Start(kTRUE); fTrackerTimer.Stop();
-  fTriggerTimer.Start(kTRUE); fTriggerTimer.Stop();
-  fMappingTimer.Start(kTRUE); fMappingTimer.Stop();
+  for ( Int_t i = 0; i < kLast; ++i )
+  {
+    fTimers[i].Start(kTRUE); 
+    fTimers[i].Stop();
+  }
   
 }
 
@@ -138,71 +132,54 @@ AliMUONRawWriter::AliMUONRawWriter(AliMUONData* data)
 AliMUONRawWriter::AliMUONRawWriter()
   : TObject(),
     fMUONData(0),
-    fBusArray(0),
     fBlockHeader(0),
     fDspHeader(0),
-    fBusStruct(0),
     fDarcHeader(0),
     fRegHeader(0),
     fLocalStruct(0),
-    fBusPatchManager(0),
+    fDDLStore(0),
     fCrateManager(0x0),
     fScalerEvent(kFALSE),
     fHeader(),
-    fTrackerTimer(),
-    fTriggerTimer(),
-    fMappingTimer(),
-    fSegFactory(0x0)
+    fTimers(0)
 {
-  //
-  // Default Constructor
-  //
+  /// Default Constructor
+
   AliDebug(1,"Default ctor");   
   fFile[0] = fFile[1] = 0x0;  
   fFile[2] = fFile[3] = 0x0;  
 
-  fTrackerTimer.Start(kTRUE); fTrackerTimer.Stop();
-  fTriggerTimer.Start(kTRUE); fTriggerTimer.Stop();
-  fMappingTimer.Start(kTRUE); fMappingTimer.Stop();
 }
 
 //__________________________________________________________________________
 AliMUONRawWriter::~AliMUONRawWriter(void)
 {
-  //
-  // Destructor
-  //
+  /// Destructor
+
   AliDebug(1,"dtor");
   
-  delete fBusArray;
-  
   delete fBlockHeader;
   delete fDspHeader;
-  delete fBusStruct;
   delete fDarcHeader;
   delete fRegHeader;
   delete fLocalStruct;
 
-  delete fBusPatchManager;
   delete fCrateManager;
 
-  delete fSegFactory;
+  for ( Int_t i = 0; i < kLast; ++i )
+  {
+    AliDebug(1, Form("Execution time (timer %d) : R:%7.2fs C:%7.2fs",i,
+                 fTimers[i].RealTime(),fTimers[i].CpuTime()));
+  }
   
-  AliInfo(Form("Execution time for MUON tracker : R:%.2fs C:%.2fs",
-               fTrackerTimer.RealTime(),fTrackerTimer.CpuTime()));
-  AliInfo(Form("   Execution time for MUON tracker (mapping calls part) "
-               ": R:%.2fs C:%.2fs",
-               fMappingTimer.RealTime(),fMappingTimer.CpuTime()));
-  AliInfo(Form("Execution time for MUON trigger : R:%.2fs C:%.2fs",
-               fTriggerTimer.RealTime(),fTriggerTimer.CpuTime()));
+  delete[] fTimers;
 }
 
 //____________________________________________________________________
 Int_t AliMUONRawWriter::Digits2Raw()
 {
-  //
-  // convert digits of the current event to raw data
-  //
+  /// convert digits of the current event to raw data
+
   Int_t idDDL;
   Char_t name[255];
 
@@ -216,9 +193,11 @@ Int_t AliMUONRawWriter::Digits2Raw()
   // This will get both tracker and trigger digits.
   fMUONData->GetDigits();
   
-  // tracking chambers
+//  CheckDigits();
 
-  for (Int_t iSt = 0; iSt < AliMUONConstants::NTrackingCh()/2; iSt++) {
+  // tracking chambers
+  
+  for (Int_t iSt = 0; iSt < AliMUONConstants::NTrackingCh()/2; ++iSt) {
 
     // open files for one station
     // cos station 3, 1/4 of DE's from 2 chambers has same DDL number 
@@ -248,6 +227,8 @@ Int_t AliMUONRawWriter::Digits2Raw()
      
   }
  
+  AliDebug(1,"Tracker written");
+  
   // trigger chambers
  
   // open files
@@ -259,43 +240,36 @@ Int_t AliMUONRawWriter::Digits2Raw()
   strcpy(name,AliDAQ::DdlFileName("MUONTRG",idDDL));
   fFile[1] = fopen(name,"w");
 
-  WriteTriggerDDL();
+   WriteTriggerDDL();
   
   // reset and close
   fclose(fFile[0]);
   fclose(fFile[1]);
 
+  AliDebug(1,"Trigger written");
+
   fMUONData->ResetDigits();
   fMUONData->ResetTrigger();  
   fMUONData->GetLoader()->UnloadDigits();
 
+  AliDebug(1,"muondata reset");
+  
   return kTRUE;
 }
 
 //____________________________________________________________________
 Int_t AliMUONRawWriter::WriteTrackerDDL(Int_t iSt)
 {
-  // writing DDL for tracker
-  // used inverse mapping
-  //
-  fTrackerTimer.Start(kFALSE);
-  
+  /// writing DDL for tracker
+  /// used inverse mapping
 
+  fTimers[kWriteTracker].Start(kFALSE);
+  
   static const Int_t kMAXADC = (1<<12)-1; // We code the charge on a 12 bits ADC.
 
   // resets
   TClonesArray* muonDigits = 0;
 
-  fBusArray->Delete();
-
-
-  //
-  TArrayI nbInBus;
-
-  nbInBus.Set(5000);
-
-  nbInBus.Reset();
-
   // DDL header
   Int_t headerSize = sizeof(fHeader)/4;
 
@@ -326,120 +300,86 @@ Int_t AliMUONRawWriter::WriteTrackerDDL(Int_t iSt)
   Int_t indexDsp;
   Int_t indexBlk;
 
-  // digits
-  Int_t nEntries = 0;
-  Int_t* buffer = 0;
-  Int_t padX;
-  Int_t padY;
-  Int_t cathode = 0;
-  Int_t detElemId;
+  // buffer size (max'ed out)
+  // (((43 manus max per bus patch *64 channels + 4 bus patch words) * 5 bus patch 
+  //   + 10 dsp words)*5 dsps + 8 block words)*2 blocks 
+  static const Int_t kBufferSize = (((43*64 + 4)*5 + 10)*5 + 8)*2;
+  
   Int_t nDigits;
 
-  const AliMUONDigit* digit;
-
-  for (Int_t iCh = iSt*2; iCh <= iSt*2 + 1; iCh++) {
+  AliMpExMap busPatchMap(kTRUE);
+  
+  fTimers[kDigitLoop].Start(kFALSE);
+  
+  for (Int_t iCh = iSt*2; iCh <= iSt*2 + 1; ++iCh) {
 
     muonDigits = fMUONData->Digits(iCh);
-
+    
     nDigits = muonDigits->GetEntriesFast();
-    AliDebug(3,Form("ndigits = %d\n",nDigits));
+    
     // loop over digit
-    for (Int_t idig = 0; idig < nDigits; idig++) {
-
-      digit = (AliMUONDigit*) muonDigits->UncheckedAt(idig);
-
-      padX = digit->PadX();
-      padY = digit->PadY();
+    for (Int_t idig = 0; idig < nDigits; ++idig) {
+      
+      AliMUONDigit* digit = static_cast<AliMUONDigit*>(muonDigits->UncheckedAt(idig));
+      
       charge = digit->ADC();
       if ( charge > kMAXADC )
-       {
-         // This is most probably an error in the digitizer (which should insure
-         // the adc is below kMAXADC), so make it a (non-fatal) error indeed.
-         AliError(Form("adc value %d above %x. Setting to %x",
-                       charge,kMAXADC,kMAXADC));
-         charge = kMAXADC;
-       }
-      cathode = digit->Cathode();
-      detElemId = digit->DetElemId();
-
+      {
+        // This is most probably an error in the digitizer (which should insure
+        // the adc is below kMAXADC), so make it a (non-fatal) error indeed.
+        AliError(Form("adc value %d above %x for ch %d . Setting to %x. Digit is:",iCh,
+                      charge,kMAXADC,kMAXADC));
+        StdoutToAliError(digit->Print());
+        charge = kMAXADC;
+      }
+      
       // inverse mapping
+      fTimers[kGetBusPatch].Start(kFALSE);
       busPatchId = GetBusPatch(*digit);
+      fTimers[kGetBusPatch].Stop();
       if (busPatchId<0) continue;
-
+      
       if ( digit->ManuId() > 0x7FF || digit->ManuId() < 0 ||
-          digit->ManuChannel() > 0x3F || digit->ManuChannel() < 0 )
-       {
-         StdoutToAliError(digit->Print(););
-         AliFatal("ManuId,ManuChannel are invalid for the digit above.");
-       }
-    
+           digit->ManuChannel() > 0x3F || digit->ManuChannel() < 0 )
+      {
+        StdoutToAliError(digit->Print(););
+        AliFatal("ManuId,ManuChannel are invalid for the digit above.");
+      }
+      
       manuId = ( digit->ManuId() & 0x7FF ); // 11 bits
       channelId = ( digit->ManuChannel() & 0x3F ); // 6 bits
-
-      AliDebug(3,Form("input  IdDE %d busPatchId %d PadX %d PadY %d iCath %d \n", 
-                     detElemId, busPatchId, padX, padY, cathode));
-
-      AliDebug(3,Form("busPatchId %d, manuId %d channelId %d\n", busPatchId, manuId, 
-                     channelId ));
-
+            
       //packing word
       word = 0;
       AliBitPacking::PackWord((UInt_t)manuId,word,18,28);
       AliBitPacking::PackWord((UInt_t)channelId,word,12,17);
       AliBitPacking::PackWord((UInt_t)charge,word,0,11);
-
+      
       // parity word
       parity = word & 0x1;
-      for (Int_t i = 1; i <= 30; i++
-       parity ^=  ((word >> i) & 0x1);
+      for (Int_t i = 1; i <= 30; ++i
+        parity ^=  ((word >> i) & 0x1);
       AliBitPacking::PackWord((UInt_t)parity,word,31,31);
+      
+      AliMUONBusStruct* busStruct = 
+        static_cast<AliMUONBusStruct*>(busPatchMap.GetValue(busPatchId));
+      
+      if (!busStruct)
+      {
+        busStruct = new AliMUONBusStruct;
+        busStruct->SetDataKey(busStruct->GetDefaultDataKey());
+        busStruct->SetBusPatchId(busPatchId);
+        busStruct->SetLength(0);
+        busPatchMap.Add(busPatchId,busStruct);
+      }
 
       // set sub Event
-      fBusStruct->SetLength(0);
-      fBusStruct->AddData(word);
-      fBusStruct->SetBusPatchId(busPatchId);
-       
-      // storing the number of identical buspatches
-      nbInBus[busPatchId]++;
-      AddData(*fBusStruct);
-   
-    }
+      busStruct->AddData(word);
+      
+    } // idig
   } // loop over chamber in station
-
-  // sorting by buspatch
-  fBusArray->Sort();
-
-  // gather datas from same bus patch
-  nEntries = fBusArray->GetEntriesFast();
-
-  for (Int_t i = 0; i < nEntries; i++) {
-    AliMUONBusStruct* temp = (AliMUONBusStruct*)fBusArray->At(i);
-    busPatchId = temp->GetBusPatchId();
-
-    // add bus patch header, length and total length managed by subevent class
-    for (Int_t j = 0; j < nbInBus[busPatchId]-1; j++) {
-      AliMUONBusStruct* temp1 =  (AliMUONBusStruct*)fBusArray->At(++i);
-      temp->AddData(temp1->GetData(0));
-      fBusArray->RemoveAt(i) ;
-    }
-  }
-  fBusArray->Compress();
-
-  if (AliLog::GetGlobalDebugLevel() == 3) {
-    nEntries = fBusArray->GetEntriesFast();
-    for (Int_t i = 0; i < nEntries; i++) {
-      AliMUONBusStruct* temp =  (AliMUONBusStruct*)fBusArray->At(i);
-      printf("busPatchid back %d\n",temp->GetBusPatchId());
-      for (Int_t j = 0; j < temp->GetLength(); j++) {
-       printf("manuId back %d, ",temp->GetManuId(j));
-       printf("channelId back %d, ",temp->GetChannelId(j));
-       printf("charge back %d\n",temp->GetCharge(j));
-      }
-    }
-    printf("\n");
-  }
-  // end of TreeD reading and storing in TClonesArray
+    
+  fTimers[kDigitLoop].Stop();
   
   // getting info for the number of buspatches
   Int_t iBusPatch;
@@ -448,273 +388,185 @@ Int_t AliMUONRawWriter::WriteTrackerDDL(Int_t iSt)
   Int_t iDspMax; //number max of DSP per block
   Int_t iFile = 0;
 
-  Int_t rEntry = -1;
-  AliMUONBusStruct* busStructPtr = 0x0;
+  AliMUONBusStruct* busStructPtr(0x0);
 
   // open DDL files, 4 per station
-  for (Int_t iDDL = iSt*4; iDDL < 4 + iSt*4; iDDL++) {
+  for (Int_t iDDL = iSt*4; iDDL < 4 + iSt*4; ++iDDL) {
 
-    fBusPatchManager->ResetBusItr(iDDL);
-    fBusPatchManager->GetDspInfo(iDDL, iDspMax, iBusPerDSP);
+    AliMpDDL* ddl = fDDLStore->GetDDL(iDDL);
+    iDspMax = ddl->GetMaxDsp();
+    ddl->GetBusPerDsp(iBusPerDSP);
+    Int_t busIter = 0;
 
+    Int_t buffer[kBufferSize];
+    
     totalDDLLength = 0;
 
-    // buffer size
-    // ((43 manus max*64 ch + 4 bus word) * 5 DSPs + 10 DSP word) * 2 blocks + 8 block words = 27588
-    static const Int_t kBufferSize = ((43*64 + 4)*5 + 10)*2 + 8;
-
-    // buffer allocation
-    buffer = new Int_t [kBufferSize];
-
     indexBlk = 0;
     indexDsp = 0;
     index = 0;
 
     // two blocks A and B per DDL
-    for (Int_t iBlock = 0; iBlock < 2; iBlock++) {
-
+    for (Int_t iBlock = 0; iBlock < 2; ++iBlock) {
+      
       // block header
       length = fBlockHeader->GetHeaderLength();
       memcpy(&buffer[index],fBlockHeader->GetHeader(),length*4);
       indexBlk = index;
       index += length; 
-
+      
       // 5 DSP's max per block
-      for (Int_t iDsp = 0; iDsp < iDspMax; iDsp++) {
-
-       // DSP header
-       length = fDspHeader->GetHeaderLength();
-       memcpy(&buffer[index],fDspHeader->GetHeader(),length*4);
-       indexDsp = index;
-       index += length; 
-
-       // 5 buspatches max per DSP
-       for (Int_t i = 0; i < iBusPerDSP[iDsp]; i++) {
-
-         // iteration over bus patch in DDL
-         if ((iBusPatch = fBusPatchManager->NextBusInDDL(iDDL)) == -1) {
-           AliWarning(Form("Error in bus itr in DDL %d\n", iDDL));
-           continue;
-         }
-
-         // 4 DDL's per station, condition needed for station 3
-         iFile = iDDL - iSt*4; // works only if DDL begins at zero (as it should be) !!!
-
-         AliDebug(3,Form("iSt %d iDDL %d iBlock %d iDsp %d busPatchId %d", iSt, iDDL, iBlock, 
-                         iDsp, iBusPatch));
-
-         nEntries = fBusArray->GetEntriesFast();
-         busPatchId = -1;
-
-         // checking buspatch structure not empty
-         for (Int_t iEntry = 0; iEntry < nEntries; iEntry++) { // method "bourrique"...
-           busStructPtr = (AliMUONBusStruct*)fBusArray->At(iEntry);
-           busPatchId = busStructPtr->GetBusPatchId();
-           if (busPatchId == iBusPatch) {
-             rEntry = iEntry;
-             break;
-           }
-           busPatchId = -1;
-           AliDebug(3,Form("busPatchId %d", busStructPtr->GetBusPatchId()));
-         } 
-        
-         // check if buspatchid has digit
-         if (busPatchId != -1) {
-           // add bus patch structure header
-           length = busStructPtr->GetHeaderLength();
-           memcpy(&buffer[index],busStructPtr->GetHeader(),length*4);
-           index += length;
-
-           // add bus patch data
-           length = busStructPtr->GetLength();
-           memcpy(&buffer[index],busStructPtr->GetData(),length*4);
-           index += length;
-
-           if (AliLog::GetGlobalDebugLevel() == 3) {
-             for (Int_t j = 0; j < busStructPtr->GetLength(); j++) {
-               printf("busPatchId %d, manuId %d channelId %d\n", busStructPtr->GetBusPatchId(), 
-                      busStructPtr->GetManuId(j), busStructPtr->GetChannelId(j));
-             }
-           }
-           
-           fBusArray->RemoveAt(rEntry);
-           fBusArray->Compress();
-         } else {
-           // writting anyhow buspatch structure (empty ones)
-           buffer[index++] = busStructPtr->GetDefaultDataKey(); // fill it also for empty data size
-           buffer[index++] = busStructPtr->GetHeaderLength(); // header length
-           buffer[index++] = 0; // raw data length
-           buffer[index++] = iBusPatch; // bus patch
-         }
-       } // bus patch
-
-       // check if totalLength even
-       // set padding word in case
-       // Add one word 0xBEEFFACE at the end of DSP structure
-       totalDspLength  = index - indexDsp;
-       if ((totalDspLength % 2) == 1) { 
-         buffer[indexDsp + fDspHeader->GetHeaderLength() - 2] = 1;
-         buffer[index++] = fDspHeader->GetDefaultPaddingWord();
-         totalDspLength++;
-       }
-
-       dspLength          = totalDspLength - fDspHeader->GetHeaderLength();
-
-       buffer[indexDsp+1] = totalDspLength; // dsp total length
-       buffer[indexDsp+2] = dspLength; // data length  
-          
+      for (Int_t iDsp = 0; iDsp < iDspMax; ++iDsp) {
+        
+        // DSP header
+        length = fDspHeader->GetHeaderLength();
+        memcpy(&buffer[index],fDspHeader->GetHeader(),length*4);
+        indexDsp = index;
+        index += length; 
+        
+        // 5 buspatches max per DSP
+        for (Int_t i = 0; i < iBusPerDSP[iDsp]; i++) {
+          
+          iBusPatch = ddl->GetBusPatchId(busIter++);
+          
+          // iteration over bus patch in DDL
+          if (iBusPatch == -1) {
+            AliWarning(Form("Error in bus itr in DDL %d\n", iDDL));
+            continue;
+          }
+          
+          // 4 DDL's per station, condition needed for station 3
+          iFile = iDDL - iSt*4; // works only if DDL begins at zero (as it should be) !!!
+          
+          busStructPtr = static_cast<AliMUONBusStruct*>(busPatchMap.GetValue(iBusPatch));
+          
+          // check if buspatchid has digit
+          if (busStructPtr) {
+            // add bus patch structure header
+            length = busStructPtr->GetHeaderLength();
+            memcpy(&buffer[index],busStructPtr->GetHeader(),length*4);
+            index += length;
+            
+            // add bus patch data
+            length = busStructPtr->GetLength();
+            memcpy(&buffer[index],busStructPtr->GetData(),length*4);
+            index += length;
+            
+            if (AliLog::GetGlobalDebugLevel() == 3) {
+              for (Int_t j = 0; j < busStructPtr->GetLength(); j++) {
+                printf("busPatchId %d, manuId %d channelId %d\n", busStructPtr->GetBusPatchId(), 
+                       busStructPtr->GetManuId(j), busStructPtr->GetChannelId(j));
+              }
+            }
+          } else {
+            // writting anyhow buspatch structure (empty ones)
+            buffer[index++] = busStructPtr->GetDefaultDataKey(); // fill it also for empty data size
+            buffer[index++] = busStructPtr->GetHeaderLength(); // header length
+            buffer[index++] = 0; // raw data length
+            buffer[index++] = iBusPatch; // bus patch
+          }
+        } // bus patch
+        
+        // check if totalLength even
+        // set padding word in case
+        // Add one word 0xBEEFFACE at the end of DSP structure
+        totalDspLength  = index - indexDsp;
+        if ((totalDspLength % 2) == 1) { 
+          buffer[indexDsp + fDspHeader->GetHeaderLength() - 2] = 1;
+          buffer[index++] = fDspHeader->GetDefaultPaddingWord();
+          totalDspLength++;
+        }
+        
+        dspLength          = totalDspLength - fDspHeader->GetHeaderLength();
+        
+        buffer[indexDsp+1] = totalDspLength; // dsp total length
+        buffer[indexDsp+2] = dspLength; // data length  
+        
       } // dsp
-
+      
       totalBlkLength  = index - indexBlk;
       blkLength       = totalBlkLength - fBlockHeader->GetHeaderLength();
       totalDDLLength += totalBlkLength;
-
+      
       buffer[indexBlk+1] = totalBlkLength; // total block length
       buffer[indexBlk+2] = blkLength;
-
+      
     } // block
     
     //writting onto disk
     // write DDL 1 - 4
-    fHeader.fSize = (totalDDLLength + headerSize) * 4;// total length in bytes
+    // total length in bytes
+    fHeader.fSize = (totalDDLLength + headerSize) * 4;
+      
     fwrite((char*)(&fHeader),headerSize*4,1,fFile[iFile]);
     fwrite(buffer,sizeof(int),index,fFile[iFile]);
-   
-    delete[] buffer;
   }
-
-  fTrackerTimer.Stop();
+  
+  fTimers[kWriteTracker].Stop();
   return kTRUE;
 }
 
 //____________________________________________________________________
-Int_t AliMUONRawWriter::GetBusPatch(const AliMUONDigit& digit)
+Int_t AliMUONRawWriter::GetBusPatch(const AliMUONDigit& digit) const
 {
-  //
-  // Determine the BusPatch this digit belongs to.
-  //
-  fMappingTimer.Start(kFALSE);
-  
-  Int_t* ptr = 0;
-
-  // information from digits
-  Int_t detElemId  = digit.DetElemId();
-
-  AliMpVSegmentation* seg = 
-    fSegFactory->CreateMpSegmentationByElectronics(detElemId, digit.ManuId());
-  
-  AliMpPlaneType plane = seg->PlaneType();
-
-  AliMpStationType stationType = AliMpDEManager::GetStationType(detElemId);
+  /// Determine the BusPatch this digit belongs to.
 
-  if ( stationType == kStation1 || stationType == kStation2 )
-  {
-    if (plane == kBendingPlane) 
-    {
-      ptr = &fgManuPerBusSwp1B[0];
-    }
-    else 
-    {
-      ptr = &fgManuPerBusSwp1NB[0];
-    }
-  }
-  else
-  {
-    if (plane == kBendingPlane)
-    {
-      ptr = &fgManuPerBusSwp2B[0];
-    }
-    else
-    {
-      ptr = &fgManuPerBusSwp2NB[0];
-    }
-  }
-
-  // Getting buspatch id
-  TArrayI* vec = fBusPatchManager->GetBusfromDE(detElemId);
-  Int_t pos = 0;
-
-  Int_t m = ( digit.ManuId() & 0x3FF ); // remove bit 10
-                                //FIXME : how can we remove that condition
-  // on the 10-th bit ? All the rest need not any knowledge about it,
-  // can't we find a way to get manu<->buspatch transparent to this too ?
-  
-  if ( stationType == kStation1 || stationType == kStation2 )
-  {
-    for (Int_t i = 0; i < 12; i++)
-    {
-      if (m >= *(ptr + pos++)) break;
-    }
-  }
-  else 
-  {
-    // offset of 100 in manuId for following bus patch
-    pos = m/100;
-  }
-
-  if (pos >(Int_t) vec->GetSize())
-  {
-    AliError(Form("pos greater %d than size %d manuId %d detElemId %d \n", 
-                   pos, (Int_t)vec->GetSize(), digit.ManuId(), detElemId));
-    AliError(Form("Chamber %s Plane %s manuId %d m %d",
-                    StationTypeName(stationType).Data(),
-                    PlaneTypeName(plane).Data(),
-                    digit.ManuId(),
-                    m));
-    return -1;
-  }
-  
-  Int_t busPatchId = vec->At(pos);
-
-  fMappingTimer.Stop();
-  
-  return busPatchId;
+    return fDDLStore->GetBusPatchId(digit.DetElemId(),digit.ManuId());
 }
 
 //____________________________________________________________________
 Int_t AliMUONRawWriter::WriteTriggerDDL()
 {
-  //
-  // Write trigger DDL
-  //
-  fTriggerTimer.Start(kFALSE);
+  /// Write trigger DDL
+
+  fTimers[kWriteTrigger].Start(kFALSE);
   
  // DDL event one per half chamber
 
-  // stored local id number 
-  TArrayI isFired(256);
-  isFired.Reset();
-
-
  // DDL header size
   Int_t headerSize = sizeof(AliRawDataHeader)/4;
 
   TClonesArray* localTrigger;
   TClonesArray* globalTrigger;
+  TClonesArray* regionalTrigger;
+
   AliMUONGlobalTrigger* gloTrg;
   AliMUONLocalTrigger* locTrg = 0x0;
+  AliMUONRegionalTrigger* regTrg = 0x0;
 
   // global trigger for trigger pattern
   globalTrigger = fMUONData->GlobalTrigger(); 
   gloTrg = (AliMUONGlobalTrigger*)globalTrigger->UncheckedAt(0);
+  if (!gloTrg) 
+  {
+    fTimers[kWriteTrigger].Stop();
+    return 0;
+  }
+  
   Int_t gloTrigResp = gloTrg->GetGlobalResponse();
 
   // local trigger 
-  localTrigger = fMUONData->LocalTrigger();    
+  localTrigger = fMUONData->LocalTrigger();   
+
+
+  // regional trigger
+  regionalTrigger = fMUONData->RegionalTrigger();   
+
 
   UInt_t word;
   Int_t* buffer = 0;
   Int_t index;
   Int_t iEntries = 0;
   Int_t iLocCard, locCard;
-  Char_t locDec, trigY, posY, posX, regOut;
+  UChar_t locDec, trigY, posY, posX, regOut;
   UInt_t regInpLpt;
   UInt_t regInpHpt;
 
-  Int_t devX;
-  Int_t version = 1; // software version
-  Int_t eventPhys = 1; // trigger type: 1 for physics, 0 for software
-  Int_t serialNb = 0xF; // serial nb of card: all bits on for the moment
+  UInt_t devX;
+  UChar_t sdevX;
+  UInt_t version = 1; // software version
+  UInt_t eventPhys = 1; // trigger type: 1 for physics, 0 for software
+  UInt_t serialNb = 0xF; // serial nb of card: all bits on for the moment
   Int_t globalFlag = 0; // set to 1 if global info present in DDL else set to 0
 
   // size of headers
@@ -740,14 +592,9 @@ Int_t AliMUONRawWriter::WriteTriggerDDL()
     eventPhys = 0; //set to generate scaler events
 
   Int_t nEntries = (Int_t) (localTrigger->GetEntries());// 234 local cards
-  // stored the local card id that's fired
-  for (Int_t i = 0; i <  nEntries; i++) {
-    locTrg = (AliMUONLocalTrigger*)localTrigger->At(i);
-    isFired[locTrg->LoCircuit()] = 1; // storing local boards with informations
-  }
 
   if (!nEntries)
-    AliInfo("No Trigger information available");
+    AliDebug(1, "No Trigger information available");
 
   if(fScalerEvent)
     buffer = new Int_t [kScalerBufferSize];
@@ -814,21 +661,30 @@ Int_t AliMUONRawWriter::WriteTriggerDDL()
       if (!crate) 
        AliWarning(Form("Missing crate number %d in DDL %d\n", iReg, iDDL));
 
+      // regional info tree, make sure that no reg card missing
+      for (Int_t i = 0; i < 16; ++i) {
+       regTrg  = (AliMUONRegionalTrigger*)regionalTrigger->At(i);
+       if (regTrg)
+         if (regTrg->GetId() == (iReg + iDDL*8)) break;
+      }
+
       // Regional card header
       word = 0;
 
       // set darc status word
       fRegHeader->SetDarcWord(word);
 
-      regOut    = 0;
-      regInpHpt = regInpLpt = 0;
+      regOut    = regTrg->GetOutput();
+      regInpHpt = regTrg->GetLocalOutput(0);
+      regInpLpt = regTrg->GetLocalOutput(1);
+
       // fill darc word, not darc status for the moment (empty)
       //see  AliMUONRegHeader.h for details
       AliBitPacking::PackWord((UInt_t)eventPhys,word,31,31); 
       AliBitPacking::PackWord((UInt_t)serialNb,word,19,24); 
       AliBitPacking::PackWord((UInt_t)version,word,16,23);
       AliBitPacking::PackWord((UInt_t)iReg,word,15,18);
-      AliBitPacking::PackWord((UInt_t)regOut,word,0,7); // waiting realistic output of AliMUONGlobalTrigger (oct 06 ?)
+      AliBitPacking::PackWord((UInt_t)regOut,word,0,7); 
       fRegHeader->SetWord(word);
 
 
@@ -849,98 +705,70 @@ Int_t AliMUONRawWriter::WriteTriggerDDL()
 
 
       // 16 local card per regional board
-      UShort_t localMask = 0x0;
-
+      //      UShort_t localMask = 0x0;
+      
       for (Int_t iLoc = 0; iLoc < 16; iLoc++) {
-
-       // slot zero for Regional card
-       AliMUONLocalTriggerBoard* localBoard = (AliMUONLocalTriggerBoard*)boards->At(iLoc+1);
-
-       if (localBoard) { // if not empty slot
-
-         if ((iLocCard = localBoard->GetNumber()) != 0) {// if notified board
-
-           localMask |= (0x1 << iLoc); // local mask
-           if (isFired[iLocCard]) { // if card has triggered
-             locTrg  = (AliMUONLocalTrigger*)localTrigger->At(iEntries);
-             locCard = locTrg->LoCircuit();
-             locDec  = locTrg->GetLoDecision();
-             trigY = 0;
-             posY  = locTrg->LoStripY();
-             posX  = locTrg->LoStripX();
-             devX  = locTrg->LoDev();
-
-             AliDebug(4,Form("loctrg %d, posX %d, posY %d, devX %d\n", 
-                             locTrg->LoCircuit(),locTrg->LoStripX(),locTrg->LoStripY(),locTrg->LoDev()));
-           } else { //no trigger (see PRR chpt 3.4)
-             locDec = 0;
-             trigY = 1;
-             posY = 15;
-             posX = 0;
-             devX = 0x8;
-             // set local card id to -1
-             locCard = -1; 
-           }
-           // calculate regional input High and low Pt
-           UInt_t tmp1 = (locDec >> 2) & 0x3;
-           UInt_t tmp2 =  locDec & 0x3;
-           
-           regInpHpt |= tmp1 << (30 - iLoc*2);
-           regInpLpt |= tmp2 << (30 - iLoc*2);
-          
-           //packing word
-           word = 0;
-           AliBitPacking::PackWord((UInt_t)iLoc,word,19,22); //card id number in crate
-           AliBitPacking::PackWord((UInt_t)locDec,word,15,18);
-           AliBitPacking::PackWord((UInt_t)trigY,word,14,14);
-           AliBitPacking::PackWord((UInt_t)posY,word,10,13);
-           AliBitPacking::PackWord((UInt_t)devX,word,5,9);
-           AliBitPacking::PackWord((UInt_t)posX,word,0,4);
-
-           if (locCard == iLocCard) {
-             // add local cards structure
-             buffer[index++] = (locTrg->GetX1Pattern() | (locTrg->GetX2Pattern() << 16));
-             buffer[index++] = (locTrg->GetX3Pattern() | (locTrg->GetX4Pattern() << 16));
-             buffer[index++] = (locTrg->GetY1Pattern() | (locTrg->GetY2Pattern() << 16));
-             buffer[index++] = (locTrg->GetY3Pattern() | (locTrg->GetY4Pattern() << 16));
-             buffer[index++] = (Int_t)word; // data word
-             if (iEntries < nEntries-1)
-               iEntries++;
-           } else {
-             buffer[index++] = 0; // 4 words for x1, x2, y1, y2
-             buffer[index++] = 0; 
-             buffer[index++] = 0; 
-             buffer[index++] = 0; 
-             buffer[index++] = (Int_t)word; // data word
-
-           }
-         } else {// number!=0
-         // fill with 10CDEAD word for 'non-notified' slots
-         for (Int_t i = 0; i < fLocalStruct->GetLength(); i++)
-           buffer[index++] = fLocalStruct->GetDisableWord(); 
+         
+         // slot zero for Regional card
+         AliMUONLocalTriggerBoard* localBoard = (AliMUONLocalTriggerBoard*)boards->At(iLoc+1);
+         
+         if (localBoard) { // if not empty slot
+             
+             if ((iLocCard = localBoard->GetNumber()) != 0) {// if notified board
+                 
+                 locTrg  = (AliMUONLocalTrigger*)localTrigger->At(iEntries++);
+                 locCard = locTrg->LoCircuit();
+                 locDec  = locTrg->GetLoDecision();
+                 trigY =  locTrg->LoTrigY();
+                 posY  = locTrg->LoStripY();
+                 posX  = locTrg->LoStripX();
+                 devX  = locTrg->LoDev();
+                 sdevX = locTrg->LoSdev();
+                 
+                 AliDebug(4,Form("loctrg %d, posX %d, posY %d, devX %d\n", 
+                                 locTrg->LoCircuit(),locTrg->LoStripX(),locTrg->LoStripY(),locTrg->LoDev()));  
+                 //packing word
+                 word = 0;
+                 AliBitPacking::PackWord((UInt_t)iLoc,word,19,22); //card id number in crate
+                 AliBitPacking::PackWord((UInt_t)locDec,word,15,18);
+                 AliBitPacking::PackWord((UInt_t)trigY,word,14,14);
+                 AliBitPacking::PackWord((UInt_t)posY,word,10,13);
+                 AliBitPacking::PackWord((UInt_t)sdevX,word,9,9);
+                 AliBitPacking::PackWord((UInt_t)devX,word,5,8);
+                 AliBitPacking::PackWord((UInt_t)posX,word,0,4);
+                 
+                 buffer[index++] = (locTrg->GetX1Pattern() | (locTrg->GetX2Pattern() << 16));
+                 buffer[index++] = (locTrg->GetX3Pattern() | (locTrg->GetX4Pattern() << 16));
+                 buffer[index++] = (locTrg->GetY1Pattern() | (locTrg->GetY2Pattern() << 16));
+                 buffer[index++] = (locTrg->GetY3Pattern() | (locTrg->GetY4Pattern() << 16));
+                 buffer[index++] = (Int_t)word; // data word
+
+             } else {// number!=0
+                 // fill with 10CDEAD word for 'non-notified' slots
+                 for (Int_t i = 0; i < fLocalStruct->GetLength(); i++)
+                     buffer[index++] = fLocalStruct->GetDisableWord(); 
+             }
+         } else { 
+             // fill with 10CDEAD word for empty slots
+             for (Int_t i = 0; i < fLocalStruct->GetLength(); i++)
+                 buffer[index++] = fLocalStruct->GetDisableWord(); 
+         }// condition localBoard
+         
+         // 45 regional scaler word
+         if (fScalerEvent) {
+             memcpy(&buffer[index], fLocalStruct->GetScalers(), kLocScalerLength*4);
+             index += kLocScalerLength;
          }
-       } else { 
-         // fill with 10CDEAD word for empty slots
-         for (Int_t i = 0; i < fLocalStruct->GetLength(); i++)
-           buffer[index++] = fLocalStruct->GetDisableWord(); 
-       }// condition localBoard
-
-       // 45 regional scaler word
-       if (fScalerEvent) {
-         memcpy(&buffer[index], fLocalStruct->GetScalers(), kLocScalerLength*4);
-         index += kLocScalerLength;
-       }
-
-       // end of local structure words
-       buffer[index++] = fLocalStruct->GetEndOfLocal();
-
+         
+         // end of local structure words
+         buffer[index++] = fLocalStruct->GetEndOfLocal();
+         
       } // local card 
       // fill regional header with local output
-      fRegHeader->SetInput(regInpLpt, 0);
+      fRegHeader->SetInput(regInpHpt, 0);
       fRegHeader->SetInput(regInpHpt, 1);
-      fRegHeader->SetMask(localMask);
       memcpy(&buffer[indexReg],fRegHeader->GetHeader(),kRegHeaderLength*4);
-
+      
     } // Regional card
     
 
@@ -953,16 +781,16 @@ Int_t AliMUONRawWriter::WriteTriggerDDL()
   }
   delete[] buffer;
 
-  fTriggerTimer.Stop();
+  fTimers[kWriteTrigger].Stop();
   
   return kTRUE;
 }
 //____________________________________________________________________
 void AliMUONRawWriter::SetScalersNumbers()
 {
-  // set numbers for scaler events for trigger headers
-  // since this is provided by the experiment
-  // put dummy numbers to check the monitoring
+  /// set numbers for scaler events for trigger headers
+  /// since this is provided by the experiment
+  /// put dummy numbers to check the monitoring
 
   fDarcHeader->SetScalersNumbers();
   fRegHeader->SetScalersNumbers();