]> git.uio.no Git - u/mrichter/AliRoot.git/blob - MUON/AliMUONRawWriter.cxx
Modifying comments for Doxygen and/or
[u/mrichter/AliRoot.git] / MUON / AliMUONRawWriter.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16 /* $Id$ */
17
18 /// \class AliMUONRawWriter
19 /// MUON Raw Data generaton in ALICE-MUON
20 /// This class version 3 (further details could be found in Alice-note)
21 ///
22 /// Implemented non-constant buspatch numbers for tracking
23 /// with correct DDL id (first guess)
24 /// (Ch. Finck, dec 2005)
25 ///
26 /// Digits2Raw:
27 /// Generates raw data for MUON tracker and finally for trigger
28 /// Using real mapping (inverse) for tracker
29 /// For trigger there is no mapping (mapping could be found in AliMUONTriggerCircuit)
30 /// Ch. Finck, July 04
31 /// Use memcpy instead of assignment elt by elt
32 /// Introducing variable DSP numbers, real manu numbers per buspatch for st12
33 /// Implemented scaler event for Trigger
34 /// Ch. Finck, Jan. 06
35 /// Using bus itr in DDL instead of simple incrementation
36 /// treat correctly the DDL & buspatch for station 3.
37 /// Using informations from AliMUONTriggerCrateStore for 
38 /// empty slots and non-notified cards in trigger crates.
39 /// Ch. Finck, August 06.
40
41 #include "AliMUONRawWriter.h"
42
43 #include "AliMUONBlockHeader.h"
44 #include "AliMUONBusStruct.h"
45 #include "AliMUONConstants.h"
46 #include "AliMUONDarcHeader.h"
47 #include "AliMUONData.h"
48 #include "AliMUONDigit.h"
49 #include "AliMUONDspHeader.h"
50 #include "AliMUONGlobalTrigger.h"
51 #include "AliMUONLocalStruct.h"
52 #include "AliMUONLocalTrigger.h"
53 #include "AliMUONLocalTriggerBoard.h"
54 #include "AliMUONRegHeader.h"
55 #include "AliMUONTriggerCrate.h"
56 #include "AliMUONTriggerCrateStore.h"
57
58 #include "AliMpBusPatch.h"
59 #include "AliMpDEManager.h"
60 #include "AliMpExMap.h"
61 #include "AliMpConstants.h"
62 #include "AliMpPlaneType.h"
63 #include "AliMpSegmentation.h"
64 #include "AliMpStationType.h"
65 #include "AliMpVSegmentation.h"
66
67 #include "AliRawReader.h"
68 #include "AliBitPacking.h" 
69 #include "AliDAQ.h"
70 #include "AliLog.h"
71
72 #include "TList.h"
73 #include "TObjArray.h"
74 #include "TStopwatch.h"
75
76 /// \cond CLASSIMP
77 ClassImp(AliMUONRawWriter) // Class implementation in ROOT context
78 /// \endcond
79
80 Int_t AliMUONRawWriter::fgManuPerBusSwp1B[12]  = {1, 27, 53, 79, 105, 131, 157, 183, 201, 214, 224, 232};
81 Int_t AliMUONRawWriter::fgManuPerBusSwp1NB[12] = {1, 27, 53, 79, 105, 131, 157, 183, 201, 214, 225, 233};
82
83 Int_t AliMUONRawWriter::fgManuPerBusSwp2B[12]  = {1, 27, 53, 79, 105, 131, 157, 183, 201, 214, 226, 246};
84 Int_t AliMUONRawWriter::fgManuPerBusSwp2NB[12] = {1, 27, 53, 79, 105, 131, 157, 183, 201, 214, 227, 245};
85
86 namespace 
87 {
88   enum ETimer { kWriteTracker, kWriteTrigger, kDigitLoop, kGetBusPatch, kTest, kLast };
89 }
90
91 //__________________________________________________________________________
92 AliMUONRawWriter::AliMUONRawWriter(AliMUONData* data)
93   : TObject(),
94     fMUONData(data),
95     fBlockHeader(new AliMUONBlockHeader()),
96     fDspHeader(new AliMUONDspHeader()),
97     fDarcHeader(new AliMUONDarcHeader()),
98     fRegHeader(new AliMUONRegHeader()),
99     fLocalStruct(new AliMUONLocalStruct()),
100     fBusPatchManager(new AliMpBusPatch()),
101     fCrateManager(new AliMUONTriggerCrateStore()),
102     fScalerEvent(kFALSE),
103     fHeader(),
104     fTimers(new TStopwatch[kLast])
105
106 {
107   /// Standard Constructor
108
109   AliDebug(1,"Standard ctor");
110   fFile[0] = fFile[1] = 0x0;  
111   fFile[2] = fFile[3] = 0x0;  
112
113   // setting data key to default value (only for writting)
114   fBlockHeader->SetDataKey(fBlockHeader->GetDefaultDataKey());
115   fDspHeader->SetDataKey(fDspHeader->GetDefaultDataKey());
116
117   // bus patch managers
118   fBusPatchManager->ReadBusPatchFile();
119
120   // Crate manager
121   fCrateManager->ReadFromFile();
122
123   // timers
124   for ( Int_t i = 0; i < kLast; ++i )
125   {
126     fTimers[i].Start(kTRUE); 
127     fTimers[i].Stop();
128   }
129   
130 }
131
132 //__________________________________________________________________________
133 AliMUONRawWriter::AliMUONRawWriter()
134   : TObject(),
135     fMUONData(0),
136     fBlockHeader(0),
137     fDspHeader(0),
138     fDarcHeader(0),
139     fRegHeader(0),
140     fLocalStruct(0),
141     fBusPatchManager(0),
142     fCrateManager(0x0),
143     fScalerEvent(kFALSE),
144     fHeader(),
145     fTimers(0)
146 {
147   /// Default Constructor
148
149   AliDebug(1,"Default ctor");   
150   fFile[0] = fFile[1] = 0x0;  
151   fFile[2] = fFile[3] = 0x0;  
152
153 }
154
155 //__________________________________________________________________________
156 AliMUONRawWriter::~AliMUONRawWriter(void)
157 {
158   /// Destructor
159
160   AliDebug(1,"dtor");
161   
162   delete fBlockHeader;
163   delete fDspHeader;
164   delete fDarcHeader;
165   delete fRegHeader;
166   delete fLocalStruct;
167
168   delete fBusPatchManager;
169   delete fCrateManager;
170
171   for ( Int_t i = 0; i < kLast; ++i )
172   {
173     AliDebug(1, Form("Execution time (timer %d) : R:%7.2fs C:%7.2fs",i,
174                  fTimers[i].RealTime(),fTimers[i].CpuTime()));
175   }
176   
177   delete[] fTimers;
178 }
179
180 //______________________________________________________________________________
181 //void
182 //AliMUONRawWriter::CheckDigits()
183 //{
184 //  std::map<int,std::map<int,int> > m;
185 //  
186 //  for (Int_t iSt = 0; iSt < AliMUONConstants::NTrackingCh()/2; ++iSt) 
187 //  {
188 //    for (Int_t iCh = iSt*2; iCh <= iSt*2 + 1; ++iCh) 
189 //    {      
190 //      TClonesArray* muonDigits = fMUONData->Digits(iCh);
191 //      for (Int_t idig = 0; idig < muonDigits->GetEntriesFast(); idig++) 
192 //      {        
193 //        AliMUONDigit* digit = (AliMUONDigit*) muonDigits->UncheckedAt(idig);
194 //        Int_t busPatchId = GetBusPatch(*digit);
195 //        m[busPatchId][digit->ManuId()]++;
196 //      }
197 //    } 
198 //  }
199 //  
200 //  std::map<int,std::map<int,int> >::const_iterator it;
201 //  
202 //  Int_t nManuMax(0);
203 //  
204 //  for ( it = m.begin(); it != m.end(); ++it )
205 //  {
206 //    AliDebug(1,Form("BusPatch %3d has %3d manus",it->first,it->second.size()));
207 //    nManuMax = std::max((Int_t)it->second.size(),nManuMax);
208 //    std::map<int,int>::const_iterator it2;
209 //    for ( it2 = it->second.begin(); it2 != it->second.end(); ++it2 )
210 //    {
211 //      AliDebug(1,Form("        BusPatch %3d Manu %4d Nch %3d",it->first,it2->first,it2->second));
212 //    }
213 //  }
214 //  AliDebug(1,Form("Max manus per busPatch : %3d",nManuMax));
215 //}
216
217 //____________________________________________________________________
218 Int_t AliMUONRawWriter::Digits2Raw()
219 {
220   /// convert digits of the current event to raw data
221
222   Int_t idDDL;
223   Char_t name[255];
224
225   fMUONData->GetLoader()->LoadDigits("READ");
226
227   fMUONData->SetTreeAddress("D,GLT");
228
229   fMUONData->ResetDigits();
230   fMUONData->ResetTrigger();
231   
232   // This will get both tracker and trigger digits.
233   fMUONData->GetDigits();
234   
235 //  CheckDigits();
236
237   // tracking chambers
238   
239   for (Int_t iSt = 0; iSt < AliMUONConstants::NTrackingCh()/2; ++iSt) {
240
241     // open files for one station
242     // cos station 3, 1/4 of DE's from 2 chambers has same DDL number 
243     idDDL = iSt * 4;
244     strcpy(name,AliDAQ::DdlFileName("MUONTRK",idDDL));
245     fFile[0] = fopen(name,"w");
246
247     idDDL = (iSt * 4) + 1;
248     strcpy(name,AliDAQ::DdlFileName("MUONTRK",idDDL));
249     fFile[1] = fopen(name,"w");
250
251     idDDL =  (iSt * 4) + 2;;
252     strcpy(name,AliDAQ::DdlFileName("MUONTRK",idDDL));
253     fFile[2] = fopen(name,"w");
254
255     idDDL =  (iSt * 4) + 3;
256     strcpy(name,AliDAQ::DdlFileName("MUONTRK",idDDL));
257     fFile[3] = fopen(name,"w");
258
259     WriteTrackerDDL(iSt);
260   
261     // reset and close when station has been processed
262     fclose(fFile[0]);
263     fclose(fFile[1]);
264     fclose(fFile[2]);
265     fclose(fFile[3]);
266      
267   }
268  
269   AliDebug(1,"Tracker written");
270   
271   // trigger chambers
272  
273   // open files
274   idDDL = 0;// MUTR
275   strcpy(name,AliDAQ::DdlFileName("MUONTRG",idDDL));
276   fFile[0] = fopen(name,"w");
277
278   idDDL = 1;// MUTR
279   strcpy(name,AliDAQ::DdlFileName("MUONTRG",idDDL));
280   fFile[1] = fopen(name,"w");
281
282   WriteTriggerDDL();
283   
284   // reset and close
285   fclose(fFile[0]);
286   fclose(fFile[1]);
287
288   AliDebug(1,"Trigger written");
289
290   fMUONData->ResetDigits();
291   fMUONData->ResetTrigger();  
292   fMUONData->GetLoader()->UnloadDigits();
293
294   AliDebug(1,"muondata reset");
295   
296   return kTRUE;
297 }
298
299 //____________________________________________________________________
300 Int_t AliMUONRawWriter::WriteTrackerDDL(Int_t iSt)
301 {
302   /// writing DDL for tracker
303   /// used inverse mapping
304
305   fTimers[kWriteTracker].Start(kFALSE);
306   
307   static const Int_t kMAXADC = (1<<12)-1; // We code the charge on a 12 bits ADC.
308
309   // resets
310   TClonesArray* muonDigits = 0;
311
312   // DDL header
313   Int_t headerSize = sizeof(fHeader)/4;
314
315   // DDL event one per half chamber
316
317   // raw data
318   Char_t parity = 0x4;
319   UShort_t manuId = 0;
320   UChar_t channelId = 0;
321   UShort_t charge = 0;
322   Int_t busPatchId = 0;
323   UInt_t word;
324
325
326   // Dsp length
327   Int_t totalDspLength;
328   Int_t dspLength;
329
330   // block length
331   Int_t totalBlkLength;
332   Int_t blkLength; 
333   
334   // total DDL length
335   Int_t totalDDLLength;
336
337   // indexes
338   Int_t index;
339   Int_t indexDsp;
340   Int_t indexBlk;
341
342   // buffer size (max'ed out)
343   // (((43 manus max per bus patch *64 channels + 4 bus patch words) * 5 bus patch 
344   //   + 10 dsp words)*5 dsps + 8 block words)*2 blocks 
345   static const Int_t kBufferSize = (((43*64 + 4)*5 + 10)*5 + 8)*2;
346   
347   Int_t nDigits;
348
349   AliMpExMap busPatchMap(kTRUE);
350   
351   fTimers[kDigitLoop].Start(kFALSE);
352   
353   for (Int_t iCh = iSt*2; iCh <= iSt*2 + 1; ++iCh) {
354
355     muonDigits = fMUONData->Digits(iCh);
356     
357     nDigits = muonDigits->GetEntriesFast();
358     
359     // loop over digit
360     for (Int_t idig = 0; idig < nDigits; ++idig) {
361       
362       AliMUONDigit* digit = static_cast<AliMUONDigit*>(muonDigits->UncheckedAt(idig));
363       
364       charge = digit->ADC();
365       if ( charge > kMAXADC )
366       {
367         // This is most probably an error in the digitizer (which should insure
368         // the adc is below kMAXADC), so make it a (non-fatal) error indeed.
369         AliError(Form("adc value %d above %x for ch %d . Setting to %x. Digit is:",iCh,
370                       charge,kMAXADC,kMAXADC));
371         StdoutToAliError(digit->Print());
372         charge = kMAXADC;
373       }
374       
375       // inverse mapping
376       fTimers[kGetBusPatch].Start(kFALSE);
377       busPatchId = GetBusPatch(*digit);
378       fTimers[kGetBusPatch].Stop();
379       if (busPatchId<0) continue;
380       
381       fTimers[kTest].Start(kFALSE);
382       busPatchId = GetBusPatch(*digit);
383       fTimers[kTest].Stop();
384       
385       if ( digit->ManuId() > 0x7FF || digit->ManuId() < 0 ||
386            digit->ManuChannel() > 0x3F || digit->ManuChannel() < 0 )
387       {
388         StdoutToAliError(digit->Print(););
389         AliFatal("ManuId,ManuChannel are invalid for the digit above.");
390       }
391       
392       manuId = ( digit->ManuId() & 0x7FF ); // 11 bits
393       channelId = ( digit->ManuChannel() & 0x3F ); // 6 bits
394             
395       //packing word
396       word = 0;
397       AliBitPacking::PackWord((UInt_t)manuId,word,18,28);
398       AliBitPacking::PackWord((UInt_t)channelId,word,12,17);
399       AliBitPacking::PackWord((UInt_t)charge,word,0,11);
400       
401       // parity word
402       parity = word & 0x1;
403       for (Int_t i = 1; i <= 30; ++i) 
404         parity ^=  ((word >> i) & 0x1);
405       AliBitPacking::PackWord((UInt_t)parity,word,31,31);
406       
407       AliMUONBusStruct* busStruct = 
408         static_cast<AliMUONBusStruct*>(busPatchMap.GetValue(busPatchId));
409       
410       if (!busStruct)
411       {
412         busStruct = new AliMUONBusStruct;
413         busStruct->SetDataKey(busStruct->GetDefaultDataKey());
414         busStruct->SetBusPatchId(busPatchId);
415         busStruct->SetLength(0);
416         busPatchMap.Add(busPatchId,busStruct);
417       }
418
419       // set sub Event
420       busStruct->AddData(word);
421       
422     } // idig
423   } // loop over chamber in station
424     
425   fTimers[kDigitLoop].Stop();
426   
427   // getting info for the number of buspatches
428   Int_t iBusPatch;
429   Int_t length;
430   Int_t iBusPerDSP[5];//number of bus patches per DSP
431   Int_t iDspMax; //number max of DSP per block
432   Int_t iFile = 0;
433
434   AliMUONBusStruct* busStructPtr(0x0);
435
436   // open DDL files, 4 per station
437   for (Int_t iDDL = iSt*4; iDDL < 4 + iSt*4; ++iDDL) {
438
439     fBusPatchManager->ResetBusItr(iDDL);
440     fBusPatchManager->GetDspInfo(iDDL, iDspMax, iBusPerDSP);
441
442     Int_t buffer[kBufferSize];
443     
444     totalDDLLength = 0;
445
446     indexBlk = 0;
447     indexDsp = 0;
448     index = 0;
449
450     // two blocks A and B per DDL
451     for (Int_t iBlock = 0; iBlock < 2; ++iBlock) {
452       
453       // block header
454       length = fBlockHeader->GetHeaderLength();
455       memcpy(&buffer[index],fBlockHeader->GetHeader(),length*4);
456       indexBlk = index;
457       index += length; 
458       
459       // 5 DSP's max per block
460       for (Int_t iDsp = 0; iDsp < iDspMax; ++iDsp) {
461         
462         // DSP header
463         length = fDspHeader->GetHeaderLength();
464         memcpy(&buffer[index],fDspHeader->GetHeader(),length*4);
465         indexDsp = index;
466         index += length; 
467         
468         // 5 buspatches max per DSP
469         for (Int_t i = 0; i < iBusPerDSP[iDsp]; i++) {
470           
471           iBusPatch = fBusPatchManager->NextBusInDDL(iDDL);
472           
473           // iteration over bus patch in DDL
474           if (iBusPatch == -1) {
475             AliWarning(Form("Error in bus itr in DDL %d\n", iDDL));
476             continue;
477           }
478           
479           // 4 DDL's per station, condition needed for station 3
480           iFile = iDDL - iSt*4; // works only if DDL begins at zero (as it should be) !!!
481           
482           busStructPtr = static_cast<AliMUONBusStruct*>(busPatchMap.GetValue(iBusPatch));
483           
484           // check if buspatchid has digit
485           if (busStructPtr) {
486             // add bus patch structure header
487             length = busStructPtr->GetHeaderLength();
488             memcpy(&buffer[index],busStructPtr->GetHeader(),length*4);
489             index += length;
490             
491             // add bus patch data
492             length = busStructPtr->GetLength();
493             memcpy(&buffer[index],busStructPtr->GetData(),length*4);
494             index += length;
495             
496             if (AliLog::GetGlobalDebugLevel() == 3) {
497               for (Int_t j = 0; j < busStructPtr->GetLength(); j++) {
498                 printf("busPatchId %d, manuId %d channelId %d\n", busStructPtr->GetBusPatchId(), 
499                        busStructPtr->GetManuId(j), busStructPtr->GetChannelId(j));
500               }
501             }
502           } else {
503             // writting anyhow buspatch structure (empty ones)
504             buffer[index++] = busStructPtr->GetDefaultDataKey(); // fill it also for empty data size
505             buffer[index++] = busStructPtr->GetHeaderLength(); // header length
506             buffer[index++] = 0; // raw data length
507             buffer[index++] = iBusPatch; // bus patch
508           }
509         } // bus patch
510         
511         // check if totalLength even
512         // set padding word in case
513         // Add one word 0xBEEFFACE at the end of DSP structure
514         totalDspLength  = index - indexDsp;
515         if ((totalDspLength % 2) == 1) { 
516           buffer[indexDsp + fDspHeader->GetHeaderLength() - 2] = 1;
517           buffer[index++] = fDspHeader->GetDefaultPaddingWord();
518           totalDspLength++;
519         }
520         
521         dspLength          = totalDspLength - fDspHeader->GetHeaderLength();
522         
523         buffer[indexDsp+1] = totalDspLength; // dsp total length
524         buffer[indexDsp+2] = dspLength; // data length  
525         
526       } // dsp
527       
528       totalBlkLength  = index - indexBlk;
529       blkLength       = totalBlkLength - fBlockHeader->GetHeaderLength();
530       totalDDLLength += totalBlkLength;
531       
532       buffer[indexBlk+1] = totalBlkLength; // total block length
533       buffer[indexBlk+2] = blkLength;
534       
535     } // block
536     
537     //writting onto disk
538     // write DDL 1 - 4
539     // total length in bytes
540     fHeader.fSize = (totalDDLLength + headerSize) * 4;
541       
542     fwrite((char*)(&fHeader),headerSize*4,1,fFile[iFile]);
543     fwrite(buffer,sizeof(int),index,fFile[iFile]);
544   }
545   
546   fTimers[kWriteTracker].Stop();
547   return kTRUE;
548 }
549
550 //____________________________________________________________________
551 Int_t AliMUONRawWriter::GetBusPatch(Int_t detElemId, Int_t manuId) const
552 {
553   /// Determine the BusPatch this digit belongs to.
554   
555   Int_t* ptr = 0;
556     
557   AliMpPlaneType plane = 
558     (manuId & AliMpConstants::ManuMask(kNonBendingPlane)) ? 
559     kNonBendingPlane : kBendingPlane; 
560   
561   AliMpStationType stationType = AliMpDEManager::GetStationType(detElemId);
562   
563   if ( stationType == kStation1 || stationType == kStation2 )
564   {
565     if (plane == kBendingPlane) 
566     {
567       ptr = &fgManuPerBusSwp1B[0];
568     }
569     else 
570     {
571       ptr = &fgManuPerBusSwp1NB[0];
572     }
573   }
574   else
575   {
576     if (plane == kBendingPlane)
577     {
578       ptr = &fgManuPerBusSwp2B[0];
579     }
580     else
581     {
582       ptr = &fgManuPerBusSwp2NB[0];
583     }
584   }
585   
586   // Getting buspatch id
587   TArrayI* vec = fBusPatchManager->GetBusfromDE(detElemId);
588   Int_t pos = 0;
589   
590   Int_t m = ( manuId & 0x3FF ); // remove bit 10
591                                         //FIXME : how can we remove that condition
592                                         // on the 10-th bit ? All the rest need not any knowledge about it,
593                                         // can't we find a way to get manu<->buspatch transparent to this too ?
594   
595   if ( stationType == kStation1 || stationType == kStation2 )
596   {
597     for (pos = 11; pos >=0 ; --pos)
598     {
599       if (m >= ptr[pos]) break;
600     }
601   }
602   else 
603   {
604     // offset of 100 in manuId for following bus patch
605     pos = m/100;
606   }
607   
608   
609   if (pos >(Int_t) vec->GetSize())
610   {
611     AliError(Form("pos greater %d than size %d manuId %d detElemId %d \n", 
612                   pos, (Int_t)vec->GetSize(), manuId, detElemId));
613     AliError(Form("Chamber %s Plane %s manuId %d m %d",
614                   StationTypeName(stationType).Data(),
615                   PlaneTypeName(plane).Data(),
616                   manuId,
617                   m));
618     return -1;
619   }
620   
621   Int_t busPatchId = vec->At(pos);
622   
623   if ( ( stationType == kStation1 || stationType == kStation2 ) &&
624        ( plane == kNonBendingPlane ) )
625   {
626     busPatchId += 12;
627   }
628   
629   return busPatchId;
630 }
631
632 //____________________________________________________________________
633 Int_t AliMUONRawWriter::GetBusPatch(const AliMUONDigit& digit) const
634 {
635   /// Determine the BusPatch this digit belongs to.
636
637   return GetBusPatch(digit.DetElemId(),digit.ManuId());
638 }
639
640 //____________________________________________________________________
641 Int_t AliMUONRawWriter::WriteTriggerDDL()
642 {
643   /// Write trigger DDL
644
645   fTimers[kWriteTrigger].Start(kFALSE);
646   
647  // DDL event one per half chamber
648
649   // stored local id number 
650   TArrayI isFired(256);
651   isFired.Reset();
652
653
654  // DDL header size
655   Int_t headerSize = sizeof(AliRawDataHeader)/4;
656
657   TClonesArray* localTrigger;
658   TClonesArray* globalTrigger;
659   AliMUONGlobalTrigger* gloTrg;
660   AliMUONLocalTrigger* locTrg = 0x0;
661
662   // global trigger for trigger pattern
663   globalTrigger = fMUONData->GlobalTrigger(); 
664   gloTrg = (AliMUONGlobalTrigger*)globalTrigger->UncheckedAt(0);
665   if (!gloTrg) 
666   {
667     fTimers[kWriteTrigger].Stop();
668     return 0;
669   }
670   
671   Int_t gloTrigResp = gloTrg->GetGlobalResponse();
672
673   // local trigger 
674   localTrigger = fMUONData->LocalTrigger();    
675
676   UInt_t word;
677   Int_t* buffer = 0;
678   Int_t index;
679   Int_t iEntries = 0;
680   Int_t iLocCard, locCard;
681   Char_t locDec, trigY, posY, posX, regOut;
682   UInt_t regInpLpt;
683   UInt_t regInpHpt;
684
685   Int_t devX;
686   Int_t version = 1; // software version
687   Int_t eventPhys = 1; // trigger type: 1 for physics, 0 for software
688   Int_t serialNb = 0xF; // serial nb of card: all bits on for the moment
689   Int_t globalFlag = 0; // set to 1 if global info present in DDL else set to 0
690
691   // size of headers
692   static const Int_t kDarcHeaderLength   = fDarcHeader->GetDarcHeaderLength();
693   static const Int_t kGlobalHeaderLength = fDarcHeader->GetGlobalHeaderLength();
694   static const Int_t kDarcScalerLength   = fDarcHeader->GetDarcScalerLength();
695   static const Int_t kGlobalScalerLength = fDarcHeader->GetGlobalScalerLength();
696   static const Int_t kRegHeaderLength    = fRegHeader->GetHeaderLength();
697   static const Int_t kRegScalerLength    = fRegHeader->GetScalerLength();
698   static const Int_t kLocHeaderLength    = fLocalStruct->GetLength();
699   static const Int_t kLocScalerLength    = fLocalStruct->GetScalerLength();
700
701   // [16(local)*6 words + 6 words]*8(reg) + 8 words = 824 
702   static const Int_t kBufferSize = (16 * (kLocHeaderLength+1) +  (kRegHeaderLength+1))* 8 
703       +  kDarcHeaderLength + kGlobalHeaderLength + 2;
704
705   // [16(local)*51 words + 16 words]*8(reg) + 8 + 10 + 8 words scaler event 6682 words
706   static const Int_t kScalerBufferSize = (16 * (kLocHeaderLength +  kLocScalerLength +1) +  
707                                          (kRegHeaderLength + kRegScalerLength +1))* 8 +
708                                          (kDarcHeaderLength + kDarcScalerLength + 
709                                           kGlobalHeaderLength + kGlobalScalerLength + 2);
710   if(fScalerEvent)
711     eventPhys = 0; //set to generate scaler events
712
713   Int_t nEntries = (Int_t) (localTrigger->GetEntries());// 234 local cards
714   // stored the local card id that's fired
715   for (Int_t i = 0; i <  nEntries; i++) {
716     locTrg = (AliMUONLocalTrigger*)localTrigger->At(i);
717     isFired[locTrg->LoCircuit()] = 1; // storing local boards with informations
718   }
719
720   if (!nEntries)
721     AliDebug(1, "No Trigger information available");
722
723   if(fScalerEvent)
724     buffer = new Int_t [kScalerBufferSize];
725   else
726     buffer = new Int_t [kBufferSize];
727
728   // reset crate
729
730   // open DDL file, on per 1/2 chamber
731   for (Int_t iDDL = 0; iDDL < 2; iDDL++) {
732
733     index = 0; 
734
735     if (iDDL == 0) // suppose global info in DDL one
736       globalFlag = 1;
737     else 
738       globalFlag = 0;
739
740     word = 0;
741     // set darc status word
742     // see AliMUONDarcHeader.h for details
743     AliBitPacking::PackWord((UInt_t)eventPhys,word,30,30);
744     AliBitPacking::PackWord((UInt_t)serialNb,word,20,23);
745     AliBitPacking::PackWord((UInt_t)globalFlag,word,10,10);
746     AliBitPacking::PackWord((UInt_t)version,word,12,19);
747     fDarcHeader->SetWord(word);
748
749     memcpy(&buffer[index], fDarcHeader->GetHeader(), (kDarcHeaderLength)*4); 
750     index += kDarcHeaderLength;
751
752     // no global input for the moment....
753     if (iDDL == 0)
754      fDarcHeader->SetGlobalOutput(gloTrigResp);
755     else 
756      fDarcHeader->SetGlobalOutput(0);
757
758     if (fScalerEvent) {
759       // 6 DARC scaler words
760       memcpy(&buffer[index], fDarcHeader->GetDarcScalers(),kDarcScalerLength*4);
761       index += kDarcScalerLength;
762     }
763     // end of darc word
764     buffer[index++] = fDarcHeader->GetEndOfDarc();
765
766     // 4 words of global board input + Global board output
767     memcpy(&buffer[index], fDarcHeader->GetGlobalInput(), (kGlobalHeaderLength)*4); 
768     index += kGlobalHeaderLength; 
769
770     if (fScalerEvent) {
771       // 10 Global scaler words
772       memcpy(fDarcHeader->GetGlobalScalers(), &buffer[index], kGlobalScalerLength*4);
773       index += kGlobalScalerLength;
774     }
775
776     // end of global word
777     buffer[index++] = fDarcHeader->GetEndOfGlobal();
778
779     // 8 regional cards per DDL
780     for (Int_t iReg = 0; iReg < 8; iReg++) {
781
782       // crate info
783       AliMUONTriggerCrate* crate = fCrateManager->Crate(iDDL, iReg);
784
785       if (!crate) 
786         AliWarning(Form("Missing crate number %d in DDL %d\n", iReg, iDDL));
787
788       // Regional card header
789       word = 0;
790
791       // set darc status word
792       fRegHeader->SetDarcWord(word);
793
794       regOut    = 0;
795       regInpHpt = regInpLpt = 0;
796       // fill darc word, not darc status for the moment (empty)
797       //see  AliMUONRegHeader.h for details
798       AliBitPacking::PackWord((UInt_t)eventPhys,word,31,31); 
799       AliBitPacking::PackWord((UInt_t)serialNb,word,19,24); 
800       AliBitPacking::PackWord((UInt_t)version,word,16,23);
801       AliBitPacking::PackWord((UInt_t)iReg,word,15,18);
802       AliBitPacking::PackWord((UInt_t)regOut,word,0,7); // waiting realistic output of AliMUONGlobalTrigger (oct 06 ?)
803       fRegHeader->SetWord(word);
804
805
806       // fill header later, need local response
807       Int_t indexReg = index;
808       index += kRegHeaderLength;
809
810       // 11 regional scaler word
811       if (fScalerEvent) {
812         memcpy(&buffer[index], fRegHeader->GetScalers(), kRegScalerLength*4);
813         index += kRegScalerLength;
814       }
815
816       // end of regional word
817       buffer[index++] = fRegHeader->GetEndOfReg();
818       
819       TObjArray *boards = crate->Boards();
820
821
822       // 16 local card per regional board
823       UShort_t localMask = 0x0;
824
825       for (Int_t iLoc = 0; iLoc < 16; iLoc++) {
826
827         // slot zero for Regional card
828         AliMUONLocalTriggerBoard* localBoard = (AliMUONLocalTriggerBoard*)boards->At(iLoc+1);
829
830         if (localBoard) { // if not empty slot
831
832           if ((iLocCard = localBoard->GetNumber()) != 0) {// if notified board
833
834             localMask |= (0x1 << iLoc); // local mask
835             if (isFired[iLocCard]) { // if card has triggered
836               locTrg  = (AliMUONLocalTrigger*)localTrigger->At(iEntries);
837               locCard = locTrg->LoCircuit();
838               locDec  = locTrg->GetLoDecision();
839               trigY = 0;
840               posY  = locTrg->LoStripY();
841               posX  = locTrg->LoStripX();
842               devX  = locTrg->LoDev();
843
844               AliDebug(4,Form("loctrg %d, posX %d, posY %d, devX %d\n", 
845                               locTrg->LoCircuit(),locTrg->LoStripX(),locTrg->LoStripY(),locTrg->LoDev()));
846             } else { //no trigger (see PRR chpt 3.4)
847               locDec = 0;
848               trigY = 1;
849               posY = 15;
850               posX = 0;
851               devX = 0x8;
852               // set local card id to -1
853               locCard = -1; 
854             }
855             // calculate regional input High and low Pt
856             UInt_t tmp1 = (locDec >> 2) & 0x3;
857             UInt_t tmp2 =  locDec & 0x3;
858             
859             regInpHpt |= tmp1 << (30 - iLoc*2);
860             regInpLpt |= tmp2 << (30 - iLoc*2);
861            
862             //packing word
863             word = 0;
864             AliBitPacking::PackWord((UInt_t)iLoc,word,19,22); //card id number in crate
865             AliBitPacking::PackWord((UInt_t)locDec,word,15,18);
866             AliBitPacking::PackWord((UInt_t)trigY,word,14,14);
867             AliBitPacking::PackWord((UInt_t)posY,word,10,13);
868             AliBitPacking::PackWord((UInt_t)devX,word,5,9);
869             AliBitPacking::PackWord((UInt_t)posX,word,0,4);
870
871             if (locCard == iLocCard) {
872               // add local cards structure
873               buffer[index++] = (locTrg->GetX1Pattern() | (locTrg->GetX2Pattern() << 16));
874               buffer[index++] = (locTrg->GetX3Pattern() | (locTrg->GetX4Pattern() << 16));
875               buffer[index++] = (locTrg->GetY1Pattern() | (locTrg->GetY2Pattern() << 16));
876               buffer[index++] = (locTrg->GetY3Pattern() | (locTrg->GetY4Pattern() << 16));
877               buffer[index++] = (Int_t)word; // data word
878               if (iEntries < nEntries-1)
879                 iEntries++;
880             } else {
881               buffer[index++] = 0; // 4 words for x1, x2, y1, y2
882               buffer[index++] = 0; 
883               buffer[index++] = 0; 
884               buffer[index++] = 0; 
885               buffer[index++] = (Int_t)word; // data word
886
887             }
888           } else {// number!=0
889           // fill with 10CDEAD word for 'non-notified' slots
890           for (Int_t i = 0; i < fLocalStruct->GetLength(); i++)
891             buffer[index++] = fLocalStruct->GetDisableWord(); 
892           }
893         } else { 
894           // fill with 10CDEAD word for empty slots
895           for (Int_t i = 0; i < fLocalStruct->GetLength(); i++)
896             buffer[index++] = fLocalStruct->GetDisableWord(); 
897         }// condition localBoard
898
899         // 45 regional scaler word
900         if (fScalerEvent) {
901           memcpy(&buffer[index], fLocalStruct->GetScalers(), kLocScalerLength*4);
902           index += kLocScalerLength;
903         }
904
905         // end of local structure words
906         buffer[index++] = fLocalStruct->GetEndOfLocal();
907
908       } // local card 
909       // fill regional header with local output
910       fRegHeader->SetInput(regInpLpt, 0);
911       fRegHeader->SetInput(regInpHpt, 1);
912       fRegHeader->SetMask(localMask);
913       memcpy(&buffer[indexReg],fRegHeader->GetHeader(),kRegHeaderLength*4);
914
915     } // Regional card
916     
917
918     // writting onto disk
919     // write DDL's
920     fHeader.fSize = (index + headerSize) * 4;// total length in bytes
921     fwrite((char*)(&fHeader),headerSize*4,1,fFile[iDDL]);
922     fwrite(buffer,sizeof(int),index,fFile[iDDL]);
923   
924   }
925   delete[] buffer;
926
927   fTimers[kWriteTrigger].Stop();
928   
929   return kTRUE;
930 }
931 //____________________________________________________________________
932 void AliMUONRawWriter::SetScalersNumbers()
933 {
934   /// set numbers for scaler events for trigger headers
935   /// since this is provided by the experiment
936   /// put dummy numbers to check the monitoring
937
938   fDarcHeader->SetScalersNumbers();
939   fRegHeader->SetScalersNumbers();
940   fLocalStruct->SetScalersNumbers();
941  
942   fScalerEvent = kTRUE;
943 }
944