/[PAMELA software]/PamelaDigitizer/Digitizer.cxx
ViewVC logotype

Diff of /PamelaDigitizer/Digitizer.cxx

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.2 by orsi, Fri Sep 28 10:46:23 2007 UTC revision 1.4 by orsi, Wed Oct 31 18:17:58 2007 UTC
# Line 1  Line 1 
1  //               ------ PAMELA Digitizer ------  //               ------ PAMELA Digitizer ------
2  //  //
3  // Date, release and how-to: see file Pamelagp2Digits.cxx  // Date, release and how-to: see file Pamelagp2Digits.cxx
4  //  //
5  // NB: Check length physics packet [packet type (0x10 = physics data)]  // NB: Check length physics packet [packet type (0x10 = physics data)]
6  //  //
7  #include <sstream>  #include <sstream>
8  #include <fstream>  #include <fstream>
9  #include <stdlib.h>  #include <stdlib.h>
10  #include <stdio.h>  #include <stdio.h>
11  #include <string.h>  #include <string.h>
12  #include <ctype.h>  #include <ctype.h>
13  #include <time.h>  #include <time.h>
14  #include "Riostream.h"  #include "Riostream.h"
15  #include "TFile.h"  #include "TFile.h"
16  #include "TDirectory.h"  #include "TDirectory.h"
17  #include "TTree.h"  #include "TTree.h"
18  #include "TLeafI.h"  #include "TLeafI.h"
19  #include "TH1.h"  #include "TH1.h"
20  #include "TH2.h"  #include "TH2.h"
21  #include "TMath.h"  #include "TMath.h"
22  #include "TRandom.h"  #include "TRandom.h"
23  #include "TSQLServer.h"  #include "TSQLServer.h"
24  #include "TSystem.h"  #include "TSystem.h"
25  //  //
26  #include "Digitizer.h"  #include "Digitizer.h"
27  #include "CRC.h"  #include "CRC.h"
28  //  //
29  #include <PamelaRun.h>  #include <PamelaRun.h>
30  #include <physics/calorimeter/CalorimeterEvent.h>  #include <physics/calorimeter/CalorimeterEvent.h>
31  #include <CalibCalPedEvent.h>  #include <CalibCalPedEvent.h>
32  #include "GLTables.h"  #include "GLTables.h"
33  //  //
34  extern "C"{  extern "C"{
35    short crc(short, short);    short crc(short, short);
36  };  };
37  //  //
38    
39  Digitizer::Digitizer(TTree* tree, char* &file_raw){  Digitizer::Digitizer(TTree* tree, char* &file_raw){
40    fhBookTree = tree;    fhBookTree = tree;
41    fFilename =  file_raw;    fFilename =  file_raw;
42    fCounter = 0;    fCounter = 0;
43    fOBT = 0;    fOBT = 0;
44    
45    //    //
46    // DB connections    // DB connections
47    //    //
48    TString host = "mysql://localhost/pamelaprod";    TString host = "mysql://localhost/pamelaprod";
49    TString user = "anonymous";    TString user = "anonymous";
50    TString psw = "";    TString psw = "";
51    //    //
52    const char *pamdbhost=gSystem->Getenv("PAM_DBHOST");    const char *pamdbhost=gSystem->Getenv("PAM_DBHOST");
53    const char *pamdbuser=gSystem->Getenv("PAM_DBUSER");    const char *pamdbuser=gSystem->Getenv("PAM_DBUSER");
54    const char *pamdbpsw=gSystem->Getenv("PAM_DBPSW");    const char *pamdbpsw=gSystem->Getenv("PAM_DBPSW");
55    if ( !pamdbhost ) pamdbhost = "";    if ( !pamdbhost ) pamdbhost = "";
56    if ( !pamdbuser ) pamdbuser = "";    if ( !pamdbuser ) pamdbuser = "";
57    if ( !pamdbpsw ) pamdbpsw = "";    if ( !pamdbpsw ) pamdbpsw = "";
58    if ( strcmp(pamdbhost,"") ) host = pamdbhost;    if ( strcmp(pamdbhost,"") ) host = pamdbhost;
59    if ( strcmp(pamdbuser,"") ) user = pamdbuser;    if ( strcmp(pamdbuser,"") ) user = pamdbuser;
60    if ( strcmp(pamdbpsw,"") ) psw = pamdbpsw;    if ( strcmp(pamdbpsw,"") ) psw = pamdbpsw;
61    fDbc = TSQLServer::Connect(host.Data(),user.Data(),psw.Data());    fDbc = TSQLServer::Connect(host.Data(),user.Data(),psw.Data());
62    //    //
63    GL_TABLES *glt = new GL_TABLES(host,user,psw);    GL_TABLES *glt = new GL_TABLES(host,user,psw);
64    if ( glt->IsConnected(fDbc) ) printf("\n DB INFORMATION:\n SQL: %s Version: %s Host %s Port %i \n\n",fDbc->GetDBMS(),fDbc->ServerInfo(),fDbc->GetHost(),fDbc->GetPort());    if ( glt->IsConnected(fDbc) ) printf("\n DB INFORMATION:\n SQL: %s Version: %s Host %s Port %i \n\n",fDbc->GetDBMS(),fDbc->ServerInfo(),fDbc->GetHost(),fDbc->GetPort());
65    //    //
66    // Use UTC in the DB and make timeout bigger    // Use UTC in the DB and make timeout bigger
67    //    //
68    stringstream myquery;    stringstream myquery;
69    myquery.str("");    myquery.str("");
70    myquery << "SET time_zone='+0:00'";    myquery << "SET time_zone='+0:00'";
71    fDbc->Query(myquery.str().c_str());    fDbc->Query(myquery.str().c_str());
72    myquery.str("");    myquery.str("");
73    myquery << "SET wait_timeout=173000;";    myquery << "SET wait_timeout=173000;";
74    fDbc->Query(myquery.str().c_str());    fDbc->Query(myquery.str().c_str());
75    //    //
76        
77    std:: cout << "preparing tree" << endl;    std:: cout << "preparing tree" << endl;
78    
79    // prepare tree    // prepare tree
80    fhBookTree->SetBranchAddress("Irun",&Irun);    fhBookTree->SetBranchAddress("Irun",&Irun);
81    fhBookTree->SetBranchAddress("Ievnt",&Ievnt);    fhBookTree->SetBranchAddress("Ievnt",&Ievnt);
82    fhBookTree->SetBranchAddress("Ipa",&Ipa);    fhBookTree->SetBranchAddress("Ipa",&Ipa);
83    fhBookTree->SetBranchAddress("X0",&X0);    fhBookTree->SetBranchAddress("X0",&X0);
84    fhBookTree->SetBranchAddress("Y0",&Y0);    fhBookTree->SetBranchAddress("Y0",&Y0);
85    fhBookTree->SetBranchAddress("Z0",&Z0);    fhBookTree->SetBranchAddress("Z0",&Z0);
86    fhBookTree->SetBranchAddress("Theta",&Theta);    fhBookTree->SetBranchAddress("Theta",&Theta);
87    fhBookTree->SetBranchAddress("Phi",&Phi);    fhBookTree->SetBranchAddress("Phi",&Phi);
88    fhBookTree->SetBranchAddress("P0",&P0);    fhBookTree->SetBranchAddress("P0",&P0);
89    fhBookTree->SetBranchAddress("Nthtof",&Nthtof);    fhBookTree->SetBranchAddress("Nthtof",&Nthtof);
90    fhBookTree->SetBranchAddress("Ipltof",Ipltof);    fhBookTree->SetBranchAddress("Ipltof",Ipltof);
91    fhBookTree->SetBranchAddress("Ipaddle",Ipaddle);    fhBookTree->SetBranchAddress("Ipaddle",Ipaddle);
92    fhBookTree->SetBranchAddress("Ipartof",Ipartof);    fhBookTree->SetBranchAddress("Ipartof",Ipartof);
93    fhBookTree->SetBranchAddress("Xintof",Xintof);    fhBookTree->SetBranchAddress("Xintof",Xintof);
94    fhBookTree->SetBranchAddress("Yintof",Yintof);    fhBookTree->SetBranchAddress("Yintof",Yintof);
95    fhBookTree->SetBranchAddress("Zintof",Zintof);    fhBookTree->SetBranchAddress("Zintof",Zintof);
96    fhBookTree->SetBranchAddress("Xouttof",Xouttof);    fhBookTree->SetBranchAddress("Xouttof",Xouttof);
97    fhBookTree->SetBranchAddress("Youttof",Youttof);    fhBookTree->SetBranchAddress("Youttof",Youttof);
98    fhBookTree->SetBranchAddress("Zouttof",Zouttof);    fhBookTree->SetBranchAddress("Zouttof",Zouttof);
99    fhBookTree->SetBranchAddress("Ereltof",Ereltof);    fhBookTree->SetBranchAddress("Ereltof",Ereltof);
100    fhBookTree->SetBranchAddress("Timetof",Timetof);    fhBookTree->SetBranchAddress("Timetof",Timetof);
101    fhBookTree->SetBranchAddress("Pathtof",Pathtof);    fhBookTree->SetBranchAddress("Pathtof",Pathtof);
102    fhBookTree->SetBranchAddress("P0tof",P0tof);    fhBookTree->SetBranchAddress("P0tof",P0tof);
103    fhBookTree->SetBranchAddress("Nthcat",&Nthcat);    fhBookTree->SetBranchAddress("Nthcat",&Nthcat);
104    fhBookTree->SetBranchAddress("Iparcat",Iparcat);    fhBookTree->SetBranchAddress("Iparcat",Iparcat);
105    fhBookTree->SetBranchAddress("Icat",Icat);    fhBookTree->SetBranchAddress("Icat",Icat);
106    fhBookTree->SetBranchAddress("Xincat",Xincat);    fhBookTree->SetBranchAddress("Xincat",Xincat);
107    fhBookTree->SetBranchAddress("Yincat",Yincat);    fhBookTree->SetBranchAddress("Yincat",Yincat);
108    fhBookTree->SetBranchAddress("Zincat",Zincat);    fhBookTree->SetBranchAddress("Zincat",Zincat);
109    fhBookTree->SetBranchAddress("Xoutcat",Xoutcat);    fhBookTree->SetBranchAddress("Xoutcat",Xoutcat);
110    fhBookTree->SetBranchAddress("Youtcat",Youtcat);    fhBookTree->SetBranchAddress("Youtcat",Youtcat);
111    fhBookTree->SetBranchAddress("Zoutcat",Zoutcat);    fhBookTree->SetBranchAddress("Zoutcat",Zoutcat);
112    fhBookTree->SetBranchAddress("Erelcat",Erelcat);    fhBookTree->SetBranchAddress("Erelcat",Erelcat);
113    fhBookTree->SetBranchAddress("Timecat",Timecat);    fhBookTree->SetBranchAddress("Timecat",Timecat);
114    fhBookTree->SetBranchAddress("Pathcat",Pathcat);    fhBookTree->SetBranchAddress("Pathcat",Pathcat);
115    fhBookTree->SetBranchAddress("P0cat",P0cat);    fhBookTree->SetBranchAddress("P0cat",P0cat);
116    fhBookTree->SetBranchAddress("Nthcas",&Nthcas);    fhBookTree->SetBranchAddress("Nthcas",&Nthcas);
117    fhBookTree->SetBranchAddress("Iparcas",Iparcas);    fhBookTree->SetBranchAddress("Iparcas",Iparcas);
118    fhBookTree->SetBranchAddress("Icas",Icas);    fhBookTree->SetBranchAddress("Icas",Icas);
119    fhBookTree->SetBranchAddress("Xincas",Xincas);    fhBookTree->SetBranchAddress("Xincas",Xincas);
120    fhBookTree->SetBranchAddress("Yincas",Yincas);    fhBookTree->SetBranchAddress("Yincas",Yincas);
121    fhBookTree->SetBranchAddress("Zincas",Zincas);    fhBookTree->SetBranchAddress("Zincas",Zincas);
122    fhBookTree->SetBranchAddress("Xoutcas",Xoutcas);    fhBookTree->SetBranchAddress("Xoutcas",Xoutcas);
123    fhBookTree->SetBranchAddress("Youtcas",Youtcas);    fhBookTree->SetBranchAddress("Youtcas",Youtcas);
124    fhBookTree->SetBranchAddress("Zoutcas",Zoutcas);    fhBookTree->SetBranchAddress("Zoutcas",Zoutcas);
125    fhBookTree->SetBranchAddress("Erelcas",Erelcas);    fhBookTree->SetBranchAddress("Erelcas",Erelcas);
126    fhBookTree->SetBranchAddress("Timecas",Timecas);    fhBookTree->SetBranchAddress("Timecas",Timecas);
127    fhBookTree->SetBranchAddress("Pathcas",Pathcas);    fhBookTree->SetBranchAddress("Pathcas",Pathcas);
128    fhBookTree->SetBranchAddress("P0cas",P0cas);    fhBookTree->SetBranchAddress("P0cas",P0cas);
129    fhBookTree->SetBranchAddress("Nthspe",&Nthspe);    fhBookTree->SetBranchAddress("Nthspe",&Nthspe);
130    fhBookTree->SetBranchAddress("Iparspe",Iparspe);    fhBookTree->SetBranchAddress("Iparspe",Iparspe);
131    fhBookTree->SetBranchAddress("Itrpb",Itrpb);    fhBookTree->SetBranchAddress("Itrpb",Itrpb);
132    fhBookTree->SetBranchAddress("Itrsl",Itrsl);    fhBookTree->SetBranchAddress("Itrsl",Itrsl);
133    fhBookTree->SetBranchAddress("Itspa",Itspa);    fhBookTree->SetBranchAddress("Itspa",Itspa);
134    fhBookTree->SetBranchAddress("Xinspe",Xinspe);    fhBookTree->SetBranchAddress("Xinspe",Xinspe);
135    fhBookTree->SetBranchAddress("Yinspe",Yinspe);    fhBookTree->SetBranchAddress("Yinspe",Yinspe);
136    fhBookTree->SetBranchAddress("Zinspe",Zinspe);    fhBookTree->SetBranchAddress("Zinspe",Zinspe);
137    fhBookTree->SetBranchAddress("Xoutspe",Xoutspe);    fhBookTree->SetBranchAddress("Xoutspe",Xoutspe);
138    fhBookTree->SetBranchAddress("Youtspe",Youtspe);    fhBookTree->SetBranchAddress("Youtspe",Youtspe);
139    fhBookTree->SetBranchAddress("Zoutspe",Zoutspe);    fhBookTree->SetBranchAddress("Zoutspe",Zoutspe);
140    fhBookTree->SetBranchAddress("Xavspe",Xavspe);    fhBookTree->SetBranchAddress("Xavspe",Xavspe);
141    fhBookTree->SetBranchAddress("Yavspe",Yavspe);    fhBookTree->SetBranchAddress("Yavspe",Yavspe);
142    fhBookTree->SetBranchAddress("Zavspe",Zavspe);    fhBookTree->SetBranchAddress("Zavspe",Zavspe);
143    fhBookTree->SetBranchAddress("Erelspe",Erelspe);    fhBookTree->SetBranchAddress("Erelspe",Erelspe);
144    fhBookTree->SetBranchAddress("Pathspe",Pathspe);    fhBookTree->SetBranchAddress("Pathspe",Pathspe);
145    fhBookTree->SetBranchAddress("P0spe",P0spe);    fhBookTree->SetBranchAddress("P0spe",P0spe);
146    fhBookTree->SetBranchAddress("Nxmult",Nxmult);    fhBookTree->SetBranchAddress("Nxmult",Nxmult);
147    fhBookTree->SetBranchAddress("Nymult",Nymult);    fhBookTree->SetBranchAddress("Nymult",Nymult);
148    fhBookTree->SetBranchAddress("Nstrpx",&Nstrpx);    fhBookTree->SetBranchAddress("Nstrpx",&Nstrpx);
149    fhBookTree->SetBranchAddress("Npstripx",Npstripx);    fhBookTree->SetBranchAddress("Npstripx",Npstripx);
150    fhBookTree->SetBranchAddress("Ntstripx",Ntstripx);    fhBookTree->SetBranchAddress("Ntstripx",Ntstripx);
151    fhBookTree->SetBranchAddress("Istripx",Istripx);    fhBookTree->SetBranchAddress("Istripx",Istripx);
152    fhBookTree->SetBranchAddress("Qstripx",Qstripx);    fhBookTree->SetBranchAddress("Qstripx",Qstripx);
153    fhBookTree->SetBranchAddress("Xstripx",Xstripx);    fhBookTree->SetBranchAddress("Xstripx",Xstripx);
154    fhBookTree->SetBranchAddress("Nstrpy",&Nstrpy);    fhBookTree->SetBranchAddress("Nstrpy",&Nstrpy);
155    fhBookTree->SetBranchAddress("Npstripy",Npstripy);    fhBookTree->SetBranchAddress("Npstripy",Npstripy);
156    fhBookTree->SetBranchAddress("Ntstripy",Ntstripy);    fhBookTree->SetBranchAddress("Ntstripy",Ntstripy);
157    fhBookTree->SetBranchAddress("Istripy",Istripy);    fhBookTree->SetBranchAddress("Istripy",Istripy);
158    fhBookTree->SetBranchAddress("Qstripy",Qstripy);    fhBookTree->SetBranchAddress("Qstripy",Qstripy);
159    fhBookTree->SetBranchAddress("Ystripy",Ystripy);    fhBookTree->SetBranchAddress("Ystripy",Ystripy);
160    fhBookTree->SetBranchAddress("Nthcali",&Nthcali);    fhBookTree->SetBranchAddress("Nthcali",&Nthcali);
161    fhBookTree->SetBranchAddress("Icaplane",Icaplane);    fhBookTree->SetBranchAddress("Icaplane",Icaplane);
162    fhBookTree->SetBranchAddress("Icastrip",Icastrip);    fhBookTree->SetBranchAddress("Icastrip",Icastrip);
163    fhBookTree->SetBranchAddress("Icamod",Icamod);    fhBookTree->SetBranchAddress("Icamod",Icamod);
164    fhBookTree->SetBranchAddress("Enestrip",Enestrip);    fhBookTree->SetBranchAddress("Enestrip",Enestrip);
165    fhBookTree->SetBranchAddress("Nthcal",&Nthcal);    fhBookTree->SetBranchAddress("Nthcal",&Nthcal);
166    fhBookTree->SetBranchAddress("Icapl",Icapl);    fhBookTree->SetBranchAddress("Icapl",Icapl);
167    fhBookTree->SetBranchAddress("Icasi",Icasi);    fhBookTree->SetBranchAddress("Icasi",Icasi);
168    fhBookTree->SetBranchAddress("Icast",Icast);    fhBookTree->SetBranchAddress("Icast",Icast);
169    fhBookTree->SetBranchAddress("Xincal",Xincal);    fhBookTree->SetBranchAddress("Xincal",Xincal);
170    fhBookTree->SetBranchAddress("Yincal",Yincal);    fhBookTree->SetBranchAddress("Yincal",Yincal);
171    fhBookTree->SetBranchAddress("Zincal",Zincal);    fhBookTree->SetBranchAddress("Zincal",Zincal);
172    fhBookTree->SetBranchAddress("Erelcal",Erelcal);    fhBookTree->SetBranchAddress("Erelcal",Erelcal);
173    fhBookTree->SetBranchAddress("Nthnd",&Nthnd);    fhBookTree->SetBranchAddress("Nthnd",&Nthnd);
174    fhBookTree->SetBranchAddress("Itubend",Itubend);    fhBookTree->SetBranchAddress("Itubend",Itubend);
175    fhBookTree->SetBranchAddress("Iparnd",Iparnd);    fhBookTree->SetBranchAddress("Iparnd",Iparnd);
176    fhBookTree->SetBranchAddress("Xinnd",Xinnd);    fhBookTree->SetBranchAddress("Xinnd",Xinnd);
177    fhBookTree->SetBranchAddress("Yinnd",Yinnd);    fhBookTree->SetBranchAddress("Yinnd",Yinnd);
178    fhBookTree->SetBranchAddress("Zinnd",Zinnd);    fhBookTree->SetBranchAddress("Zinnd",Zinnd);
179    fhBookTree->SetBranchAddress("Xoutnd",Xoutnd);    fhBookTree->SetBranchAddress("Xoutnd",Xoutnd);
180    fhBookTree->SetBranchAddress("Youtnd",Youtnd);    fhBookTree->SetBranchAddress("Youtnd",Youtnd);
181    fhBookTree->SetBranchAddress("Zoutnd",Zoutnd);    fhBookTree->SetBranchAddress("Zoutnd",Zoutnd);
182    fhBookTree->SetBranchAddress("Erelnd",Erelnd);    fhBookTree->SetBranchAddress("Erelnd",Erelnd);
183    fhBookTree->SetBranchAddress("Timend",Timend);    fhBookTree->SetBranchAddress("Timend",Timend);
184    fhBookTree->SetBranchAddress("Pathnd",Pathnd);    fhBookTree->SetBranchAddress("Pathnd",Pathnd);
185    fhBookTree->SetBranchAddress("P0nd",P0nd);    fhBookTree->SetBranchAddress("P0nd",P0nd);
186    fhBookTree->SetBranchAddress("Nthcard",&Nthcard);    fhBookTree->SetBranchAddress("Nthcard",&Nthcard);
187    fhBookTree->SetBranchAddress("Iparcard",Iparcard);    fhBookTree->SetBranchAddress("Iparcard",Iparcard);
188    fhBookTree->SetBranchAddress("Icard",Icard);    fhBookTree->SetBranchAddress("Icard",Icard);
189    fhBookTree->SetBranchAddress("Xincard",Xincard);    fhBookTree->SetBranchAddress("Xincard",Xincard);
190    fhBookTree->SetBranchAddress("Yincard",Yincard);    fhBookTree->SetBranchAddress("Yincard",Yincard);
191    fhBookTree->SetBranchAddress("Zincard",Zincard);    fhBookTree->SetBranchAddress("Zincard",Zincard);
192    fhBookTree->SetBranchAddress("Xoutcard",Xoutcard);    fhBookTree->SetBranchAddress("Xoutcard",Xoutcard);
193    fhBookTree->SetBranchAddress("Youtcard",Youtcard);    fhBookTree->SetBranchAddress("Youtcard",Youtcard);
194    fhBookTree->SetBranchAddress("Zoutcard",Zoutcard);    fhBookTree->SetBranchAddress("Zoutcard",Zoutcard);
195    fhBookTree->SetBranchAddress("Erelcard",Erelcard);    fhBookTree->SetBranchAddress("Erelcard",Erelcard);
196    fhBookTree->SetBranchAddress("Timecard",Timecard);    fhBookTree->SetBranchAddress("Timecard",Timecard);
197    fhBookTree->SetBranchAddress("Pathcard",Pathcard);    fhBookTree->SetBranchAddress("Pathcard",Pathcard);
198    fhBookTree->SetBranchAddress("P0card",P0card);    fhBookTree->SetBranchAddress("P0card",P0card);
199    
200    fhBookTree->SetBranchStatus("*",0);    fhBookTree->SetBranchStatus("*",0);
201    
202  };  };
203    
204    
205    
206  void Digitizer::Close(){  void Digitizer::Close(){
207    
208    delete fhBookTree;    delete fhBookTree;
209    
210  };  };
211    
212    
213    
214    
215  void Digitizer::Loop() {  void Digitizer::Loop() {
216    //    //
217    // opens the raw output file and loops over the events    // opens the raw output file and loops over the events
218    //    //
219    fOutputfile.open(fFilename, ios::out | ios::binary);    fOutputfile.open(fFilename, ios::out | ios::binary);
220    //fOutputfile.open(Form("Output%s",fFilename), ios::out | ios::binary);    //fOutputfile.open(Form("Output%s",fFilename), ios::out | ios::binary);
221    //    //
222    // Load in memory and save at the beginning of file the calorimeter calibration    // Load in memory and save at the beginning of file the calorimeter calibration
223    //    //
224    CaloLoadCalib();    CaloLoadCalib();
225    DigitizeCALOCALIB();    DigitizeCALOCALIB();
226    
227    //  load, digitize and write tracker calibration    //  load, digitize and write tracker calibration
228    LoadTrackCalib();    LoadTrackCalib();
229        
230    DigitizeTrackCalib(1);    DigitizeTrackCalib(1);
231    UInt_t length=fTracklength*2;    UInt_t length=fTracklength*2;
232    DigitizePSCU(length,0x12);    DigitizePSCU(length,0x12);
233    AddPadding();    AddPadding();
234    WriteTrackCalib();    WriteTrackCalib();
235        
236    DigitizeTrackCalib(2);    DigitizeTrackCalib(2);
237    length=fTracklength*2;    length=fTracklength*2;
238    DigitizePSCU(length,0x13);    DigitizePSCU(length,0x13);
239    AddPadding();    AddPadding();
240    WriteTrackCalib();    WriteTrackCalib();
241        
242    LoadMipCor();  // some initialization of parameters -not used now-    LoadMipCor();  // some initialization of parameters -not used now-
243    //  end loading, digitizing and writing tracker calibration    //  end loading, digitizing and writing tracker calibration
244    
245    //    //
246    // loops over the events    // loops over the events
247    //    //
248        
249    Int_t nentries = fhBookTree->GetEntriesFast();    Int_t nentries = fhBookTree->GetEntriesFast();
250    Long64_t nbytes = 0;    Long64_t nbytes = 0;
251    for (Int_t i=0; i<nentries;i++) {    for (Int_t i=0; i<nentries;i++) {
252      //      //
253      nbytes += fhBookTree->GetEntry(i);      nbytes += fhBookTree->GetEntry(i);
254      // read detectors sequentially:      // read detectors sequentially:
255      // http://www.ts.infn.it/fileadmin/documents/physics/experiments/wizard/cpu/gen_arch/RM_Acquisition.pdf      // http://www.ts.infn.it/fileadmin/documents/physics/experiments/wizard/cpu/gen_arch/RM_Acquisition.pdf
256      // on pamelatov:      // on pamelatov:
257      // /cvs/yoda/techmodel/physics/NeutronDetectorReader.cpp      // /cvs/yoda/techmodel/physics/NeutronDetectorReader.cpp
258      DigitizeTRIGGER();      DigitizeTRIGGER();
259      DigitizeTOF();      DigitizeTOF();
260      DigitizeAC();      DigitizeAC();
261      DigitizeCALO();      DigitizeCALO();
262      DigitizeTrack();      DigitizeTrack();
263      //DigitizeS4();      DigitizeS4();
264      DigitizeND();      DigitizeND();
265        //        //
266      // Add padding to 64 bits      // Add padding to 64 bits
267      //      //
268      AddPadding();      AddPadding();
269  //  //
270      // Create CPU header, we need packet type (0x10 = physics data) and packet length.      // Create CPU header, we need packet type (0x10 = physics data) and packet length.
271      //      //
272      //UInt_t length=2*(fCALOlength+fACbuffer+fTracklength+fNDbuffer+fS4buffer)+fPadding+fTOFbuffer+fTRIGGERbuffer;      UInt_t length=2*(fCALOlength+fACbuffer+fTracklength+fNDbuffer+fS4buffer)+fPadding+fTOFbuffer+fTRIGGERbuffer;
273      UInt_t length=2*(fCALOlength+fACbuffer+fTracklength+fNDbuffer)+fPadding+fTOFbuffer+fTRIGGERbuffer;      //UInt_t length=2*(fCALOlength+fACbuffer+fTracklength+fNDbuffer)+fPadding+fTOFbuffer+fTRIGGERbuffer;
274      DigitizePSCU(length,0x10);      DigitizePSCU(length,0x10);
275      if ( !i%100 ) std::cout << "writing event " << i << endl;      if ( !i%100 ) std::cout << "writing event " << i << endl;
276      WriteData();      WriteData();
277    };    };
278    
279    fOutputfile.close();    fOutputfile.close();
280    std::cout << "files closed" << endl << flush;    std::cout << "files closed" << endl << flush;
281    
282  };  };
283    
284  void Digitizer::AddPadding(){  void Digitizer::AddPadding(){
285    //    //
286    Float_t pd0 = (fLen+16)/64.;    Float_t pd0 = (fLen+16)/64.;
287    Float_t pd1 = pd0 - (Float_t)int(pd0);    Float_t pd1 = pd0 - (Float_t)int(pd0);
288    Float_t padfrac = 64. - pd1 * 64.;    Float_t padfrac = 64. - pd1 * 64.;
289    //    //
290    UInt_t padbytes = (UInt_t)padfrac;    UInt_t padbytes = (UInt_t)padfrac;
291    if ( padbytes > 0 && padbytes < 64 ){    if ( padbytes > 0 && padbytes < 64 ){
292      //      //
293      // here the padding length      // here the padding length
294      //      //
295      fPadding = padbytes+64;      fPadding = padbytes+64;
296      //      //
297      // random padding bytes      // random padding bytes
298      //      //
299      for (Int_t ur=0; ur<32; ur++){      for (Int_t ur=0; ur<32; ur++){
300        fDataPadding[ur] = (UShort_t)rand();        fDataPadding[ur] = (UShort_t)rand();
301      };      };
302    };    };
303  };  };
304    
305    
306  void Digitizer::DigitizePSCU(UInt_t length, UChar_t type) {  void Digitizer::DigitizePSCU(UInt_t length, UChar_t type) {
307    //    //
308    UChar_t buff[16];    UChar_t buff[16];
309    //    //
310    // CPU signature    // CPU signature
311    //      //  
312    buff[0] = 0xFA;    buff[0] = 0xFA;
313    buff[1] = 0xFE;    buff[1] = 0xFE;
314    buff[2] = 0xDE;    buff[2] = 0xDE;
315    //    //
316    // packet type (twice)    // packet type (twice)
317    //    //
318    buff[3] = type;    buff[3] = type;
319    buff[4] = type;    buff[4] = type;
320    //    //
321    // counter    // counter
322    //    //
323    fCounter++;    fCounter++;
324    while ( fCounter > 16777215 ){    while ( fCounter > 16777215 ){
325      fCounter -= 16777215;      fCounter -= 16777215;
326    };    };
327    //    //
328    buff[5] = (UChar_t)(fCounter >> 16);    buff[5] = (UChar_t)(fCounter >> 16);
329    buff[6] = (UChar_t)(fCounter >> 8);    buff[6] = (UChar_t)(fCounter >> 8);
330    buff[7] = (UChar_t)fCounter;    buff[7] = (UChar_t)fCounter;
331    //    //
332    // on board time    // on board time
333    //    //
334    ULong64_t obt = fOBT + 30LL;    ULong64_t obt = fOBT + 30LL;
335    //    //
336    while ( obt > 4294967295LL ){    while ( obt > 4294967295LL ){
337      obt -= 4294967295LL;      obt -= 4294967295LL;
338    };    };
339    fOBT = (UInt_t)obt;    fOBT = (UInt_t)obt;
340    //    //
341    buff[8] = (UChar_t)(fOBT >> 24);    buff[8] = (UChar_t)(fOBT >> 24);
342    buff[9] = (UChar_t)(fOBT >> 16);    buff[9] = (UChar_t)(fOBT >> 16);
343    buff[10] = (UChar_t)(fOBT >> 8);    buff[10] = (UChar_t)(fOBT >> 8);
344    buff[11] = (UChar_t)fOBT;    buff[11] = (UChar_t)fOBT;
345    //    //
346    // Packet length    // Packet length
347    //    //
348    fLen = length;    fLen = length;
349    //    //
350    buff[12] = (UChar_t)(fLen >> 16);    buff[12] = (UChar_t)(fLen >> 16);
351    buff[13] = (UChar_t)(fLen >> 8);    buff[13] = (UChar_t)(fLen >> 8);
352    buff[14] = (UChar_t)fLen;    buff[14] = (UChar_t)fLen;
353    //    //
354    // CPU header CRC    // CPU header CRC
355    //    //
356    buff[15] = (BYTE)CM_Compute_CRC16((UINT16)0, (BYTE*)&buff, (UINT32)15);    buff[15] = (BYTE)CM_Compute_CRC16((UINT16)0, (BYTE*)&buff, (UINT32)15);
357    //    //
358    memcpy(fDataPSCU,buff,16*sizeof(UChar_t));    memcpy(fDataPSCU,buff,16*sizeof(UChar_t));
359    //    //
360  };  };
361    
362  void Digitizer::ClearCaloCalib(Int_t s){  void Digitizer::ClearCaloCalib(Int_t s){
363    //    //
364    fcstwerr[s] = 0;    fcstwerr[s] = 0;
365    fcperror[s] = 0.;    fcperror[s] = 0.;
366    for ( Int_t d=0 ; d<11 ;d++  ){    for ( Int_t d=0 ; d<11 ;d++  ){
367      Int_t pre = -1;      Int_t pre = -1;
368      for ( Int_t j=0; j<96 ;j++){      for ( Int_t j=0; j<96 ;j++){
369        if ( j%16 == 0 ) pre++;        if ( j%16 == 0 ) pre++;
370        fcalped[s][d][j] = 0.;        fcalped[s][d][j] = 0.;
371        fcstwerr[s] = 0.;        fcstwerr[s] = 0.;
372        fcperror[s] = 0.;        fcperror[s] = 0.;
373        fcalgood[s][d][j] = 0.;        fcalgood[s][d][j] = 0.;
374        fcalthr[s][d][pre] = 0.;        fcalthr[s][d][pre] = 0.;
375        fcalrms[s][d][j] = 0.;        fcalrms[s][d][j] = 0.;
376        fcalbase[s][d][pre] = 0.;        fcalbase[s][d][pre] = 0.;
377        fcalvar[s][d][pre] = 0.;        fcalvar[s][d][pre] = 0.;
378      };      };
379    };    };
380    return;    return;
381  }  }
382    
383  Int_t Digitizer::CaloLoadCalib(Int_t s,TString fcalname, UInt_t calibno){  Int_t Digitizer::CaloLoadCalib(Int_t s,TString fcalname, UInt_t calibno){
384    //    //
385    //    //
386    UInt_t e = 0;    UInt_t e = 0;
387    if ( s == 0 ) e = 0;    if ( s == 0 ) e = 0;
388    if ( s == 1 ) e = 2;    if ( s == 1 ) e = 2;
389    if ( s == 2 ) e = 3;    if ( s == 2 ) e = 3;
390    if ( s == 3 ) e = 1;    if ( s == 3 ) e = 1;
391    //    //
392    ifstream myfile;    ifstream myfile;
393    myfile.open(fcalname.Data());    myfile.open(fcalname.Data());
394    if ( !myfile ){        if ( !myfile ){    
395      return(-107);      return(-107);
396    };    };
397    myfile.close();    myfile.close();
398    //    //
399    TFile *File = new TFile(fcalname.Data());    TFile *File = new TFile(fcalname.Data());
400    if ( !File ) return(-108);    if ( !File ) return(-108);
401    TTree *tr = (TTree*)File->Get("CalibCalPed");    TTree *tr = (TTree*)File->Get("CalibCalPed");
402    if ( !tr ) return(-109);    if ( !tr ) return(-109);
403    //    //
404    TBranch *calo = tr->GetBranch("CalibCalPed");    TBranch *calo = tr->GetBranch("CalibCalPed");
405    //    //
406    pamela::CalibCalPedEvent *ce = 0;    pamela::CalibCalPedEvent *ce = 0;
407    tr->SetBranchAddress("CalibCalPed", &ce);    tr->SetBranchAddress("CalibCalPed", &ce);
408    //    //
409    Long64_t ncalibs = calo->GetEntries();    Long64_t ncalibs = calo->GetEntries();
410    //    //
411    if ( !ncalibs ) return(-110);    if ( !ncalibs ) return(-110);
412    //    //
413    calo->GetEntry(calibno);    calo->GetEntry(calibno);
414    //    //
415    if (ce->cstwerr[s] != 0 && ce->cperror[s] == 0 ) {    if (ce->cstwerr[s] != 0 && ce->cperror[s] == 0 ) {
416      fcstwerr[s] = ce->cstwerr[s];      fcstwerr[s] = ce->cstwerr[s];
417      fcperror[s] = ce->cperror[s];      fcperror[s] = ce->cperror[s];
418      for ( Int_t d=0 ; d<11 ;d++  ){      for ( Int_t d=0 ; d<11 ;d++  ){
419        Int_t pre = -1;        Int_t pre = -1;
420        for ( Int_t j=0; j<96 ;j++){        for ( Int_t j=0; j<96 ;j++){
421          if ( j%16 == 0 ) pre++;          if ( j%16 == 0 ) pre++;
422          fcalped[s][d][j] = ce->calped[e][d][j];          fcalped[s][d][j] = ce->calped[e][d][j];
423          fcalgood[s][d][j] = ce->calgood[e][d][j];          fcalgood[s][d][j] = ce->calgood[e][d][j];
424          fcalthr[s][d][pre] = ce->calthr[e][d][pre];          fcalthr[s][d][pre] = ce->calthr[e][d][pre];
425          fcalrms[s][d][j] = ce->calrms[e][d][j];          fcalrms[s][d][j] = ce->calrms[e][d][j];
426          fcalbase[s][d][pre] = ce->calbase[e][d][pre];          fcalbase[s][d][pre] = ce->calbase[e][d][pre];
427          fcalvar[s][d][pre] = ce->calvar[e][d][pre];          fcalvar[s][d][pre] = ce->calvar[e][d][pre];
428        };        };
429      };      };
430    } else {    } else {
431      printf(" CALORIMETER - ERROR: problems finding a good calibration in this file! \n\n ");      printf(" CALORIMETER - ERROR: problems finding a good calibration in this file! \n\n ");
432      File->Close();      File->Close();
433      return(-111);      return(-111);
434    };    };
435    File->Close();    File->Close();
436    return(0);    return(0);
437  }  }
438    
439    
440  void Digitizer::DigitizeCALOCALIB() {  void Digitizer::DigitizeCALOCALIB() {
441    //    //
442    // Header of the four sections    // Header of the four sections
443    //    //
444    fSecCalo[0] = 0xAA00; // XE    fSecCalo[0] = 0xAA00; // XE
445    fSecCalo[1] = 0xB100; // XO    fSecCalo[1] = 0xB100; // XO
446    fSecCalo[2] = 0xB600; // YE    fSecCalo[2] = 0xB600; // YE
447    fSecCalo[3] = 0xAD00; // YO    fSecCalo[3] = 0xAD00; // YO
448    //    //
449    // length of the data is 0x1215    // length of the data is 0x1215
450    //    //
451    fSecCALOLength[0] = 0x1215; // XE    fSecCALOLength[0] = 0x1215; // XE
452    fSecCALOLength[1] = 0x1215; // XO    fSecCALOLength[1] = 0x1215; // XO
453    fSecCALOLength[2] = 0x1215; // YE    fSecCALOLength[2] = 0x1215; // YE
454    fSecCALOLength[3] = 0x1215; // YO    fSecCALOLength[3] = 0x1215; // YO
455    //    //
456    Int_t chksum = 0;    Int_t chksum = 0;
457    UInt_t tstrip = 0;    UInt_t tstrip = 0;
458    UInt_t fSecPointer = 0;    UInt_t fSecPointer = 0;
459    //    //
460    for (Int_t sec=0; sec < 4; sec++){    for (Int_t sec=0; sec < 4; sec++){
461      //      //
462      // sec =    0 -> XE      1 -> XO        2-> YE         3 -> YO      // sec =    0 -> XE      1 -> XO        2-> YE         3 -> YO
463      //      //
464      fCALOlength = 0;      fCALOlength = 0;
465      memset(fDataCALO,0,sizeof(UShort_t)*fCALObuffer);      memset(fDataCALO,0,sizeof(UShort_t)*fCALObuffer);
466      fSecPointer = fCALOlength;      fSecPointer = fCALOlength;
467      //      //
468      // First of all we have section header and packet length      // First of all we have section header and packet length
469      //      //
470      fDataCALO[fCALOlength] = fSecCalo[sec];      fDataCALO[fCALOlength] = fSecCalo[sec];
471      fCALOlength++;      fCALOlength++;
472      fDataCALO[fCALOlength] = fSecCALOLength[sec];      fDataCALO[fCALOlength] = fSecCALOLength[sec];
473      fCALOlength++;      fCALOlength++;
474      //      //
475      // Section XO is read in the opposite direction respect to the others      // Section XO is read in the opposite direction respect to the others
476      //      //
477      chksum = 0;      chksum = 0;
478      //      //
479      for (Int_t plane=0; plane < 11; plane++){      for (Int_t plane=0; plane < 11; plane++){
480        //        //
481        if ( sec == 1 ) tstrip = fCALOlength + 96*2;        if ( sec == 1 ) tstrip = fCALOlength + 96*2;
482        //        //
483        for (Int_t strip=0; strip < 96; strip++){          for (Int_t strip=0; strip < 96; strip++){  
484          //          //
485          chksum += (Int_t)fcalped[sec][plane][strip];          chksum += (Int_t)fcalped[sec][plane][strip];
486          //          //
487          // save value          // save value
488          //          //
489          if ( sec == 1 ){          if ( sec == 1 ){
490            tstrip -= 2;            tstrip -= 2;
491            fDataCALO[tstrip] = (Int_t)fcalped[sec][plane][strip];            fDataCALO[tstrip] = (Int_t)fcalped[sec][plane][strip];
492            fDataCALO[tstrip+1] = (Int_t)fcalgood[sec][plane][strip];            fDataCALO[tstrip+1] = (Int_t)fcalgood[sec][plane][strip];
493          } else {          } else {
494            fDataCALO[fCALOlength] = (Int_t)fcalped[sec][plane][strip];            fDataCALO[fCALOlength] = (Int_t)fcalped[sec][plane][strip];
495            fDataCALO[fCALOlength+1] = (Int_t)fcalgood[sec][plane][strip];            fDataCALO[fCALOlength+1] = (Int_t)fcalgood[sec][plane][strip];
496          };          };
497          fCALOlength +=2;          fCALOlength +=2;
498        };        };
499        //        //
500      };      };
501      //      //
502      fDataCALO[fCALOlength] = (UShort_t)chksum;      fDataCALO[fCALOlength] = (UShort_t)chksum;
503      fCALOlength++;      fCALOlength++;
504      fDataCALO[fCALOlength] = 0;      fDataCALO[fCALOlength] = 0;
505      fCALOlength++;      fCALOlength++;
506      fDataCALO[fCALOlength] = (UShort_t)((Int_t)(chksum >> 16));      fDataCALO[fCALOlength] = (UShort_t)((Int_t)(chksum >> 16));
507      fCALOlength++;      fCALOlength++;
508      //      //
509      // Section XO is read in the opposite direction respect to the others      // Section XO is read in the opposite direction respect to the others
510      //      //
511      chksum = 0;      chksum = 0;
512      //      //
513      for (Int_t plane=0; plane < 11; plane++){      for (Int_t plane=0; plane < 11; plane++){
514        //        //
515        if ( sec == 1 ) tstrip = fCALOlength+6*2;        if ( sec == 1 ) tstrip = fCALOlength+6*2;
516        //        //
517        for (Int_t strip=0; strip < 6; strip++){        for (Int_t strip=0; strip < 6; strip++){
518          //          //
519          chksum += (Int_t)fcalthr[sec][plane][strip];          chksum += (Int_t)fcalthr[sec][plane][strip];
520          //          //
521          // save value          // save value
522          //          //
523          if ( sec == 1 ){          if ( sec == 1 ){
524            tstrip -= 2;            tstrip -= 2;
525            fDataCALO[tstrip] = 0;            fDataCALO[tstrip] = 0;
526            fDataCALO[tstrip+1] = (Int_t)fcalthr[sec][plane][strip];            fDataCALO[tstrip+1] = (Int_t)fcalthr[sec][plane][strip];
527          } else {          } else {
528            fDataCALO[fCALOlength] = 0;            fDataCALO[fCALOlength] = 0;
529            fDataCALO[fCALOlength+1] = (Int_t)fcalthr[sec][plane][strip];            fDataCALO[fCALOlength+1] = (Int_t)fcalthr[sec][plane][strip];
530          };          };
531          fCALOlength +=2;          fCALOlength +=2;
532        };        };
533        //        //
534      };      };
535      //      //
536      fDataCALO[fCALOlength] = 0;      fDataCALO[fCALOlength] = 0;
537      fCALOlength++;      fCALOlength++;
538      fDataCALO[fCALOlength] = (UShort_t)chksum;      fDataCALO[fCALOlength] = (UShort_t)chksum;
539      fCALOlength++;      fCALOlength++;
540      fDataCALO[fCALOlength] = 0;      fDataCALO[fCALOlength] = 0;
541      fCALOlength++;      fCALOlength++;
542      fDataCALO[fCALOlength] = (UShort_t)((Int_t)(chksum >> 16));      fDataCALO[fCALOlength] = (UShort_t)((Int_t)(chksum >> 16));
543      fCALOlength++;      fCALOlength++;
544      //      //
545      // Section XO is read in the opposite direction respect to the others      // Section XO is read in the opposite direction respect to the others
546      //      //
547      for (Int_t plane=0; plane < 11; plane++){      for (Int_t plane=0; plane < 11; plane++){
548        //        //
549        if ( sec == 1 ) tstrip = fCALOlength+96*2;        if ( sec == 1 ) tstrip = fCALOlength+96*2;
550        //        //
551        for (Int_t strip=0; strip < 96; strip++){        for (Int_t strip=0; strip < 96; strip++){
552          //          //
553          // save value          // save value
554          //          //
555          if ( sec == 1 ){          if ( sec == 1 ){
556            tstrip -= 2;            tstrip -= 2;
557            fDataCALO[tstrip] = 0;            fDataCALO[tstrip] = 0;
558            fDataCALO[tstrip+1] = (Int_t)fcalrms[sec][plane][strip];            fDataCALO[tstrip+1] = (Int_t)fcalrms[sec][plane][strip];
559          } else {          } else {
560            fDataCALO[fCALOlength] = 0;            fDataCALO[fCALOlength] = 0;
561            fDataCALO[fCALOlength+1] = (Int_t)fcalrms[sec][plane][strip];            fDataCALO[fCALOlength+1] = (Int_t)fcalrms[sec][plane][strip];
562          };          };
563          fCALOlength += 2;          fCALOlength += 2;
564        };        };
565        //        //
566      };          };    
567      //      //
568      // Section XO is read in the opposite direction respect to the others      // Section XO is read in the opposite direction respect to the others
569      //      //
570      for (Int_t plane=0; plane < 11; plane++){      for (Int_t plane=0; plane < 11; plane++){
571        //        //
572        if ( sec == 1 ) tstrip = fCALOlength+6*4;        if ( sec == 1 ) tstrip = fCALOlength+6*4;
573        //        //
574        for (Int_t strip=0; strip < 6; strip++){        for (Int_t strip=0; strip < 6; strip++){
575          //          //
576          // save value          // save value
577          //          //
578          if ( sec == 1 ){          if ( sec == 1 ){
579            tstrip -= 4;            tstrip -= 4;
580            fDataCALO[tstrip] = 0;            fDataCALO[tstrip] = 0;
581            fDataCALO[tstrip+1] = (Int_t)fcalbase[sec][plane][strip];            fDataCALO[tstrip+1] = (Int_t)fcalbase[sec][plane][strip];
582            fDataCALO[tstrip+2] = 0;            fDataCALO[tstrip+2] = 0;
583            fDataCALO[tstrip+3] = (Int_t)fcalvar[sec][plane][strip];            fDataCALO[tstrip+3] = (Int_t)fcalvar[sec][plane][strip];
584          } else {          } else {
585            fDataCALO[fCALOlength] = 0;            fDataCALO[fCALOlength] = 0;
586            fDataCALO[fCALOlength+1] = (Int_t)fcalbase[sec][plane][strip];            fDataCALO[fCALOlength+1] = (Int_t)fcalbase[sec][plane][strip];
587            fDataCALO[fCALOlength+2] = 0;            fDataCALO[fCALOlength+2] = 0;
588            fDataCALO[fCALOlength+3] = (Int_t)fcalvar[sec][plane][strip];            fDataCALO[fCALOlength+3] = (Int_t)fcalvar[sec][plane][strip];
589          };          };
590          fCALOlength +=4;          fCALOlength +=4;
591        };        };
592        //        //
593      };            };      
594      //      //
595      //      //
596      // here we calculate and save the CRC      // here we calculate and save the CRC
597      //      //
598      fDataCALO[fCALOlength] = 0;      fDataCALO[fCALOlength] = 0;
599      fCALOlength++;      fCALOlength++;
600      Short_t CRC = 0;      Short_t CRC = 0;
601      for (UInt_t i=0; i<(fCALOlength-fSecPointer); i++){      for (UInt_t i=0; i<(fCALOlength-fSecPointer); i++){
602        CRC=crc(CRC,fDataCALO[i+fSecPointer]);        CRC=crc(CRC,fDataCALO[i+fSecPointer]);
603      };      };
604      fDataCALO[fCALOlength] = (UShort_t)CRC;      fDataCALO[fCALOlength] = (UShort_t)CRC;
605      fCALOlength++;      fCALOlength++;
606      //      //
607      UInt_t length=fCALOlength*2;      UInt_t length=fCALOlength*2;
608      DigitizePSCU(length,0x18);      DigitizePSCU(length,0x18);
609      //      //
610      // Add padding to 64 bits      // Add padding to 64 bits
611      //      //
612      AddPadding();      AddPadding();
613      //      //
614      fOutputfile.write(reinterpret_cast<char*>(fDataPSCU),sizeof(UShort_t)*fPSCUbuffer);      fOutputfile.write(reinterpret_cast<char*>(fDataPSCU),sizeof(UShort_t)*fPSCUbuffer);
615      UShort_t temp[1000000];      UShort_t temp[1000000];
616      memset(temp,0,sizeof(UShort_t)*1000000);      memset(temp,0,sizeof(UShort_t)*1000000);
617      swab(fDataCALO,temp,sizeof(UShort_t)*fCALOlength);  // WE MUST SWAP THE BYTES!!!      swab(fDataCALO,temp,sizeof(UShort_t)*fCALOlength);  // WE MUST SWAP THE BYTES!!!
618      fOutputfile.write(reinterpret_cast<char*>(temp),sizeof(UShort_t)*fCALOlength);      fOutputfile.write(reinterpret_cast<char*>(temp),sizeof(UShort_t)*fCALOlength);
619      //      //
620      // padding to 64 bytes      // padding to 64 bytes
621      //      //
622      if ( fPadding ){      if ( fPadding ){
623        fOutputfile.write(reinterpret_cast<char*>(fDataPadding),sizeof(UChar_t)*fPadding);        fOutputfile.write(reinterpret_cast<char*>(fDataPadding),sizeof(UChar_t)*fPadding);
624      };      };
625      //      //
626      //          //    
627    };    };
628    //    //
629  };  };
630    
631  void Digitizer::CaloLoadCalib() {  void Digitizer::CaloLoadCalib() {
632    //    //
633    fGivenCaloCalib = 0; //                                  ####@@@@ should be given as input par @@@@####    fGivenCaloCalib = 0; //                                  ####@@@@ should be given as input par @@@@####
634    //    //
635    // first of all load the MIP to ADC conversion values    // first of all load the MIP to ADC conversion values
636    //    //
637    stringstream calfile;    stringstream calfile;
638    Int_t error = 0;    Int_t error = 0;
639    GL_PARAM *glparam = new GL_PARAM();    GL_PARAM *glparam = new GL_PARAM();
640    //    //
641    // determine where I can find calorimeter ADC to MIP conversion file      // determine where I can find calorimeter ADC to MIP conversion file  
642    //    //
643    error = 0;    error = 0;
644    error = glparam->Query_GL_PARAM(3,101,fDbc);    error = glparam->Query_GL_PARAM(3,101,fDbc);
645    //    //
646    calfile.str("");    calfile.str("");
647    calfile << glparam->PATH.Data() << "/";    calfile << glparam->PATH.Data() << "/";
648    calfile << glparam->NAME.Data();    calfile << glparam->NAME.Data();
649    //    //
650    printf("\n Using Calorimeter ADC to MIP conversion file: \n %s \n",calfile.str().c_str());    printf("\n Using Calorimeter ADC to MIP conversion file: \n %s \n",calfile.str().c_str());
651    FILE *f;    FILE *f;
652    f = fopen(calfile.str().c_str(),"rb");    f = fopen(calfile.str().c_str(),"rb");
653    //    //
654    memset(fCalomip,0,4224*sizeof(fCalomip[0][0][0]));    memset(fCalomip,0,4224*sizeof(fCalomip[0][0][0]));
655    //    //
656    for (Int_t m = 0; m < 2 ; m++ ){    for (Int_t m = 0; m < 2 ; m++ ){
657      for (Int_t k = 0; k < 22; k++ ){      for (Int_t k = 0; k < 22; k++ ){
658        for (Int_t l = 0; l < 96; l++ ){        for (Int_t l = 0; l < 96; l++ ){
659          fread(&fCalomip[m][k][l],sizeof(fCalomip[m][k][l]),1,f);          fread(&fCalomip[m][k][l],sizeof(fCalomip[m][k][l]),1,f);
660        };        };
661      };      };
662    };    };
663    fclose(f);    fclose(f);
664    //    //
665    // determine which calibration has to be used and load it for each section    // determine which calibration has to be used and load it for each section
666    //      //  
667    GL_CALO_CALIB *glcalo = new GL_CALO_CALIB();    GL_CALO_CALIB *glcalo = new GL_CALO_CALIB();
668    GL_ROOT *glroot = new GL_ROOT();      GL_ROOT *glroot = new GL_ROOT();  
669    TString fcalname;    TString fcalname;
670    UInt_t idcalib;    UInt_t idcalib;
671    UInt_t calibno;    UInt_t calibno;
672    UInt_t utime = 0;    UInt_t utime = 0;
673    //    //
674    for (UInt_t s=0; s<4; s++){    for (UInt_t s=0; s<4; s++){
675      //      //
676      // clear calo calib variables for section s      // clear calo calib variables for section s
677      //      //
678      ClearCaloCalib(s);      ClearCaloCalib(s);
679      //      //
680      if ( fGivenCaloCalib ){      if ( fGivenCaloCalib ){
681        //        //
682        // a time has been given as input on the command line so retrieve the calibration that preceed that time        // a time has been given as input on the command line so retrieve the calibration that preceed that time
683        //        //
684        glcalo->Query_GL_CALO_CALIB(fGivenCaloCalib,utime,s,fDbc);        glcalo->Query_GL_CALO_CALIB(fGivenCaloCalib,utime,s,fDbc);
685        //          //  
686        calibno = glcalo->EV_ROOT;        calibno = glcalo->EV_ROOT;
687        idcalib = glcalo->ID_ROOT_L0;        idcalib = glcalo->ID_ROOT_L0;
688        //        //
689        // determine path and name and entry of the calibration file        // determine path and name and entry of the calibration file
690        //        //
691        printf("\n");        printf("\n");
692        printf(" ** SECTION %i **\n",s);        printf(" ** SECTION %i **\n",s);
693        //        //
694        glroot->Query_GL_ROOT(idcalib,fDbc);        glroot->Query_GL_ROOT(idcalib,fDbc);
695        //        //
696        stringstream name;        stringstream name;
697        name.str("");        name.str("");
698        name << glroot->PATH.Data() << "/";        name << glroot->PATH.Data() << "/";
699        name << glroot->NAME.Data();        name << glroot->NAME.Data();
700        //        //
701        fcalname = (TString)name.str().c_str();        fcalname = (TString)name.str().c_str();
702        //        //
703        printf("\n Section %i : using  file %s calibration at entry %i: \n",s,fcalname.Data(),calibno);        printf("\n Section %i : using  file %s calibration at entry %i: \n",s,fcalname.Data(),calibno);
704        //        //
705      } else {      } else {
706        error = 0;        error = 0;
707        error = glparam->Query_GL_PARAM(1,104,fDbc);        error = glparam->Query_GL_PARAM(1,104,fDbc);
708        //        //
709        calfile.str("");        calfile.str("");
710        calfile << glparam->PATH.Data() << "/";        calfile << glparam->PATH.Data() << "/";
711        calfile << glparam->NAME.Data();        calfile << glparam->NAME.Data();
712        //        //
713        printf("\n Section %i : using default calorimeter calibration: \n %s \n",s,calfile.str().c_str());        printf("\n Section %i : using default calorimeter calibration: \n %s \n",s,calfile.str().c_str());
714        //        //
715        fcalname = (TString)calfile.str().c_str();        fcalname = (TString)calfile.str().c_str();
716        calibno = s;        calibno = s;
717        //        //
718      };      };
719      //      //
720      // load calibration variables in memory      // load calibration variables in memory
721      //      //
722      CaloLoadCalib(s,fcalname,calibno);      CaloLoadCalib(s,fcalname,calibno);
723      //      //
724    };    };
725    //    //
726    // at this point we have in memory the calorimeter calibration and we can save it to disk in the correct format and use it to digitize the data    // at this point we have in memory the calorimeter calibration and we can save it to disk in the correct format and use it to digitize the data
727    //    //
728    delete glparam;    delete glparam;
729    delete glcalo;    delete glcalo;
730    delete glroot;    delete glroot;
731  };  };
732    
733  void Digitizer::DigitizeCALO() {  void Digitizer::DigitizeCALO() {
734    //    //
735    fModCalo = 0; // 0 is RAW, 1 is COMPRESS, 2 is FULL     ####@@@@ should be given as input par @@@@####    fModCalo = 0; // 0 is RAW, 1 is COMPRESS, 2 is FULL     ####@@@@ should be given as input par @@@@####
736    //    //
737    //    //
738    //    //
739    fCALOlength = 0;  // reset total dimension of calo data    fCALOlength = 0;  // reset total dimension of calo data
740    //    //
741    // gpamela variables to be used    // gpamela variables to be used
742    //    //
743    fhBookTree->SetBranchStatus("Nthcali",1);    fhBookTree->SetBranchStatus("Nthcali",1);
744    fhBookTree->SetBranchStatus("Icaplane",1);    fhBookTree->SetBranchStatus("Icaplane",1);
745    fhBookTree->SetBranchStatus("Icastrip",1);    fhBookTree->SetBranchStatus("Icastrip",1);
746    fhBookTree->SetBranchStatus("Icamod",1);    fhBookTree->SetBranchStatus("Icamod",1);
747    fhBookTree->SetBranchStatus("Enestrip",1);    fhBookTree->SetBranchStatus("Enestrip",1);
748    //    //
749    // call different routines depending on the acq mode you want to simulate    // call different routines depending on the acq mode you want to simulate
750    //    //
751    switch ( fModCalo ){    switch ( fModCalo ){
752    case 0:    case 0:
753      this->DigitizeCALORAW();      this->DigitizeCALORAW();
754      break;      break;
755    case 1:    case 1:
756      this->DigitizeCALOCOMPRESS();      this->DigitizeCALOCOMPRESS();
757      break;      break;
758    case 2:    case 2:
759      this->DigitizeCALOFULL();      this->DigitizeCALOFULL();
760      break;      break;
761    };    };
762    //    //
763  };  };
764    
765  Float_t Digitizer::GetCALOen(Int_t sec, Int_t plane, Int_t strip){  Float_t Digitizer::GetCALOen(Int_t sec, Int_t plane, Int_t strip){
766    //    //
767    // determine plane and strip    // determine plane and strip
768    //    //
769    Int_t mplane = 0;    Int_t mplane = 0;
770    //    //
771    // wrong!    // wrong!
772    //    //
773    //  if ( sec == 0 || sec == 3 ) mplane = (plane * 4) + sec + 1;      //  if ( sec == 0 || sec == 3 ) mplane = (plane * 4) + sec + 1;  
774    //  if ( sec == 1 ) mplane = (plane * 4) + 2 + 1;      //  if ( sec == 1 ) mplane = (plane * 4) + 2 + 1;  
775    //  if ( sec == 2 ) mplane = (plane * 4) + 1 + 1;      //  if ( sec == 2 ) mplane = (plane * 4) + 1 + 1;  
776    //    //
777    if ( sec == 0 ) mplane = plane * 4 + 1; // it must be 0, 4, 8, ... (+1)  from plane = 0, 11    if ( sec == 0 ) mplane = plane * 4 + 1; // it must be 0, 4, 8, ... (+1)  from plane = 0, 11
778    if ( sec == 1 ) mplane = plane * 4 + 2 + 1; // it must be 2, 6, 10, ... (+1)  from plane = 0, 11    if ( sec == 1 ) mplane = plane * 4 + 2 + 1; // it must be 2, 6, 10, ... (+1)  from plane = 0, 11
779    if ( sec == 2 ) mplane = plane * 4 + 3 + 1; // it must be 3, 7, 11, ... (+1)  from plane = 0, 11    if ( sec == 2 ) mplane = plane * 4 + 3 + 1; // it must be 3, 7, 11, ... (+1)  from plane = 0, 11
780    if ( sec == 3 ) mplane = plane * 4 + 1 + 1; // it must be 1, 5, 9, ... (+1)  from plane = 0, 11    if ( sec == 3 ) mplane = plane * 4 + 1 + 1; // it must be 1, 5, 9, ... (+1)  from plane = 0, 11
781    //    //
782    Int_t mstrip = strip + 1;    Int_t mstrip = strip + 1;
783    //    //
784    // search energy release in gpamela output    // search energy release in gpamela output
785    //    //
786    for (Int_t i=0; i<Nthcali;i++){    for (Int_t i=0; i<Nthcali;i++){
787      if ( Icaplane[i] == mplane && Icastrip[i] == mstrip ){      if ( Icaplane[i] == mplane && Icastrip[i] == mstrip ){
788        return (Enestrip[i]);        return (Enestrip[i]);
789      };      };
790    };    };
791    //    //
792    // if not found it means no energy release so return 0.    // if not found it means no energy release so return 0.
793    //    //
794    return(0.);    return(0.);
795  };  };
796    
797  void Digitizer::DigitizeCALORAW() {  void Digitizer::DigitizeCALORAW() {
798    //    //
799    // some variables    // some variables
800    //    //
801    Float_t ens = 0.;    Float_t ens = 0.;
802    UInt_t adcsig = 0;    UInt_t adcsig = 0;
803    UInt_t adcbase = 0;    UInt_t adcbase = 0;
804    UInt_t adc = 0;    UInt_t adc = 0;
805    Int_t pre = 0;    Int_t pre = 0;
806    UInt_t l = 0;    UInt_t l = 0;
807    UInt_t lpl = 0;    UInt_t lpl = 0;
808    UInt_t tstrip = 0;    UInt_t tstrip = 0;
809    UInt_t fSecPointer = 0;    UInt_t fSecPointer = 0;
810    Double_t pedenoise;    Double_t pedenoise;
811    Float_t rms = 0.;    Float_t rms = 0.;
812    Float_t pedestal = 0.;    Float_t pedestal = 0.;
813    //    //
814    // clean the data structure    // clean the data structure
815    //    //
816    memset(fDataCALO,0,sizeof(UShort_t)*fCALObuffer);    memset(fDataCALO,0,sizeof(UShort_t)*fCALObuffer);
817    //    //
818    // Header of the four sections    // Header of the four sections
819    //    //
820    fSecCalo[0] = 0xEA08; // XE    fSecCalo[0] = 0xEA08; // XE
821    fSecCalo[1] = 0xF108; // XO    fSecCalo[1] = 0xF108; // XO
822    fSecCalo[2] = 0xF608; // YE    fSecCalo[2] = 0xF608; // YE
823    fSecCalo[3] = 0xED08; // YO    fSecCalo[3] = 0xED08; // YO
824    //    //
825    // length of the data is 0x0428 in RAW mode    // length of the data is 0x0428 in RAW mode
826    //    //
827    fSecCALOLength[0] = 0x0428; // XE    fSecCALOLength[0] = 0x0428; // XE
828    fSecCALOLength[1] = 0x0428; // XO    fSecCALOLength[1] = 0x0428; // XO
829    fSecCALOLength[2] = 0x0428; // YE    fSecCALOLength[2] = 0x0428; // YE
830    fSecCALOLength[3] = 0x0428; // YO    fSecCALOLength[3] = 0x0428; // YO
831    //    //
832    // let's start    // let's start
833    //    //
834    fCALOlength = 0;    fCALOlength = 0;
835    //    //
836    for (Int_t sec=0; sec < 4; sec++){    for (Int_t sec=0; sec < 4; sec++){
837      //      //
838      // sec =    0 -> XE      1 -> XO        2-> YE         3 -> YO      // sec =    0 -> XE      1 -> XO        2-> YE         3 -> YO
839      //      //
840      l = 0;                 // XE and XO are Y planes      l = 0;                 // XE and XO are Y planes
841      if ( sec < 2 ) l = 1;  // while YE and  YO are X planes      if ( sec < 2 ) l = 1;  // while YE and  YO are X planes
842      //      //
843      fSecPointer = fCALOlength;      fSecPointer = fCALOlength;
844      //      //
845      // First of all we have section header and packet length      // First of all we have section header and packet length
846      //      //
847      fDataCALO[fCALOlength] = fSecCalo[sec];      fDataCALO[fCALOlength] = fSecCalo[sec];
848      fCALOlength++;      fCALOlength++;
849      fDataCALO[fCALOlength] = fSecCALOLength[sec];      fDataCALO[fCALOlength] = fSecCALOLength[sec];
850      fCALOlength++;      fCALOlength++;
851      //      //
852      // selftrigger coincidences - in the future we should add here some code to simulate timing response of pre-amplifiers      // selftrigger coincidences - in the future we should add here some code to simulate timing response of pre-amplifiers
853      //      //
854      for (Int_t autoplane=0; autoplane < 7; autoplane++){      for (Int_t autoplane=0; autoplane < 7; autoplane++){
855        fDataCALO[fCALOlength] = 0x0000;        fDataCALO[fCALOlength] = 0x0000;
856        fCALOlength++;        fCALOlength++;
857      };      };
858      //      //
859      //      //
860      // here comes data      // here comes data
861      //      //
862      //      //
863      // Section XO is read in the opposite direction respect to the others      // Section XO is read in the opposite direction respect to the others
864      //      //
865      if ( sec == 1 ){            if ( sec == 1 ){      
866        tstrip = 96*11 + fCALOlength;        tstrip = 96*11 + fCALOlength;
867      } else {      } else {
868        tstrip = 0;        tstrip = 0;
869      };      };
870      //      //
871      pre = -1;      pre = -1;
872      //      //
873      for (Int_t strip=0; strip < 96; strip++){        for (Int_t strip=0; strip < 96; strip++){  
874        //        //
875        // which is the pre for this strip?        // which is the pre for this strip?
876        //        //
877        if (strip%16 == 0) {        if (strip%16 == 0) {
878          pre++;          pre++;
879        };        };
880        //        //
881        if ( sec == 1 ) tstrip -= 11;        if ( sec == 1 ) tstrip -= 11;
882        //        //
883        for (Int_t plane=0; plane < 11; plane++){        for (Int_t plane=0; plane < 11; plane++){
884          //          //
885          // here is wrong!!!!          // here is wrong!!!!
886          //          //
887          //          //
888          //      if ( plane%2 == 0 && sec%2 != 0){          //      if ( plane%2 == 0 && sec%2 != 0){
889          //        lpl = plane*2;          //        lpl = plane*2;
890          //      } else {          //      } else {
891          //        lpl = (plane*2) + 1;          //        lpl = (plane*2) + 1;
892          //      };          //      };
893          //          //
894          if ( sec == 0 || sec == 3 ) lpl = plane * 2;          if ( sec == 0 || sec == 3 ) lpl = plane * 2;
895          if ( sec == 1 || sec == 2 ) lpl = (plane * 2) + 1;          if ( sec == 1 || sec == 2 ) lpl = (plane * 2) + 1;
896          //          //
897          // get the energy in GeV from the simulation for that strip          // get the energy in GeV from the simulation for that strip
898          //          //
899          ens = this->GetCALOen(sec,plane,strip);          ens = this->GetCALOen(sec,plane,strip);
900          //          //
901          // convert it into ADC channels          // convert it into ADC channels
902          //                //      
903          adcsig = int(ens*fCalomip[l][lpl][strip]/fCALOGeV2MIPratio);          adcsig = int(ens*fCalomip[l][lpl][strip]/fCALOGeV2MIPratio);
904          //          //
905          // sum baselines          // sum baselines
906          //          //
907          adcbase = (UInt_t)fcalbase[sec][plane][pre];          adcbase = (UInt_t)fcalbase[sec][plane][pre];
908          //          //
909          // add noise and pedestals          // add noise and pedestals
910          //                //      
911          pedestal = fcalped[sec][plane][strip];          pedestal = fcalped[sec][plane][strip];
912          rms = fcalrms[sec][plane][strip]/4.;          rms = fcalrms[sec][plane][strip]/4.;
913          //          //
914          // Add random gaussian noise of RMS rms and Centered in the pedestal          // Add random gaussian noise of RMS rms and Centered in the pedestal
915          //          //
916          pedenoise = gRandom->Gaus((Double_t)pedestal,(Double_t)rms);          pedenoise = gRandom->Gaus((Double_t)pedestal,(Double_t)rms);
917          //          //
918          // Sum all contribution          // Sum all contribution
919          //          //
920          adc = adcsig + adcbase + (Int_t)round(pedenoise);          adc = adcsig + adcbase + (Int_t)round(pedenoise);
921          //          //
922          // Signal saturation          // Signal saturation
923          //          //
924          if ( adc > 0x7FFF ) adc = 0x7FFF;          if ( adc > 0x7FFF ) adc = 0x7FFF;
925          //          //
926          // save value          // save value
927          //          //
928          if ( sec == 1 ){          if ( sec == 1 ){
929            fDataCALO[tstrip] = adc;            fDataCALO[tstrip] = adc;
930            tstrip++;            tstrip++;
931          } else {          } else {
932            fDataCALO[fCALOlength] = adc;            fDataCALO[fCALOlength] = adc;
933          };          };
934          fCALOlength++;          fCALOlength++;
935          //          //
936        };        };
937        //        //
938        if ( sec == 1 ) tstrip -= 11;        if ( sec == 1 ) tstrip -= 11;
939        //        //
940      };      };
941      //      //
942      // here we calculate and save the CRC      // here we calculate and save the CRC
943      //      //
944      Short_t CRC = 0;      Short_t CRC = 0;
945      for (UInt_t i=0; i<(fCALOlength-fSecPointer); i++){      for (UInt_t i=0; i<(fCALOlength-fSecPointer); i++){
946        CRC=crc(CRC,fDataCALO[i+fSecPointer]);        CRC=crc(CRC,fDataCALO[i+fSecPointer]);
947      };      };
948      fDataCALO[fCALOlength] = (UShort_t)CRC;      fDataCALO[fCALOlength] = (UShort_t)CRC;
949      fCALOlength++;      fCALOlength++;
950      //      //
951    };    };
952    //    //
953    //   for (Int_t i=0; i<fCALOlength; i++){    //   for (Int_t i=0; i<fCALOlength; i++){
954    //     printf(" WORD %i       DIGIT %0x   \n",i,fDataCALO[i]);    //     printf(" WORD %i       DIGIT %0x   \n",i,fDataCALO[i]);
955    //   };    //   };
956    //    //
957  };  };
958    
959  void Digitizer::DigitizeCALOCOMPRESS() {  void Digitizer::DigitizeCALOCOMPRESS() {
960    //    //
961    printf(" COMPRESS MODE STILL NOT IMPLEMENTED! \n");      printf(" COMPRESS MODE STILL NOT IMPLEMENTED! \n");  
962    //    //
963    this->DigitizeCALORAW();    this->DigitizeCALORAW();
964    return;    return;
965    //    //
966    //    //
967    //    //
968    fSecCalo[0] = 0xEA00;    fSecCalo[0] = 0xEA00;
969    fSecCalo[1] = 0xF100;    fSecCalo[1] = 0xF100;
970    fSecCalo[2] = 0xF600;    fSecCalo[2] = 0xF600;
971    fSecCalo[3] = 0xED00;    fSecCalo[3] = 0xED00;
972    //    //
973    // length of the data in DSP mode must be calculated on fly during digitization    // length of the data in DSP mode must be calculated on fly during digitization
974    //    //
975    memset(fSecCALOLength,0x0,4*sizeof(UShort_t));    memset(fSecCALOLength,0x0,4*sizeof(UShort_t));
976    //    //
977    // here comes raw data    // here comes raw data
978    //    //
979    Int_t en = 0;    Int_t en = 0;
980    //    //
981    for (Int_t sec=0; sec < 4; sec++){    for (Int_t sec=0; sec < 4; sec++){
982      fDataCALO[en] = fSecCalo[sec];      fDataCALO[en] = fSecCalo[sec];
983      en++;      en++;
984      fDataCALO[en] = fSecCALOLength[sec];      fDataCALO[en] = fSecCALOLength[sec];
985      en++;      en++;
986      for (Int_t plane=0; plane < 11; plane++){      for (Int_t plane=0; plane < 11; plane++){
987        for (Int_t strip=0; strip < 11; strip++){        for (Int_t strip=0; strip < 11; strip++){
988          fDataCALO[en] = 0x0;          fDataCALO[en] = 0x0;
989          en++;          en++;
990        };        };
991      };      };
992    };    };
993    //    //
994  };  };
995    
996  void Digitizer::DigitizeCALOFULL() {  void Digitizer::DigitizeCALOFULL() {
997    //    //
998    printf(" FULL MODE STILL NOT IMPLEMENTED! \n");      printf(" FULL MODE STILL NOT IMPLEMENTED! \n");  
999    //    //
1000    this->DigitizeCALORAW();    this->DigitizeCALORAW();
1001    return;    return;
1002    //    //
1003    fSecCalo[0] = 0xEA00;    fSecCalo[0] = 0xEA00;
1004    fSecCalo[1] = 0xF100;    fSecCalo[1] = 0xF100;
1005    fSecCalo[2] = 0xF600;    fSecCalo[2] = 0xF600;
1006    fSecCalo[3] = 0xED00;    fSecCalo[3] = 0xED00;
1007    //    //
1008    // length of the data in DSP mode must be calculated on fly during digitization    // length of the data in DSP mode must be calculated on fly during digitization
1009    //    //
1010    memset(fSecCALOLength,0x0,4*sizeof(UShort_t));    memset(fSecCALOLength,0x0,4*sizeof(UShort_t));
1011    //    //
1012    // here comes raw data    // here comes raw data
1013    //    //
1014    Int_t  en = 0;    Int_t  en = 0;
1015    //    //
1016    for (Int_t sec=0; sec < 4; sec++){    for (Int_t sec=0; sec < 4; sec++){
1017      fDataCALO[en] = fSecCalo[sec];      fDataCALO[en] = fSecCalo[sec];
1018      en++;      en++;
1019      fDataCALO[en] = fSecCALOLength[sec];      fDataCALO[en] = fSecCALOLength[sec];
1020      en++;      en++;
1021      for (Int_t plane=0; plane < 11; plane++){      for (Int_t plane=0; plane < 11; plane++){
1022        for (Int_t strip=0; strip < 11; strip++){        for (Int_t strip=0; strip < 11; strip++){
1023          fDataCALO[en] = 0x0;          fDataCALO[en] = 0x0;
1024          en++;          en++;
1025        };        };
1026      };      };
1027    };    };
1028    //    //
1029  };  };
1030    
1031  void Digitizer::DigitizeTRIGGER() {  void Digitizer::DigitizeTRIGGER() {
1032    //fDataTrigger: 153 bytes    //fDataTrigger: 153 bytes
1033    for (Int_t j=0; j < 153; j++)    for (Int_t j=0; j < 153; j++)
1034      fDataTrigger[0]=0x00;      fDataTrigger[j]=0x00;
1035  };  };
1036    
1037  Int_t Digitizer::DigitizeTOF() {  Int_t Digitizer::DigitizeTOF() {
1038    //fDataTof: 12 x 23 bytes (=276 bytes)    //fDataTof: 12 x 23 bytes (=276 bytes)
1039    UChar_t *pTof=fDataTof;    UChar_t *pTof=fDataTof;
1040      Bool_t DEBUG=false;
1041    // --- activate branches:  
1042    fhBookTree->SetBranchStatus("Nthtof",1);    // --- activate branches:
1043    fhBookTree->SetBranchStatus("Ipltof",1);    fhBookTree->SetBranchStatus("Nthtof",1);
1044    fhBookTree->SetBranchStatus("Ipaddle",1);    fhBookTree->SetBranchStatus("Ipltof",1);
1045    fhBookTree->SetBranchStatus("Xintof",1);    fhBookTree->SetBranchStatus("Ipaddle",1);
1046    fhBookTree->SetBranchStatus("Yintof",1);    fhBookTree->SetBranchStatus("Xintof",1);
1047    fhBookTree->SetBranchStatus("Xouttof",1);    fhBookTree->SetBranchStatus("Yintof",1);
1048    fhBookTree->SetBranchStatus("Youttof",1);    fhBookTree->SetBranchStatus("Xouttof",1);
1049    fhBookTree->SetBranchStatus("Ereltof",1);    fhBookTree->SetBranchStatus("Youttof",1);
1050    fhBookTree->SetBranchStatus("Timetof",1);    fhBookTree->SetBranchStatus("Ereltof",1);
1051    // not yet used: Zintof, Xouttof, Youttof, Zouttof    fhBookTree->SetBranchStatus("Timetof",1);
1052      // not yet used: Zintof, Xouttof, Youttof, Zouttof
1053    // ------ evaluate energy in each pmt: ------  
1054    // strip geometry (lenght/width)    // ------ evaluate energy in each pmt: ------
1055    Float_t dimel[6] = {33.0, 40.8 ,18.0, 15.0, 15.0, 18.0};    // strip geometry (lenght/width)
1056    //Float_t dimes[6] = {5.1, 5.5, 7.5, 9.0, 6.0, 5.0};    Float_t dimel[6] = {33.0, 40.8 ,18.0, 15.0, 15.0, 18.0};
1057        //Float_t dimes[6] = {5.1, 5.5, 7.5, 9.0, 6.0, 5.0};
1058    //  S11 8 paddles  33.0 x 5.1 cm    
1059    //  S12 6 paddles  40.8 x 5.5 cm    //  S11 8 paddles  33.0 x 5.1 cm
1060    //  S21 2 paddles  18.0 x 7.5 cm    //  S12 6 paddles  40.8 x 5.5 cm
1061    //  S22 2 paddles  15.0 x 9.0 cm    //  S21 2 paddles  18.0 x 7.5 cm
1062    //  S31 3 paddles  15.0 x 6.0 cm    //  S22 2 paddles  15.0 x 9.0 cm
1063    //  S32 3 paddles  18.0 x 5.0 cm    //  S31 3 paddles  15.0 x 6.0 cm
1064      //  S32 3 paddles  18.0 x 5.0 cm
1065    // distance from the interaction point to the pmts (right,left)  
1066    Float_t xpath[2]={0., 0.}; /*path(cm) in X per S12,S21,S32 verso il pmt DX o SX*/    Float_t FGeo[2]={0., 0.}; /* geometrical factor */
1067    Float_t ypath[2]={0., 0.}; /*path(cm) in Y per S11,S22,S31 verso il pmt DX o SX*/  
1068    Float_t FGeo[2]={0., 0.}; /* fattore geometrico */    const Float_t Pho_keV = 10.;     // photons per keV in scintillator
1069      const Float_t echarge = 1.6e-19; // electron charge
1070    const Float_t Pho_keV = 10.;     // photons per keV in scintillator    Float_t Npho=0.;
1071    const Float_t echarge = 1.6e-19; // carica dell'elettrone    Float_t QevePmt_pC[48];
1072    Float_t Npho=0.;    Float_t QhitPad_pC[2]={0., 0.};
1073    Float_t QevePmt_pC[48];    Float_t QhitPmt_pC[2]={0., 0.};
1074    Float_t QhitPad_pC[2]={0., 0.};    Float_t pmGain = 3.5e6;  /* PMT Gain: the same for all PMTs */
1075    Float_t QhitPmt_pC[2]={0., 0.};    Float_t effi=0.21;       /* Efficienza di fotocatodo */
1076    Float_t pmGain = 3.5e6;  /* Gain: per il momento uguale per tutti */  
1077    Float_t effi=0.21;       /* Efficienza di fotocatodo */    Float_t ADC_pC0=-58.1;      //  ADC/pC conversion coefficient 0
1078    Float_t ADC_pC=1.666667; // ADC_ch/pC conversion = 0.6 pC/channel (+30 di offset)    Float_t ADC_pC1=1.728;      //  ADC/pC conversion coefficient 1
1079    Float_t ADCoffset=30.;    Float_t ADC_pC2=-4.063e-05; //  ADC/pC conversion coefficient 2
1080    Int_t ADClast=4095;      // no signal --> ADC ch=4095    Float_t ADC_pC3=-5.763e-08; //  ADC/pC conversion coefficient 3
1081    Int_t ADCtof[48];  
1082    //Float_t ADCsat=3100;  ci pensiamo in futuro !    Float_t pCthres=40.;     // threshold in charge
1083    //Float_t pCsat=2500;      Int_t ADClast=4095;      // no signal --> ADC ch=4095
1084    for(Int_t i=0; i<48; i++){    Int_t ADCsat=3100;       // saturation value for the ADCs
1085      QevePmt_pC[i] = 0;    Int_t ADCtof[48];
1086      ADCtof[i]=0;  
1087    }  
1088      // ---- introduce scale factors to tune simul ADC to real data   24-oct DC
1089    // ------ read calibration file (get A1, A2, lambda1, lambda2)    Float_t ScaleFact[48]={0.18,0.22,0.35,0.26,0.47,0.35,0.31,0.37,
1090    ifstream fileTriggerCalib;                           0.44,0.23,0.38,0.60,0.39,0.29,0.40,0.23,
1091    TString ftrigname="TrigCalibParam.txt";                           0.30,0.66,0.22,1.53,0.17,0.55,
1092    fileTriggerCalib.open(ftrigname.Data());                           0.84,0.19,0.21,1.64,0.62,0.13,
1093    if ( !fileTriggerCalib ) {                           0.18,0.15,0.10,0.14,0.14,0.14,0.14,0.12,
1094      printf("debug: no trigger calib file!\n");                           0.26,0.18,0.25,0.23,0.20,0.40,
1095      return(-117); //check output!                           0.19,0.23,0.25,0.23,0.25,0.20};
1096    };    
1097    Float_t atte1[48],atte2[48],lambda1[48],lambda2[48];    for(Int_t i=0; i<48; i++){
1098    Int_t temp=0;      QevePmt_pC[i] = 0;
1099    for(Int_t i=0; i<48; i++){      ADCtof[i]=0;
1100      fileTriggerCalib >> temp;    }
1101      fileTriggerCalib >> atte1[i];    
1102      fileTriggerCalib >> atte2[i];    // ------ read calibration file (get A1, A2, lambda1, lambda2)
1103      fileTriggerCalib >> lambda1[i];    ifstream fileTriggerCalib;
1104      fileTriggerCalib >> lambda2[i];    TString ftrigname="TrigCalibParam.txt";
1105      fileTriggerCalib >> temp;    fileTriggerCalib.open(ftrigname.Data());
1106    }    if ( !fileTriggerCalib ) {
1107    fileTriggerCalib.close();      printf("debug: no trigger calib file!\n");
1108        return(-117); //check output!
1109    //  Read from file the 48*4 values of the attenuation fit function    };
1110    //  NB: lambda<0; x,y defined in gpamela (=0 in the centre of the cavity)    Float_t atte1[48],atte2[48],lambda1[48],lambda2[48];
1111    //    Qhitpmt_pC =  atte1 * exp(x/lambda1) + atte2 * exp(x/lambda2)    Int_t temp=0;
1112      // correct readout WM Oct '07
1113    //    fine lettura dal file */    for(Int_t i=0; i<48; i++){
1114        fileTriggerCalib >> temp;
1115    //const Int_t nmax=??; = Nthtof      fileTriggerCalib >> atte1[i];
1116    Int_t ip, ipad;      fileTriggerCalib >> lambda1[i];
1117    //Int_t ipmt;      fileTriggerCalib >> atte2[i];
1118    Int_t pmtleft=0, pmtright=0;      fileTriggerCalib >> lambda2[i];
1119    Int_t *pl, *pr;      fileTriggerCalib >> temp;
1120    pl = &pmtleft;    }
1121    pr = &pmtright;    fileTriggerCalib.close();
1122    
1123    // TDC variables:    Int_t ip, ipad;
1124    Int_t TDClast=4095;      // no signal --> ADC ch=4095    //Int_t ipmt;
1125    Int_t TDCint[48];    Int_t pmtleft=0, pmtright=0;
1126    Float_t  tdc[48],tdc1[48],tdcpmt[48];    Int_t *pl, *pr;
1127    for(Int_t i=0; i<48; i++)    pl = &pmtleft;
1128      tdcpmt[i] = 1000.;    pr = &pmtright;
1129    Float_t thresh=1.; // to be defined better... (Wolfgang)  
1130      // TDC variables:
1131      // === TDC: simulate timing for each paddle    Int_t TDClast=4095;      // no signal --> TDC ch=4095
1132      Float_t dt1 = 285.e-12 ;   // single PMT resolution    Int_t TDCint[48];
1133      Float_t tdcres[50],c1_S[50],c2_S[50],c3_S[50];    Float_t  tdc[48],tdc1[48],tdcpmt[48];
1134      for(Int_t j=0;j<48;j++)  tdcres[j] = 50.E-12;   // TDC resolution 50 picosec    for(Int_t i=0; i<48; i++) {
1135      for(Int_t j=0;j<48;j++)  c1_S[j] = 500.;  // cable length in channels      tdcpmt[i] = 1000.;
1136      for(Int_t j=0;j<48;j++)  c2_S[j] = 0.;      tdc[i]  = 0.;            // 18-oct WM
1137      for(Int_t j=0;j<48;j++)  c3_S[j] = 1000.;      tdc1[i] = 0.;            // 18-oct WM
1138      for(Int_t j=0;j<48;j++)  c1_S[j] = c1_S[j]*tdcres[j];   // cable length in sec    }
1139      for(Int_t j=0;j<48;j++)  c2_S[j] = c2_S[j]*tdcres[j];  
1140       // ih = 0 + i1;  // not used?? (Silvio)    Float_t thresh=10.; // to be defined better... (Wolfgang)
1141    
1142    /* **********************************  inizio loop sugli hit */    // === TDC: simulate timing for each paddle
1143        Float_t dt1 = 285.e-12 ;   // single PMT resolution
1144    for(Int_t nh=0; nh<Nthtof; nh++){    //    Float_t dt1 = 10.e-12 ;   // TEST
1145          Float_t tdcres[50],c1_S[50],c2_S[50],c3_S[50];
1146      for(Int_t j=0; j<2; j++) { // already done!! remove???    for(Int_t j=0;j<48;j++)  tdcres[j] = 50.E-12;   // TDC resolution 50 picosec
1147        xpath[j]=0.;    for(Int_t j=0;j<48;j++)  c1_S[j] = 500.;  // cable length in channels
1148        ypath[j]=0.;    for(Int_t j=0;j<48;j++)  c2_S[j] = 0.;
1149        FGeo[j]=0.;    for(Int_t j=0;j<48;j++)  c3_S[j] = 1000.;
1150      }    for(Int_t j=0;j<48;j++)  c1_S[j] = c1_S[j]*tdcres[j];   // cable length in sec
1151      for(Int_t j=0;j<48;j++)  c2_S[j] = c2_S[j]*tdcres[j];
1152      Float_t s_l_g[6] = {8.0, 8.0, 20.9, 22.0, 9.8, 8.3 };  // length of the lightguide    // ih = 0 + i1;  // not used?? (Silvio)
1153      Float_t t1,t2,veff,veff1,veff0 ;  
1154      veff0 = 100.*1.0e8 ; // light velocity in the scintillator in m/sec    /* **********************************  start loop over hits */
1155      veff1 = 100.*1.5e8; // light velocity in the lightguide in m/sec    
1156      veff=veff0;         // signal velocity in the paddle    for(Int_t nh=0; nh<Nthtof; nh++){
1157        
1158      t1 = Timetof[nh] ;  // Start      Float_t s_l_g[6] = {8.0, 8.0, 20.9, 22.0, 9.8, 8.3 };  // length of the lightguide
1159      t2 = Timetof[nh] ;      Float_t t1,t2,veff,veff1,veff0 ;
1160        veff0 = 100.*1.0e8 ; // light velocity in the scintillator in m/sec
1161      // Donatella          veff1 = 100.*1.5e8; // light velocity in the lightguide in m/sec
1162      // ridefiniz. piano e pad per i vettori in C      veff=veff0;         // signal velocity in the paddle
1163      ip = Ipltof[nh]-1;  
1164      ipad = Ipaddle[nh]-1;      t1 = Timetof[nh] ;  // Start
1165      pmtleft=0;      t2 = Timetof[nh] ;
1166      pmtright=0;  
1167          // Donatella: redefinition plane and pad for vectors in C
1168      //Paddle2Pmt((Int_t)ip, (Int_t) ipad, (Int_t*) &pmtleft, (Int_t*) &pmtright);      ip = Ipltof[nh]-1;
1169      Paddle2Pmt(ip, ipad, &pmtleft, &pmtright);      ipad = Ipaddle[nh]-1;
1170      //Paddle2Pmt(ip, ipad, pl, pr);      pmtleft=0;
1171            pmtright=0;
1172      // per avere anche la corrispondenza pmt --> half board e canale    
1173      // metodo GetPMTIndex(Int_t ipmt, Int_t &hb, Int_t &ch) // non lo usiamo x ora      if (ip<6) {
1174            Paddle2Pmt(ip, ipad, &pmtleft, &pmtright);
1175      /*calcola la pos media e il path all'interno della paddle */  
1176            // DC: evaluates mean position and path inside the paddle
1177      Float_t tpos=0.;    
1178      Float_t path[2] = {0., 0.};        Float_t tpos=0.;
1179      //--- Strip in Y = S11,S22,S31 ------        Float_t path[2] = {0., 0.};
1180      if(ip==0 || ip==3 || ip==4)        //--- Strip in Y = S11,S22,S31 ------
1181        tpos = (Yintof[nh]+Youttof[nh])/2.;        if(ip==0 || ip==3 || ip==4)
1182      else          tpos = (Yintof[nh]+Youttof[nh])/2.;
1183        if(ip==1 || ip==2 || ip==5)   //--- Strip in X per S12,S21,S32        else
1184          tpos = (Xintof[nh]+Xouttof[nh])/2.;          if(ip==1 || ip==2 || ip==5)   //--- Strip in X per S12,S21,S32
1185        else if (ip!=6)            tpos = (Xintof[nh]+Xouttof[nh])/2.;
1186          printf("*** Warning: this option should never occur! (ip=%2i, nh=%2i)\n",ip,nh);          else //if (ip!=6)
1187      path[0]= tpos + dimel[ip]/2.;            printf("*** WARNING TOF: this option should never occur! (ip=%2i, nh=%2i)\n",ip,nh);
1188      path[1]= dimel[ip]/2.- tpos;  
1189          path[0]= tpos + dimel[ip]/2.;   // path to left PMT
1190      //  cout <<"Strip N. ="<< ipaddle <<" piano n.= "<< iplane <<" POSIZ = "<< tpos <<"\n";        path[1]= dimel[ip]/2.- tpos;    // path to right PMT
1191    
1192      /* per il momento metto un fattore geometrico costante*/          //  cout <<"Strip N. ="<< ipaddle <<" piano n.= "<< iplane <<" POSIZ = "<< tpos <<"\n";
1193      FGeo[0] =0.5;        
1194      FGeo[1] =0.5;        if (DEBUG) {
1195      //  FGeo[1] = atan(path[1]/dimes[ip])/6.28318; // frazione fotoni verso SX          cout <<" plane "<<ip<<" strip # ="<< ipad <<" tpos  "<< tpos <<"\n";
1196      //  FGeo[2] = atan(path[2]/dimes[ip])/6.28318; // e verso DX          cout <<"pmtleft, pmtright "<<pmtleft<<" "<<pmtright<<endl;
1197                }
1198      /*  rimando la fluttuazione poissoniana sui fotoni prodotti        
1199          sto studiando come funziona la funzione:        // constant geometric factor, for the moment
1200          long int i = sto.Poisson(double x);  */        FGeo[0] =0.5;
1201      //  Npho = Poisson(ERELTOF[nh])*Pho_keV*1e6   Eloss in GeV ?        FGeo[1] =0.5;
1202      Npho = Ereltof[nh]*Pho_keV*10.0e6;  // Eloss in GeV ?        //  FGeo[1] = atan(path[1]/dimes[ip])/6.28318; // fraction of photons toward SX
1203            //  FGeo[2] = atan(path[2]/dimes[ip])/6.28318; // toward DX
1204      Float_t knorm[2]={0., 0.}; // Donatella        
1205      Float_t Atten[2]={0., 0.}; // Donatella        
1206      for(Int_t j=0; j<2; j++){        //  Npho = Poisson(ERELTOF[nh])*Pho_keV*1e6  Poissonian fluctuations to be inserted-DC
1207        QhitPad_pC[j]= Npho*FGeo[j]*effi*pmGain*echarge;        Npho = Ereltof[nh]*Pho_keV*1.0e6;  // Eloss in GeV
1208        knorm[j]=QhitPad_pC[j]/(atte1[pmtleft+j]*exp((dimel[ip]/2.*pow(-1,j+1))/lambda1[pmtleft+j]) +        
1209                                atte2[pmtleft+j]*exp((dimel[ip]/2.*pow(-1,j+1))/lambda2[pmtleft+j]));        Float_t knorm[2]={0., 0.}; // Donatella
1210          Float_t Atten[2]={0., 0.}; // Donatella
1211        Atten[j]=knorm[j]*(atte1[pmtleft+j]*exp(tpos/lambda1[pmtleft+j]) +        for(Int_t j=0; j<2; j++){
1212                           atte2[pmtleft+j]*exp(tpos/lambda2[pmtleft+j]));          QhitPad_pC[j]= Npho*FGeo[j]*effi*pmGain*echarge*1.E12; // corrected WM
1213                  // WM
1214        QhitPmt_pC[j]= QhitPad_pC[j]*Atten[j];          knorm[j]=atte1[pmtleft+j]*exp(lambda1[pmtleft+j]*dimel[ip]/2.*pow(-1,j+1)) +
1215      }            atte2[pmtleft+j]*exp(lambda2[pmtleft+j]*dimel[ip]/2.*pow(-1,j+1));
1216                Atten[j]=atte1[pmtleft+j]*exp(tpos*lambda1[pmtleft+j]) +
1217      QevePmt_pC[pmtleft]  += QhitPmt_pC[0];            atte2[pmtleft+j]*exp(tpos*lambda2[pmtleft+j]) ;
1218      QevePmt_pC[pmtright] += QhitPmt_pC[1];          QhitPmt_pC[j]= QhitPad_pC[j]*Atten[j]/knorm[j];
1219                //              QhitPmt_pC[j]= QhitPad_pC[j]; //no attenuation
1220      // TDC  
1221      t2 = t2 + fabs(path[0]/veff) + s_l_g[ip]/veff1 ;  // Signal reaches PMT  
1222      t1 = t1 + fabs(path[1]/veff) + s_l_g[ip]/veff1;          if (DEBUG) {
1223                  cout<<"pmtleft "<<pmtleft<<" j "<<j<<endl;
1224      TRandom r;            cout<<" atte1 "<<atte1[pmtleft+j]<<"lambda1 "<<lambda1[pmtleft+j]<<" atte2 "<<atte2[pmtleft+j]<<"lambda2 "<<lambda2[pmtleft+j] <<endl;    
1225      t1 = r.Gaus(t1,dt1);  //apply gaussian error  dt            cout<<j<<" tpos "<<tpos<<" knorm "<<knorm[j]<<" "<<Atten[j]<<" "<<"QhitPmt_pC "<<QhitPmt_pC[j]<<endl;    
1226      t2 = r.Gaus(t2,dt1);  //apply gaussian error  dt          }
1227              }
1228      t1 = t1 + c1_S[pmtleft] ;  // Signal reaches Discriminator ,TDC starts  to run        
1229      t2 = t2 + c1_S[pmtright] ;        if (DEBUG)
1230                cout<<"Npho "<<Npho<<" QhitPmt_pC "<<QhitPmt_pC[0]<<" "<<QhitPmt_pC[1]<<endl;  
1231      // check if signal is above threshold        
1232      // then check if tdcpmt is already filled by another hit...        QevePmt_pC[pmtleft]  += QhitPmt_pC[0];
1233      // only re-fill if time is smaller        QevePmt_pC[pmtright] += QhitPmt_pC[1];
1234              
1235      if (QhitPmt_pC[0] > thresh)        // TDC
1236        if (tdcpmt[pmtleft] < 1000.) // is already filled!  // WM right and left <->
1237          if (t1 <  tdcpmt[pmtleft]) {  //      t2 = t2 + fabs(path[0]/veff) + s_l_g[ip]/veff1 ;  // Signal reaches PMT
1238            tdcpmt[pmtleft] = t1;  //      t1 = t1 + fabs(path[1]/veff) + s_l_g[ip]/veff1;
1239            t1 = t1 + c2_S[pmtleft] ;  // Signal reaches Coincidence  
1240            tdc[pmtleft] = t1;        t1 = t1 + fabs(path[0]/veff) + s_l_g[ip]/veff1;
1241          }        t2 = t2 + fabs(path[1]/veff) + s_l_g[ip]/veff1 ;  // Signal reaches PMT
1242              
1243      if (QhitPmt_pC[1] > thresh)        Float_t t1save = t1;
1244          if (tdcpmt[pmtright] < 1000.)  // is already filled!        Float_t t2save = t2;
1245            if (t2 <  tdcpmt[pmtright]) {  
1246              tdcpmt[pmtright] = t2;  /*
1247              t2 = t2 + c2_S[pmtright] ;        TRandom r;
1248              tdc[pmtright] = t2;  // This does not work... WM -  but works in my simulation code ??
1249            }        //      t1 = r.Gaus(t1,dt1);  //apply gaussian error  dt
1250        //      t2 = r.Gaus(t2,dt1);  //apply gaussian error  dt
1251    } // ****************************************       end loop over hits  */      
1252            t1 = gRandom->Gaus(t1,dt1); //apply gaussian error  dt
1253    // ======  ADC ======          t2 = gRandom->Gaus(t2,dt1); //apply gaussian error  dt
1254    for(Int_t i=0; i<48; i++){  
1255      if(QevePmt_pC[i] != 0.){  //      cout<<1E12*(t1save-t1)<<" "<<1E12*(t2save-t2)<<endl;
1256        ADCtof[i]= (Int_t)(ADC_pC*QevePmt_pC[i] + ADCoffset);  
1257        if(ADCtof[i]> ADClast) ADCtof[i]=ADClast;        t1 = t1 + c1_S[pmtleft] ;  // Signal reaches Discriminator ,TDC starts  to run
1258      } else        t2 = t2 + c1_S[pmtright] ;
1259        ADCtof[i]= ADClast;        
1260    };        // check if signal is above threshold
1261          // then check if tdcpmt is already filled by another hit...
1262              // only re-fill if time is smaller
1263    // ======  build  TDC coincidence  ======        
1264          if (QhitPmt_pC[0] > thresh) {
1265    Float_t t_coinc = 0;          if (tdcpmt[pmtleft] == 1000.) {  // fill for the first time
1266    Int_t ilast = 100;            tdcpmt[pmtleft] = t1;
1267    for (Int_t ii=0; ii<48;ii++)            tdc[pmtleft] = t1 + c2_S[pmtleft] ;  // Signal reaches Coincidence
1268      if (tdc[ii] > t_coinc) {          }
1269        t_coinc = tdc[ii];          if (tdcpmt[pmtleft] < 1000.) // is already filled!
1270        ilast = ii;            if (t1 <  tdcpmt[pmtleft]) {
1271      }              tdcpmt[pmtleft] = t1;
1272                  t1 = t1 + c2_S[pmtleft] ;  // Signal reaches Coincidence
1273    //     cout<<ilast<<" "<<t_coinc<<endl;              tdc[pmtleft] = t1;
1274    //     At t_coinc  trigger condition is fulfilled            }
1275            }      
1276    for (Int_t ii=0; ii<48;ii++){        if (QhitPmt_pC[1] > thresh) {
1277      //      if (tdc[ii] != 0) tdc1[ii] = t_coinc - tdc[ii];   // test 1          if (tdcpmt[pmtright] == 1000.) {  // fill for the first time
1278      if (tdc[ii] != 0) tdc1[ii] = t_coinc - tdcpmt[ii];  // test 2            tdcpmt[pmtright] = t2;
1279      tdc1[ii] = tdc1[ii]/tdcres[ii];                     // divide by TDC resolution            tdc[pmtright] = t2 + c2_S[pmtright] ;  // Signal reaches Coincidence
1280      if (tdc[ii] != 0) tdc1[ii] = tdc1[ii] + c3_S[ii];  // add cable length c3          }
1281            if (tdcpmt[pmtright] < 1000.)  // is already filled!
1282    } // missing parenthesis inserted! (Silvio)            if (t2 <  tdcpmt[pmtright]) {
1283                tdcpmt[pmtright] = t2;
1284    for(Int_t i=0; i<48; i++){              t2 = t2 + c2_S[pmtright] ;
1285      if(tdc1[i] != 0.){              tdc[pmtright] = t2;
1286        TDCint[i]=(Int_t)tdc1[i];            }      
1287        //ADC[i]= ADC_pC * QevePmt_pC[i] + ADCoffset;        }
1288        //if(ADC[i]> ADClast) ADC[i]=ADClast;  
1289      } else        if (DEBUG)
1290        TDCint[i]= TDClast;          cout<<nh<<" "<<Timetof[nh]<<" "<<t1<<" "<<t2<<endl;
1291    }  
1292        } // ip < 6
1293  // ======  write fDataTof  =======  
1294    UChar_t tofBin;    }; // ****************************************       end loop over hits
1295    for (Int_t j=0; j < 12; j++){    
1296      Int_t j12=j*12;    // ======  ADC ======
1297      fDataTof[j12+0]=0x00;   // TDC_ID  
1298      fDataTof[j12+1]=0x00;   // EV_COUNT  
1299      fDataTof[j12+2]=0x00;   // TDC_MASK (1)    for(Int_t i=0; i<48; i++){
1300      fDataTof[j12+3]=0x00;   // TDC_MASK (2)      if(QevePmt_pC[i] >= pCthres){
1301      for (Int_t k=0; k < 4; k++){        ADCtof[i]= (Int_t)(ADC_pC0 + ADC_pC1*QevePmt_pC[i] + ADC_pC2*pow(QevePmt_pC[i],2) + ADC_pC3*pow(QevePmt_pC[i],3));
1302        Int_t jk12=j12+k;    } else
1303        tofBin=(UChar_t)(ADCtof[k+4*j]/256);   // ADC# (msb) (#=1+k+4*j)        ADCtof[i]= ADClast;  
1304        fDataTof[jk12+4] = Bin2GrayTof(tofBin,fDataTof[jk12+4]);  }
1305        tofBin=(UChar_t)(ADCtof[k+4*j]%256);   // ADC# (lsb)    
1306        fDataTof[jk12+5] = Bin2GrayTof(tofBin,fDataTof[jk12+5]);  // ---- introduce scale factors to tune simul ADC to real data   24-oct DC
1307        tofBin=(UChar_t)(TDCint[k+4*j]/256);   // TDC# (msb)  
1308        fDataTof[jk12+6]=Bin2GrayTof(tofBin,fDataTof[jk12+6]);    for(Int_t i=0; i<48; i++){
1309        tofBin=(UChar_t)(TDCint[k+4*j]%256);   // TDC# (lsb)      if(ADCtof[i] != ADClast){
1310        fDataTof[jk12+7]=Bin2GrayTof(tofBin,fDataTof[jk12+7]);                               //      printf("%3d, %4d, %4.2f\n",i, ADCtof[i],ScaleFact[i]);
1311      };        ADCtof[i]= Int_t (ADCtof[i]*ScaleFact[i]);
1312      fDataTof[j12+20]=0x00;   // TEMP1                               //      printf("%3d, %4d,\n",i, ADCtof[i]);
1313      fDataTof[j12+21]=0x00;   // TEMP2      }
1314      fDataTof[j12+22]= EvaluateCrcTof(pTof);   // CRC    }
1315      pTof+=23;  
1316    };    for(Int_t i=0; i<48; i++){
1317    return(0);      if(ADCtof[i] != ADClast){
1318  };        if(ADCtof[i]> ADCsat) ADCtof[i]=ADCsat;
1319          else if(ADCtof[i]< 0) ADCtof[i]=ADClast;    
1320  UChar_t Digitizer::Bin2GrayTof(UChar_t binaTOF,UChar_t grayTOF){    }
1321    union graytof_data {    }    
1322      UChar_t word;    // ======  build  TDC coincidence  ======
1323      struct bit_field {  
1324        unsigned b0:1;    Float_t t_coinc = 0;
1325        unsigned b1:1;    Int_t ilast = 100;
1326        unsigned b2:1;    for (Int_t ii=0; ii<48;ii++)
1327        unsigned b3:1;      if (tdc[ii] > t_coinc) {
1328        unsigned b4:1;        t_coinc = tdc[ii];
1329        unsigned b5:1;        ilast = ii;
1330        unsigned b6:1;      }
1331        unsigned b7:1;    
1332      } bit;    //     cout<<ilast<<" "<<t_coinc<<endl;
1333    } bi,gr;    //     At t_coinc  trigger condition is fulfilled
1334    //    
1335    bi.word = binaTOF;    for (Int_t ii=0; ii<48;ii++){
1336    gr.word = grayTOF;      //      if (tdc[ii] != 0) tdc1[ii] = t_coinc - tdc[ii];   // test 1
1337    //      if (tdc[ii] != 0) tdc1[ii] = t_coinc - tdcpmt[ii];  // test 2
1338    gr.bit.b0 = bi.bit.b1 ^ bi.bit.b0;      tdc1[ii] = tdc1[ii]/tdcres[ii];                     // divide by TDC resolution
1339    gr.bit.b1 = bi.bit.b2 ^ bi.bit.b1;      if (tdc[ii] != 0) tdc1[ii] = tdc1[ii] + c3_S[ii];  // add cable length c3
1340    gr.bit.b2 = bi.bit.b3 ^ bi.bit.b2;  
1341    gr.bit.b3 = bi.bit.b3;    } // missing parenthesis inserted! (Silvio)
1342    //  
1343    /* bin to gray conversion 4 bit per time*/    for(Int_t i=0; i<48; i++){
1344    //      if(tdc1[i] != 0.){
1345    gr.bit.b4 = bi.bit.b5 ^ bi.bit.b4;        TDCint[i]=(Int_t)tdc1[i];
1346    gr.bit.b5 = bi.bit.b6 ^ bi.bit.b5;        if (TDCint[i]>4093) TDCint[i]=TDClast;  // 18-oct WM
1347    gr.bit.b6 = bi.bit.b7 ^ bi.bit.b6;        if (DEBUG)
1348    gr.bit.b7 = bi.bit.b7;          cout<<i<<" "<<TDCint[i]<<endl;
1349    //        //ADC[i]= ADC_pC * QevePmt_pC[i] + ADCoffset;
1350    return(gr.word);        //if(ADC[i]> ADClast) ADC[i]=ADClast;
1351  }      } else
1352          TDCint[i]= TDClast;
1353  UChar_t Digitizer::EvaluateCrcTof(UChar_t *pTof) {    }
1354    // UChar_t crcTof=0x00;  
1355    //   for (Int_t jp=0; jp < 23; jp++){    if (DEBUG)
1356    //     crcTof = crc8(...)      cout<<"-----------"<<endl;
1357    //   }  
1358    return(0x00);  
1359  };  //------ use channelmap  18-oct WM
1360    
1361  //void Digitizer::Paddle2Pmt(Int_t plane, Int_t paddle, Int_t* &pmtleft, Int_t* &pmtright){  Int_t  channelmap[] =  {3,21,11,29,19,45,27,37,36,28,44,20,5,12,13,4,
1362  void Digitizer::Paddle2Pmt(Int_t plane, Int_t paddle, Int_t *pl, Int_t *pr){                          6,47,14,39,22,31,30,23,38,15,46,7,0,33,16,24,
1363    //* @param plane    (0 - 5)                          8,41,32,40,25,17,34,9,42,1,2,10,18,26,35,43};
1364    //* @param paddle   (plane=0, paddle = 0,...5)  
1365    //* @param padid    (0 - 23)      Int_t ADChelp[48];
1366    //    Int_t TDChelp[48];
1367    Int_t padid=-1;  
1368    Int_t pads[6]={8,6,2,2,3,3};    for(Int_t i=0; i<48; i++){
1369    //        Int_t ii=channelmap[i];
1370    Int_t somma=0;        ADChelp[ii]= ADCtof[i];
1371    Int_t np=plane;        TDChelp[ii]= TDCint[i];
1372    for(Int_t j=0; j<np; j++)                            }
1373      somma+=pads[j];  
1374    padid=paddle+somma;    for(Int_t i=0; i<48; i++){
1375    *pl = padid*2;        ADCtof[i]= ADChelp[i];
1376    *pr = *pr + 1;        TDCint[i]= TDChelp[i];
1377  };                            }
1378    
1379  void Digitizer::DigitizeAC() {  
1380    // created:  J. Conrad, KTH  /*
1381    // modified: S. Orsi, INFN Roma2  //--- fake data ------------------------
1382      for(Int_t i=0; i<48; i++){
1383    fDataAC[0] = 0xACAC;        ADCtof[i]= 100 + 10*i;
1384    fDataAC[64]= 0xACAC;        TDCint[i]= 800 + 10*i;
1385    fDataAC[1] = 0xAC11;   // main card  //      cout<<i<<" "<<ADCtof[i]<<" "<<TDCint[i]<<endl;
1386    fDataAC[65] = 0xAC22;   // extra card                            }
1387    */
1388    // the third word is a status word (dummy)  
1389    fDataAC[2] = 0xFFFF; //FFEF?  /*
1390    fDataAC[66] = 0xFFFF;    for(Int_t i=0; i<48; i++){
1391       if (((ADCtof[i]>0)&&(ADCtof[i]<4095)) || ((TDCint[i]>0)&&(TDCint[i]<4095)))  cout<<i<<" "<<ADCtof[i]<<" "<<TDCint[i]<<endl;
1392    const UInt_t nReg = 6;                            }
1393    */
1394    // Registers (dummy)  
1395    for (UInt_t i=0; i<=nReg; i++){  
1396      fDataAC[i+4] = 0xFFFF;  // ======  write fDataTof  =======
1397      fDataAC[i+68] = 0xFFFF;  
1398    }  
1399    //  UChar_t tdcadd[8]={1,0,3,2,5,4,7,6};  (coded in 3 bit)
1400    // the last word is a CRC    UChar_t Ctrl3bit[8]={32,0,96,64,160,128,224,192};  // DC (msb in 8 bit word )
1401    // Dummy for the time being, but it might need to be calculated in the end    
1402    fDataAC[63] = 0xABCD;    UChar_t tofBin;
1403    fDataAC[127] = 0xABCD;    for (Int_t j=0; j < 12; j++){   // loop on TDC #12
1404        Int_t j12=j*23;               // for each TDC 23 bytes (8 bits)
1405    // shift registers, which one is with respect to PMT, where in      fDataTof[j12+0]=0x00;   // TDC_ID
1406    // shift registers is a question of time relative trigger      fDataTof[j12+1]=0x00;   // EV_COUNT
1407    // In level2: hitmap, hitmap-status (synchronised with a trigger),      fDataTof[j12+2]=0x00;   // TDC_MASK (1)
1408    // status      fDataTof[j12+3]=0x00;   // TDC_MASK (2)
1409                  for (Int_t k=0; k < 4; k++){   // for each TDC 4 channels (ADC+TDC)
1410    for (UInt_t i=0; i<=15; i++){            
1411      fDataAC[i+11] = 0x0000;          Int_t jk12=j12+4*k;         // ADC,TDC channel (0-47)
1412      fDataAC[i+75] = 0x0000;  
1413    }        tofBin =(UChar_t)(ADCtof[k+4*j]/256);   // ADC# (msb)
1414          fDataTof[jk12+4] = Bin2GrayTof(tofBin,fDataTof[jk12+4]);
1415    // singles counters are dummy        /* control bits inserted here, after the bin to gray conv - DC*/
1416          fDataTof[jk12+4] = Ctrl3bit[2*k] | fDataTof[jk12+4];
1417    for (UInt_t i=0; i<=16; i++){        tofBin=(UChar_t)(ADCtof[k+4*j]%256);   // ADC# (lsb)
1418      fDataAC[i+26] = 0x0000;          fDataTof[jk12+5] = Bin2GrayTof(tofBin,fDataTof[jk12+5]);
1419      fDataAC[i+90] = 0x0000;        tofBin=(UChar_t)(TDCint[k+4*j]/256);   // TDC# (msb)
1420    }        fDataTof[jk12+6]=Bin2GrayTof(tofBin,fDataTof[jk12+6]);
1421            /* control bits inserted here, after the bin to gray conv - DC*/
1422    // coincidences are dummy        fDataTof[jk12+6] = Ctrl3bit[2*k+1] | fDataTof[jk12+6];
1423          tofBin=(UChar_t)(TDCint[k+4*j]%256);   // TDC# (lsb)
1424    for (UInt_t i=0; i<=7; i++){        fDataTof[jk12+7]=Bin2GrayTof(tofBin,fDataTof[jk12+7]);
1425      fDataAC[i+42] = 0x0000;      };
1426      fDataAC[i+106] = 0x0000;      fDataTof[j12+20]=0x00;   // TEMP1
1427    }      fDataTof[j12+21]=0x00;   // TEMP2
1428        fDataTof[j12+22]= EvaluateCrcTof(pTof);   // CRC
1429    // increments for every trigger might be needed at some point.      pTof+=23;
1430    // dummy for now    };
1431    fDataAC[50]  = 0x0000;    return(0);
1432    fDataAC[114] = 0x0000;  };
1433    
1434    // dummy FPGA clock  
1435    UChar_t Digitizer::Bin2GrayTof(UChar_t binaTOF,UChar_t grayTOF){
1436    fDataAC[51] = 0x006C;    union graytof_data {
1437    fDataAC[52] = 0x6C6C;      UChar_t word;
1438    fDataAC[115] = 0x006C;      struct bit_field {
1439    fDataAC[116] = 0x6C6C;        unsigned b0:1;
1440          unsigned b1:1;
1441          unsigned b2:1;
1442    // dummy temperatures        unsigned b3:1;
1443    fDataAC[53] = 0x0000;        unsigned b4:1;
1444    fDataAC[54] = 0x0000;        unsigned b5:1;
1445    fDataAC[117] = 0x0000;        unsigned b6:1;
1446    fDataAC[118] = 0x0000;        unsigned b7:1;
1447        } bit;
1448      } bi,gr;
1449    // dummy DAC thresholds    //
1450    for (UInt_t i=0; i<=7; i++){    bi.word = binaTOF;
1451      fDataAC[i+55] = 0x1A13;      gr.word = grayTOF;
1452      fDataAC[i+119] = 0x1A13;    //
1453    }    gr.bit.b0 = bi.bit.b1 ^ bi.bit.b0;
1454        gr.bit.b1 = bi.bit.b2 ^ bi.bit.b1;
1455    // We activate all branches. Once the digitization algorithm    gr.bit.b2 = bi.bit.b3 ^ bi.bit.b2;
1456    // is determined only the branches need to activated which involve needed    gr.bit.b3 = bi.bit.b3;
1457    // information    //
1458        /* bin to gray conversion 4 bit per time*/
1459    fhBookTree->SetBranchStatus("Nthcat",1);    //
1460    fhBookTree->SetBranchStatus("Iparcat",1);    gr.bit.b4 = bi.bit.b5 ^ bi.bit.b4;
1461    fhBookTree->SetBranchStatus("Icat",1);    gr.bit.b5 = bi.bit.b6 ^ bi.bit.b5;
1462    fhBookTree->SetBranchStatus("Xincat",1);    gr.bit.b6 = bi.bit.b7 ^ bi.bit.b6;
1463    fhBookTree->SetBranchStatus("Yincat",1);    gr.bit.b7 = bi.bit.b7;
1464    fhBookTree->SetBranchStatus("Zincat",1);    //
1465    fhBookTree->SetBranchStatus("Xoutcat",1);    return(gr.word);
1466    fhBookTree->SetBranchStatus("Youtcat",1);  }
1467    fhBookTree->SetBranchStatus("Zoutcat",1);  
1468    fhBookTree->SetBranchStatus("Erelcat",1);  UChar_t Digitizer::EvaluateCrcTof(UChar_t *pTof) {
1469    fhBookTree->SetBranchStatus("Timecat",1);    Bool_t DEBUG=false;
1470    fhBookTree->SetBranchStatus("Pathcat",1);    if (DEBUG)
1471    fhBookTree->SetBranchStatus("P0cat",1);      return(0x00);
1472    fhBookTree->SetBranchStatus("Nthcas",1);  
1473    fhBookTree->SetBranchStatus("Iparcas",1);    UChar_t crcTof=0x00;
1474    fhBookTree->SetBranchStatus("Icas",1);    UChar_t *pc=&crcTof, *pc2;
1475    fhBookTree->SetBranchStatus("Xincas",1);    pc2=pTof;
1476    fhBookTree->SetBranchStatus("Yincas",1);    for (Int_t jp=0; jp < 23; jp++){
1477    fhBookTree->SetBranchStatus("Zincas",1);      //crcTof = crc8(...)
1478    fhBookTree->SetBranchStatus("Xoutcas",1);      Crc8Tof(pc2++,pc);
1479    fhBookTree->SetBranchStatus("Youtcas",1);      //    printf("%2i --- %x\n",jp,crcTof);
1480    fhBookTree->SetBranchStatus("Zoutcas",1);    }
1481    fhBookTree->SetBranchStatus("Erelcas",1);    return(crcTof);
1482    fhBookTree->SetBranchStatus("Timecas",1);  }
1483    fhBookTree->SetBranchStatus("Pathcas",1);  
1484    fhBookTree->SetBranchStatus("P0cas",1);  void Digitizer::Crc8Tof(UChar_t *oldCRC, UChar_t *crcTof){
1485    fhBookTree->SetBranchStatus("Nthcard",1);    union crctof_data {
1486    fhBookTree->SetBranchStatus("Iparcard",1);      UChar_t word;
1487    fhBookTree->SetBranchStatus("Icard",1);      struct bit_field {
1488    fhBookTree->SetBranchStatus("Xincard",1);        unsigned b0:1;
1489    fhBookTree->SetBranchStatus("Yincard",1);        unsigned b1:1;
1490    fhBookTree->SetBranchStatus("Zincard",1);        unsigned b2:1;
1491    fhBookTree->SetBranchStatus("Xoutcard",1);        unsigned b3:1;
1492    fhBookTree->SetBranchStatus("Youtcard",1);        unsigned b4:1;
1493    fhBookTree->SetBranchStatus("Zoutcard",1);        unsigned b5:1;
1494    fhBookTree->SetBranchStatus("Erelcard",1);        unsigned b6:1;
1495    fhBookTree->SetBranchStatus("Timecard",1);        unsigned b7:1;
1496    fhBookTree->SetBranchStatus("Pathcard",1);      } bit;
1497    fhBookTree->SetBranchStatus("P0card",1);    } c,d,r;
1498    
1499    // In this simpliefied approach we will assume that once    c.word = *oldCRC;
1500    // a particle releases > 0.5 mip in one of the 12 AC detectors it    //d.word = *newCRC;
1501    // will fire. We will furthermore assume that both cards read out    d.word = *crcTof;
1502    // identical data.    r.word = 0;
1503    
1504    // If you develop you digitization algorithm, you should start by    r.bit.b0 = c.bit.b7 ^ c.bit.b6 ^ c.bit.b0 ^
1505    // identifying the information present in level2 (post-darth-vader)               d.bit.b0 ^ d.bit.b6 ^ d.bit.b7;
1506    // data.  
1507      r.bit.b1 = c.bit.b6 ^ c.bit.b1 ^ c.bit.b0 ^
1508    Float_t SumEcat[5];               d.bit.b0 ^ d.bit.b1 ^ d.bit.b6;
1509    Float_t SumEcas[5];  
1510    Float_t SumEcard[5];    r.bit.b2 = c.bit.b6 ^ c.bit.b2 ^ c.bit.b1 ^ c.bit.b0 ^
1511    for (Int_t k= 0;k<5;k++){               d.bit.b0 ^ d.bit.b1 ^ d.bit.b2 ^ d.bit.b6;
1512      SumEcat[k]=0.;  
1513      SumEcas[k]=0.;    r.bit.b3 = c.bit.b7 ^ c.bit.b3 ^ c.bit.b2 ^ c.bit.b1 ^
1514      SumEcard[k]=0.;               d.bit.b1 ^ d.bit.b2 ^ d.bit.b3 ^ d.bit.b7;
1515    };  
1516      r.bit.b4 = c.bit.b4 ^ c.bit.b3 ^ c.bit.b2 ^
1517    if (Nthcat>50 || Nthcas>50 || Nthcard>50)               d.bit.b2 ^ d.bit.b3 ^ d.bit.b4;
1518      printf("Error! NthAC out of range!\n\n");  
1519      r.bit.b5 = c.bit.b5 ^ c.bit.b4 ^ c.bit.b3 ^
1520    // look in CAT               d.bit.b3 ^ d.bit.b4 ^ d.bit.b5;
1521    //  for (UInt_t k= 0;k<50;k++){  
1522    for (Int_t k= 0;k<Nthcat;k++){    r.bit.b6 = c.bit.b6 ^ c.bit.b5 ^ c.bit.b4 ^
1523      if (Erelcat[k] > 0)               d.bit.b4 ^ d.bit.b5 ^ d.bit.b6;
1524        SumEcat[Icat[k]] += Erelcat[k];  
1525    };    r.bit.b7 = c.bit.b7 ^ c.bit.b6 ^ c.bit.b5 ^
1526                 d.bit.b5 ^ d.bit.b6 ^ d.bit.b7 ;
1527    // look in CAS  
1528    for (Int_t k= 0;k<Nthcas;k++){    *crcTof=r.word;
1529      if (Erelcas[k] >0)    //return r.word;
1530        SumEcas[Icas[k]] += Erelcas[k];  };
1531    };  
1532    //void Digitizer::Paddle2Pmt(Int_t plane, Int_t paddle, Int_t* &pmtleft, Int_t* &pmtright){
1533    // look in CARD  void Digitizer::Paddle2Pmt(Int_t plane, Int_t paddle, Int_t *pl, Int_t *pr){
1534    for (Int_t k= 0;k<Nthcard;k++){    //* @param plane    (0 - 5)
1535      if (Erelcard[k] >0)    //* @param paddle   (plane=0, paddle = 0,...5)
1536        SumEcard[Icard[k]] += Erelcard[k];    //* @param padid    (0 - 23)  
1537    };    //
1538      Int_t padid=-1;
1539    // channel mapping              Hit Map    Int_t pads[6]={8,6,2,2,3,3};
1540    // 1 CARD4                      0          LSB    //
1541    // 2 CAT2                       0    Int_t somma=0;
1542    // 3 CAS1                       0    Int_t np=plane;
1543    // 4 NC                         0    for(Int_t j=0; j<np; j++)
1544    // 5 CARD2                      0      somma+=pads[j];
1545    // 6 CAT4                       1    padid=paddle+somma;
1546    // 7 CAS4                       0      *pl = padid*2;
1547    // 8 NC                         0    //  *pr = *pr + 1;
1548    // 9 CARD3                      0    *pr = *pl + 1; // WM
1549    // 10 CAT3                      0  };
1550    // 11 CAS3                      0  
1551    // 12 NC                        0  void Digitizer::DigitizeAC() {
1552    // 13 CARD1                     0    // created:  J. Conrad, KTH
1553    // 14 CAT1                      0    // modified: S. Orsi, INFN Roma2
1554    // 15 CAS2                      0    // fDataAC[0-63]:   main AC board
1555    // 16 NC                        0          MSB    // fDataAC[64-127]: extra AC board
1556    
1557    // In the first version only the hit-map is filled, not the SR.    fDataAC[0] = 0xACAC;
1558      fDataAC[64]= 0xACAC;
1559    // Threshold: 0.8 MeV.    fDataAC[1] = 0xAC11;  
1560      fDataAC[65] = 0xAC22;  
1561    Float_t thr = 8e-4;  
1562      // the third word is a status word (dummy: "no errors are present in the AC boards")
1563    fDataAC[3] = 0x0000;    fDataAC[2] = 0xFFFF; //FFEF?
1564      fDataAC[66] = 0xFFFF;
1565    if (SumEcas[0] > thr)  fDataAC[3]  = 0x0004;  
1566    if (SumEcas[1] > thr)  fDataAC[3] += 0x4000;    const UInt_t nReg = 6;
1567    if (SumEcas[2] > thr)  fDataAC[3] += 0x0400;  
1568    if (SumEcas[3] > thr)  fDataAC[3] += 0x0040;      // FPGA Registers (dummy)
1569      for (UInt_t i=0; i<=nReg; i++){
1570    if (SumEcat[0] > thr)  fDataAC[3] += 0x2000;      fDataAC[i+4] = 0xFFFF;
1571    if (SumEcat[1] > thr)  fDataAC[3] += 0x0002;      fDataAC[i+68] = 0xFFFF;
1572    if (SumEcat[2] > thr)  fDataAC[3] += 0x0200;    }
1573    if (SumEcat[3] > thr)  fDataAC[3] += 0x0020;  
1574        // the last word is a CRC
1575    if (SumEcard[0] > thr)  fDataAC[3] += 0x1000;    // Dummy for the time being, but it might need to be calculated in the end
1576    if (SumEcard[1] > thr)  fDataAC[3] += 0x0010;    fDataAC[63] = 0xABCD;
1577    if (SumEcard[2] > thr)  fDataAC[3] += 0x0100;    fDataAC[127] = 0xABCD;
1578    if (SumEcard[3] > thr)  fDataAC[3] += 0x0001;  
1579      // shift registers (moved to the end of the routine)
1580    fDataAC[67] = fDataAC[3];  
1581      Int_t evntLSB=Ievnt%65536;
1582    //    for (Int_t i=0; i<fACbuffer; i++){    Int_t evntMSB=(Int_t)(Ievnt/65536);
1583    //    printf("%0x  ",fDataAC[i]);    
1584    //    if ((i+1)%8 ==0) cout << endl;    // singles counters are dummy
1585    //   }    for (UInt_t i=0; i<=15; i++){  //SO Oct '07: // for (UInt_t i=0; i<=16; i++){
1586  };      //     fDataAC[i+26] = 0x0000;  
1587        //     fDataAC[i+90] = 0x0000;
1588        fDataAC[i+26] = evntLSB;
1589        fDataAC[i+90] = evntLSB;
1590  void Digitizer::DigitizeS4(){    };
1591    // creato:  S. Borisov, INFN Roma2 e MEPHI, Sett 2007    
1592    TString ciao,modo="ns";    // coincidences are dummy (increment by 1 at each event)
1593    Int_t i,j,t,NdF,pmt,NdFT,S4,S4v=0,S4p=32;    // for (UInt_t i=0; i<=7; i++){
1594    Float_t E0,E1=1e-6,Ert,X,Y,Z,x,y,z,V[3],Xs[2],Ys[2],Zs[2],Yp[6],q,w,p=0.1,l,l0=500.;    //    fDataAC[i+42] = 0x0000;
1595    Xs[0]=-24.1;    //    fDataAC[i+106] = 0x0000;
1596    Xs[1]=24.1;    //   }
1597    Ys[0]=-24.1;    for (UInt_t i=0; i<=7; i++){
1598    Ys[1]=24.1;      fDataAC[i+42] = evntLSB;
1599    Zs[0]=-0.5;      fDataAC[i+106] = evntLSB;
1600    Zs[1]=0.5;    };
1601    Yp[0]=-20.;  
1602    Yp[2]=-1.;    // increments for every trigger might be needed at some point.
1603    Yp[4]=17.;    // dummy for now
1604    for(i=0;i<3;i++)    fDataAC[50]  = 0x0000;
1605      Yp[2*i+1]=Yp[2*i]+3;    fDataAC[114] = 0x0000;
1606    srand(time(NULL));  
1607    // --- activate branches:    // dummy FPGA clock (increment by 1 at each event)
1608    fhBookTree->SetBranchStatus("Nthtof",1);    /*    
1609    fhBookTree->SetBranchStatus("Ipltof",1);      fDataAC[51] = 0x006C;
1610    fhBookTree->SetBranchStatus("Ipaddle",1);      fDataAC[52] = 0x6C6C;
1611          fDataAC[115] = 0x006C;
1612    fhBookTree->SetBranchStatus("Xintof",1);      fDataAC[116] = 0x6C6C;
1613    fhBookTree->SetBranchStatus("Yintof",1);    */
1614    fhBookTree->SetBranchStatus("Xouttof",1);    if (Ievnt<=0xFFFF) {
1615    fhBookTree->SetBranchStatus("Youttof",1);      fDataAC[51] = 0x0000;
1616          fDataAC[52] = Ievnt;
1617    fhBookTree->SetBranchStatus("Ereltof",1);      fDataAC[115] = 0x0000;
1618    fhBookTree->SetBranchStatus("Timetof",1);      fDataAC[116] = Ievnt;
1619    NdFT=0;    } else {
1620    Ert=0;      fDataAC[51] = evntMSB;
1621    for(i=0;i<Nthtof;i++){      fDataAC[52] = evntLSB;
1622      if(Ipltof[i]!=6) continue;      fDataAC[115] = fDataAC[51];
1623      Ert+=Ereltof[i];      fDataAC[116] = fDataAC[52];
1624            }
1625        
1626      if(modo=="ns") continue;    // dummy temperatures
1627      NdF=Int_t(Ereltof[i]/E1);    fDataAC[53] = 0x0000;
1628      NdFT=0;    fDataAC[54] = 0x0000;
1629      X=Xintof[i];    fDataAC[117] = 0x0000;
1630      Y=Yintof[i];    fDataAC[118] = 0x0000;
1631      Z=((Float_t)random()/(Float_t)0x7fffffff)-0.5;  
1632      //cout<<"XYZ "<<X<<"  "<<Y<<"  "<<Z<<endl;  
1633      for(j=0;j<NdF;j++){    // dummy DAC thresholds
1634        q=(Float_t)random()/(Float_t)0x7fffffff;    for (UInt_t i=0; i<=7; i++){
1635        w=(Float_t)random()/(Float_t)0x7fffffff;      fDataAC[i+55] = 0x1A13;  
1636        // cout<<"qw "<<q<<" "<<w<<endl;      fDataAC[i+119] = 0x1A13;
1637        V[0]=p*cos(6.28318*q);    }
1638        V[1]=p*sin(6.28318*q);    
1639        V[2]=p*(2.*w-1.);    // We activate all branches. Once the digitization algorithm is determined
1640        pmt=0;    // only the branches that involve needed information will be activated
1641        x=X;    
1642        y=Y;    fhBookTree->SetBranchAddress("Ievnt",&Ievnt);
1643        z=Z;    fhBookTree->SetBranchStatus("Nthcat",1);
1644        while(pmt==0 && (x>Xs[0] && x<Xs[1])&&(y>Ys[0] && y<Ys[1])&&(z>Zs[0] && z<Zs[1])){    fhBookTree->SetBranchStatus("Iparcat",1);
1645          l=0;    fhBookTree->SetBranchStatus("Icat",1);
1646          while(pmt==0 && (x>Xs[0] && x<Xs[1])&&(y>Ys[0] && y<Ys[1])&&(z>Zs[0] && z<Zs[1])){    fhBookTree->SetBranchStatus("Xincat",1);
1647            x+=V[0];    fhBookTree->SetBranchStatus("Yincat",1);
1648            y+=V[1];    fhBookTree->SetBranchStatus("Zincat",1);
1649            z+=V[2];    fhBookTree->SetBranchStatus("Xoutcat",1);
1650            l+=p;    fhBookTree->SetBranchStatus("Youtcat",1);
1651            //cout<<x<<"  "<<y<<"  "<<z<<"  "<<l<<endl;    fhBookTree->SetBranchStatus("Zoutcat",1);
1652            //cin>>ciao;    fhBookTree->SetBranchStatus("Erelcat",1);
1653          }    fhBookTree->SetBranchStatus("Timecat",1);
1654          if((x<Xs[0]+p || x>Xs[1]-p)&&(y>Ys[0]+p && y<Ys[1]-p)&&(z>Zs[0]+p && z<Zs[1]-p)){    fhBookTree->SetBranchStatus("Pathcat",1);
1655            for(t=0;t<3;t++){    fhBookTree->SetBranchStatus("P0cat",1);
1656              if(y>=Yp[2*t] && y<Yp[2*t+1]){    fhBookTree->SetBranchStatus("Nthcas",1);
1657                if(pmt==0)NdFT++;    fhBookTree->SetBranchStatus("Iparcas",1);
1658                pmt=1;    fhBookTree->SetBranchStatus("Icas",1);
1659                //cout<<NdFT<<endl;    fhBookTree->SetBranchStatus("Xincas",1);
1660                break;    fhBookTree->SetBranchStatus("Yincas",1);
1661              }    fhBookTree->SetBranchStatus("Zincas",1);
1662            }    fhBookTree->SetBranchStatus("Xoutcas",1);
1663            if(pmt==1)break;    fhBookTree->SetBranchStatus("Youtcas",1);
1664            V[0]=-V[0];    fhBookTree->SetBranchStatus("Zoutcas",1);
1665          }    fhBookTree->SetBranchStatus("Erelcas",1);
1666          q=(Float_t)random()/(Float_t)0x7fffffff;    fhBookTree->SetBranchStatus("Timecas",1);
1667          w=1-exp(-l/l0);    fhBookTree->SetBranchStatus("Pathcas",1);
1668          if(q<w)break;    fhBookTree->SetBranchStatus("P0cas",1);
1669          q=(Float_t)random()/(Float_t)0x7fffffff;    fhBookTree->SetBranchStatus("Nthcard",1);
1670          w=0.5;    fhBookTree->SetBranchStatus("Iparcard",1);
1671          if(q<w)break;    fhBookTree->SetBranchStatus("Icard",1);
1672          if((x>Xs[0]+p && x<Xs[1]-p)&&(y<Ys[0]+p || y>Ys[1]-p)&&(z>Zs[0]+p && z<Zs[1]-p))V[1]=-V[1];    fhBookTree->SetBranchStatus("Xincard",1);
1673          if((x>Xs[0]+p && x<Xs[1]-p)&&(y>Ys[0]+p && y<Ys[1]-p)&&(z<Zs[0]+p || z>Zs[1]-p))V[2]=-V[2];    fhBookTree->SetBranchStatus("Yincard",1);
1674          x+=V[0];    fhBookTree->SetBranchStatus("Zincard",1);
1675          y+=V[1];    fhBookTree->SetBranchStatus("Xoutcard",1);
1676          z+=V[2];    fhBookTree->SetBranchStatus("Youtcard",1);
1677          l=0;    fhBookTree->SetBranchStatus("Zoutcard",1);
1678          //cout<<x<<"  "<<y<<"  "<<z<<"  "<<l<<endl;    fhBookTree->SetBranchStatus("Erelcard",1);
1679                  //cin>>ciao;    fhBookTree->SetBranchStatus("Timecard",1);
1680        }    fhBookTree->SetBranchStatus("Pathcard",1);
1681      }    fhBookTree->SetBranchStatus("P0card",1);
1682    }  
1683    Ert=Ert/0.002;    // In this simpliefied approach we will assume that once
1684    q=(Float_t)(random())/(Float_t)(0x7fffffff);    // a particle releases > 0.5 mip in one of the 12 AC detectors it
1685    w=0.7;    // will fire. We will furthermore assume that both cards read out
1686    //E0=Float_t(4064)/7;    // identical data.
1687    E0=4064./7.;  
1688    S4=(Int_t)(4064.*(1.-exp(-int(Ert)/E0)));    // If you develop your digitization algorithm, you should start by
1689    //S4=Ert*7;    // identifying the information present in level2 (post-darth-vader)
1690    i=S4/4;    // data.
1691    if(S4%4==0)  
1692      S4v=S4+S4p;    Float_t SumEcat[5];
1693    else if(S4%4==1) {    Float_t SumEcas[5];
1694      if(q<w) S4v=S4-1+S4p;    Float_t SumEcard[5];
1695      else S4v=S4+1+S4p;    for (Int_t k= 0;k<5;k++){
1696    } else if(S4%4==2)      SumEcat[k]=0.;
1697      S4v=S4+S4p;      SumEcas[k]=0.;
1698    else if(S4%4==3){      SumEcard[k]=0.;
1699      if(q<w) S4v=S4+1+S4p;    };
1700      else S4v=S4-1+S4p;  
1701    }    if (Nthcat>50 || Nthcas>50 || Nthcard>50)
1702        printf("*** ERROR AC! NthAC out of range!\n\n");
1703    cout << "Ert= " <<Ert<<"; S4v= "<<S4v<<"; S4= "<<S4<<endl;  
1704    fDataS4[0]=S4v;//0xf028;    // energy dependence on position (see file AcFitOutputDistancePmt.C by S.Orsi)
1705    fDataS4[1]=0xd800;    // based on J.Lundquist's calculations (PhD thesis, page 94)
1706    fDataS4[2]=0x0300;    // function: [0]+[1]*atan([2]/(x+1)), where the 3 parameters are:
1707    //  cout<<"  PMT  "<<NdFT<<"  "<<NdF<<endl;    //   8.25470e-01   +- 1.79489e-02
1708    //cin>>ciao;    //   6.41609e-01   +- 2.65846e-02
1709  }    //   9.81177e+00   +- 1.21284e+00
1710      // hp: 1 minimum ionising particle at 35cm from the PMT releases 1mip
1711      //
1712      // NB: the PMT positions are needed!
1713  void Digitizer::DigitizeND(){  
1714    // creato:  S. Borisov, INFN Roma2 e MEPHI, Sett 2007    // look in CAT
1715    Int_t i=0;    //  for (UInt_t k= 0;k<50;k++){
1716    UShort_t NdN=0;    for (Int_t k= 0;k<Nthcat;k++){
1717    fhBookTree->SetBranchStatus("Nthnd",1);      if (Erelcat[k] > 0)
1718    fhBookTree->SetBranchStatus("Itubend",1);        SumEcat[Icat[k]] += Erelcat[k];
1719    fhBookTree->SetBranchStatus("Iparnd",1);      };
1720    fhBookTree->SetBranchStatus("Xinnd",1);  
1721    fhBookTree->SetBranchStatus("Yinnd",1);    // look in CAS
1722    fhBookTree->SetBranchStatus("Zinnd",1);    for (Int_t k= 0;k<Nthcas;k++){
1723    fhBookTree->SetBranchStatus("Xoutnd",1);      if (Erelcas[k] >0)
1724    fhBookTree->SetBranchStatus("Youtnd",1);        SumEcas[Icas[k]] += Erelcas[k];
1725    fhBookTree->SetBranchStatus("Zoutnd",1);    };
1726    fhBookTree->SetBranchStatus("Erelnd",1);  
1727    fhBookTree->SetBranchStatus("Timend",1);    // look in CARD
1728    fhBookTree->SetBranchStatus("Pathnd",1);    for (Int_t k= 0;k<Nthcard;k++){
1729    fhBookTree->SetBranchStatus("P0nd",1);      if (Erelcard[k] >0)
1730    //cout<<"n="<<Nthnd<<"  "<<NdN<<"\n";        SumEcard[Icard[k]] += Erelcard[k];
1731    for(i=0;i<Nthnd;i++){    };
1732      if(Iparnd[i]==13){  
1733        NdN++;    // channel mapping              Hit Map
1734      }    // 1 CARD4                      0          LSB
1735    }    // 2 CAT2                       0
1736    NdN=100;    // 3 CAS1                       0
1737    for(i=0;i<3;i++){    // 4 NC                         0
1738      fDataND[2*i]=0x0000;    // 5 CARD2                      0
1739      fDataND[2*i+1]=0x010F;    // 6 CAT4                       1
1740    }    // 7 CAS4                       0  
1741    fDataND[0]=0xFF00 & (256*NdN);    // 8 NC                         0
1742  }    // 9 CARD3                      0
1743      // 10 CAT3                      0
1744      // 11 CAS3                      0
1745  void Digitizer::DigitizeDummy() {    // 12 NC                        0
1746      // 13 CARD1                     0
1747    fhBookTree->SetBranchStatus("Enestrip",1);    // 14 CAT1                      0
1748      // 15 CAS2                      0
1749    // dumy header    // 16 NC                        0          MSB
1750    fDataDummy[0] = 0xCAAA;  
1751      // In the first version only the hit-map is filled, not the SR.
1752    for (Int_t i=1; i<fDummybuffer; i++){  
1753      fDataDummy[i] = 0xFFFF;    // Threshold: 0.8 MeV.
1754      //   printf("%0x  ",fDataDummy[i]);    
1755      //if ((i+1)%8 ==0) cout << endl;    Float_t thr = 8e-4;
1756    }  
1757  };    fDataAC[3] = 0x0000;
1758    
1759      if (SumEcas[0] > thr)  fDataAC[3]  = 0x0004;
1760  void Digitizer::WriteData(){    if (SumEcas[1] > thr)  fDataAC[3] += 0x4000;
1761      if (SumEcas[2] > thr)  fDataAC[3] += 0x0400;
1762    // Routine that writes the data to a binary file    if (SumEcas[3] > thr)  fDataAC[3] += 0x0040;  
1763    // PSCU data are already swapped  
1764    fOutputfile.write(reinterpret_cast<char*>(fDataPSCU),sizeof(UShort_t)*fPSCUbuffer);    if (SumEcat[0] > thr)  fDataAC[3] += 0x2000;
1765    // TRG    if (SumEcat[1] > thr)  fDataAC[3] += 0x0002;
1766    fOutputfile.write(reinterpret_cast<char*>(fDataTrigger),sizeof(UChar_t)*153);    if (SumEcat[2] > thr)  fDataAC[3] += 0x0200;
1767    // TOF    if (SumEcat[3] > thr)  fDataAC[3] += 0x0020;
1768    fOutputfile.write(reinterpret_cast<char*>(fDataTof),sizeof(UChar_t)*276);    
1769    // AC    if (SumEcard[0] > thr)  fDataAC[3] += 0x1000;
1770    UShort_t temp[1000000];    if (SumEcard[1] > thr)  fDataAC[3] += 0x0010;
1771    memset(temp,0,sizeof(UShort_t)*1000000);    if (SumEcard[2] > thr)  fDataAC[3] += 0x0100;
1772    swab(fDataAC,temp,sizeof(UShort_t)*fACbuffer);  // WE MUST SWAP THE BYTES!!!    if (SumEcard[3] > thr)  fDataAC[3] += 0x0001;
1773    fOutputfile.write(reinterpret_cast<char*>(temp),sizeof(UShort_t)*fACbuffer);  
1774    // CALO    fDataAC[67] = fDataAC[3];
1775    memset(temp,0,sizeof(UShort_t)*1000000);  
1776    swab(fDataCALO,temp,sizeof(UShort_t)*fCALOlength); // WE MUST SWAP THE BYTES!!!    // shift registers
1777    fOutputfile.write(reinterpret_cast<char*>(temp),sizeof(UShort_t)*fCALOlength);    // the central bin is equal to the hitmap, all other bins in the shift register are 0
1778    // TRK    for (UInt_t i=0; i<=15; i++){
1779    memset(temp,0,sizeof(UShort_t)*1000000);      fDataAC[i+11] = 0x0000;  
1780    swab(fDataTrack,temp,sizeof(UShort_t)*fTracklength);  // WE MUST SWAP THE BYTES!!!      fDataAC[i+75] = 0x0000;
1781    fOutputfile.write(reinterpret_cast<char*>(temp),sizeof(UShort_t)*fTracklength);    }
1782    fTracklength=0;    fDataAC[18] = fDataAC[3];
1783     // padding to 64 bytes    fDataAC[82] = fDataAC[3];
1784    //  
1785    if ( fPadding ){    //    for (Int_t i=0; i<fACbuffer; i++){
1786      fOutputfile.write(reinterpret_cast<char*>(fDataPadding),sizeof(UChar_t)*fPadding);    //    printf("%0x  ",fDataAC[i]);  
1787    };    //    if ((i+1)%8 ==0) cout << endl;
1788    // S4    //   }
1789    memset(temp,0,sizeof(UShort_t)*1000000);  };
1790    swab(fDataS4,temp,sizeof(UShort_t)*fS4buffer);  // WE MUST SWAP THE BYTES!!!  
1791    fOutputfile.write(reinterpret_cast<char*>(temp),sizeof(UShort_t)*fS4buffer);  
1792    // ND  void Digitizer::DigitizeS4(){
1793    memset(temp,0,sizeof(UShort_t)*1000000);    Int_t DEBUG=0;
1794    swab(fDataND,temp,sizeof(UShort_t)*fNDbuffer);  // WE MUST SWAP THE BYTES!!!    // creato:  S. Borisov, INFN Roma2 e MEPHI, Sett 2007
1795    fOutputfile.write(reinterpret_cast<char*>(temp),sizeof(UShort_t)*fNDbuffer);    TString ciao,modo="ns";
1796  };    Int_t i,j,t,NdF,pmt,NdFT,S4,S4v=0,S4p=32;
1797      Float_t E0,E1=1e-6,Ert,X,Y,Z,x,y,z,V[3],Xs[2],Ys[2],Zs[2],Yp[6],q,w,p=0.1,l,l0=500;
1798      Xs[0]=-24.1;
1799  void Digitizer::ReadData(){    Xs[1]=24.1;
1800      Ys[0]=-24.1;
1801    UShort_t InData[64];    Ys[1]=24.1;
1802      Zs[0]=-0.5;
1803    // for debuggigng purposes only, write your own routine if you like (many    Zs[1]=0.5;
1804    // hardwired things.    Yp[0]=-20.;
1805        Yp[2]=-1.;
1806    ifstream InputFile;    Yp[4]=17.;
1807      for(i=0;i<3;i++)
1808    // if (!InputFile) {      Yp[2*i+1]=Yp[2*i]+3;
1809      srand(time(NULL));
1810    //     std::cout << "ERROR" << endl;    // --- activate branches:
1811    //     // An error occurred!    fhBookTree->SetBranchStatus("Nthtof",1);
1812    //     // myFile.gcount() returns the number of bytes read.    fhBookTree->SetBranchStatus("Ipltof",1);
1813    //     // calling myFile.clear() will reset the stream state    fhBookTree->SetBranchStatus("Ipaddle",1);
1814    //     // so it is usable again.    
1815    //   };    fhBookTree->SetBranchStatus("Xintof",1);
1816      fhBookTree->SetBranchStatus("Yintof",1);
1817      fhBookTree->SetBranchStatus("Xouttof",1);
1818        fhBookTree->SetBranchStatus("Youttof",1);
1819    //InputFile.seekg(0);    
1820      fhBookTree->SetBranchStatus("Ereltof",1);
1821    InputFile.open(fFilename, ios::in | ios::binary);    fhBookTree->SetBranchStatus("Timetof",1);
1822    //    fOutputfile.seekg(0);    NdFT=0;
1823    if (!InputFile.is_open()) std::cout << "ERROR" << endl;    Ert=0;
1824      for(i=0;i<Nthtof;i++){
1825    InputFile.seekg(0);      if(Ipltof[i]!=6) continue;
1826          Ert+=Ereltof[i];
1827    for (Int_t k=0; k<=1000; k++){            
1828      InputFile.read(reinterpret_cast<char*>(InData),384*sizeof(UShort_t));      if(modo=="ns") continue;
1829        NdF=Int_t(Ereltof[i]/E1);
1830      std::cout << "Read back: " << endl << endl;      NdFT=0;
1831        X=Xintof[i];
1832      for (Int_t i=0; i<=384; i++){      Y=Yintof[i];
1833        printf("%4x ", InData[i]);        Z=(Float_t)(random())/(Float_t)(0x7fffffff)-0.5;
1834        if ((i+1)%8 ==0) cout << endl;      //cout<<"XYZ "<<X<<"  "<<Y<<"  "<<Z<<endl;
1835      }      for(j=0;j<NdF;j++){
1836          q=(Float_t)random()/(Float_t)0x7fffffff;
1837    }        w=(Float_t)random()/(Float_t)0x7fffffff;
1838    cout << endl;        // cout<<"qw "<<q<<" "<<w<<endl;
1839    InputFile.close();        V[0]=p*cos(6.28318*q);
1840          V[1]=p*sin(6.28318*q);
1841  };        V[2]=p*(2.*w-1.);
1842          pmt=0;
1843          x=X;
1844          y=Y;
1845  void Digitizer::DigitizeTrack() {        z=Z;
1846  //std:: cout << "Entering DigitizeTrack " << endl;        while(pmt==0 && (x>Xs[0] && x<Xs[1])&&(y>Ys[0] && y<Ys[1])&&(z>Zs[0] && z<Zs[1])){
1847  Float_t  AdcTrack[fNviews][fNstrips_view];  //  Vector of strips to be compressed          l=0;
1848            while(pmt==0 && (x>Xs[0] && x<Xs[1])&&(y>Ys[0] && y<Ys[1])&&(z>Zs[0] && z<Zs[1])){
1849  Int_t Iview;            x+=V[0];
1850  Int_t Nstrip;            y+=V[1];
1851              z+=V[2];
1852    for (Int_t j=0; j<fNviews;j++) {            l+=p;
1853              //cout<<x<<"  "<<y<<"  "<<z<<"  "<<l<<endl;
1854      for (Int_t i=0; i<fNladder;i++) {            //cin>>ciao;
1855            }
1856        Float_t commonN1=gRandom->Gaus(0.,fSigmaCommon);          if((x<Xs[0]+p || x>Xs[1]-p)&&(y>Ys[0]+p && y<Ys[1]-p)&&(z>Zs[0]+p && z<Zs[1]-p)){
1857        Float_t commonN2=gRandom->Gaus(0.,fSigmaCommon);            for(t=0;t<3;t++){
1858        for (Int_t k=0; k<fNstrips_ladder;k++) {              if(y>=Yp[2*t] && y<Yp[2*t+1]){
1859        Nstrip=i*fNstrips_ladder+k;                if(pmt==0)NdFT++;
1860        AdcTrack[j][Nstrip]=gRandom->Gaus(fPedeTrack[j][Nstrip],fSigmaTrack[j][Nstrip]);                pmt=1;
1861        if(k<4*128) {AdcTrack[j][Nstrip] += commonN1;}  // full correlation of 4 VA1 Com. Noise                //cout<<NdFT<<endl;
1862        else {AdcTrack[j][Nstrip] += commonN2;}   // full correlation of 4 VA1 Com. Noise                break;
1863                }
1864        };            }
1865                    if(pmt==1)break;
1866                      V[0]=-V[0];
1867      };          }
1868            q=(Float_t)random()/(Float_t)0x7fffffff;
1869            w=1-exp(-l/l0);
1870    };          if(q<w)break;
1871            q=(Float_t)random()/(Float_t)0x7fffffff;
1872            w=0.5;
1873    fhBookTree->SetBranchStatus("Nstrpx",1);          if(q<w)break;
1874    fhBookTree->SetBranchStatus("Npstripx",1);          if((x>Xs[0]+p && x<Xs[1]-p)&&(y<Ys[0]+p || y>Ys[1]-p)&&(z>Zs[0]+p && z<Zs[1]-p))V[1]=-V[1];
1875    fhBookTree->SetBranchStatus("Ntstripx",1);          if((x>Xs[0]+p && x<Xs[1]-p)&&(y>Ys[0]+p && y<Ys[1]-p)&&(z<Zs[0]+p || z>Zs[1]-p))V[2]=-V[2];
1876    fhBookTree->SetBranchStatus("Istripx",1);          x+=V[0];
1877    fhBookTree->SetBranchStatus("Qstripx",1);          y+=V[1];
1878    fhBookTree->SetBranchStatus("Xstripx",1);          z+=V[2];
1879    fhBookTree->SetBranchStatus("Nstrpy",1);          l=0;
1880    fhBookTree->SetBranchStatus("Npstripy",1);          //cout<<x<<"  "<<y<<"  "<<z<<"  "<<l<<endl;
1881    fhBookTree->SetBranchStatus("Ntstripy",1);                  //cin>>ciao;
1882    fhBookTree->SetBranchStatus("Istripy",1);        }
1883    fhBookTree->SetBranchStatus("Qstripy",1);      }
1884    fhBookTree->SetBranchStatus("Ystripy",1);    }
1885      Ert=Ert/0.002;
1886      q=(Float_t)(random())/(Float_t)0x7fffffff;
1887      w=0.7;
1888    Float_t ADCfull;    //E0=(Float_t)(4064./7.);
1889    Int_t iladd=0;    E0=4064./7.;
1890    for (Int_t ix=0; ix<Nstrpx;ix++) {    if(Ert<1) S4=0;
1891    Iview=Npstripx[ix]*2-1;    else S4=(Int_t)(4064.*(1.-exp(-(Ert-1.)/E0)));
1892    Nstrip=(Int_t)Istripx[ix]-1;    i=S4/4;
1893    if(Nstrip<fNstrips_ladder) iladd=0;    if(S4%4==0)
1894    if((Nstrip>=fNstrips_ladder)&&(Nstrip<2*fNstrips_ladder)) iladd=1;      S4v=S4+S4p;
1895    if((Nstrip>=2*fNstrips_ladder)&&(Nstrip<3*fNstrips_ladder)) iladd=2;    else if(S4%4==1){
1896    ADCfull=AdcTrack[Iview][Nstrip] += Qstripx[ix]*fMipCor[iladd][Iview];      if(q<w) S4v=S4-1+S4p;
1897    AdcTrack[Iview][Nstrip] *= SaturationTrack(ADCfull);      else S4v=S4+1+S4p;
1898      } else if(S4%4==2) S4v=S4+S4p;
1899    };    else if(S4%4==3){
1900        if(q<w) S4v=S4+1+S4p;
1901        else S4v=S4-1+S4p;
1902    for (Int_t iy=0; iy<Nstrpy;iy++) {    }
1903    Iview=Npstripy[iy]*2-2;    if (DEBUG)
1904    Nstrip=(Int_t)Istripy[iy]-1;      cout<<"Ert_S4 = " << Ert << " --- S4v = " << S4v << endl;
1905    if(Nstrip<fNstrips_ladder) iladd=0;    fDataS4[0]=S4v;//0xf028;
1906    if((Nstrip>=fNstrips_ladder)&&(Nstrip<2*fNstrips_ladder)) iladd=1;    fDataS4[1]=0xd800;
1907    if((Nstrip>=2*fNstrips_ladder)&&(Nstrip<3*fNstrips_ladder)) iladd=2;    fDataS4[2]=0x0300;
1908    ADCfull=AdcTrack[Iview][Nstrip] -= Qstripy[iy]*fMipCor[iladd][Iview];    //cout<<"  PMT  "<<NdFT<<"  "<<NdF<<endl;
1909    AdcTrack[Iview][Nstrip] *= SaturationTrack(ADCfull);    //cin>>ciao;
1910    }
1911    };    
1912          
1913  CompressTrackData(AdcTrack);  // Compress and Digitize data of one Ladder  in turn for all ladders  
1914    void Digitizer::DigitizeND(){
1915  };    // creato:  S. Borisov, INFN Roma2 e MEPHI, Sett 2007
1916      Int_t i=0;
1917      UShort_t NdN=0;
1918      fhBookTree->SetBranchStatus("Nthnd",1);
1919  void Digitizer::DigitizeTrackCalib(Int_t ii) {    fhBookTree->SetBranchStatus("Itubend",1);
1920      fhBookTree->SetBranchStatus("Iparnd",1);  
1921  std:: cout << "Entering DigitizeTrackCalib " << ii << endl;    fhBookTree->SetBranchStatus("Xinnd",1);
1922  if( (ii!=1)&&(ii!=2) ) {    fhBookTree->SetBranchStatus("Yinnd",1);
1923   std:: cout << "error wrong DigitizeTrackCalib argument" << endl;    fhBookTree->SetBranchStatus("Zinnd",1);
1924   return;    fhBookTree->SetBranchStatus("Xoutnd",1);
1925  };    fhBookTree->SetBranchStatus("Youtnd",1);
1926      fhBookTree->SetBranchStatus("Zoutnd",1);
1927  memset(fDataTrack,0,sizeof(UShort_t)*fTRACKbuffer);    fhBookTree->SetBranchStatus("Erelnd",1);
1928  fTracklength=0;    fhBookTree->SetBranchStatus("Timend",1);
1929      fhBookTree->SetBranchStatus("Pathnd",1);
1930  UShort_t Dato;    fhBookTree->SetBranchStatus("P0nd",1);
1931      //cout<<"n="<<Nthnd<<"  "<<NdN<<"\n";
1932  Float_t dato1;    for(i=0;i<Nthnd;i++){
1933  Float_t dato2;      if(Iparnd[i]==13){
1934  Float_t dato3;        NdN++;
1935  Float_t dato4;      }
1936      }
1937  UShort_t DatoDec;    //NdN=100; //only for debug
1938  UShort_t DatoDec1;  
1939  UShort_t DatoDec2;    for(i=0;i<3;i++){
1940  UShort_t DatoDec3;      fDataND[2*i]=0x0000;
1941  UShort_t DatoDec4;      fDataND[2*i+1]=0x010F;
1942      }
1943  UShort_t EVENT_CAL;    fDataND[0]=0xFF00 & (256*NdN);
1944  UShort_t PED_L1;  }
1945  UShort_t ReLength;  
1946  UShort_t OveCheckCode;  
1947  //UShort_t PED_L2;  void Digitizer::DigitizeDummy() {
1948  //UShort_t PED_L3HI;  
1949  //UShort_t PED_L3LO;    fhBookTree->SetBranchStatus("Enestrip",1);
1950  //UShort_t SIG_L1HI;  
1951  //UShort_t SIG_L1LO;    // dumy header
1952  //UShort_t SIG_L2HI;    fDataDummy[0] = 0xCAAA;
1953  //UShort_t SIG_L2LO;  
1954  //UShort_t SIG_L3;    for (Int_t i=1; i<fDummybuffer; i++){
1955  //UShort_t BAD_L1;      fDataDummy[i] = 0xFFFF;
1956  //UShort_t BAD_L2LO;      //   printf("%0x  ",fDataDummy[i]);  
1957  //UShort_t BAD_L3HI;      //if ((i+1)%8 ==0) cout << endl;
1958  //UShort_t BAD_L3LO;    }
1959  //UShort_t FLAG;  };
1960    
1961    
1962    Int_t DSPpos;  void Digitizer::WriteData(){
1963    for (Int_t j=ii-1; j<fNviews;j+=2) {  
1964    UShort_t CkSum=0;    // Routine that writes the data to a binary file
1965    // here skip the dsp header and his trailer , to be written later    // PSCU data are already swapped
1966    DSPpos=fTracklength;    fOutputfile.write(reinterpret_cast<char*>(fDataPSCU),sizeof(UShort_t)*fPSCUbuffer);
1967    fTracklength=fTracklength+13+3;    // TRG
1968      fOutputfile.write(reinterpret_cast<char*>(fDataTrigger),sizeof(UChar_t)*153);
1969      // TOF
1970      for (Int_t i=0; i<fNladder;i++) {    fOutputfile.write(reinterpret_cast<char*>(fDataTof),sizeof(UChar_t)*276);
1971        for (Int_t k=0; k<fNstrips_ladder;k++) {    // AC
1972        // write in buffer the current LADDER    UShort_t temp[1000000];
1973        Dato=(UShort_t)fPedeTrack[j][i*fNstrips_ladder+k];    memset(temp,0,sizeof(UShort_t)*1000000);
1974        dato1=fPedeTrack[j][i*fNstrips_ladder+k]-Dato;    swab(fDataAC,temp,sizeof(UShort_t)*fACbuffer);  // WE MUST SWAP THE BYTES!!!
1975      fOutputfile.write(reinterpret_cast<char*>(temp),sizeof(UShort_t)*fACbuffer);
1976        DatoDec1=(UShort_t)(dato1*2);    // CALO
1977        dato2=dato1*2-DatoDec1;    memset(temp,0,sizeof(UShort_t)*1000000);
1978      swab(fDataCALO,temp,sizeof(UShort_t)*fCALOlength); // WE MUST SWAP THE BYTES!!!
1979        DatoDec2=(UShort_t)(dato2*2);    fOutputfile.write(reinterpret_cast<char*>(temp),sizeof(UShort_t)*fCALOlength);
1980        dato3=dato2*2-DatoDec2;    // TRK
1981            memset(temp,0,sizeof(UShort_t)*1000000);
1982        DatoDec3=(UShort_t)(dato3*2);    swab(fDataTrack,temp,sizeof(UShort_t)*fTracklength);  // WE MUST SWAP THE BYTES!!!
1983        dato4=dato3*2-DatoDec3;    fOutputfile.write(reinterpret_cast<char*>(temp),sizeof(UShort_t)*fTracklength);
1984            fTracklength=0;
1985        DatoDec4=(UShort_t)(dato4*2);     // padding to 64 bytes
1986            //
1987        DatoDec=DatoDec1*0x0008+DatoDec2*0x0004+DatoDec3*0x0002+DatoDec4*0x0001;    if ( fPadding ){
1988        fDataTrack[fTracklength]=( (Dato << 4) | (DatoDec & 0x000F) );      fOutputfile.write(reinterpret_cast<char*>(fDataPadding),sizeof(UChar_t)*fPadding);
1989        CkSum=CkSum^fDataTrack[fTracklength];    };
1990        fTracklength++;    // S4
1991        };    memset(temp,0,sizeof(UShort_t)*1000000);
1992      swab(fDataS4,temp,sizeof(UShort_t)*fS4buffer);  // WE MUST SWAP THE BYTES!!!
1993        for (Int_t k=0; k<fNstrips_ladder;k++) {    fOutputfile.write(reinterpret_cast<char*>(temp),sizeof(UShort_t)*fS4buffer);
1994        // write in buffer the current LADDER    // ND
1995        Dato=(UShort_t)fSigmaTrack[j][i*fNstrips_ladder+k];    memset(temp,0,sizeof(UShort_t)*1000000);
1996        dato1=fSigmaTrack[j][i*fNstrips_ladder+k]-Dato;    swab(fDataND,temp,sizeof(UShort_t)*fNDbuffer);  // WE MUST SWAP THE BYTES!!!
1997      fOutputfile.write(reinterpret_cast<char*>(temp),sizeof(UShort_t)*fNDbuffer);
1998        DatoDec1=(UShort_t)(dato1*2);  };
1999        dato2=dato1*2-DatoDec1;  
2000    
2001        DatoDec2=(UShort_t)(dato2*2);  void Digitizer::ReadData(){
2002        dato3=dato2*2-DatoDec2;  
2003            UShort_t InData[64];
2004        DatoDec3=(UShort_t)(dato3*2);  
2005        dato4=dato3*2-DatoDec3;    // for debuggigng purposes only, write your own routine if you like (many
2006            // hardwired things.
2007        DatoDec4=(UShort_t)(dato4*2);    
2008            ifstream InputFile;
2009        DatoDec=DatoDec1*0x0008+DatoDec2*0x0004+DatoDec3*0x0002+DatoDec4*0x0001;  
2010            // if (!InputFile) {
2011        fDataTrack[fTracklength]=( (Dato << 4) | (DatoDec & 0x000F) );  
2012        CkSum=CkSum^fDataTrack[fTracklength];    //     std::cout << "ERROR" << endl;
2013        fTracklength++;    //     // An error occurred!
2014        };    //     // myFile.gcount() returns the number of bytes read.
2015            //     // calling myFile.clear() will reset the stream state
2016        for (Int_t k=0; k<64;k++) {    //     // so it is usable again.
2017        fDataTrack[fTracklength]=0x0000;    //   };
2018        CkSum=CkSum^fDataTrack[fTracklength];  
2019        fTracklength++;  
2020      
2021        };    //InputFile.seekg(0);
2022        // end ladder  
2023      InputFile.open(fFilename, ios::in | ios::binary);
2024      // write in buffer the end ladder word    //    fOutputfile.seekg(0);
2025      if(i==0) fDataTrack[fTracklength]=0x1807;    if (!InputFile.is_open()) std::cout << "ERROR" << endl;
2026      if(i==1) fDataTrack[fTracklength]=0x1808;  
2027      if(i==2) fDataTrack[fTracklength]=0x1809;    InputFile.seekg(0);
2028      CkSum=CkSum^fDataTrack[fTracklength];    
2029      fTracklength++;    for (Int_t k=0; k<=1000; k++){
2030        InputFile.read(reinterpret_cast<char*>(InData),384*sizeof(UShort_t));
2031      // write in buffer the TRAILER  
2032      ReLength=(UShort_t)((fNstrips_ladder*2+64+1)*2+3);      std::cout << "Read back: " << endl << endl;
2033      OveCheckCode=0x0000;  
2034        for (Int_t i=0; i<=384; i++){
2035      fDataTrack[fTracklength]=0x0000;        printf("%4x ", InData[i]);  
2036      fTracklength++;        if ((i+1)%8 ==0) cout << endl;
2037          }
2038      fDataTrack[fTracklength]=(ReLength >> 8);  
2039      fTracklength++;    }
2040        cout << endl;
2041      fDataTrack[fTracklength]=( (ReLength << 8) | (OveCheckCode & 0x00FF) );    InputFile.close();
2042      fTracklength++;  
2043    };
2044      // end TRAILER          
2045      };  
2046    
2047    // write in buffer the DSP header  void Digitizer::DigitizeTrack() {
2048    //std:: cout << "Entering DigitizeTrack " << endl;
2049    fDataTrack[DSPpos]=(0xE800 | ( ((j+1) << 3) | 0x0005) );  Float_t  AdcTrack[fNviews][fNstrips_view];  //  Vector of strips to be compressed
2050      
2051    fDataTrack[DSPpos+1]=0x01A9;  Int_t Iview;
2052    Int_t Nstrip;
2053    fDataTrack[DSPpos+2]=0x8740;  
2054        for (Int_t j=0; j<fNviews;j++) {
2055    EVENT_CAL=0;  
2056    fDataTrack[DSPpos+3]=(0x1A00 | ( (0x03FF & EVENT_CAL)>> 1) );      for (Int_t i=0; i<fNladder;i++) {
2057      
2058    PED_L1=0;        Float_t commonN1=gRandom->Gaus(0.,fSigmaCommon);
2059    fDataTrack[DSPpos+4]=( ((EVENT_CAL << 15) | 0x5002 ) | ((0x03FF & PED_L1) << 2) );        Float_t commonN2=gRandom->Gaus(0.,fSigmaCommon);
2060            for (Int_t k=0; k<fNstrips_ladder;k++) {
2061    // FROM HERE WE WRITE AS ALL VARIABLE apart CkSum are =0          Nstrip=i*fNstrips_ladder+k;
2062          AdcTrack[j][Nstrip]=gRandom->Gaus(fPedeTrack[j][Nstrip],fSigmaTrack[j][Nstrip]);
2063    fDataTrack[DSPpos+5]=0x8014;        if(k<4*128) {AdcTrack[j][Nstrip] += commonN1;}  // full correlation of 4 VA1 Com. Noise
2064            else {AdcTrack[j][Nstrip] += commonN2;}   // full correlation of 4 VA1 Com. Noise
2065    fDataTrack[DSPpos+6]=0x00A0;  
2066            };
2067    fDataTrack[DSPpos+7]=0x0500;        
2068              
2069    fDataTrack[DSPpos+8]=0x2801;      };
2070      
2071    fDataTrack[DSPpos+9]=0x400A;  
2072        };
2073    fDataTrack[DSPpos+10]=0x0050;  
2074      
2075    CkSum=(CkSum >> 8)^(CkSum&0x00FF);    fhBookTree->SetBranchStatus("Nstrpx",1);
2076    fDataTrack[DSPpos+11]=(0x0280 | (CkSum >> 3));    fhBookTree->SetBranchStatus("Npstripx",1);
2077        fhBookTree->SetBranchStatus("Ntstripx",1);
2078    fDataTrack[DSPpos+12]=(0x1FFF | (CkSum << 13) );    fhBookTree->SetBranchStatus("Istripx",1);
2079      fhBookTree->SetBranchStatus("Qstripx",1);
2080    // end dsp header    fhBookTree->SetBranchStatus("Xstripx",1);
2081      fhBookTree->SetBranchStatus("Nstrpy",1);
2082    // write in buffer the TRAILER    fhBookTree->SetBranchStatus("Npstripy",1);
2083        fhBookTree->SetBranchStatus("Ntstripy",1);
2084    ReLength=(UShort_t)((13*2)+3);    fhBookTree->SetBranchStatus("Istripy",1);
2085    OveCheckCode=0x0000;    fhBookTree->SetBranchStatus("Qstripy",1);
2086    fDataTrack[DSPpos+13]=0x0000;    fhBookTree->SetBranchStatus("Ystripy",1);
2087    
2088    fDataTrack[DSPpos+14]=(ReLength >> 8);  
2089      
2090    fDataTrack[DSPpos+15]=( (ReLength << 8) | (OveCheckCode & 0x00FF) );    Float_t ADCfull;
2091        Int_t iladd=0;
2092    // end TRAILER    for (Int_t ix=0; ix<Nstrpx;ix++) {
2093      Iview=Npstripx[ix]*2-1;
2094      Nstrip=(Int_t)Istripx[ix]-1;
2095      if(Nstrip<fNstrips_ladder) iladd=0;
2096        if((Nstrip>=fNstrips_ladder)&&(Nstrip<2*fNstrips_ladder)) iladd=1;
2097    // end DSP        if((Nstrip>=2*fNstrips_ladder)&&(Nstrip<3*fNstrips_ladder)) iladd=2;
2098    };        ADCfull=AdcTrack[Iview][Nstrip] += Qstripx[ix]*fMipCor[iladd][Iview];
2099      AdcTrack[Iview][Nstrip] *= SaturationTrack(ADCfull);
2100    
2101      };
2102  };  
2103    
2104  void Digitizer::WriteTrackCalib() {    for (Int_t iy=0; iy<Nstrpy;iy++) {
2105      Iview=Npstripy[iy]*2-2;
2106      Nstrip=(Int_t)Istripy[iy]-1;
2107  std:: cout << " Entering WriteTrackCalib " << endl;    if(Nstrip<fNstrips_ladder) iladd=0;
2108      if((Nstrip>=fNstrips_ladder)&&(Nstrip<2*fNstrips_ladder)) iladd=1;
2109  fOutputfile.write(reinterpret_cast<char*>(fDataPSCU),sizeof(UShort_t)*fPSCUbuffer);    if((Nstrip>=2*fNstrips_ladder)&&(Nstrip<3*fNstrips_ladder)) iladd=2;
2110      ADCfull=AdcTrack[Iview][Nstrip] -= Qstripy[iy]*fMipCor[iladd][Iview];
2111  UShort_t temp[1000000];    AdcTrack[Iview][Nstrip] *= SaturationTrack(ADCfull);
2112  memset(temp,0,sizeof(UShort_t)*1000000);  
2113  swab(fDataTrack,temp,sizeof(UShort_t)*fTracklength);  // WE MUST SWAP THE BYTES!!!    };  
2114  fOutputfile.write(reinterpret_cast<char*>(temp),sizeof(UShort_t)*fTracklength);        
2115  fTracklength=0;  CompressTrackData(AdcTrack);  // Compress and Digitize data of one Ladder  in turn for all ladders
2116  if ( fPadding ){  
2117        fOutputfile.write(reinterpret_cast<char*>(fDataPadding),sizeof(UChar_t)*fPadding);  };
2118  };  
2119    
2120  };  
2121    void Digitizer::DigitizeTrackCalib(Int_t ii) {
2122    
2123  void Digitizer::ClearTrackCalib() {  std:: cout << "Entering DigitizeTrackCalib " << ii << endl;
2124    if( (ii!=1)&&(ii!=2) ) {
2125  std:: cout << "Entering ClearTrackCalib " << endl;   std:: cout << "error wrong DigitizeTrackCalib argument" << endl;
2126         return;
2127      };
2128  };  
2129    memset(fDataTrack,0,sizeof(UShort_t)*fTRACKbuffer);
2130    fTracklength=0;
2131  void Digitizer::LoadTrackCalib() {  
2132  std:: cout << "Entering LoadTrackCalib " << endl;  UShort_t Dato;
2133    
2134  // Generate the pedestals and sigmas according to parametrization  Float_t dato1;
2135    for (Int_t j=0; j<fNviews;j++) {  Float_t dato2;
2136      for (Int_t i=0; i<fNstrips_view;i++) {  Float_t dato3;
2137        Float_t dato4;
2138      if((j+1)%2==0) {  
2139      fPedeTrack[j][i]=gRandom->Gaus(fAvePedex,fSigmaPedex);  UShort_t DatoDec;
2140      fSigmaTrack[j][i]=gRandom->Gaus(fAveSigmax,fSigmaSigmax);  UShort_t DatoDec1;
2141      };  UShort_t DatoDec2;
2142      if((j+1)%2==1) {  UShort_t DatoDec3;
2143      fPedeTrack[j][i]=gRandom->Gaus(fAvePedey,fSigmaPedey);  UShort_t DatoDec4;
2144      fSigmaTrack[j][i]=gRandom->Gaus(fAveSigmay,fSigmaSigmay);  
2145      };  UShort_t EVENT_CAL;
2146        UShort_t PED_L1;
2147      };  UShort_t ReLength;
2148    };      UShort_t OveCheckCode;
2149    //UShort_t PED_L2;
2150      //UShort_t PED_L3HI;
2151      //UShort_t PED_L3LO;
2152  };  //UShort_t SIG_L1HI;
2153    //UShort_t SIG_L1LO;
2154  void Digitizer::LoadMipCor() {  //UShort_t SIG_L2HI;
2155  std:: cout << "Entering LoadMipCor" << endl;  //UShort_t SIG_L2LO;
2156    Float_t xfactor=1./151.6*1.04;  //UShort_t SIG_L3;
2157    Float_t yfactor=1./152.1;  //UShort_t BAD_L1;
2158    //UShort_t BAD_L2LO;
2159    fMipCor[0][0]=140.02*yfactor;  //UShort_t BAD_L3HI;
2160    fMipCor[0][1]=140.99*xfactor;  //UShort_t BAD_L3LO;
2161    fMipCor[0][2]=134.48*yfactor;  //UShort_t FLAG;
2162    fMipCor[0][3]=144.41*xfactor;  
2163    fMipCor[0][4]=140.74*yfactor;  
2164    fMipCor[0][5]=142.28*xfactor;    Int_t DSPpos;
2165    fMipCor[0][6]=134.53*yfactor;    for (Int_t j=ii-1; j<fNviews;j+=2) {
2166    fMipCor[0][7]=140.63*xfactor;    UShort_t CkSum=0;
2167    fMipCor[0][8]=135.55*yfactor;    // here skip the dsp header and his trailer , to be written later
2168    fMipCor[0][9]=138.00*xfactor;    DSPpos=fTracklength;
2169    fMipCor[0][10]=154.95*yfactor;    fTracklength=fTracklength+13+3;
2170    fMipCor[0][11]=158.44*xfactor;  
2171      
2172          for (Int_t i=0; i<fNladder;i++) {
2173    fMipCor[1][0]=136.07*yfactor;        for (Int_t k=0; k<fNstrips_ladder;k++) {
2174    fMipCor[1][1]=135.59*xfactor;        // write in buffer the current LADDER
2175    fMipCor[1][2]=142.69*yfactor;        Dato=(UShort_t)fPedeTrack[j][i*fNstrips_ladder+k];
2176    fMipCor[1][3]=138.19*xfactor;        dato1=fPedeTrack[j][i*fNstrips_ladder+k]-Dato;
2177    fMipCor[1][4]=137.35*yfactor;  
2178    fMipCor[1][5]=140.23*xfactor;        DatoDec1=(UShort_t)(dato1*2);
2179    fMipCor[1][6]=153.15*yfactor;        dato2=dato1*2-DatoDec1;
2180    fMipCor[1][7]=151.42*xfactor;  
2181    fMipCor[1][8]=129.76*yfactor;        DatoDec2=(UShort_t)(dato2*2);
2182    fMipCor[1][9]=140.63*xfactor;        dato3=dato2*2-DatoDec2;
2183    fMipCor[1][10]=157.87*yfactor;        
2184    fMipCor[1][11]=153.64*xfactor;        DatoDec3=(UShort_t)(dato3*2);
2185          dato4=dato3*2-DatoDec3;
2186    fMipCor[2][0]=134.98*yfactor;        
2187    fMipCor[2][1]=143.95*xfactor;        DatoDec4=(UShort_t)(dato4*2);
2188    fMipCor[2][2]=140.23*yfactor;        
2189    fMipCor[2][3]=138.88*xfactor;        DatoDec=DatoDec1*0x0008+DatoDec2*0x0004+DatoDec3*0x0002+DatoDec4*0x0001;
2190    fMipCor[2][4]=137.95*yfactor;        fDataTrack[fTracklength]=( (Dato << 4) | (DatoDec & 0x000F) );
2191    fMipCor[2][5]=134.87*xfactor;        CkSum=CkSum^fDataTrack[fTracklength];
2192    fMipCor[2][6]=157.56*yfactor;        fTracklength++;
2193    fMipCor[2][7]=157.31*xfactor;        };
2194    fMipCor[2][8]=141.37*yfactor;  
2195    fMipCor[2][9]=143.39*xfactor;        for (Int_t k=0; k<fNstrips_ladder;k++) {
2196    fMipCor[2][10]=156.15*yfactor;        // write in buffer the current LADDER
2197    fMipCor[2][11]=158.79*xfactor;        Dato=(UShort_t)fSigmaTrack[j][i*fNstrips_ladder+k];
2198          dato1=fSigmaTrack[j][i*fNstrips_ladder+k]-Dato;
2199  /*  
2200    for (Int_t j=0; j<fNviews;j++) {        DatoDec1=(UShort_t)(dato1*2);
2201      for (Int_t i=0; i<fNstrips_view;i++) {        dato2=dato1*2-DatoDec1;
2202      fMipCor[j][i]=1.;  
2203      };        DatoDec2=(UShort_t)(dato2*2);
2204    };            dato3=dato2*2-DatoDec2;
2205          
2206              DatoDec3=(UShort_t)(dato3*2);
2207  */          dato4=dato3*2-DatoDec3;
2208  };        
2209          DatoDec4=(UShort_t)(dato4*2);
2210  void Digitizer::CompressTrackData(Float_t AdcTrack[fNviews][fNstrips_view]) {        
2211  // copy of the corresponding compression fortran routine + new digitization        DatoDec=DatoDec1*0x0008+DatoDec2*0x0004+DatoDec3*0x0002+DatoDec4*0x0001;
2212  // std:: cout << "Entering CompressTrackData " << endl;        
2213  Int_t oldval=0;        fDataTrack[fTracklength]=( (Dato << 4) | (DatoDec & 0x000F) );
2214  Int_t newval=0;        CkSum=CkSum^fDataTrack[fTracklength];
2215  Int_t trasmesso=0;        fTracklength++;
2216  Int_t ntrastot=0;        };
2217  Float_t real;        
2218  Float_t inte;        for (Int_t k=0; k<64;k++) {
2219  Int_t cercacluster=0;        fDataTrack[fTracklength]=0x0000;
2220  Int_t kt=0;        CkSum=CkSum^fDataTrack[fTracklength];
2221  static const int DSPbufferSize = 4000; // 13 bit buffer to be rearranged in 16 bit Track buffer        fTracklength++;
2222  UShort_t DataDSP[DSPbufferSize];  // 13 bit  buffer to be rearranged in 16 bit Track buffer  
2223  UShort_t DSPlength;  // 13 bit buffer to be rearranged in 16 bit Track buffer        };
2224          // end ladder
2225  memset(fDataTrack,0,sizeof(UShort_t)*fTRACKbuffer); // probably not necessary becouse already done ?  
2226  fTracklength=0;      // write in buffer the end ladder word
2227        if(i==0) fDataTrack[fTracklength]=0x1807;
2228    for (Int_t iv=0; iv<fNviews;iv++) {      if(i==1) fDataTrack[fTracklength]=0x1808;
2229    memset(DataDSP,0,sizeof(UShort_t)*DSPbufferSize);      if(i==2) fDataTrack[fTracklength]=0x1809;
2230    DSPlength=16; // skip the header, to be written later      CkSum=CkSum^fDataTrack[fTracklength];
2231    UShort_t CheckSum=0;      fTracklength++;
2232  // write dsp header on buffer  
2233        // write in buffer the TRAILER
2234  //    fDataTrack[fTracklength]=0xE805;      ReLength=(UShort_t)((fNstrips_ladder*2+64+1)*2+3);
2235  //    fTracklength++;      OveCheckCode=0x0000;
2236    
2237  //    fDataTrack[fTracklength]=0x01A9;      fDataTrack[fTracklength]=0x0000;
2238  //    fTracklength++;      fTracklength++;
2239      
2240  // end dsp header      fDataTrack[fTracklength]=(ReLength >> 8);
2241        fTracklength++;
2242     //    
2243     // INIZIO VISTA IV - TAKE PROPER ACTION      fDataTrack[fTracklength]=( (ReLength << 8) | (OveCheckCode & 0x00FF) );
2244     //      fTracklength++;
2245    
2246        // end TRAILER        
2247        };
2248      for (Int_t ladder=0; ladder<fNladder;ladder++) {  
2249        Int_t k=0;    // write in buffer the DSP header
2250        while (k<fNstrips_ladder) {  
2251          // compress write in buffer the current LADDER    fDataTrack[DSPpos]=(0xE800 | ( ((j+1) << 3) | 0x0005) );
2252          if ( k == 0)  {    
2253            real=modff(AdcTrack[iv][ladder*fNstrips_ladder+k],&inte);    fDataTrack[DSPpos+1]=0x01A9;
2254            if (real > 0.5) inte=inte+1;  
2255            newval=(Int_t)inte -(Int_t)fPedeTrack[iv][ladder*fNstrips_ladder+k];    fDataTrack[DSPpos+2]=0x8740;
2256            // first strip of ladder is transmitted    
2257            // DC_TOT first " << AdcTrack[iv][ladder*fNstrips_ladder+k] << endl;    EVENT_CAL=0;
2258            DataDSP[DSPlength]=( ((UShort_t)inte) & 0x0FFF);    fDataTrack[DSPpos+3]=(0x1A00 | ( (0x03FF & EVENT_CAL)>> 1) );
2259            DSPlength++;      
2260            ntrastot++;    PED_L1=0;
2261            trasmesso=1;    fDataTrack[DSPpos+4]=( ((EVENT_CAL << 15) | 0x5002 ) | ((0x03FF & PED_L1) << 2) );
2262            oldval=newval;    
2263            kt=k;    // FROM HERE WE WRITE AS ALL VARIABLE apart CkSum are =0  
2264            k++;  
2265            continue;    fDataTrack[DSPpos+5]=0x8014;
2266          };    
2267          real=modff(AdcTrack[iv][ladder*fNstrips_ladder+k],&inte);    fDataTrack[DSPpos+6]=0x00A0;
2268          if (real > 0.5) inte=inte+1;    
2269          newval=(Int_t)inte -(Int_t)(fPedeTrack[iv][ladder*fNstrips_ladder+k]);    fDataTrack[DSPpos+7]=0x0500;
2270          cercacluster=1; // ?????????    
2271          if (cercacluster==1) {    fDataTrack[DSPpos+8]=0x2801;
2272              
2273   // controlla l'ordine di tutti queste strip ladder e DSP !!!!!!!          fDataTrack[DSPpos+9]=0x400A;
2274            Int_t diff=0;    
2275      fDataTrack[DSPpos+10]=0x0050;
2276                
2277            switch ((iv+1)%2) {    CkSum=(CkSum >> 8)^(CkSum&0x00FF);
2278            case 0: diff=newval-oldval;    fDataTrack[DSPpos+11]=(0x0280 | (CkSum >> 3));
2279            break;    
2280            case 1: diff=oldval-newval;        fDataTrack[DSPpos+12]=(0x1FFF | (CkSum << 13) );
2281            break;  
2282            };    // end dsp header
2283    
2284            if (diff>fCutclu*(Int_t)fSigmaTrack[iv][ladder*fNstrips_ladder+k]) {    // write in buffer the TRAILER
2285              Int_t clval=newval;    
2286              Int_t klp=k;        // go on to search for maximum    ReLength=(UShort_t)((13*2)+3);
2287              klp++;    OveCheckCode=0x0000;
2288      fDataTrack[DSPpos+13]=0x0000;
2289              while(klp<fNstrips_ladder) {  
2290                real=modff(AdcTrack[iv][ladder*fNstrips_ladder+klp],&inte);    fDataTrack[DSPpos+14]=(ReLength >> 8);
2291                if (real > 0.5) inte=inte+1;    
2292                Int_t clvalp=(Int_t)inte -(Int_t)fPedeTrack[iv][ladder*fNstrips_ladder+klp];    fDataTrack[DSPpos+15]=( (ReLength << 8) | (OveCheckCode & 0x00FF) );
2293                if((iv+1)%2==0) {    
2294      // end TRAILER
2295                  if(clvalp>clval) {  
2296                     clval=clvalp;  
2297                     k=klp;}  
2298                  else break; // max of cluster found    
2299      // end DSP    
2300                } else {      };    
2301    
2302                  if(clvalp<clval) {  
2303                     clval=clvalp;  
2304                     k=klp;}  };
2305                  else break; // max of cluster found  
2306    void Digitizer::WriteTrackCalib() {
2307                };  
2308                  
2309                klp++;  std:: cout << " Entering WriteTrackCalib " << endl;
2310              };  
2311    fOutputfile.write(reinterpret_cast<char*>(fDataPSCU),sizeof(UShort_t)*fPSCUbuffer);
2312              Int_t kl1=k-fNclst; // max of cluster (or end of ladder ?)  
2313              trasmesso=0;  UShort_t temp[1000000];
2314              if(kl1<0)  kl1=0;  memset(temp,0,sizeof(UShort_t)*1000000);
2315    swab(fDataTrack,temp,sizeof(UShort_t)*fTracklength);  // WE MUST SWAP THE BYTES!!!
2316              if(kt>=kl1) kl1=kt+1;  fOutputfile.write(reinterpret_cast<char*>(temp),sizeof(UShort_t)*fTracklength);
2317              if( (kt+1)==kl1 ) trasmesso=1;  fTracklength=0;
2318    if ( fPadding ){
2319          fOutputfile.write(reinterpret_cast<char*>(fDataPadding),sizeof(UChar_t)*fPadding);
2320                };
2321              Int_t kl2=k+fNclst;  
2322              if(kl2>=fNstrips_ladder) kl2=fNstrips_ladder-1;  };
2323    
2324              for(Int_t klt=kl1 ; klt<=kl2 ; klt++) {  
2325                if(trasmesso==0) {  void Digitizer::ClearTrackCalib() {
2326                //  std:: cout << "STRIP " << klt << endl;  
2327                //  std:: cout << "ADC_TOT " <<AdcTrack[iv][ladder*fNstrips_ladder+klt] << endl;  std:: cout << "Entering ClearTrackCalib " << endl;
2328        
2329                  DataDSP[DSPlength]=( ((UShort_t)klt) | 0x1000);    
2330                  DSPlength++;    };
2331                  ntrastot++;  
2332                
2333    void Digitizer::LoadTrackCalib() {
2334                  real=modff(AdcTrack[iv][ladder*fNstrips_ladder+klt],&inte);  std:: cout << "Entering LoadTrackCalib " << endl;
2335                  if (real > 0.5) inte=inte+1;  
2336                  DataDSP[DSPlength]=( ((UShort_t)inte) & 0x0FFF);  // Generate the pedestals and sigmas according to parametrization
2337                  DSPlength++;    for (Int_t j=0; j<fNviews;j++) {
2338                  ntrastot++;      for (Int_t i=0; i<fNstrips_view;i++) {
2339                    
2340                 }      if((j+1)%2==0) {
2341                 else {      fPedeTrack[j][i]=gRandom->Gaus(fAvePedex,fSigmaPedex);
2342                 //   std:: cout << "ADC_TOT " <<AdcTrack[iv][ladder*fNstrips_ladder+klt] << endl;      fSigmaTrack[j][i]=gRandom->Gaus(fAveSigmax,fSigmaSigmax);
2343                  real=modff(AdcTrack[iv][ladder*fNstrips_ladder+klt],&inte);      };
2344                  if (real > 0.5) inte=inte+1;      if((j+1)%2==1) {
2345                  DataDSP[DSPlength]=( ((UShort_t)inte) & 0x0FFF);      fPedeTrack[j][i]=gRandom->Gaus(fAvePedey,fSigmaPedey);
2346                  DSPlength++;                    fSigmaTrack[j][i]=gRandom->Gaus(fAveSigmay,fSigmaSigmay);
2347                  ntrastot++;      };
2348                  };      
2349                  trasmesso=1;                              };
2350              };  // end trasmission    };    
2351              kt=kl2;  
2352              k=kl2;    
2353              real=modff(AdcTrack[iv][ladder*fNstrips_ladder+kt],&inte);    
2354              if (real > 0.5) inte=inte+1;  };
2355              oldval=(Int_t)inte -(Int_t)fPedeTrack[iv][ladder*fNstrips_ladder+kt];  
2356              k++;  void Digitizer::LoadMipCor() {
2357              continue;  std:: cout << "Entering LoadMipCor" << endl;
2358      Float_t xfactor=1./151.6*1.04;
2359      Float_t yfactor=1./152.1;
2360            }; // end cercacluster  
2361          }; // end cercacluster    fMipCor[0][0]=140.02*yfactor;
2362            fMipCor[0][1]=140.99*xfactor;
2363  // start ZOP check for strips no    fMipCor[0][2]=134.48*yfactor;
2364            fMipCor[0][3]=144.41*xfactor;
2365        if(abs(newval-oldval)>=fCutzop*(Int_t)fSigmaTrack[iv][ladder*fNstrips_ladder+k]) {    fMipCor[0][4]=140.74*yfactor;
2366      fMipCor[0][5]=142.28*xfactor;
2367         if(trasmesso==0) {    fMipCor[0][6]=134.53*yfactor;
2368         // std:: cout << "STRIP " << k << endl;    fMipCor[0][7]=140.63*xfactor;
2369         // std:: cout << "ADC_TOT " << AdcTrack[iv][ladder*fNstrips_ladder+k] << endl;    fMipCor[0][8]=135.55*yfactor;
2370      fMipCor[0][9]=138.00*xfactor;
2371           DataDSP[DSPlength]=( ((UShort_t)k) | 0x1000);    fMipCor[0][10]=154.95*yfactor;
2372           DSPlength++;      fMipCor[0][11]=158.44*xfactor;
2373           ntrastot++;    
2374                  
2375      fMipCor[1][0]=136.07*yfactor;
2376           real=modff(AdcTrack[iv][ladder*fNstrips_ladder+k],&inte);    fMipCor[1][1]=135.59*xfactor;
2377           if (real > 0.5) inte=inte+1;    fMipCor[1][2]=142.69*yfactor;
2378           DataDSP[DSPlength]=( ((UShort_t)inte) & 0x0FFF);    fMipCor[1][3]=138.19*xfactor;
2379           DSPlength++;    fMipCor[1][4]=137.35*yfactor;
2380           ntrastot++;    fMipCor[1][5]=140.23*xfactor;
2381      fMipCor[1][6]=153.15*yfactor;
2382         }    fMipCor[1][7]=151.42*xfactor;
2383         else {    fMipCor[1][8]=129.76*yfactor;
2384         //  std:: cout << "ADC_TOT " << AdcTrack[iv][ladder*fNstrips_ladder+k] << endl;    fMipCor[1][9]=140.63*xfactor;
2385           real=modff(AdcTrack[iv][ladder*fNstrips_ladder+k],&inte);    fMipCor[1][10]=157.87*yfactor;
2386           if (real > 0.5) inte=inte+1;    fMipCor[1][11]=153.64*xfactor;
2387           DataDSP[DSPlength]=(  ((UShort_t)inte) & 0x0FFF);  
2388           DSPlength++;    fMipCor[2][0]=134.98*yfactor;
2389           ntrastot++;          fMipCor[2][1]=143.95*xfactor;
2390         };    fMipCor[2][2]=140.23*yfactor;
2391         trasmesso=1;    fMipCor[2][3]=138.88*xfactor;
2392         oldval=newval;    fMipCor[2][4]=137.95*yfactor;
2393         kt=k;    fMipCor[2][5]=134.87*xfactor;
2394      fMipCor[2][6]=157.56*yfactor;
2395        }      fMipCor[2][7]=157.31*xfactor;
2396        else trasmesso=0;    fMipCor[2][8]=141.37*yfactor;
2397        // end zop    fMipCor[2][9]=143.39*xfactor;
2398            fMipCor[2][10]=156.15*yfactor;
2399        k++;          fMipCor[2][11]=158.79*xfactor;
2400        };  // end cycle inside ladder  
2401  // write here the end ladder bytes  /*
2402  //            std:: cout << "FINE LADDER " << ladder+1 << endl;    for (Int_t j=0; j<fNviews;j++) {
2403        for (Int_t i=0; i<fNstrips_view;i++) {
2404        DataDSP[DSPlength]=( ((UShort_t)(ladder+1))  | 0x1800);      fMipCor[j][i]=1.;
2405        DSPlength++;      };
2406        ntrastot++;    };    
2407        trasmesso=0;  
2408        
2409      };  //end cycle inside dsp  */  
2410  //  std:: cout << "FINE DSP " << iv+1 << endl;  };
2411  // here put DSP header  
2412      DataDSP[0]=(0x1CA0 | ((UShort_t)(iv+1)) );  void Digitizer::CompressTrackData(Float_t AdcTrack[fNviews][fNstrips_view]) {
2413      UShort_t Nword=(DSPlength*13)/16;  // copy of the corresponding compression fortran routine + new digitization
2414      if( ((DSPlength*13)%16)!=0) Nword++;  // std:: cout << "Entering CompressTrackData " << endl;
2415      DataDSP[1]=(0x1400 | ( Nword >> 10));  Int_t oldval=0;
2416      DataDSP[2]=(0x1400 | ( Nword & 0x03FF) );  Int_t newval=0;
2417      DataDSP[3]=(0x1400 | (( (UShort_t)(fCounter >> 10) ) & 0x03FF) );  Int_t trasmesso=0;
2418      DataDSP[4]=(0x1400 | (( (UShort_t)(fCounter) )  & 0x03FF) );  Int_t ntrastot=0;
2419      DataDSP[5]=(0x1400 | ( (UShort_t)(fNclst << 7) ) | ( (UShort_t)(fCutzop << 4) )  Float_t real;
2420       | ( (UShort_t)fCutzop  ) );  Float_t inte;
2421      DataDSP[6]=0x1400;  Int_t cercacluster=0;
2422      DataDSP[7]=0x1400;  Int_t kt=0;
2423      DataDSP[8]=0x1400;  static const int DSPbufferSize = 4000; // 13 bit buffer to be rearranged in 16 bit Track buffer
2424      DataDSP[9]=0x1400;  UShort_t DataDSP[DSPbufferSize];  // 13 bit  buffer to be rearranged in 16 bit Track buffer
2425      DataDSP[10]=0x1400;  UShort_t DSPlength;  // 13 bit buffer to be rearranged in 16 bit Track buffer
2426      DataDSP[11]=0x1400;  
2427      DataDSP[12]=0x1400;  memset(fDataTrack,0,sizeof(UShort_t)*fTRACKbuffer); // probably not necessary becouse already done ?
2428      DataDSP[13]=0x1400;  fTracklength=0;
2429      DataDSP[14]=(0x1400 | (CheckSum & 0x00FF) );  
2430      DataDSP[15]=0x1C00;    for (Int_t iv=0; iv<fNviews;iv++) {
2431  // end DSP header        memset(DataDSP,0,sizeof(UShort_t)*DSPbufferSize);
2432      DSPlength=16; // skip the header, to be written later
2433      UShort_t CheckSum=0;
2434  // write 13 bit DataDSP bufer inside 16 bit fDataTrack buffer  // write dsp header on buffer
2435      Int_t Bit16free=16;  
2436      UShort_t Dato;  //    fDataTrack[fTracklength]=0xE805;
2437      for (Int_t NDSP=0; NDSP<DSPlength;NDSP++) {  //    fTracklength++;
2438        Int_t Bit13ToWrite=13;  
2439        while(Bit13ToWrite>0) {  //    fDataTrack[fTracklength]=0x01A9;
2440          if(Bit13ToWrite<=Bit16free) {  //    fTracklength++;
2441            Dato=((DataDSP[NDSP]&(0xFFFF >> (16-Bit13ToWrite)))<<(Bit16free-Bit13ToWrite));  
2442            fDataTrack[fTracklength]=fDataTrack[fTracklength] | Dato ;  // end dsp header
2443            Bit16free=Bit16free-Bit13ToWrite;  
2444            Bit13ToWrite=0;     //
2445            if(Bit16free==0) {     // INIZIO VISTA IV - TAKE PROPER ACTION
2446              if(NDSP>15) CheckSum=CheckSum^fDataTrack[fTracklength];     //
2447              fTracklength++;  
2448              Bit16free=16;  
2449            };            
2450          }      for (Int_t ladder=0; ladder<fNladder;ladder++) {
2451          else if(Bit13ToWrite>Bit16free) {        Int_t k=0;
2452            Dato=( (DataDSP[NDSP]&(0xFFFF >> (16-Bit13ToWrite) ) ) >> (Bit13ToWrite-Bit16free) );        while (k<fNstrips_ladder) {
2453            fDataTrack[fTracklength]=fDataTrack[fTracklength] | Dato ;          // compress write in buffer the current LADDER
2454            if(NDSP>15) CheckSum=CheckSum^fDataTrack[fTracklength];          if ( k == 0)  {
2455            fTracklength++;            real=modff(AdcTrack[iv][ladder*fNstrips_ladder+k],&inte);
2456            Bit13ToWrite=Bit13ToWrite-Bit16free;            if (real > 0.5) inte=inte+1;
2457            Bit16free=16;              newval=(Int_t)inte -(Int_t)fPedeTrack[iv][ladder*fNstrips_ladder+k];
2458          };            // first strip of ladder is transmitted
2459                      // DC_TOT first " << AdcTrack[iv][ladder*fNstrips_ladder+k] << endl;
2460        }; // end cycle while(Bit13ToWrite>0)            DataDSP[DSPlength]=( ((UShort_t)inte) & 0x0FFF);
2461                        DSPlength++;  
2462      }; // end cycle DataDSP            ntrastot++;
2463      if(Bit16free!=16) { fTracklength++; CheckSum=CheckSum^fDataTrack[fTracklength]; };            trasmesso=1;
2464      CheckSum=(CheckSum >> 8)^(CheckSum&0x00FF);            oldval=newval;
2465      fDataTrack[fTracklength-Nword+11]=(0x0280 | (CheckSum >> 3));            kt=k;
2466      fDataTrack[fTracklength-Nword+12]=(0x1C00 | (CheckSum << 13) );            k++;
2467              continue;
2468  // end write 13 bit DataDSP bufer inside 16 bit fDataTrack buffer          };
2469            real=modff(AdcTrack[iv][ladder*fNstrips_ladder+k],&inte);
2470  //write trailer on buffer          if (real > 0.5) inte=inte+1;
2471      UShort_t ReLength=(UShort_t)((Nword+13)*2+3);          newval=(Int_t)inte -(Int_t)(fPedeTrack[iv][ladder*fNstrips_ladder+k]);
2472      UShort_t OveCheckCode=0x0000;          cercacluster=1; // ?????????
2473            if (cercacluster==1) {
2474      fDataTrack[fTracklength]=0x0000;          
2475      fTracklength++;   // controlla l'ordine di tutti queste strip ladder e DSP !!!!!!!      
2476                Int_t diff=0;
2477      fDataTrack[fTracklength]=(ReLength >> 8);  
2478      fTracklength++;            
2479                switch ((iv+1)%2) {
2480      fDataTrack[fTracklength]=( (ReLength << 8) | (OveCheckCode & 0x00FF) );            case 0: diff=newval-oldval;
2481      fTracklength++;              break;
2482  // end trailer            case 1: diff=oldval-newval;    
2483  //    std:: cout  << "DSPlength  " <<DSPlength << endl;            break;
2484  //    std:: cout << "Nword " << Nword  << endl;            };
2485  //    std:: cout <<  "ReLength " << ReLength << endl;  
2486    };                if (diff>fCutclu*(Int_t)fSigmaTrack[iv][ladder*fNstrips_ladder+k]) {
2487  //    std:: cout << "ntrastot " << ntrastot << endl;                  Int_t clval=newval;
2488                Int_t klp=k;        // go on to search for maximum
2489  };              klp++;
2490    
2491                while(klp<fNstrips_ladder) {
2492  Float_t Digitizer::SaturationTrack(Float_t ADC) {                real=modff(AdcTrack[iv][ladder*fNstrips_ladder+klp],&inte);
2493    Float_t SatFact=1.;                if (real > 0.5) inte=inte+1;
2494    if(ADC<70.) { SatFact=80./ADC; };                Int_t clvalp=(Int_t)inte -(Int_t)fPedeTrack[iv][ladder*fNstrips_ladder+klp];
2495    if(ADC>3000.) { SatFact=3000./ADC; };                if((iv+1)%2==0) {
2496    return SatFact;  
2497  };                  if(clvalp>clval) {
2498                       clval=clvalp;
2499                       k=klp;}
2500                    else break; // max of cluster found
2501    
2502                  } else {  
2503    
2504                    if(clvalp<clval) {
2505                       clval=clvalp;
2506                       k=klp;}
2507                    else break; // max of cluster found
2508    
2509                  };
2510                  
2511                  klp++;
2512                };
2513    
2514                Int_t kl1=k-fNclst; // max of cluster (or end of ladder ?)
2515                trasmesso=0;
2516                if(kl1<0)  kl1=0;
2517    
2518                if(kt>=kl1) kl1=kt+1;
2519                if( (kt+1)==kl1 ) trasmesso=1;
2520    
2521    
2522                
2523                Int_t kl2=k+fNclst;
2524                if(kl2>=fNstrips_ladder) kl2=fNstrips_ladder-1;
2525    
2526                for(Int_t klt=kl1 ; klt<=kl2 ; klt++) {
2527                  if(trasmesso==0) {
2528                  //  std:: cout << "STRIP " << klt << endl;
2529                  //  std:: cout << "ADC_TOT " <<AdcTrack[iv][ladder*fNstrips_ladder+klt] << endl;
2530    
2531                    DataDSP[DSPlength]=( ((UShort_t)klt) | 0x1000);
2532                    DSPlength++;  
2533                    ntrastot++;
2534                
2535    
2536                    real=modff(AdcTrack[iv][ladder*fNstrips_ladder+klt],&inte);
2537                    if (real > 0.5) inte=inte+1;
2538                    DataDSP[DSPlength]=( ((UShort_t)inte) & 0x0FFF);
2539                    DSPlength++;
2540                    ntrastot++;
2541                
2542                   }
2543                   else {
2544                   //   std:: cout << "ADC_TOT " <<AdcTrack[iv][ladder*fNstrips_ladder+klt] << endl;
2545                    real=modff(AdcTrack[iv][ladder*fNstrips_ladder+klt],&inte);
2546                    if (real > 0.5) inte=inte+1;
2547                    DataDSP[DSPlength]=( ((UShort_t)inte) & 0x0FFF);
2548                    DSPlength++;              
2549                    ntrastot++;
2550                    };
2551                    trasmesso=1;                        
2552                };  // end trasmission
2553                kt=kl2;
2554                k=kl2;
2555                real=modff(AdcTrack[iv][ladder*fNstrips_ladder+kt],&inte);
2556                if (real > 0.5) inte=inte+1;
2557                oldval=(Int_t)inte -(Int_t)fPedeTrack[iv][ladder*fNstrips_ladder+kt];
2558                k++;
2559                continue;
2560    
2561    
2562              }; // end cercacluster
2563            }; // end cercacluster
2564          
2565    // start ZOP check for strips no
2566          
2567          if(abs(newval-oldval)>=fCutzop*(Int_t)fSigmaTrack[iv][ladder*fNstrips_ladder+k]) {
2568    
2569           if(trasmesso==0) {
2570           // std:: cout << "STRIP " << k << endl;
2571           // std:: cout << "ADC_TOT " << AdcTrack[iv][ladder*fNstrips_ladder+k] << endl;
2572    
2573             DataDSP[DSPlength]=( ((UShort_t)k) | 0x1000);
2574             DSPlength++;  
2575             ntrastot++;
2576                
2577    
2578             real=modff(AdcTrack[iv][ladder*fNstrips_ladder+k],&inte);
2579             if (real > 0.5) inte=inte+1;
2580             DataDSP[DSPlength]=( ((UShort_t)inte) & 0x0FFF);
2581             DSPlength++;
2582             ntrastot++;
2583    
2584           }
2585           else {
2586           //  std:: cout << "ADC_TOT " << AdcTrack[iv][ladder*fNstrips_ladder+k] << endl;
2587             real=modff(AdcTrack[iv][ladder*fNstrips_ladder+k],&inte);
2588             if (real > 0.5) inte=inte+1;
2589             DataDSP[DSPlength]=(  ((UShort_t)inte) & 0x0FFF);
2590             DSPlength++;
2591             ntrastot++;      
2592           };
2593           trasmesso=1;
2594           oldval=newval;
2595           kt=k;
2596    
2597          }  
2598          else trasmesso=0;
2599          // end zop
2600          
2601          k++;      
2602          };  // end cycle inside ladder
2603    // write here the end ladder bytes
2604    //            std:: cout << "FINE LADDER " << ladder+1 << endl;
2605    
2606          DataDSP[DSPlength]=( ((UShort_t)(ladder+1))  | 0x1800);
2607          DSPlength++;
2608          ntrastot++;
2609          trasmesso=0;
2610    
2611        };  //end cycle inside dsp
2612    //  std:: cout << "FINE DSP " << iv+1 << endl;
2613    // here put DSP header
2614        DataDSP[0]=(0x1CA0 | ((UShort_t)(iv+1)) );
2615        UShort_t Nword=(DSPlength*13)/16;
2616        if( ((DSPlength*13)%16)!=0) Nword++;
2617        DataDSP[1]=(0x1400 | ( Nword >> 10));
2618        DataDSP[2]=(0x1400 | ( Nword & 0x03FF) );
2619        DataDSP[3]=(0x1400 | (( (UShort_t)(fCounter >> 10) ) & 0x03FF) );
2620        DataDSP[4]=(0x1400 | (( (UShort_t)(fCounter) )  & 0x03FF) );
2621        DataDSP[5]=(0x1400 | ( (UShort_t)(fNclst << 7) ) | ( (UShort_t)(fCutzop << 4) )
2622         | ( (UShort_t)fCutzop  ) );
2623        DataDSP[6]=0x1400;
2624        DataDSP[7]=0x1400;
2625        DataDSP[8]=0x1400;
2626        DataDSP[9]=0x1400;
2627        DataDSP[10]=0x1400;
2628        DataDSP[11]=0x1400;
2629        DataDSP[12]=0x1400;
2630        DataDSP[13]=0x1400;
2631        DataDSP[14]=(0x1400 | (CheckSum & 0x00FF) );
2632        DataDSP[15]=0x1C00;
2633    // end DSP header    
2634    
2635    
2636    // write 13 bit DataDSP bufer inside 16 bit fDataTrack buffer
2637        Int_t Bit16free=16;
2638        UShort_t Dato;
2639        for (Int_t NDSP=0; NDSP<DSPlength;NDSP++) {
2640          Int_t Bit13ToWrite=13;
2641          while(Bit13ToWrite>0) {
2642            if(Bit13ToWrite<=Bit16free) {
2643              Dato=((DataDSP[NDSP]&(0xFFFF >> (16-Bit13ToWrite)))<<(Bit16free-Bit13ToWrite));
2644              fDataTrack[fTracklength]=fDataTrack[fTracklength] | Dato ;
2645              Bit16free=Bit16free-Bit13ToWrite;
2646              Bit13ToWrite=0;
2647              if(Bit16free==0) {
2648                if(NDSP>15) CheckSum=CheckSum^fDataTrack[fTracklength];
2649                fTracklength++;
2650                Bit16free=16;
2651              };          
2652            }
2653            else if(Bit13ToWrite>Bit16free) {
2654              Dato=( (DataDSP[NDSP]&(0xFFFF >> (16-Bit13ToWrite) ) ) >> (Bit13ToWrite-Bit16free) );
2655              fDataTrack[fTracklength]=fDataTrack[fTracklength] | Dato ;
2656              if(NDSP>15) CheckSum=CheckSum^fDataTrack[fTracklength];
2657              fTracklength++;
2658              Bit13ToWrite=Bit13ToWrite-Bit16free;
2659              Bit16free=16;  
2660            };
2661            
2662          }; // end cycle while(Bit13ToWrite>0)
2663              
2664        }; // end cycle DataDSP
2665        if(Bit16free!=16) { fTracklength++; CheckSum=CheckSum^fDataTrack[fTracklength]; };
2666        CheckSum=(CheckSum >> 8)^(CheckSum&0x00FF);
2667        fDataTrack[fTracklength-Nword+11]=(0x0280 | (CheckSum >> 3));
2668        fDataTrack[fTracklength-Nword+12]=(0x1C00 | (CheckSum << 13) );
2669    
2670    // end write 13 bit DataDSP bufer inside 16 bit fDataTrack buffer
2671    
2672    //write trailer on buffer
2673        UShort_t ReLength=(UShort_t)((Nword+13)*2+3);
2674        UShort_t OveCheckCode=0x0000;
2675    
2676        fDataTrack[fTracklength]=0x0000;
2677        fTracklength++;
2678      
2679        fDataTrack[fTracklength]=(ReLength >> 8);
2680        fTracklength++;
2681      
2682        fDataTrack[fTracklength]=( (ReLength << 8) | (OveCheckCode & 0x00FF) );
2683        fTracklength++;  
2684    // end trailer
2685    //    std:: cout  << "DSPlength  " <<DSPlength << endl;
2686    //    std:: cout << "Nword " << Nword  << endl;
2687    //    std:: cout <<  "ReLength " << ReLength << endl;
2688      };    
2689    //    std:: cout << "ntrastot " << ntrastot << endl;    
2690    
2691    };
2692    
2693    
2694    Float_t Digitizer::SaturationTrack(Float_t ADC) {
2695      Float_t SatFact=1.;
2696      if(ADC<70.) { SatFact=80./ADC; };
2697      if(ADC>3000.) { SatFact=3000./ADC; };
2698      return SatFact;
2699    };
2700    
2701    
2702    
2703    
2704    
2705    

Legend:
Removed from v.1.2  
changed lines
  Added in v.1.4

  ViewVC Help
Powered by ViewVC 1.1.23