]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TRD/AliTRDrawData.cxx
Updated version of the rawStream with the option to dump MCM raw data
[u/mrichter/AliRoot.git] / TRD / AliTRDrawData.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 //  TRD raw data conversion class                                            //
21 //                                                                           //
22 ///////////////////////////////////////////////////////////////////////////////
23
24
25 #include <TMath.h>
26 #include "TClass.h"
27
28 #include "AliDAQ.h"
29 #include "AliRawDataHeaderSim.h"
30 #include "AliRawReader.h"
31 #include "AliLog.h"
32 #include "AliFstream.h"
33 #include "AliTreeLoader.h"
34
35 #include "AliTRDrawData.h"
36 #include "AliTRDdigitsManager.h"
37 #include "AliTRDgeometry.h"
38 #include "AliTRDarrayDictionary.h"
39 #include "AliTRDarrayADC.h"
40 #include "AliTRDrawStreamBase.h"
41 #include "AliTRDcalibDB.h"
42 #include "AliTRDSignalIndex.h"
43 #include "AliTRDfeeParam.h"
44 #include "AliTRDmcmSim.h"
45 #include "AliTRDtrackletWord.h"
46 #include "AliTRDdigitsParam.h"
47
48 ClassImp(AliTRDrawData)
49
50 Int_t AliTRDrawData::fgRawFormatVersion = AliTRDrawData::kRawNewFormat;
51 Int_t AliTRDrawData::fgDataSuppressionLevel = 0;
52
53 //_____________________________________________________________________________
54 AliTRDrawData::AliTRDrawData()
55   :TObject()
56   ,fRunLoader(NULL)
57   ,fGeo(NULL)
58   ,fFee(NULL)
59   ,fNumberOfDDLs(0)
60   ,fTrackletTree(NULL)
61   ,fTrackletContainer(NULL)
62   ,fSMindexPos(0)
63   ,fStackindexPos(0)
64   ,fEventCounter(0)
65   ,fDigitsParam(NULL)
66 {
67   //
68   // Default constructor
69   //
70
71   fFee = AliTRDfeeParam::Instance();
72   fNumberOfDDLs = AliDAQ::NumberOfDdls("TRD");
73
74 }
75
76 //_____________________________________________________________________________
77 AliTRDrawData::AliTRDrawData(const AliTRDrawData &r)
78   :TObject(r)
79   ,fRunLoader(NULL)
80   ,fGeo(NULL)
81   ,fFee(NULL)
82   ,fNumberOfDDLs(0)
83   ,fTrackletTree(NULL)
84   ,fTrackletContainer(NULL)
85   ,fSMindexPos(0)
86   ,fStackindexPos(0)
87   ,fEventCounter(0)
88   ,fDigitsParam(NULL)
89 {
90   //
91   // Copy constructor
92   //
93
94   fFee = AliTRDfeeParam::Instance();
95   fNumberOfDDLs = AliDAQ::NumberOfDdls("TRD");
96
97 }
98
99 //_____________________________________________________________________________
100 AliTRDrawData::~AliTRDrawData()
101 {
102   //
103   // Destructor
104   //
105
106   if (fTrackletContainer){
107     delete fTrackletContainer;
108     fTrackletContainer = NULL;
109   }
110
111 }
112
113 //_____________________________________________________________________________
114 Bool_t AliTRDrawData::Digits2Raw(TTree *digitsTree, const TTree *tracks )
115 {
116   //
117   // Initialize necessary parameters and call one
118   // of the raw data simulator selected by SetRawVersion.
119   //
120   // Currently tracklet output is not spported yet and it
121   // will be supported in higher version simulator.
122   //
123
124   AliTRDdigitsManager* const digitsManager = new AliTRDdigitsManager();
125
126   if (!digitsManager->ReadDigits(digitsTree)) {
127     delete digitsManager;
128     return kFALSE;
129   }
130
131   if (tracks != NULL) {
132     delete digitsManager;
133     AliError("Tracklet input is not supported yet.");
134     return kFALSE;
135   }
136
137   fGeo = new AliTRDgeometry();
138
139   if (!AliTRDcalibDB::Instance()) {
140     AliError("Could not get calibration object");
141     delete fGeo;
142     delete digitsManager;
143     return kFALSE;
144   }
145
146   Int_t retval = kTRUE;
147   Int_t rv     = fFee->GetRAWversion();
148
149   // Call appropriate Raw Simulator
150   if ( rv > 0 && rv <= 3 ) retval = Digits2Raw(digitsManager); 
151   else {
152     retval = kFALSE;
153     AliWarning(Form("Unsupported raw version (%d).", rv));
154   }
155
156   // Cleanup
157   delete fGeo;
158   delete digitsManager;
159
160   return retval;
161
162 }
163
164 //_____________________________________________________________________________
165 Bool_t AliTRDrawData::Digits2Raw(AliTRDdigitsManager *digitsManager)
166 {
167   //
168   // Raw data simulator for all versions > 0. This is prepared for real data.
169   // This version simulate only raw data with ADC data and not with tracklet.
170   //
171
172   const Int_t kMaxHcWords = (fGeo->TBmax()/3)
173                           * fGeo->ADCmax()
174                           * fGeo->MCMmax()
175                           * fGeo->ROBmaxC1()/2 
176                           + 100 + 20;
177
178   // Buffer to temporary store half chamber data
179   UInt_t     *hcBuffer    = new UInt_t[kMaxHcWords];
180
181   Bool_t newEvent = kFALSE;  // only for correct readout tree
182   Bool_t newSM    = kFALSE;  // new SM flag, for writing SM index words
183   Bool_t newStack = kFALSE;  // new stack flag, for writing stack index words
184
185   // Get digits parameter
186   fDigitsParam = digitsManager->GetDigitsParam();
187
188   // sect is same as iDDL, so I use only sect here.
189   for (Int_t sect = 0; sect < fGeo->Nsector(); sect++) { 
190
191     char name[1024];
192     sprintf(name,"TRD_%d.ddl",sect + AliTRDrawStreamBase::kDDLOffset);
193
194     AliFstream* of = new AliFstream(name);
195
196             // Write a dummy data header
197     AliRawDataHeaderSim  header;  // the event header
198     UInt_t hpos = of->Tellp();
199     of->WriteBuffer((char *) (& header), sizeof(header));
200
201     // Reset payload byte size (payload does not include header).
202     Int_t npayloadbyte = 0;
203
204
205    if ( fgRawFormatVersion == 0 ){
206     // GTU common data header (5x4 bytes per super module, shows link mask)
207     for( Int_t stack = 0; stack < fGeo->Nstack(); stack++ ) {
208         UInt_t gtuCdh = (UInt_t)(0xe << 28);
209         for( Int_t layer = 0; layer < fGeo->Nlayer(); layer++) {
210             Int_t iDet = fGeo->GetDetector(layer, stack, sect);
211
212             // If chamber status is ok, we assume that the optical link is also OK.
213             // This is shown in the GTU link mask.
214             if ( AliTRDcalibDB::Instance()->GetChamberStatus(iDet) )
215                 gtuCdh = gtuCdh | (3 << (2*layer));
216         }
217         of->WriteBuffer((char *) (& gtuCdh), sizeof(gtuCdh));
218         npayloadbyte += 4;
219     }
220    }
221
222
223     // check the existance of the data
224     // SM index word and Stack index word
225    if ( fgRawFormatVersion == 1 ){
226     UInt_t *iwbuffer = new UInt_t[109]; // index word buffer; max 109 = 2 SM headers + 67 dummy headers + 5*8 stack headers
227     Int_t nheader = 0;
228     UInt_t bStackMask = 0x0;
229     Bool_t bStackHasData = kFALSE;
230     Bool_t bSMHasData = kFALSE;
231
232     //iwbuffer[nheader++] = 0x0001a020;   // SM index words 
233     iwbuffer[nheader++] = 0x0044a020;   // SM index words | additional SM header:48 = 1 SM header + 47 dummy words(for future use)
234     iwbuffer[nheader++] = 0x10404071;   // SM header
235     for ( Int_t i=0; i<66; i++ ) iwbuffer[nheader++] = 0x00000000;  // dummy words 
236     iwbuffer[nheader++] = 0x10000000;   // end of dummy words
237
238     for ( Int_t stack= 0; stack < fGeo->Nstack(); stack++) {
239         UInt_t linkMask = 0x0;
240         for( Int_t layer = 0; layer < fGeo->Nlayer(); layer++) {
241             Int_t iDet = fGeo->GetDetector(layer,stack,sect);
242                         AliTRDarrayADC *digits = (AliTRDarrayADC *) digitsManager->GetDigits(iDet);
243             if ( digits->HasData() ) {
244                 bStackMask = bStackMask | ( 1 << stack ); // active stack mask for new stack
245                 linkMask = linkMask | ( 3 << (2*layer) );    // 3 = 0011
246                 bStackHasData = kTRUE;
247                 bSMHasData = kTRUE;
248             } // has data
249         } // loop over layer
250
251         if ( fgDataSuppressionLevel==0 || bStackHasData ){
252             iwbuffer[nheader++] = 0x0007a000 | linkMask;    // stack index word + link masks
253             if (fgDataSuppressionLevel==0) iwbuffer[nheader-1] = 0x0007afff;  // no suppression
254             iwbuffer[nheader++] = 0x04045b01;               // stack header
255             for (Int_t i=0;i<6;i++) iwbuffer[nheader++] = 0x00000000; // 6 dummy words
256             bStackHasData = kFALSE;
257         }
258     } // loop over stack
259
260     if ( fgDataSuppressionLevel==0 || bSMHasData ){
261         iwbuffer[0] = iwbuffer[0] | bStackMask;  // add stack masks to SM index word
262         if (fgDataSuppressionLevel==0) iwbuffer[0] = 0x0044a03f;    // no suppression : all stacks are active
263         of->WriteBuffer((char *) iwbuffer, nheader*4);
264         AliDebug(11, Form("SM %d index word: %08x", iwbuffer[0]));
265         AliDebug(11, Form("SM %d header: %08x", iwbuffer[1]));
266     }
267    }
268     // end of SM & stack header ------------------------------------------------------------------------
269     // -------------------------------------------------------------------------------------------------
270
271     // Prepare chamber data
272     for( Int_t stack = 0; stack < fGeo->Nstack(); stack++) {
273       for( Int_t layer = 0; layer < fGeo->Nlayer(); layer++) {
274
275         Int_t iDet = fGeo->GetDetector(layer,stack,sect);
276         if (iDet == 0){
277             newEvent = kTRUE; // it is expected that each event has at least one tracklet; 
278                                          // this is only needed for correct readout tree
279             fEventCounter++;
280             AliDebug(11, Form("New event!! Event counter: %d",fEventCounter));
281         }
282
283         if ( stack==0 && layer==0 ) newSM = kTRUE;  // new SM flag
284         if ( layer==0 ) newStack = kTRUE;           // new stack flag
285         AliDebug(15, Form("stack : %d, layer : %d, iDec : %d\n",stack,layer,iDet));
286         // Get the digits array
287                 AliTRDarrayADC *digits = (AliTRDarrayADC *) digitsManager->GetDigits(iDet);
288         if (fgDataSuppressionLevel==0 || digits->HasData() ) {  // second part is new!! and is for indicating a new event
289
290                 if (digits->HasData()) digits->Expand();
291
292                         Int_t hcwords = 0;
293                         Int_t rv = fFee->GetRAWversion();
294
295
296         if ( fgRawFormatVersion == 0 ){
297       // Process A side of the chamber
298           if ( rv >= 1 && rv <= 2 ) {
299             hcwords = ProduceHcDataV1andV2(digits,0,iDet,hcBuffer,kMaxHcWords);
300           }
301           if ( rv == 3 ) { 
302    
303               hcwords = ProduceHcDataV3     (digits,0,iDet,hcBuffer,kMaxHcWords,newEvent);
304               //hcwords = ProduceHcDataV3     (digits,0,iDet,hcBuffer,kMaxHcWords);
305             if(newEvent == kTRUE) newEvent = kFALSE;
306           }
307
308           of->WriteBuffer((char *) hcBuffer, hcwords*4);
309           npayloadbyte += hcwords*4;
310
311       // Process B side of the chamber
312           if ( rv >= 1 && rv <= 2 ) {
313             hcwords = ProduceHcDataV1andV2(digits,1,iDet,hcBuffer,kMaxHcWords);
314           }
315           if ( rv >= 3 ) {
316            
317               hcwords = ProduceHcDataV3     (digits,1,iDet,hcBuffer,kMaxHcWords,newEvent);
318               //hcwords = ProduceHcDataV3     (digits,1,iDet,hcBuffer,kMaxHcWords);
319           }
320
321           of->WriteBuffer((char *) hcBuffer, hcwords*4);
322           npayloadbyte += hcwords*4;
323
324     } else { // real data format
325
326        if (digits->HasData()){
327         // Process A side of the chamber
328         hcwords = ProduceHcData(digits,0,iDet,hcBuffer,kMaxHcWords,newEvent,newSM);
329         //if ( newStack ){
330         //  AssignStackMask(hcBuffer, stack);   // active stack mask for this stack
331         //  hcwords += AddStackIndexWords(hcBuffer, stack, hcwords);
332         //  newStack = kFALSE;
333         //}
334         //if ( newSM ) newSM = kFALSE;
335         if ( newEvent ) newEvent = kFALSE;
336         //AssignLinkMask(hcBuffer, layer);  // active link mask for this layer(2*HC)
337         of->WriteBuffer((char *) hcBuffer, hcwords*4);
338         npayloadbyte += hcwords*4;
339         //for ( Int_t i=0; i<hcwords; i++ ) AliInfo(Form("Buf : %X",hcBuffer[i]));
340
341         // Process B side of the chamber
342         hcwords = ProduceHcData(digits,1,iDet,hcBuffer,kMaxHcWords,newEvent,newSM);
343         of->WriteBuffer((char *) hcBuffer, hcwords*4);
344         npayloadbyte += hcwords*4;
345        } else {   // in case of no-suppression or NZS
346 /*        
347         hcBuffer[hcwords++] = fgkEndOfTrackletMarker;
348         hcBuffer[hcwords++] = fgkEndOfTrackletMarker;
349         hcBuffer[hcwords++] = (1<<31) | (0<<24) | (0<<17) | (1<<14) | (sect<<9) | (layer<<6) | (stack<<3) | (0<<2) | 1;
350         hcBuffer[hcwords++] = (24<<26) | (99<<10) | (15<<6) | (11<<2) | 1;
351         hcBuffer[hcwords++] = kEndofrawdatamarker;
352         hcBuffer[hcwords++] = kEndofrawdatamarker;
353         hcBuffer[hcwords++] = kEndofrawdatamarker;
354         hcBuffer[hcwords++] = kEndofrawdatamarker;
355         npayloadbyte += hcwords*4;
356
357         hcBuffer[hcwords++] = fgkEndOfTrackletMarker;
358         hcBuffer[hcwords++] = fgkEndOfTrackletMarker;
359         hcBuffer[hcwords++] = (1<<31) | (0<<24) | (0<<17) | (1<<14) | (sect<<9) | (layer<<6) | (stack<<3) | (1<<2) | 1;
360         hcBuffer[hcwords++] = (24<<26) | (99<<10) | (15<<6) | (11<<2) | 1;
361         hcBuffer[hcwords++] = kEndofrawdatamarker;
362         hcBuffer[hcwords++] = kEndofrawdatamarker;
363         hcBuffer[hcwords++] = kEndofrawdatamarker;
364         hcBuffer[hcwords++] = kEndofrawdatamarker;
365 */        
366         hcwords = ProduceHcDataNoSuppression(0,iDet,hcBuffer,kMaxHcWords); // side 0
367         of->WriteBuffer((char *) hcBuffer, hcwords*4);
368         npayloadbyte += hcwords*4;
369
370         hcwords = ProduceHcDataNoSuppression(1,iDet,hcBuffer,kMaxHcWords); // side 1
371         of->WriteBuffer((char *) hcBuffer, hcwords*4);
372         npayloadbyte += hcwords*4;
373        }
374     }
375
376     } // has data
377
378       } // loop over layer
379     } // loop over stack
380
381     // Complete header
382     header.fSize = UInt_t(of->Tellp()) - hpos;
383     header.SetAttribute(0);  // Valid data
384     of->Seekp(hpos);         // Rewind to header position
385     of->WriteBuffer((char *) (& header), sizeof(header));
386     delete of;
387   } // loop over sector(SM)
388
389   delete [] hcBuffer;
390
391   return kTRUE;
392
393 }
394
395 //_____________________________________________________________________________
396 void AliTRDrawData::ProduceSMIndexData(UInt_t *buf, Int_t& nw){
397         // 
398         // This function generates 
399         //       1) SM index words : ssssssss ssssssss vvvv rrrr r d t mmmmm
400         //          - s : size of SM header (number of header, default = 0x0001)
401         //          - v : SM header version (default = 0xa)
402         //          - r : reserved for future use (default = 00000)
403         //          - d : track data enabled bit (default = 0)
404         //          - t : tracklet data enabled bit (default = 1)
405         //          - m : stack mask (each bit corresponds a stack, default = 11111)
406         //
407         //       2) SM header : rrr c vvvv vvvvvvvv vvvv rrrr bbbbbbbb
408         //          - r : reserved for future use (default = 000)
409         //          - c : clean check out flag (default = 1)
410         //          - v : hardware design revision (default = 0x0404)
411         //          - r : reserved for future use (default = 0x0)
412         //          - b : physical board ID (default = 0x71)
413         //
414         //       3) stack index words : ssssssss ssssssss vvvv mmmm mmmmmmmm
415         //          - s : size of stack header (number of header, (default = 0x0007)
416         //          - v : header version (default = 0xa)
417         //          - m : link mask (default = 0xfff)
418         //
419         //       4) stack header : vvvvvvvv vvvvvvvv bbbbbbbb rrrr rrr c
420         //          - v : hardware design revision (default = 0x0404)
421         //          - b : physical board ID (default = 0x5b)
422         //          - r : reserved for future use (default = 0000 000)
423         //          - c : clean checkout flag (default = 1)
424         //      
425         //       and 6 dummy words(0x00000000)
426         //
427         
428     //buf[nw++] = 0x0001a03f;   // SM index words
429     fSMindexPos = nw;       // memorize position of the SM index word for re-allocating stack mask
430     buf[nw++] = 0x0001a020; // SM index words
431     buf[nw++] = 0x10404071; // SM header
432
433     fStackindexPos = nw;    // memorize position of the stack index word for future adding
434         /*  
435     for (Int_t istack=0; istack<5; istack++){
436         buf[nw++] = 0x0007afff; // stack index words
437         buf[nw++] = 0x04045b01; // stack header
438         for (Int_t i=0;i<6;i++) buf[nw++] = 0x00000000; // 6 dummy words
439     } // loop over 5 stacks
440         */
441 }
442
443 //_____________________________________________________________________________
444 void AliTRDrawData::AssignStackMask(UInt_t *buf, Int_t nStack){
445     //
446     // This function re-assign stack mask active(from 0 to 1) in the SM index word
447     //   
448     buf[fSMindexPos] = buf[fSMindexPos] | ( 1 << nStack );
449 }
450
451 //_____________________________________________________________________________  
452 Int_t AliTRDrawData::AddStackIndexWords(UInt_t *buf, Int_t /*nStack*/, Int_t nMax){
453     // 
454     // This function add stack index words and stack header when there is data for the stack
455     //
456     //   1) stack index words : ssssssss ssssssss vvvv mmmm mmmmmmmm 
457     //      - s : size of stack header (number of header, (default = 0x0007)       
458     //      - v : header version (default = 0xa)
459     //      - m : link mask (default = 0xfff)
460     //      - m : link mask (starting value = 0x000)
461     //
462     //   2) stack header : vvvvvvvv vvvvvvvv bbbbbbbb rrrr rrr c
463     //      - v : hardware design revision (default = 0x0404)
464     //      - b : physical board ID (default = 0x5b)
465     //      - r : reserved for future use (default = 0000 000)
466     //      - c : clean checkout flag (default = 1)
467     //  
468     //   and 6 dummy words(0x00000000)
469     //
470
471     Int_t nAddedWords = 0;  // Number of added words
472     if ( ShiftWords(buf, fStackindexPos, 8, nMax)== kFALSE ){
473         AliError("Adding stack header failed.");
474         return 0;
475     }
476
477     buf[fStackindexPos++] = 0x0007a000; // stack index words
478     buf[fStackindexPos++] = 0x04045b01; // stack header
479     for (Int_t i=0;i<6;i++) buf[fStackindexPos++] = 0x00000000; // 6 dummy words 
480     nAddedWords += 8;
481
482     return nAddedWords;
483 }
484
485 //_____________________________________________________________________________
486 void AliTRDrawData::AssignLinkMask(UInt_t *buf, Int_t nLayer){
487     //
488     // This function re-assign link mask active(from 0 to 1) in the stack index word
489     //   
490     buf[fStackindexPos-8] = buf[fStackindexPos-8] | ( 3 << (2*nLayer) );    // 3 = 0011 
491 }
492
493 //_____________________________________________________________________________ 
494 Bool_t AliTRDrawData::ShiftWords(UInt_t *buf, Int_t nStart, Int_t nWords, Int_t nMax){
495     //  
496     // This function shifts n words
497     //
498     //if ( nStart+nWords > sizeof(buf)/sizeof(UInt_t) ){
499     //  AliError("Words shift failed. No more buffer space.");
500     //  return kFALSE;
501     //}
502
503     for ( Int_t iw=nMax; iw>nStart-1; iw--){
504         buf[iw+nWords] = buf[iw];
505     }
506     return kTRUE;
507 }
508
509 //_____________________________________________________________________________
510 Int_t AliTRDrawData::ProduceHcData(AliTRDarrayADC *digits, Int_t side, Int_t det, UInt_t *buf, Int_t maxSize, Bool_t /*newEvent = kFALSE*/, Bool_t /*newSM = kFALSE*/){
511         //
512         // This function can be used for both ZS and NZS data
513         //
514
515         Int_t           nw = 0;                       // Number of written    words
516         Int_t           of = 0;                       // Number of overflowed words
517         Int_t      *tempnw = 0x0;                     // Number of written    words for temp. buffer
518         Int_t      *tempof = 0x0;                     // Number of overflowed words for temp. buffer
519         Int_t        layer = fGeo->GetLayer( det );   // Layer
520         Int_t        stack = fGeo->GetStack( det );   // Stack
521         Int_t         sect = fGeo->GetSector( det );  // Sector (=iDDL)
522         const Int_t kCtype = fGeo->GetStack(det) == 2 ? 0 : 1;                       // Chamber type (0:C0, 1:C1)
523
524         Bool_t trackletOn = fFee->GetTracklet();     // tracklet simulation active?
525
526         AliDebug(1,Form("Producing raw data for sect=%d layer=%d stack=%d side=%d",sect,layer,stack,side));
527         
528         AliTRDmcmSim* mcm = new AliTRDmcmSim();
529
530         UInt_t *tempBuffer = buf; // tempBuffer used to write ADC data
531                                   // different in case of tracklet writing
532         
533         if (trackletOn) {
534           tempBuffer = new UInt_t[maxSize];
535           tempnw = new Int_t(0);
536           tempof = new Int_t(0);
537         }
538         else {
539           tempnw = &nw;
540           tempof = &of;
541         }
542
543         WriteIntermediateWordsV2(tempBuffer,*tempnw,*tempof,maxSize,det,side);  //??? no tracklet or NZS
544
545         // scanning direction such, that tracklet-words are sorted in ascending z and then in ascending y order
546         // ROB numbering on chamber and MCM numbering on ROB increase with decreasing z and increasing y
547         for (Int_t iRobRow = 0; iRobRow <= (kCtype + 3)-1; iRobRow++ ) {        // ROB number should be increasing
548           Int_t iRob = iRobRow * 2 + side;
549           // MCM on one ROB
550           for (Int_t iMcmRB = 0; iMcmRB < fGeo->MCMmax(); iMcmRB++ ) {
551             Int_t iMcm = 16 - 4*(iMcmRB/4 + 1) + (iMcmRB%4);
552             
553             mcm->Init(det, iRob, iMcm);
554             mcm->SetData(digits);     // no filtering done here (already done in digitizer)
555             if (trackletOn) {
556               mcm->Tracklet();
557               Int_t tempNw = mcm->ProduceTrackletStream(&buf[nw], maxSize - nw);
558               if(  tempNw < 0 ) {
559                 of += tempNw;
560                 nw += maxSize - nw;
561                 AliError(Form("Buffer overflow detected. Please increase the buffer size and recompile."));
562               } else {
563                 nw += tempNw;
564               }
565             }
566             mcm->ZSMapping();  // Calculate zero suppression mapping
567                                // at the moment it has to be rerun here
568             // Write MCM data to temp. buffer
569             Int_t tempNw = mcm->ProduceRawStream( &tempBuffer[*tempnw], maxSize - *tempnw, fEventCounter );
570             if ( tempNw < 0 ) {
571               *tempof += tempNw;
572               *tempnw += maxSize - nw;
573               AliError(Form("Buffer overflow detected. Please increase the buffer size and recompile."));
574             } else {
575               *tempnw += tempNw;
576             }
577           }
578         }
579
580         delete mcm;
581
582
583         // in case of tracklet writing copy temp data to final buffer
584         if (trackletOn) {
585           if (nw + *tempnw < maxSize) {
586             memcpy(&buf[nw], tempBuffer, *tempnw * sizeof(UInt_t));
587             nw += *tempnw;
588           }
589           else {
590             AliError("Buffer overflow detected");
591           }
592         }
593
594         // Write end of raw data marker
595         if (nw+3 < maxSize) {
596           buf[nw++] = fgkEndOfDataMarker; // fFee->GetRawDataEndmarker(); 
597           buf[nw++] = fgkEndOfDataMarker; // fFee->GetRawDataEndmarker(); 
598           //buf[nw++] = fgkEndOfDataMarker; // fFee->GetRawDataEndmarker(); 
599           //buf[nw++] = fgkEndOfDataMarker; // fFee->GetRawDataEndmarker(); 
600         } else {
601           of++;
602         }
603         
604         if (trackletOn) {
605           delete [] tempBuffer;
606           delete tempof;
607           delete tempnw;
608         }
609
610         if (of != 0) {
611           AliError("Buffer overflow. Data is truncated. Please increase buffer size and recompile.");
612         }
613
614         return nw;
615 }
616
617 //_____________________________________________________________________________
618 Int_t AliTRDrawData::ProduceHcDataNoSuppression(Int_t side, Int_t det, UInt_t *buf, Int_t maxSize){
619
620     // This function generates below words for no-suppression option(same as real data format) 
621     //   1. end of tracklet marker
622     //   2. HC index word, HC header
623     //   3. MCM header, ADC mask
624     //   4. end of data marker
625     //
626
627     Int_t   nw = 0;         // number of written words
628     Int_t   of = 0;         // number of overflowed words
629     UInt_t  x  = 0;         // word buffer
630     //UInt_t *tempBuffer  = buf;   // temp buffer
631     Int_t  *tempnw      = &nw;   // temp number of written words
632     Int_t  *tempof      = &of;   // temp number of overflowed words
633
634     const Int_t kCtype = fGeo->GetStack(det) == 2 ? 0 : 1;   // Chamber type (0:C0, 1:C1)
635
636     WriteIntermediateWordsV2(buf, *tempnw, *tempof, maxSize, det, side);  // end of tracklet marker and HC headers
637
638     for (Int_t iRobRow = 0; iRobRow <= (kCtype + 3)-1; iRobRow++ ) {    // ROB number should be increasing
639         Int_t iRob = iRobRow * 2 + side;  // ROB position
640
641         for (Int_t iMcmRB = 0; iMcmRB < fGeo->MCMmax(); iMcmRB++ ) {    // MCM on ROB
642             Int_t iMcm = 16 - 4*(iMcmRB/4 + 1) + (iMcmRB%4);    // MCM position
643
644             if ( nw+2 < maxSize ){
645                 x = 0;
646                 x = (1<<31) | (iRob << 28) | (iMcm << 24) | ((fEventCounter % 0x100000) << 4) | 0xC;    // MCM header
647                 buf[nw++] = x;
648
649                 x = 0;
650                 // Produce ADC mask : nncc cccm mmmm mmmm mmmm mmmm mmmm 1100
651                 //                n : unused , c : ADC count, m : selected ADCs , where ccccc are inverted
652                 x = x | (1 << 30) | (31 << 25) | 0xC;   // 11111 = 31
653                 buf[nw++] = x;
654             } else {
655                 of++;
656             }
657
658         }   // loop over MCM
659     }   // loop over ROB
660
661         // Write end of raw data marker
662         if (nw+1 < maxSize) {
663           buf[nw++] = fgkEndOfDataMarker; // fFee->GetRawDataEndmarker(); 
664           buf[nw++] = fgkEndOfDataMarker; // fFee->GetRawDataEndmarker(); 
665           //buf[nw++] = fgkEndOfDataMarker; // fFee->GetRawDataEndmarker(); 
666           //buf[nw++] = fgkEndOfDataMarker; // fFee->GetRawDataEndmarker(); 
667         } else {
668           of++;
669         }
670
671     if ( of != 0 ){     // if there is overflow
672         AliError("Buffer overflow. Data is truncated. Please increase buffer size and recompile.");
673     }
674
675     AliDebug(1, Form("Number of written words in this HC is %d",nw));
676
677     return nw;
678 }
679
680 //_____________________________________________________________________________
681 Int_t AliTRDrawData::ProduceHcDataV1andV2(AliTRDarrayADC *digits, Int_t side
682                                         , Int_t det, UInt_t *buf, Int_t maxSize)
683 {
684   //
685   // This function simulates: 1) SM-I commissiong data Oct. 06 (Raw Version == 1).
686   //                          2) Full Raw Production Version   (Raw Version == 2)
687   //
688   // Produce half chamber data (= an ORI data) for the given chamber (det) and side (side)
689   // where
690   //
691   //   side=0 means A side with ROB positions 0, 2, 4, 6.
692   //   side=1 means B side with ROB positions 1, 3, 5, 7.
693   //
694   // Chamber type (C0 orC1) is determined by "det" automatically.
695   // Appropriate size of buffer (*buf) must be prepared prior to calling this function.
696   // Pointer to the buffer and its size must be given to "buf" and "maxSize".
697   // Return value is the number of valid data filled in the buffer in unit of 32 bits
698   // UInt_t words.
699   // If buffer size if too small, the data is truncated with the buffer size however
700   // the function will finish without crash (this behaviour is similar to the MCM).
701   //
702
703   Int_t           nw = 0;                       // Number of written    words
704   Int_t           of = 0;                       // Number of overflowed words
705   Int_t        layer = fGeo->GetLayer( det );   // Layer
706   Int_t        stack = fGeo->GetStack( det );   // Stack
707   Int_t         sect = fGeo->GetSector( det );  // Sector (=iDDL)
708   Int_t         nRow = fGeo->GetRowMax( layer, stack, sect );
709   Int_t         nCol = fGeo->GetColMax( layer );
710   const Int_t kNTBin = fDigitsParam->GetNTimeBins(det); 
711
712   Int_t       kCtype = 0;                       // Chamber type (0:C0, 1:C1)
713   Int_t          iEv = 0xA;                     // Event ID. Now fixed to 10, how do I get event id?
714   UInt_t           x = 0;                       // General used number
715   Int_t           rv = fFee->GetRAWversion();
716
717   // Check the nCol and nRow.
718   if ((nCol == 144) && 
719       (nRow == 16 || nRow == 12)) {
720     kCtype = (nRow-12) / 4;
721   } 
722   else {
723     AliError(Form("This type of chamber is not supported (nRow=%d, nCol=%d)."
724                  ,nRow,nCol));
725     return 0;
726   }
727
728   AliDebug(1,Form("Producing raw data for sect=%d layer=%d stack=%d side=%d"
729                  ,sect,layer,stack,side));
730
731   // Tracklet should be processed here but not implemented yet
732
733   // Write end of tracklet marker
734   if (nw < maxSize) {
735     buf[nw++] = kEndoftrackletmarker;
736   } 
737   else {
738     of++;
739   }
740
741   // Half Chamber header
742   if      ( rv == 1 ) {
743     // Now it is the same version as used in SM-I commissioning.
744     Int_t  dcs = det+100;      // DCS Serial (in simulation, it is meaningless
745     x = (dcs<<20) | (sect<<15) | (layer<<12) | (stack<<9) | (side<<8) | 1;
746     if (nw < maxSize) {
747       buf[nw++] = x; 
748     }
749     else {
750       of++;
751     }
752   } 
753   else if ( rv == 2 ) {
754     // h[0] (there are 3 HC header)
755     Int_t minorv = 0;      // The minor version number
756     Int_t add    = 2;      // The number of additional header words to follow
757     x = (1<<31) | (rv<<24) | (minorv<<17) | (add<<14) | (sect<<9) | (layer<<6) | (stack<<3) | (side<<2) | 1;
758     if (nw < maxSize) {
759       buf[nw++] = x; 
760     }
761     else {
762       of++;
763     }
764     // h[1]
765     Int_t bcCtr   = 99; // bunch crossing counter. Here it is set to 99 always for no reason
766     Int_t ptCtr   = 15; // pretrigger counter. Here it is set to 15 always for no reason
767     Int_t ptPhase = 11; // pretrigger phase. Here it is set to 11 always for no reason
768     x = (bcCtr<<16) | (ptCtr<<12) | (ptPhase<<8) | ((kNTBin-1)<<2) | 1;
769     if (nw < maxSize) {
770       buf[nw++] = x; 
771     }
772     else {
773       of++;
774     }
775     // h[2]
776     Int_t pedSetup       = 1;    // Pedestal filter setup (0:1). Here it is always 1 for no reason
777     Int_t gainSetup      = 1;    // Gain filter setup (0:1). Here it is always 1 for no reason
778     Int_t tailSetup      = 1;    // Tail filter setup (0:1). Here it is always 1 for no reason
779     Int_t xtSetup        = 0;    // Cross talk filter setup (0:1). Here it is always 0 for no reason
780     Int_t nonlinSetup    = 0;    // Nonlinearity filter setup (0:1). Here it is always 0 for no reason
781     Int_t bypassSetup    = 0;    // Filter bypass (for raw data) setup (0:1). Here it is always 0 for no reason
782     Int_t commonAdditive = 10;   // Digital filter common additive (0:63). Here it is always 10 for no reason
783     x = (pedSetup<<31) | (gainSetup<<30) | (tailSetup<<29) | (xtSetup<<28) | (nonlinSetup<<27)
784       | (bypassSetup<<26) | (commonAdditive<<20) | 1;
785     if (nw < maxSize) {
786       buf[nw++] = x; 
787     }
788     else {
789       of++;
790     }
791   }
792
793   // Scan for ROB and MCM
794   for (Int_t iRobRow = 0; iRobRow < (kCtype + 3); iRobRow++ ) {
795     Int_t iRob = iRobRow * 2 + side;
796     for (Int_t iMcm = 0; iMcm < fGeo->MCMmax(); iMcm++ ) {
797       Int_t padrow = iRobRow * 4 + iMcm / 4;
798
799       // MCM header
800       x = ((iRob * fGeo->MCMmax() + iMcm) << 24) | ((iEv % 0x100000) << 4) | 0xC;
801       if (nw < maxSize) {
802         buf[nw++] = x; 
803       }
804       else {
805         of++;
806       }
807
808       // ADC data
809       for (Int_t iAdc = 0; iAdc < 21; iAdc++ ) {
810         Int_t padcol = fFee->GetPadColFromADC(iRob, iMcm, iAdc);
811         UInt_t aa = !(iAdc & 1) + 2;    // 3 for the even ADC channel , 2 for the odd ADC channel
812         UInt_t *a = new UInt_t[kNTBin+2];
813         // 3 timebins are packed into one 32 bits word
814         for (Int_t iT = 0; iT < kNTBin; iT+=3) { 
815           if ((padcol >=    0) && (padcol <  nCol)) {
816             a[iT  ] = ((iT    ) < kNTBin ) ? digits->GetData(padrow,padcol,iT    ) : 0;
817             a[iT+1] = ((iT + 1) < kNTBin ) ? digits->GetData(padrow,padcol,iT + 1) : 0;
818             a[iT+2] = ((iT + 2) < kNTBin ) ? digits->GetData(padrow,padcol,iT + 2) : 0; 
819           } 
820           else {
821             a[iT] = a[iT+1] = a[iT+2] = 0; // This happenes at the edge of chamber (should be pedestal! How?)
822           }
823           x = (a[iT+2] << 22) | (a[iT+1] << 12) | (a[iT] << 2) | aa;
824           if (nw < maxSize) {
825             buf[nw++] = x; 
826           }
827           else {
828             of++;
829           }
830         }
831         // Diagnostics
832         Float_t avg = 0;
833         Float_t rms = 0;
834         for (Int_t iT = 0; iT < kNTBin; iT++) {
835           avg += (Float_t) (a[iT]);
836         }
837         avg /= (Float_t) kNTBin;
838         for (Int_t iT = 0; iT < kNTBin; iT++) {
839           rms += ((Float_t) (a[iT]) - avg) * ((Float_t) (a[iT]) - avg);
840         }
841         rms = TMath::Sqrt(rms / (Float_t) kNTBin);
842         if (rms > 1.7) {
843           AliDebug(2,Form("Large RMS (>1.7)  (ROB,MCM,ADC)=(%02d,%02d,%02d), avg=%03.1f, rms=%03.1f"
844                           ,iRob,iMcm,iAdc,avg,rms));
845         }
846         delete [] a;
847       }
848     }
849   }
850
851   // Write end of raw data marker
852   if (nw < maxSize) {
853     buf[nw++] = kEndofrawdatamarker; 
854   }
855   else {
856     of++;
857   }
858   if (of != 0) {
859     AliWarning("Buffer overflow. Data is truncated. Please increase buffer size and recompile.");
860   }
861
862   return nw;
863
864 }
865
866 //_____________________________________________________________________________
867
868 //Int_t AliTRDrawData::ProduceHcDataV3(AliTRDarrayADC *digits, Int_t side , Int_t det, UInt_t *buf, Int_t maxSize)
869 Int_t AliTRDrawData::ProduceHcDataV3(AliTRDarrayADC *digits, Int_t side , Int_t det, UInt_t *buf, Int_t maxSize, Bool_t newEvent = kFALSE)
870 {
871   //
872   // This function simulates: Raw Version == 3 (Zero Suppression Prototype)
873   //
874
875   Int_t           nw = 0;                       // Number of written    words
876   Int_t           of = 0;                       // Number of overflowed words
877   Int_t        layer = fGeo->GetLayer( det );   // Layer
878   Int_t        stack = fGeo->GetStack( det );   // Stack
879   Int_t         sect = fGeo->GetSector( det );  // Sector (=iDDL)
880   Int_t         nRow = fGeo->GetRowMax( layer, stack, sect );
881   Int_t         nCol = fGeo->GetColMax( layer );
882   const Int_t kNTBin = fDigitsParam->GetNTimeBins(det);
883   Int_t       kCtype = 0;                       // Chamber type (0:C0, 1:C1)
884   //Int_t          iEv = 0xA;                     // Event ID. Now fixed to 10, how do I get event id?
885
886  
887
888   Bool_t trackletOn = fFee->GetTracklet();     // **new**
889
890   // Check the nCol and nRow.
891   if ((nCol == 144) && 
892       (nRow == 16 || nRow == 12)) {
893     kCtype = (nRow-12) / 4;
894   } 
895   else {
896     AliError(Form("This type of chamber is not supported (nRow=%d, nCol=%d)."
897                  ,nRow,nCol));
898     return 0;
899   }
900
901   AliDebug(1,Form("Producing raw data for sect=%d layer=%d stack=%d side=%d"
902                  ,sect,layer,stack,side));
903
904   AliTRDmcmSim** mcm = new AliTRDmcmSim*[(kCtype + 3)*(fGeo->MCMmax())];
905
906   // in case no tracklet-words are processed: write the tracklet-endmarker as well as all additional words immediately and write 
907   // raw-data in one go; if tracklet-processing is enabled, first all tracklet-words of a half-chamber have to be processed before the
908   // additional words (tracklet-endmarker,headers,...)are written. Raw-data is written in a second loop;
909   
910   if (!trackletOn) {
911       WriteIntermediateWords(buf,nw,of,maxSize,det,side); 
912   }
913   
914   // Scan for ROB and MCM
915   // scanning direction such, that tracklet-words are sorted in ascending z and then in ascending y order
916   // ROB numbering on chamber and MCM numbering on ROB increase with decreasing z and increasing y
917   for (Int_t iRobRow =  (kCtype + 3)-1; iRobRow >= 0; iRobRow-- ) {
918     Int_t iRob = iRobRow * 2 + side;
919     // MCM on one ROB
920     for (Int_t iMcmRB = 0; iMcmRB < fGeo->MCMmax(); iMcmRB++ ) {
921         Int_t iMcm = 16 - 4*(iMcmRB/4 + 1) + (iMcmRB%4);
922         Int_t entry = iRobRow*(fGeo->MCMmax()) + iMcm;
923         
924         mcm[entry] = new AliTRDmcmSim();
925         mcm[entry]->Init( det, iRob, iMcm , newEvent);
926         //mcm[entry]->Init( det, iRob, iMcm);
927         if (newEvent == kTRUE) newEvent = kFALSE; // only one mcm is concerned with new event
928         Int_t padrow = mcm[entry]->GetRow();
929
930         // Copy ADC data to MCM simulator
931         for (Int_t iAdc = 0; iAdc < 21; iAdc++ ) {
932             Int_t padcol = mcm[entry]->GetCol( iAdc );
933             if ((padcol >=    0) && (padcol <  nCol)) {
934                 for (Int_t iT = 0; iT < kNTBin; iT++) { 
935                   mcm[entry]->SetData( iAdc, iT, digits->GetData( padrow, padcol, iT) );
936                 } 
937             } 
938             else {  // this means it is out of chamber, and masked ADC
939                 mcm[entry]->SetDataPedestal( iAdc );
940             }
941         }
942
943         // Simulate process in MCM
944         mcm[entry]->Filter();     // Apply filter
945         mcm[entry]->ZSMapping();  // Calculate zero suppression mapping
946 //jkl   mcm[entry]->CopyArrays();
947 //jkl   mcm[entry]->GeneratefZSM1Dim();
948 //jkl   mcm[entry]->RestoreZeros();
949
950         if (trackletOn) {
951             mcm[entry]->Tracklet(); 
952             Int_t tempNw =  mcm[entry]->ProduceTrackletStream( &buf[nw], maxSize - nw );
953             //Int_t tempNw = 0;
954             if( tempNw < 0 ) {
955                 of += tempNw;
956                 nw += maxSize - nw;
957                 AliError(Form("Buffer overflow detected. Please increase the buffer size and recompile."));
958             } else {
959                 nw += tempNw;
960             }
961         }
962         // no tracklets: write raw-data already in this loop
963         else {
964              // Write MCM data to buffer
965             Int_t tempNw =  mcm[entry]->ProduceRawStream( &buf[nw], maxSize - nw );
966             if( tempNw < 0 ) {
967                 of += tempNw;
968                 nw += maxSize - nw;
969                 AliError(Form("Buffer overflow detected. Please increase the buffer size and recompile."));
970             } else {
971                 nw += tempNw;
972             }
973             
974             delete mcm[entry];
975         }
976             
977         
978
979
980         //mcm->DumpData( "trdmcmdata.txt", "RFZS" ); // debugging purpose
981     }
982   }
983
984   // if tracklets are switched on, raw-data can be written only after all tracklets
985   if (trackletOn) {
986       WriteIntermediateWords(buf,nw,of,maxSize,det,side); 
987   
988   
989       // Scan for ROB and MCM
990       for (Int_t iRobRow =  (kCtype + 3)-1; iRobRow >= 0; iRobRow-- ) {
991           //Int_t iRob = iRobRow * 2 + side;
992           // MCM on one ROB
993           for (Int_t iMcmRB = 0; iMcmRB < fGeo->MCMmax(); iMcmRB++ ) {
994               Int_t iMcm = 16 - 4*(iMcmRB/4 + 1) + (iMcmRB%4);
995               
996               Int_t entry = iRobRow*(fGeo->MCMmax()) + iMcm; 
997               
998               // Write MCM data to buffer
999               Int_t tempNw =  mcm[entry]->ProduceRawStream( &buf[nw], maxSize - nw );
1000               if( tempNw < 0 ) {
1001                   of += tempNw;
1002                   nw += maxSize - nw;
1003                   AliError(Form("Buffer overflow detected. Please increase the buffer size and recompile."));
1004               } else {
1005                   nw += tempNw;
1006               }
1007               
1008               delete mcm[entry];
1009           
1010           }
1011       }
1012   }
1013
1014   delete [] mcm;
1015   
1016   // Write end of raw data marker
1017   if (nw < maxSize) {
1018     buf[nw++] = kEndofrawdatamarker; 
1019   }
1020   else {
1021     of++;
1022   }
1023   if (of != 0) {
1024     AliError("Buffer overflow. Data is truncated. Please increase buffer size and recompile.");
1025   }
1026
1027
1028   return nw;
1029
1030 }
1031
1032 //_____________________________________________________________________________
1033 AliTRDdigitsManager *AliTRDrawData::Raw2Digits(AliRawReader *rawReader)
1034 {
1035   //
1036   // Vx of the raw data reading
1037   //
1038
1039   rawReader->Select("TRD"); //[mj]
1040
1041   AliTRDarrayADC *digits = 0;
1042   AliTRDarrayDictionary *track0 = 0;
1043   AliTRDarrayDictionary *track1 = 0;
1044   AliTRDarrayDictionary *track2 = 0;  
1045
1046   //AliTRDSignalIndex *indexes = 0;
1047   // Create the digits manager
1048   AliTRDdigitsManager* digitsManager = new AliTRDdigitsManager();
1049   digitsManager->CreateArrays();
1050
1051   if (!fTrackletContainer) {
1052     const Int_t kTrackletChmb=256;
1053     fTrackletContainer = new UInt_t *[2];
1054     fTrackletContainer[0] = new UInt_t[kTrackletChmb];
1055     fTrackletContainer[1] = new UInt_t[kTrackletChmb];
1056     memset(fTrackletContainer[0], 0, kTrackletChmb*sizeof(UInt_t)); //jkl
1057     memset(fTrackletContainer[1], 0, kTrackletChmb*sizeof(UInt_t)); //jkl
1058   }
1059
1060   AliTRDrawStreamBase *pinput = AliTRDrawStreamBase::GetRawStream(rawReader);
1061   AliTRDrawStreamBase &input = *pinput;
1062   input.SetRawVersion( fFee->GetRAWversion() ); //<= ADDED by MinJung
1063
1064   AliInfo(Form("Stream version: %s", input.IsA()->GetName()));
1065
1066   // ----- preparing tracklet output -----
1067   AliDataLoader *trklLoader = AliRunLoader::Instance()->GetLoader("TRDLoader")->GetDataLoader("tracklets");
1068   if (!trklLoader) {
1069     //AliInfo("Could not get the tracklets data loader, adding it now!");
1070     trklLoader = new AliDataLoader("TRD.Tracklets.root","tracklets", "tracklets");
1071     AliRunLoader::Instance()->GetLoader("TRDLoader")->AddDataLoader(trklLoader);
1072   }
1073   AliTreeLoader *trklTreeLoader = dynamic_cast<AliTreeLoader*> (trklLoader->GetBaseLoader("tracklets-raw"));
1074   if (!trklTreeLoader) {
1075     trklTreeLoader = new AliTreeLoader("tracklets-raw", trklLoader);
1076     trklLoader->AddBaseLoader(trklTreeLoader);
1077   }
1078
1079   if (!trklTreeLoader->Tree())
1080     trklTreeLoader->MakeTree();
1081
1082   // Loop through the digits
1083   Int_t det    = 0;
1084
1085   while (det >= 0)
1086     {
1087       det = input.NextChamber(digitsManager,fTrackletContainer);
1088
1089       if (*(fTrackletContainer[0]) > 0 || *(fTrackletContainer[1]) > 0) WriteTracklets(det);
1090
1091       if (det >= 0)
1092         {
1093           // get...
1094           digits = (AliTRDarrayADC *) digitsManager->GetDigits(det);
1095           track0 = (AliTRDarrayDictionary *) digitsManager->GetDictionary(det,0);
1096           track1 = (AliTRDarrayDictionary *) digitsManager->GetDictionary(det,1);
1097           track2 = (AliTRDarrayDictionary *) digitsManager->GetDictionary(det,2);
1098           // and compress
1099           if (digits) digits->Compress();  
1100           if (track0) track0->Compress();   
1101           if (track1) track1->Compress();     
1102           if (track2) track2->Compress();
1103         }
1104     }
1105
1106   if (trklTreeLoader)
1107     trklTreeLoader->WriteData("OVERWRITE");
1108   if (trklLoader) 
1109     trklLoader->UnloadAll();
1110
1111   if (fTrackletContainer){
1112     delete [] fTrackletContainer[0];
1113     delete [] fTrackletContainer[1];
1114     delete [] fTrackletContainer;
1115     fTrackletContainer = NULL;
1116   }
1117
1118   delete pinput;
1119   pinput = NULL;
1120
1121   return digitsManager;
1122 }
1123
1124 //_____________________________________________________________________________
1125 void AliTRDrawData::WriteIntermediateWords(UInt_t* buf, Int_t& nw, Int_t& of, const Int_t& maxSize, const Int_t& det, const Int_t& side) {
1126     //
1127     // write half-chamber headers 
1128     //
1129     
1130     Int_t        layer = fGeo->GetLayer( det );   // Layer
1131     Int_t        stack = fGeo->GetStack( det );   // Stack
1132     Int_t         sect = fGeo->GetSector( det );  // Sector (=iDDL)
1133     Int_t           rv = fFee->GetRAWversion();
1134     const Int_t kNTBin = fDigitsParam->GetNTimeBins(det);
1135     UInt_t           x = 0;
1136
1137     // Write end of tracklet marker
1138     if (nw < maxSize) {
1139         buf[nw++] = kEndoftrackletmarker;
1140     } 
1141     else {
1142         of++;
1143     }
1144     
1145   // Half Chamber header
1146   // h[0] (there are 3 HC header)
1147     Int_t minorv = 0;    // The minor version number
1148     Int_t add    = 2;    // The number of additional header words to follow
1149     x = (1<<31) | (rv<<24) | (minorv<<17) | (add<<14) | (sect<<9) | (layer<<6) | (stack<<3) | (side<<2) | 1;
1150     if (nw < maxSize) {
1151         buf[nw++] = x; 
1152     }
1153     else {
1154         of++;
1155     }
1156     // h[1]
1157     Int_t bcCtr   = 99; // bunch crossing counter. Here it is set to 99 always for no reason
1158     Int_t ptCtr   = 15; // pretrigger counter. Here it is set to 15 always for no reason
1159     Int_t ptPhase = 11; // pretrigger phase. Here it is set to 11 always for no reason
1160     x = (bcCtr<<16) | (ptCtr<<12) | (ptPhase<<8) | ((kNTBin-1)<<2) | 1;
1161     if (nw < maxSize) {
1162         buf[nw++] = x; 
1163     }
1164     else {
1165         of++;
1166     }
1167     // h[2]
1168     Int_t pedSetup       = 1;  // Pedestal filter setup (0:1). Here it is always 1 for no reason
1169     Int_t gainSetup      = 1;  // Gain filter setup (0:1). Here it is always 1 for no reason
1170     Int_t tailSetup      = 1;  // Tail filter setup (0:1). Here it is always 1 for no reason
1171     Int_t xtSetup        = 0;  // Cross talk filter setup (0:1). Here it is always 0 for no reason
1172     Int_t nonlinSetup    = 0;  // Nonlinearity filter setup (0:1). Here it is always 0 for no reason
1173     Int_t bypassSetup    = 0;  // Filter bypass (for raw data) setup (0:1). Here it is always 0 for no reason
1174     Int_t commonAdditive = 10; // Digital filter common additive (0:63). Here it is always 10 for no reason
1175     x = (pedSetup<<31) | (gainSetup<<30) | (tailSetup<<29) | (xtSetup<<28) | (nonlinSetup<<27)
1176         | (bypassSetup<<26) | (commonAdditive<<20) | 1;
1177     if (nw < maxSize) {
1178         buf[nw++] = x; 
1179     }
1180     else {
1181         of++;
1182     } 
1183 }
1184
1185 //_____________________________________________________________________________
1186 void AliTRDrawData::WriteIntermediateWordsV2(UInt_t* buf, Int_t& nw, Int_t& of, const Int_t& maxSize, const Int_t& det, const Int_t& side) {
1187     // 
1188     // write tracklet end marker(0x10001000) 
1189     // and half chamber headers(H[0] and H[1])
1190     //
1191     
1192     Int_t        layer = fGeo->GetLayer( det );   // Layer
1193     Int_t        stack = fGeo->GetStack( det );   // Stack
1194     Int_t         sect = fGeo->GetSector( det );  // Sector (=iDDL)
1195     Int_t           rv = fFee->GetRAWversion();
1196     const Int_t kNTBin = fDigitsParam->GetNTimeBins(det);
1197     Bool_t  trackletOn = fFee->GetTracklet();
1198     UInt_t           x = 0;
1199
1200     // Write end of tracklet marker
1201         if (nw < maxSize){
1202         buf[nw++] = fgkEndOfTrackletMarker;
1203         buf[nw++] = fgkEndOfTrackletMarker;     // the number of tracklet end marker should be more than 2
1204     }
1205     else {
1206         of++;
1207     }
1208
1209    
1210         // Half Chamber header
1211         // h[0] (there are 2 HC headers) xmmm mmmm nnnn nnnq qqss sssp ppcc ci01
1212         //      , where  x : Raw version speacial number (=1)
1213         //                   m : Raw version major number (test pattern, ZS, disable tracklet, 0, options)
1214         //                   n : Raw version minor number
1215         //                   q : number of addtional header words (default = 1)
1216         //                   s : SM sector number (ALICE numbering)
1217         //                   p : plane(layer) number
1218         //                       c : chamber(stack) number
1219         //                       i : side number (0:A, 1:B)
1220         Int_t majorv = 0;       // The major version number 
1221     Int_t minorv = 0;   // The minor version number
1222     Int_t add    = 1;   // The number of additional header words to follow : now 1, previous 2
1223         Int_t tp         = 0;   // test pattern (default=0)
1224         Int_t zs         = (rv==3) ? 1 : 0;                     // zero suppression
1225         Int_t dt         = (trackletOn) ? 0 : 1;        // disable tracklet 
1226
1227         majorv = (tp<<6) | (zs<<5) | (dt<<4) | 1;       // major version
1228
1229     x = (1<<31) | (majorv<<24) | (minorv<<17) | (add<<14) | (sect<<9) | (layer<<6) | (stack<<3) | (side<<2) | 1;
1230     if (nw < maxSize) buf[nw++] = x; else of++;
1231    
1232     // h[1]             tttt ttbb bbbb bbbb bbbb bbpp pphh hh01
1233         // , where  t : number of time bins
1234         //          b : bunch crossing number
1235         //          p : pretrigger counter
1236         //          h : pretrigger phase
1237     Int_t bcCtr   = 99; // bunch crossing counter. Here it is set to 99 always for no reason
1238     Int_t ptCtr   = 15; // pretrigger counter. Here it is set to 15 always for no reason
1239     Int_t ptPhase = 11; // pretrigger phase. Here it is set to 11 always for no reason
1240     //x = (bcCtr<<16) | (ptCtr<<12) | (ptPhase<<8) | ((kNTBin-1)<<2) | 1;       // old format
1241     x = ((kNTBin)<<26) | (bcCtr<<10) | (ptCtr<<6) | (ptPhase<<2) | 1;
1242     if (nw < maxSize) buf[nw++] = x; else of++;
1243   
1244 }
1245
1246 //_____________________________________________________________________________
1247 Bool_t AliTRDrawData::WriteTracklets(Int_t det)
1248 {
1249   //
1250   // Write the raw data tracklets into seperate file
1251   //
1252
1253   UInt_t **leaves = new UInt_t *[2];
1254   for (Int_t i=0; i<2 ;i++){
1255     leaves[i] = new UInt_t[258];
1256     leaves[i][0] = det; // det
1257     leaves[i][1] = i;   // side
1258     memcpy(leaves[i]+2, fTrackletContainer[i], sizeof(UInt_t) * 256);
1259   }
1260
1261   if (!fTrackletTree){
1262     AliDataLoader *dl = fRunLoader->GetLoader("TRDLoader")->GetDataLoader("tracklets");
1263     dl->MakeTree();
1264     fTrackletTree = dl->Tree();
1265   }
1266
1267   TBranch *trkbranch = fTrackletTree->GetBranch("trkbranch");
1268   if (!trkbranch) {
1269     trkbranch = fTrackletTree->Branch("trkbranch",leaves[0],"det/i:side/i:tracklets[256]/i");
1270   }
1271
1272   for (Int_t i=0; i<2; i++){
1273     if (leaves[i][2]>0) {
1274       trkbranch->SetAddress(leaves[i]);
1275       fTrackletTree->Fill();
1276     }
1277   }
1278
1279   //  AliDataLoader *dl = fRunLoader->GetLoader("TRDLoader")->GetDataLoader("tracklets"); //jkl: wrong
1280   //  dl->WriteData("OVERWRITE"); //jkl: wrong
1281   //dl->Unload();
1282   delete [] leaves;
1283
1284   return kTRUE;
1285 }