]> git.uio.no Git - u/mrichter/AliRoot.git/blob - TPC/AliTPCAltroEmulator.cxx
Secure codin - overruns corrected.
[u/mrichter/AliRoot.git] / TPC / AliTPCAltroEmulator.cxx
1 /**             @file Altro.C
2  *      @brief The Altro class implements the Altro digital Chain in C++
3  *
4  *      This Class represents a C++ version of the ALTRO. For a complete Documentation of the Altro
5  *      Look at : http://ep-ed-alice-tpc.web.cern.ch/ep-ed-alice-tpc/altro_chip.htm\n
6  *      Due to the fact that the real ALTRO constantly samples in between the recorded events,
7  *      it has the knowledge on what happened in the period. This affects the BSL1, TCF and BSL2 module.
8  *      In the BSL1 the ALTRO follows slow baseline drifts e.g. temperature change, the TCF has a infinite
9  *      (IIR Filter) memory of "old samples" i.e. a cluster at the start of a readout cycle will be treated
10  *      differently, and the BSL2 has a 8 step pipeline. The ALTRO Class can't emulate this behavior,
11  *      since the data is not recorded.\n
12  *
13  *      @author Roland Bramm
14  *      @version $LastChangedRevision: 688 $
15  *      @date    $LastChangedDate: 2005-12-16 14:07:11 +0100 (Fri, 16 Dec 2005) $
16  *
17  *      \verbinclude Altro/Altro.C.log
18  *
19  */
20
21 /////////////////////////////////////////////////////////////////////////////////////////////////////
22 //     Class for emulation of the ALTRO chip (Altro digital Chain) in C++                          //
23 //     Author: Roland Bramm                                                                        //
24 //                                                                                                 //
25 //     NOTE: This class has been modified to be conform with the coding conventions of the         //
26 //           ALICE Off-line Project. Keywords for setting the mode of BSC1 were modified           //
27 //           and are shown in the header file ...                                                  //
28 //                           Stefan Rossegger, 8th february 2008                                   //
29 /////////////////////////////////////////////////////////////////////////////////////////////////////
30
31 #include <AliTPCAltroEmulator.h>
32 #include <TH1F.h>
33 #include <TMath.h>
34 #include <TSystem.h>
35 #include <AliDAQ.h>
36 #include <AliRawReader.h>
37 #include <AliRawVEvent.h>
38 #include <AliRawData.h>
39 #include <AliRawVEquipment.h>
40 #include <AliRawEquipmentHeader.h>
41 #include <AliTPCRawStreamV3.h>
42 #include <TCanvas.h>
43
44
45 /**     @brief Consturctor of Altro Class
46  *
47  *      Consturctor of Altro Class, some variables are set.\n
48  *      The input Data is altered, so after running the complete emulation you have the
49  *      Altro Processed Data in the Channel Pointer.\n
50  *
51  *      @param timebins an <tt> int </tt> sets the length of the input Data (Channel)
52  *      @param Channel an <tt> short* </tt> Pointer to a 1d Short_tArray with the input Data
53  */
54
55
56 ClassImp(AliTPCAltroEmulator)
57
58 AliTPCAltroEmulator::AliTPCAltroEmulator(Int_t timebins, short* Channel) : 
59   TNamed(),
60   ftimebins(timebins),
61 //  fChannelIn(Channel),
62   fChannelShort(Channel), 
63   fADCkeep(0),     
64   fOnBSL1(0), 
65   fOnTCF(0),  
66   fOnBSL2(0), 
67   fOnClip(0), 
68   fOnZSU(0),  
69
70   fConfiguredAltro(0),   // ConfiguredAltro
71   fConfiguredBSL1(0),    // ConfiguredBSL1
72   fConfiguredTCF(0),     // ConfiguredTCF
73   fConfiguredTCFraw(0),     // ConfiguredTCF
74   fConfiguredBSL2(0),    // ConfiguredBSL2
75   fConfiguredZSU(0),     // ConfiguredZSU
76   fBSL1mode(0),          // BSL1mode
77   fBSL1ValuePeDestal(0), // BSL1ValuePeDestal
78   fBSL1PedestalMem(0),   // BSL1PedestalMem
79   fBSL1polarity(0),      // BSL1polarity
80
81   fTCFK1(0), // K1
82   fTCFK2(0), // K2
83   fTCFK3(0), // K3
84   fTCFL1(0), // L1
85   fTCFL2(0), // L2
86   fTCFL3(0), // L3
87
88   fTCFK1Int(0), // K1Int
89   fTCFK2Int(0), // K2Int
90   fTCFK3Int(0), // K3Int
91   fTCFL1Int(0), // L1Int
92   fTCFL2Int(0), // L2Int
93   fTCFL3Int(0), // L3Int
94
95   fBSL2HighThreshold(0), // BSL2HighThreshold
96   fBSL2LowThreshold(0),  // BSL2LowThreshold
97   fBSL2Offset(0),        // BSL2Offset
98   fBSL2Presamples(0),    // BSL2Presamples(0),
99   fBSL2Postsamples(0),   // BSL2Postsamples
100
101   fZSUThreshold(0),      // ZSUThreshold
102
103   fZSUMinSamplesaboveThreshold(0), // ZSUMinSamplesaboveThreshold
104   fZSUPresamples(0),     // ZSUPresamples
105   fZSUPostsamples(0),     // ZSUPostsamples
106   
107   fReader(0),           // for Altro Emulation on Raw Reader
108   fDecoder(0),
109   fRunNumber(0), 
110   fDDLFolderName("./"),
111   fOutputDateFileName("./tmpRaw.date"),
112   fOutputRootFileName("./tmpRaw.root"),
113   fIsRandom(kTRUE),
114   fChannels(0),
115   fCDHs(0),
116   fADCs(0),
117   fTrailers(0),
118   fRawData(0) {
119   //
120   // Constructor of Altro Class
121   //
122
123   fADCkeep = new Short_t[1024]; 
124
125   fTCFK1IntROC[0]=0; fTCFK1IntROC[1]=0; // dummy defaults
126   fTCFK2IntROC[0]=0; fTCFK2IntROC[1]=0; // dummy defaults
127   fTCFK3IntROC[0]=0; fTCFK3IntROC[1]=0; // dummy defaults
128   fTCFL1IntROC[0]=0; fTCFL1IntROC[1]=0; // dummy defaults
129   fTCFL2IntROC[0]=0; fTCFL2IntROC[1]=0; // dummy defaults
130   fTCFL3IntROC[0]=0; fTCFL3IntROC[1]=0; // dummy defaults
131
132 }
133
134
135
136 /**     @brief Destructor of Altro Class
137  *
138  *      Destructor of Altro Class\n
139  */
140 AliTPCAltroEmulator::~AliTPCAltroEmulator() {
141   //
142   // Destructor of Altro Class
143   //
144
145   //  if(fConfiguredZSU == 1)
146   delete[] fADCkeep;
147
148   delete[] fChannels;
149   delete[] fCDHs    ;
150   delete[] fADCs    ;
151   delete[] fTrailers;
152   delete[] fRawData ;
153   delete fDecoder   ;
154
155 }
156
157
158 /**  @brief Configures which modules of the Altro should be on.
159  *
160  *      Configures which modules of the Altro should be on. Each of the modules
161  *      which are configured to be on, have to be configured later before running
162  *      the emulation!\n
163  *
164  *      @param ONBaselineCorrection1 an <tt> Int_t </tt> Switch (0,1) to turn on the Base Line Correction 1 (BSL1) Module
165  *      @param ONTailcancellation an <tt> Int_t </tt> Switch (0,1) to turn on the Tail Cancellation Filter (TCF) Module
166  *      @param ONBaselineCorrection2 an <tt> Int_t </tt> Switch (0,1) to turn on the Moving Average Filter (BSL2) Module
167  *      @param ONClipping an <tt> Int_t </tt> Switch (0,1) to turn on the Clipping Module. This is not possible in the real Altro, there it is always on.
168  *      @param ONZerosuppression an <tt> Int_t </tt> Switch (0,1) to turn on the Zero Suppression (ZSU) Module
169  *      @param ONDataFormatting an <tt> Int_t </tt> Switch (0,1) to turn on the Data Formatting on (not implemented)
170  */
171 void AliTPCAltroEmulator::ConfigAltro(Int_t ONBaselineCorrection1, Int_t ONTailcancellation, Int_t ONBaselineCorrection2, Int_t ONClipping, Int_t ONZerosuppression, Int_t ONDataFormatting){
172   //
173   // Configures which modules of the Altro should be on 
174   //
175   fOnBSL1 = InRange(ONBaselineCorrection1,0,1,"AliTPCAltroEmulator::ConfigAltro","ONBaselineCorrection1");
176   fOnTCF  = InRange(ONTailcancellation,0,1,"AliTPCAltroEmulator::ConfigAltro","ONTailcancellation");
177   fOnBSL2 = InRange(ONBaselineCorrection2,0,1,"AliTPCAltroEmulator::ConfigAltro","ONBaselineCorrection2");
178   fOnClip = InRange(ONClipping,0,1,"AliTPCAltroEmulator::ConfigAltro","ONClipping");
179   fOnZSU = InRange(ONZerosuppression,0,1,"AliTPCAltroEmulator::ConfigAltro","ONZerosuppression");
180   fConfiguredAltro = 1;
181   if (!fConfiguredAltro) { //dummy code to avoid warning
182     printf("%d\n",ONDataFormatting); // does not have to be checked
183   }
184 }
185
186 /**  @brief Configures the Base Line Correction 1 (BSL1) Module
187  *
188  *      Configures the Base Line Correction 1 (BSL1) Module. You dont have to build a proper pedestalMemory
189  *      array, a pointer of the correct type is enough, of course you are not allowed to use Basline
190  *      Correction Modes which need then the array ...\n
191  *      All configurable values are "Range checked" and if out of the Range set to the nearest extreme.
192  *      So the Emulation will work, but the result is maybe not the expected one.
193  *
194  *      @param mode an <tt> Int_t </tt> sets the mode of the Baseline Correction. See the Altro manual for a description
195  *      @param ValuePeDestal an <tt> Int_t </tt> this is the baseline of the Channel.
196  *      @param PedestalMem an <tt> *Int_t </tt> Pointer to a 1d Short_t Array with the pedestal memory Data
197  *      @param polarity an <tt> Int_t </tt> Switch (0,1) for the polarity
198  */
199 void AliTPCAltroEmulator::ConfigBaselineCorrection1(Int_t mode, Int_t ValuePeDestal, Int_t *PedestalMem, Int_t polarity){
200   //
201   // Configures the Base Line Correction 1 (BSL1) Module
202   //
203   fBSL1mode          = InRange(mode,0,16,"AliTPCAltroEmulator::ConfigBaselineCorrection1","mode");
204   fBSL1ValuePeDestal = InRange(ValuePeDestal,0,1023,"AliTPCAltroEmulator::BaselineCorrection1","ValuePeDestal");
205   fBSL1PedestalMem = PedestalMem;
206   fBSL1polarity = InRange(polarity,0,1,"AliTPCAltroEmulator::BaselineCorrection1","polarity");
207   fConfiguredBSL1 = 1;
208 }
209
210 /**  @brief Configures the Tail Cancellation Filter (TCF) Module
211  *
212  *      Configures the Tail Cancellation Filter (TCF) Module. You have to set the coefficients in the
213  *      Integer version.\n
214  *      To convert from Int_t to Float_t use (int)*(pow(2,-16)-1)
215  *      To convert from Float_t to Int_t usw (Float_t)*(pow(2,16)-1)
216  *      All configurable values are "Range checked" and if out of the Range set to the nearest extreme.
217  *      So the Emulation will work, but the result is maybe not the expected one.
218  *
219  *      @param K1 an <tt> Int_t </tt> sets the K1 coeeficient of the TCF
220  *      @param K2 an <tt> Int_t </tt> sets the K2 coeeficient of the TCF
221  *      @param K3 an <tt> Int_t </tt> sets the K3 coeeficient of the TCF
222  *      @param L1 an <tt> Int_t </tt> sets the L1 coeeficient of the TCF
223  *      @param L2 an <tt> Int_t </tt> sets the L2 coeeficient of the TCF
224  *      @param L3 an <tt> Int_t </tt> sets the L3 coeeficient of the TCF
225  */
226 void AliTPCAltroEmulator::ConfigTailCancellationFilter(Int_t K1, Int_t K2, Int_t K3, Int_t L1, Int_t L2, Int_t L3){
227   //
228   // Configures the Tail Cancellation Filter (TCF) Module
229   //
230   // conf from Int_t to fp:  (int)*(pow(2,-16)-1)
231   //             backway:  (Float_t)*(pow(2,16)-1)
232   fTCFK1Int = InRange(K1,0,65535,"AliTPCAltroEmulator::ConfigTailCancellationFilter","K1");
233   fTCFK2Int = InRange(K2,0,65535,"AliTPCAltroEmulator::ConfigTailCancellationFilter","K2");
234   fTCFK3Int = InRange(K3,0,65535,"AliTPCAltroEmulator::ConfigTailCancellationFilter","K3");
235   
236   fTCFL1Int = InRange(L1,0,65535,"AliTPCAltroEmulator::ConfigTailCancellationFilter","L1");
237   fTCFL2Int = InRange(L2,0,65535,"AliTPCAltroEmulator::ConfigTailCancellationFilter","L2");
238   fTCFL3Int = InRange(L3,0,65535,"AliTPCAltroEmulator::ConfigTailCancellationFilter","L3");
239   fConfiguredTCF = 1;
240 }
241 void AliTPCAltroEmulator::ConfigTailCancellationFilterForRAWfiles(const Int_t *K1, const Int_t *K2, const Int_t *K3, 
242                                                                   const Int_t *L1, const Int_t *L2, const Int_t *L3){
243   //
244   // Configures the Tail Cancellation Filter (TCF) Module - Different settings for IROC and OROC
245   //
246   // conf from Int_t to fp:  (int)*(pow(2,-16)-1)
247   //             backway:  (Float_t)*(pow(2,16)-1)
248
249   // IROC
250   fTCFK1IntROC[0] = InRange(K1[0],0,65535,"AliTPCAltroEmulator::ConfigTailCancellationFilter","K1[0]");
251   fTCFK2IntROC[0] = InRange(K2[0],0,65535,"AliTPCAltroEmulator::ConfigTailCancellationFilter","K2[0]");
252   fTCFK3IntROC[0] = InRange(K3[0],0,65535,"AliTPCAltroEmulator::ConfigTailCancellationFilter","K3[0]");
253   fTCFL1IntROC[0] = InRange(L1[0],0,65535,"AliTPCAltroEmulator::ConfigTailCancellationFilter","L1[0]");
254   fTCFL2IntROC[0] = InRange(L2[0],0,65535,"AliTPCAltroEmulator::ConfigTailCancellationFilter","L2[0]");
255   fTCFL3IntROC[0] = InRange(L3[0],0,65535,"AliTPCAltroEmulator::ConfigTailCancellationFilter","L3[0]");
256   // OROC
257   fTCFK1IntROC[1] = InRange(K1[1],0,65535,"AliTPCAltroEmulator::ConfigTailCancellationFilter","K1[1]");
258   fTCFK2IntROC[1] = InRange(K2[1],0,65535,"AliTPCAltroEmulator::ConfigTailCancellationFilter","K2[1]");
259   fTCFK3IntROC[1] = InRange(K3[1],0,65535,"AliTPCAltroEmulator::ConfigTailCancellationFilter","K3[1]");
260   fTCFL1IntROC[1] = InRange(L1[1],0,65535,"AliTPCAltroEmulator::ConfigTailCancellationFilter","L1[1]");
261   fTCFL2IntROC[1] = InRange(L2[1],0,65535,"AliTPCAltroEmulator::ConfigTailCancellationFilter","L2[1]");
262   fTCFL3IntROC[1] = InRange(L3[1],0,65535,"AliTPCAltroEmulator::ConfigTailCancellationFilter","L3[1]");
263
264
265   fConfiguredTCFraw = 1;
266 }
267
268
269 /**  @brief Configures the Moving Average Filter (BSL2) Module
270  *
271  *      Configures the Moving Average Filter (BSL2) Module.
272  *      All configurable values are "Range checked" and if out of the Range set to the nearest extreme.
273  *      So the Emulation will work, but the result is maybe not the expected one.
274  *
275  *      @param HighThreshold an <tt> Int_t </tt> sets the high Threshold
276  *      @param LowThreshold an <tt> Int_t </tt> sets the low Theshold
277  *      @param Offset an <tt> Int_t </tt> sets the the offset which is added to the Signal
278  *      @param Presamples an <tt> Int_t </tt> sets the number of pre samples excluded from the moving average caclulation
279  *      @param Postsamples an <tt> Int_t </tt> sets the number of post samples excluded from the moving average caclulation
280  */
281 void AliTPCAltroEmulator::ConfigBaselineCorrection2(Int_t HighThreshold, Int_t LowThreshold, Int_t Offset, Int_t Presamples, Int_t Postsamples){
282   //
283   // Configures the Moving Average Filter (BSL2) Module
284   //
285   fBSL2HighThreshold = InRange(HighThreshold,0,1023,"AliTPCAltroEmulator::ConfigBaselineCorrection2","HighThreshold");
286   fBSL2LowThreshold  = InRange(LowThreshold,0,1023,"AliTPCAltroEmulator::ConfigBaselineCorrection2","LowThreshold");
287   fBSL2Offset        = InRange(Offset,0,1023,"AliTPCAltroEmulator::ConfigBaselineCorrection2","Offset");
288   fBSL2Presamples    = InRange(Presamples,0,3,"AliTPCAltroEmulator::ConfigBaselineCorrection2","Presamples");
289   fBSL2Postsamples   = InRange(Postsamples,0,15,"AliTPCAltroEmulator::ConfigBaselineCorrection2","Postsamples");
290   fConfiguredBSL2 = 1;
291 }
292
293 /**  @brief Configures the Zero Suppression Module (ZSU)
294  *
295  *      Configures the Zero Suppression Module (ZSU).
296  *      All configurable values are "Range checked" and if out of the Range set to the nearest extreme.
297  *      So the Emulation will work, but the result is maybe not the expected one.
298  *
299  *      @param Threshold an <tt> Int_t </tt> sets the Threshold
300  *      @param MinSamplesaboveThreshold an <tt> Int_t </tt> sets the minimum number of samples which have to be greater than the threshold
301  *      @param Presamples an <tt> Int_t </tt> sets the number of pre samples which are kept
302  *      @param Postsamples an <tt> Int_t </tt> sets the number of post samples which are kept
303  */
304 void AliTPCAltroEmulator::ConfigZerosuppression(Int_t Threshold, Int_t MinSamplesaboveThreshold, Int_t Presamples, Int_t Postsamples){
305   //
306   // Configures the Zero Suppression Module (ZSU)
307   //
308   fZSUThreshold                = InRange(Threshold,0,1023,"AliTPCAltroEmulator::BaselineCorrection1","Threshold");
309   fZSUMinSamplesaboveThreshold = InRange(MinSamplesaboveThreshold,1,3,"AliTPCAltroEmulator::BaselineCorrection1","MinSamplesaboveThreshold");
310   fZSUPresamples               = InRange(Presamples,0,3,"AliTPCAltroEmulator::BaselineCorrection1","Presamples");
311   fZSUPostsamples              = InRange(Postsamples,0,7,"AliTPCAltroEmulator::BaselineCorrection1","Postsamples");
312   
313   for(Int_t i = 0; i < ftimebins; i++){
314     fADCkeep[i] = 0;
315   }
316   fConfiguredZSU = 1;
317 }
318
319 /**  @brief Prints the set Parameters, if module is configured
320  *
321  *      Prints the set Parameters, if module is configured.
322  */
323 void AliTPCAltroEmulator::PrintParameters(){
324   //
325   // Prints the set Parameters, if module is configured
326   //
327   cout << "+-------------------------------------------+" << endl;
328   cout << "| Configured Parameters of the Altro Module |" << endl;
329   cout << "+-------------------------------------------+" << endl << endl;
330   
331   cout << "Parameters set in the Altro Modules:" << endl << endl;
332   cout << "ONBaselineCorrection1: " << fOnBSL1 << endl;
333   cout << "ONTailcancellation   : " << fOnTCF << endl;
334   cout << "ONBaselineCorrection2: " << fOnBSL2 << endl;
335   cout << "ONClipping           : " << fOnClip << endl;
336   cout << "ONZerosuppression    : " << fOnZSU << endl << endl << endl;
337   if(fConfiguredBSL1 == 1){
338     cout << "Parameters set in the BSL1 (Baseline Correction 1) Module:" << endl << endl;
339     cout << "mode                 : " << fBSL1mode << endl;
340     cout << "ValuePeDestal        : " << fBSL1ValuePeDestal << endl;
341     cout << "polarity             : " << fBSL1ValuePeDestal << endl << endl << endl;
342   }else{
343     cout << "BSL1 (Baseline Correction 1) Module not configured!" << endl << endl << endl;
344   }
345   if(fConfiguredTCF == 1){
346     cout << "Parameters set in the TCF (TailCancellation Filter) Module:" << endl << endl;
347     cout << "K1       (int|Float_t) : " << fTCFK1Int << " | " << fTCFK1Int/(Float_t)((1<<16)-1) << endl;
348     cout << "K2       (int|Float_t) : " << fTCFK2Int << " | " << fTCFK2Int/(Float_t)((1<<16)-1) << endl;
349     cout << "K3       (int|Float_t) : " << fTCFK3Int << " | " << fTCFK3Int/(Float_t)((1<<16)-1) << endl;
350     cout << "L1       (int|Float_t) : " << fTCFL1Int << " | " << fTCFL1Int/(Float_t)((1<<16)-1) << endl;
351     cout << "L2       (int|Float_t) : " << fTCFL2Int << " | " << fTCFL2Int/(Float_t)((1<<16)-1) << endl;
352     cout << "L3       (int|Float_t) : " << fTCFL3Int << " | " << fTCFL3Int/(Float_t)((1<<16)-1) << endl << endl << endl;
353   }else{
354     cout << "TCF (TailCancellation Filter) Module not configured!" << endl << endl << endl;
355   }
356   if(fConfiguredBSL2 == 1){
357     cout << "Parameters set in the BSL2 (Baseline Correction 2) Module:" << endl << endl;
358     cout << "HighThreshold        : " << fBSL2HighThreshold << endl;
359     cout << "LowThreshold         : " << fBSL2LowThreshold << endl;
360     cout << "Offset               : " << fBSL2Offset << endl;
361     cout << "Presamples           : " << fBSL2Presamples << endl;
362     cout << "Postsamples          : " << fBSL2Postsamples << endl << endl << endl;
363   }else{
364     cout << "BSL2 (Baseline Correction 2) Module not configured!" << endl << endl << endl;
365   }
366   if(fConfiguredZSU == 1){
367     cout << "Parameters set in the ZSU (Zero Suppression Unit) Module:" << endl << endl;
368     cout << "Threshold            : " << fZSUThreshold << endl;
369     cout << "MinSampaboveThreshold: " << fZSUMinSamplesaboveThreshold << endl;
370     cout << "Presamples           : " << fZSUPresamples << endl;
371     cout << "Postsamples          : " << fZSUPostsamples << endl << endl << endl;
372   }else{
373     cout << "ZSU (Zero Suppression Unit) Module not configured!" << endl << endl << endl;
374   }
375 }
376
377
378 void AliTPCAltroEmulator::SetChannelData(Int_t timebins, Short_t* channelData) {
379   //
380   // Set channel data, for example a new channel
381   //
382
383   ftimebins = timebins;
384   fChannelShort = channelData;
385
386 }
387  
388
389 /**  @brief Runs the emulation of all configured Modules.
390  *
391  *      Runs the emulation of all configured Modules. This changes then the content of the
392  *      input Array
393  */
394 void AliTPCAltroEmulator::RunEmulation(Int_t roc){
395   //
396   // Runs the emulation of all configured Modules.
397   //
398
399   if (!fChannelShort) {
400     printf("ERROR cant run Altro Emulation: Channel input not set.\nUse for example: SetChannelData(Int_t timebins, Short_t* Channel)\n");
401     return;
402   }
403
404   //cout << "AliTPCAltroEmulator::RunEmulation | start" << endl;
405   if(fConfiguredAltro == 0){
406     cout << "ERROR cant run Altro Emulation because not configured" << endl;
407     return;
408   }
409   
410   //cout << "AliTPCAltroEmulator::RunEmulation | start BSL1 on: " << fOnBSL1 << " configures: " << fConfiguredBSL1 << endl;
411   if(fOnBSL1 == 1){
412     if(fConfiguredBSL1 == 1){
413       BaselineCorrection1(fBSL1mode, fBSL1ValuePeDestal, fBSL1PedestalMem, fBSL1polarity);
414     }else{
415       cout << "ERROR cant run Baseline Correction 1 because not configured" << endl;
416       return;
417     }
418   }
419   
420   //cout << "AliTPCAltroEmulator::RunEmulation | start TCF on: " << fOnTCF << " configures: " << fConfiguredTCF << endl;
421   if(fOnTCF == 1){
422     if (roc==-1) { // use one set of TCF params
423       if(fConfiguredTCF == 1){
424         TailCancellationFilterFixedPoint(fTCFK1Int, fTCFK2Int, fTCFK3Int, fTCFL1Int, fTCFL2Int, fTCFL3Int);
425       }else{
426         cout << "ERROR cant run Tail Cancellation Filter because not configured" << endl;
427         return;
428       }
429     } else { // use different TCF params for IROC and OROC
430       if(fConfiguredTCFraw == 1){
431         if (roc==0)      //IROC
432           TailCancellationFilterFixedPoint(fTCFK1IntROC[0], fTCFK2IntROC[0], fTCFK3IntROC[0], 
433                                            fTCFL1IntROC[0], fTCFL2IntROC[0], fTCFL3IntROC[0]);
434         else if (roc==1) // OROC
435           TailCancellationFilterFixedPoint(fTCFK1IntROC[1], fTCFK2IntROC[1], fTCFK3IntROC[1], 
436                                            fTCFL1IntROC[1], fTCFL2IntROC[1], fTCFL3IntROC[1]);
437         else
438           cout << "ERROR cant run Tail Cancellation Filter because TCF settings for ROC not found" << endl;
439       } else {
440         cout << "ERROR cant run Tail Cancellation Filter because not configured (for RAW data files!)" << endl;
441         return;
442       }
443
444     }
445   }
446   
447   //cout << "AliTPCAltroEmulator::RunEmulation | start BSL2 on: " << fOnBSL2 << " configures: " << fConfiguredBSL2 << endl;
448   if(fOnBSL2 == 1){
449     if(fConfiguredBSL2 == 1){
450       BaselineCorrection2RTL(fBSL2HighThreshold, fBSL2LowThreshold, fBSL2Offset, fBSL2Presamples, fBSL2Postsamples);
451     }else{
452       cout << "ERROR cant run Baseline Correction 2 because not configured" << endl;
453       return;
454     }
455   }
456   //cout << "AliTPCAltroEmulator::RunEmulation | start CLIP on: " << fOnClip << endl;
457   if(fOnClip == 1){
458     Clipping();
459   }
460   //cout << "AliTPCAltroEmulator::RunEmulation | start ZSU on: " << fOnZSU << " configures: " << fConfiguredZSU << endl;
461   if(fOnZSU == 1){
462     if(fConfiguredZSU == 1){
463       Zerosuppression(fZSUThreshold,fZSUMinSamplesaboveThreshold,fZSUPresamples,fZSUPostsamples);
464     }else{
465       cout << "ERROR cant run Zero Suppression Unit because not configured" << endl;
466       return;
467     }
468   }
469
470   
471
472 }
473
474 void AliTPCAltroEmulator::BaselineCorrection1(Int_t mode, Int_t ValuePeDestal, Int_t *PedestalMem, Int_t polarity){
475   //
476   // BaselineCorrection1
477   //
478
479   //VPD == 0 !!
480   Int_t fixedPeDestal = 0;
481
482   // take first and last bins to calculate a mean pedestal value
483   Int_t window = 3;
484   Int_t meanPeDestal = 0;
485   if (mode == kDINxMPD && ftimebins>=6) {
486     for(Int_t i = 0; i < window; i++) {
487       meanPeDestal += fChannelShort[i];
488       meanPeDestal += fChannelShort[ftimebins-1-i];
489     }
490     meanPeDestal /= (window*2);
491   }
492     
493   if(polarity ==1){
494     for(Int_t i = 0; i < ftimebins; i++){
495       fChannelShort[i]  = 1023 - fChannelShort[i];
496     }
497   }
498   
499   switch(mode) {
500   case kDINxFPD:
501     for(Int_t i = 0; i < ftimebins; i++)
502       fChannelShort[i]  = fChannelShort[i]  - fixedPeDestal;
503     break;
504   case kDINxFT:
505     for(Int_t i = 0; i < ftimebins; i++)
506       fChannelShort[i]  = fChannelShort[i]  - PedestalMem[i];
507     break;
508   case kDINxFDIN:
509     for(Int_t i = 0; i < ftimebins; i++)
510       fChannelShort[i]  = fChannelShort[i]  - PedestalMem[ fChannelShort[i] ];
511     break;
512   case kDINxFDINxVPD:
513     for(Int_t i = 0; i < ftimebins; i++)
514       fChannelShort[i]  = fChannelShort[i]  - PedestalMem[ fChannelShort[i] - ValuePeDestal];
515     break;
516   case kDINxVPDxFPD:
517     for(Int_t i = 0; i < ftimebins; i++)
518       fChannelShort[i]  = fChannelShort[i]  - ValuePeDestal - fixedPeDestal;
519     break;
520   case kDINxVPDxFT:
521     for(Int_t i = 0; i < ftimebins; i++)
522       fChannelShort[i]  = fChannelShort[i]  - ValuePeDestal - PedestalMem[i];
523     break;
524   case kDINxVPDxFDIN:
525     for(Int_t i = 0; i < ftimebins; i++)
526       fChannelShort[i]  = fChannelShort[i]  - ValuePeDestal - PedestalMem[ fChannelShort[i] ];
527     break;
528   case kDINxVPDxFDINxVPD:
529     for(Int_t i = 0; i < ftimebins; i++)
530       fChannelShort[i]  = fChannelShort[i]  - ValuePeDestal - PedestalMem[ fChannelShort[i] - ValuePeDestal ];
531     break;
532   case kFDINxFPD:
533     for(Int_t i = 0; i < ftimebins; i++)
534       fChannelShort[i]  = PedestalMem[ fChannelShort[i] ] - fixedPeDestal;
535     break;
536   case kFDINxVPDxFPD:
537     for(Int_t i = 0; i < ftimebins; i++)
538       fChannelShort[i]  = PedestalMem[ fChannelShort[i] - ValuePeDestal ] - fixedPeDestal;
539     break;
540   case kFTxFPD:
541     for(Int_t i = 0; i < ftimebins; i++)
542       fChannelShort[i]  = PedestalMem[i] - fixedPeDestal;
543     break;
544   case kDINxMPD:
545     for(Int_t i = 0; i < ftimebins; i++)
546       fChannelShort[i]  = fChannelShort[i] - meanPeDestal;
547     break;
548   }
549 }
550
551 Int_t AliTPCAltroEmulator::Multiply36(Int_t P, Int_t N){
552   //
553   // multiply function to emulate the 36 bit fixed point multiplication of the Altro.
554   //
555   long long retval =0;
556   long long temp = 0;
557   long long vAX = 0;
558   temp = (long long)P*(long long)N;
559   vAX = (( Mask(temp,35,18) + ((long long)(-P)<<18) ) + Mask(temp,17,0));
560   if ( Maskandshift(N,17,17) == 1){
561     retval = ((Maskandshift(vAX,35,35)<<17) + Maskandshift(vAX,32,16));
562   }else{
563     retval = Maskandshift(temp,32,16);
564   }
565   return retval;
566 }
567 long long AliTPCAltroEmulator::Mask(long long in, Int_t left, Int_t right){
568   //
569   // mask
570   //
571   long long retval;
572   long long pattern;
573   long long length = abs(left - right)+1;
574   pattern = ((1<<length)-1)<<right;
575   retval = in&pattern;
576   return retval;
577 }
578
579 long long AliTPCAltroEmulator::Maskandshift(long long in, Int_t left, Int_t right){
580   //
581   // maskandshift
582   //
583   long long retval;
584   long long pattern;
585   long long length = abs(left - right)+1;
586   pattern = ((1<<length)-1);
587   retval = (in>>right)&pattern;
588   return retval;
589 }
590
591 void AliTPCAltroEmulator::TailCancellationFilterFixedPoint(Int_t K1, Int_t K2, Int_t K3, Int_t L1, Int_t L2, Int_t L3){
592   //
593   // TailCancellationFilterFixedPoint
594   //
595   Int_t c1n = 0, c2n = 0, c3n = 0;
596   Int_t c1o = 0, c2o = 0, c3o = 0;
597   Int_t d1  = 0, d2  = 0;
598   Int_t dout = 0;
599   Int_t din = 0;
600   Int_t bit = 0;
601
602   //  printf("%5d %5d %5d %5d %5d %5d\n",K1,K2,K3,L1,L2,L3);
603
604   for(Int_t i = 0; i < ftimebins; i++){
605     din = fChannelShort[i];
606     
607     din = (din<<2);
608     c1n             = Mask( (Mask(din,17,0) + Multiply36(K1,Mask(c1o,17,0)) ) ,17,0);
609     d1              = Mask( (Mask(c1n,17,0) - Multiply36(L1,Mask(c1o,17,0)) ) ,17,0);
610     //d1              = Mask( (Mask(c1n,17,0) + Mask(~Multiply36(L1,Mask(c1o,17,0))+1,17,0) ) ,17,0);
611     
612     c2n             = Mask( (Mask(d1 ,17,0) + Multiply36(K2,Mask(c2o,17,0)) ) ,17,0);
613     d2              = Mask( (Mask(c2n,17,0) - Multiply36(L2,Mask(c2o,17,0)) ) ,17,0);
614     //d2              = Mask( (Mask(c2n,17,0) + Mask(~Multiply36(L2,Mask(c2o,17,0))+1,17,0) ) ,17,0);
615     
616     c3n             = Mask( (Mask(d2 ,17,0) + Multiply36(K3,Mask(c3o,17,0)) ) ,17,0);
617     dout            = Mask( (Mask(c3n,17,0) - Multiply36(L3,Mask(c3o,17,0)) ) ,17,0);
618     //dout            = Mask( (Mask(c3n,17,0) + Mask(~Multiply36(L3,Mask(c3o,17,0))+1,17,0) ) ,17,0);
619     
620     if( (Maskandshift(dout,2,2) == 1) || (Maskandshift(dout,1,1) == 1)){
621       bit = 1;
622     }else{
623       bit = 0;
624     }
625     
626     dout = ((dout>>3)<<1) + bit;
627     if(Maskandshift(dout,15,15) == 1){
628       //is needed to get the correct coding when getting negative results
629       dout = -Mask((-Mask(dout,9,0)),9,0);
630     }else{
631       dout = Mask(dout,9,0);
632     }
633     
634     fChannelShort[i] = (short) dout;
635     c1o = c1n;
636     c2o = c2n;
637     c3o = c3n;
638   }
639 }
640
641 void AliTPCAltroEmulator::BaselineCorrection2RTL(Int_t HighThreshold, Int_t LowThreshold, Int_t Offset, Int_t Presamples, Int_t Postsamples){
642   //
643   // BaselineCorrection2RTL
644   //
645
646   //cout << "Altro::BaselineCorrection2RTL | HighThreshold: " << HighThreshold << " LowThreshold: " << LowThreshold << " Offset: " << Offset << " Presamples: " << Presamples << " Postsamples: " << Postsamples << endl;
647   //more or less direct "translation" of the hdl code.
648   //Input signals
649   Int_t din;
650   Int_t dout;
651   Int_t edges[6]; // = Postsamples*4 + Presamples;
652   Int_t offset = Offset;
653   Int_t thrlo = LowThreshold;//called thr_mau[19] ...
654   Int_t thrhi = HighThreshold;
655   
656   // Variables
657   Int_t fOld[4]; //flag pipe
658   Int_t fNew[4]; //flag pipe
659   Int_t dOld[4]; //data pipe
660   Int_t dNew[4]; //data pipe
661   Int_t dxOld;
662   Int_t dxNew;
663   Int_t pstscnt; // Counter for Postsamples
664   Int_t zOld[9]; // Filter stages
665   Int_t zNew[9]; // Filter stages
666   Int_t zxOld; //Accumulator stage
667   Int_t zxNew; //Accumulator stage
668   Int_t valcntOld; //Valid sample counter
669   Int_t valcntNew = 0; //Valid sample counter
670   
671   Int_t valid; //Valid flag
672   Int_t fx; //postsample flag
673   //Int_t s07; // differentiator result
674   Int_t s8; // Acc + Diff result
675   Int_t flag;
676   //Int_t bsth; //baseline threshold
677   //Int_t din_p; //Data input strictly positive
678   Int_t bsl;
679   //Int_t dx_bsls; // dx -bsl
680   //Int_t dx_clip; // dxbsl clipped
681   //Int_t bsl_of = 0;
682   
683   //initialisation
684   for(Int_t i = 0; i < 9 ; i++)
685     zOld[i] = 0;
686   for(Int_t i = 0; i < 4 ; i++){
687     fOld[i] = 0;
688     dOld[i] = 0;
689   }
690   dxOld= 0;
691   pstscnt = 0;
692   zxOld = 0;
693   valcntOld = 0;
694   valid = 0;
695   for(Int_t i = 0; i < 2 ; i++){
696     edges[i] = (Presamples&(1<<i))>>i;
697   }
698   for(Int_t i = 0; i < 4 ; i++){
699     edges[(3-i)+2] = (Postsamples&(1<<i))>>i;
700   }
701   /*cout << "edges :";
702     for(Int_t i = 0; i < 6 ; i++)
703     cout << edges[i] << ":";
704     cout << " Presamples: " << Presamples << " Postsamples: " << Postsamples << endl;*/
705   
706   //Loop
707   //cout << "AliTPCAltroEmulator::BaselineCorrection2_RTL | starting Loop" << endl;
708   for(Int_t timebin = -12; timebin < ftimebins+10; timebin++){
709     //cout << "AliTPCAltroEmulator::BaselineCorrection2_RTL | in Loop timebin: " << timebin << endl;
710     din = GetElement(fChannelShort,timebin);
711     
712     s8 = zxOld + (zOld[8] - zOld[0]);
713     
714     if(valid == 1)
715       bsl = s8>>3;// ...
716     else
717       bsl = 0;
718     
719     //assign flag = (din_p > thrhi) | (thrlo > din_p);  // Signal samples between thresholds
720     if( (din <= (bsl + thrhi)) && (din >= (bsl - thrlo)) )
721       flag = 0;
722     else
723       flag = 1;
724     
725     if(pstscnt == 0)
726       fx = 0;
727     else
728       fx = 1;
729     
730     if(valcntOld >= 12)
731       valid = 1;
732     else
733       valid = 0;
734     
735     fNew[3] = flag;
736     
737     if( (fOld[3] == 1) || ( (flag == 1) && ( (edges[0] == 1) || (edges[1] == 1) ) ) ) //f[2] =  f[3] | (flag&(edges[0]|edges[1]));
738       fNew[2] = 1;
739     else
740       fNew[2] = 0;
741     
742     if( (fOld[2] == 1) || ( (edges[1] == 1) && (flag == 1) ) ) //               f[1] =  f[2] | (edges[1] & flag);
743       fNew[1] = 1;
744     else
745       fNew[1] = 0;
746     
747     if( ( (fOld[1] == 1) || ( (flag == 1) && (edges[0] == 1) && (edges[1] == 1) )  || (fx==1) ) && (valid==1) ) //              f[0] = (f[1] | (edges[1] & edges[0] & flag) | fx) & valid;
748       fNew[0] = 1;
749     else
750       fNew[0] = 0;
751     
752     dxNew = dOld[0];
753     for(Int_t i = 0; i < 3; i++)
754       dNew[i] = dOld[i+1];
755     dNew[3] = din;
756     
757     if( (fOld[1]==1) && (fOld[2]==0) )
758       pstscnt = Postsamples;
759     else if(fx == 1)
760       pstscnt--;
761     
762     if(fOld[0] == 0){
763       if(valid == 0)
764         valcntNew =  ++valcntOld;
765       
766       zxNew = s8;
767       for(Int_t i = 0; i < 8; i++)
768         zNew[i] = zOld[i+1];
769       zNew[8] = dOld[0];
770     }else{
771       zxNew = zxOld;
772       for(Int_t i = 0; i < 9; i++)
773         zNew[i] = zOld[i];
774     }
775     dout = dxOld - (bsl - offset);
776     //if(dout <0)
777     //  dout = 0;
778     
779     SetElement(fChannelShort,timebin-5,(short)dout);
780     //sim clockschange
781     for(Int_t i = 0; i < 9 ; i++)
782       zOld[i] = zNew[i];
783     zxOld = zxNew;
784     for(Int_t i = 0; i < 4 ; i++){
785       fOld[i] = fNew[i];
786       dOld[i] = dNew[i];
787     }
788     dxOld = dxNew;
789     valcntOld = valcntNew;
790   }
791 }
792
793 void AliTPCAltroEmulator::Clipping(){ 
794   //
795   // implement if no BC2 clipping has to run
796   //
797   for(Int_t i = 0; i < ftimebins; i++){
798     if(fChannelShort[i] < -1)
799       fChannelShort[i] = -1;
800   }
801 }
802
803 void AliTPCAltroEmulator::Zerosuppression(Int_t Threshold, Int_t MinSamplesaboveThreshold, Int_t Presamples, Int_t Postsamples){
804   //
805   // add again altro feature
806   //
807
808   //TODO: Implement "Altro zsu merging"
809   //Int_t Postsamplecounter = 0;
810   //Int_t setPostsample = 0;
811
812   for(Int_t i = 0; i < ftimebins; i++){
813     if(fChannelShort[i] >= Threshold)
814       fADCkeep[i] = 1;
815     else
816       fADCkeep[i] = 0;
817   }
818
819   Int_t startofclustersequence = -1;
820   Int_t endofClustersInSequence = -1;
821   
822   for(Int_t i = 0; i < ftimebins; i++){
823     if( (fADCkeep[i] == 1) && (GetElement(fADCkeep,i-1) == 0) ){
824       startofclustersequence = i;
825     }
826     if( (fADCkeep[i] == 1) && (GetElement(fADCkeep,i+1) == 0) ){
827       endofClustersInSequence = i;
828     }
829     //cout << i << " startofclustersequence: " << startofclustersequence << " endofClustersInSequence: " << endofClustersInSequence;
830     if( (startofclustersequence != -1) && (endofClustersInSequence != -1) ){
831       //cout << " found! " <<  (endofClustersInSequence - startofclustersequence + 1);
832       if ( (endofClustersInSequence - startofclustersequence + 1) < MinSamplesaboveThreshold ){
833         for(Int_t j = startofclustersequence; j <= endofClustersInSequence ; j++){
834           fADCkeep[j] = 0;
835         }
836       }
837       startofclustersequence = -1;
838       endofClustersInSequence = -1;
839     }
840     //cout << endl;
841   }
842   
843   /*for(Int_t i = 0; i < ftimebins; i++){
844     if( (GetElement(fADCkeep,i-1) == 1) && (GetElement(fADCkeep,i) == 0) && (GetElement(fADCkeep,i+1) == 1) ){
845     SetElement(fADCkeep,i,1);
846     }
847     }*/
848   
849   for(Int_t i = 0; i < ftimebins; i++){
850     if( (fADCkeep[i] == 1) && (GetElement(fADCkeep,i-1) == 0) ){
851       for(Int_t j = i-Presamples ; j <= i; j++){
852         SetElement(fADCkeep,j,1);
853       }
854     }
855   }
856   for(Int_t i = ftimebins; i >= 0; i--){
857     if( (fADCkeep[i] == 1) && (GetElement(fADCkeep,i+1) == 0) ){
858       for(Int_t j = i ; j <= i+Postsamples; j++){
859         SetElement(fADCkeep,j,1);
860       }
861     }
862   }
863   /*cout << " Postsamplecounter: " << Postsamplecounter;
864     for(Int_t j = i+1 ; j <= i+Postsamples; j++){
865     SetElement(fADCkeep,j,1);
866     i+=Postsamples;
867     }
868     cout << endl;
869     }
870     cout << i << " ADCK: " << GetElement(fADCkeep,i);
871     cout << " Postsam: " << Postsamplecounter << " ADCK: " << GetElement(fADCkeep,i);*/
872   
873   for(Int_t i = 0; i < ftimebins; i++){
874     if( (fADCkeep[i] == 1) && (GetElement(fADCkeep,i+1) == 0) && ( (GetElement(fADCkeep,i+3) == 1) || (GetElement(fADCkeep,i+2) == 1) ) ){
875       SetElement(fADCkeep,i+1,1);
876       SetElement(fADCkeep,i+2,1);
877     }
878   }
879
880   for(Int_t i = 0; i < ftimebins; i++){
881     if( !GetKeepChannel(i) ) {
882       SetElement(fChannelShort,i,-1); // set non relevant data to -1
883     }
884   }
885
886
887 }
888
889 /**  @brief formats the data like the ALTRO. Result is a 64 bit array
890  *
891  *      formats the data like the ALTRO. Result is a 64 bit array
892  *
893  */
894
895 void AliTPCAltroEmulator::DataFormater(){
896   //
897   // formats the data like the ALTRO. Result is a 64 bit array
898   //
899
900
901 }
902
903
904 /**  @brief calculates the compression out of the bitmask
905  *
906  *      calculates the compression out of the bitmask with the set adc values
907  *
908  *      @return \c Float_t consisting of the compression factor
909  */
910 Float_t AliTPCAltroEmulator::CalculateCompression() {
911   //
912   // calculates the compression out of the bitmask
913   //
914
915   // calculation is based on altro 10 bit words ..
916   Int_t sample = 0;
917   Int_t cluster = 0;
918   Int_t data = 0;
919   Float_t retval = 0.0;
920   
921   for(Int_t i = 0; i < ftimebins; i++){
922     if(fADCkeep[i] == 1){
923       sample++;
924     }
925     if( (fADCkeep[i] == 1) && (GetElement(fADCkeep,i+1) == 0) ){
926       cluster++;
927     }
928   }
929   data = sample + cluster*2;
930   data = data + data%4 + 4;
931   if(data >0){
932     retval = ftimebins / (Float_t)data;//num of timebins is equal to max number of samples
933   }else{
934     retval = 1.0;
935   }
936   return retval;
937 }
938
939 Short_t AliTPCAltroEmulator::GetElement(short* Array,Int_t index){
940   //
941   // GetElement of array
942   //
943   if (index < 0)
944     return 0;
945   else if(index >= ftimebins)
946     return 0;
947   else
948     return Array[index];
949 }
950
951 void AliTPCAltroEmulator::SetElement(short* Array,Int_t index,Short_t value){
952   //
953   // SetElement of array
954   //
955   if (index < 0)
956     return;
957   else if(index >= ftimebins)
958     return;
959   else
960     Array[index] = value;
961 }
962
963 Int_t AliTPCAltroEmulator::InBand(Int_t ADC,Int_t bsl, Int_t LowThreshold, Int_t HighThreshold){
964   //
965   // check if it's within the band of search
966   //
967   Int_t fLow = bsl - LowThreshold;
968   Int_t fHigh = bsl + HighThreshold;
969   if( (ADC <= fHigh) && (ADC >= fLow) )
970     return 1;
971   else
972     return 0;
973 }
974
975 Int_t AliTPCAltroEmulator::InRange(Int_t parameter,Int_t Low,Int_t High,const char *Module,const char *ParameterName){
976   //
977   // checks it it's within the range
978   //
979
980   char out[255];
981   Int_t retval;
982   if(parameter > High){
983     snprintf(out,255,"Error | %s | Parameter %s is to big, has to be %d <= %s <= %d, is %d, now set to %d",Module,ParameterName,Low,ParameterName,High,parameter,High);
984     cout << out << endl;
985     retval = High;
986   }else if(parameter < Low){
987     snprintf(out,255,"Error | %s | Parameter %s is to small, has to be %d <= %s <= %d, is %d, now set to %d",Module,ParameterName,Low,ParameterName,High,parameter,Low);
988     cout << out << endl;
989     retval = Low;
990   }else{
991     retval = parameter;
992   }
993   return retval;
994 }
995
996 Short_t AliTPCAltroEmulator::GetShortChannel(Int_t i){
997   //
998   // GetElement of channel
999   //
1000   return GetElement(fChannelShort,i);
1001 }
1002
1003 Short_t AliTPCAltroEmulator::GetKeepChannel(Int_t i){
1004   //
1005   // GetElement of Keep Channel
1006   //
1007   return GetElement(fADCkeep,i);
1008 }
1009
1010 Bool_t AliTPCAltroEmulator::WriteEvent(Int_t ievent) {
1011   //
1012   // Write event to the DDL data folders
1013   //
1014
1015   for (Int_t ddlID=0;ddlID<216;++ddlID) {
1016     Bool_t  *channelsDDL=fChannels+ddlID*4096     ;
1017     Short_t *adcsDDL    =fADCs    +ddlID*4096*1024;
1018     UInt_t  *cdhDDL     =fCDHs    +ddlID*8        ;
1019     UInt_t  *trailerDDL =fTrailers+ddlID*9        ;
1020     
1021     FILE *file=fopen(Form("%s/raw%d/TPC_%03d.ddl",
1022                           fDDLFolderName.Data(),ievent,768+ddlID),
1023                      "wb");
1024     if (!file) {
1025       return kFALSE;
1026     } else { 
1027       Int_t i32;
1028       // write CDH (first word to be altered later)
1029       for (i32=0;i32<8;++i32)
1030         fRawData[i32]=cdhDDL[i32];
1031       
1032       // process payload
1033       for (Int_t hwaddr=0;hwaddr<4096;++hwaddr) if (channelsDDL[hwaddr]) {
1034         Short_t *adcsChannel=adcsDDL+hwaddr*1024;
1035         // merge custers
1036         // TODO: acqusition window
1037         for (Int_t it=0;it<1024-3;++it) {
1038           if (adcsChannel[it]>=0&&adcsChannel[it+3]>=0) {
1039             if (adcsChannel[it+1]<0) {
1040               //            printf("merge");
1041               adcsChannel[it+1]=0;
1042             }
1043             if (adcsChannel[it+2]<0) {
1044               //            printf("merge");
1045               adcsChannel[it+2]=0;
1046             }
1047           }
1048         }
1049         Int_t i10=3;
1050         Int_t icw=0;
1051         Int_t its=1;
1052         Int_t cw =0;
1053         Int_t ts =0;
1054         for (Int_t it=1023;it>=0;--it) {
1055           Short_t w10=adcsChannel[it];
1056           if (w10>=0) {
1057             if (cw<0) {
1058               icw=i10++;
1059               its=i10++;
1060               cw =0    ;
1061               ts=it    ;
1062             }
1063             fRawData[i32+i10/3]|=w10<<(10*(2-i10%3));
1064             ++i10;
1065             ++cw;
1066           }
1067           else {
1068             if (cw>=0) {
1069               cw+=2;
1070               fRawData[i32+icw/3]|=cw <<(10*(2-icw%3));
1071               fRawData[i32+its/3]|=ts <<(10*(2-its%3));
1072               cw=-1;
1073             }
1074           }
1075         }
1076         fRawData[i32]=0x1<<30|(i10-3)<<16|hwaddr;
1077         i32+=(i10+2)/3;
1078         
1079         // clean up
1080         for (Int_t i=0;i<1024;++i) adcsChannel[i]=-1;
1081         channelsDDL[hwaddr]=kFALSE;
1082       }
1083       
1084       // write RCU trailer
1085       fRawData[i32]=0x2<<30|(i32-8);i32++;
1086       for (Int_t i=0;i<8;++i)
1087         fRawData[i32++]=trailerDDL[i];
1088       
1089       // write first word of CDH
1090       fRawData[0]=i32*4;
1091       
1092       Int_t nwritten=fwrite(fRawData,sizeof(UInt_t),i32,file);
1093       if (nwritten!=i32) return kFALSE;
1094       
1095       // clean up
1096       do {fRawData[--i32]=0;} while (i32>0);
1097       
1098       fclose(file);
1099     }
1100   }
1101   return kTRUE;
1102 }
1103
1104 Bool_t AliTPCAltroEmulator::GDC2DDLs(AliRawVEvent *gdc,Int_t ievent) {
1105   //
1106   // Converte GDC data to DDL format
1107   //
1108   for(Int_t iLDC=0;iLDC<gdc->GetNSubEvents();++iLDC) {
1109     AliRawVEvent *ldc=gdc->GetSubEvent(iLDC);
1110     for(Int_t iEq=0;iEq<ldc->GetNEquipments();++iEq) {
1111       AliRawVEquipment *eq=ldc->GetEquipment(iEq);
1112       AliRawEquipmentHeader *eqHeader=eq->GetEquipmentHeader();
1113       Int_t eqSize=eqHeader->GetEquipmentSize();
1114       if (eqSize>0) {
1115         Int_t ddlIndex;
1116         Int_t detId=AliDAQ::DetectorIDFromDdlID(eqHeader->GetId(),ddlIndex);
1117         Int_t nwritten=0;
1118         FILE *ddlFile=fopen(Form("%s/raw%d/%s",
1119                                  fDDLFolderName.Data(),
1120                                  ievent,
1121                                  AliDAQ::DdlFileName(detId,ddlIndex)),
1122                             "wb");
1123         AliRawData *rawData=eq->GetRawData();
1124         if (ddlFile) {
1125           nwritten=fwrite(rawData->GetBuffer(),1,rawData->GetSize(),ddlFile);
1126           fclose(ddlFile);
1127         }
1128         if (nwritten<rawData->GetSize()) return kFALSE;
1129       }
1130     }
1131   }
1132   return kTRUE;
1133 }
1134
1135
1136 Bool_t AliTPCAltroEmulator::ConvertRawFilesToDate(Int_t nevents) {
1137   //
1138   //  Convertes Raw files to Date format
1139   //
1140   
1141   // from $ALICE_ROOT/STEER/AliSimulation.cxx
1142   
1143   char command[100];
1144   FILE *pipe;
1145
1146   printf(" RAW to DATE CONVERSION: Run Number %d\n",fRunNumber);
1147
1148   if (fRunNumber>0)
1149     pipe=gSystem->OpenPipe(Form("dateStream -c -s -D -o %s -C -# %d -run %d", 
1150                                 fOutputDateFileName.Data(),
1151                                 nevents,
1152                                 fRunNumber),
1153                            "w");
1154   else
1155     pipe=gSystem->OpenPipe(Form("dateStream -c -s -D -o %s -C -# %d", 
1156                                 fOutputDateFileName.Data(),
1157                                 nevents),
1158                            "w");
1159   if (!pipe) {
1160     fprintf(stderr,"error: cannot execute command: %s",command);
1161     return kFALSE;
1162   }
1163
1164   for (Int_t ievent=0;ievent<nevents;++ievent) {
1165     UInt_t detectorPattern = 0xFFFFFFFF;
1166     fprintf(pipe, "GDC DetectorPattern %u\n", detectorPattern);
1167
1168     Float_t ldc = 0;
1169     Int_t prevLDC = -1;
1170   
1171     // loop over detectors and DDLs
1172     for (Int_t iDet = 0; iDet < AliDAQ::kNDetectors; iDet++) {
1173       if (!(iDet<=5 || iDet==17 )) continue;
1174       for (Int_t iDDL = 0; iDDL < AliDAQ::NumberOfDdls(iDet); iDDL++) {
1175         //      printf("iDet=%d, iDDL=%d, filenmae=%s\n",iDet,iDDL,filename);
1176         Int_t ddlID = AliDAQ::DdlID(iDet,iDDL);
1177         Int_t ldcID = Int_t(ldc + 0.0001);
1178         ldc += AliDAQ::NumberOfLdcs(iDet) / AliDAQ::NumberOfDdls(iDet);
1179
1180         // check existence and size of raw data file
1181         FILE* file = fopen(Form("%s/raw%d/%s",
1182                                 fDDLFolderName.Data(),
1183                                 ievent,
1184                                 AliDAQ::DdlFileName(iDet,iDDL)),
1185                            "rb");
1186         if (!file) continue;
1187         fseek(file, 0, SEEK_END);
1188         unsigned long size = ftell(file);
1189         fclose(file);
1190         if (!size) continue;
1191
1192         if (ldcID != prevLDC) {
1193           fprintf(pipe, " LDC Id %d\n", ldcID);
1194           prevLDC = ldcID;
1195         }
1196         fprintf(pipe,Form("  Equipment Id %d Payload %s/raw%d/%s\n",
1197                           ddlID,
1198                           fDDLFolderName.Data(),
1199                           ievent,
1200                           AliDAQ::DdlFileName(iDet,iDDL))
1201                 );
1202       }
1203     }
1204   }
1205   Int_t result = gSystem->ClosePipe(pipe);
1206   return (result == 0);
1207 }
1208
1209 void AliTPCAltroEmulator::InitBuffers() {
1210   // 
1211   // Initialization of the Buffers
1212   //
1213   if (!fChannels) fChannels=new Bool_t [216*4096     ];
1214   if (!fCDHs    ) fCDHs    =new UInt_t [216*8        ];
1215   if (!fADCs    ) fADCs    =new Short_t[216*4096*1024];
1216   if (!fTrailers) fTrailers=new UInt_t [216*9        ];
1217   if (!fRawData ) fRawData =new UInt_t [  1*4096*1024]; // be save...
1218
1219   for (Int_t i=0;i<216*4096     ;++i) fChannels[i]=kFALSE;
1220   // no need to init CDHs
1221   for (Int_t i=0;i<216*4096*1024;++i) fADCs    [i]=-1    ;
1222   // no need to init trailers
1223   for (Int_t i=0;i<  1*4096*1024;++i) fRawData [i]= 0    ;
1224 }
1225
1226 Bool_t AliTPCAltroEmulator::ConvertDateToRoot() {
1227   //
1228   // convert a DATE file to a root file with the program "alimdc"
1229   //
1230
1231   // from $ALICE_ROOT/STEER/AliSimulation.cxx
1232
1233   printf(" DATE to ROOT CONVERSION: Run Number %d\n",fRunNumber);
1234
1235   // ALIMDC setup
1236   const Int_t kDBSize    = 2000000000; //2GB
1237   const Int_t kTagDBSize = 1000000000;
1238   const Bool_t kFilter = kFALSE;
1239   const Int_t kCompression = 1;
1240
1241   //  AliInfo(Form("converting DATE file %s to root file %s", 
1242   //               dateFileName, rootFileName));
1243
1244   const char* rawDBFS[2] = { "/tmp/mdc1", "/tmp/mdc2" };
1245   const char* tagDBFS    = "/tmp/mdc1/tags";
1246
1247   // User defined file system locations
1248   if (gSystem->Getenv("ALIMDC_RAWDB1")) 
1249     rawDBFS[0] = gSystem->Getenv("ALIMDC_RAWDB1");
1250   if (gSystem->Getenv("ALIMDC_RAWDB2")) 
1251     rawDBFS[1] = gSystem->Getenv("ALIMDC_RAWDB2");
1252   if (gSystem->Getenv("ALIMDC_TAGDB")) 
1253     tagDBFS = gSystem->Getenv("ALIMDC_TAGDB");
1254
1255   gSystem->Exec(Form("rm -rf %s",rawDBFS[0]));
1256   gSystem->Exec(Form("rm -rf %s",rawDBFS[1]));
1257   gSystem->Exec(Form("rm -rf %s",tagDBFS));
1258
1259   gSystem->Exec(Form("mkdir %s",rawDBFS[0]));
1260   gSystem->Exec(Form("mkdir %s",rawDBFS[1]));
1261   gSystem->Exec(Form("mkdir %s",tagDBFS));
1262
1263   Int_t result = gSystem->Exec(Form("alimdc %d %d %d %d %s", 
1264                                     kDBSize, kTagDBSize, kFilter, kCompression, fOutputDateFileName.Data()));
1265   gSystem->Exec(Form("mv %s/*.root %s", rawDBFS[0],fOutputRootFileName.Data()));
1266
1267   gSystem->Exec(Form("rm -rf %s",rawDBFS[0]));
1268   gSystem->Exec(Form("rm -rf %s",rawDBFS[1]));
1269   gSystem->Exec(Form("rm -rf %s",tagDBFS));
1270
1271   return (result == 0);
1272 }
1273
1274 void AliTPCAltroEmulator::RunEmulationOnRAWdata(AliRawReader *reader, Int_t plotFlag) {
1275   //
1276   // Run the Altro Emulation on a full Raw data set (AliRawReader)
1277   // plus write the outcome in a RAW data format
1278   //
1279
1280   if (!reader) {
1281     printf("ERROR cant run Altro Emulation: AliRawReader is zero. No RAW data file.\n");
1282     return;
1283   }
1284
1285   fReader=reader;
1286   if (fDecoder) delete fDecoder;
1287   fDecoder=new AliTPCRawStreamV3(reader);
1288
1289   InitBuffers();
1290   
1291   Int_t chanCount=0;
1292   TH1F hisO("DINO","DINO",1024,0,1024); 
1293   TH1F his("DIN","DIN",1024,0,1024); 
1294   his.GetYaxis()->SetRangeUser(-20,90);
1295   Short_t *data = new Short_t[1024]; 
1296   TCanvas *c1 =0;
1297   if (plotFlag) {
1298     c1 = new TCanvas("c1","c1");
1299     c1->SetGridx(); c1->SetGridy();
1300   }
1301
1302   // event loop
1303   Int_t ievent=0;
1304   while (fReader->NextEvent()) {
1305     
1306     if (fReader->GetRunNumber()>0) fRunNumber=fReader->GetRunNumber();
1307     gSystem->Exec(Form("mkdir -p %s/raw%d/",fDDLFolderName.Data(),ievent));
1308     GDC2DDLs(const_cast<AliRawVEvent*>(fReader->GetEvent()),ievent);
1309     
1310     Int_t ddlC =0;
1311     while (fDecoder->NextDDL()) {
1312       Int_t ddlID=fDecoder->GetDDLNumber();
1313       printf("ddl: %d (%d/216)\n",ddlID,++ddlC);
1314      
1315       Bool_t  *channelsDDL=fChannels+ddlID*4096      ;
1316       Short_t *adcsDDL    =fADCs    +ddlID*4096*1024 ;
1317       UInt_t  *cdhDDL     =fCDHs    +ddlID*8         ;
1318       UInt_t  *trailerDDL =fTrailers+ddlID*9         ;
1319       
1320       // CDH 
1321       for (Int_t i=0;i<8;++i)
1322         // just to show how ugly it is...
1323         cdhDDL[i]=reinterpret_cast<UInt_t*>(const_cast<AliRawDataHeader*>(fReader->GetDataHeader()))[i]; 
1324       
1325       // PAYLOAD
1326       while (fDecoder->NextChannel()) {
1327         Int_t hwaddr=fDecoder->GetHWAddress();
1328         Int_t sector=fDecoder->GetSector();
1329         Int_t row=fDecoder->GetRow();
1330         Int_t pad=fDecoder->GetPad();
1331         Short_t *adcsChannel=adcsDDL+hwaddr*1024;
1332         while (fDecoder->NextBunch()) {
1333           UInt_t          ts     =fDecoder->GetStartTimeBin();
1334           Int_t           cw     =fDecoder->GetBunchLength() ;
1335           const UShort_t *signals=fDecoder->GetSignals()     ;
1336           for (Int_t ci=0;ci<cw;++ci) {
1337             Short_t s=signals[ci];
1338             Int_t   t=ts-ci;
1339             // TODO aqcuisition window
1340             if (0<=t&&t<(1024-3)) {
1341               channelsDDL[hwaddr]=kTRUE;
1342               if (adcsChannel[t]<0)
1343                 adcsChannel[t]=s;
1344               else
1345                 adcsChannel[t]+=s;
1346               if (adcsChannel[t]>0x3ff)
1347                 adcsChannel[t]=0x3ff;
1348             }
1349           }
1350         }
1351
1352         // search start of aquisition
1353         Int_t t0 = 0;    while (adcsChannel[t0]==-1) t0++;
1354         // search end of aquisition
1355         Int_t tE = 1024; while (adcsChannel[tE]==-1) tE--;
1356         
1357         // channel is complete - Perform Altro Emulation
1358         if (plotFlag!=0 && !(chanCount%plotFlag) ) {
1359           for (Int_t t=0; t<1024; t++) {
1360             his.SetBinContent(t+1,adcsChannel[t]);
1361           }
1362           his.SetTitle(Form("sig_sec%d_row%d_pad%d",sector,row,pad));
1363           his.SetStats(0); his.GetXaxis()->SetTitle("timebin"); 
1364           his.DrawCopy();
1365         }
1366
1367         // FEED THE ALTRO EMULATOR WITH CLEAN SIGNAL (no aquisition-window ghosts)
1368         Int_t timebins = tE-t0+1;
1369         for (Int_t t=t0;t<(t0+timebins);t++)
1370           data[t-t0]=adcsChannel[t];
1371         SetChannelData(timebins,data);
1372         
1373         Int_t roc = (sector%36)>=18; // 0 for IROC, 1 for OROC
1374         RunEmulation(roc); 
1375         for (Int_t t=t0;t<(t0+timebins);t++) 
1376           adcsChannel[t]=data[t-t0];
1377           
1378         if (plotFlag!=0 && !(chanCount%plotFlag) ) {
1379           for (Int_t t=0; t<1024; t++)
1380             hisO.SetBinContent(t+1,adcsChannel[t]);
1381           hisO.SetStats(0); hisO.SetLineColor(2);
1382           hisO.DrawCopy("same");
1383             
1384           c1->SaveAs(Form("%s/sig_sec%02d_row%02d_pad%03d_%s_%d%d%d%d%d.png",
1385                           fDDLFolderName.Data(),sector,row,pad,
1386                           fOutputRootFileName.Data(),
1387                           fOnBSL1,fOnTCF,fOnBSL2,fOnClip,fOnZSU));
1388             
1389           his.Reset();
1390           hisO.Reset();
1391
1392         }
1393         chanCount++;
1394
1395       }
1396       
1397       // TRAILER 
1398       UChar_t *rcuTrailer;
1399       fDecoder->GetRCUTrailerData(rcuTrailer);
1400       for (Int_t i=0;i<= /* (!) */ fDecoder->GetRCUTrailerSize()/4;++i)
1401         trailerDDL[i]=reinterpret_cast<UInt_t*>(rcuTrailer)[i]; // again: UGLY!
1402       
1403     }
1404             
1405     if (ddlC>0) WriteEvent(ievent++);
1406   }
1407
1408   delete[] data; // free space
1409
1410   // convert to date and back
1411   ConvertRawFilesToDate(ievent);
1412   ConvertDateToRoot();
1413
1414
1415 }