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