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