]> git.uio.no Git - u/mrichter/AliRoot.git/blobdiff - MUON/AliMUONRawWriter.cxx
Extracting the BLOCK DATA in a separate file. Changes to make it working on macosx
[u/mrichter/AliRoot.git] / MUON / AliMUONRawWriter.cxx
index 3c86898f98c5764ac3b2789d3d2c39e4f9a9e80b..69e8c5b7acc6d0ee73f6fcd65963d1011e6560ed 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
+/// 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.
 
 #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 "AliMUONRegHeader.h"
+#include "AliMUONTriggerCrate.h"
+#include "AliMUONTriggerCrateStore.h"
 
+#include "AliMpBusPatch.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"
 
+/// \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};
@@ -84,15 +83,17 @@ Int_t AliMUONRawWriter::fgManuPerBusSwp1NB[12] = {1, 27, 53, 79, 105, 131, 157,
 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()),
@@ -100,26 +101,18 @@ AliMUONRawWriter::AliMUONRawWriter(AliMUONData* data)
     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();
@@ -128,9 +121,11 @@ AliMUONRawWriter::AliMUONRawWriter(AliMUONData* data)
   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,10 +133,8 @@ AliMUONRawWriter::AliMUONRawWriter(AliMUONData* data)
 AliMUONRawWriter::AliMUONRawWriter()
   : TObject(),
     fMUONData(0),
-    fBusArray(0),
     fBlockHeader(0),
     fDspHeader(0),
-    fBusStruct(0),
     fDarcHeader(0),
     fRegHeader(0),
     fLocalStruct(0),
@@ -149,36 +142,25 @@ AliMUONRawWriter::AliMUONRawWriter()
     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;
@@ -186,23 +168,57 @@ AliMUONRawWriter::~AliMUONRawWriter(void)
   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;
 }
 
+//______________________________________________________________________________
+//void
+//AliMUONRawWriter::CheckDigits()
+//{
+//  std::map<int,std::map<int,int> > m;
+//  
+//  for (Int_t iSt = 0; iSt < AliMUONConstants::NTrackingCh()/2; ++iSt) 
+//  {
+//    for (Int_t iCh = iSt*2; iCh <= iSt*2 + 1; ++iCh) 
+//    {      
+//      TClonesArray* muonDigits = fMUONData->Digits(iCh);
+//      for (Int_t idig = 0; idig < muonDigits->GetEntriesFast(); idig++) 
+//      {        
+//        AliMUONDigit* digit = (AliMUONDigit*) muonDigits->UncheckedAt(idig);
+//        Int_t busPatchId = GetBusPatch(*digit);
+//        m[busPatchId][digit->ManuId()]++;
+//      }
+//    } 
+//  }
+//  
+//  std::map<int,std::map<int,int> >::const_iterator it;
+//  
+//  Int_t nManuMax(0);
+//  
+//  for ( it = m.begin(); it != m.end(); ++it )
+//  {
+//    AliDebug(1,Form("BusPatch %3d has %3d manus",it->first,it->second.size()));
+//    nManuMax = std::max((Int_t)it->second.size(),nManuMax);
+//    std::map<int,int>::const_iterator it2;
+//    for ( it2 = it->second.begin(); it2 != it->second.end(); ++it2 )
+//    {
+//      AliDebug(1,Form("        BusPatch %3d Manu %4d Nch %3d",it->first,it2->first,it2->second));
+//    }
+//  }
+//  AliDebug(1,Form("Max manus per busPatch : %3d",nManuMax));
+//}
+
 //____________________________________________________________________
 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 +232,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 +266,8 @@ Int_t AliMUONRawWriter::Digits2Raw()
      
   }
  
+  AliDebug(1,"Tracker written");
+  
   // trigger chambers
  
   // open files
@@ -265,37 +285,30 @@ Int_t AliMUONRawWriter::Digits2Raw()
   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 +339,90 @@ 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;
-
+      
+      fTimers[kTest].Start(kFALSE);
+      busPatchId = GetBusPatch(*digit);
+      fTimers[kTest].Stop();
+      
       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,165 +431,135 @@ 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);
 
+    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 = fBusPatchManager->NextBusInDDL(iDDL);
+          
+          // 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(Int_t detElemId, Int_t manuId) const
 {
-  //
-  // Determine the BusPatch this digit belongs to.
-  //
-  fMappingTimer.Start(kFALSE);
+  /// Determine the BusPatch this digit belongs to.
   
   Int_t* ptr = 0;
-
-  // information from digits
-  Int_t detElemId  = digit.DetElemId();
-
-  AliMpVSegmentation* seg = 
-    fSegFactory->CreateMpSegmentationByElectronics(detElemId, digit.ManuId());
+    
+  AliMpPlaneType plane = 
+    (manuId & AliMpConstants::ManuMask(kNonBendingPlane)) ? 
+    kNonBendingPlane : kBendingPlane; 
   
-  AliMpPlaneType plane = seg->PlaneType();
-
   AliMpStationType stationType = AliMpDEManager::GetStationType(detElemId);
-
+  
   if ( stationType == kStation1 || stationType == kStation2 )
   {
     if (plane == kBendingPlane) 
@@ -629,21 +582,21 @@ Int_t AliMUONRawWriter::GetBusPatch(const AliMUONDigit& digit)
       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 ?
+  
+  Int_t m = ( 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++)
+    for (pos = 11; pos >=0 ; --pos)
     {
-      if (m >= *(ptr + pos++)) break;
+      if (m >= ptr[pos]) break;
     }
   }
   else 
@@ -651,33 +604,45 @@ Int_t AliMUONRawWriter::GetBusPatch(const AliMUONDigit& digit)
     // 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));
+                  pos, (Int_t)vec->GetSize(), manuId, detElemId));
     AliError(Form("Chamber %s Plane %s manuId %d m %d",
-                    StationTypeName(stationType).Data(),
-                    PlaneTypeName(plane).Data(),
-                    digit.ManuId(),
-                    m));
+                  StationTypeName(stationType).Data(),
+                  PlaneTypeName(plane).Data(),
+                  manuId,
+                  m));
     return -1;
   }
   
   Int_t busPatchId = vec->At(pos);
-
-  fMappingTimer.Stop();
+  
+  if ( ( stationType == kStation1 || stationType == kStation2 ) &&
+       ( plane == kNonBendingPlane ) )
+  {
+    busPatchId += 12;
+  }
   
   return busPatchId;
 }
 
+//____________________________________________________________________
+Int_t AliMUONRawWriter::GetBusPatch(const AliMUONDigit& digit) const
+{
+  /// Determine the BusPatch this digit belongs to.
+
+  return GetBusPatch(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
 
@@ -697,6 +662,12 @@ Int_t AliMUONRawWriter::WriteTriggerDDL()
   // 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 
@@ -747,7 +718,7 @@ Int_t AliMUONRawWriter::WriteTriggerDDL()
   }
 
   if (!nEntries)
-    AliInfo("No Trigger information available");
+    AliDebug(1, "No Trigger information available");
 
   if(fScalerEvent)
     buffer = new Int_t [kScalerBufferSize];
@@ -953,16 +924,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();