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