/[PAMELA software]/chewbacca/YodaProfiler/src/PamelaDBOperations.cpp
ViewVC logotype

Annotation of /chewbacca/YodaProfiler/src/PamelaDBOperations.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1.28 - (hide annotations) (download)
Mon Dec 14 13:20:37 2009 UTC (15 years ago) by mocchiut
Branch: MAIN
Changes since 1.27: +2 -1 lines
Error -29 bug fixed

1 mocchiut 1.1 //
2     #include <iomanip>
3     #include <sstream>
4     //
5     #include <iostream>
6     #include <string>
7     #include <fstream>
8     #include <list>
9     #include <errno.h>
10     //
11     #include <TFile.h>
12     #include <TSystem.h>
13     #include <TSQLResult.h>
14     #include <TSQLRow.h>
15     #include <TTree.h>
16     #include <TGraph.h>
17     #include <TTimeStamp.h>
18     #include <TF1.h>
19     //
20     #include <EventHeader.h>
21     #include <PscuHeader.h>
22     #include <mcmd/McmdEvent.h>
23     #include <mcmd/McmdRecord.h>
24     #include <RunHeaderEvent.h>
25     #include <RunTrailerEvent.h>
26     #include <CalibCalPedEvent.h>
27     #include <CalibCalPulse1Event.h>
28     #include <CalibCalPulse2Event.h>
29     #include <CalibS4Event.h>
30     #include <CalibTrk1Event.h>
31     #include <CalibTrk2Event.h>
32     #include <varDump/VarDumpEvent.h>
33     #include <varDump/VarDumpRecord.h>
34     #include <physics/S4/S4Event.h>
35     //
36     #include <sgp4.h>
37    
38     #include <PamelaDBOperations.h>
39     //
40     using namespace std;
41     using namespace pamela;
42    
43     // Some function to work with cTle stuff.
44     bool compTLE(cTle* tle1, cTle *tle2);
45     float getTleJulian(cTle *);
46     string getTleDatetime(cTle*);
47    
48     /**
49     * Constructor.
50     * @param host hostname for the SQL connection.
51     * @param user username for the SQL connection.
52     * @param password password for the SQL connection.
53     * @param filerawname The path and name to the raw file.
54     * @param filerootname The path and name of the raw file.
55     * @param boot file BOOT number.
56     * @param obt0 file obt0.
57     * @param tsync file timesync.
58     * @param debug debug flag.
59     * @param tlefilename ascii file with TLE 3 line elements.
60     */
61 mocchiut 1.5 PamelaDBOperations::PamelaDBOperations(TString host, TString user, TString password, TString filerawname, TString filerootname, UInt_t boot, UInt_t tsync, UInt_t obt0, Bool_t debug, TString tlefilename, UInt_t dwinput, Bool_t staticp, Bool_t gpamela, Bool_t keepenv){
62 mocchiut 1.1 //
63 mocchiut 1.21 RELAXED = false;
64 mocchiut 1.1 chewbacca = false;
65     chminentry = 0;
66     chID = 0;
67     if ( filerootname.IsDigit() ){
68     if ( debug ) printf(" => using database to process the file \n");
69     chewbacca = true;
70     chID = (UInt_t)filerootname.Atoll();
71     //
72     // are these really necessary?
73     //
74     staticp = false;
75     INSERT_RAW = false;
76     dwinput = 1;
77     //
78     };
79     //
80 mocchiut 1.5 KEEPENV = false;
81     if ( keepenv ) KEEPENV=true;
82 mocchiut 1.1 STATIC=false;
83     if ( staticp ) STATIC=true;
84     //
85     SetConnection(host,user,password);
86     //
87     SetDebugFlag(debug);
88     //
89     glrun = new GL_RUN();
90     //
91     if ( !chewbacca ){
92     if ( !boot ) SetNOBOOT(false);
93     SetTsync(tsync,gpamela);
94     SetBOOTnumber(boot,gpamela);
95     SetObt0(obt0);
96     };
97     //
98     SetTLEPath(tlefilename);
99     //
100     //
101     if ( !chewbacca ) INSERT_RAW =!filerawname.IsNull();
102     if (INSERT_RAW) SetRawName(filerawname);
103     //
104     INSERT_ROOT = !filerootname.IsNull();
105 mocchiut 1.13 if ( INSERT_ROOT ) this->SetRootName(filerootname);
106 mocchiut 1.1 this->SetOrbitNo(dwinput);
107     //
108     this->SetID_RAW(0);
109     this->SetID_ROOT(0);
110    
111     VALIDATE = false;
112    
113     //
114     };
115    
116     /**
117     * Destructor
118     */
119     void PamelaDBOperations::Close(){
120     if( conn && conn->IsConnected() ) conn->Close();
121     delete clean_time;
122     delete glrun;
123     delete this;
124     };
125    
126     //
127     // SETTERS
128     //
129    
130     void PamelaDBOperations::OpenL0File(TString filerootname){
131     if( INSERT_ROOT ){
132     if ( chewbacca ){
133     //
134     // retrieve from the ROOT_TABLE the chewbacca path and filename
135     //
136     stringstream qu;
137     TSQLResult *result = 0;
138     TSQLResult *result2 = 0;
139 mocchiut 1.18 TSQLResult *result3 = 0;
140 mocchiut 1.1 TSQLRow *row = 0;
141     TSQLRow *row2 = 0;
142 mocchiut 1.18 TSQLRow *row3 = 0;
143 mocchiut 1.1 TString chpath;
144     TString chfile;
145     UInt_t ridn = 0;
146     qu.str("");
147 mocchiut 1.21 qu << "SELECT ROOT_ID_N,PKT_NUMBER_INIT,PKT_NUMBER_FINAL,PKT_OBT_INIT,PKT_OBT_FINAL,INSERTED_BY,REAL_TIME_INIT from ROOT_TABLE_MERGING where ID_N=" << chID << ";";
148 mocchiut 1.1 if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
149     result = conn->Query(qu.str().c_str());
150     if ( result ){
151     row = result->Next();
152     if ( row ){
153     ridn = (UInt_t)atoll(row->GetField(0));
154     chpktmin = (UInt_t)atoll(row->GetField(1));
155     chpktmax = (UInt_t)atoll(row->GetField(2));
156     chobtmin = (UInt_t)atoll(row->GetField(3));
157     chobtmax = (UInt_t)atoll(row->GetField(4));
158 mocchiut 1.5 chiby = (TString)(row->GetField(5));
159 mocchiut 1.21 chrtinit = (UInt_t)atoll(row->GetField(6));
160 mocchiut 1.1 } else {
161     throw -84;
162     };
163     } else {
164     throw -84;
165     };
166     delete result;
167     qu.str("");
168 mocchiut 1.18 qu << "SELECT FOLDER_NAME,FILE_NAME,OBT_TIME_SYNC,LAST_TIME_SYNC_INFO,TIME_OFFSET,BOOT_NUMBER,PKT_NUMBER_INIT,PKT_NUMBER_FINAL,PKT_OBT_INIT,PKT_OBT_FINAL,REAL_TIME_INIT from ROOT_TABLE where ID_N=" << ridn << ";";
169 mocchiut 1.1 if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
170     result2 = conn->Query(qu.str().c_str());
171     if ( result2 ){
172     row2 = result2->Next();
173     if ( row2 ){
174 mocchiut 1.5 if ( KEEPENV ){
175     chpath = (TString)(row2->GetField(0))+'/';
176     } else {
177     chpath = (TString)gSystem->ExpandPathName(row2->GetField(0))+'/';
178     };
179 mocchiut 1.1 chfile = (TString)(row2->GetField(1));
180     chobtts = (UInt_t)atoll(row2->GetField(2));
181     chlastts = (UInt_t)atoll(row2->GetField(3));
182     chresursts = (UInt_t)atoll(row2->GetField(4));
183     chboot = (UInt_t)atoll(row2->GetField(5));
184     //
185 mocchiut 1.18 if ( !chboot ){
186     qu.str("");
187 mocchiut 1.21 // qu << "SELECT BOOT_NUMBER from ROOT_TABLE where BOOT_NUMBER!=0 AND ABS(LAST_TIME_SYNC_INFO-"<< chlastts <<")<10000 AND ABS(REAL_TIME_INIT-"<< row2->GetField(10) <<")<7200 group by BOOT_NUMBER order by BOOT_NUMBER asc;";
188 mocchiut 1.28 // qu << "SELECT BOOT_NUMBER from ROOT_TABLE where BOOT_NUMBER!=0 AND ABS(LAST_TIME_SYNC_INFO-"<< chlastts <<")<40000 AND ABS(REAL_TIME_INIT-"<< row2->GetField(10) <<")<40000 group by BOOT_NUMBER order by BOOT_NUMBER asc;"; // relax conditions... 090112 [8RED: error -29]
189     qu << "SELECT BOOT_NUMBER from ROOT_TABLE where BOOT_NUMBER!=0 AND ABS(LAST_TIME_SYNC_INFO-"<< chlastts <<")<50000 AND ABS(REAL_TIME_INIT-"<< row2->GetField(10) <<")<50000 group by BOOT_NUMBER order by BOOT_NUMBER asc;"; // even more relaxed conditions... 091214 [9REDtest3: error -29]
190 mocchiut 1.18 if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
191     result3 = conn->Query(qu.str().c_str());
192     if ( result3 ){
193     row3 = result3->Next();
194 mocchiut 1.19 if ( row3 && result3->GetRowCount() == 1 ){
195 mocchiut 1.18 chboot = (UInt_t)atoll(row3->GetField(0));
196     if ( debug ) printf(" Found boot_number = %u \n",chboot);
197     } else {
198     if ( debug ) printf(" AGH CANNOT DETERMINE THE BOOT NUMBER... \n");
199 mocchiut 1.19 throw -29;
200 mocchiut 1.18 };
201     };
202     };
203     //
204 mocchiut 1.1 chpktinit = (UInt_t)atoll(row2->GetField(6));
205     chpktfinal = (UInt_t)atoll(row2->GetField(7));
206     chobtinit = (UInt_t)atoll(row2->GetField(8));
207     chobtfinal = (UInt_t)atoll(row2->GetField(9));
208     //
209     } else {
210     throw -85;
211     };
212     } else {
213     throw -85;
214     };
215     filerootname = chpath + chfile;// + ".root";
216     };
217     this->SetRootName(filerootname);
218     };
219 mocchiut 1.13 if ( debug ) printf(" Filename is %s \n",filerootname.Data());
220     file = TFile::Open(this->GetRootName().Data());
221     // } else {
222     // this->SetRootName("");
223     // this->SetRootName(filerootname);
224     // };
225 mocchiut 1.1 }
226    
227     //
228     // must be out of the constructor in order to FORCE the validation of the latest runs in case you run the validation together with the latest file
229     //
230     void PamelaDBOperations::CheckValidate(Long64_t olderthan){
231     clean_time = new TDatime();
232     //
233     if(olderthan >= 0){
234     VALIDATE = true;
235     UInt_t timelim = 0;
236     timelim = (UInt_t)clean_time->Convert(true) - olderthan;
237     clean_time->Set(timelim,false);
238     };
239     };
240    
241     /**
242     * Open the DB connection
243     * @param host hostname for the SQL connection.
244     * @param user username for the SQL connection.
245     * @param password password for the SQL connection.
246     */
247     void PamelaDBOperations::SetConnection(TString host, TString user, TString password){
248     if ( IsDebug() ) printf(" Connecting using host = %s user = %s password = %s \n",host.Data(),user.Data(),password.Data());
249     conn = TSQLServer::Connect(host.Data(),user.Data(),password.Data());
250     };
251    
252     /**
253     * Store the ID of the ROOT file.
254     * @param idr ID of the ROOT file
255     */
256     void PamelaDBOperations::SetID_ROOT(UInt_t idr){
257     idroot=idr;
258     };
259    
260     /**
261     * Store the ID of the RAW file.
262     * @param idr ID of the RAW file
263     */
264     void PamelaDBOperations::SetID_RAW(UInt_t idr){
265     id=idr;
266     };
267    
268     /**
269     * Set the debug flag
270     *
271     */
272     void PamelaDBOperations::SetDebugFlag(Bool_t dbg){
273     debug = dbg;
274     };
275    
276     /**
277     * Set the autoboot flag
278     *
279     */
280     void PamelaDBOperations::SetAutoBoot(Bool_t dbg){
281     AUTOBOOT = dbg;
282     };
283    
284     /**
285     * Set the pedantic flag
286     *
287     */
288     void PamelaDBOperations::SetPedantic(Bool_t dbg){
289     PEDANTIC = dbg;
290     };
291    
292     /**
293     * Set the nofrag flag
294     *
295     */
296     void PamelaDBOperations::SetNoFrag(Bool_t nf){
297     NOFRAG = nf;
298     };
299    
300     /**
301     * Store the BOOT number of the RAW file.
302     * @param boot BOOT number of the RAW file
303     */
304     void PamelaDBOperations::SetBOOTnumber(UInt_t boot){
305     this->SetBOOTnumber(boot,false);
306     };
307    
308     /**
309     * Store the BOOT number of the RAW file.
310     * @param boot BOOT number of the RAW file
311     */
312     void PamelaDBOperations::SetBOOTnumber(UInt_t boot, Bool_t gpamela){
313     BOOTNO=boot;
314     if ( gpamela ){
315     stringstream oss;
316     TSQLResult *result = 0;
317     TSQLRow *row = 0;
318     if ( !boot ){
319     //
320     BOOTNO = 1;
321     //
322     // look in the DB for the last timesync and the last run
323     //
324     oss.str("");
325     oss << "SELECT BOOT_NUMBER FROM GL_RUN order by RUNHEADER_TIME desc limit 1;";
326     result = conn->Query(oss.str().c_str());
327     if ( result ){
328     row = result->Next();
329     if ( row ){
330     BOOTNO = (UInt_t)atoll(row->GetField(0)) + 1;
331     };
332     };
333     };
334     };
335     };
336    
337     /**
338     * Store the time sync of the RAW file.
339     * @param boot time sync
340     */
341     void PamelaDBOperations::SetTsync(UInt_t ts){
342     this->SetTsync(ts,false);
343     };
344    
345     /**
346     * Store the time sync of the RAW file.
347     * @param boot time sync
348     */
349     void PamelaDBOperations::SetTsync(UInt_t ts, Bool_t gpamela){
350     //
351     // if not gpamela or given tsync file set ts
352     //
353     tsync=ts;
354     if ( gpamela ){
355     stringstream oss;
356     TSQLResult *result = 0;
357     TSQLRow *row = 0;
358     TSQLResult *result2 = 0;
359     TSQLRow *row2 = 0;
360     if ( !ts ){
361     //
362     tsync = 1;
363     //
364     // look in the DB for the last timesync and the last run
365     //
366     oss.str("");
367     oss << "SELECT TIMESYNC FROM GL_TIMESYNC order by TIMESYNC desc limit 1;";
368     result = conn->Query(oss.str().c_str());
369     if ( result ){
370     row = result->Next();
371     if ( row ){
372     tsync = (UInt_t)atoll(row->GetField(0)) + 1;
373     oss.str("");
374     oss << "SELECT (RUNTRAILER_TIME-RUNHEADER_TIME) FROM GL_RUN order by RUNHEADER_TIME desc limit 1;";
375     result2 = conn->Query(oss.str().c_str());
376     if ( result2 ){
377     row2 = result2->Next();
378     if ( row2 ){
379     tsync += (UInt_t)atoll(row2->GetField(0));
380     };
381     }
382     };
383     };
384     };
385     };
386     };
387    
388     /**
389     * Store the time sync of the RAW file.
390     * @param boot time sync
391     */
392     void PamelaDBOperations::SetObt0(UInt_t ts){
393     obt0=ts;
394     };
395    
396     /**
397     * Store the RAW filename.
398     * @param str the RAW filename.
399     */
400     void PamelaDBOperations::SetRawName(TString str){
401     filerawname=str;
402     };
403    
404     /**
405     * Store the ROOT filename.
406     * @param str the ROOT filename.
407     */
408     void PamelaDBOperations::SetRootName(TString str){
409     filerootname=str;
410     };
411    
412     /**
413     * Store the downlink orbit number from filename.
414     */
415     void PamelaDBOperations::SetOrbitNo(UInt_t dwinput){
416     dworbit = 0;
417     //
418     if ( dwinput ){
419     dworbit = dwinput;
420     if ( IsDebug() && !chewbacca ) printf(" Downlink orbit given by hand: %i \n",dworbit);
421     return;
422     };
423     //
424 mocchiut 1.13 if ( !chewbacca ){
425     TString name = this->GetRootFile();
426     Int_t nlength = name.Length();
427     if ( nlength < 5 ){
428     if ( IsDebug() ) printf(" Agh problems determining the orbit number! name = %s \n",name.Data());
429     return;
430     };
431 pizzolot 1.24 TString dwo = "";
432 mocchiut 1.13 for (Int_t i = 0; i<5; i++){
433 mocchiut 1.1 dwo.Append(name[i],1);
434 mocchiut 1.13 };
435     if ( dwo.IsDigit() ){
436     dworbit = (UInt_t)dwo.Atoi();
437     } else {
438     dwo="";
439     for (Int_t i = 8; i<13; i++){
440     dwo.Append(name[i],1);
441     };
442     if ( dwo.IsDigit() ) dworbit = (UInt_t)dwo.Atoi();
443     };
444     if ( IsDebug() ) printf(" Downlink orbit is %i (dwo = %s) \n",dworbit,dwo.Data());
445 mocchiut 1.1 };
446     return;
447     };
448    
449    
450    
451     /**
452     * Store the NOBOOT flag.
453     * @param noboot true/false.
454     */
455     void PamelaDBOperations::SetNOBOOT(Bool_t noboot){
456     NOBOOT = noboot;
457     };
458    
459     /**
460     * Store path to the TLE file.
461     */
462     void PamelaDBOperations::SetTLEPath(TString str){
463     tlefilename = str;
464     };
465    
466     TString PamelaDBOperations::GetRawPath(){
467     if ( STATIC ){
468     return((TString)gSystem->DirName(filerawname.Data())+'/');
469     } else {
470     return((TString)gSystem->ExpandPathName("$PAM_RAW")+'/');
471     };
472     };
473    
474     TString PamelaDBOperations::GetRootPath(){
475     if ( STATIC ){
476 mocchiut 1.5 return((TString)gSystem->DirName(this->GetRootName().Data())+'/');
477     } else {
478     if ( KEEPENV ){
479     return((TString)gSystem->ExpandPathName(gSystem->DirName(filerootname.Data()))+'/');
480     } else {
481     return((TString)gSystem->ExpandPathName("$PAM_L0")+'/');
482     };
483 mocchiut 1.1 };
484     };
485    
486     /**
487     * Store the olderthan variable
488     * @param olderthan
489     */
490     // void PamelaDBOperations::SetOlderThan(Long64_t oldthan){
491     // olderthan = oldthan;
492     // };
493    
494     /**
495     * Retrieve the ID_RAW, if exists, returns NULL if does not exist.
496     */
497     Bool_t PamelaDBOperations::SetID_RAW(){
498     stringstream oss;
499     TSQLResult *result = 0;
500     TSQLRow *row = 0;
501     oss.str("");
502     if ( STATIC ){
503     oss << "SELECT ID FROM GL_RAW WHERE "
504     << " PATH = '" << this->GetRawPath().Data() << "' AND "
505     << " NAME = '" << this->GetRawFile().Data() << "' ";
506     } else {
507     oss << "SELECT ID FROM GL_RAW WHERE "
508     << " PATH = '$PAM_RAW' AND "
509     << " NAME = '" << this->GetRawFile().Data() << "' ";
510     }
511     result = conn->Query(oss.str().c_str());
512     if ( result == NULL ) throw -4;
513     row = result->Next();
514     if ( !row ) return(false);
515     id = (UInt_t)atoll(row->GetField(0));
516     delete result;
517     return(true);
518     }
519    
520     /**
521     *
522     * Set the variables which have to be stored in the GL_RUN table and that do not depend on the RUN
523     *
524     */
525     void PamelaDBOperations::SetCommonGLRUN(UInt_t absth, UInt_t abstt){
526     glrun->SetBOOTNUMBER(BOOTNO);
527     glrun->SetRUNHEADER_TIME(absth);
528     glrun->SetRUNTRAILER_TIME(abstt);
529     glrun->SetID_ROOT_L2(0);
530     glrun->SetID_ROOT_L0(idroot);
531     glrun->SetVALIDATION(0);
532     };
533    
534     /**
535 mocchiut 1.2 *
536     * Set the variables which belogns to physendrun tree
537     *
538     */
539     void PamelaDBOperations::SetPhysEndRunVariables(){
540     //
541     //
542     //
543     TTree *T = 0;
544     T = (TTree*)file->Get("PhysEndRun");
545     if ( !T || T->IsZombie() ) throw -90;
546     //
547     PhysEndRunEvent *pher= 0;
548     EventHeader *eh = 0;
549     T->SetBranchAddress("PhysEndRun", &pher);
550     T->SetBranchAddress("Header", &eh);
551     //
552     UInt_t phobt = 0;
553     UInt_t phpkt = 0;
554     //
555     glrun->SetPHYSENDRUN_MASK_S3S2S12(0);
556     glrun->SetPHYSENDRUN_MASK_S11CRC(0);
557     //
558     for (Int_t p=0; p<T->GetEntries(); p++){
559     //
560     T->GetEntry(p);
561     //
562     phobt = (UInt_t)eh->GetPscuHeader()->GetOrbitalTime();
563     phpkt = (UInt_t)eh->GetPscuHeader()->GetCounter();
564     //
565     if ( this->PKT(phpkt) >= this->PKT(glrun->GetRUNHEADER_PKT()) && this->PKT(phpkt) <= this->PKT(glrun->GetRUNTRAILER_PKT()) && this->OBT(phobt) >= this->OBT(glrun->GetRUNHEADER_OBT()) && this->OBT(phobt) <= this->OBT(glrun->GetRUNTRAILER_OBT()) ){
566     if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() || glrun->GetPHYSENDRUN_MASK_S11CRC() ){
567     if ( IsDebug() ) printf(" WARNING while looping in physendrun: found two PhysEndRun packet for the same RUN! \n");
568     if ( IsDebug() ) printf(" Actual values: %X %X New values %X %X \n ",glrun->GetPHYSENDRUN_MASK_S3S2S12(),glrun->GetPHYSENDRUN_MASK_S11CRC(),(UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S3S2S12,(UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S11CRC);
569     if ( PEDANTIC && IsDebug() ) printf(" ERROR while looping in physendrun: found two PhysEndRun packet for the same RUN!\n ");
570     if ( PEDANTIC ) throw -91;
571     } else {
572     glrun->SetPHYSENDRUN_MASK_S3S2S12((UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S3S2S12);
573     glrun->SetPHYSENDRUN_MASK_S11CRC((UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S11CRC);
574     };
575     };
576     };
577     //
578     };
579    
580     /**
581 mocchiut 1.1 * Patch, look for upper limits to avoid processing retransmitted data
582     */
583     Int_t PamelaDBOperations::SetUpperLimits(){
584     UInt_t nevent = 0;
585     UInt_t pktlast = 0;
586     UInt_t obtlast = 0;
587     Long64_t t_pktlast = 0LL;
588     // UInt_t t_obtlast = 0;
589     Long64_t t_obtlast = 0LL;
590     Long64_t upperpkt2 = 0LL;
591     Long64_t upperobt2 = 0LL;
592     UInt_t zomp = 0;
593     UInt_t jump = 50000; // was 5000
594     EventCounter *code=0;
595     //
596     Long64_t deltapkt = 5000LL;
597     Long64_t deltaobt = 50000LL;
598     //
599     pcksList packetsNames;
600     pcksList::iterator Iter;
601     getPacketsNames(packetsNames);
602     //
603     pktfirst = 0;
604     obtfirst = 0;
605     ppktfirst = 0;
606     pobtfirst = 0;
607     //
608     //
609     //
610     TTree *T = 0;
611     T = (TTree*)file->Get("Physics");
612     if ( !T || T->IsZombie() ) throw -16;
613     EventHeader *eh = 0;
614     PscuHeader *ph = 0;
615     T->SetBranchAddress("Header", &eh);
616     nevent = T->GetEntries();
617     //
618     T->GetEntry(0);
619     ph = eh->GetPscuHeader();
620    
621     if ( chewbacca ){
622     if ( IsDebug() ) printf(" FROM CHEWBACCA: upperpkt %u upperobt %u lowerpkt %u lowerobt %u \n",chpktmax,chobtmax,chpktmin,chobtmin);
623     ppktfirst = chpktmin;
624     pobtfirst = chobtts*1000;
625     } else {
626     //
627     pktfirst = ph->GetCounter();
628     obtfirst = ph->GetOrbitalTime();
629     ppktfirst = pktfirst;
630     pobtfirst = obtfirst; // to be changed AFTER time sync determination this is a profiler bug!
631     };
632     //
633     code = eh->GetCounter();
634     UInt_t en = 0;
635     // if ( !chewbacca ){
636     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
637     en = code->Get(GetPacketType(*Iter));
638     if ( !strcmp("CalibCalPed",*Iter) || !strcmp("CalibTrk1",*Iter) || !strcmp("CalibTrk2",*Iter) || !strcmp("CalibS4",*Iter) ){
639     if ( IsDebug() ) printf(" We have a calibration before the first physic packet: packet type is %s, entries: %i \n",*Iter,en);
640     //
641     TTree *TC = 0;
642     TC = (TTree*)file->Get("CalibCalPed");
643     if ( !TC || TC->IsZombie() ) throw -16;
644     EventHeader *ehc = 0;
645     PscuHeader *phc = 0;
646     TC->SetBranchAddress("Header", &ehc);
647     TC->GetEntry(0);
648     phc = ehc->GetPscuHeader();
649     pktfirst = phc->GetCounter();
650     obtfirst = phc->GetOrbitalTime();
651     //
652     };
653     };
654     //
655     T->GetEntry(nevent-1);
656     ph = eh->GetPscuHeader();
657     pktlast = ph->GetCounter();
658     obtlast = ph->GetOrbitalTime();
659     //
660     // paranoid check
661     //
662     if ( chewbacca ) {
663     //
664     // query the ROOT_TABLE to find upper and lower limits of the file and compare them to the given interval
665     //
666     if ( IsDebug() ) printf(" Is good if \n");
667     if ( IsDebug() ) printf("PKT(chpktfinal) >= PKT(chpktmax) && PKT(chpktinit) <= PKT(chpktmin) && OBT(chobtfinal) >= OBT(chobtmax) && OBT(chobtinit) <= OBT(chobtmin) \n");
668     if ( IsDebug() ) printf(" %llu >= %llu && %llu <= %llu && %llu >= %llu && %llu <= %llu \n",PKT(chpktfinal),PKT(chpktmax),PKT(chpktinit),PKT(chpktmin),OBT(chobtfinal),OBT(chobtmax),OBT(chobtinit),OBT(chobtmin));
669     if ( PKT(chpktfinal) >= PKT(chpktmax) && PKT(chpktinit) <= PKT(chpktmin) && OBT(chobtfinal) >= OBT(chobtmax) && OBT(chobtinit) <= OBT(chobtmin) ){
670     if ( IsDebug() ) printf(" OK, the file contains the chewbacca interval\n");
671     } else {
672     if ( IsDebug() ) printf(" Bah, the file seems to be the wrong one, the chewbacca interval is not contained in the file... is the DB correctly filled??\n");
673     if ( PEDANTIC ) throw -89;
674     };
675     };
676     //
677     nrtbef = 0;
678     nrtaf = 0;
679     nrtbef = 0;
680     nrtaf = 0;
681     //
682     if ( chewbacca ){
683     pktfirst = chpktmin;
684     obtfirst = chobtmin;
685     pktlast = chpktmax;
686     obtlast = chobtmax;
687     upperpkt = PKT(chpktmax);
688     upperobt = OBT(chobtmax);
689     pktlast = numeric_limits<UInt_t>::max();
690     Int_t it = 0;
691     UInt_t tjump = 50000;
692     //UInt_t tjump = 100;
693     while ( tjump > 0 ){
694 mocchiut 1.9 // pktlast = numeric_limits<UInt_t>::max();
695     pktlast = chpktmax + 1;
696 mocchiut 1.8 while ( PKT(pktlast) > PKT(chpktmax) && (Int_t)(nevent-1-it) >= 0 ){
697 mocchiut 1.1 if ( (Int_t)(nevent-1-it) >= 0 ){
698     T->GetEntry(nevent-1-it);
699     ph = eh->GetPscuHeader();
700     pktlast = ph->GetCounter();
701     } else {
702     pktlast = chpktmax + 1;
703     };
704 mocchiut 1.8 if ( (!(it%1000) || abs((int)(PKT(pktlast) - PKT(chpktmax)))<1000 ) && debug ) printf(" look for up %i %i %i nevent %u (nevent-1-it) %i \n",it,pktlast,chpktmax,nevent,(Int_t)(nevent-1-it));
705 mocchiut 1.1 it += tjump;
706     };
707     if ( tjump > 1 ) it -= 2*tjump;
708     if ( it < 0 ) it = 0;
709     //
710     if ( debug ) printf(" - look for up %i %i %i nevent %u (nevent-1-it) %i \n",it,pktlast,chpktmax,nevent,(Int_t)(nevent-1-it));
711     if ( debug ) printf(" - up , tjump was %u it was %u \n",tjump,it);
712     if ( tjump == 1 ) tjump = 0;
713     if ( tjump == 10 ) tjump = 1;
714     if ( tjump == 100 ) tjump = 10;
715     if ( tjump == 1000 ) tjump = 100;
716     if ( tjump == 5000 ) tjump = 1000;
717     if ( tjump == 50000 ) tjump = 5000;
718     //
719     };
720     Int_t tupperentry = (Int_t)nevent-1-(Int_t)it+1;//+1+1;
721     if ( tupperentry < 0 ) tupperentry = 0;
722     upperentry = tupperentry;
723     it = 0;
724     pktlast = 0;
725     tjump = 50000;
726     //tjump = 100;
727     while ( tjump > 0 ){
728 mocchiut 1.9 // pktlast = 0;
729     pktlast = chpktmin - 1;
730     if ( debug ) printf("LLlook for down %i %i %llu %llu \n",it,pktlast,PKT(pktlast),PKT(chpktmin));
731 mocchiut 1.8 while ( PKT(pktlast) < PKT(chpktmin) && it < (Int_t)nevent ){
732 mocchiut 1.1 if ( it < (Int_t)nevent ){
733     T->GetEntry(it);
734     ph = eh->GetPscuHeader();
735     pktlast = ph->GetCounter();
736     } else {
737     // pktlast = chpktmax - 1;
738     pktlast = chpktmin - 1;
739     };
740     if ( !(it%1000) && debug ) printf("look for down %i %i %i \n",it,pktlast,chpktmin);
741     it += tjump;
742     };
743     if ( tjump > 1 ) it -= 2*tjump;
744     if ( it < 0 ) it = 0;
745     //
746     if ( debug ) printf(" down , tjump was %u it was %u \n",tjump,it);
747     if ( tjump == 1 ) tjump = 0;
748     if ( tjump == 10 ) tjump = 1;
749     if ( tjump == 100 ) tjump = 10;
750     if ( tjump == 1000 ) tjump = 100;
751     if ( tjump == 5000 ) tjump = 1000;
752     if ( tjump == 50000 ) tjump = 5000;
753     //
754     };
755     Int_t tchminentry = (Int_t)it-1;//-1+1;
756     if ( tchminentry < 0 ) tchminentry = 0;
757     chminentry = tchminentry;
758     //
759     if ( debug ) printf(" Chewbacca: chminentry %i chmaxentry %i delta %i nevent %i \n",chminentry,upperentry,upperentry-chminentry,nevent);
760     //
761     //
762     //
763     TTree *rh=(TTree*)file->Get("RunHeader");
764     if ( !rh || rh->IsZombie() ) throw -17;
765     TTree *rt=(TTree*)file->Get("RunTrailer");
766     if ( !rt || rt->IsZombie() ) throw -18;
767     //
768     rh->SetBranchAddress("RunHeader", &runh);
769     rh->SetBranchAddress("Header", &ehh);
770     //
771     rt->SetBranchAddress("RunTrailer", &runt);
772     rt->SetBranchAddress("Header", &eht);
773     //
774     rhev = rh->GetEntries();
775     rtev = rt->GetEntries();
776     //
777     if ( IsDebug() ){
778     for (Int_t rr=0; rr<rh->GetEntries(); rr++){
779     rh->GetEntry(rr);
780     phh = ehh->GetPscuHeader();
781     printf(" RUNHEADER %i OBT %u PKT %u \n",rr,phh->GetOrbitalTime(),phh->GetCounter());
782     };
783     for (Int_t rr=0; rr<rt->GetEntries(); rr++){
784     rt->GetEntry(rr);
785     pht = eht->GetPscuHeader();
786     printf(" RUNTRAILER %i OBT %u PKT %u \n",rr,pht->GetOrbitalTime(),pht->GetCounter());
787     };
788     };
789     //
790     nrhev = 0;
791     nrhbef = 0;
792     nrhaf = 0;
793     for (Int_t rr=0; rr<rh->GetEntries(); rr++){
794     rh->GetEntry(rr);
795     phh = ehh->GetPscuHeader();
796     if ( debug ) printf(" RRRRRRR %llu %llu %llu %llu %llu %llu \n",PKT(phh->GetCounter()),PKT(pktfirst),upperpkt,OBT(obtfirst),OBT(phh->GetOrbitalTime()),upperobt);
797     if ( PKT(phh->GetCounter()) >= PKT(pktfirst) && PKT(phh->GetCounter()) <= upperpkt && OBT(phh->GetOrbitalTime()) >= OBT(obtfirst) && OBT(phh->GetOrbitalTime()) <= upperobt ){
798     nrhev++;
799     if ( debug ) printf(" ++++ RH %i \n",nrhev);
800     };
801     if ( !nrhev ) nrhbef++;
802     if ( (nrhev && (nrhev+1+nrhbef+1) == rr) || nrhaf ) nrhaf++;
803     };
804     nrtev = 0;
805     nrtbef = 0;
806     nrtaf = 0;
807     for (Int_t rr=0; rr<rt->GetEntries(); rr++){
808     rt->GetEntry(rr);
809     pht = eht->GetPscuHeader();
810     if ( debug ) printf(" TTTTTTT %llu %llu %llu %llu %llu %llu \n",PKT(pht->GetCounter()),PKT(pktfirst),upperpkt,OBT(obtfirst),OBT(pht->GetOrbitalTime()),upperobt);
811     if ( PKT(pht->GetCounter()) >= PKT(pktfirst) && PKT(pht->GetCounter()) <= upperpkt && OBT(pht->GetOrbitalTime()) >= OBT(obtfirst) && OBT(pht->GetOrbitalTime()) <= upperobt ){
812     nrtev++;
813     if ( debug ) printf(" ++++ RT %i \n",nrtev);
814     };
815     if ( !nrtev ) nrtbef++;
816     if ( (nrtev && (nrtev+1+nrtbef+1) == rr) || nrtaf ) nrtaf++;
817     };
818     if ( debug ) printf(" NUMBER OF RH %i RT %i IN THE INTERVAL, NUMBER OF TOTAL RH %i RT %i \n",nrhev,nrtev,rhev,rtev);
819     if ( debug ) printf(" RH before %i RH after %i -- RT before %i RT after %i \n",nrhbef,nrhaf,nrtbef,nrtaf);
820     //
821     T->GetEntry(upperentry);
822     ph = eh->GetPscuHeader();
823     pktlast = ph->GetCounter();
824     nevent = upperentry - chminentry;
825 mocchiut 1.21 if ( ((Int_t)upperentry - (Int_t)chminentry) < 0 ) nevent = 0; // nevent is UInt_t! 090112 [8RED: error -88]
826     if ( IsDebug() ) printf(" Setting nevent to %u - upperentry %i chminentry %i \n",nevent,upperentry,chminentry);
827 mocchiut 1.1 //
828     } else {
829     upperpkt = PKT(pktlast);
830     upperobt = OBT(obtlast);
831     upperentry = nevent-1;
832     };
833     //
834     if ( chewbacca && nevent < 1 ) {
835 mocchiut 1.21 if ( IsDebug() ) printf(" chewbacca and no events in the file \n");
836 mocchiut 1.2 pktfirst = chpktmin;
837     upperpkt = PKT(chpktmax);
838     pktlast = chpktmax;
839     obtfirst = chobtmin;
840     obtlast = chobtmax;
841     upperobt = OBT(chobtmax);
842 mocchiut 1.1 };
843     //
844     if ( IsDebug() ) printf(" First entries are: OBT %u pkt_num %u entry %i\n",obtfirst,pktfirst,chminentry);
845     //
846     if ( IsDebug() ) printf(" Last entries are: OBT %lld pkt_num %lld entry %i\n",upperobt,upperpkt,upperentry);
847     //
848     if ( (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) > OBT(obtfirst)) || (PKT(pktlast) > PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) ){
849 mocchiut 1.2 if ( IsDebug() ) printf(" Inconsistent PKT/OBT sequence: \n (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) > OBT(obtfirst)) %llu < %llu && %llu > %llu \n OR \n (PKT(pktlast) > PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) %llu > %llu && %llu < %llu \n",PKT(pktlast),PKT(pktfirst),OBT(obtlast),OBT(obtfirst),PKT(pktlast),PKT(pktfirst),OBT(obtlast),OBT(obtfirst));
850     if ( PEDANTIC ) throw -88;
851     return(32);
852 mocchiut 1.1 };
853     //
854     if ( !nevent ) return(64);
855     //
856     if ( nevent < 2 ) return(128);
857     if ( nevent < jump ) jump = 1;
858     // if ( nevent < jump ) jump = int(nevent/10);
859     // if ( !jump ) jump = 1;
860     //
861 pam-fi 1.25
862     if ( ((PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) || (labs(PKT(pktlast)-PKT(pktfirst))<deltapkt && labs(OBT(obtlast)-OBT(obtfirst))<deltaobt)) && nevent > deltapkt ){
863 mocchiut 1.1 //
864     if ( IsDebug() ) printf(" starting jump %i \n",jump);
865     // if ( IsDebug() ) printf(" (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) > OBT(obtfirst)) %llu < %llu && %llu > %llu \n OR \n (PKT(pktlast) > PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) %llu > %llu && %llu < %llu \n",PKT(pktlast),PKT(pktfirst),OBT(obtlast),OBT(obtfirst),PKT(pktlast),PKT(pktfirst),OBT(obtlast),OBT(obtfirst));
866     if ( IsDebug() ) printf(" labs(PKT(pktlast)-PKT(pktfirst) %lu < deltapkt %lld && labs(OBT(obtlast)-OBT(obtfirst)) %lu <deltaobt %lld && nevent %u > deltapkt %lld \n",(labs(PKT(pktlast)-PKT(pktfirst))),deltapkt, labs(OBT(obtlast)-OBT(obtfirst)),deltaobt, nevent, deltapkt);
867     if ( PEDANTIC ) throw -66;
868     // go back
869     zomp = nevent - 2;
870     //
871     while ( jump > 0 ){
872     //
873     t_pktlast = PKT(pktlast);
874     t_obtlast = OBT(obtlast);
875     //
876     for (UInt_t i = zomp; i>1; i-=jump){
877     //
878     if ( i >= 0 ) T->GetEntry(i);
879     ph = eh->GetPscuHeader();
880     upperpkt = PKT(ph->GetCounter());
881     upperobt = OBT(ph->GetOrbitalTime());
882     upperentry = i;
883     //
884     if ( (i-1) >= 0 ) T->GetEntry(i-1);
885     ph = eh->GetPscuHeader();
886     upperpkt2 = PKT(ph->GetCounter());
887     upperobt2 = OBT(ph->GetOrbitalTime());
888     //
889     if ( (t_pktlast < upperpkt && t_obtlast > upperobt) || (t_pktlast < upperpkt2 && t_obtlast > upperobt2) ){
890     if ( IsDebug() ) printf(" .-. upperpkt2 %lld upperobt2 %lld \n",upperpkt2,upperobt2);
891     if ( IsDebug() ) printf(" .-. upperpkt %lld t_pktlast %lld upperobt %lld t_obtlast %lld \n",upperpkt,t_pktlast,upperobt,t_obtlast);
892     if ( IsDebug() ) printf(" .-. jump %i zomp %i upperpkt %lld pktlast %u upperobt %lld obtlast %u last entry is %i \n",jump,zomp,upperpkt,pktlast,upperobt,obtlast,i);
893     throw -13;
894     };
895     //
896     if ( t_pktlast < upperpkt && t_obtlast < upperobt && t_pktlast < upperpkt2 && t_obtlast < upperobt2 ){
897     zomp = i + jump + 1;
898     if ( zomp > nevent-2 ) zomp = nevent - 2;
899     if ( IsDebug() ) printf(" .-. jump %i zomp %i upperpkt %lld pktlast %u upperobt %lld obtlast %u last entry is %i \n",jump,zomp,upperpkt,pktlast,upperobt,obtlast,i);
900     break;
901     };
902     //
903     t_pktlast = upperpkt;
904     t_obtlast = upperobt;
905     };
906     //
907     if ( jump == 1 ) jump = 0;
908     if ( jump == 10 ) jump = 1;
909     if ( jump == 100 ) jump = 10;
910     if ( jump == 1000 ) jump = 100;
911     if ( jump == 5000 ) jump = 1000;
912     if ( jump == 50000 ) jump = 5000;
913     //
914     };
915     //
916     };
917     //
918     // check if last runtrailer is within limits, if not extend limits (one should check for all packets but we need only runtrailer)
919     //
920     if ( !chewbacca ){
921     PacketType *pctp=0;
922     TTree *rh=(TTree*)file->Get("RunHeader");
923     if ( !rh || rh->IsZombie() ) throw -17;
924     TTree *rt=(TTree*)file->Get("RunTrailer");
925     if ( !rt || rt->IsZombie() ) throw -18;
926     //
927     rh->SetBranchAddress("RunHeader", &runh);
928     rh->SetBranchAddress("Header", &ehh);
929     //
930     rt->SetBranchAddress("RunTrailer", &runt);
931     rt->SetBranchAddress("Header", &eht);
932     //
933     rhev = rh->GetEntries();
934     rtev = rt->GetEntries();
935     Long64_t sobtt = 0LL;
936     Long64_t sobth = 0LL;
937     Long64_t spktt = 0LL;
938     Long64_t spkth = 0LL;
939     Long64_t pktt = 0LL;
940     Long64_t obtt = 0LL;
941     Long64_t pkth = 0LL;
942     Long64_t obth = 0LL;
943     //
944     if ( rhev || rtev ){
945    
946     T->GetEntry(upperentry);
947     code = eh->GetCounter();
948     Int_t lasttrail = code->Get(pctp->RunTrailer);
949     Int_t lasthead = code->Get(pctp->RunHeader);
950     if ( lasttrail < rtev ){
951     rt->GetEntry(lasttrail);
952     pht = eht->GetPscuHeader();
953     pktt = PKT(pht->GetCounter());
954     obtt = OBT(pht->GetOrbitalTime());
955     };
956     //
957     if ( lasthead < rhev ){
958     rh->GetEntry(lasthead);
959     phh = ehh->GetPscuHeader();
960     pkth = PKT(phh->GetCounter());
961     obth = OBT(phh->GetOrbitalTime());
962     };
963     //
964     if ( IsDebug() ) printf(" rhev before %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
965     if ( pkth > upperpkt && obth > upperobt ){
966     if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %lld upperp %lld oh %lld uppero %lld \n",pkth,upperpkt,obth,upperobt);
967     upperpkt = pkth;
968     upperobt = obth;
969     rhev = lasthead+1;
970     } else {
971     rhev = lasthead;
972     };
973     if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
974     //
975     if ( IsDebug() ) printf(" rtev beforev %i pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
976     if ( pktt > upperpkt && obtt > upperobt ){
977     if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %lld upperp %lld ot %lld uppero %lld \n",pktt,upperpkt,obtt,upperobt);
978     upperpkt = pktt;
979     upperobt = obtt;
980     rtev = lasttrail+1;
981     } else {
982     rtev = lasttrail;
983     };
984     if ( IsDebug() ) printf(" rtev after %i pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
985     // goto kikko;
986     //
987     //
988     // Check if runtrailer/runheader are within lower limits
989     //
990     //
991     pkth = 0LL;
992     obth = 0LL;
993     spkth = 0LL;
994     sobth = 0LL;
995     for (Int_t k=0; k<rhev; k++){
996     if ( k > 0 ){
997     spkth = pkth;
998     sobth = obth;
999     };
1000     rh->GetEntry(k);
1001     phh = ehh->GetPscuHeader();
1002     pkth = PKT(phh->GetCounter());
1003     obth = OBT(phh->GetOrbitalTime());
1004     //
1005     // if ( IsDebug() ) printf(" k %i rhev before %i ph %u upperp %u oh %u uppero %u \n",k,rhev,pkth,spkth,obth,sobth);
1006     //
1007     if ( pkth < spkth && obth < sobth ){
1008     if ( IsDebug() ) printf(" RH PROBLEMS determining the event repetition at the end of the file lasthead %i \n",rhev);
1009     if ( PEDANTIC ) throw -66;
1010     //
1011     rhev = k-1;
1012     rh->GetEntry(rhev);
1013     pkth = spkth;
1014     obth = sobth;
1015     //
1016     UInt_t evbefh = 0;
1017     code = ehh->GetCounter();
1018     evbefh = code->Get(pctp->Physics);
1019     if ( evbefh >= 0 ){
1020     T->GetEntry(evbefh);
1021     ph = eh->GetPscuHeader();
1022     t_pktlast = PKT(ph->GetCounter());
1023     t_obtlast = OBT(ph->GetOrbitalTime());
1024     if ( t_pktlast <= spkth && t_obtlast <= sobth ){ // jump
1025     upperpkt = pkth;
1026     upperobt = obth;
1027     upperentry = evbefh-1;
1028     } else {
1029     while ( t_pktlast > spkth && t_obtlast > sobth && evbefh < nevent ){
1030     evbefh++;
1031     T->GetEntry(evbefh);
1032     ph = eh->GetPscuHeader();
1033     t_pktlast = PKT(ph->GetCounter());
1034     t_obtlast = OBT(ph->GetOrbitalTime());
1035     };
1036     T->GetEntry(evbefh-1);
1037     ph = eh->GetPscuHeader();
1038     upperpkt = PKT(ph->GetCounter());
1039     upperobt = OBT(ph->GetOrbitalTime());
1040     upperentry = evbefh-1;
1041     };
1042     };
1043     if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
1044     goto kikko0;
1045     };
1046     };
1047     kikko0:
1048     //
1049     //
1050     //
1051     pktt = 0LL;
1052     obtt = 0LL;
1053     spktt = 0LL;
1054     sobtt = 0LL;
1055     for (Int_t k=0; k<rtev; k++){
1056     if ( k > 0 ){
1057     spktt = pktt;
1058     sobtt = obtt;
1059     };
1060     rt->GetEntry(k);
1061     pht = eht->GetPscuHeader();
1062     pktt = PKT(pht->GetCounter());
1063     obtt = OBT(pht->GetOrbitalTime());
1064     //
1065     // if ( IsDebug() ) printf(" k %i rtev beforev %i pt %i upperp %i ot %llu uppero %llu \n",k,rtev,pktt,spktt,obtt,sobtt);
1066     //
1067     if ( pktt < spktt && obtt < sobtt ){
1068     if ( IsDebug() ) printf(" RT PROBLEMS determining the event repetition at the end of the file lasttrail %i \n",rtev);
1069     if ( PEDANTIC ) throw -66;
1070     //
1071     rtev = k-1;
1072     rt->GetEntry(rtev);
1073     pktt = spktt;
1074     obtt = sobtt;
1075     if ( IsDebug() ) printf(" lasttrail %i pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
1076     //
1077     UInt_t evbeft = 0;
1078     code = eht->GetCounter();
1079     evbeft = code->Get(pctp->Physics);
1080     if ( evbeft >= 0 ){
1081     T->GetEntry(evbeft);
1082     ph = eh->GetPscuHeader();
1083     t_pktlast = PKT(ph->GetCounter());
1084     t_obtlast = OBT(ph->GetOrbitalTime());
1085     if ( t_pktlast <= spktt && t_obtlast <= sobtt ){ // jump
1086     upperpkt = pktt;
1087     upperobt = obtt;
1088     upperentry = evbeft-1;
1089     } else {
1090     while ( t_pktlast > spktt && t_obtlast > sobtt && evbeft < nevent ){
1091     evbeft++;
1092     T->GetEntry(evbeft);
1093     ph = eh->GetPscuHeader();
1094     t_pktlast = PKT(ph->GetCounter());
1095     t_obtlast = OBT(ph->GetOrbitalTime());
1096     };
1097     T->GetEntry(evbeft-1);
1098     ph = eh->GetPscuHeader();
1099     upperpkt = PKT(ph->GetCounter());
1100     upperobt = OBT(ph->GetOrbitalTime());
1101     upperentry = evbeft-1;
1102     };
1103     };
1104     if ( IsDebug() ) printf(" rtev after %i pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
1105     goto kikko;
1106     // break;
1107     //
1108     };
1109     //
1110     };
1111     //
1112     kikko:
1113     //
1114     T->GetEntry(upperentry);
1115     code = eh->GetCounter();
1116     lasttrail = code->Get(pctp->RunTrailer);
1117     lasthead = code->Get(pctp->RunHeader);
1118     if ( lasttrail < rtev ){
1119     rt->GetEntry(lasttrail);
1120     pht = eht->GetPscuHeader();
1121     pktt = PKT(pht->GetCounter());
1122     obtt = OBT(pht->GetOrbitalTime());
1123     };
1124     //
1125     if ( lasthead < rhev ){
1126     rh->GetEntry(lasthead);
1127     phh = ehh->GetPscuHeader();
1128     pkth = PKT(phh->GetCounter());
1129     obth = OBT(phh->GetOrbitalTime());
1130     };
1131     //
1132     if ( IsDebug() ) printf(" rhev before %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
1133     if ( pkth > upperpkt && obth > upperobt ){
1134     if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %lld upperp %lld oh %lld uppero %lld \n",pkth,upperpkt,obth,upperobt);
1135     upperpkt = pkth;
1136     upperobt = obth;
1137     rhev = lasthead+1;
1138 mocchiut 1.2 } else {
1139 mocchiut 1.1 rhev = lasthead;
1140     };
1141     if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
1142     //
1143     if ( IsDebug() ) printf(" rtev beforev %i pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
1144     if ( pktt > upperpkt && obtt > upperobt ){
1145     if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %lld upperp %lld ot %lld uppero %lld \n",pktt,upperpkt,obtt,upperobt);
1146     upperpkt = pktt;
1147     upperobt = obtt;
1148     rtev = lasttrail+1;
1149     } else {
1150     rtev = lasttrail;
1151     };
1152     if ( IsDebug() ) printf(" rtev after %i pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
1153     //
1154     };
1155     };
1156     //
1157     if ( IsDebug() ) printf(" Upper limits are: OBT %lld pkt_num %lld upper entry %i \n",upperobt,upperpkt,upperentry);
1158     //
1159     return(0);
1160     }
1161    
1162     /**
1163     *
1164     * Trick to have unique RUN ID numbers even when runs are deleted and mysql deamon restarted.
1165     * Entries in the _RUNID_GEN table are never deleted.
1166     *
1167     **/
1168     UInt_t PamelaDBOperations::AssignRunID(){
1169     //
1170     TSQLResult *result = 0;
1171     TSQLRow *row = 0;
1172     UInt_t runid = 0;
1173     //
1174     stringstream oss;
1175     //
1176     oss.str("");
1177 mocchiut 1.5 if ( chewbacca ){// if chewbacca and tag=none then use chewbacca tag (chiby = chewbacca inserted by), if chewbacca and tag!=none then use tag, if not chewbacca use tag.
1178     if ( !strcmp(tag.Data(),"NONE") ){
1179     oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< chiby.Data() <<"');";
1180     } else {
1181     oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< tag.Data() <<"');";
1182     };
1183     } else {
1184     oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< tag.Data() <<"');";
1185     };
1186 mocchiut 1.1 result = conn->Query(oss.str().c_str());
1187     if ( !result ) throw -10;
1188     oss.str("");
1189     oss << "SELECT ID FROM _RUNID_GEN ORDER BY ID DESC LIMIT 1;";
1190     result = conn->Query(oss.str().c_str());
1191     if ( !result ) throw -10;
1192     //
1193     row = result->Next();
1194     //
1195     if ( !row ) throw -28;
1196     //
1197     runid = (UInt_t)atoll(row->GetField(0));
1198     //
1199     return(runid);
1200     };
1201    
1202     //
1203     // GETTERS
1204     //
1205    
1206     /**
1207     *
1208     * Returns the DB absolute time needed to associate calibrations to data
1209     *
1210     */
1211     UInt_t PamelaDBOperations::GetAbsTime(UInt_t obt){
1212     //
1213     return(((UInt_t)(OBT(obt)/1000)+toffset));
1214     //
1215     };
1216    
1217     /**
1218     *
1219     * List of packet types (just to make easily the loops)
1220     *
1221     */
1222     const PacketType* PamelaDBOperations::GetPacketType(const char* type){
1223     if ( !strcmp(type,"Pscu") ) return(PacketType::Pscu);
1224     if ( !strcmp(type,"PhysEndRun") ) return(PacketType::PhysEndRun);
1225     if ( !strcmp(type,"CalibCalPulse1") ) return(PacketType::CalibCalPulse1);
1226     if ( !strcmp(type,"CalibCalPulse2") ) return(PacketType::CalibCalPulse2);
1227     if ( !strcmp(type,"Physics") ) return(PacketType::Physics);
1228     if ( !strcmp(type,"CalibTrkBoth") ) return(PacketType::CalibTrkBoth);
1229     if ( !strcmp(type,"CalibTrk1") ) return(PacketType::CalibTrk1);
1230     if ( !strcmp(type,"CalibTrk2") ) return(PacketType::CalibTrk2);
1231     if ( !strcmp(type,"CalibTof") ) return(PacketType::CalibTof);
1232     if ( !strcmp(type,"CalibS4") ) return(PacketType::CalibS4);
1233     if ( !strcmp(type,"CalibCalPed") ) return(PacketType::CalibCalPed);
1234     if ( !strcmp(type,"Calib1_Ac1") ) return(PacketType::Calib1_Ac1);
1235     if ( !strcmp(type,"Calib2_Ac1") ) return(PacketType::Calib2_Ac1);
1236     if ( !strcmp(type,"Calib1_Ac2") ) return(PacketType::Calib1_Ac2);
1237     if ( !strcmp(type,"Calib2_Ac2") ) return(PacketType::Calib2_Ac2);
1238     if ( !strcmp(type,"CalibCal") ) return(PacketType::CalibCal);
1239     if ( !strcmp(type,"RunHeader") ) return(PacketType::RunHeader);
1240     if ( !strcmp(type,"RunTrailer") ) return(PacketType::RunTrailer);
1241     if ( !strcmp(type,"CalibHeader") ) return(PacketType::CalibHeader);
1242     if ( !strcmp(type,"CalibTrailer") ) return(PacketType::CalibTrailer);
1243     if ( !strcmp(type,"InitHeader") ) return(PacketType::InitHeader);
1244     if ( !strcmp(type,"InitTrailer") ) return(PacketType::InitTrailer);
1245     if ( !strcmp(type,"EventTrk") ) return(PacketType::EventTrk);
1246     if ( !strcmp(type,"Log") ) return(PacketType::Log);
1247     if ( !strcmp(type,"VarDump") ) return(PacketType::VarDump);
1248     if ( !strcmp(type,"ArrDump") ) return(PacketType::ArrDump);
1249     if ( !strcmp(type,"TabDump") ) return(PacketType::TabDump);
1250     if ( !strcmp(type,"Tmtc") ) return(PacketType::Tmtc);
1251     if ( !strcmp(type,"Mcmd") ) return(PacketType::Mcmd);
1252     if ( !strcmp(type,"ForcedFECmd") ) return(PacketType::ForcedFECmd);
1253     if ( !strcmp(type,"Ac1Init") ) return(PacketType::Ac1Init);
1254     if ( !strcmp(type,"CalInit") ) return(PacketType::CalInit);
1255     if ( !strcmp(type,"TrkInit") ) return(PacketType::TrkInit);
1256     if ( !strcmp(type,"TofInit") ) return(PacketType::TofInit);
1257     if ( !strcmp(type,"TrgInit") ) return(PacketType::TrgInit);
1258     if ( !strcmp(type,"NdInit") ) return(PacketType::NdInit);
1259     if ( !strcmp(type,"S4Init") ) return(PacketType::S4Init);
1260     if ( !strcmp(type,"Ac2Init") ) return(PacketType::Ac2Init);
1261     if ( !strcmp(type,"CalAlarm") ) return(PacketType::CalAlarm);
1262     if ( !strcmp(type,"Ac1Alarm") ) return(PacketType::Ac1Alarm);
1263     if ( !strcmp(type,"TrkAlarm") ) return(PacketType::TrkAlarm);
1264     if ( !strcmp(type,"TrgAlarm") ) return(PacketType::TrgAlarm);
1265     if ( !strcmp(type,"TofAlarm") ) return(PacketType::TofAlarm);
1266     if ( !strcmp(type,"S4Alarm") ) return(PacketType::S4Alarm);
1267     if ( !strcmp(type,"Ac2Alarm") ) return(PacketType::Ac2Alarm);
1268     if ( !strcmp(type,"TsbT") ) return(PacketType::TsbT);
1269     if ( !strcmp(type,"TsbB") ) return(PacketType::TsbB);
1270     return(PacketType::Invalid);
1271     };
1272    
1273     //
1274     // PRIVATE FUNCTIONS
1275     //
1276    
1277     // /**
1278     // * Open the ROOT filename for reading
1279     // */
1280     // void PamelaDBOperations::OpenFile(){
1281     // file = TFile::Open(this->GetRootName().Data());
1282     // //
1283    
1284     void PamelaDBOperations::CheckFile(){
1285     if ( !file ) throw -12;
1286     };
1287    
1288    
1289     /**
1290     * Check if LEVEL0 file and DB connection have really be opened
1291     */
1292     void PamelaDBOperations::CheckConnection(){
1293     //
1294     // check connection
1295     //
1296     if( !conn ) throw -1;
1297     bool connect = conn->IsConnected();
1298     if( !connect ) throw -1;
1299     //
1300     if ( IsDebug() ) printf("\n DB INFORMATIONS:\n SQL: %s Version: %s Host %s Port %i \n\n",conn->GetDBMS(),conn->ServerInfo(),conn->GetHost(),conn->GetPort());
1301     //
1302     if ( !dworbit && strcmp(this->GetRootName().Data(),"") ) throw -27;
1303     //
1304     // set DB timezone to UTC
1305     //
1306     stringstream oss;
1307     //
1308     oss.str("");
1309     oss << "SET time_zone='+0:00';";
1310     TSQLResult *result = 0;
1311     result = conn->Query(oss.str().c_str());
1312     if ( !result ) throw -10;
1313     oss.str("");
1314     oss << "SET wait_timeout=173000;";
1315     conn->Query(oss.str().c_str());
1316     //
1317     }
1318    
1319     /**
1320     * Lock tables
1321     */
1322     void PamelaDBOperations::LockTables(){
1323     //
1324     // check connection
1325     //
1326     if( !conn ) throw -1;
1327     bool connect = conn->IsConnected();
1328     if( !connect ) throw -1;
1329     //
1330     stringstream oss;
1331     //
1332     oss.str("");
1333 pam-fi 1.4 oss << "lock table GL_RUN write, GL_ROOT write, GL_RAW write, GL_TIMESYNC write, GL_RESURS_OFFSET write, GL_PARAM write, GL_TLE write, GL_RUN_FRAGMENTS write, GL_RUN_TRASH write, GL_CALO_CALIB write, GL_CALOPULSE_CALIB write, GL_TRK_CALIB write, GL_S4_CALIB write, ROOT_TABLE_MERGING write, ROOT_TABLE_BAD write, ROOT_TABLE write, _RUNID_GEN write;";
1334 mocchiut 1.1 TSQLResult *result = 0;
1335     result = conn->Query(oss.str().c_str());
1336     if ( !result ) throw -10;
1337     //
1338     }
1339    
1340     /**
1341     * Lock tables
1342     */
1343     void PamelaDBOperations::UnLockTables(){
1344     //
1345     // check connection
1346     //
1347     if( !conn ) throw -1;
1348     bool connect = conn->IsConnected();
1349     if( !connect ) throw -1;
1350     //
1351     stringstream oss;
1352     //
1353     oss.str("");
1354     oss << "unlock tables;";
1355     TSQLResult *result = 0;
1356     result = conn->Query(oss.str().c_str());
1357     if ( !result ) throw -10;
1358     //
1359     }
1360    
1361     /**
1362     * Return the correct packet number if we went back to zero
1363     */
1364     Long64_t PamelaDBOperations::PKT(UInt_t pkt_num){
1365     //
1366 mocchiut 1.2 // if ( IsDebug() ) printf(" pkt conversion: pkt_num is %u pktfirst is %u (UInt_t)(16777214/2)) is %u \n",pkt_num,ppktfirst,(UInt_t)(16777214/2));
1367 mocchiut 1.1 //
1368     if ( pkt_num < (ppktfirst/2) && ppktfirst > (16777214/2) ){
1369 mocchiut 1.2 // if ( IsDebug() ) printf(" rise up pktnum %lld \n",(Long64_t)pkt_num+16777215LL);
1370 mocchiut 1.1 return((Long64_t)pkt_num+16777215LL);
1371     };
1372     //
1373     if ( pkt_num > ((Long64_t)ppktfirst*2) && pkt_num > (16777214/2) ){
1374 mocchiut 1.2 // if ( IsDebug() ) printf(" rise down pktnum %lld \n",(Long64_t)pkt_num-16777215LL);
1375 mocchiut 1.1 return((Long64_t)pkt_num-16777215LL);
1376     };
1377     //
1378 mocchiut 1.2 // if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)pkt_num);
1379 mocchiut 1.1 return((Long64_t)pkt_num);
1380     //
1381     };
1382    
1383     /**
1384     * Return the correct On Board Time if we went back to zero
1385     */
1386     Long64_t PamelaDBOperations::OBT(UInt_t obt){
1387     //
1388 mocchiut 1.2 // if ( IsDebug() ) printf(" obt conversion: obt is %u obtfirst is %u (numeric_limits<UInt_t>::max()/2) is %u \n",obt,pobtfirst,(UInt_t)(numeric_limits<UInt_t>::max()/2));
1389 mocchiut 1.1 //
1390 mocchiut 1.11 if ( obt < ((Long64_t)pobtfirst/2) && pobtfirst > (numeric_limits<UInt_t>::max()/2) ){
1391 mocchiut 1.2 // if ( IsDebug() ) printf(" rise up obt %lld \n",(Long64_t)obt+(Long64_t)numeric_limits<UInt_t>::max());
1392 mocchiut 1.1 return((Long64_t)obt+(Long64_t)numeric_limits<UInt_t>::max());
1393     };
1394     //
1395     if ( obt > ((Long64_t)pobtfirst*2) && obt > (numeric_limits<UInt_t>::max()/2) ){
1396 mocchiut 1.2 // if ( IsDebug() ) printf(" pobtfirst*2 %lld \n",((Long64_t)pobtfirst*2));
1397     // if ( IsDebug() ) printf(" rise down pktnum %lld \n", (Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());
1398 mocchiut 1.1 return((Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());
1399     };
1400     //
1401 mocchiut 1.2 // if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)obt);
1402 mocchiut 1.1 return((Long64_t)obt);
1403     };
1404    
1405     /**
1406     *
1407     * Fill the glrun class with infos about the run when we have both runtrailer and runheader
1408     *
1409     */
1410     void PamelaDBOperations::FillClass(){
1411     this->FillClass(false,false,-1,-1);
1412     };
1413    
1414     /**
1415     *
1416     * Fill the glrun class with infos about the run when we have both runtrailer and runheader
1417     *
1418     */
1419     void PamelaDBOperations::FillClass(Bool_t mishead, Bool_t mistrail, Int_t firstev, Int_t lastev){
1420     //
1421     TTree *T = 0;
1422     T = (TTree*)file->Get("Physics");
1423     if ( !T || T->IsZombie() ) throw -16;
1424     //
1425     EventHeader *eh = 0;
1426     PscuHeader *ph = 0;
1427     T->SetBranchAddress("Header", &eh);
1428     PacketType *pctp=0;
1429     EventCounter *codt=0;
1430     EventCounter *codh=0;
1431     UInt_t firstObt = 0;
1432     UInt_t lastObt = 0;
1433     UInt_t firstPkt = 0;
1434     UInt_t lastPkt = 0;
1435     UInt_t rhtime = 0;
1436     UInt_t rttime = 0;
1437 mocchiut 1.3 //
1438     if ( IsDebug() ) printf(" A firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1439     //
1440 mocchiut 1.1 if ( !mishead ){
1441     codh = ehh->GetCounter();
1442 mocchiut 1.3 if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){
1443     if ( IsDebug() ) printf(" B firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1444 mocchiut 1.1 firstev = 1;
1445     lastev = 0;
1446     } else {
1447     firstev = codh->Get(pctp->Physics);
1448     };
1449     rhtime = this->GetAbsTime(phh->GetOrbitalTime());
1450     glrun->Set_GL_RUNH(runh,phh);
1451     firstObt = glrun->GetRUNHEADER_OBT();
1452     firstPkt = glrun->GetRUNHEADER_PKT();
1453     };
1454     if ( !mistrail ){
1455     codt = eht->GetCounter();
1456 mocchiut 1.3 if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1)){
1457     if ( IsDebug() ) printf(" C firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1458 mocchiut 1.1 lastev = 0;
1459     firstev = lastev+1;
1460     } else {
1461     lastev = codt->Get(pctp->Physics)-1;
1462     };
1463     rttime = this->GetAbsTime(pht->GetOrbitalTime());
1464     glrun->Set_GL_RUNT(runt,pht);
1465     lastObt = glrun->GetRUNTRAILER_OBT();
1466     lastPkt = glrun->GetRUNTRAILER_PKT();
1467     };
1468     //
1469     if ( mishead && mistrail && lastev+1 == firstev ) throw -14; // run with no events, no runtrailer, no runheader... unsupported should never arrive here
1470     //
1471     if ( mishead ) {
1472     glrun->Set_GL_RUNH0();
1473     //
1474 mocchiut 1.3 if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){
1475 mocchiut 1.1 firstObt = lastObt;
1476     firstPkt = lastPkt;
1477     rhtime = rttime;
1478     } else {
1479     T->GetEntry(firstev);
1480     ph = eh->GetPscuHeader();
1481     firstObt = ph->GetOrbitalTime();
1482     rhtime = this->GetAbsTime(firstObt);
1483     firstPkt = ph->GetCounter();
1484     };
1485     //
1486     glrun->SetRUNHEADER_PKT(firstPkt);
1487     glrun->SetRUNHEADER_OBT(firstObt);
1488     //
1489     };
1490     if ( mistrail ){
1491     glrun->Set_GL_RUNT0();
1492     //
1493 mocchiut 1.3 if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){
1494 mocchiut 1.1 lastObt = firstObt;
1495     lastPkt = firstPkt;
1496     rttime = rhtime;
1497     } else {
1498     T->GetEntry(lastev);
1499     ph = eh->GetPscuHeader();
1500     lastObt = ph->GetOrbitalTime();
1501     rttime = this->GetAbsTime(lastObt);
1502     lastPkt = ph->GetCounter();
1503     };
1504     //
1505     glrun->SetRUNTRAILER_OBT(lastObt);
1506     glrun->SetRUNTRAILER_PKT(lastPkt);
1507     //
1508     };
1509 mocchiut 1.23 //
1510     // ad hoc solution for INF EV_TO [8RED] 090113
1511     //
1512     if ( !firstev && lastev == -1 ){
1513     if ( IsDebug() ) printf(" EE firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1514     firstev = 1;
1515     lastev = 0;
1516     };
1517 mocchiut 1.1 glrun->SetEV_FROM((UInt_t)firstev);
1518     glrun->SetEV_TO((UInt_t)lastev);
1519     glrun->SetNEVENTS((UInt_t)lastev-(UInt_t)firstev+1);
1520     //
1521     if ( IsDebug() ) printf(" firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1522     //
1523     this->SetCommonGLRUN(rhtime,rttime);
1524 mocchiut 1.2 this->SetPhysEndRunVariables();
1525 mocchiut 1.1 //
1526     };
1527    
1528     //
1529     // PUBLIC FUNCTIONS
1530     //
1531    
1532     /**
1533     * Insert a new row into GL_RAW table.
1534     */
1535     Int_t PamelaDBOperations::insertPamelaRawFile(){
1536 pam-fi 1.4
1537     //
1538     Bool_t idr = this->SetID_RAW();
1539     if ( idr ) return(1);
1540    
1541     GL_RAW glraw = GL_RAW();
1542    
1543     glraw.PATH = GetRawPath();
1544     glraw.NAME = GetRawFile();
1545 mocchiut 1.5 // glraw.BOOT_NUMBER = 0;//???
1546     glraw.BOOT_NUMBER = this->GetBOOTnumber();
1547 pam-fi 1.4
1548     if( insertPamelaRawFile(&glraw) )return(1);
1549     //
1550     idr = this->SetID_RAW();
1551     if ( !idr ) throw -11;
1552    
1553     return(0);
1554     }
1555     /**
1556     * Insert a new row into GL_RAW table.
1557     */
1558     Int_t PamelaDBOperations::insertPamelaRawFile(GL_RAW *glraw){
1559 mocchiut 1.1 //
1560 mocchiut 1.5 if(!glraw)return(1);//?? ok I think
1561 pam-fi 1.4 //
1562     stringstream oss;
1563     //
1564     oss.str("");
1565     if ( STATIC ){
1566     oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"
1567     << glraw->PATH << "', '" << glraw->NAME << "')";
1568     } else {
1569     oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('$PAM_RAW', '" << glraw->NAME << "')";
1570     };
1571     if ( debug ) cout <<oss.str().c_str() <<endl;
1572     if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
1573     //
1574     oss.str("");
1575     oss << "SELECT ID FROM GL_RAW WHERE NAME=\""<<glraw->NAME<<"\";";
1576     if ( debug ) cout << oss.str().c_str()<<endl;
1577     if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
1578     //
1579     TSQLResult *result = 0;
1580     TSQLRow *row = 0;
1581     result = conn->Query(oss.str().c_str());
1582     if ( result == NULL ) throw -4;
1583     row = result->Next();
1584     if ( !row ) return(1);
1585     glraw->ID = (UInt_t)atoll(row->GetField(0));
1586     if ( debug ) printf(" The ID of the RAW file is %u \n",glraw->ID);
1587     delete result;
1588     delete row;
1589     //
1590     return(0);
1591 mocchiut 1.1 }
1592    
1593    
1594     /**
1595     * Look for one timesync information in the file and
1596     * fill the GL_TIMESYNC table. It will look for: 1) TS-MCMD 2) TS info in the RunHeader 3) TS info in the runtrailer, if none exists exit with error
1597     */
1598     Int_t PamelaDBOperations::insertPamelaGL_TIMESYNC(){
1599     //
1600     Int_t signal = 0;
1601     UInt_t idresof = 0;
1602     stringstream oss;
1603     TSQLResult *result = 0;
1604     TSQLRow *row = 0;
1605     UInt_t OBT = 0;
1606     UInt_t TYPE = 0;
1607     UInt_t TSYNC = 0;
1608     UInt_t t0 = 0;
1609     Bool_t existsts = false;
1610     //
1611     if ( chewbacca ){
1612     //
1613     OBT = chobtts * 1000;
1614     TSYNC = chlastts;
1615     t0 = chresursts;
1616     TYPE = 777;
1617     oss.str("");
1618     oss << "select * from GL_RESURS_OFFSET where OFFSET_DATE=FROM_UNIXTIME("<< t0 <<") limit 1;";
1619     if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
1620     result = conn->Query(oss.str().c_str());
1621     if ( !result ) throw -10;
1622     row = result->Next();
1623 mocchiut 1.14 if ( !row ) throw -92;
1624 mocchiut 1.1 idresof = (UInt_t)atoll(row->GetField(0));
1625     existsts = true;
1626     goto eout;
1627     //
1628     } else {
1629     //
1630     //signal = this->SetUpperLimits();
1631     //
1632     if ( this->GetID_RAW() == 0 ) throw -11;
1633     //
1634     oss.str("");
1635     oss << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE),ID FROM GL_RESURS_OFFSET WHERE SPECIAL_FILE='"
1636     << this->GetRawFile().Data() << "';";
1637     if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
1638     result = conn->Query(oss.str().c_str());
1639     if ( !result ) throw -10;
1640     row = result->Next();
1641     //
1642     if ( !row ){
1643     oss.str("");
1644     oss << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE),ID FROM GL_RESURS_OFFSET WHERE FROM_ORBIT< "
1645 mocchiut 1.20 << dworbit << " AND SPECIAL_FILE='' order by FROM_ORBIT desc limit 1;";
1646 mocchiut 1.1 if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
1647     result = conn->Query(oss.str().c_str());
1648     if ( !result ) throw -10;
1649     row = result->Next();
1650     if ( !row ) throw -10;
1651     };
1652     //
1653     idresof = (UInt_t)atoll(row->GetField(6));
1654     //
1655     TTimeStamp tu = TTimeStamp((UInt_t)atoi(row->GetField(0)),(UInt_t)atoi(row->GetField(1)),(UInt_t)atoi(row->GetField(2)),(UInt_t)atoi(row->GetField(3)),(UInt_t)atoi(row->GetField(4)),(UInt_t)atoi(row->GetField(5)),0,true,0);
1656     t0 = (UInt_t)tu.GetSec();
1657     if ( IsDebug() ) printf(" t0 is %u ti is %s %s %s %s %s %s %s\n",t0,row->GetField(0),row->GetField(1),row->GetField(2),row->GetField(3),row->GetField(4),row->GetField(5),row->GetField(6));
1658     //
1659     /*
1660     * Verify that the TIMESYNC have been not already processed
1661     */
1662     oss.str("");
1663     oss << " SELECT COUNT(GL_TIMESYNC.ID),GL_TIMESYNC.OBT0,GL_TIMESYNC.TIMESYNC FROM GL_TIMESYNC "
1664     << " LEFT JOIN GL_RAW "
1665     << " ON GL_RAW.ID = GL_TIMESYNC.ID_RAW "
1666     << " WHERE GL_TIMESYNC.ID_RAW = " << this->GetID_RAW()
1667     << " GROUP BY GL_TIMESYNC.OBT0;";
1668     if ( IsDebug() ) printf(" check for old timesync: query is \n %s \n",oss.str().c_str());
1669     result = conn->Query(oss.str().c_str());
1670     if (result == NULL) throw -10;
1671     row = result->Next();
1672     if ((row != NULL) && ((UInt_t)atoll(row->GetField(0)) > 0)){
1673     if ( IsDebug() ) printf(" found a timesync t0 is %u \n",t0);
1674     toffset = (UInt_t)atoll(row->GetField(2)) - (UInt_t)(this->OBT((UInt_t)atoll(row->GetField(1)))/1000) + t0;
1675     //
1676     tsync = (UInt_t)atoll(row->GetField(2));
1677     obt0 = (UInt_t)atoll(row->GetField(1));
1678     //
1679     if ( PEDANTIC ) throw -67;
1680     return(1);
1681     };
1682     //
1683     TTree *T = 0;
1684     //
1685     UInt_t nevent = 0;
1686     UInt_t recEntries = 0;
1687     //
1688     OBT = 0;
1689     TYPE = 0;
1690     TSYNC = 0;
1691     //
1692     Double_t minimum = 0.;
1693     Double_t maximum = 0.;
1694     Double_t minimum2 = 0.;
1695     Double_t maximum2 = 0.;
1696     //
1697     //
1698     pamela::McmdEvent *mc = 0;
1699     pamela::McmdRecord *mcrc = 0;
1700     TArrayC *mcmddata = 0;
1701     //
1702     minimum = numeric_limits<Double_t>::max();
1703     maximum = numeric_limits<Double_t>::min();
1704     minimum2 = numeric_limits<Double_t>::max();
1705     maximum2 = numeric_limits<Double_t>::min();
1706     //
1707     T = (TTree*)file->Get("Mcmd");
1708     if ( !T || T->IsZombie() ) throw -19;
1709     T->SetBranchAddress("Mcmd",&mc);
1710     //
1711     nevent = T->GetEntries();
1712     //
1713     // loop over events
1714     //
1715     existsts = false;
1716     //
1717     for (UInt_t i=0; i<nevent;i++){
1718     //
1719     T->GetEntry(i);
1720     //
1721     recEntries = mc->Records->GetEntries();
1722     //
1723     for (UInt_t j = 0; j < recEntries; j++){
1724     mcrc = (pamela::McmdRecord*)mc->Records->At(j);
1725     mcmddata = mcrc->McmdData;
1726     //
1727     if (mcrc->ID1 == 0xE0){ // mcmd timesync
1728     //
1729     OBT = (Int_t)(mcrc->MCMD_RECORD_OBT);
1730     //
1731     TSYNC = (((UInt_t)mcmddata->At(0)<<24)&0xFF000000) + (((UInt_t)mcmddata->At(1)<<16)&0x00FF0000) + (((UInt_t)mcmddata->At(2)<<8)&0x0000FF00) + (((UInt_t)mcmddata->At(3))&0x000000FF);
1732     //
1733     TYPE = 55;//224;
1734     //
1735     if ( IsDebug() ) printf("mcmd tsync %i tsync %u obt %u \n",i,TSYNC,OBT);
1736     //
1737     if ( TSYNC && OBT ){
1738     existsts = true;
1739     goto eout;
1740     };
1741     //
1742     };
1743     };
1744     };
1745     if ( !existsts ) { // try with runheader and runtrailer
1746     //
1747     if ( IsDebug() ) printf(" No ts mcmd \n");
1748     signal = 2;
1749     //
1750     TTree *rh=(TTree*)file->Get("RunHeader");
1751     if ( !rh || rh->IsZombie() ) throw -17;
1752     TTree *rt=(TTree*)file->Get("RunTrailer");
1753     if ( !rt || rt->IsZombie() ) throw -18;
1754     //
1755     rh->SetBranchAddress("RunHeader", &runh);
1756     //
1757     rt->SetBranchAddress("RunTrailer", &runt);
1758     //
1759     Int_t nnrhev = rh->GetEntries();
1760     Int_t nnrtev = rt->GetEntries();
1761     if ( IsDebug() ) printf(" ou nevent %i rhev %i rtev %i \n",nevent,nnrhev,nnrtev);
1762     //
1763     if ( nnrhev > 0 ){
1764     for (Int_t i=0; i<nnrhev; i++){
1765     //
1766     rh->GetEntry(i);
1767     //
1768     TSYNC = runh->LAST_TIME_SYNC_INFO;
1769     OBT = runh->OBT_TIME_SYNC * 1000;
1770     //
1771     TYPE = 20;
1772     //
1773     if ( IsDebug() ) printf("runheader %i tsync %u obt %u \n",i,TSYNC,OBT);
1774     //
1775     if ( TSYNC && OBT ){
1776     existsts = true;
1777     goto eout;
1778     };
1779     };
1780     //
1781     };
1782     if ( nnrtev > 0 ){
1783     //
1784     if ( IsDebug() ) printf(" No runheader \n");
1785     signal = 6;
1786     //
1787     for (Int_t i=0; i<nnrtev; i++){
1788     //
1789     rt->GetEntry(i);
1790     //
1791     TSYNC = runt->LAST_TYME_SYNC_INFO;
1792     OBT = runt->OBT_TYME_SYNC * 1000;
1793     //
1794     TYPE = 21;
1795     //
1796     if ( IsDebug() ) printf("runtrailer %i tsync %u obt %u \n",i,TSYNC,OBT);
1797     //
1798     if ( TSYNC && OBT ){
1799     existsts = true;
1800     goto eout;
1801     };
1802     };
1803     //
1804     } else {
1805     if ( IsDebug() ) printf(" No runheader \n");
1806     };
1807     };
1808     //
1809     if ( !existsts ){ // try with inclination mcmd
1810     //
1811     if ( IsDebug() ) printf(" No runtrailer \n");
1812     signal = 14;
1813     //
1814     Double_t timesync = 0.;
1815     for (UInt_t i=0; i<nevent;i++){
1816     //
1817     T->GetEntry(i);
1818     //
1819     recEntries = mc->Records->GetEntries();
1820     // //
1821     for (UInt_t j = 0; j < recEntries; j++){
1822     mcrc = (pamela::McmdRecord*)mc->Records->At(j);
1823     mcmddata = mcrc->McmdData;
1824     //
1825     if (mcrc->ID1 == 0xE2){ // mcmd inclination
1826     timesync = 0.;
1827     timesync = (Double_t)(((((UInt_t)mcmddata->At(0) << 24) & 0xFF000000) + (((UInt_t)mcmddata->At(1) << 16) & 0x00FF0000) + (((UInt_t)mcmddata->At(2) << 8) & 0x0000FF00) + ((UInt_t)mcmddata->At(3) & 0x000000FF))/128.0);
1828     //
1829     if ( timesync > maximum2){
1830     maximum2 = timesync;
1831     OBT = (Int_t)(mcrc->MCMD_RECORD_OBT);
1832     };
1833     };
1834     //
1835     };
1836     };
1837     if ( maximum2 > numeric_limits<Double_t>::min() ){
1838     TSYNC = (UInt_t)(maximum2 + 0.5);
1839     TYPE = 666;
1840     if ( TSYNC && OBT ){
1841     existsts = true;
1842     goto eout;
1843     };
1844     };
1845     };
1846     //
1847     };
1848     //
1849     if ( !existsts && obt0 ){ // insert timesync by hand
1850     //
1851     if ( PEDANTIC ) throw -68;
1852     if ( IsDebug() ) printf(" No incl mcmd \n");
1853     signal = 30;
1854     //
1855     OBT = obt0;
1856     TSYNC = tsync;
1857     TYPE = 999;
1858     existsts = true;
1859     goto eout;
1860     };
1861     //
1862     eout:
1863     //
1864     if ( !existsts ) throw -3;
1865     //
1866     oss.str("");
1867     oss << "INSERT INTO GL_TIMESYNC (ID_RAW,TYPE,OBT0,TIMESYNC,ID_RESURS_OFFSET) VALUES ('"
1868     << this->GetID_RAW() << "','"//224'"
1869     << dec << (UInt_t)TYPE << "','"
1870     << dec << (UInt_t)OBT << "','"
1871     << dec << (UInt_t)TSYNC << "','"
1872     << dec << (UInt_t)idresof << "');";
1873     conn->Query(oss.str().c_str());
1874     if ( IsDebug() ) printf(" Query the GL_TIMESYNC table to fill it:\n %s \n",oss.str().c_str());
1875     if ( conn->GetErrorCode() ){
1876     printf(" OK, you got an error because the database structure you are using is not up to date\n Using backward compability code, hence you can continue safetly \n");
1877     oss.str("");
1878     oss << "INSERT INTO GL_TIMESYNC (ID_RAW,TYPE,OBT0,TIMESYNC) VALUES ('"
1879     << this->GetID_RAW() << "','"//224'"
1880     << dec << (UInt_t)TYPE << "','"
1881     << dec << (UInt_t)OBT << "','"
1882     << dec << (UInt_t)TSYNC << "');";
1883     conn->Query(oss.str().c_str());
1884     if ( IsDebug() ) printf(" Query the GL_TIMESYNC table to fill it:\n %s \n",oss.str().c_str());
1885     };
1886     //
1887     if ( IsDebug() ) printf(" found a timesync t0 is %u \n",t0);
1888     //
1889     toffset = (UInt_t)TSYNC - (UInt_t)(this->OBT(OBT)/1000) + t0;
1890     //
1891     tsync = TSYNC;
1892     obt0 = OBT;
1893     //
1894     delete result;
1895     return(signal);
1896     }
1897    
1898     /**
1899     * Insert all the new rows into GL_ROOT.
1900     * The raw file indicates in the parameters should be already been stored in the database.
1901     */
1902     Int_t PamelaDBOperations::insertPamelaRootFile(){
1903 pam-fi 1.4
1904     stringstream oss;
1905     TSQLResult *result = 0;
1906     TSQLRow *row = 0;
1907 mocchiut 1.5 //
1908 pam-fi 1.4 // ----------------------
1909     // determine the timesync
1910     // ----------------------
1911     UInt_t idtimesync = 0;
1912     //
1913     if ( chewbacca ){
1914     oss.str("");
1915     oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" limit 1;";
1916     if ( debug ) printf(" %s \n",oss.str().c_str());
1917     result = conn->Query(oss.str().c_str());
1918     //
1919     if ( !result ) throw -3;
1920     //
1921     row = result->Next();
1922     //
1923     if ( !row ) throw -3;
1924     idtimesync = (UInt_t)atoll(row->GetField(0));
1925     } else {
1926     oss.str("");
1927     if ( STATIC ){
1928     oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1929     << " LEFT JOIN GL_ROOT "
1930     << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1931     << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "
1932     << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1933     } else {
1934     oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1935     << " LEFT JOIN GL_ROOT "
1936     << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1937     << " WHERE GL_RAW.PATH = '$PAM_RAW' AND "
1938     << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1939     };
1940     result = conn->Query(oss.str().c_str());
1941     //
1942     if ( !result ) throw -12;
1943     //
1944     row = result->Next();
1945     //
1946     if ( !row ) throw -10;
1947     if ( row != NULL && (UInt_t)atoll(row->GetField(0))>0 ){
1948     idroot = (UInt_t)atoll(row->GetField(2));
1949     delete row;
1950     delete result;
1951     return(1);
1952     };
1953     //
1954     // determine which timesync has to be used
1955     //
1956     oss.str("");
1957     oss << "SELECT GL_TIMESYNC.ID FROM GL_TIMESYNC LEFT JOIN GL_RAW ON GL_RAW.ID = GL_TIMESYNC.ID_RAW ORDER BY GL_TIMESYNC.ID DESC LIMIT 1;";
1958     result = conn->Query(oss.str().c_str());
1959     //
1960     if ( !result ) throw -3;
1961     //
1962     row = result->Next();
1963     //
1964     if ( !row ) throw -3;
1965     idtimesync = (UInt_t)atoll(row->GetField(0));
1966     };
1967    
1968     delete row;
1969     delete result;
1970    
1971     // ----------------------
1972     // insert root file
1973     // ----------------------
1974    
1975     GL_ROOT glroot = GL_ROOT();
1976    
1977     glroot.ID_RAW = GetID_RAW();
1978     glroot.ID_TIMESYNC = idtimesync;
1979 mocchiut 1.5 if ( STATIC ){
1980     glroot.PATH = GetRootPath();
1981     } else {
1982     if ( KEEPENV ){
1983     glroot.PATH = gSystem->DirName(filerootname.Data());
1984     } else {
1985     glroot.PATH = "$PAM_L0";
1986     };
1987     };
1988 mocchiut 1.6 glroot.NAME = GetRootFile();
1989 pam-fi 1.4
1990     if ( insertPamelaRootFile(&glroot) )return 1;
1991    
1992     SetID_ROOT(glroot.ID);
1993    
1994    
1995     return (0);
1996     }
1997     /**
1998     * Insert all the new rows into GL_ROOT.
1999     * The raw file indicates in the parameters should be already been stored in the database.
2000     */
2001     Int_t PamelaDBOperations::insertPamelaRootFile(GL_ROOT *glroot){
2002 mocchiut 1.1 stringstream oss;
2003     TSQLResult *result = 0;
2004     TSQLRow *row = 0;
2005     //
2006     //
2007     oss.str("");
2008 mocchiut 1.5 oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
2009     << glroot->ID_RAW << "', '" << glroot->ID_TIMESYNC << "', '" << glroot->PATH << "', '" << glroot->NAME << "')";
2010 mocchiut 1.1 //
2011 pam-fi 1.4 if ( debug ) printf("%s \n",oss.str().c_str());
2012 mocchiut 1.1 if (conn->Query(oss.str().c_str()) == 0) throw -4;
2013     //
2014     delete result;
2015     //
2016     oss.str("");
2017     // oss << "SELECT ID FROM GL_ROOT WHERE ID_RAW=" << this->GetID_RAW() << ";";
2018 mocchiut 1.5 oss << "SELECT ID FROM GL_ROOT WHERE PATH='" << glroot->PATH << "' and NAME='"<< glroot->NAME <<"';";
2019 mocchiut 1.1 //
2020 pam-fi 1.4 if ( debug ) printf("%s \n",oss.str().c_str());
2021 mocchiut 1.1 result = conn->Query(oss.str().c_str());
2022     if ( !result ) throw -12;
2023     row = result->Next();
2024     if ( !row ) throw -3;
2025 pam-fi 1.4
2026     glroot->ID = (UInt_t)atoll(row->GetField(0));
2027    
2028     if ( debug ) printf(" The ID of the ROOT file is %u \n",glroot->ID);
2029 mocchiut 1.1 //
2030     delete result;
2031     //
2032     return(0);
2033     }
2034    
2035     /**
2036     * Assign the BOOT_NUMBER to the raw file.
2037     */
2038     Int_t PamelaDBOperations::assignBOOT_NUMBER(){
2039     Bool_t found = false;
2040     UInt_t idRaw = 0;
2041     UInt_t bn = 0;
2042     stringstream oss;
2043     TSQLResult *result = 0;
2044     TSQLRow *row = 0;
2045     if ( chewbacca ){
2046     if ( chboot == 1 ){
2047     // not found!
2048     found = false;
2049     } else {
2050     found = true;
2051     this->SetBOOTnumber(chboot);
2052     };
2053     } else {
2054     oss.str("");
2055     if ( STATIC ){
2056     oss << "SELECT ID, BOOT_NUMBER FROM GL_RAW WHERE "
2057     << " PATH = '" << this->GetRawPath().Data() << "' AND "
2058     << " NAME = '" << this->GetRawFile().Data() << "' ";
2059     } else {
2060     oss << "SELECT ID, BOOT_NUMBER FROM GL_RAW WHERE "
2061     << " PATH = '$PAM_RAW' AND "
2062     << " NAME = '" << this->GetRawFile().Data() << "' ";
2063     };
2064     result = conn->Query(oss.str().c_str());
2065     //
2066     if ( !result ) throw -4;;
2067     row = result->Next();
2068     if ( !row ) return(16);
2069     if ( row->GetField(1) ){
2070     this->SetBOOTnumber((UInt_t)atoll(row->GetField(1)));
2071     return(1);
2072     };
2073     if ( !row->GetField(0) ) throw -26;
2074     //
2075     idRaw = (UInt_t)atoll(row->GetField(0));
2076     //
2077     //
2078     //
2079     TTree *trDumpEv = 0;
2080     trDumpEv = (TTree*)file->Get("VarDump");
2081     if ( !trDumpEv || trDumpEv->IsZombie() ) throw -20;
2082     //
2083     VarDumpEvent *vde = 0;
2084     VarDumpRecord *vdr = 0;
2085     //
2086     trDumpEv->SetBranchAddress("VarDump", &vde);
2087     if ( trDumpEv->GetEntries() > 0 ){
2088     found = false;
2089     for ( Int_t i = 0; i < trDumpEv->GetEntries(); i++){
2090     trDumpEv->GetEntry(i);
2091     // vde->Records->GetEntries();
2092     if ( vde->Records->GetEntries()>5 ){
2093     found = true;
2094     goto fill;
2095     };
2096     };
2097     fill:
2098     if ( found ){
2099     //
2100     vdr = (VarDumpRecord*)vde->Records->At(6);
2101     //
2102     this->SetBOOTnumber((Int_t)vdr->VAR_VALUE);
2103     //
2104     } else {
2105     if ( !this->GetBOOTnumber() && !this->AutoBoot()) return(4);
2106     };
2107     } else {
2108     if ( !this->GetBOOTnumber() && !this->AutoBoot()) return(2);
2109     };
2110     //
2111     };
2112     //
2113     Bool_t afound = false;
2114     if ( !found && this->AutoBoot()){
2115     afound = true;
2116     //
2117     // Search for other files with similar timesync
2118     //
2119     if ( IsDebug() ) printf(" tsync %u obt0 %u \n",tsync,obt0);
2120     UInt_t upperts = tsync-(obt0/1000)+5;
2121     UInt_t lowerts = tsync-(obt0/1000)-5;
2122     if ( chewbacca ){
2123     oss.str("");
2124     oss << "select BOOT_NUMBER from ROOT_TABLE where LAST_TIME_SYNC_INFO-(OBT_TIME_SYNC)<"
2125     << upperts
2126     << " AND LAST_TIME_SYNC_INFO-(OBT_TIME_SYNC)>"
2127     << lowerts
2128     << " AND BOOT_NUMBER>1;";
2129     } else {
2130     oss.str("");
2131     oss << "select GL_RAW.BOOT_NUMBER from GL_TIMESYNC LEFT JOIN GL_RAW ON GL_RAW.ID = GL_TIMESYNC.ID_RAW where TIMESYNC-(OBT0/1000)<"
2132     << upperts
2133     << " AND TIMESYNC-(OBT0/1000)>"
2134     << lowerts
2135     << " AND GL_RAW.BOOT_NUMBER>0 GROUP BY GL_TIMESYNC.OBT0;";
2136     };
2137     result = conn->Query(oss.str().c_str());
2138     if ( IsDebug() && !chewbacca ) printf(" Query the GL_TIMESYNC table to find boot number:\n %s \n",oss.str().c_str());
2139     if ( IsDebug() && chewbacca ) printf(" Query the ROOT_TABLE table to find boot number:\n %s \n",oss.str().c_str());
2140     //
2141     if ( !result ) throw -4;;
2142     found = true;
2143     if ( result->GetRowCount()<3 ){
2144     if ( IsDebug() ) printf(" AGH! no results!\n");
2145     found = false;
2146     } else {
2147     row = result->Next();
2148     bn = (UInt_t)atoll(row->GetField(0));
2149     for ( Int_t r=1; r<result->GetRowCount() ;r++){
2150     if ( !row ) throw -4;
2151     if ( IsDebug() ) printf(" BOOT number is %s \n",row->GetField(0));
2152     if ( bn != (UInt_t)atoll(row->GetField(0)) ){
2153     if ( IsDebug() ) printf(" AGH! bn = %u here instead %u \n",bn,(UInt_t)atoll(row->GetField(0)));
2154     found = false;
2155     };
2156     row = result->Next();
2157     };
2158     };
2159     };
2160     //
2161     Int_t sgn = 0;
2162     //
2163     if ( !found && !BOOTNO ){
2164     throw -29;
2165     } else {
2166     if ( afound ){
2167     this->SetBOOTnumber(bn);
2168     sgn = 8;
2169     };
2170     };
2171     //
2172     if ( !chewbacca ){
2173     oss.str("");
2174     oss << " UPDATE GL_RAW "
2175     << " SET GL_RAW.BOOT_NUMBER = '" << dec << this->GetBOOTnumber() << "'"
2176     << " WHERE GL_RAW.ID = '" << idRaw << "'";
2177     conn->Query(oss.str().c_str());
2178     };
2179     //
2180     delete result;
2181     return(sgn);
2182     };
2183    
2184     /**
2185     * Scan runtrailer packet, fill the GL_RUN table and
2186     * check for missing and truncated runs
2187     */
2188     Int_t PamelaDBOperations::insertPamelaRUN(){
2189     Int_t signal = 0;
2190     //
2191     stringstream oss;
2192     oss.str("");
2193     //
2194     // signal = this->SetUpperLimits();
2195    
2196     //
2197     // loop on runheader and runtrailer events
2198     //
2199     TTree *rh=(TTree*)file->Get("RunHeader");
2200     if ( !rh || rh->IsZombie() ) throw -17;
2201     TTree *rt=(TTree*)file->Get("RunTrailer");
2202     if ( !rt || rt->IsZombie() ) throw -18;
2203     //
2204     PacketType *pctp=0;
2205     EventCounter *cod=0;
2206     //
2207     rh->SetBranchAddress("RunHeader", &runh);
2208     rh->SetBranchAddress("Header", &ehh);
2209     //
2210     rt->SetBranchAddress("RunTrailer", &runt);
2211     rt->SetBranchAddress("Header", &eht);
2212     //
2213     TTree *T = (TTree*)file->Get("Physics");
2214     if ( !T || T->IsZombie() ) throw -16;
2215     EventHeader *eh = 0;
2216     T->SetBranchAddress("Header", &eh);
2217     //
2218     if ( !(rh->GetEntries()) && !(rt->GetEntries()) && !(T->GetEntries()) ) return(16);
2219     //
2220     UInt_t obtt = 0;
2221     UInt_t obth = 0;
2222     UInt_t pktt = 0;
2223     UInt_t pkth = 0;
2224     Int_t pth = -1;
2225     Int_t ptht = -1;
2226     Int_t evbeft = 0;
2227     Int_t evbefh = 0;
2228     UInt_t tcod;
2229     //
2230     // no runtrailers in the file!
2231     //
2232     if ( !rtev ){
2233     if ( !rhev ){
2234     if ( IsDebug() ) printf(" No runheaders nor runtrailers!! \n");
2235     if ( !(upperentry-chminentry) ){
2236     if ( IsDebug() ) printf(" No physics events nor runs in the file \n"); // di nuovo potrebbe esserci un runtrailer senza eventi (riempimento MM)
2237     // throw -8;
2238     return 0; // one could check if there is any calibration no need to exit with error
2239     } else {
2240     this->HandleRunFragments(true,true,chminentry,upperentry); // no runtrailers ma potrebbe esserci un runheader ora...
2241     };
2242     } else {
2243     //
2244     // we have runheaders but not runtrailers!
2245     //
2246     if ( debug ) printf(" We have runheaders (%i) but not runtrailers (%i) ! \n",rhev,rtev);
2247     for ( pth=0; pth < rhev; pth++ ){
2248     rh->GetEntry(pth);
2249     phh = ehh->GetPscuHeader();
2250     pkth = phh->GetCounter();
2251     obth = phh->GetOrbitalTime();
2252     if ( PKT(pkth) >= PKT(pktfirst) && PKT(pkth) <= upperpkt ){
2253     cod = ehh->GetCounter();
2254     tcod = (UInt_t)cod->Get(pctp->Physics);
2255     evbefh = TMath::Max(chminentry,tcod);
2256 mocchiut 1.2 // if ( (UInt_t)evbefh == upperentry ) evbefh = upperentry + 1; // this does not work due to the Counter bug in chewbacca
2257 mocchiut 1.1 if ( (UInt_t)evbefh == upperentry || !upperentry ) evbefh = upperentry + 1;
2258 mocchiut 1.2 //
2259     if ( debug ) printf(" evbefh %i upperentry %u \n",evbefh,upperentry);
2260 mocchiut 1.1 //
2261     this->HandleRunFragments(false,true,evbefh,upperentry);
2262     //
2263     };
2264     };
2265     //
2266     };
2267     //
2268     } else {
2269     //
2270     Int_t conptt = -1;
2271     for (Int_t ptt=0; ptt<rtev; ptt++){
2272     //
2273     rt->GetEntry(ptt);
2274     pht = eht->GetPscuHeader();
2275     pktt = pht->GetCounter();
2276     obtt = pht->GetOrbitalTime();
2277     //
2278     if ( PKT(pktt) >= PKT(pktfirst) && PKT(pktt) <= upperpkt ){
2279     //
2280     conptt++;
2281     //
2282     cod = eht->GetCounter();
2283     ptht = cod->Get(pctp->RunHeader) - 1;
2284     // evbeft = cod->Get(pctp->Physics);
2285     tcod = (UInt_t)cod->Get(pctp->Physics);
2286 mocchiut 1.17 if ( !tcod ) tcod = 1; // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
2287 mocchiut 1.1 evbeft = TMath::Min(upperentry,(tcod-1));
2288     if ( debug ) printf(" Loop in runtrailers, evbeft is %u upperentry %u cod->getetc %u \n",evbeft,upperentry,cod->Get(pctp->Physics));
2289     //
2290     // if ( !conptt && !(ptht+1) ){ // here we assume ptht+1 = 0 at the beginning of the interval that could not be true if the interval start from middle file... it must be equal to the number of RH before the interval that is not counted anywhere
2291     if ( !conptt && (ptht+1) == nrhbef ){
2292     //
2293     if ( IsDebug() ) printf(" Piece of run at the beginning of the file %i %i %u \n",ptht,pth,ptt);
2294     //
2295     this->HandleRunFragments(true,false,chminentry,(evbeft));
2296     //
2297     pth = ptht; // ??
2298     //
2299     } else if ( pth == ptht ){
2300     //
2301     if ( IsDebug() ) printf(" Missing header %i %i %u\n",ptht,pth,ptt);
2302     //
2303     if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
2304     rt->GetEntry(ptt-1);
2305     cod = eht->GetCounter();
2306     tcod = (UInt_t)cod->Get(pctp->Physics);
2307     evbefh = TMath::Max(chminentry,tcod);
2308     //evbefh = cod->Get(pctp->Physics);
2309     rt->GetEntry(ptt);
2310     pht = eht->GetPscuHeader();
2311     //
2312     if ( IsDebug() ) printf(" Try to find the beginning of a run which has only the runtrailer %i %i %u \n",ptht,pth,ptt);
2313     if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' %u %u %u \n",pkth,obth,obtt);
2314     //
2315     this->HandleMissingHoT(true,false,evbefh,(evbeft));
2316     //
2317     } else {
2318     //
2319     rh->GetEntry(ptht);
2320     phh = ehh->GetPscuHeader();
2321     pkth = phh->GetCounter();
2322     obth = phh->GetOrbitalTime();
2323     cod = ehh->GetCounter();
2324     tcod = (UInt_t)cod->Get(pctp->Physics);
2325 mocchiut 1.17 if ( !tcod ) tcod = 1; // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
2326 mocchiut 1.1 evbefh = TMath::Max(chminentry,(tcod-1));
2327     //
2328     if ( PKT(pkth) >= PKT(pktfirst) && PKT(pkth) <= upperpkt ){
2329     if ( IsDebug() ) printf(" Could be a good run, we have a runheader followed by a runtrailer %i %i %u\n",ptht,pth,ptt);
2330     //
2331     // evbefh = cod->Get(pctp->Physics);
2332     if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' %u %u %u \n",pkth,obth,obtt);
2333     //
2334     // handle this run
2335     //
2336     this->HandleRun();
2337     //
2338     //
2339     if ( debug ) printf(" Standard case, evbefh is %u chminentry %u cod->getetc %u \n",evbefh,chminentry,cod->Get(pctp->Physics));
2340     //
2341     } else {
2342     // missing header in the considered interval!
2343     if ( debug ) printf(" Missing header in the considered interval \n");
2344     this->HandleRunFragments(true,false,evbefh,evbeft);
2345     };
2346     //
2347     if ( PKT(pkth)>PKT(pktfirst) && OBT(obth)>OBT(obtfirst) && PKT(pkth)<=(upperpkt) && !conptt ){
2348     //
2349     if ( IsDebug() ) printf(" Piece of run at the beginning of the file WITH NO RUNTRAILER evbefh = %u \n",evbefh);
2350     //
2351     if ( evbefh == 0 ) {
2352     //
2353     if ( !chewbacca ){
2354     signal = 8;
2355     if ( IsDebug() ) printf(" Not supported yet: run with no events, no runtrailer, no runheader \n");
2356     } else {
2357     if ( debug ) printf(" The file does not start with a physics packet, no problem continue \n");
2358     };
2359     //
2360     } else {
2361     //
2362     this->HandleRunFragments(true,true,chminentry,(evbefh));
2363     //
2364 mocchiut 1.10 // what about pth=ptht-1
2365 mocchiut 1.1 };
2366     };
2367     //
2368     //
2369     if ( (ptht - pth) > 1 ){
2370     //
2371     if ( IsDebug() ) printf(" Missing runtrailers! \n");
2372     if ( IsDebug() ) printf(" Attention there is a jump in the runheader counter %i %i %u \n",ptht,pth,ptt);
2373     // is not the consecutive header
2374     while ( pth != ptht ){
2375     //
2376     // treat the header(s) in the middle and then go to the next header, repeat until you reach the correct header.
2377     //
2378     pth++;
2379     //
2380     rh->GetEntry(pth+1);
2381     phh = ehh->GetPscuHeader();
2382     pktt = phh->GetCounter();
2383     obtt = phh->GetOrbitalTime();
2384     cod = ehh->GetCounter();
2385     // evbeft = cod->Get(pctp->Physics);
2386     tcod = (UInt_t)cod->Get(pctp->Physics);
2387 mocchiut 1.17 if ( !tcod ) tcod = 1; // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
2388 mocchiut 1.1 evbeft = TMath::Min(upperentry,(tcod-1));
2389     rh->GetEntry(pth);
2390     phh = ehh->GetPscuHeader();
2391     cod = ehh->GetCounter();
2392     pkth = phh->GetCounter();
2393     obth = phh->GetOrbitalTime();
2394     //evbefh = cod->Get(pctp->Physics);
2395     tcod = (UInt_t)cod->Get(pctp->Physics);
2396     evbefh = TMath::Max(chminentry,tcod);
2397     //
2398     if ( PKT(pkth) >= PKT(pktfirst) && PKT(pkth) <= upperpkt && pth != ptht ){
2399     //
2400     if ( IsDebug() ) printf(" Try to find the end of a run which has only the runheader %i %i %u \n",ptht,pth,ptt);
2401     if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' %u %u %u \n",pkth,obth,obtt);
2402     //
2403     this->HandleMissingHoT(false,true,evbefh,evbeft);
2404     //
2405     };
2406     };
2407     //
2408     } else if ( !(ptht - pth) ){
2409     //
2410     if ( IsDebug() ) printf(" Missing runheader! \n");
2411     if ( IsDebug() ) printf(" Attention! the runheader counter did not changed %i %i %u \n",ptht,pth,ptt);
2412     if ( IsDebug() ) printf(" The run should have already been handled by HandleRun() \n");
2413     if ( PEDANTIC ) throw -87;
2414     //
2415     } else {
2416     //
2417     // go on with next header
2418     //
2419     pth = ptht;
2420     };
2421     //
2422     };
2423     //
2424     // if ( ptt+1 == rtev){
2425     if ( conptt+1 == nrtev ){
2426     // if ( conptt+1 == (nrtev+nrtbef )){
2427 mocchiut 1.10 if ( IsDebug() ) printf(" >>>>>>>>>>> %i %u %i %u \n",ptht,rhev,nrtev,conptt);
2428 mocchiut 1.1 ptht++;
2429 mocchiut 1.15 if ( ptht < rhev ){
2430 mocchiut 1.1 rh->GetEntry(ptht);
2431 mocchiut 1.10 //pth++;
2432     //if ( pth < rhev ){
2433     //rh->GetEntry(pth);
2434 mocchiut 1.1 phh = ehh->GetPscuHeader();
2435     pkth = phh->GetCounter();
2436     obth = phh->GetOrbitalTime();
2437     cod = ehh->GetCounter();
2438     tcod = (UInt_t)cod->Get(pctp->Physics);
2439     evbefh = TMath::Max(chminentry,tcod);
2440     if ( PKT(pkth) >= PKT(pktfirst) && PKT(pkth) <= upperpkt ){
2441     // evbefh = cod->Get(pctp->Physics);
2442     if ( IsDebug() ) printf(" Piece of run at the end of file %u %u %u \n",pkth,obth,obtt);
2443     if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''' %i %i %u \n",ptht,pth,ptt);
2444     if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''' %u \n",rhev);
2445     if ( IsDebug() ) printf(" evbefh %u upperentry %u \n",(UInt_t)evbefh,upperentry);
2446     //
2447     this->HandleRunFragments(false,true,evbefh,upperentry);
2448     //
2449     };
2450     } else {
2451     //
2452     // check if we have a fragment with no header
2453     //
2454     if ( (UInt_t)evbeft < upperentry-1 && upperentry>0 ){
2455     if ( IsDebug() ) printf(" Piece of run at the end of the file with NO RUNHEADER! evbeft %u upperentry-1 %u \n",(UInt_t)evbeft,upperentry-1);
2456     //
2457 mocchiut 1.15 // if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
2458     if ( (rtev-1) < 0 || ptt < 0 ) throw -15; // should never arrive here!
2459 mocchiut 1.10 // rt->GetEntry(ptt-1);
2460     rt->GetEntry(rtev-1);
2461 mocchiut 1.1 cod = eht->GetCounter();
2462 mocchiut 1.10 tcod = (UInt_t)cod->Get(pctp->Physics)+1;
2463 mocchiut 1.1 evbefh = TMath::Max(chminentry,tcod);
2464     // evbefh = cod->Get(pctp->Physics);
2465     rt->GetEntry(ptt);
2466     pht = eht->GetPscuHeader();
2467     this->HandleRunFragments(true,true,evbefh,upperentry);
2468     };
2469     };
2470     };
2471     //
2472     };
2473     };
2474     };
2475     //
2476     return(signal);
2477     };
2478    
2479     /**
2480     *
2481     * Check if the run has already been inserted
2482     *
2483     */
2484     Bool_t PamelaDBOperations::IsRunAlreadyInserted(){
2485     //
2486     TSQLResult *result = 0;
2487     TSQLRow *row = 0;
2488     //
2489     stringstream oss;
2490     oss.str("");
2491     //
2492     // the where clause is of the type: boot_number = _our_boot && (
2493     // ( runhead_time >= (_our_runhead_time-10) && runtrail_time <= (_our_runtrail_time+10) &&
2494     // ( runhead_obt >= _our_runheadobt || runhead_pkt >= _our_runheadpkt ) &&
2495     // ( runtrail_obt >= _our_runtrailobt || runtrail_pkt >= _our_runtrailpkt ) )
2496     // ||
2497     // ( runhead_time <= _our_runhead_time && runtrail_time >= _our_runtrail_time &&
2498     // ( runhead_obt <= _our_runheadobt || runhead_pkt <= _our_runheadpkt ) &&
2499     // ( runtrail_obt <= _our_runtrailobt || runtrail_pkt <= _our_runtrailpkt ) )
2500     // ||
2501     // ( runhead_time = _our_runhead_time && runtrail_time = _our_runtrail_time && nevents > 100 )
2502     // )
2503     // ||
2504     // ( runhead_time = _our_runhead_time && runtrail_time > _our_runtrail_time && nevents > 100 )
2505     // )
2506     // ||
2507     // ( runhead_time < _our_runhead_time && runtrail_time = _our_runtrail_time && nevents > 100 )
2508     // )
2509     //
2510     oss << " SELECT ID,NEVENTS,TRK_CALIB_USED,PKT_COUNTER FROM GL_RUN WHERE "
2511     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
2512     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
2513     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
2514     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
2515     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2516     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
2517     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
2518     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2519     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
2520     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
2521     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2522     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR ";
2523     if ( glrun->GetNEVENTS() < 100 ){
2524     oss<<" RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << "))); ";
2525     } else {
2526     oss << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ")) OR "
2527     << " (RUNHEADER_TIME=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND " // these two lines in a certain way disable the patch below...
2528     << " RUNTRAILER_TIME=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND NEVENTS>100) OR" //
2529     << " (RUNHEADER_TIME=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND " //
2530     << " RUNTRAILER_TIME>" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND NEVENTS>100) OR" //
2531     << " (RUNHEADER_TIME<" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND " //
2532     << " RUNTRAILER_TIME=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND NEVENTS>100)" //
2533     << " );";
2534     };
2535     //
2536     if ( IsDebug() ) printf(" THIS RUN: RUNHEADER_OBT %u RUNTRAILER_OBT %u RUNHEADER_PKT %u RUNTRAILER_PKT %u NEVENTS %u\n", glrun->GetRUNHEADER_OBT(),glrun->GetRUNTRAILER_OBT(),glrun->GetRUNHEADER_PKT(),glrun->GetRUNTRAILER_PKT(),glrun->GetNEVENTS());
2537     if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
2538     result = conn->Query(oss.str().c_str());
2539     //
2540     if ( !result ) throw -4;
2541     //
2542     row = result->Next();
2543     //
2544     if ( !row ){
2545     if ( IsDebug() ) printf(" The run is new \n");
2546     if ( IsDebug() ) printf(" -> fill the DB \n");
2547     return(false); // the file has not been inserted in the DB, go on.
2548     };
2549     //
2550     Bool_t signal = true;
2551     //
2552     while ( row != NULL ){
2553     if ( IsDebug() ) printf(" A run exists with runheader and runtrailer time and packets compatible with this one \n");
2554     //
2555     // the run has already been inserted
2556     //
2557     if ( signal && IsDebug() ) printf(" The run has already been inserted\n");
2558     if ( PEDANTIC ) throw -86;
2559     return(true); //<<<<<<<<<<<<<<<<<<<<<<<< patch follows, uncomment here
2560     //
2561     // PATCH!
2562     // we keep the processing run if (in order of growing importance) 1) we have the runtrailer while the old run doesn't have it 2) we have the runheader
2563     // while the old run doesn't have it 3) we have more events than the old run
2564     //
2565     if ( glrun->GetNEVENTS() > (UInt_t)atoll(row->GetField(1)) ){
2566     //
2567     if ( IsDebug() ) printf(" The new run has more events than the old one \n");
2568     glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2569 mocchiut 1.2 // oss.str("");
2570     // oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2571     // if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());
2572     // conn->Query(oss.str().c_str());
2573 mocchiut 1.1 if ( signal ) signal = false;
2574     goto gonext;
2575     //
2576     } else if ( glrun->GetNEVENTS() < (UInt_t)atoll(row->GetField(1)) ){
2577     if ( IsDebug() ) printf(" The new run has less events than the old one \n");
2578     if ( IsDebug() ) printf(" The run is already inserted \n");
2579     goto gonext;
2580     };
2581     //
2582     if ( glrun->GetTRK_CALIB() && !(UInt_t)atoll(row->GetField(2)) ){
2583     //
2584     if ( IsDebug() ) printf(" The new run has the same number of events and the runheader the old one miss the runheader \n");
2585     //
2586     glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2587 mocchiut 1.2 // oss.str("");
2588     // oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2589     // if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());
2590     // conn->Query(oss.str().c_str());
2591 mocchiut 1.1 //
2592     if ( signal ) signal = false;
2593     goto gonext;
2594     } else if ( !glrun->GetTRK_CALIB() && (UInt_t)atoll(row->GetField(2)) ){
2595     if ( IsDebug() ) printf(" The new run has the same number of events but miss the runheader the old has the runheader \n");
2596     if ( IsDebug() ) printf(" The run is already inserted \n");
2597     goto gonext;
2598     };
2599     //
2600     if ( glrun->GetPKT_COUNTER() && !(UInt_t)atoll(row->GetField(3)) ){
2601     //
2602     if ( IsDebug() ) printf(" The new run has the same number of events, the runheader and the runtrailer the old one miss the runtrailer \n");
2603     //
2604     glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2605 mocchiut 1.2 // oss.str("");
2606     // oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2607     // if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());
2608     // conn->Query(oss.str().c_str());
2609 mocchiut 1.1 if ( signal ) signal = false;
2610     //
2611     };
2612     //
2613     gonext:
2614     // END PATCH!
2615     //
2616     row = result->Next();
2617     //
2618     };
2619     //
2620     delete result;
2621     //
2622     if ( signal && IsDebug() ) printf(" The run has already been inserted \n");
2623     if ( !signal && IsDebug() ) printf(" The run existed and has been overridden, fill the DB \n");
2624     if ( PEDANTIC ) throw -86;
2625     return(signal);
2626     };
2627    
2628     /**
2629     * Handle runs which seems to be good ones.
2630     **/
2631     void PamelaDBOperations::HandleRun(){
2632     ULong64_t chkpkt = 0;
2633     ULong64_t pktt = (ULong64_t)PKT(pht->GetCounter());
2634     ULong64_t pkth = (ULong64_t)PKT(phh->GetCounter());
2635     //
2636     chkpkt = pkth + (ULong64_t)runt->PKT_COUNTER + 1ULL + 1ULL;
2637     //
2638     if ( labs(chkpkt-pktt)<2 ){
2639     //
2640     if ( IsDebug() ) printf(" check %llu pktt %llu \n",chkpkt,pktt);
2641     //
2642     // it must be a good run, fill the db
2643     //
2644     this->FillClass();
2645     //
2646     if ( !IsRunAlreadyInserted() ){
2647     glrun->SetID(this->AssignRunID());
2648     glrun->SetID_RUN_FRAG(0);
2649     glrun->Fill_GL_RUN(conn);
2650     };
2651     } else {
2652     //
2653     if ( IsDebug() ) printf(" oh no! the distance between runheader and runtrailer seems wrong: check %llu pktt %llu \n",chkpkt,pktt);
2654     if ( IsDebug() ) printf(" try to recover run(s) without runheader and runtrailer between runheader and runtrailer\n");
2655     //
2656     this->HandleSuspiciousRun();
2657     //
2658     };
2659     //
2660     //
2661     return;
2662     };
2663    
2664    
2665     /**
2666     * Handle run fragments at the beginning or at the end of the file
2667     **/
2668     void PamelaDBOperations::HandleRunFragments(Bool_t mishead, Bool_t mistrail, UInt_t firstev, UInt_t lastev){
2669     //
2670     UInt_t rhfirstev = firstev;
2671     UInt_t rtlastev = lastev;
2672     Bool_t found = false;
2673     Bool_t foundinrun = false;
2674     //
2675     TSQLResult *result = 0;
2676     TSQLRow *row = 0;
2677     //
2678     stringstream oss;
2679     oss.str("");
2680     //
2681     // is the piece of run good (no other packets inside)?
2682     //
2683     if ( !this->IsRunConsistent(mishead,mistrail,firstev,lastev)){
2684     //
2685     // if not, handle other pieces and continue with the first one
2686     //
2687     if ( IsDebug() ) printf("The run is not consistent, it contains non-physics packets! The run has been handled \n");
2688     //
2689     } else {
2690     //
2691 mocchiut 1.2 // we have now the good first piece of a run, fill the glrun object
2692     //
2693 mocchiut 1.16 if ( firstev != (lastev+1) ){ // could be a problem sometimes (?)
2694     if ( rhfirstev != firstev && !mishead ) mishead = true;
2695     if ( rtlastev != lastev && !mistrail ) mistrail = true;
2696     };
2697 mocchiut 1.1 //
2698 mocchiut 1.16 if ( IsDebug() ) printf(" bhere firstev is %i lastev is %i \n",firstev,lastev);
2699 mocchiut 1.2 this->FillClass(mishead,mistrail,firstev,lastev);
2700 mocchiut 1.16 if ( IsDebug() ) printf(" chere firstev is %i lastev is %i \n",firstev,lastev);
2701 mocchiut 1.1 //
2702 mocchiut 1.2 if ( IsDebug() ) printf("The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
2703     if ( IsDebug() ) printf(" C THIS RUN: RUNHEADER_OBT %u RUNTRAILER_OBT %u RUNHEADER_PKT %u RUNTRAILER_PKT %u \n", glrun->GetRUNHEADER_OBT(),glrun->GetRUNTRAILER_OBT(),glrun->GetRUNHEADER_PKT(),glrun->GetRUNTRAILER_PKT());
2704 mocchiut 1.1 //
2705 mocchiut 1.2 // First of all insert the run in the fragment table...
2706 mocchiut 1.1 //
2707     oss.str("");
2708 mocchiut 1.2 oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
2709     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
2710     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
2711     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
2712     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
2713     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2714     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
2715     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
2716     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2717     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
2718     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
2719     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2720     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
2721     << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
2722 mocchiut 1.1 //
2723 mocchiut 1.2 if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
2724 mocchiut 1.1 result = conn->Query(oss.str().c_str());
2725     //
2726     if ( !result ) throw -4;
2727     //
2728     row = result->Next();
2729     //
2730 mocchiut 1.2 if ( !row ){
2731     //
2732     // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
2733     //
2734     if ( IsDebug() ) printf(" The run is new \n");
2735     if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
2736     //
2737     glrun->SetID(this->AssignRunID());
2738     glrun->SetID_RUN_FRAG(0);
2739     glrun->Fill_GL_RUN_FRAGMENTS(conn);
2740     //
2741     } else {
2742 mocchiut 1.21 if ( IsDebug() ) printf(" The run is already present in the fragment table, relaxed %u \n",RELAXED);
2743     if ( !RELAXED ){
2744     if ( PEDANTIC ) throw -69;
2745     return;
2746     } else {
2747     glrun->SetID((UInt_t)atoll(row->GetField(0)));
2748     glrun->SetID_RUN_FRAG(0);
2749     };
2750 mocchiut 1.2 };
2751     //
2752     if ( chewbacca && mishead && mistrail ) goto justcheck;
2753     //
2754     // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
2755     //
2756     if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
2757     // missing it no way we can found a piece in the frag table
2758 mocchiut 1.1 //
2759     oss.str("");
2760 mocchiut 1.2 oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "
2761 mocchiut 1.1 << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2762     << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2763     << " ID != " << glrun->ID
2764 mocchiut 1.2 << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
2765 mocchiut 1.1 //
2766 mocchiut 1.2 if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());
2767 mocchiut 1.1 result = conn->Query(oss.str().c_str());
2768     //
2769     if ( !result ) throw -4;
2770     //
2771     row = result->Next();
2772     //
2773 mocchiut 1.2 if ( !row && NoFrag() ){
2774     //
2775     oss.str("");
2776     oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
2777     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2778     << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2779     << " ID != " << glrun->ID
2780     << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
2781     //
2782     if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
2783     result = conn->Query(oss.str().c_str());
2784     //
2785     if ( !result ) throw -4;
2786     //
2787     foundinrun = true;
2788     //
2789     row = result->Next();
2790     //
2791     };
2792 mocchiut 1.1 //
2793 mocchiut 1.2 if ( !row ){
2794     if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2795     found = false;
2796     } else {
2797     //
2798     found = false; // default value
2799     //
2800 mocchiut 1.16 if ( IsDebug() ) printf(" A Found a possible candidate, checking if it is the good one... \n");
2801 mocchiut 1.1 //
2802 mocchiut 1.2 // if we have both runheader and runtrailer we can check with pkt_counter:
2803 mocchiut 1.1 //
2804 mocchiut 1.2 if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){
2805     ULong64_t chkpkt = 0;
2806     ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
2807     ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
2808     //
2809     chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;
2810 mocchiut 1.1 //
2811 mocchiut 1.2 if ( labs(chkpkt-pktt)<2 ){
2812     //
2813     if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
2814     //
2815     found = true;
2816 mocchiut 1.16 if ( IsDebug() ) printf(" where firstev is %i lastev is %i \n",firstev,lastev);
2817 mocchiut 1.2 //
2818     } else {
2819     //
2820     if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);
2821     //
2822     found = false;
2823     //
2824     };
2825     };
2826     if ( !found && chewbacca ) goto justcheck;
2827     if ( !found ){
2828 mocchiut 1.1 //
2829 mocchiut 1.2 // if we arrive here we were not able to decide if the two pieces matches using only the pkt counter information, we must check times and obts
2830 mocchiut 1.1 //
2831 mocchiut 1.2 ULong64_t chkpkt1 = 0;
2832     ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
2833     ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
2834     chkpkt1 = labs(orunh1-dbrunt1);
2835 mocchiut 1.1 //
2836 mocchiut 1.2 ULong64_t chkpkt2 = 0;
2837     ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());
2838     ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
2839     chkpkt2 = labs(orunh2-dbrunt2);
2840 mocchiut 1.1 //
2841 mocchiut 1.2 ULong64_t chkpkt3 = 0;
2842     ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());
2843     ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
2844     chkpkt3 = labs(orunh3-dbrunt3);
2845 mocchiut 1.1 //
2846 mocchiut 1.2 if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
2847     // if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){
2848     //
2849     if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
2850     //
2851     found = true;
2852     //
2853     } else {
2854     //
2855     if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
2856     //
2857     found = false;
2858     //
2859     };
2860 mocchiut 1.1 };
2861     };
2862 mocchiut 1.2 //
2863     if ( found ){
2864     //
2865     // we have found the missing piece, glue the two together, merge the informations, fill the gl_run table (check first runs do not exists), delete entry in frag table
2866     //
2867     if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
2868     //
2869     if ( foundinrun ){
2870     glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2871     glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2872     };
2873 mocchiut 1.1 //
2874 mocchiut 1.2 GL_RUN *glrun1 = new GL_RUN();
2875 mocchiut 1.1 //
2876 mocchiut 1.2 // UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
2877     //
2878     oss.str("");
2879     oss << " ID="<<row->GetField(0)<<";";
2880     //
2881     glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos
2882 mocchiut 1.16 if ( IsDebug() ) printf(" there firstev is %i lastev is %i \n",firstev,lastev);
2883 mocchiut 1.2 //
2884     // merge infos
2885     //
2886     UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());
2887     ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
2888     UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
2889     ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
2890     if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2891     TTree *T= 0;
2892     T = (TTree*)file->Get("Physics");
2893     if ( !T || T->IsZombie() ) throw -16;
2894     EventHeader *eh = 0;
2895     PscuHeader *ph = 0;
2896     T->SetBranchAddress("Header", &eh);
2897     while ( apkt > bpkt && aobt > bobt && firstev < lastev ){
2898     T->GetEntry(firstev);
2899     ph = eh->GetPscuHeader();
2900     bpkt = PKT(ph->GetCounter());
2901     bobt = OBT(ph->GetOrbitalTime());
2902     firstev++;
2903     if ( PEDANTIC ) throw -71;
2904     };
2905     if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2906 mocchiut 1.1 //
2907 mocchiut 1.2 glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
2908     glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
2909     glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
2910     glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());
2911     glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());
2912     //
2913 mocchiut 1.16 if ( IsDebug() ) printf(" here firstev is %i lastev is %i \n",firstev,lastev);
2914     //
2915 mocchiut 1.2 glrun->SetEV_FROM(firstev);
2916     glrun->SetNEVENTS(lastev-firstev+1);
2917     //
2918     glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
2919     glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
2920     glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
2921     glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());
2922     glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());
2923     glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());
2924     glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());
2925     glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());
2926     glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());
2927     glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());
2928     glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());
2929     glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());
2930     glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());
2931     glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());
2932     glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());
2933     glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());
2934     //
2935     if ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
2936     if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
2937     //
2938     if ( !IsRunAlreadyInserted() ){
2939     //
2940     // glrun->SetID(this->AssignRunID());
2941     glrun->SetID_RUN_FRAG(glrun1->GetID());
2942     glrun->Fill_GL_RUN(conn);
2943 mocchiut 1.1 //
2944 mocchiut 1.2 // set id number
2945 mocchiut 1.1 //
2946 mocchiut 1.2 glrun1->SetID_RUN_FRAG(glrun->GetID());
2947     glrun1->Fill_GL_RUN(conn);
2948 mocchiut 1.1 //
2949     };
2950 mocchiut 1.2 // delete old entry in fragment table
2951     //
2952     glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2953     glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2954 mocchiut 1.1 //
2955 mocchiut 1.2 delete glrun1;
2956 mocchiut 1.1 //
2957     //
2958 mocchiut 1.2 return;
2959 mocchiut 1.1 //
2960     };
2961     //
2962     };
2963     //
2964 mocchiut 1.2 if ( mistrail && ( rtlastev == lastev || chewbacca )) { // look for runtrailer (only when at the end of the file, if at the beginning and the runh is
2965     // missing it no way we can found a piece in the frag table
2966 mocchiut 1.1 //
2967     oss.str("");
2968 mocchiut 1.2 oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN_FRAGMENTS WHERE "
2969 mocchiut 1.1 << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2970     << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2971     << " ID != " << glrun->ID
2972 mocchiut 1.2 << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2973 mocchiut 1.1 //
2974 mocchiut 1.2 if ( IsDebug() ) printf(" look for runtrailer in the fragments table: query is \n %s \n",oss.str().c_str());
2975 mocchiut 1.1 result = conn->Query(oss.str().c_str());
2976     //
2977     if ( !result ) throw -4;
2978     //
2979     row = result->Next();
2980     //
2981 mocchiut 1.2 if ( !row && NoFrag() ){
2982     //
2983     oss.str("");
2984     oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN WHERE "
2985     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2986     << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2987     << " ID != " << glrun->ID
2988     << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2989     //
2990     if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
2991     result = conn->Query(oss.str().c_str());
2992     //
2993     if ( !result ) throw -4;
2994     //
2995     foundinrun = true;
2996     row = result->Next();
2997     //
2998     };
2999 mocchiut 1.1 //
3000 mocchiut 1.2 if ( !row ){
3001     if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
3002     found = false;
3003     } else {
3004     //
3005     found = false; // default value
3006     //
3007 mocchiut 1.16 if ( IsDebug() ) printf(" B Found a possible candidate, checking if it is the good one... \n");
3008 mocchiut 1.1 //
3009 mocchiut 1.2 // if we have both runheader and runtrailer we can check with pkt_counter:
3010 mocchiut 1.1 //
3011 mocchiut 1.2 if ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){
3012     ULong64_t chkpkt = 0;
3013     ULong64_t pktt = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
3014     ULong64_t pkth = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
3015 mocchiut 1.1 //
3016 mocchiut 1.2 chkpkt = pkth + (ULong64_t)((UInt_t)atoll(row->GetField(1))) + 1ULL + 1ULL;
3017 mocchiut 1.1 //
3018 mocchiut 1.2 if ( labs(chkpkt-pktt)<2 ){
3019     //
3020     if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
3021     //
3022     found = true;
3023     //
3024     } else {
3025     //
3026     if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);
3027     //
3028     found = false;
3029     //
3030     };
3031     };
3032     if ( !found && chewbacca ) goto justcheck;
3033     if ( !found ){
3034     //
3035     // if we arrive here we were not able to decide if the two pieces matches using only the pkt counter information, we must check times and obts
3036 mocchiut 1.1 //
3037 mocchiut 1.2 ULong64_t chkpkt1 = 0;
3038     ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
3039     ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
3040     chkpkt1 = labs(orunh1-dbrunt1);
3041 mocchiut 1.1 //
3042 mocchiut 1.2 ULong64_t chkpkt2 = 0;
3043     ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNTRAILER_OBT());
3044     ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
3045     chkpkt2 = labs(orunh2-dbrunt2);
3046 mocchiut 1.1 //
3047 mocchiut 1.2 ULong64_t chkpkt3 = 0;
3048     ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNTRAILER_TIME());
3049     ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
3050     chkpkt3 = labs(orunh3-dbrunt3);
3051 mocchiut 1.1 //
3052 mocchiut 1.2 if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
3053     //
3054     if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
3055     //
3056     found = true;
3057     //
3058     } else {
3059     //
3060     if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
3061     //
3062     found = false;
3063     //
3064     };
3065 mocchiut 1.1 };
3066     };
3067 mocchiut 1.2 //
3068     if ( found ){
3069     //
3070     // we have found the missing piece, glue the two together, merge the informations, fill the gl_run table (check first runs do not exists), delete entry in frag table
3071     //
3072     if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
3073     //
3074     if ( foundinrun ){
3075     glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3076     glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
3077     };
3078 mocchiut 1.1 //
3079 mocchiut 1.2 GL_RUN *glrun1 = new GL_RUN();
3080 mocchiut 1.1 //
3081 mocchiut 1.2 // UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
3082 mocchiut 1.1 //
3083 mocchiut 1.2 oss.str("");
3084     oss << " ID="<<row->GetField(0)<<";";
3085     //
3086     glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runtrailer infos
3087 mocchiut 1.1 //
3088 mocchiut 1.2 // merge infos
3089 mocchiut 1.1 //
3090 mocchiut 1.2 UInt_t apkt = PKT(glrun->GetRUNTRAILER_PKT());
3091     ULong64_t aobt = OBT(glrun->GetRUNTRAILER_OBT());
3092     UInt_t bpkt = PKT(glrun1->GetRUNHEADER_PKT());
3093     ULong64_t bobt = OBT(glrun1->GetRUNHEADER_OBT());
3094     if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
3095     TTree *T= 0;
3096     T = (TTree*)file->Get("Physics");
3097     if ( !T || T->IsZombie() ) throw -16;
3098     EventHeader *eh = 0;
3099     PscuHeader *ph = 0;
3100     T->SetBranchAddress("Header", &eh);
3101     while ( apkt > bpkt && aobt > bobt && lastev > 0 ){
3102     T->GetEntry(lastev);
3103     ph = eh->GetPscuHeader();
3104     apkt = PKT(ph->GetCounter());
3105     aobt = OBT(ph->GetOrbitalTime());
3106     lastev--;
3107 mocchiut 1.21 if ( PEDANTIC && !RELAXED) throw -72;
3108 mocchiut 1.2 };
3109     if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
3110     //
3111     glrun->SetEV_TO(lastev);
3112     glrun->SetNEVENTS(lastev-firstev+1);
3113     glrun->SetPKT_COUNTER(glrun1->GetPKT_COUNTER());
3114     glrun->SetPKT_READY_COUNTER(glrun1->GetPKT_READY_COUNTER());
3115     glrun->SetRUNTRAILER_TIME(glrun1->GetRUNTRAILER_TIME());
3116     glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());
3117     glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());
3118     //
3119     glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());
3120     glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());
3121     glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());
3122     glrun1->SetCOMPILATIONTIMESTAMP(glrun->GetCOMPILATIONTIMESTAMP());
3123     glrun1->SetFAV_WRK_SCHEDULE(glrun->GetFAV_WRK_SCHEDULE());
3124     glrun1->SetEFF_WRK_SCHEDULE(glrun->GetEFF_WRK_SCHEDULE());
3125     glrun1->SetPRH_VAR_TRG_MODE_A(glrun->GetPRH_VAR_TRG_MODE_A());
3126     glrun1->SetPRH_VAR_TRG_MODE_B(glrun->GetPRH_VAR_TRG_MODE_B());
3127     glrun1->SetACQ_BUILD_INFO(glrun->GetACQ_BUILD_INFO());
3128     glrun1->SetACQ_VAR_INFO(glrun->GetACQ_VAR_INFO());
3129     glrun1->SetRM_ACQ_AFTER_CALIB(glrun->GetRM_ACQ_AFTER_CALIB());
3130     glrun1->SetRM_ACQ_SETTING_MODE(glrun->GetRM_ACQ_SETTING_MODE());
3131     glrun1->SetTRK_CALIB_USED(glrun->GetTRK_CALIB_USED());
3132     glrun1->SetCAL_DSP_MASK(glrun->GetCAL_DSP_MASK());
3133     glrun1->SetLAST_TIMESYNC(glrun->GetLAST_TIMESYNC());
3134     glrun1->SetOBT_TIMESYNC(glrun->GetOBT_TIMESYNC());
3135     //
3136     if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ) glrun1->SetPHYSENDRUN_MASK_S3S2S12(glrun->GetPHYSENDRUN_MASK_S3S2S12());
3137     if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) glrun1->SetPHYSENDRUN_MASK_S11CRC(glrun->GetPHYSENDRUN_MASK_S11CRC());
3138     //
3139     if ( !IsRunAlreadyInserted() ){
3140     //
3141     // glrun->SetID(this->AssignRunID());
3142 mocchiut 1.1 //
3143 mocchiut 1.2 glrun->SetID_RUN_FRAG(glrun1->GetID());
3144     glrun->Fill_GL_RUN(conn);
3145 mocchiut 1.1 //
3146 mocchiut 1.2 // set id number
3147 mocchiut 1.1 //
3148 mocchiut 1.2 glrun1->SetID_RUN_FRAG(glrun->GetID());
3149     glrun1->Fill_GL_RUN(conn);
3150 mocchiut 1.1 //
3151     };
3152 mocchiut 1.2 //
3153     // delete old entries in fragment table
3154     //
3155     glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3156     glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3157     //
3158     delete glrun1;
3159     //
3160     return;
3161     //
3162 mocchiut 1.1 };
3163 mocchiut 1.2 //
3164 mocchiut 1.1 };
3165     //
3166 mocchiut 1.2 justcheck:
3167     //
3168     if ( !found ){
3169 mocchiut 1.1 //
3170 mocchiut 1.2 if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");
3171 mocchiut 1.1 //
3172 mocchiut 1.2 // not found, has this run already inserted in the GL_RUN or in the GL_RUN_FRAGMENTS table?
3173 mocchiut 1.1 //
3174     oss.str("");
3175 mocchiut 1.21 oss << " SELECT ID,ID_ROOT_L0 FROM GL_RUN WHERE "
3176 mocchiut 1.2 << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3177     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3178     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3179     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3180     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3181     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3182     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3183     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3184     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3185     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3186     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3187     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3188     << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3189 mocchiut 1.1 //
3190 mocchiut 1.2 if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3191     result = conn->Query(oss.str().c_str());
3192 mocchiut 1.1 //
3193 mocchiut 1.2 if ( !result ) throw -4;
3194 mocchiut 1.1 //
3195 mocchiut 1.2 row = result->Next();
3196 mocchiut 1.1 //
3197 mocchiut 1.2 if ( row ){
3198 mocchiut 1.21 //
3199     // we end up here if chewbacca and we have RH---| small gap |---RT, in this case the two pieces are attached and moved to GL_RUN. We are now processing the
3200     // "small gap" piece... we recognize this since: we have two entries from this query, the pkt number is consistent with our pkt number.
3201     //
3202     // 090112 [8RED (-70): RUN ALREADY INSERTED]
3203     //
3204     Bool_t OK = false;
3205     UInt_t IDRL2A = 0;
3206     UInt_t IDRL2B = 0;
3207     if ( chewbacca ){
3208     if ( result->GetRowCount() == 2 ){
3209     IDRL2A = (UInt_t)atoll(row->GetField(0));
3210     UInt_t IDRL0A = (UInt_t)atoll(row->GetField(1));
3211     row = result->Next();
3212     IDRL2B = (UInt_t)atoll(row->GetField(0));
3213     UInt_t IDRL0B = (UInt_t)atoll(row->GetField(1));
3214     if ( IsDebug() ) printf(" IDRL0A %u B %u IDRL2A %u B %u \n",IDRL0A,IDRL0B,IDRL2A,IDRL2B);
3215     if ( IDRL0A == IDRL0B ){
3216     TSQLResult *result2 = 0;
3217     TSQLRow *row2 = 0;
3218     oss.str("");
3219     oss << "select PKT_NUMBER_FINAL from ROOT_TABLE_MERGING where REAL_TIME_INIT<" << chrtinit << " order by REAL_TIME_INIT desc limit 1;";
3220     if ( IsDebug() ) printf(" Check if we are in the case RH---| small gap |---RT: query is \n %s \n",oss.str().c_str());
3221     result2 = conn->Query(oss.str().c_str());
3222     //
3223     if ( !result2 ) throw -4;
3224     //
3225     row2 = result2->Next();
3226     //
3227     if ( row2 ){
3228     UInt_t PKA = (UInt_t)atoll(row2->GetField(0));
3229     delete result2;
3230     oss.str("");
3231     oss << "select PKT_NUMBER_INIT from ROOT_TABLE_MERGING where REAL_TIME_INIT>" << chrtinit << " order by REAL_TIME_INIT asc limit 1;";
3232     if ( IsDebug() ) printf(" Check if we are in the case RH---| small gap |---RT: query is \n %s \n",oss.str().c_str());
3233     result2 = conn->Query(oss.str().c_str());
3234     //
3235     if ( !result2 ) throw -4;
3236     //
3237     row2 = result2->Next();
3238     //
3239     if ( row2 ){
3240     UInt_t PKB = (UInt_t)atoll(row2->GetField(0));
3241     //
3242     if ( IsDebug() ) printf(" PKT(PKA) + 1 %llu == runheaderpkt %llu && PKB = runtrailer %llu + 1 %llu \n",PKT(PKA)+1LL, PKT(glrun->GetRUNHEADER_PKT()),PKT(PKB), PKT(glrun->GetRUNTRAILER_PKT())+1LL);
3243     if ( PKT(PKA)+1LL == PKT(glrun->GetRUNHEADER_PKT()) && PKT(PKB) == PKT(glrun->GetRUNTRAILER_PKT())+1LL ){
3244     if ( IsDebug() ) printf(" Ok, we are in the case: RH---| small gap |---RT \n");
3245     OK = true;
3246     };
3247     };
3248     };
3249     };
3250     };
3251     };
3252     if ( OK ){
3253     //
3254     // this is the case in which we must insert a piece of run between two fragments in the GL_RUN table
3255     //
3256     // we have to update with runheader/trailer infos our run and we have to change the ROOT_ID_FRAG of the header piece ( 1/2 2/1 must become 1/3 3/2 2/1 )
3257     //
3258     GL_RUN *glA = new GL_RUN();
3259     glA->Query_GL_RUN(IDRL2A,conn);
3260     //
3261     if ( glA->GetACQ_BUILD_INFO() != 0 ){
3262     //
3263     // the first piece contains a good runheader we can update all the other runs with correct infos!
3264     //
3265     oss.str("");
3266     oss << "UPDATE GL_RUN_FRAGMENTS SET "
3267     << " RUNHEADER_TIME=" << glA->GetRUNHEADER_TIME()<< " , "
3268     << " RUNHEADER_OBT=" << glA->GetRUNHEADER_OBT()<< " , "
3269     << " RUNHEADER_PKT=" << glA->GetRUNHEADER_PKT()<< " , "
3270     << " COMPILATIONTIMESTAMP=" << glA->GetCOMPILATIONTIMESTAMP()<< " , "
3271     << " FAV_WRK_SCHEDULE=" << glA->GetFAV_WRK_SCHEDULE()<< " , "
3272     << " EFF_WRK_SCHEDULE=" << glA->GetEFF_WRK_SCHEDULE()<< " , "
3273     << " PRH_VAR_TRG_MODE_A=" << glA->GetPRH_VAR_TRG_MODE_A()<< " , "
3274     << " PRH_VAR_TRG_MODE_B=" << glA->GetPRH_VAR_TRG_MODE_B()<< " , "
3275     << " ACQ_BUILD_INFO=" << glA->GetACQ_BUILD_INFO()<< " , "
3276     << " ACQ_VAR_INFO=" << glA->GetACQ_VAR_INFO()<< " , "
3277     << " RM_ACQ_AFTER_CALIB=" << glA->GetRM_ACQ_AFTER_CALIB()<< " , "
3278     << " RM_ACQ_SETTING_MODE=" << glA->GetRM_ACQ_SETTING_MODE()<< " , "
3279     << " TRK_CALIB_USED=" << glA->GetTRK_CALIB_USED()<< " , "
3280     << " CAL_DSP_MASK=" << glA->GetCAL_DSP_MASK()<< " , "
3281     << " LAST_TIMESYNC=" << glA->GetLAST_TIMESYNC()<< " , ";
3282     //
3283     if ( glA->GetPHYSENDRUN_MASK_S3S2S12() )
3284     oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12() << " , ";
3285     if ( glA->GetPHYSENDRUN_MASK_S11CRC() )
3286     oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC() << " , ";
3287     //
3288     oss << " OBT_TIMESYNC=" << glA->GetOBT_TIMESYNC();
3289     oss << " WHERE ID=" << glrun->GetID() << ";";
3290     if ( IsDebug() ) printf(" update with correct infos: %s\n",oss.str().c_str());
3291     conn->Query(oss.str().c_str());
3292     //
3293     } else {
3294     //
3295     // sig no runheader, let set anyway what is possible...
3296     //
3297     oss.str("");
3298     oss << "UPDATE GL_RUN_FRAGMENTS SET "
3299     << " RUNHEADER_TIME=" << glA->GetRUNHEADER_TIME()<< " , ";
3300     //
3301     if ( glA->GetPHYSENDRUN_MASK_S3S2S12() )
3302     oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , ";
3303     if ( glA->GetPHYSENDRUN_MASK_S11CRC() )
3304     oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , ";
3305     //
3306     oss << " RUNHEADER_OBT=" << glA->GetRUNHEADER_OBT()<< " , "
3307     << " RUNHEADER_PKT=" << glA->GetRUNHEADER_PKT();
3308     oss << " WHERE ID=" << glrun->GetID() << ";";
3309     if ( IsDebug() ) printf(" update with correct infos2: %s\n",oss.str().c_str());
3310     conn->Query(oss.str().c_str());
3311     };
3312     //
3313     // update runheader ROOT_ID_FRAG
3314     //
3315     oss.str("");
3316     oss << "UPDATE GL_RUN SET ID_RUN_FRAG = " << glrun->GetID() << " where ID = " << IDRL2A << ";";
3317     if ( IsDebug() ) printf(" update gl_run to have cross indexing: %s\n",oss.str().c_str());
3318     conn->Query(oss.str().c_str());
3319     //
3320     // now let's look for runtrailer if any in the last run
3321     //
3322     glA->Query_GL_RUN(IDRL2B,conn);
3323     //
3324     if ( glA->GetPKT_READY_COUNTER() != 0 ){
3325     //
3326     // the first piece contains a good runtrailer we can update all the other runs with correct infos!
3327     //
3328     oss.str("");
3329     oss << "UPDATE GL_RUN_FRAGMENTS SET "
3330     << " RUNTRAILER_TIME=" << glA->GetRUNTRAILER_TIME()<< " , "
3331     << " RUNTRAILER_OBT=" << glA->GetRUNTRAILER_OBT()<< " , "
3332     << " RUNTRAILER_PKT=" << glA->GetRUNTRAILER_PKT()<< " , "
3333     << " PKT_COUNTER=" << glA->GetPKT_COUNTER()<< " , ";
3334     //
3335     if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ){
3336     oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
3337     if ( glA->GetPHYSENDRUN_MASK_S11CRC() ) {
3338     oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
3339     //
3340     oss << " PKT_READY_COUNTER=" << glA->GetPKT_READY_COUNTER()
3341     << " WHERE ID=" << glrun->GetID() << ";";
3342     if ( IsDebug() ) printf(" update with correct trailer infos: %s\n",oss.str().c_str());
3343     conn->Query(oss.str().c_str());
3344     //
3345     } else {
3346     //
3347     // sig no runtrailer, let set anyway what is possible...
3348     //
3349     oss.str("");
3350     oss << "UPDATE GL_RUN_FRAGMENTS SET "
3351     << " RUNTRAILER_TIME=" << glA->GetRUNTRAILER_TIME()<< " , "
3352     << " RUNTRAILER_OBT=" << glA->GetRUNTRAILER_OBT()<< " , ";
3353     //
3354     if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ){
3355     oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
3356     if ( glA->GetPHYSENDRUN_MASK_S11CRC() ){
3357     oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
3358     //
3359     oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()
3360     << " WHERE ID=" << glrun->GetID() << ";";
3361     if ( IsDebug() ) printf(" update with correct trailer infos2: %s\n",oss.str().c_str());
3362     conn->Query(oss.str().c_str());
3363     };
3364     //
3365     UInt_t myi = glrun->GetID();
3366     oss.str("");
3367     oss << " ID= "<< myi;
3368     //
3369     glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);
3370     //
3371     // fill the new run in GL_RUN
3372     //
3373     glrun->SetID_RUN_FRAG(IDRL2B);
3374     glrun->Fill_GL_RUN(conn);
3375     glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3376 mocchiut 1.23 delete glA;
3377 mocchiut 1.21 //
3378     } else {
3379     //
3380     // is just a repetition
3381     //
3382     if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");
3383     if ( PEDANTIC ) throw -70;
3384     };
3385     //
3386 mocchiut 1.2 } else {
3387     if ( NoFrag() ){
3388     glrun->SetID_RUN_FRAG(glrun->GetID());
3389     glrun->Fill_GL_RUN(conn);
3390     glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3391     };
3392 mocchiut 1.1 };
3393     };
3394     }; // EEE
3395     //
3396     return;
3397     };
3398    
3399    
3400     /**
3401     * Handle run without header or trailer
3402     **/
3403     void PamelaDBOperations::HandleMissingHoT(Bool_t mishead, Bool_t mistrail, UInt_t firstev, UInt_t lastev){
3404     //
3405     //
3406     // is the piece of run good (no other packets inside)?
3407     //
3408     if ( !this->IsRunConsistent(mishead,mistrail,firstev,lastev)){
3409     //
3410     // if not, handle other pieces and continue with the first one
3411     //
3412     if ( IsDebug() ) printf("The run is not consistent, it contains non-physics packets! The run has been handled \n");
3413     //
3414     } else {
3415     //
3416     this->FillClass(mishead,mistrail,firstev,lastev);
3417     //
3418     if ( !IsRunAlreadyInserted() ){
3419     glrun->SetID(this->AssignRunID());
3420     glrun->SetID_RUN_FRAG(0);
3421     glrun->Fill_GL_RUN(conn); // it'ok we arrive here only inside a file hence in the middle of the runs...
3422 mocchiut 1.16 };
3423 mocchiut 1.1 //
3424     };
3425     //
3426     return;
3427     };
3428    
3429     /**
3430     *
3431     * check if we have non-physics packets inside the run
3432     *
3433     */
3434     Bool_t PamelaDBOperations::IsRunConsistent(Bool_t mishead, Bool_t mistrail, UInt_t &firstev, UInt_t &lastev){
3435     //
3436     EventCounter *code=0;
3437     //
3438     UInt_t nevent = 0;
3439     UInt_t checkfirst = 0;
3440     UInt_t checklast = 0;
3441     UInt_t firstentry = 0;
3442     UInt_t lastentry = 0;
3443     UInt_t firstTime = 0;
3444     UInt_t lastTime = 0;
3445     UInt_t firstPkt = 0;
3446     UInt_t lastPkt = 0;
3447     UInt_t firstObt = 0;
3448     UInt_t lastObt = 0;
3449     //
3450     pcksList packetsNames;
3451     pcksList::iterator Iter;
3452     getPacketsNames(packetsNames);
3453     //
3454     TTree *T= 0;
3455     T =(TTree*)file->Get("Physics");
3456     if ( !T || T->IsZombie() ) throw -16;
3457     EventHeader *eh = 0;
3458     PscuHeader *ph = 0;
3459     T->SetBranchAddress("Header", &eh);
3460     nevent = T->GetEntries();
3461     //
3462     //
3463     if ( firstev == lastev+1 || lastev == firstev ) { // no events inside the run!
3464     //if ( firstev <= lastev+1 ) { // no events inside the run!
3465     if ( IsDebug() ) printf(" Checking but no events in the run! \n");
3466 mocchiut 1.16 firstev = lastev+1; // this is necessary for files with no Physics entries, should have no influence on other files
3467 mocchiut 1.1 // return true is correct
3468     return(true);
3469     //
3470     } else {
3471     //
3472     T->GetEntry(firstev);
3473     code = eh->GetCounter();
3474     checkfirst = 0;
3475     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3476 mocchiut 1.2 if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
3477     };
3478 mocchiut 1.1 if ( IsDebug() ) printf(" Check first is %i firstev is %i\n",checkfirst,firstev);
3479     //
3480     T->GetEntry(lastev);
3481     code = eh->GetCounter();
3482     checklast = 0;
3483     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3484 mocchiut 1.2 if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
3485     };
3486 mocchiut 1.1 if ( IsDebug() ) printf(" Check last is %i lastev is %i\n",checklast,lastev);
3487     //
3488     if ( checkfirst == checklast ){
3489     //
3490     if ( IsDebug() ) printf(" No packets but physics inside the run, I will consider it as good\n");
3491     //
3492     return(true);
3493     //
3494     } else {
3495     //
3496 mocchiut 1.10 if ( IsDebug() ) printf(" There are no-physics packets inside the run!\n");
3497 mocchiut 1.1 //
3498     // HERE WE MUST HANDLE THAT RUNS AND GO BACK
3499     //
3500 mocchiut 1.2 // if ( IsDebug() ) printf(" Never seen this case, try to handle it anyway, it was throw -95\n");
3501 mocchiut 1.1 //
3502     Bool_t emptyruns = false;
3503     UInt_t check = 0;
3504     UInt_t lastevtemp = lastev;
3505     UInt_t firstevno = firstev;
3506 mocchiut 1.10 UInt_t rhchko=0;
3507     UInt_t rhchk=0;
3508 mocchiut 1.1 //
3509     for (UInt_t i=firstev; i<=lastev; i++){
3510     //
3511     T->GetEntry(i);
3512     code = eh->GetCounter();
3513     //
3514     check = 0;
3515     //
3516 mocchiut 1.10
3517     // if we have a runheader set lastev then exit
3518     //
3519 mocchiut 1.1 for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3520     if ( strcmp(*Iter,"Physics") ) check += code->Get(GetPacketType(*Iter));
3521     };
3522 mocchiut 1.10 // check here if we have a runheader
3523     rhchko = rhchk;
3524     rhchk = code->Get(GetPacketType("RunHeader"));
3525 mocchiut 1.1 //
3526     if ( checkfirst < check || i == lastev ){
3527     //
3528     firstentry = firstevno;
3529     //
3530     if ( checkfirst < check ){
3531     lastentry = i-1;
3532     } else {
3533     lastentry = i;
3534     };
3535     //
3536     if ( IsDebug() ) printf(" Run between %i and %i entries\n",firstentry,lastentry);
3537     //
3538     glrun->SetEV_FROM(firstentry);
3539     glrun->SetEV_TO(lastentry);
3540     if ( lastentry == (firstentry-1) ){ // no physics packets inside physics run with no runheader no runtrailer
3541     if ( IsDebug() ) printf(" no physics packets inside physics run with no runheader no runtrailer\n");
3542     lastentry--;
3543     };
3544     glrun->SetNEVENTS(lastentry-firstentry+1);
3545     //
3546     glrun->Set_GL_RUNH0();
3547     glrun->Set_GL_RUNT0();
3548     //
3549     glrun->SetLAST_TIMESYNC(0);
3550     glrun->SetOBT_TIMESYNC(0);
3551     //
3552     T->GetEntry(firstentry);
3553     ph = eh->GetPscuHeader();
3554     firstObt = ph->GetOrbitalTime();
3555     firstTime = this->GetAbsTime(firstObt);
3556     firstPkt = ph->GetCounter();
3557     //
3558     T->GetEntry(lastentry);
3559     ph = eh->GetPscuHeader();
3560     lastObt = ph->GetOrbitalTime();
3561     lastTime = this->GetAbsTime(lastObt);
3562     lastPkt = ph->GetCounter();
3563     //
3564     glrun->SetRUNHEADER_PKT(firstPkt);
3565 mocchiut 1.2 glrun->SetRUNTRAILER_PKT(lastPkt);
3566     //
3567     glrun->SetRUNHEADER_OBT(firstObt);
3568     glrun->SetRUNTRAILER_OBT(lastObt);
3569     //
3570     if ( IsDebug() ) printf(" A THIS RUN: RUNHEADER_OBT %u RUNTRAILER_OBT %u RUNHEADER_PKT %u RUNTRAILER_PKT %u \n", glrun->GetRUNHEADER_OBT(),glrun->GetRUNTRAILER_OBT(),glrun->GetRUNHEADER_PKT(),glrun->GetRUNTRAILER_PKT());
3571     if ( firstev == firstentry && !emptyruns && !mishead ){
3572     glrun->Set_GL_RUNH(runh,phh);
3573     firstTime = this->GetAbsTime(phh->GetOrbitalTime());
3574     if ( IsDebug() ) printf(" We have the runheader \n");
3575     };
3576     if ( lastev == i && !mistrail ){
3577     glrun->Set_GL_RUNT(runt,pht);
3578     lastTime = this->GetAbsTime(pht->GetOrbitalTime());
3579     if ( IsDebug() ) printf(" We have the runtrailer \n");
3580     };
3581     //
3582     if ( IsDebug() ) printf(" B THIS RUN: RUNHEADER_OBT %u RUNTRAILER_OBT %u RUNHEADER_PKT %u RUNTRAILER_PKT %u \n", glrun->GetRUNHEADER_OBT(),glrun->GetRUNTRAILER_OBT(),glrun->GetRUNHEADER_PKT(),glrun->GetRUNTRAILER_PKT());
3583     if ( lastentry == (firstentry-2) ){ // no events in the run
3584     emptyruns = true;
3585     if ( IsDebug() ) printf(" No events in the run \n");
3586     lastTime = firstTime;
3587     if ( (UInt_t)firstTime == this->GetAbsTime(phh->GetOrbitalTime()) ){
3588     lastObt = glrun->RUNHEADER_OBT;
3589     lastPkt = glrun->RUNHEADER_PKT;
3590     } else {
3591     lastObt = firstObt;
3592     lastPkt = firstPkt;
3593     };
3594     glrun->SetRUNTRAILER_PKT(lastPkt);
3595     glrun->SetRUNTRAILER_OBT(lastObt);
3596     lastentry++;
3597     };
3598     //
3599     this->SetCommonGLRUN(firstTime,lastTime);
3600     this->SetPhysEndRunVariables();
3601     //
3602     if ( chminentry == firstentry ){ // EEE
3603     if ( IsDebug() ) printf(" Inside isrunconsistent found a fragment of run at the beginning of the file, put it in the fragment table \n");
3604     //
3605     // this->HandleRunFragments(true,mistrail,firstentry,lastentry); // cannot call it here since it enters a loop which will destroy the already stored variables if we arrive here from HandleRunFragments
3606     //
3607    
3608     mishead = true;
3609    
3610    
3611     UInt_t rhfirstev = firstentry;
3612     // UInt_t rtlastev = lastentry;
3613     Bool_t found = false;
3614     Bool_t foundinrun = false;
3615     //
3616     TSQLResult *result = 0;
3617     TSQLRow *row = 0;
3618     //
3619     stringstream oss;
3620     oss.str("");
3621     //
3622     // we have now the good first piece of a run, fill the glrun object
3623     //
3624     // if ( rhfirstev != firstev && !mishead ) mishead = true;
3625     // if ( rtlastev != lastev && !mistrail ) mistrail = true;
3626     //
3627     // this->FillClass(mishead,mistrail,firstev,lastev);
3628     //
3629     if ( IsDebug() ) printf("zz The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
3630     if ( IsDebug() ) printf("zz C THIS RUN: RUNHEADER_OBT %u RUNTRAILER_OBT %u RUNHEADER_PKT %u RUNTRAILER_PKT %u \n", glrun->GetRUNHEADER_OBT(),glrun->GetRUNTRAILER_OBT(),glrun->GetRUNHEADER_PKT(),glrun->GetRUNTRAILER_PKT());
3631     //
3632     // First of all insert the run in the fragment table...
3633     //
3634     oss.str("");
3635     oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
3636     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3637     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3638     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3639     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3640     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3641     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3642     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3643     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3644     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3645     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3646     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3647     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3648     << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3649     //
3650     if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3651     result = conn->Query(oss.str().c_str());
3652     //
3653     if ( !result ) throw -4;
3654     //
3655     row = result->Next();
3656     //
3657     if ( !row ){
3658     //
3659     // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
3660     //
3661     if ( IsDebug() ) printf(" The run is new \n");
3662     if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
3663     //
3664     glrun->SetID(this->AssignRunID());
3665     glrun->SetID_RUN_FRAG(0);
3666     glrun->Fill_GL_RUN_FRAGMENTS(conn);
3667     //
3668     } else {
3669     if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
3670     if ( PEDANTIC ) throw -69;
3671     // return;
3672     };
3673     //
3674     if ( chewbacca && mishead && mistrail ) goto zjustcheck;
3675     //
3676     // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
3677     //
3678     if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
3679     // missing it no way we can found a piece in the frag table
3680     //
3681     oss.str("");
3682     oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "
3683     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3684     << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3685     << " ID != " << glrun->ID
3686     << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
3687     //
3688     if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());
3689     result = conn->Query(oss.str().c_str());
3690     //
3691     if ( !result ) throw -4;
3692     //
3693     row = result->Next();
3694     //
3695     if ( !row && NoFrag() ){
3696     //
3697     oss.str("");
3698     oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
3699     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3700     << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3701     << " ID != " << glrun->ID
3702     << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
3703     //
3704     if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
3705     result = conn->Query(oss.str().c_str());
3706     //
3707     if ( !result ) throw -4;
3708     //
3709     foundinrun = true;
3710     //
3711     row = result->Next();
3712     //
3713     };
3714     //
3715     if ( !row ){
3716     if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
3717     found = false;
3718     } else {
3719     //
3720     found = false; // default value
3721     //
3722 mocchiut 1.16 if ( IsDebug() ) printf(" C Found a possible candidate, checking if it is the good one... \n");
3723 mocchiut 1.2 //
3724     // if we have both runheader and runtrailer we can check with pkt_counter:
3725     //
3726     if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){
3727     ULong64_t chkpkt = 0;
3728     ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
3729     ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
3730     //
3731     chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;
3732     //
3733     if ( labs(chkpkt-pktt)<2 ){
3734     //
3735     if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
3736     //
3737     found = true;
3738     //
3739     } else {
3740     //
3741     if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);
3742     //
3743     found = false;
3744     //
3745     };
3746     };
3747     if ( !found && chewbacca ) goto zjustcheck;
3748     if ( !found ){
3749     //
3750     // if we arrive here we were not able to decide if the two pieces matches using only the pkt counter information, we must check times and obts
3751     //
3752     ULong64_t chkpkt1 = 0;
3753     ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
3754     ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
3755     chkpkt1 = labs(orunh1-dbrunt1);
3756     //
3757     ULong64_t chkpkt2 = 0;
3758     ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());
3759     ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
3760     chkpkt2 = labs(orunh2-dbrunt2);
3761     //
3762     ULong64_t chkpkt3 = 0;
3763     ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());
3764     ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
3765     chkpkt3 = labs(orunh3-dbrunt3);
3766     //
3767     if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
3768     // if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){
3769     //
3770     if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
3771     //
3772     found = true;
3773     //
3774     } else {
3775     //
3776     if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
3777     //
3778     found = false;
3779     //
3780     };
3781     };
3782     };
3783     //
3784     if ( found ){
3785     //
3786     // we have found the missing piece, glue the two together, merge the informations, fill the gl_run table (check first runs do not exists), delete entry in frag table
3787     //
3788     if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
3789     //
3790     if ( foundinrun ){
3791     glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3792     glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
3793     };
3794     //
3795     GL_RUN *glrun1 = new GL_RUN();
3796     //
3797     // UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
3798     //
3799     oss.str("");
3800     oss << " ID="<<row->GetField(0)<<";";
3801     //
3802     glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos
3803     //
3804     // merge infos
3805     //
3806     UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());
3807     ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
3808     UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
3809     ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
3810     if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
3811     TTree *T= 0;
3812     T = (TTree*)file->Get("Physics");
3813     if ( !T || T->IsZombie() ) throw -16;
3814     EventHeader *eh = 0;
3815     PscuHeader *ph = 0;
3816     T->SetBranchAddress("Header", &eh);
3817     while ( apkt > bpkt && aobt > bobt && firstev < lastev ){
3818     T->GetEntry(firstev);
3819     ph = eh->GetPscuHeader();
3820     bpkt = PKT(ph->GetCounter());
3821     bobt = OBT(ph->GetOrbitalTime());
3822     firstev++;
3823     if ( PEDANTIC ) throw -71;
3824     };
3825     if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
3826     //
3827     glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
3828     glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
3829     glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
3830     glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());
3831     glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());
3832     //
3833     glrun->SetEV_FROM(firstev);
3834     glrun->SetNEVENTS(lastev-firstev+1);
3835     //
3836     glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
3837     glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
3838     glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
3839     glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());
3840     glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());
3841     glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());
3842     glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());
3843     glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());
3844     glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());
3845     glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());
3846     glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());
3847     glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());
3848     glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());
3849     glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());
3850     glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());
3851     glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());
3852     //
3853     if ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
3854     if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
3855     //
3856     if ( !IsRunAlreadyInserted() ){
3857     //
3858     // glrun->SetID(this->AssignRunID());
3859     glrun->SetID_RUN_FRAG(glrun1->GetID());
3860     glrun->Fill_GL_RUN(conn);
3861     //
3862     // set id number
3863     //
3864     glrun1->SetID_RUN_FRAG(glrun->GetID());
3865     glrun1->Fill_GL_RUN(conn);
3866     //
3867     };
3868     // delete old entry in fragment table
3869     //
3870     glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3871     glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3872     //
3873     delete glrun1;
3874     //
3875     //
3876     // return;
3877     //
3878     };
3879     //
3880 mocchiut 1.1 };
3881 mocchiut 1.2 //
3882     //
3883     zjustcheck:
3884     //
3885     if ( !found ){
3886     //
3887     if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");
3888     //
3889     // not found, has this run already inserted in the GL_RUN or in the GL_RUN_FRAGMENTS table?
3890     //
3891     oss.str("");
3892     oss << " SELECT ID FROM GL_RUN WHERE "
3893     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3894     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3895     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3896     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3897     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3898     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3899     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3900     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3901     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3902     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3903     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3904     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3905     << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3906     //
3907     if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3908     result = conn->Query(oss.str().c_str());
3909     //
3910     if ( !result ) throw -4;
3911     //
3912     row = result->Next();
3913     //
3914     if ( row ){
3915     if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");
3916     if ( PEDANTIC ) throw -70;
3917     } else {
3918     if ( NoFrag() ){
3919     glrun->SetID_RUN_FRAG(glrun->GetID());
3920     glrun->Fill_GL_RUN(conn);
3921     glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3922     };
3923     };
3924     }; // EEE
3925 mocchiut 1.1
3926    
3927     } else {
3928 mocchiut 1.2 if ( !IsRunAlreadyInserted() ){
3929     glrun->SetID(this->AssignRunID());
3930     glrun->SetID_RUN_FRAG(0);
3931     glrun->Fill_GL_RUN(conn);
3932     };
3933 mocchiut 1.1 }; // EEE
3934     //
3935     firstevno = lastentry + 1;
3936     //
3937     checkfirst = check;
3938     //
3939     };
3940     //
3941 mocchiut 1.10 if ( i > firstev ){
3942     if ( rhchko != rhchk ){
3943     if ( IsDebug() ) printf("oh oh... we have a runheader! stop here and handle later the remaining piece\n");
3944     lastev = i;
3945     return(false);
3946     };
3947     };
3948     //
3949 mocchiut 1.1 if ( check == checklast && i != lastev ){
3950     lastevtemp = i - 1;
3951     i = lastev - 1;
3952     };
3953     //
3954     };
3955     //
3956     lastev = lastevtemp;
3957     //
3958     return(false);
3959     //
3960     };
3961     };
3962     //
3963     return(false); // should never arrive here
3964     };
3965    
3966     /**
3967     *
3968     * we end up here when we have a runheader and a runtrailer but they seems not belonging to the same run since the number of events does not coincide with the
3969     * number of event written in the runtrailer. We try to split into different runs scanning the physics events from the runheader to the runtrailer and
3970     * looking for non-physics packets inside.
3971     *
3972     */
3973     void PamelaDBOperations::HandleSuspiciousRun(){
3974     //
3975     PacketType *pctp=0;
3976     EventCounter *codt=0;
3977     EventCounter *codh=0;
3978     EventCounter *code=0;
3979     UInt_t firstev = 0;
3980     UInt_t lastev = 0;
3981     UInt_t nevent = 0;
3982     UInt_t checkfirst = 0;
3983     UInt_t checklast = 0;
3984     UInt_t firstentry = 0;
3985     UInt_t lastentry = 0;
3986     UInt_t firstTime = 0;
3987     UInt_t lastTime = 0;
3988     UInt_t firstPkt = 0;
3989     UInt_t lastPkt = 0;
3990     UInt_t firstObt = 0;
3991     UInt_t lastObt = 0;
3992     //
3993     pcksList packetsNames;
3994     pcksList::iterator Iter;
3995     getPacketsNames(packetsNames);
3996     //
3997     TTree *rh=0;
3998     rh = (TTree*)file->Get("RunHeader");
3999     if ( !rh || rh->IsZombie() ) throw -17;
4000     TTree *T=0;
4001     T =(TTree*)file->Get("Physics");
4002     if ( !T || T->IsZombie() ) throw -16;
4003     EventHeader *eh = 0;
4004     PscuHeader *ph = 0;
4005     T->SetBranchAddress("Header", &eh);
4006     nevent = T->GetEntries();
4007     //
4008     codt = eht->GetCounter();
4009     codh = ehh->GetCounter();
4010     firstev = codh->Get(pctp->Physics);
4011     lastev = codt->Get(pctp->Physics)-1;
4012     if ( IsDebug() ) printf(" From the current runheader firstev is %u from the runtrailer lastev is %u \n",firstev,lastev);
4013     //
4014     if ( firstev == lastev+1 ) { // no events inside the run!
4015     if ( IsDebug() ) printf(" Checking but no events in the run! \n");
4016     //
4017     this->FillClass();
4018     if ( !IsRunAlreadyInserted() ){
4019     glrun->SetID(this->AssignRunID());
4020     glrun->SetID_RUN_FRAG(0);
4021     glrun->Fill_GL_RUN(conn);
4022     };
4023     //
4024     } else {
4025     //
4026     UInt_t nrunh = 0 + codh->Get(pctp->RunHeader);
4027     UInt_t nrunh1 = 0 + codh->Get(pctp->RunHeader);
4028     T->GetEntry(firstev);
4029     code = eh->GetCounter();
4030     checkfirst = 0;
4031     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
4032 mocchiut 1.2 if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
4033     if ( !strcmp(*Iter,"RunHeader") ) nrunh1++;
4034     };
4035 mocchiut 1.1 if ( IsDebug() ) printf(" Check first is %i \n",checkfirst);
4036     //
4037     T->GetEntry(lastev);
4038     code = eh->GetCounter();
4039     checklast = 0;
4040     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
4041 mocchiut 1.2 if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
4042     };
4043 mocchiut 1.1 if ( IsDebug() ) printf(" Check last is %i \n",checklast);
4044     //
4045     if ( checkfirst == checklast ){
4046     //
4047     if ( IsDebug() ) printf(" No packets but physics inside the run, I will consider it as good\n");
4048     //
4049     this->FillClass();
4050     if ( !IsRunAlreadyInserted() ){
4051     glrun->SetID(this->AssignRunID());
4052     glrun->SetID_RUN_FRAG(0);
4053     glrun->Fill_GL_RUN(conn);
4054     };
4055     //
4056     } else {
4057     //
4058     if ( IsDebug() ) printf(" There are no-physics packets inside the run, try to separate runs \n");
4059     //
4060     Bool_t emptyruns = false;
4061     UInt_t check = 0;
4062     UInt_t firstevno = firstev;
4063     //
4064     for (UInt_t i=firstev; i<=lastev; i++){
4065     //
4066     T->GetEntry(i);
4067     code = eh->GetCounter();
4068     //
4069     check = 0;
4070     //
4071     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
4072     if ( strcmp(*Iter,"Physics") ) check += code->Get(GetPacketType(*Iter));
4073     if ( !strcmp(*Iter,"RunHeader") ) nrunh++;
4074     };
4075     //
4076     if ( checkfirst < check || i == lastev ){
4077     //
4078     firstentry = firstevno;
4079     //
4080     if ( checkfirst < check ){
4081     lastentry = i-1;
4082     } else {
4083     lastentry = i;
4084     };
4085     //
4086     if ( IsDebug() ) printf(" Run between %i and %i entries\n",firstentry,lastentry);
4087     //
4088     glrun->SetEV_FROM(firstentry);
4089     glrun->SetEV_TO(lastentry);
4090     if ( lastentry == (firstentry-1) ){ // no physics packets inside physics run with no runheader no runtrailer
4091     if ( IsDebug() ) printf(" no physics packets inside physics run with no runheader no runtrailer\n");
4092     lastentry--;
4093     };
4094     glrun->SetNEVENTS(lastentry-firstentry+1);
4095     //
4096     glrun->Set_GL_RUNH0();
4097     glrun->Set_GL_RUNT0();
4098     //
4099     glrun->SetLAST_TIMESYNC(0);
4100     glrun->SetOBT_TIMESYNC(0);
4101     //
4102     T->GetEntry(firstentry);
4103     ph = eh->GetPscuHeader();
4104     firstObt = ph->GetOrbitalTime();
4105     firstTime = this->GetAbsTime(firstObt);
4106     firstPkt = ph->GetCounter();
4107     //
4108     T->GetEntry(lastentry);
4109     ph = eh->GetPscuHeader();
4110     lastObt = ph->GetOrbitalTime();
4111     lastTime = this->GetAbsTime(lastObt);
4112     lastPkt = ph->GetCounter();
4113     //
4114     glrun->SetRUNHEADER_PKT(firstPkt);
4115     glrun->SetRUNTRAILER_PKT(lastPkt);
4116     //
4117     glrun->SetRUNHEADER_OBT(firstObt);
4118     glrun->SetRUNTRAILER_OBT(lastObt);
4119     //
4120     if ( IsDebug() ) printf(" AA THIS RUN: RUNHEADER_OBT %u RUNTRAILER_OBT %u RUNHEADER_PKT %u RUNTRAILER_PKT %u \n", glrun->GetRUNHEADER_OBT(),glrun->GetRUNTRAILER_OBT(),glrun->GetRUNHEADER_PKT(),glrun->GetRUNTRAILER_PKT());
4121     //
4122     if ( (firstev == firstentry && !emptyruns) || nrunh == (nrunh1 + 1) ){
4123     rh->GetEntry(nrunh1-1);
4124     phh = ehh->GetPscuHeader();
4125     nrunh1++;
4126     glrun->Set_GL_RUNH(runh,phh);
4127     firstTime = this->GetAbsTime(phh->GetOrbitalTime());
4128     if ( IsDebug() ) printf(" We have the runheader \n");
4129     };
4130     if ( lastev == i && checkfirst == check ){
4131     glrun->Set_GL_RUNT(runt,pht);
4132     lastTime = this->GetAbsTime(pht->GetOrbitalTime());
4133     if ( IsDebug() ) printf(" We have the runtrailer \n");
4134     };
4135     if ( IsDebug() ) printf(" BB THIS RUN: RUNHEADER_OBT %u RUNTRAILER_OBT %u RUNHEADER_PKT %u RUNTRAILER_PKT %u \n", glrun->GetRUNHEADER_OBT(),glrun->GetRUNTRAILER_OBT(),glrun->GetRUNHEADER_PKT(),glrun->GetRUNTRAILER_PKT());
4136     //
4137     if ( lastentry == (firstentry-2) ){ // no events in the run
4138     emptyruns = true;
4139     if ( IsDebug() ) printf(" No events in the run \n");
4140     lastTime = firstTime;
4141     if ( (UInt_t)firstTime == this->GetAbsTime(phh->GetOrbitalTime()) ){
4142     lastObt = glrun->RUNHEADER_OBT;
4143     lastPkt = glrun->RUNHEADER_PKT;
4144     } else {
4145     lastObt = firstObt;
4146     lastPkt = firstPkt;
4147     };
4148     glrun->SetRUNTRAILER_PKT(lastPkt);
4149     glrun->SetRUNTRAILER_OBT(lastObt);
4150     lastentry++;
4151     };
4152     //
4153     this->SetCommonGLRUN(firstTime,lastTime);
4154 mocchiut 1.2 this->SetPhysEndRunVariables();
4155 mocchiut 1.1 //
4156     if ( !IsRunAlreadyInserted() ){
4157     glrun->SetID(this->AssignRunID());
4158     glrun->SetID_RUN_FRAG(0);
4159     glrun->Fill_GL_RUN(conn);
4160     };
4161     //
4162     if ( i == lastev && checkfirst < check ){ // if the last event gives a wrong check...
4163     //
4164     firstentry = i;
4165     //
4166     lastentry = i;
4167     //
4168     if ( IsDebug() ) printf(" Run between %i and %i entries\n",firstentry,lastentry);
4169     //
4170     glrun->SetEV_FROM(firstentry);
4171     glrun->SetEV_TO(lastentry);
4172     glrun->SetNEVENTS(lastentry-firstentry+1);
4173     //
4174     glrun->Set_GL_RUNH0();
4175     //
4176     glrun->SetLAST_TIMESYNC(0);
4177     glrun->SetOBT_TIMESYNC(0);
4178     //
4179     T->GetEntry(firstentry);
4180     ph = eh->GetPscuHeader();
4181     firstObt = ph->GetOrbitalTime();
4182     firstTime = this->GetAbsTime(firstObt);
4183     firstPkt = ph->GetCounter();
4184     //
4185     glrun->SetRUNHEADER_PKT(firstPkt);
4186     //
4187     glrun->SetRUNHEADER_OBT(firstObt);
4188     //
4189     glrun->Set_GL_RUNT(runt,pht);
4190     lastTime = this->GetAbsTime(pht->GetOrbitalTime());
4191     if ( IsDebug() ) printf(" We have the runtrailer \n");
4192     //
4193     this->SetCommonGLRUN(firstTime,lastTime);
4194 mocchiut 1.2 this->SetPhysEndRunVariables();
4195 mocchiut 1.1 //
4196     if ( !IsRunAlreadyInserted() ){
4197     glrun->SetID(this->AssignRunID());
4198     glrun->SetID_RUN_FRAG(0);
4199     glrun->Fill_GL_RUN(conn);
4200     };
4201     };
4202     //
4203     firstevno = lastentry + 1;
4204     //
4205     checkfirst = check;
4206     //
4207     };
4208     //
4209     if ( check == checklast && i != lastev ) i = lastev - 1; // >>>>>>>>>>>>>>>>>>>>>>
4210     //
4211     };
4212     };
4213     };
4214     //
4215     return;
4216     };
4217    
4218    
4219     /**
4220     * Scan calorimeter calibrations packets, fill the GL_CALO_CALIB table
4221     */
4222     Int_t PamelaDBOperations::insertCALO_CALIB(){
4223     //
4224     TSQLResult *result = 0;
4225     TSQLRow *row = 0;
4226     //
4227     stringstream oss;
4228     oss.str("");
4229     //
4230     CalibCalPedEvent *calibCalPed = 0;
4231     TTree *tr = 0;
4232     EventHeader *eh = 0;
4233     PscuHeader *ph = 0;
4234     //
4235     UInt_t nevents = 0;
4236     UInt_t fromtime = 0;
4237     UInt_t totime = 0;
4238     UInt_t obt = 0;
4239     UInt_t pkt = 0;
4240 mocchiut 1.26 Float_t totped = 0.;
4241 mocchiut 1.1 //
4242     tr = (TTree*)file->Get("CalibCalPed");
4243     if ( !tr || tr->IsZombie() ) throw -21;
4244     //
4245     tr->SetBranchAddress("CalibCalPed", &calibCalPed);
4246     tr->SetBranchAddress("Header", &eh);
4247     nevents = tr->GetEntries();
4248     //
4249     if ( !nevents ) return(1);
4250     //
4251     for (UInt_t i=0; i < nevents; i++){
4252     tr->GetEntry(i);
4253     for (UInt_t section = 0; section < 4; section++){
4254     //
4255     if ( calibCalPed->cstwerr[section] ){
4256     valid = 1;
4257     if ( calibCalPed->cperror[section] ) valid = 0;
4258 mocchiut 1.26 //
4259     // check pedestal values for one plane, if all zeros calibration is not valid (calorimeter power problems) [8th data reduction bug, fixed on 25/11/2009 by E.M.]
4260     //
4261     totped = 0.;
4262 mocchiut 1.27 Int_t ns = 0;
4263     if ( section == 2 ) ns = 3;
4264     if ( section == 3 ) ns = 1;
4265     if ( section == 1 ) ns = 2;
4266 mocchiut 1.26 for (UInt_t ss=0; ss<96; ss++){
4267 mocchiut 1.27 totped += fabs(calibCalPed->calped[ns][0][ss]);
4268 mocchiut 1.26 }
4269     if ( totped < 1. ){
4270     if ( IsDebug() ) printf(" Section %i totped %f - No calibration data! Calorimeter power problems? \n",section,totped);
4271     valid = 0;
4272     };
4273     //
4274 mocchiut 1.1 ph = eh->GetPscuHeader();
4275     obt = ph->GetOrbitalTime();
4276     pkt = ph->GetCounter();
4277     fromtime = this->GetAbsTime(ph->GetOrbitalTime());
4278     if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->PKT(pkt) <= upperpkt && this->OBT(obt) >= this->OBT(obtfirst) && this->OBT(obt) <= upperobt ){
4279     //
4280     if ( IsDebug() ) printf(" Calo calibration for section %i at time %u obt %u pkt %u \n",section,fromtime,obt,pkt);
4281     //
4282     // check if the calibration has already been inserted
4283     //
4284     oss.str("");
4285     oss << " SELECT ID FROM GL_CALO_CALIB WHERE "
4286     << " SECTION = "<< section << " AND "
4287     << " BOOT_NUMBER = "<< this->GetBOOTnumber() << " AND "
4288     << " OBT = "<< obt << " AND "
4289     << " PKT = "<< pkt << ";";
4290     //
4291     if ( IsDebug() ) printf(" Check if the calo calibration has already been inserted: query is \n %s \n",oss.str().c_str());
4292     result = conn->Query(oss.str().c_str());
4293     //
4294     if ( !result ) throw -4;
4295     //
4296     row = result->Next();
4297     //
4298     if ( row ){
4299     //
4300     if ( IsDebug() ) printf(" Calo calibration already inserted in the DB\n");
4301     if ( PEDANTIC ) throw -73;
4302     //
4303     } else {
4304     //
4305     // we have to insert a new calibration, check where to place it
4306     //
4307     oss.str("");
4308     oss << " SELECT ID,TO_TIME FROM GL_CALO_CALIB WHERE "
4309     << " SECTION = "<< section << " AND "
4310     << " FROM_TIME < "<< fromtime << " AND "
4311     << " TO_TIME > "<< fromtime << ";";
4312     //
4313     if ( IsDebug() ) printf(" Check where to place the calo calibration: query is \n %s \n",oss.str().c_str());
4314     result = conn->Query(oss.str().c_str());
4315     //
4316     if ( !result ) throw -4;
4317     //
4318     row = result->Next();
4319     //
4320     if ( !row ){
4321     //
4322     // no calibrations in the db contain our calibration
4323     //
4324     if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB for section %i \n",section);
4325     if ( fromtime < 1150871000 ){ //1150866904
4326     if ( IsDebug() ) printf(" First PAMELA flight calibration at time %u \n",fromtime);
4327     fromtime = 0;// the first flight calibration was taken at about 1156429100 s, this line allow to analyze first runs in raw mode
4328     };
4329     //
4330     oss.str("");
4331     oss << " SELECT FROM_TIME FROM GL_CALO_CALIB WHERE "
4332     << " SECTION = "<< section << " AND "
4333     << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
4334     //
4335     if ( IsDebug() ) printf(" Check the upper limit for calibration: query is \n %s \n",oss.str().c_str());
4336     result = conn->Query(oss.str().c_str());
4337     //
4338     if ( !result ) throw -4;
4339     //
4340     row = result->Next();
4341     if ( !row ){
4342     totime = numeric_limits<UInt_t>::max();
4343     } else {
4344     totime = (UInt_t)atoll(row->GetField(0));
4345     };
4346     //
4347     } else {
4348     //
4349     // determine upper and lower limits and make space for the new calibration
4350     //
4351     totime = (UInt_t)atoll(row->GetField(1));
4352     //
4353     oss.str("");
4354     oss << " UPDATE GL_CALO_CALIB SET "
4355     << " TO_TIME = "<< fromtime << " WHERE " // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
4356     << " ID = "<< row->GetField(0) << ";";
4357     //
4358     if ( IsDebug() ) printf(" Make space for the new calibration: query is \n %s \n",oss.str().c_str());
4359     result = conn->Query(oss.str().c_str());
4360     //
4361     if ( !result ) throw -4;
4362     //
4363     };
4364     //
4365     oss.str("");
4366     oss << " INSERT INTO GL_CALO_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,SECTION,OBT,PKT,BOOT_NUMBER,VALIDATION) "
4367     << " VALUES (NULL,' "
4368     << idroot << "','"
4369     << i << "','"
4370     << fromtime << "','"
4371     << totime << "','"
4372     << section << "','"
4373     << obt << "','"
4374     << pkt << "','"
4375     << this->GetBOOTnumber() << "','"
4376     << valid << "');";
4377     //
4378     if ( IsDebug() ) printf(" Insert the new calibration: query is \n %s \n",oss.str().c_str());
4379     //
4380     result = conn->Query(oss.str().c_str());
4381     //
4382     if ( !result ) throw -4;
4383     //
4384     };
4385     //
4386     } else {
4387     //
4388     if ( IsDebug() ) printf(" Calo calibration for section %i at time %u obt %u pkt %u OUTSIDE the considered interval \n",section,fromtime,obt,pkt);
4389     // if ( PEDANTIC ) throw -74;
4390     //
4391     };
4392     //
4393     };
4394     };
4395     };
4396     //
4397     return(0);
4398     };
4399    
4400    
4401     /**
4402     * Scan calorimeter calibrations packets, fill the GL_CALO_CALIB table
4403     */
4404     Int_t PamelaDBOperations::insertCALOPULSE_CALIB(){
4405     //
4406     TSQLResult *result = 0;
4407     TSQLRow *row = 0;
4408     //
4409     stringstream oss;
4410     oss.str("");
4411     //
4412     oss << " DESCRIBE GL_CALOPULSE_CALIB;";
4413     if ( IsDebug() ) printf(" Check if the GL_CALOPULSE_CALIB table exists: query is \n %s \n",oss.str().c_str());
4414     result = conn->Query(oss.str().c_str());
4415     //
4416     if ( conn->GetErrorCode() ){
4417     if ( IsDebug() ) printf(" The GL_CALOPULSE_CALIB table does not exists! \n");
4418     throw -30;
4419     };
4420     //
4421     // CaloPulse1
4422     //
4423     CalibCalPulse1Event *cp1 = 0;
4424     TTree *tr = 0;
4425     EventHeader *eh = 0;
4426     PscuHeader *ph = 0;
4427     //
4428     UInt_t nevents = 0;
4429     UInt_t fromtime = 0;
4430     UInt_t totime = 0;
4431     UInt_t obt = 0;
4432     UInt_t pkt = 0;
4433     //
4434     tr = (TTree*)file->Get("CalibCalPulse1");
4435     if ( !tr || tr->IsZombie() ) throw -31;
4436     //
4437     tr->SetBranchAddress("CalibCalPulse1", &cp1);
4438     tr->SetBranchAddress("Header", &eh);
4439     nevents = tr->GetEntries();
4440     //
4441 mocchiut 1.26 Float_t totpul = 0.;
4442     //
4443 mocchiut 1.1 if ( nevents > 0 ){
4444     //
4445     for (UInt_t i=0; i < nevents; i++){
4446     tr->GetEntry(i);
4447     for (UInt_t section = 0; section < 4; section++){
4448     //
4449     if ( cp1->pstwerr[section] && cp1->unpackError == 0 ){
4450     valid = 1;
4451     if ( cp1->pperror[section] ) valid = 0;
4452 mocchiut 1.26 //
4453     // check pulse values for one plane, if all zeros calibration is not valid (calorimeter power problems) [8th data reduction bug, fixed on 25/11/2009 by E.M.]
4454     //
4455     totpul = 0.;
4456 mocchiut 1.27 Int_t ns = 0;
4457     if ( section == 2 ) ns = 3;
4458     if ( section == 3 ) ns = 1;
4459     if ( section == 1 ) ns = 2;
4460 mocchiut 1.26 for (UInt_t ss=0; ss<96; ss++){
4461 mocchiut 1.27 totpul += cp1->calpuls[ns][0][ss];
4462 mocchiut 1.26 }
4463     if ( totpul >= 3145632. ){
4464     if ( IsDebug() ) printf(" PULSE1 Section %i totpul %f - No calibration data! Calorimeter power problems? \n",section,totpul);
4465     valid = 0;
4466     };
4467     //
4468 mocchiut 1.1 ph = eh->GetPscuHeader();
4469     obt = ph->GetOrbitalTime();
4470     pkt = ph->GetCounter();
4471     fromtime = this->GetAbsTime(ph->GetOrbitalTime());
4472     if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->PKT(pkt) <= upperpkt && this->OBT(obt) >= this->OBT(obtfirst) && this->OBT(obt) <= upperobt ){
4473     // if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->OBT(obt) >= this->OBT(obtfirst) ){
4474     //
4475     if ( IsDebug() ) printf(" Calo pulse1 calibration for section %i at time %u obt %u pkt %u \n",section,fromtime,obt,pkt);
4476     //
4477     // check if the calibration has already been inserted
4478     //
4479     oss.str("");
4480     oss << " SELECT ID FROM GL_CALOPULSE_CALIB WHERE "
4481     << " SECTION = "<< section << " AND "
4482     << " PULSE_AMPLITUDE = 0 AND "
4483     << " BOOT_NUMBER = "<< this->GetBOOTnumber() << " AND "
4484     << " OBT = "<< obt << " AND "
4485     << " PKT = "<< pkt << ";";
4486     //
4487     if ( IsDebug() ) printf(" Check if the calo pulse1 calibration has already been inserted: query is \n %s \n",oss.str().c_str());
4488     result = conn->Query(oss.str().c_str());
4489     //
4490     if ( !result ) throw -4;
4491     //
4492     row = result->Next();
4493     //
4494     if ( row ){
4495     //
4496     if ( IsDebug() ) printf(" Calo pulse1 calibration already inserted in the DB\n");
4497     if ( PEDANTIC ) throw -75;
4498     //
4499     } else {
4500     //
4501     // we have to insert a new calibration, check where to place it
4502     //
4503     oss.str("");
4504     oss << " SELECT ID,TO_TIME FROM GL_CALOPULSE_CALIB WHERE "
4505     << " SECTION = "<< section << " AND "
4506     << " PULSE_AMPLITUDE = 0 AND "
4507     << " SECTION = "<< section << " AND "
4508     << " FROM_TIME < "<< fromtime << " AND "
4509     << " TO_TIME > "<< fromtime << ";";
4510     //
4511     if ( IsDebug() ) printf(" Check where to place the pulse1 calo calibration: query is \n %s \n",oss.str().c_str());
4512     result = conn->Query(oss.str().c_str());
4513     //
4514     if ( !result ) throw -4;
4515     //
4516     row = result->Next();
4517     //
4518     if ( !row ){
4519     //
4520     // no calibrations in the db contain our calibration
4521     //
4522     if ( IsDebug() ) printf(" Pulse1 calibration with fromtime lower than others to be inserted in the DB for section %i \n",section);
4523     if ( fromtime < 1150871000 ){ //1150866904
4524     if ( IsDebug() ) printf(" First PAMELA flight calibration at time %u \n",fromtime);
4525     fromtime = 0;// the first flight calibration was taken at about 1156429100 s, this line allow to analyze first runs in raw mode
4526     };
4527     //
4528     oss.str("");
4529     oss << " SELECT FROM_TIME FROM GL_CALOPULSE_CALIB WHERE "
4530     << " PULSE_AMPLITUDE = 0 AND "
4531     << " SECTION = "<< section << " AND "
4532     << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
4533     //
4534     if ( IsDebug() ) printf(" Check the upper limit for pulse1 calibration: query is \n %s \n",oss.str().c_str());
4535     result = conn->Query(oss.str().c_str());
4536     //
4537     if ( !result ) throw -4;
4538     //
4539     row = result->Next();
4540     if ( !row ){
4541     totime = numeric_limits<UInt_t>::max();
4542     } else {
4543     totime = (UInt_t)atoll(row->GetField(0));
4544     };
4545     //
4546     } else {
4547     //
4548     // determine upper and lower limits and make space for the new calibration
4549     //
4550     totime = (UInt_t)atoll(row->GetField(1));
4551     //
4552     oss.str("");
4553     oss << " UPDATE GL_CALOPULSE_CALIB SET "
4554     << " TO_TIME = "<< fromtime << " WHERE " // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
4555     << " ID = "<< row->GetField(0) << ";";
4556     //
4557     if ( IsDebug() ) printf(" Make space for the new pulse1 calibration: query is \n %s \n",oss.str().c_str());
4558     result = conn->Query(oss.str().c_str());
4559     //
4560     if ( !result ) throw -4;
4561     //
4562     };
4563     //
4564     oss.str("");
4565     oss << " INSERT INTO GL_CALOPULSE_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,SECTION,PULSED_STRIP,PULSE_AMPLITUDE,OBT,PKT,BOOT_NUMBER,VALIDATION) "
4566     << " VALUES (NULL,' "
4567     << idroot << "','"
4568     << i << "','"
4569     << fromtime << "','"
4570     << totime << "','"
4571     << section << "',NULL,'0','"
4572     << obt << "','"
4573     << pkt << "','"
4574     << this->GetBOOTnumber() << "','"
4575     << valid << "');";
4576     //
4577     if ( IsDebug() ) printf(" Insert the new pulse1 calibration: query is \n %s \n",oss.str().c_str());
4578     //
4579     result = conn->Query(oss.str().c_str());
4580     //
4581     if ( !result ) throw -4;
4582     //
4583     };
4584     //
4585     } else {
4586     //
4587     if ( IsDebug() ) printf(" Pulse1 calo calibration for section %i at time %u obt %u pkt %u OUTSIDE the considered time interval \n",section,fromtime,obt,pkt);
4588     // if ( PEDANTIC ) throw -76;
4589     //
4590     };
4591     //
4592     };
4593     };
4594     };
4595     };
4596     //
4597     // CaloPulse2
4598     //
4599     tr->Reset();
4600     CalibCalPulse2Event *cp2 = 0;
4601     tr = 0;
4602     //
4603     nevents = 0;
4604     fromtime = 0;
4605     totime = 0;
4606     obt = 0;
4607     pkt = 0;
4608     //
4609     tr = (TTree*)file->Get("CalibCalPulse2");
4610     if ( !tr || tr->IsZombie() ) throw -32;
4611     //
4612     tr->SetBranchAddress("CalibCalPulse2", &cp2);
4613     tr->SetBranchAddress("Header", &eh);
4614     nevents = tr->GetEntries();
4615     //
4616     if ( nevents > 0 ){
4617     //
4618     for (UInt_t i=0; i < nevents; i++){
4619     tr->GetEntry(i);
4620     for (UInt_t section = 0; section < 4; section++){
4621     //
4622     if ( cp2->pstwerr[section] && cp2->unpackError == 0 ){
4623     valid = 1;
4624     if ( cp2->pperror[section] ) valid = 0;
4625 mocchiut 1.26 //
4626     // check pulse values for one plane, if all zeros calibration is not valid (calorimeter power problems) [8th data reduction bug, fixed on 25/11/2009 by E.M.]
4627     //
4628     totpul = 0.;
4629 mocchiut 1.27 Int_t ns = 0;
4630     if ( section == 2 ) ns = 3;
4631     if ( section == 3 ) ns = 1;
4632     if ( section == 1 ) ns = 2;
4633 mocchiut 1.26 for (UInt_t ss=0; ss<96; ss++){
4634 mocchiut 1.27 totpul += cp2->calpuls[ns][0][ss];
4635 mocchiut 1.26 }
4636     if ( totpul >= 3145632. ){
4637     if ( IsDebug() ) printf(" PULSE2 Section %i totpul %f - No calibration data! Calorimeter power problems? \n",section,totpul);
4638     valid = 0;
4639     };
4640     //
4641 mocchiut 1.1 ph = eh->GetPscuHeader();
4642     obt = ph->GetOrbitalTime();
4643     pkt = ph->GetCounter();
4644     fromtime = this->GetAbsTime(ph->GetOrbitalTime());
4645     if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->PKT(pkt) <= upperpkt && this->OBT(obt) >= this->OBT(obtfirst) && this->OBT(obt) <= upperobt ){
4646     // if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->OBT(obt) >= this->OBT(obtfirst) ){
4647     //
4648     if ( IsDebug() ) printf(" Calo pulse2 calibration for section %i at time %u obt %u pkt %u \n",section,fromtime,obt,pkt);
4649     //
4650     // check if the calibration has already been inserted
4651     //
4652     oss.str("");
4653     oss << " SELECT ID FROM GL_CALOPULSE_CALIB WHERE "
4654     << " SECTION = "<< section << " AND "
4655     << " PULSE_AMPLITUDE != 0 AND "
4656     << " BOOT_NUMBER = "<< this->GetBOOTnumber() << " AND "
4657     << " OBT = "<< obt << " AND "
4658     << " PKT = "<< pkt << ";";
4659     //
4660     if ( IsDebug() ) printf(" Check if the calo pulse2 calibration has already been inserted: query is \n %s \n",oss.str().c_str());
4661     result = conn->Query(oss.str().c_str());
4662     //
4663     if ( !result ) throw -4;
4664     //
4665     row = result->Next();
4666     //
4667     if ( row ){
4668     //
4669     if ( IsDebug() ) printf(" Calo pulse2 calibration already inserted in the DB\n");
4670     if ( PEDANTIC ) throw -77;
4671     //
4672     } else {
4673     //
4674     // we have to insert a new calibration
4675     //
4676     //
4677     // Determine the amplitude of the pulse
4678     //
4679     UInt_t pampli = 1;
4680     UInt_t pstrip = 0;
4681     UInt_t se = 0;
4682     if ( section == 1 ) se = 2;
4683     if ( section == 2 ) se = 3;
4684     if ( section == 3 ) se = 1;
4685     for (Int_t ii=0;ii<16;ii++){
4686     if ( cp2->calpuls[se][0][ii] > 10000. ){
4687     pampli = 2;
4688     pstrip = ii;
4689     };
4690     };
4691     if ( pampli == 1 ){
4692     Bool_t found = false;
4693     Float_t delta=0.;
4694     UInt_t cstr = 0;
4695     while ( !found && cstr < 16 ){
4696     for (Int_t ii=0;ii<16;ii++){
4697     delta = cp2->calpuls[se][0][ii] - cp2->calpuls[se][0][cstr];
4698     if ( IsDebug() ) printf(" cstr is %u ii is %i delta is %f \n",cstr,ii,delta);
4699     if ( delta > 500. ){
4700     pampli = 1;
4701     pstrip = ii;
4702     found = true;
4703     if ( IsDebug() ) printf(" FOUND cstr is %u ii is %i delta is %f \n",cstr,ii,delta);
4704     };
4705     };
4706     cstr++;
4707     };
4708     if ( !found ) pstrip = 100;
4709     };
4710     if ( IsDebug() ) printf(" The amplitude of the pulser is %u (where 1 = low pulse, 2 = high pulse), pulsed strip is %u \n",pampli,pstrip);
4711     //
4712     // we have to insert a new calibration, check where to place it
4713     //
4714     oss.str("");
4715     oss << " SELECT ID,TO_TIME FROM GL_CALOPULSE_CALIB WHERE "
4716     << " SECTION = "<< section << " AND "
4717     << " PULSE_AMPLITUDE = " << pampli << " AND "
4718     << " SECTION = "<< section << " AND "
4719     << " FROM_TIME < "<< fromtime << " AND "
4720     << " TO_TIME > "<< fromtime << ";";
4721     //
4722     if ( IsDebug() ) printf(" Check where to place the pulse2 calo calibration: query is \n %s \n",oss.str().c_str());
4723     result = conn->Query(oss.str().c_str());
4724     //
4725     if ( !result ) throw -4;
4726     //
4727     row = result->Next();
4728     //
4729     if ( !row ){
4730     //
4731     // no calibrations in the db contain our calibration
4732     //
4733     if ( IsDebug() ) printf(" Pulse2 calibration with fromtime lower than others to be inserted in the DB for section %i \n",section);
4734     if ( fromtime < 1150871000 ){ //1150866904
4735     if ( IsDebug() ) printf(" First PAMELA flight calibration at time %u \n",fromtime);
4736     fromtime = 0;// the first flight calibration was taken at about 1156429100 s, this line allow to analyze first runs in raw mode
4737     };
4738     //
4739     oss.str("");
4740     oss << " SELECT FROM_TIME FROM GL_CALOPULSE_CALIB WHERE "
4741     << " PULSE_AMPLITUDE = " << pampli << " AND "
4742     << " SECTION = "<< section << " AND "
4743     << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
4744     //
4745     if ( IsDebug() ) printf(" Check the upper limit for pulse2 calibration: query is \n %s \n",oss.str().c_str());
4746     result = conn->Query(oss.str().c_str());
4747     //
4748     if ( !result ) throw -4;
4749     //
4750     row = result->Next();
4751     if ( !row ){
4752     totime = numeric_limits<UInt_t>::max();
4753     } else {
4754     totime = (UInt_t)atoll(row->GetField(0));
4755     };
4756     //
4757     } else {
4758     //
4759     // determine upper and lower limits and make space for the new calibration
4760     //
4761     totime = (UInt_t)atoll(row->GetField(1));
4762     //
4763     oss.str("");
4764     oss << " UPDATE GL_CALOPULSE_CALIB SET "
4765     << " TO_TIME = "<< fromtime << " WHERE " // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
4766     << " ID = "<< row->GetField(0) << ";";
4767     //
4768     if ( IsDebug() ) printf(" Make space for the new pulse2 calibration: query is \n %s \n",oss.str().c_str());
4769     result = conn->Query(oss.str().c_str());
4770     //
4771     if ( !result ) throw -4;
4772     //
4773     };
4774     //
4775     // Fill the DB
4776     //
4777     oss.str("");
4778     // oss << " INSERT INTO GL_CALOPULSE_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,SECTION,OBT,PKT,BOOT_NUMBER,VALIDATION) "
4779     oss << " INSERT INTO GL_CALOPULSE_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,SECTION,PULSED_STRIP,PULSE_AMPLITUDE,OBT,PKT,BOOT_NUMBER,VALIDATION) "
4780     << " VALUES (NULL,' "
4781     << idroot << "','"
4782     << i << "','"
4783     << fromtime << "','"
4784     << totime << "','"
4785     << section << "','"
4786     << pstrip << "','"
4787     << pampli << "','"
4788     << obt << "','"
4789     << pkt << "','"
4790     << this->GetBOOTnumber() << "','"
4791     << valid << "');";
4792     //
4793     if ( IsDebug() ) printf(" Insert the new pulse2 calibration: query is \n %s \n",oss.str().c_str());
4794     //
4795     result = conn->Query(oss.str().c_str());
4796     //
4797     if ( !result ) throw -4;
4798     //
4799     };
4800     //
4801     } else {
4802     //
4803     if ( IsDebug() ) printf(" Pulse2 calo calibration for section %i at time %u obt %u pkt %u OUTSIDE the considered time interval \n",section,fromtime,obt,pkt);
4804     // if ( PEDANTIC ) throw -78;
4805     //
4806     };
4807     //
4808     };
4809     };
4810     };
4811     };
4812     //
4813     return(0);
4814     };
4815    
4816     /**
4817     * Fill the GL_TRK_CALIB table
4818     */
4819     void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){
4820 pam-fi 1.4
4821     GL_TRK_CALIB *glcal = new GL_TRK_CALIB();
4822     //
4823     glcal->ID = 0;
4824     glcal->ID_ROOT_L0 = GetID_ROOT();
4825     glcal->EV_ROOT_CALIBTRK1 = t1;
4826     glcal->EV_ROOT_CALIBTRK2 = t2;
4827     glcal->FROM_TIME = fromtime;
4828     glcal->TO_TIME = 0;
4829     glcal->OBT1 = obt1;
4830     glcal->OBT2 = obt2;
4831     glcal->PKT1 = pkt1;
4832     glcal->PKT2 = pkt2;
4833     glcal->BOOT_NUMBER = GetBOOTnumber();
4834     glcal->VALIDATION = valid;
4835     //
4836     HandleTRK_CALIB(glcal);
4837     //
4838     delete glcal;
4839     }
4840     /**
4841     * Fill the GL_TRK_CALIB table
4842     */
4843     void PamelaDBOperations::HandleTRK_CALIB(GL_TRK_CALIB *glcal){
4844    
4845     Bool_t pk1 = (glcal->OBT1>0&&glcal->PKT1>0);
4846     Bool_t pk2 = (glcal->OBT2>0&&glcal->PKT2>0);
4847     UInt_t boot_number = glcal->BOOT_NUMBER;
4848     UInt_t obt1 = glcal->OBT1;
4849     UInt_t obt2 = glcal->OBT2;
4850     UInt_t pkt1 = glcal->PKT1;
4851     UInt_t pkt2 = glcal->PKT2;
4852     UInt_t fromtime = glcal->FROM_TIME;
4853     UInt_t totime = 0;
4854     UInt_t idroot = glcal->ID_ROOT_L0;
4855     UInt_t t1 = glcal->EV_ROOT_CALIBTRK1;
4856     UInt_t t2 = glcal->EV_ROOT_CALIBTRK2;
4857     UInt_t valid = glcal->VALIDATION;
4858     //
4859     TSQLResult *result = 0;
4860     TSQLRow *row = 0;
4861     //
4862     stringstream oss;
4863     oss.str("");
4864 mocchiut 1.1 //
4865     //
4866 pam-fi 1.4 if ( !pk1 && !pk2 ){
4867     if ( IsDebug() ) printf(" Cannot handle trk calibration with both packet missing!\n");
4868     return;
4869     };
4870 mocchiut 1.1 //
4871 pam-fi 1.4 // check if the calibration has already been inserted
4872 mocchiut 1.1 //
4873     oss.str("");
4874 pam-fi 1.4 oss << " SELECT ID FROM GL_TRK_CALIB WHERE "
4875     << " BOOT_NUMBER = "<< boot_number; //
4876     oss << " AND FROM_TIME="<<fromtime; /// NEWNEWNEW -- VA BENE ?!?!?!?!
4877     oss << " AND ( ( ";
4878     if ( pk1 ){
4879     oss << " OBT1 = "<< obt1 << " AND "
4880     << " PKT1 = "<< pkt1
4881     << " ) OR ( ";
4882     } else {
4883     oss << " PKT1 = "<< pkt2-1
4884     << " ) OR ( ";
4885     };
4886     if ( pk2 ){
4887     oss << " OBT2 = "<< obt2 << " AND "
4888     << " PKT2 = "<< pkt2;
4889     } else {
4890     oss << " PKT2 = "<< pkt1+1;
4891     };
4892     oss << " ) );";
4893 mocchiut 1.1 //
4894 pam-fi 1.4 if ( IsDebug() ) printf(" Check if the trk calibration has already been inserted: query is \n %s \n",oss.str().c_str());
4895 mocchiut 1.1 result = conn->Query(oss.str().c_str());
4896     //
4897     if ( !result ) throw -4;
4898     //
4899     row = result->Next();
4900     //
4901 pam-fi 1.4 if ( row ){
4902     //
4903     if ( IsDebug() ) printf(" Trk calibration already inserted in the DB\n");
4904     if ( PEDANTIC ) throw -80;
4905     //
4906 mocchiut 1.1 } else {
4907 pam-fi 1.4 //
4908     // we have to insert a new calibration, check where to place it
4909     //
4910     oss.str("");
4911     oss << " SELECT ID,TO_TIME FROM GL_TRK_CALIB WHERE "
4912     << " FROM_TIME < "<< fromtime << " AND "
4913     << " TO_TIME > "<< fromtime << ";";
4914     //
4915     if ( IsDebug() ) printf(" Check where to place the trk calibration: query is \n %s \n",oss.str().c_str());
4916     result = conn->Query(oss.str().c_str());
4917     //
4918     if ( !result ) throw -4;
4919     //
4920     row = result->Next();
4921     //
4922     if ( !row ){
4923     //
4924     // no calibrations in the db contain our calibration
4925     //
4926     if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB\n");
4927     if ( fromtime < 1150871000 ) fromtime = 0; // the first flight calibration was taken at about 1150863300 s, this line allows to analyze first runs in raw mode
4928     //
4929     oss.str("");
4930     oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "
4931     << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
4932     //
4933     if ( IsDebug() ) printf(" Check the upper limit for calibration: query is \n %s \n",oss.str().c_str());
4934     result = conn->Query(oss.str().c_str());
4935     //
4936     if ( !result ) throw -4;
4937     //
4938     row = result->Next();
4939     if ( !row ){
4940     totime = numeric_limits<UInt_t>::max();
4941     } else {
4942     totime = (UInt_t)atoll(row->GetField(0));
4943     };
4944     //
4945     } else {
4946     //
4947     // determine upper and lower limits and make space for the new calibration
4948     //
4949     totime = (UInt_t)atoll(row->GetField(1));
4950     //
4951     oss.str("");
4952     oss << " UPDATE GL_TRK_CALIB SET "
4953     << " TO_TIME = "<< fromtime << " WHERE " // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
4954     << " ID = "<< row->GetField(0) << ";";
4955     //
4956     if ( IsDebug() ) printf(" Make space for the new trk calibration: query is \n %s \n",oss.str().c_str());
4957     result = conn->Query(oss.str().c_str());
4958     //
4959     if ( !result ) throw -4;
4960     //
4961     };
4962     //
4963     oss.str("");
4964     oss << " INSERT INTO GL_TRK_CALIB (ID,ID_ROOT_L0,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,FROM_TIME,TO_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION) "
4965     << " VALUES (NULL,' "
4966     << idroot << "',";
4967     //
4968     if ( !pk1 ){
4969     oss << "NULL,";
4970     } else {
4971     oss << "'"
4972     << t1 << "',";
4973     };
4974     //
4975     if ( !pk2 ){
4976     oss << "NULL,'";
4977     } else {
4978     oss << "'"
4979     << t2 << "','";
4980     };
4981     //
4982     oss << fromtime << "','"
4983     << totime << "','"
4984     << obt1 << "','"
4985     << pkt1 << "','"
4986     << obt2 << "','"
4987     << pkt2 << "','"
4988     << boot_number << "','"
4989     << valid << "');";
4990     //
4991     if ( IsDebug() ) printf(" Insert the new trk calibration: query is \n %s \n",oss.str().c_str());
4992     //
4993     result = conn->Query(oss.str().c_str());
4994     //
4995     if ( !result ) throw -4;
4996     //
4997 mocchiut 1.1 };
4998 pam-fi 1.4
4999 mocchiut 1.1 oss.str("");
5000 pam-fi 1.4 oss << " SELECT ID FROM GL_TRK_CALIB ORDER BY ID DESC LIMIT 1 ;";
5001     if ( IsDebug() ) cout << oss.str().c_str() << endl;
5002 mocchiut 1.1 result = conn->Query(oss.str().c_str());
5003 pam-fi 1.4 if ( !result ) throw -4;;
5004     row = result->Next();
5005     if(row)glcal->ID = (UInt_t)atoll(row->GetField(0));
5006 mocchiut 1.21 //
5007     delete result; // mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
5008 mocchiut 1.1 //
5009     };
5010    
5011     /**
5012     * Scan tracker calibrations packets, fill the GL_TRK_CALIB table
5013     */
5014     Int_t PamelaDBOperations::insertTRK_CALIB(){
5015     //
5016 pam-fi 1.4 CalibTrk1Event *caltrk1 = 0;
5017     CalibTrk2Event *caltrk2 = 0;
5018     TTree *tr1 = 0;
5019     TTree *tr2 = 0;
5020     EventHeader *eh1 = 0;
5021     PscuHeader *ph1 = 0;
5022     EventHeader *eh2 = 0;
5023     PscuHeader *ph2 = 0;
5024     //
5025     PacketType *pctp=0;
5026     EventCounter *codt2=0;
5027     //
5028     Int_t nevents1 = 0;
5029     Int_t nevents2 = 0;
5030 mocchiut 1.1 //
5031 pam-fi 1.4 fromtime = 0;
5032 mocchiut 1.1 //
5033 pam-fi 1.4 obt1 = 0;
5034     pkt1 = 0;
5035     obt2 = 0;
5036     pkt2 = 0;
5037 mocchiut 1.1 //
5038 pam-fi 1.4 tr1 = (TTree*)file->Get("CalibTrk1");
5039     if ( !tr1 || tr1->IsZombie() ) throw -22;
5040     tr2 = (TTree*)file->Get("CalibTrk2");
5041     if ( !tr2 || tr2->IsZombie() ) throw -23;
5042     //
5043     tr1->SetBranchAddress("CalibTrk1", &caltrk1);
5044     tr1->SetBranchAddress("Header", &eh1);
5045     nevents1 = tr1->GetEntries();
5046     tr2->SetBranchAddress("CalibTrk2", &caltrk2);
5047     tr2->SetBranchAddress("Header", &eh2);
5048     nevents2 = tr2->GetEntries();
5049     //
5050     if ( !nevents1 && !nevents2 ) return(1);
5051     //
5052     t2 = -1;
5053     Int_t pret2 = 0;
5054     Int_t t2t1cal = 0;
5055     //
5056     bool MISSING_pkt1 = true;
5057     bool MISSING_pkt2 = true;
5058     int ncalib = 0;
5059     bool try_to_recover = false;
5060 mocchiut 1.1 //
5061 pam-fi 1.4 for (t1=0; t1 < nevents1; t1++){//loop over packet1
5062     //
5063     pret2 = t2;
5064     tr1->GetEntry(t1);
5065 mocchiut 1.1 //
5066 pam-fi 1.4 ph1 = eh1->GetPscuHeader();
5067     obt1 = ph1->GetOrbitalTime();
5068     pkt1 = ph1->GetCounter();
5069     fromtime = GetAbsTime(ph1->GetOrbitalTime());
5070 mocchiut 1.1 //
5071 pam-fi 1.4 // chek if the packet number and obt are consistent with the other packets ???
5072 mocchiut 1.1 //
5073 pam-fi 1.4 if ( PKT(pkt1) >= PKT(pktfirst) && PKT(pkt1) <= upperpkt && OBT(obt1) >= OBT(obtfirst) && OBT(obt1) <= upperobt ){
5074     // if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->OBT(obt1) >= this->OBT(obtfirst) ){
5075     //
5076     if ( IsDebug() ) printf("\n Trk calibration1 %u at time %u obt %u pkt %u \n",t1,fromtime,obt1,pkt1);
5077     //
5078     valid = ValidateTrkCalib( caltrk1, eh1 );
5079     if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;
5080     //
5081     // Do we have the second calibration packet?
5082     //
5083     if ( IsDebug() ) cout << " Loop over calibration2 to search associated calibration: "<<endl;
5084     while ( t2t1cal < t1+1 ){ // get the calibration packet2 that follows the packet1
5085     //
5086     t2++;
5087     //
5088     pret2 = t2 - 1; // EMILIANO
5089     //
5090     if ( t2 < nevents2 ){
5091     tr2->GetEntry(t2);
5092     codt2 = eh2->GetCounter();
5093     t2t1cal = codt2->Get(pctp->CalibTrk1);
5094     //
5095     ph2 = eh2->GetPscuHeader();
5096     obt2 = ph2->GetOrbitalTime();
5097     pkt2 = ph2->GetCounter();
5098     //
5099     if ( IsDebug() ) printf(" >> trk calibration2 at obt %u pkt %u t2 is %u , t2t1cal is %u \n",obt2,pkt2,t2,t2t1cal);
5100     // if ( caltrk2->unpackError != 0 || caltrk2->good0 == 0 ) valid = 0; // CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT2
5101     //
5102     } else {
5103     //
5104     // running out of vector without finding the corresponding calibration, sig
5105     //
5106     if ( IsDebug() ) printf(" t2 >= nevents2 \n");
5107     pret2 = t2;
5108     obt2 = 0;
5109     // pkt2 = pkt1+2;
5110     pkt2 = 0;
5111     t2t1cal = t1+1;
5112     };
5113     // if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) && (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){
5114    
5115     // EMILIANO
5116     // if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) || (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){
5117     // // if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){
5118     // if ( IsDebug() ) printf(" running out of vector without finding the corresponding calibration, sig \n");
5119     // //
5120     // // running out of vector without finding the corresponding calibration, sig
5121     // //
5122     // pret2 = t2;
5123     // obt2 = 0;
5124     // // pkt2 = pkt1+2;
5125     // pkt2 = 0;
5126     // t2t1cal = t1+1;
5127     // };
5128    
5129    
5130     //
5131     };
5132     //
5133     if ( IsDebug() ) printf(" Check if trk calibration2 is the right one \n");
5134     //
5135     // EMILIANO
5136     if ( ( PKT(pkt2) < PKT(pktfirst) || PKT(pkt2) > upperpkt) || (OBT(obt2) < OBT(obtfirst) || OBT(obt2) > upperobt) ){
5137     // if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){
5138     if ( IsDebug() ) printf(" *WARNING* The calibration found is outside the interval, sig \n");
5139     //
5140     // running out of vector without finding the corresponding calibration, sig
5141     //
5142     pret2 = t2;
5143     obt2 = 0;
5144     pkt2 = 0;
5145     };
5146     if ( PKT(pkt2) == PKT(pkt1)+1 ){
5147     if ( IsDebug() ) cout << " ...OK"<<endl;
5148     // =======================
5149     // The calibration is good
5150     // =======================
5151     //
5152     // if ( IsDebug() ) printf(" Found trk calibration2 at obt %u pkt %u t2 is %u \n",obt2,pkt2,t2);
5153     // if ( IsDebug() ) printf(" Trk calibration2 at obt %u pkt %u t2 is %u is good \n",obt2,pkt2,t2);
5154     // if ( IsDebug() ) printf("\n Trk calibration2 at time %u obt %u pkt %u \n",fromtime,obt2,pkt2);
5155     if ( IsDebug() ) printf(" Trk calibration2 %u at time %u obt %u pkt %u \n",t2,fromtime,obt2,pkt2);
5156     //
5157     UInt_t valid2 = ValidateTrkCalib( caltrk2, eh2 );
5158     if ( IsDebug() ) cout << " pkt2 validation --> "<<valid2<<endl;
5159     // valid = valid & valid2;
5160     valid = valid & valid2; //QUESTO VA CAMBIATO
5161     //
5162     // Handle good calib
5163     //
5164     MISSING_pkt1 = false;
5165     MISSING_pkt2 = false;
5166     // this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5167     //
5168     // Check for missing calibtrk1
5169     //
5170     if ( t2 != pret2+1 ){
5171     //
5172     if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %u pkt %u t2 is %u pret2 is %u \n",obt2,pkt2,t2,pret2);
5173     //
5174     while ( t2 > pret2+1 ){
5175     //
5176     // handle missing calib1
5177     //
5178     pret2++;
5179     //
5180     obt1 = 0;
5181     pkt1 = 0;
5182     //
5183     tr2->GetEntry(pret2);
5184     ph2 = eh2->GetPscuHeader();
5185     obt2 = ph2->GetOrbitalTime();
5186     pkt2 = ph2->GetCounter();
5187     //
5188     fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
5189     //
5190     valid = 0;
5191     MISSING_pkt1 = true;
5192     MISSING_pkt2 = false;
5193     // this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5194     //
5195     };
5196     //
5197     };
5198     //
5199     } else if ( this->PKT(pkt2) > this->PKT(pkt1)+1 ){
5200     //
5201     // Check for missing calibtrk2
5202     //
5203     if ( IsDebug() ) printf(" Missing the trk calibration2! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);
5204     t2 = pret2;
5205     //
5206     // handle missing calib2
5207     //
5208     obt2 = 0;
5209     pkt2 = 0;
5210     valid = 0;
5211     MISSING_pkt1 = false;
5212     MISSING_pkt2 = true;
5213     // this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5214     //
5215     };
5216     //
5217 mocchiut 1.7
5218     if( !(MISSING_pkt1&MISSING_pkt2) ){
5219     this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5220     ncalib++;
5221     if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
5222     }
5223    
5224    
5225 mocchiut 1.1 } else {
5226 mocchiut 1.7 //
5227 pam-fi 1.4 if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u OUTSIDE the considered time interval \n",fromtime,obt1,pkt1);
5228     // if ( PEDANTIC ) throw -79;
5229     //
5230 mocchiut 1.1 };
5231 pam-fi 1.4 //
5232    
5233     }; //end loop on pkt1
5234 mocchiut 1.1
5235    
5236    
5237 pam-fi 1.4 //
5238     // we have one more calib pkt2 !
5239     //
5240     t2++;
5241     while ( t2 < nevents2 ){
5242 mocchiut 1.1 //
5243 pam-fi 1.4 // handle missing calib1
5244 mocchiut 1.1 //
5245 pam-fi 1.4 if ( IsDebug() ) printf(" t2 is %u nevents2 is %u \n",t2,nevents2);
5246     obt1 = 0;
5247     pkt1 = 0;
5248 mocchiut 1.1 //
5249 pam-fi 1.4 tr2->GetEntry(t2);
5250     ph2 = eh2->GetPscuHeader();
5251     obt2 = ph2->GetOrbitalTime();
5252     pkt2 = ph2->GetCounter();
5253 mocchiut 1.1 //
5254 pam-fi 1.4 fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
5255     valid = 0;
5256     // if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->PKT(pkt1) <= upperpkt && this->OBT(obt1) >= this->OBT(obtfirst) && this->OBT(obt1) <= upperobt ){
5257     // EMILIANO
5258     if ( this->PKT(pkt2) >= this->PKT(pktfirst) && this->PKT(pkt2 <= upperpkt) && this->OBT(obt2) >= this->OBT(obtfirst) && this->OBT(obt2) <= upperobt ){
5259     // if ( this->PKT(pkt2) > this->PKT(pktfirst) || this->OBT(obt2) > this->OBT(obtfirst) ){
5260 mocchiut 1.1 //
5261 pam-fi 1.4 if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);
5262 mocchiut 1.1 //
5263 pam-fi 1.4 MISSING_pkt1 = true;
5264     MISSING_pkt2 = false;
5265     this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5266     ncalib++;
5267     if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
5268 mocchiut 1.1 //
5269     };
5270     //
5271 pam-fi 1.4 t2++;
5272 mocchiut 1.1 //
5273 pam-fi 1.4 };
5274    
5275     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5276     // -----------------------------------------------------------------
5277     // in case of corruption, check if the calibration can be recovered
5278     // from another chewbacca file
5279     // -----------------------------------------------------------------
5280     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5281    
5282     // cout <<" TRY TO RECOVER ?? "<<try_to_recover<<endl;
5283    
5284     if(chewbacca&&try_to_recover){
5285    
5286    
5287     if ( IsDebug() ) cout << endl << ">>>> TRY TO RECOVER TRACKER CALIBRATIONS <<<<"<<endl;
5288    
5289     TSQLResult *result = 0;
5290     TSQLRow *row = 0;
5291 mocchiut 1.1 //
5292 pam-fi 1.4 stringstream oss;
5293     oss.str("");
5294 mocchiut 1.1 //
5295 pam-fi 1.4
5296     ////////////////////////////////////////////////////////////////////////
5297     // retrieve the name of the current file:
5298     ////////////////////////////////////////////////////////////////////////
5299     oss.str("");
5300     oss << "SELECT NAME FROM GL_ROOT where ID=" << GetID_ROOT() <<";";
5301     if ( IsDebug() ) cout << oss.str().c_str() << endl;
5302    
5303     result = conn->Query(oss.str().c_str());
5304     if ( !result ) throw -4;;
5305     row = result->Next();
5306     TString thisfilename = (TString)row->GetField(0);
5307     if ( IsDebug() ) cout << "Current file ==> "<<thisfilename<<endl;
5308    
5309     ////////////////////////////////////////////////////////////////////////
5310     // read all the calibrations inserted
5311     ////////////////////////////////////////////////////////////////////////
5312     oss.str("");
5313     oss << " SELECT ";
5314     oss << " ID,FROM_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,TO_TIME";
5315     oss << " FROM GL_TRK_CALIB ";
5316     oss << " ORDER BY ID DESC LIMIT "<<ncalib<<"; ";
5317     if ( IsDebug() ) cout << oss.str().c_str() << endl;
5318    
5319     result = conn->Query(oss.str().c_str());
5320     if ( !result ) throw -4;;
5321     if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5322    
5323     // -----------------------------------
5324     // loop over calibrations ...
5325     // -----------------------------------
5326     UInt_t nn=0;
5327     do {
5328     row = result->Next();
5329     if(!row)break;
5330    
5331     UInt_t id = (UInt_t)atoll(row->GetField(0));
5332     UInt_t fromtime = (UInt_t)atoll(row->GetField(1));
5333     UInt_t obt1 = (UInt_t)atoll(row->GetField(2));
5334     UInt_t pkt1 = (UInt_t)atoll(row->GetField(3));
5335     UInt_t obt2 = (UInt_t)atoll(row->GetField(4));
5336     UInt_t pkt2 = (UInt_t)atoll(row->GetField(5));
5337     UInt_t boot = (UInt_t)atoll(row->GetField(6));
5338     UInt_t valid = (UInt_t)atoll(row->GetField(7));
5339     bool MISSING_pkt1 = (row->GetFieldLength(8)==0);
5340     bool MISSING_pkt2 = (row->GetFieldLength(9)==0);
5341     UInt_t totime = (UInt_t)atoll(row->GetField(10));
5342    
5343     // -------------------------------------
5344     // ...check if the entry is corrupted...
5345     // -------------------------------------
5346     cout <<"*** "<< MISSING_pkt1 << MISSING_pkt2 << valid <<endl;
5347     bool CORRUPTED = (MISSING_pkt1||MISSING_pkt2||!valid);
5348    
5349     if ( IsDebug() ) cout << "("<<nn<<") ID = "<<id<<" from GL_TRK_CALIB ==> corrupted ? "<<CORRUPTED<<endl;
5350    
5351     // if( !CORRUPTED )continue; // nothing to do
5352    
5353     /////////////////////////////////////////////////////////
5354     // if it is corrupted, ...look for ather chewbacca files
5355     // containing the same calibrations ...
5356     /////////////////////////////////////////////////////////
5357    
5358     bool this_MISSING_pkt1 = false;
5359     bool this_MISSING_pkt2 = false;
5360     int this_t1=0;
5361     int this_t2=0;;
5362     UInt_t this_valid = 0;
5363    
5364     TString path = "";
5365     TString name = "";
5366     TString raw = "";
5367     UInt_t obt0 = 0;
5368     UInt_t timesync = 0;
5369     UInt_t boot_number = 0;
5370     bool FOUND = false;
5371    
5372     if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
5373    
5374     // for(int itable=0; itable<2; itable++){
5375     for(int itable=0; itable<1; itable++){
5376    
5377     // ------------------------------------------------------
5378     // loop over both ROOT_TABLE and ROOT_TABLE_BAD
5379     // ------------------------------------------------------
5380    
5381     TString table = "ROOT_TABLE";
5382     if(itable==1)table = "ROOT_TABLE_BAD";
5383    
5384     oss.str("");
5385     oss << " SELECT ";
5386     oss << " FOLDER_NAME,FILE_NAME,OBT_TIME_SYNC,LAST_TIME_SYNC_INFO,BOOT_NUMBER,INPUT_NAME ";
5387     oss << " FROM "<<table;
5388     oss << " WHERE 1 " << endl;
5389     oss << " AND FILE_NAME != \""<< thisfilename<<"\"";
5390     if( !MISSING_pkt1 ){
5391     oss << " AND ";
5392     oss << " PKT_NUMBER_INIT < "<<pkt1;
5393     oss << " AND ";
5394     oss << " PKT_NUMBER_FINAL > "<<pkt1;
5395     oss << " AND ";
5396     oss << " PKT_OBT_INIT < "<<obt1;
5397     oss << " AND ";
5398     oss << " PKT_OBT_FINAL > "<<obt1;
5399     }else{
5400     if(pkt2>1) pkt1 = pkt2-1;//serve dopo
5401     }
5402     if( !MISSING_pkt2 ){
5403     oss << " AND ";
5404     oss << " PKT_NUMBER_INIT < "<<pkt2;
5405     oss << " AND ";
5406     oss << " PKT_NUMBER_FINAL > "<<pkt2;
5407     oss << " AND ";
5408     oss << " PKT_OBT_INIT < "<<obt2;
5409     oss << " AND ";
5410     oss << " PKT_OBT_FINAL > "<<obt2;
5411     }else{
5412     if(pkt1>0) pkt2 = pkt1+1;//serve dopo
5413     }
5414     if( boot> 0 ){
5415     oss << " AND ";
5416     oss << " BOOT_NUMBER = "<<boot;
5417     }else{
5418     }
5419     oss << " ORDER BY BAD_PKT_CALREAD ASC; ";
5420    
5421     TSQLResult *result2 = 0;
5422     TSQLRow *row2 = 0;
5423    
5424     if ( IsDebug() ) cout << oss.str().c_str() << endl;
5425     result2 = conn->Query(oss.str().c_str());
5426     if ( !result2 ) throw -4;;
5427     if ( IsDebug() ) cout <<"Rows: "<<result2->GetRowCount()<<endl;
5428    
5429     // ------------------------------------------------------
5430     // loop over files containing repetition (if any)
5431     // ------------------------------------------------------
5432     do {
5433     row2 = result2->Next();
5434     if(!row2)break;
5435    
5436     // ------------------------------------------------------
5437     // ... a repetition is found ...
5438     // ------------------------------------------------------
5439     path = (TString)row2->GetField(0);
5440     name = (TString)row2->GetField(1);
5441     raw = (TString)row2->GetField(5);
5442     obt0 = (UInt_t)atoll(row2->GetField(2));
5443     timesync = (UInt_t)atoll(row2->GetField(3));
5444     boot_number = (UInt_t)atoll(row2->GetField(4));
5445    
5446     if ( IsDebug() ) cout << "- - - - - - - - - - -" <<endl;
5447     // cout << path <<endl;
5448 mocchiut 1.5 // cout << "File : " <<name <<endl;
5449 pam-fi 1.4 // cout << obt0 <<endl;
5450     // cout << timesync <<endl;
5451 mocchiut 1.5 // cout << "boot n. : "<<boot_number <<endl;
5452 pam-fi 1.4 // cout << raw <<endl;
5453    
5454     // ------------------------------------------------------
5455     // ... retrieve the calibration packets.
5456     // ------------------------------------------------------
5457 mocchiut 1.7 if ( IsDebug() ) printf(" file is %s/%s \n",((TString)gSystem->ExpandPathName(path.Data())).Data(),name.Data());
5458     TFile *file = new TFile(((TString)gSystem->ExpandPathName(path.Data()))+"/"+name); // EM, path could be symbolic and we must expand it
5459 pam-fi 1.4 if(!file)throw -100;
5460     if(file->IsZombie())throw -100;
5461     //
5462     tr1 = (TTree*)file->Get("CalibTrk1");
5463     if ( !tr1 || tr1->IsZombie() ) throw -22;
5464     tr2 = (TTree*)file->Get("CalibTrk2");
5465     if ( !tr2 || tr2->IsZombie() ) throw -23;
5466     //
5467     tr1->SetBranchAddress("CalibTrk1", &caltrk1);
5468     tr1->SetBranchAddress("Header", &eh1);
5469     nevents1 = tr1->GetEntries();
5470     tr2->SetBranchAddress("CalibTrk2", &caltrk2);
5471     tr2->SetBranchAddress("Header", &eh2);
5472     nevents2 = tr2->GetEntries();
5473     for(this_t1=0; this_t1<nevents1; this_t1++){
5474     tr1->GetEntry(this_t1);
5475     if(
5476     (UInt_t)eh1->GetPscuHeader()->GetCounter() == pkt1 &&
5477     true) break;
5478     this_MISSING_pkt1 = true;
5479     }
5480     for(this_t2=0; this_t2<nevents2; this_t2++){
5481     tr2->GetEntry(this_t2);
5482     if(
5483     (UInt_t)eh2->GetPscuHeader()->GetCounter() == pkt2 &&
5484     true) break;
5485     this_MISSING_pkt2 = true;
5486     }
5487     this_valid =
5488     ValidateTrkCalib( caltrk1, eh1, file )
5489     *
5490     ValidateTrkCalib( caltrk2, eh2, file );
5491    
5492     // ---------------------------------------------------------------------
5493     // accept the calibration if it is better than the previous:
5494     //
5495     // - if the new calibration is perfect (both valid packets)
5496     // - if the new calibration has both the packets and the previous does not
5497     // ---------------------------------------------------------------------
5498     if(
5499     ( !this_MISSING_pkt1&&!this_MISSING_pkt2&&this_valid )||
5500     ( (MISSING_pkt1||MISSING_pkt2) && (!this_MISSING_pkt1&&!this_MISSING_pkt2) )||
5501     false)FOUND=true;
5502    
5503     if(file)file->Close();
5504    
5505     if(FOUND)break;
5506    
5507     }while(1);//endl loop over root table entries
5508    
5509     if(FOUND)break;
5510    
5511     }//end loop over tables
5512    
5513     if(FOUND){
5514    
5515 mocchiut 1.21 if ( IsDebug() ) cout << " >>> REPETITION FOUND :-) <<<" <<endl;
5516 pam-fi 1.4
5517 mocchiut 1.21 ////////////////////////////////////////////
5518     // insert a new entry in GL_TRK_CALIB and
5519     // modify the time-tag of the previous one
5520     ////////////////////////////////////////////
5521    
5522     // ---------------------------------------------------------------------
5523     // step 1: insert a new raw file in GL_RAW
5524     // ---------------------------------------------------------------------
5525     //
5526     // check if the raw file already exist
5527     //
5528     UInt_t id_raw = 0; // EM GL_RAW is there only for backward compatibility so we do not need to fill it when in "chewbacca" mode
5529     // oss.str("");
5530     // oss << "SELECT ID FROM GL_RAW where NAME=\"" << gSystem->BaseName(raw.Data()) <<"\";";
5531     // if ( IsDebug() ) cout << oss.str().c_str() << endl;
5532 pam-fi 1.4
5533 mocchiut 1.21 // result = conn->Query(oss.str().c_str());
5534     // if ( !result ) throw -4;;
5535     // if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5536     // if( result->GetRowCount() == 0){
5537     // if ( IsDebug() ) cout << " << Insert new RAW file >> "<<endl;
5538     // // - - - - - - - - - - -
5539     // // insert new raw file
5540     // // - - - - - - - - - - -
5541     // GL_RAW glraw = GL_RAW();
5542     // glraw.PATH = gSystem->DirName(raw.Data());
5543     // glraw.NAME = gSystem->BaseName(raw.Data());
5544     // glraw.BOOT_NUMBER = boot_number;
5545     // //
5546     // insertPamelaRawFile( &glraw );
5547     // //
5548     // id_raw = glraw.ID;
5549     // }else{
5550     // row = result->Next();
5551     // id_raw = (UInt_t)atoll(row->GetField(0));
5552     // }
5553     // if ( IsDebug() ) cout << "ID_RAW = "<<id_raw<<endl;
5554    
5555     // ---------------------------------------------------------------------
5556     // step 1(bis): retrieve the timesync id associated to the file
5557     // (NB, uso lo stesso associato al file iniziale)
5558     // ---------------------------------------------------------------------
5559     UInt_t idtimesync = 0;
5560     oss.str("");
5561     oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" limit 1;";
5562     if ( debug ) printf(" %s \n",oss.str().c_str());
5563     result = conn->Query(oss.str().c_str());
5564     if ( !result ) throw -3;
5565 pam-fi 1.4 row = result->Next();
5566     if ( !row ) throw -3;
5567     idtimesync = (UInt_t)atoll(row->GetField(0));
5568     if ( IsDebug() ) cout << "ID_TIMESYNC = "<<idtimesync<<endl;
5569    
5570 mocchiut 1.21 delete result;// mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
5571 pam-fi 1.4 // ---------------------------------------------------------------------
5572     // step 2: insert a new root file in GL_ROOT
5573     // ---------------------------------------------------------------------
5574     //
5575 mocchiut 1.5 // check if the root file already exist
5576 pam-fi 1.4 //
5577     UInt_t id_root = 0;
5578     oss.str("");
5579     oss << "SELECT ID FROM GL_ROOT where NAME=\"" << gSystem->BaseName(name.Data()) <<"\";";
5580     if ( IsDebug() ) cout << oss.str().c_str() << endl;
5581    
5582     result = conn->Query(oss.str().c_str());
5583     if ( !result ) throw -4;;
5584     if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5585     if( result->GetRowCount() == 0){
5586     if ( IsDebug() ) cout << " << Insert new ROOT file >> "<<endl;
5587     // - - - - - - - - - - -
5588     // insert new root file
5589     // - - - - - - - - - - -
5590     GL_ROOT glroot = GL_ROOT();
5591     glroot.ID_RAW = id_raw;
5592     glroot.ID_TIMESYNC = idtimesync;
5593 mocchiut 1.5 //
5594     // EM STATIC = the full expanded path must be put in the DB, KEEPENV = the path given as input (or found in ROOT_TABLE) must be used,
5595     // NOT STATIC NOT KEEPENV = $PAM_L0 must be used in the DB
5596     //
5597     if ( STATIC ){
5598     glroot.PATH = (TString)gSystem->ExpandPathName(path);
5599     } else {
5600     if ( KEEPENV ){
5601     glroot.PATH = path;
5602     } else {
5603     glroot.PATH = "$PAM_L0";
5604     };
5605     };
5606     // glroot.PATH = path;
5607 pam-fi 1.4 glroot.NAME = name;
5608     //
5609     insertPamelaRootFile( &glroot );
5610     //
5611     id_root = glroot.ID;
5612     }else{
5613     row = result->Next();
5614     if(row)id_root = (UInt_t)atoll(row->GetField(0));
5615     }
5616     if ( IsDebug() ) cout << "ID_ROOT = "<<id_root<<endl;
5617    
5618 mocchiut 1.21 delete result;// mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
5619 pam-fi 1.4 // ---------------------------------------------------------------------
5620     // step 3: modify time-tag of corrupted GL_TRK_CALIB entry
5621     // ---------------------------------------------------------------------
5622     if ( IsDebug() ) cout << " << Modify time-tag of calibration ID="<<id<<" >> "<<endl;
5623     oss.str("");
5624     oss << " UPDATE GL_TRK_CALIB SET "
5625     << " TO_TIME=0 , FROM_TIME=0 WHERE "
5626     << " ID = "<< id << ";";
5627     if ( IsDebug() ) cout << oss.str().c_str() << endl;
5628     result = conn->Query(oss.str().c_str());
5629     if ( !result ) throw -4;;
5630    
5631 mocchiut 1.21 delete result; // mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
5632    
5633 pam-fi 1.4 // ---------------------------------------------------------------------
5634     // step 4: insert the new calibration:
5635     // ---------------------------------------------------------------------
5636     if ( IsDebug() ) cout << " << Insert new TRK calibration >> "<<endl;
5637     //
5638     GL_TRK_CALIB glcal = GL_TRK_CALIB();
5639     //
5640     glcal.ID_ROOT_L0 = id_root;
5641     glcal.EV_ROOT_CALIBTRK1 = this_t1;
5642     glcal.EV_ROOT_CALIBTRK2 = this_t2;
5643     glcal.FROM_TIME = fromtime;
5644     glcal.TO_TIME = totime;
5645     glcal.OBT1 = obt1;
5646     glcal.OBT2 = obt2;
5647     glcal.PKT1 = pkt1;
5648     glcal.PKT2 = pkt1;
5649     glcal.BOOT_NUMBER = GetBOOTnumber();
5650     glcal.VALIDATION = this_valid;
5651     //
5652     HandleTRK_CALIB(&glcal);
5653     if ( IsDebug() ) cout << "ID = "<<glcal.ID<<endl;
5654     //
5655    
5656     }
5657     if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
5658    
5659     }while(1);//end loop over calibrations
5660    
5661    
5662     if( result )delete result;
5663     if( row )delete row;
5664    
5665    
5666    
5667    
5668    
5669    
5670     }
5671    
5672    
5673     // // ------------------------------
5674     // // try to recover the calibration
5675     // // ------------------------------
5676     // cout << "TRY TO RECOVER TRACKER CALIBRATION"<<endl;
5677     // //
5678     // ULong64_t time = 0; //absolute time
5679     // string path[100]; //mettere un limite massimo
5680     // int nrows = 0;
5681     // UInt_t pkt = 0;
5682     // UInt_t obt = 0;
5683     // char *type = "";
5684     // EventHeader *eh = new EventHeader();
5685     // CalibTrk1Event *c = new CalibTrk1Event();
5686    
5687     // //
5688     // if(which_is_not_valid==1 || which_is_not_valid==3){
5689     // //
5690     // cout << "PKT1 --> missing or corrupted "<<endl;
5691     // type = "CalibTrk1";
5692     // pkt = pkt1;
5693     // obt = obt1;
5694     // time = this->GetAbsTime(obt1);
5695     // if( pkt1 == 0 ){//missing
5696     // time = this->GetAbsTime(obt2);
5697     // pkt = pkt2-1;
5698     // }
5699     // //
5700     // }else if (which_is_not_valid==2 || which_is_not_valid==3){
5701     // //
5702     // cout << "PKT2--> missing or corrupted "<<endl;
5703     // type = "CalibTrk2 ";
5704     // pkt = pkt2;
5705     // obt = obt2;
5706     // time = this->GetAbsTime(obt2);
5707     // if( pkt2 == 0 ){//missing
5708     // time = this->GetAbsTime(obt1);
5709     // pkt = pkt1+1;
5710     // }
5711     // //
5712     // }else{
5713     // cout << "this should not happen!!! "<<endl;
5714     // trow -666;
5715     // }
5716    
5717     // nrows = Query_ROOT_TABLE(time,conn,path);// get the list of file which might contain the packet
5718    
5719    
5720     // for(int r=0; r<nrows; r++){ //loop over rows
5721     // if(path)cout << r << " >>>> "<<(path+r)->c_str() << endl;
5722     // /// verifica che il file non sia quello gia` aperto
5723     // }
5724    
5725     // ////////////////////////////////////////////////////////////////////////
5726    
5727     // TSQLResult *result = 0;
5728     // TSQLRow *row = 0;
5729     // //
5730     // stringstream oss;
5731     // oss.str("");
5732     // // ----------------------------------------
5733     // // read the id of last calibration inserted
5734     // // ----------------------------------------
5735     // oss.str("");
5736     // oss << " SELECT ";
5737     // oss << " (ID,ID_ROOT_L0,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,FROM_TIME,TO_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION) ";
5738     // oss << " ORDER BY ID DESC LIMIT 1; ";
5739    
5740     // result = conn->Query(oss.str().c_str());
5741     // row = result->Next();
5742     // if( !row )throw -666;
5743    
5744     // if( result )delete result;
5745     // if( row )delete row;
5746    
5747     // UInt_t id = (UInt_t)atoll(row->GetField(0));
5748    
5749     // // -------------------------------------
5750     // // ...and modify it with new parameters
5751     // // -------------------------------------
5752    
5753    
5754     // }
5755 mocchiut 1.1 //
5756     return(0);
5757     };
5758    
5759    
5760     /**
5761     * Scan S4 calibrations packets, fill the GL_S4_CALIB table
5762     */
5763     Int_t PamelaDBOperations::insertS4_CALIB(){
5764     //
5765     TSQLResult *result = 0;
5766     TSQLRow *row = 0;
5767     //
5768     stringstream oss;
5769     oss.str("");
5770     //
5771     TTree *tr = 0;
5772     EventHeader *eh = 0;
5773     PscuHeader *ph = 0;
5774     //
5775     UInt_t nevents = 0;
5776     UInt_t fromtime = 0;
5777     UInt_t totime = 0;
5778     UInt_t obt = 0;
5779     UInt_t pkt = 0;
5780     //
5781     tr = (TTree*)file->Get("CalibS4");
5782     if ( !tr || tr->IsZombie() ) throw -24;
5783     //
5784     tr->SetBranchAddress("Header", &eh);
5785     //
5786     nevents = tr->GetEntries();
5787     //
5788     if ( !nevents ) return(1);
5789     //
5790     for (UInt_t i = 0; i < nevents; i++){
5791     //
5792     tr->GetEntry(i);
5793     //
5794     ph = eh->GetPscuHeader();
5795     obt = ph->GetOrbitalTime();
5796     pkt = ph->GetCounter();
5797     fromtime = this->GetAbsTime(ph->GetOrbitalTime());
5798     if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->PKT(pkt) <= upperpkt && this->OBT(obt) >= this->OBT(obtfirst) && this->OBT(obt) <= upperobt ){
5799     // if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->OBT(obt) >= this->OBT(obtfirst) ){
5800     //
5801     if ( IsDebug() ) printf(" S4 calibration at time %u obt %u pkt %u \n",fromtime,obt,pkt);
5802     //
5803     // check if the calibration has already been inserted
5804     //
5805     oss.str("");
5806     oss << " SELECT ID FROM GL_S4_CALIB WHERE "
5807     << " BOOT_NUMBER = "<< this->GetBOOTnumber() << " AND "
5808     << " OBT = "<< obt << " AND "
5809     << " PKT = "<< pkt << ";";
5810     //
5811     if ( IsDebug() ) printf(" Check if the S4 calibration has already been inserted: query is \n %s \n",oss.str().c_str());
5812     result = conn->Query(oss.str().c_str());
5813     //
5814     if ( !result ) throw -4;
5815     //
5816     row = result->Next();
5817     //
5818     if ( row ){
5819     //
5820     if ( IsDebug() ) printf(" S4 calibration already inserted in the DB\n");
5821     if ( PEDANTIC ) throw -81;
5822     //
5823     } else {
5824     //
5825     // we have to insert a new calibration, check where to place it
5826     //
5827     oss.str("");
5828     oss << " SELECT ID,TO_TIME FROM GL_S4_CALIB WHERE "
5829     << " FROM_TIME < "<< fromtime << " AND "
5830     << " TO_TIME > "<< fromtime << ";";
5831     //
5832     if ( IsDebug() ) printf(" Check where to place the S4 calibration: query is \n %s \n",oss.str().c_str());
5833     result = conn->Query(oss.str().c_str());
5834     //
5835     if ( !result ) throw -4;
5836     //
5837     row = result->Next();
5838     //
5839     if ( !row ){
5840     //
5841     // no calibrations in the db contain our calibration
5842     //
5843     if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB \n");
5844     if ( fromtime < 1150871000 ){
5845     if ( IsDebug() ) printf(" First PAMELA flight calibration at time %u \n",fromtime);
5846     fromtime = 0;// the first flight calibration was taken at about 1156429100 s, this line allow to analyze first runs in raw mode
5847     };
5848     //
5849     oss.str("");
5850     oss << " SELECT FROM_TIME FROM GL_S4_CALIB WHERE "
5851     << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
5852     //
5853     if ( IsDebug() ) printf(" Check the upper limit for calibration: query is \n %s \n",oss.str().c_str());
5854     result = conn->Query(oss.str().c_str());
5855     //
5856     if ( !result ) throw -4;
5857     //
5858     row = result->Next();
5859     if ( !row ){
5860     totime = numeric_limits<UInt_t>::max();
5861     } else {
5862     totime = (UInt_t)atoll(row->GetField(0));
5863     };
5864     //
5865     } else {
5866     //
5867     // determine upper and lower limits and make space for the new calibration
5868     //
5869     totime = (UInt_t)atoll(row->GetField(1));
5870     //
5871     oss.str("");
5872     oss << " UPDATE GL_S4_CALIB SET "
5873     << " TO_TIME = "<< fromtime << " WHERE " // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
5874     << " ID = "<< row->GetField(0) << ";";
5875     //
5876     if ( IsDebug() ) printf(" Make space for the new calibration: query is \n %s \n",oss.str().c_str());
5877     result = conn->Query(oss.str().c_str());
5878     //
5879     if ( !result ) throw -4;
5880     //
5881     };
5882     //
5883     oss.str("");
5884     oss << " INSERT INTO GL_S4_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,OBT,PKT,BOOT_NUMBER) "
5885     << " VALUES (NULL,' "
5886     << idroot << "','"
5887     << i << "','"
5888     << fromtime << "','"
5889     << totime << "','"
5890     << obt << "','"
5891     << pkt << "','"
5892     << this->GetBOOTnumber() << "');";
5893     //
5894     if ( IsDebug() ) printf(" Insert the new calibration: query is \n %s \n",oss.str().c_str());
5895     //
5896     result = conn->Query(oss.str().c_str());
5897     //
5898     if ( !result ) throw -4;
5899     //
5900     };
5901     //
5902     } else {
5903     //
5904     if ( IsDebug() ) printf(" S4 calibration at time %u obt %u pkt %u OUTSIDE the considered time interval\n",fromtime,obt,pkt);
5905     // if ( PEDANTIC ) throw -82;
5906     //
5907     };
5908     //
5909     };
5910     //
5911     return(0);
5912     };
5913    
5914     /**
5915     * Scan the fragment table and move old fragments to the GL_RUN table
5916     */
5917     Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(){
5918     return(this->CleanGL_RUN_FRAGMENTS(""));
5919     };
5920    
5921     /**
5922     * Scan the fragment table and move old fragments to the GL_RUN table
5923     */
5924     Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(Bool_t runpieces){
5925     return(this->CleanGL_RUN_FRAGMENTS("",runpieces));
5926     };
5927    
5928     /**
5929     * Scan the fragment table and move old fragments to the GL_RUN table
5930     */
5931     Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(TString fcleanfile){
5932     return(this->CleanGL_RUN_FRAGMENTS("",false));
5933     };
5934    
5935     /**
5936     * Scan the fragment table and move old fragments to the GL_RUN table
5937     */
5938     Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(TString fcleanfile, Bool_t runpieces){
5939     //
5940     TSQLResult *nresult = 0;
5941     TSQLRow *nrow = 0;
5942     TSQLResult *nresult1 = 0;
5943     TSQLRow *nrow1 = 0;
5944     TSQLResult *result = 0;
5945     TSQLRow *row = 0;
5946     TSQLResult *result2 = 0;
5947     TSQLRow *row2 = 0;
5948     //
5949     UInt_t moved = 0;
5950     //
5951     stringstream oss;
5952     oss.str("");
5953     //
5954     // Before moving blindly the runs from GL_RUN_FRAGMENTS to GL_RUN try to find out if we have runs divided in more than two pieces (chewbacca or explicit flag only)
5955     //
5956     if ( runpieces ){
5957     //
5958     UInt_t nid = 0;
5959     UInt_t myid[500];
5960     memset(myid,0,500*sizeof(UInt_t));
5961     //
5962     oss.str("");
5963     oss << "SELECT ID,RUNTRAILER_TIME,RUNTRAILER_PKT,BOOT_NUMBER FROM GL_RUN_FRAGMENTS WHERE INSERT_TIME <= '" << clean_time->AsSQLString() << "'order BY RUNHEADER_TIME asc;";
5964     if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS runs older than %s : query is \n %s \n",clean_time->AsSQLString(),oss.str().c_str());
5965     nresult = conn->Query(oss.str().c_str());
5966     //
5967     if ( nresult ){
5968     //
5969     nrow = nresult->Next();
5970     //
5971     while ( nrow ){
5972     //
5973     UInt_t mbo = (UInt_t)atoll(nrow->GetField(3));
5974     UInt_t mrhp = (UInt_t)atoll(nrow->GetField(2));
5975     UInt_t mrht = (UInt_t)atoll(nrow->GetField(1));
5976     Bool_t anr = true;
5977     Bool_t runisthere = true;
5978     //
5979     for (UInt_t u=0; u<=nid; u++){
5980     if ( (UInt_t)atoll(nrow->GetField(0)) == myid[u] && (UInt_t)atoll(nrow->GetField(0)) != 0 ) runisthere = false;
5981     };
5982     //
5983     // check if the run is still in the fragment table or if we have just move it in the gl_run table!
5984     //
5985     if ( runisthere ){
5986     //
5987     memset(myid,0,500*sizeof(UInt_t));
5988     nid = 0;
5989     myid[nid] = (UInt_t)atoll(nrow->GetField(0));
5990     //
5991     while ( anr ){
5992     //
5993     oss.str("");
5994     oss << "SELECT ID,RUNTRAILER_TIME,RUNTRAILER_PKT,BOOT_NUMBER FROM GL_RUN_FRAGMENTS WHERE BOOT_NUMBER=" << mbo << " AND RUNHEADER_PKT=" << mrhp << "+1 AND ABS(RUNHEADER_TIME-"<< mrht <<")<=1 AND INSERT_TIME <= '" << clean_time->AsSQLString() << "' order BY RUNHEADER_TIME asc;";
5995     if ( IsDebug() ) printf(" In the loop searching for fragmented runs : query is \n %s \n",oss.str().c_str());
5996     //
5997     nresult1 = conn->Query(oss.str().c_str());
5998     //
5999     if ( nresult1 ){
6000     //
6001     if ( nresult1->GetRowCount() == 1 ){
6002     //
6003     // one piece is found
6004     //
6005     nrow1 = nresult1->Next();
6006     //
6007     if ( nrow1 ){
6008     //
6009     nid++;
6010     myid[nid] = (UInt_t)atoll(nrow1->GetField(0));
6011     mbo = (UInt_t)atoll(nrow1->GetField(3));
6012     mrhp = (UInt_t)atoll(nrow1->GetField(2));
6013     mrht = (UInt_t)atoll(nrow1->GetField(1));
6014     if ( debug ) printf(" FOUND A PIECE OF RUN! nid %u myid[nid] %u mbo %u mrhp %u mrht %u \n",nid,myid[nid],mbo,mrhp,mrht);
6015     //
6016     nrow1->Close();
6017     } else {
6018     throw -88;
6019     };
6020     } else {
6021     anr = false;
6022     };
6023     nresult1->Close();
6024     } else {
6025     throw -88;
6026     };
6027     };
6028     //
6029     // handle these runs which are ordered and "good". Does the first contain a valid runheader?
6030     //
6031     oss.str("");
6032     oss << " ID= "<< myid[0];
6033     //
6034     glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);
6035     //
6036     if ( glrun->GetACQ_BUILD_INFO() != 0 ){
6037     //
6038     // the first piece contains a good runheader we can update all the other runs with correct infos!
6039     //
6040     for (UInt_t u=1; u <= nid ; u++){
6041     oss.str("");
6042     oss << "UPDATE GL_RUN_FRAGMENTS SET "
6043     << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , "
6044     << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "
6045     << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT()<< " , "
6046     << " COMPILATIONTIMESTAMP=" << glrun->GetCOMPILATIONTIMESTAMP()<< " , "
6047     << " FAV_WRK_SCHEDULE=" << glrun->GetFAV_WRK_SCHEDULE()<< " , "
6048     << " EFF_WRK_SCHEDULE=" << glrun->GetEFF_WRK_SCHEDULE()<< " , "
6049     << " PRH_VAR_TRG_MODE_A=" << glrun->GetPRH_VAR_TRG_MODE_A()<< " , "
6050     << " PRH_VAR_TRG_MODE_B=" << glrun->GetPRH_VAR_TRG_MODE_B()<< " , "
6051     << " ACQ_BUILD_INFO=" << glrun->GetACQ_BUILD_INFO()<< " , "
6052     << " ACQ_VAR_INFO=" << glrun->GetACQ_VAR_INFO()<< " , "
6053     << " RM_ACQ_AFTER_CALIB=" << glrun->GetRM_ACQ_AFTER_CALIB()<< " , "
6054     << " RM_ACQ_SETTING_MODE=" << glrun->GetRM_ACQ_SETTING_MODE()<< " , "
6055     << " TRK_CALIB_USED=" << glrun->GetTRK_CALIB_USED()<< " , "
6056     << " CAL_DSP_MASK=" << glrun->GetCAL_DSP_MASK()<< " , "
6057 mocchiut 1.2 << " LAST_TIMESYNC=" << glrun->GetLAST_TIMESYNC()<< " , ";
6058     //
6059     if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
6060     oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12() << " , ";
6061     if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
6062     oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC() << " , ";
6063     //
6064     oss << " OBT_TIMESYNC=" << glrun->GetOBT_TIMESYNC();
6065     oss << " WHERE ID=" << myid[u] << ";";
6066 mocchiut 1.1 conn->Query(oss.str().c_str());
6067     };
6068     //
6069     } else {
6070     //
6071     // sig no runheader, let set anyway what is possible...
6072     //
6073     for (UInt_t u=1; u <= nid ; u++){
6074     oss.str("");
6075     oss << "UPDATE GL_RUN_FRAGMENTS SET "
6076 mocchiut 1.2 << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , ";
6077     //
6078     if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
6079     oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , ";
6080     if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
6081     oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , ";
6082     //
6083     oss << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "
6084 mocchiut 1.21 << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT();
6085     oss << " WHERE ID=" << myid[u] << ";"; // BUG!!! 090112
6086 mocchiut 1.1 conn->Query(oss.str().c_str());
6087     };
6088     };
6089     //
6090     // now let's look for runtrailer if any in the last run
6091     //
6092     oss.str("");
6093     oss << " ID= "<< myid[nid];
6094     //
6095     glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);
6096     //
6097     if ( glrun->GetPKT_READY_COUNTER() != 0 ){
6098     //
6099     // the first piece contains a good runtrailer we can update all the other runs with correct infos!
6100     //
6101     for (UInt_t u=0; u < nid ; u++){
6102     oss.str("");
6103     oss << "UPDATE GL_RUN_FRAGMENTS SET "
6104     << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
6105     << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "
6106     << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< " , "
6107 mocchiut 1.2 << " PKT_COUNTER=" << glrun->GetPKT_COUNTER()<< " , ";
6108     //
6109     if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
6110     oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
6111     if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) {
6112     oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
6113     //
6114     oss << " PKT_READY_COUNTER=" << glrun->GetPKT_READY_COUNTER()
6115 mocchiut 1.1 << " WHERE ID=" << myid[u] << ";";
6116     conn->Query(oss.str().c_str());
6117     };
6118     //
6119     } else {
6120     //
6121     // sig no runtrailer, let set anyway what is possible...
6122     //
6123     for (UInt_t u=0; u < nid ; u++){
6124     oss.str("");
6125     oss << "UPDATE GL_RUN_FRAGMENTS SET "
6126     << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
6127 mocchiut 1.2 << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , ";
6128     //
6129     if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
6130     oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
6131     if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ){
6132     oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
6133     //
6134 mocchiut 1.21 oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT();
6135     oss << " WHERE ID=" << myid[u] << ";"; // BUG!!! 090112
6136 mocchiut 1.1 conn->Query(oss.str().c_str());
6137     };
6138     };
6139     //
6140     // Now we want to cross indexize the runs
6141     //
6142     for (UInt_t u=0; u < nid ; u++){
6143     oss.str("");
6144     oss << "UPDATE GL_RUN_FRAGMENTS SET "
6145     << " ID_RUN_FRAG=" << myid[u+1] << " where ID=" << myid[u] <<";";
6146     conn->Query(oss.str().c_str());
6147     };
6148     oss.str("");
6149     oss << "UPDATE GL_RUN_FRAGMENTS SET "
6150     << " ID_RUN_FRAG=" << myid[0] << " where ID=" << myid[nid] <<";";
6151     conn->Query(oss.str().c_str());
6152     //
6153     // and now we can move the runs in the GL_RUN table
6154     //
6155     for (UInt_t u=0; u <= nid; u++){
6156     oss.str("");
6157     oss << " ID= "<< myid[u];
6158     //
6159     glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);
6160     //
6161     if ( u == 0 ){
6162     oss.str("");
6163     oss << " SELECT ID,NEVENTS,TRK_CALIB_USED,PKT_COUNTER FROM GL_RUN WHERE "
6164     << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND ("
6165     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
6166     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
6167     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
6168     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
6169     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
6170     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
6171     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
6172     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
6173     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
6174     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
6175     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
6176     << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
6177     //
6178     if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
6179     result2 = conn->Query(oss.str().c_str());
6180     //
6181     if ( !result2 ) throw -4;
6182     //
6183     row2 = result2->Next();
6184     //
6185     if ( row2 ){
6186 mocchiut 1.23 if ( IsDebug() ) printf(" The run already exists in the GL_RUN table! \n");
6187 mocchiut 1.1 if ( PEDANTIC ) throw -83;
6188     row2->Close();
6189     };
6190     result2->Close();
6191     };
6192     //
6193     if ( IsDebug() ) printf(" The run is new \n");
6194     if ( IsDebug() ) printf(" -> fill the DB \n");
6195     //
6196     glrun->Fill_GL_RUN(conn);
6197     //
6198     if ( IsDebug() ) printf(" Delete run %u from the GL_RUN_FRAGMENTS table \n",myid[u]);
6199     //
6200     glrun->DeleteRun(conn,myid[u],"GL_RUN_FRAGMENTS");
6201     //
6202     moved++;
6203     //
6204     };
6205     //
6206     };
6207     //
6208     nrow = nresult->Next();
6209     };
6210     };
6211    
6212    
6213    
6214     };
6215     //
6216     if ( !strcmp(fcleanfile.Data(),"") ){
6217     //
6218     // check if there are entries older than "olderthan" seconds from now
6219     //
6220     oss.str("");
6221     oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
6222     << " INSERT_TIME <= '" << clean_time->AsSQLString() << "';";
6223     //
6224     if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS runs older than %s : query is \n %s \n",clean_time->AsSQLString(),oss.str().c_str());
6225     result = conn->Query(oss.str().c_str());
6226     //
6227     } else {
6228     oss.str("");
6229     oss << " SELECT ID FROM GL_ROOT WHERE NAME='" << fcleanfile.Data() << "';";
6230     if ( IsDebug() ) printf(" Getting ID_ROOT_L0 query %s \n",oss.str().c_str());
6231     result = conn->Query(oss.str().c_str());
6232     //
6233     if ( result ){
6234     //
6235     row = result->Next();
6236     //
6237     if ( row ){
6238     oss.str("");
6239     oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
6240     << " ID_ROOT_L0=" << row->GetField(0) << ";";
6241     //
6242     if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS for ROOT file query is \n %s \n",oss.str().c_str());
6243     result = conn->Query(oss.str().c_str());
6244     //
6245     };
6246     } else {
6247     return(2);
6248     };
6249     };
6250     //
6251     if ( result ){
6252     //
6253     row = result->Next();
6254     //
6255     while ( row ){
6256     //
6257     oss.str("");
6258     oss << " ID= "<< row->GetField(0);
6259     //
6260     glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);
6261     //
6262     oss.str("");
6263 mocchiut 1.23 oss << " SELECT ID,NEVENTS,TRK_CALIB_USED,PKT_COUNTER,ID_ROOT_L0 FROM GL_RUN WHERE "
6264 mocchiut 1.1 << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND ("
6265     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
6266     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
6267     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
6268     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
6269     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
6270     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
6271     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
6272     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
6273     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
6274     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
6275     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
6276     << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
6277     //
6278     if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
6279     result2 = conn->Query(oss.str().c_str());
6280     //
6281     if ( !result2 ) throw -4;
6282     //
6283     row2 = result2->Next();
6284     //
6285     if ( !row2 ){
6286     //
6287     if ( IsDebug() ) printf(" The run is new \n");
6288     if ( IsDebug() ) printf(" -> fill the DB \n");
6289     //
6290     // glrun->SetID(this->AssignRunID()); we use the old run number!
6291     glrun->SetID_RUN_FRAG(glrun->GetID());
6292     glrun->Fill_GL_RUN(conn);
6293     //
6294 mocchiut 1.2 // oss.str("");
6295     // oss << " SELECT ID FROM GL_RUN WHERE "
6296     // << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
6297     // << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
6298     // << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
6299     // << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
6300     // << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
6301     // //
6302     // if ( IsDebug() ) printf(" Look for the ID of the inserted run: query is \n %s \n",oss.str().c_str());
6303     // result2 = conn->Query(oss.str().c_str());
6304     // //
6305     // if ( !result2 ) throw -4;
6306     // //
6307     // row2 = result2->Next();
6308     // //
6309     // if ( !row2 ) throw -25;
6310     // //
6311     // oss.str("");
6312     // oss << " UPDATE GL_RUN SET ID_RUN_FRAG = " << row2->GetField(0) << " WHERE ID = " << row2->GetField(0);
6313     // if ( IsDebug() ) printf(" Update the ID_RUN_FRAG of the inserted run: query is \n %s \n",oss.str().c_str());
6314     // result2 = conn->Query(oss.str().c_str());
6315     // //
6316     // if ( !result2 ) throw -4;
6317 mocchiut 1.1 //
6318     moved++;
6319     //
6320     } else {
6321 mocchiut 1.23
6322     // questa parte mah mah mah... da controllare
6323    
6324     //
6325     // we end up here if chewbacca and we have RH---| small gap |---RT, in this case the two pieces are attached and moved to GL_RUN. We are now processing the
6326     // "small gap" piece... we recognize this since: we have two entries from this query, the pkt number is consistent with our pkt number.
6327     //
6328     // 090112 [8RED (-70): RUN ALREADY INSERTED]
6329     //
6330     Bool_t OK = false;
6331     UInt_t IDRL2A = 0;
6332     UInt_t IDRL2B = 0;
6333     if ( result2->GetRowCount() == 2 ){
6334     IDRL2A = (UInt_t)atoll(row2->GetField(0));
6335     UInt_t IDRL0A = (UInt_t)atoll(row2->GetField(4));
6336     row2 = result2->Next();
6337     IDRL2B = (UInt_t)atoll(row2->GetField(0));
6338     UInt_t IDRL0B = (UInt_t)atoll(row2->GetField(4));
6339     if ( IsDebug() ) printf(" IDRL0A %u B %u IDRL2A %u B %u \n",IDRL0A,IDRL0B,IDRL2A,IDRL2B);
6340     // if ( IDRL0A == IDRL0B ){
6341     // TSQLResult *result2a = 0;
6342     // TSQLRow *row2a = 0;
6343     // oss.str("");
6344     // oss << "select PKT_NUMBER_FINAL from ROOT_TABLE_MERGING where REAL_TIME_INIT<" << chrtinit << " order by REAL_TIME_INIT desc limit 1;";
6345     // if ( IsDebug() ) printf(" Check if we are in the case RH---| small gap |---RT: query is \n %s \n",oss.str().c_str());
6346     // result2a = conn->Query(oss.str().c_str());
6347     // //
6348     // if ( !result2a ) throw -4;
6349     // //
6350     // row2a = result2a->Next();
6351     // //
6352     // if ( row2a ){
6353     // UInt_t PKA = (UInt_t)atoll(row2a->GetField(0));
6354     // delete result2a;
6355     // oss.str("");
6356     // oss << "select PKT_NUMBER_INIT from ROOT_TABLE_MERGING where REAL_TIME_INIT>" << chrtinit << " order by REAL_TIME_INIT asc limit 1;";
6357     // if ( IsDebug() ) printf(" Check if we are in the case RH---| small gap |---RT: query is \n %s \n",oss.str().c_str());
6358     // result2a = conn->Query(oss.str().c_str());
6359     // //
6360     // if ( !result2a ) throw -4;
6361     // //
6362     // row2a = result2a->Next();
6363     // //
6364     // if ( row2a ){
6365     // UInt_t PKB = (UInt_t)atoll(row2a->GetField(0));
6366     // //
6367     // if ( IsDebug() ) printf(" PKT(PKA) + 1 %llu == runheaderpkt %llu && PKB = runtrailer %llu + 1 %llu \n",PKT(PKA)+1LL, PKT(glrun->GetRUNHEADER_PKT()),PKT(PKB), PKT(glrun->GetRUNTRAILER_PKT())+1LL);
6368     // if ( PKT(PKA)+1LL == PKT(glrun->GetRUNHEADER_PKT()) && PKT(PKB) == PKT(glrun->GetRUNTRAILER_PKT())+1LL ){
6369     // if ( IsDebug() ) printf(" Ok, we are in the case: RH---| small gap |---RT \n");
6370     OK = true;
6371     // };
6372     // };
6373     // };
6374     // };
6375     };
6376     if ( OK ){
6377     //
6378     // this is the case in which we must insert a piece of run between two fragments in the GL_RUN table
6379     //
6380     // we have to update with runheader/trailer infos our run and we have to change the ROOT_ID_FRAG of the header piece ( 1/2 2/1 must become 1/3 3/2 2/1 )
6381     //
6382     GL_RUN *glA = new GL_RUN();
6383     glA->Query_GL_RUN(IDRL2A,conn);
6384     //
6385     if ( glA->GetACQ_BUILD_INFO() != 0 ){
6386     //
6387     // the first piece contains a good runheader we can update all the other runs with correct infos!
6388     //
6389     oss.str("");
6390     oss << "UPDATE GL_RUN_FRAGMENTS SET "
6391     << " RUNHEADER_TIME=" << glA->GetRUNHEADER_TIME()<< " , "
6392     << " RUNHEADER_OBT=" << glA->GetRUNHEADER_OBT()<< " , "
6393     << " RUNHEADER_PKT=" << glA->GetRUNHEADER_PKT()<< " , "
6394     << " COMPILATIONTIMESTAMP=" << glA->GetCOMPILATIONTIMESTAMP()<< " , "
6395     << " FAV_WRK_SCHEDULE=" << glA->GetFAV_WRK_SCHEDULE()<< " , "
6396     << " EFF_WRK_SCHEDULE=" << glA->GetEFF_WRK_SCHEDULE()<< " , "
6397     << " PRH_VAR_TRG_MODE_A=" << glA->GetPRH_VAR_TRG_MODE_A()<< " , "
6398     << " PRH_VAR_TRG_MODE_B=" << glA->GetPRH_VAR_TRG_MODE_B()<< " , "
6399     << " ACQ_BUILD_INFO=" << glA->GetACQ_BUILD_INFO()<< " , "
6400     << " ACQ_VAR_INFO=" << glA->GetACQ_VAR_INFO()<< " , "
6401     << " RM_ACQ_AFTER_CALIB=" << glA->GetRM_ACQ_AFTER_CALIB()<< " , "
6402     << " RM_ACQ_SETTING_MODE=" << glA->GetRM_ACQ_SETTING_MODE()<< " , "
6403     << " TRK_CALIB_USED=" << glA->GetTRK_CALIB_USED()<< " , "
6404     << " CAL_DSP_MASK=" << glA->GetCAL_DSP_MASK()<< " , "
6405     << " LAST_TIMESYNC=" << glA->GetLAST_TIMESYNC()<< " , ";
6406     //
6407     if ( glA->GetPHYSENDRUN_MASK_S3S2S12() )
6408     oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12() << " , ";
6409     if ( glA->GetPHYSENDRUN_MASK_S11CRC() )
6410     oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC() << " , ";
6411     //
6412     oss << " OBT_TIMESYNC=" << glA->GetOBT_TIMESYNC();
6413     oss << " WHERE ID=" << glrun->GetID() << ";";
6414     if ( IsDebug() ) printf(" update with correct infos: %s\n",oss.str().c_str());
6415     conn->Query(oss.str().c_str());
6416     //
6417     } else {
6418     //
6419     // sig no runheader, let set anyway what is possible...
6420     //
6421     oss.str("");
6422     oss << "UPDATE GL_RUN_FRAGMENTS SET "
6423     << " RUNHEADER_TIME=" << glA->GetRUNHEADER_TIME()<< " , ";
6424     //
6425     if ( glA->GetPHYSENDRUN_MASK_S3S2S12() )
6426     oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , ";
6427     if ( glA->GetPHYSENDRUN_MASK_S11CRC() )
6428     oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , ";
6429     //
6430     oss << " RUNHEADER_OBT=" << glA->GetRUNHEADER_OBT()<< " , "
6431     << " RUNHEADER_PKT=" << glA->GetRUNHEADER_PKT();
6432     oss << " WHERE ID=" << glrun->GetID() << ";";
6433     if ( IsDebug() ) printf(" update with correct infos2: %s\n",oss.str().c_str());
6434     conn->Query(oss.str().c_str());
6435     };
6436     //
6437     // update runheader ROOT_ID_FRAG
6438     //
6439     oss.str("");
6440     oss << "UPDATE GL_RUN SET ID_RUN_FRAG = " << glrun->GetID() << " where ID = " << IDRL2A << ";";
6441     if ( IsDebug() ) printf(" update gl_run to have cross indexing: %s\n",oss.str().c_str());
6442     conn->Query(oss.str().c_str());
6443     //
6444     // now let's look for runtrailer if any in the last run
6445     //
6446     glA->Query_GL_RUN(IDRL2B,conn);
6447     //
6448     if ( glA->GetPKT_READY_COUNTER() != 0 ){
6449     //
6450     // the first piece contains a good runtrailer we can update all the other runs with correct infos!
6451     //
6452     oss.str("");
6453     oss << "UPDATE GL_RUN_FRAGMENTS SET "
6454     << " RUNTRAILER_TIME=" << glA->GetRUNTRAILER_TIME()<< " , "
6455     << " RUNTRAILER_OBT=" << glA->GetRUNTRAILER_OBT()<< " , "
6456     << " RUNTRAILER_PKT=" << glA->GetRUNTRAILER_PKT()<< " , "
6457     << " PKT_COUNTER=" << glA->GetPKT_COUNTER()<< " , ";
6458     //
6459     if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ){
6460     oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
6461     if ( glA->GetPHYSENDRUN_MASK_S11CRC() ) {
6462     oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
6463     //
6464     oss << " PKT_READY_COUNTER=" << glA->GetPKT_READY_COUNTER()
6465     << " WHERE ID=" << glrun->GetID() << ";";
6466     if ( IsDebug() ) printf(" update with correct trailer infos: %s\n",oss.str().c_str());
6467     conn->Query(oss.str().c_str());
6468     //
6469     } else {
6470     //
6471     // sig no runtrailer, let set anyway what is possible...
6472     //
6473     oss.str("");
6474     oss << "UPDATE GL_RUN_FRAGMENTS SET "
6475     << " RUNTRAILER_TIME=" << glA->GetRUNTRAILER_TIME()<< " , "
6476     << " RUNTRAILER_OBT=" << glA->GetRUNTRAILER_OBT()<< " , ";
6477     //
6478     if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ){
6479     oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
6480     if ( glA->GetPHYSENDRUN_MASK_S11CRC() ){
6481     oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
6482     //
6483     oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()
6484     << " WHERE ID=" << glrun->GetID() << ";";
6485     if ( IsDebug() ) printf(" update with correct trailer infos2: %s\n",oss.str().c_str());
6486     conn->Query(oss.str().c_str());
6487     };
6488     //
6489     UInt_t myi = glrun->GetID();
6490     oss.str("");
6491     oss << " ID= "<< myi;
6492     //
6493     glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);
6494     //
6495     // fill the new run in GL_RUN
6496     //
6497     glrun->SetID_RUN_FRAG(IDRL2B);
6498     glrun->Fill_GL_RUN(conn);
6499     glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
6500     delete glA;
6501     moved++;
6502     //
6503     } else {
6504     //
6505     // is just a repetition
6506     //
6507     if ( IsDebug() ) printf(" The run %u is already present in the GL_RUN table...\n",glrun->GetID());
6508     // printf(" CCCCCCCCICCCCCCCCCCCCIOOOOOOOOOO si muove Ciccio! %u \n",glrun->GetID());
6509     // if ( PEDANTIC && glrun->GetID() != 61563 ) throw -83;
6510     if ( PEDANTIC ) throw -83;
6511     };
6512     // if ( IsDebug() ) printf(" The run already exists in the GL_RUN table! ...\n");
6513     // if ( PEDANTIC ) throw -83;
6514 mocchiut 1.1 };
6515     if ( IsDebug() ) printf(" Delete run %s from the GL_RUN_FRAGMENTS table \n",row->GetField(0));
6516     //
6517     //
6518     glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
6519 mocchiut 1.2 // oss.str("");
6520     // oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);
6521     // if ( IsDebug() ) printf(" Clean the GL_RUN_FRAGMENTS table: query is \n %s \n",oss.str().c_str());
6522     // result2 = conn->Query(oss.str().c_str());
6523     // //
6524     // if ( !result2 ) throw -4;
6525     // //
6526 mocchiut 1.1 row = result->Next();
6527     };
6528     };
6529     if ( IsDebug() ) printf(" Moved %u runs\n",moved);
6530     return(0);
6531     };
6532    
6533     /**
6534     * Check if runs are good, i.e. if the tracker calibration is correctly associated..
6535     */
6536     Int_t PamelaDBOperations::ValidateRuns(){
6537     return(this->ValidateRuns(""));
6538     };
6539    
6540     /**
6541     * Check if runs are good, i.e. if the tracker calibration is correctly associated..
6542     */
6543     Int_t PamelaDBOperations::ValidateRuns(TString valfile){
6544     //
6545     TSQLResult *result = 0;
6546     TSQLRow *row = 0;
6547     //
6548     UInt_t calibtime = 50;
6549     //
6550     stringstream oss;
6551     oss.str("");
6552     //
6553     // =======================================================
6554     // validate runs by checking missing calibrations
6555     // =======================================================
6556     UInt_t t_stop = 0;
6557     UInt_t t_start = 0;
6558     if ( !strcmp(valfile.Data(),"") ) {
6559     // --------------------------------------------------------------
6560     // 1) get the OBT of the last run inserted after clean-time limit
6561     // --------------------------------------------------------------
6562     oss.str("");
6563     oss << " SELECT * FROM GL_RUN WHERE INSERT_TIME <= '" << clean_time->AsSQLString()
6564     << "' ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
6565     if ( IsDebug() ) printf(" Get start validation-time: query is \n %s \n",oss.str().c_str());
6566     result = conn->Query(oss.str().c_str());
6567     if ( !result ) throw -4;
6568     if ( !result->GetRowCount() ) {
6569     printf(" No runs to validate \n");
6570     return(1);
6571     }else{
6572     row = result->Next();
6573     t_start = (UInt_t)atoll(row->GetField(4));
6574     };
6575     // --------------------------------------------------------------
6576     // 2) get the OBT of the last validated run
6577     // --------------------------------------------------------------
6578     oss.str("");
6579 mocchiut 1.12 // oss << " SELECT * FROM GL_RUN WHERE VALIDATION=1 AND RUNHEADER_TIME<="<< t_start
6580     oss << " SELECT * FROM GL_RUN WHERE VALIDATION>0 AND RUNHEADER_TIME<="<< t_start
6581 mocchiut 1.1 <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
6582     if ( IsDebug() ) printf(" Get stop validation-time: query is \n %s \n",oss.str().c_str());
6583     result = conn->Query(oss.str().c_str());
6584     if ( !result ) throw -4;
6585     if ( result->GetRowCount() ){
6586     row = result->Next();
6587     t_stop = (UInt_t)atoll(row->GetField(4));
6588     };
6589     if ( IsDebug() ) printf("Validation interval: from time %u - to time %u \n\n",t_stop,t_start);
6590     // --------------------------------------------------------------
6591     // now retrieves runs to be validated
6592     // --------------------------------------------------------------
6593     oss.str("");
6594     oss << " SELECT * FROM GL_RUN WHERE RUNHEADER_TIME <=" << t_start;
6595     oss << " AND RUNHEADER_TIME >="<< t_stop;
6596     oss << " ORDER BY RUNHEADER_TIME DESC;";
6597     if ( IsDebug() )printf(" Check runs for validation: query is \n %s \n",oss.str().c_str());
6598     result = conn->Query(oss.str().c_str());
6599     } else {
6600     //
6601     stringstream myquery;
6602     UInt_t myid = 0;
6603     myquery.str("");
6604     myquery << " SELECT ID FROM GL_ROOT where NAME='"<<valfile.Data() <<"';";
6605     //
6606     result = conn->Query(myquery.str().c_str());
6607     //
6608     row = result->Next();
6609     if( !row ){
6610     if ( strcmp(valfile.Data(),GetRootName().Data()) ){
6611     if ( IsDebug() ) printf(" No file to be validated even if option \"-validate file\" was used!!\n");
6612     return(2);
6613     };
6614     if ( IsDebug() ) printf(" No file to be validated (force mode)! \n");
6615     return(0);
6616     };
6617     myid=(UInt_t)atoll(row->GetField(0));
6618     //
6619     myquery.str("");
6620     myquery << " SELECT MAX(RUNTRAILER_TIME),MIN(RUNHEADER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< myid <<";";
6621     //
6622     result = conn->Query(myquery.str().c_str());
6623     //
6624     row = result->Next();
6625     if( !row->GetField(0) || !row->GetField(1)){
6626     //
6627     if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
6628     //
6629     return(0);
6630     //
6631     } else {
6632     //
6633     UInt_t runhtime = (UInt_t)atoll(row->GetField(0));
6634     UInt_t runttime = (UInt_t)atoll(row->GetField(1));
6635     UInt_t caltime = 0;
6636     //
6637     myquery.str("");
6638     myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
6639     myquery << " order by FROM_TIME asc limit 1;";
6640     //
6641     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
6642     //
6643     //
6644     result = conn->Query(myquery.str().c_str());
6645     //
6646     row = result->Next();
6647     if( !row ){
6648     caltime = runhtime;
6649     } else {
6650     caltime = (UInt_t)atoll(row->GetField(0));
6651     };
6652     //
6653     myquery.str("");
6654     myquery << " SELECT * from GL_RUN where RUNHEADER_TIME>="<< runttime <<" AND RUNHEADER_TIME<=" ;
6655     myquery << caltime << " order by RUNHEADER_TIME DESC";
6656     //
6657     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
6658     //
6659     result = conn->Query(myquery.str().c_str());
6660     //
6661     };
6662     };
6663     //
6664     if ( !result ) throw -4;
6665     if ( !result->GetRowCount() && IsDebug() ) printf(" No runs to validate \n");
6666     //
6667     Int_t nrow = 0;
6668     GL_RUN* this_run = new GL_RUN();
6669     GL_RUN* next_run = new GL_RUN();
6670     Int_t nseq_max = 1000;
6671 mocchiut 1.2 // UInt_t* sequence = new UInt_t[100];
6672 mocchiut 1.1 vector<UInt_t> sequence(nseq_max);
6673     Int_t nseq = 0;
6674     Bool_t CHECK = false;
6675     Bool_t this_ONLINE = false;
6676     Bool_t next_ONLINE = false;
6677     UInt_t t1=0,t2=0;
6678     // ---------------------------------------------------------------------------------
6679     // - loop over runs, back in time,
6680     // - select sequences of runs close in time (less than calibtime s apart),
6681     // which could be preceeded by a calibration
6682     // - check if there might be a missing calibration
6683     // ---------------------------------------------------------------------------------
6684     while(1){
6685    
6686 mocchiut 1.2 row = result->Next();
6687     if( row == NULL ) break;
6688 mocchiut 1.1
6689 mocchiut 1.2 //------------
6690     //get run info
6691     //------------
6692     this_run->Set_GL_RUN(row);
6693 mocchiut 1.1
6694 mocchiut 1.2 Bool_t this_BAD = false;
6695     if(this_run->GetTRK_CALIB_USED() == 1 || this_run->GetTRK_CALIB_USED() == 2) this_ONLINE = true;
6696     else if (this_run->GetTRK_CALIB_USED() == 104) this_ONLINE = false;
6697     else{
6698     // printf("Missing or corrupted header!! \n");
6699     this_ONLINE = false;
6700     this_BAD = true;
6701     };
6702 mocchiut 1.1
6703 mocchiut 1.2 //-----------------------------------
6704     //compare with previous(next in time)
6705     //-----------------------------------
6706     CHECK = false;
6707     UInt_t interval=0;
6708 mocchiut 1.1
6709 mocchiut 1.2 if( nrow != 0){
6710 mocchiut 1.1
6711    
6712 mocchiut 1.2 t1 = this_run->GetRUNTRAILER_TIME();
6713     t2 = next_run->GetRUNHEADER_TIME();
6714     interval = (t2-t1);
6715 mocchiut 1.1
6716 mocchiut 1.2 if(this_ONLINE && next_ONLINE){ // this: ON-LINE + next: ON-LINE
6717 mocchiut 1.1
6718 mocchiut 1.2 if( this_run->ID == next_run->ID_RUN_FRAG ) interval = 0; //=> run fragments
6719 mocchiut 1.1
6720 mocchiut 1.2 if( interval >= calibtime )CHECK = true; //more than calibtime s => there might be a calibration
6721 mocchiut 1.1
6722 mocchiut 1.2 if( !CHECK && this_run->VALIDATION ){
6723 mocchiut 1.12 // for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
6724     for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],this_run->VALIDATION);
6725 mocchiut 1.2 nseq=0;
6726     }
6727 mocchiut 1.1
6728 mocchiut 1.2 }else if( !this_ONLINE && next_ONLINE) { // this: DEFAULT + next:ON-LINE
6729 mocchiut 1.1
6730 mocchiut 1.2 CHECK = true;
6731 mocchiut 1.1
6732 mocchiut 1.2 }else if( !next_ONLINE ){ // this:ANY + next:DEFAULT
6733 mocchiut 1.1
6734 mocchiut 1.2 assignVALIDATION(next_run->ID,true);
6735     nseq=0;
6736     }
6737     }
6738 mocchiut 1.1
6739 mocchiut 1.2 //----------------------------
6740     //check run sequence for calib
6741     //----------------------------
6742     if( CHECK ){
6743     // check if calibration exists
6744     if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);
6745 mocchiut 1.12 // Bool_t MISSING = MissingTRK_CALIB(t1,t2);
6746     UInt_t MISSING = MissingTRK_CALIB(t1,t2);
6747     UInt_t val = 0;
6748     if ( MISSING == 1 ) val = 0;
6749     if ( MISSING == 0 ) val = 1;
6750     if ( MISSING == 2 ) val = 2;
6751     for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],val);
6752 mocchiut 1.2 nseq=0;
6753     };
6754     //--------------
6755     //store run info
6756     //--------------
6757     *next_run = *this_run;
6758     next_ONLINE = this_ONLINE;
6759     if( !this_BAD ){
6760     if(nseq < nseq_max){
6761     sequence[nseq] = this_run->ID;
6762     nseq++;
6763     }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);
6764     };
6765 mocchiut 1.1
6766 mocchiut 1.2 if ( IsDebug() ) printf("%i Run %u \n",nrow,this_run->ID);
6767     nrow++;
6768 mocchiut 1.1
6769     };
6770     delete this_run;
6771     delete next_run;
6772     //
6773     return(0);
6774     };
6775     /**
6776     * Check if there might be a missing tracker calibration in a given time interval
6777     * @param t1 From absolute time
6778     * @param t2 To absolute time
6779     * @return true if there might be a missing calibration
6780     */
6781 mocchiut 1.12 //Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
6782     UInt_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
6783 mocchiut 1.1
6784 mocchiut 1.2 GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();
6785 mocchiut 1.1
6786 pam-fi 1.4 // get the closest calibration before the run start (t2)
6787 mocchiut 1.12 // if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true); //>>> missing
6788     if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(1); //>>> missing
6789 mocchiut 1.1
6790 mocchiut 1.12 // if ( trkcalib->TO_TIME < t2 ) return(true); //>>> missing
6791     if ( trkcalib->TO_TIME < t2 ) return(1); //>>> missing
6792 mocchiut 1.1
6793 mocchiut 1.2 //==============================================================
6794     // Check is done first on the basis of time between calibration,
6795     // which should be equal to the time between ascending-nodes.
6796     //==============================================================
6797     if ( t2 - trkcalib->FROM_TIME > 5700) {
6798     if ( IsDebug() )printf("Long time between calib and run start %u :-( ==> there might be a missing calib \n",t2 - trkcalib->FROM_TIME);
6799     //==============================================================
6800     // there might be a missing calibration, due to:
6801     // - MM full
6802     // - corrupted packets
6803     // - loss of data
6804     // There is an exception in case a download was done during ascending node
6805     //==============================================================
6806     Bool_t DOWNLOAD = false;
6807     // check if the calib was skipped becouse of download .... DA FARE!!
6808 mocchiut 1.12 // if(DOWNLOAD)return(false);
6809     if(DOWNLOAD)return(0);
6810 mocchiut 1.1
6811 mocchiut 1.12 // return(true); //>>> missing
6812     return(1); //>>> missing
6813 mocchiut 1.1
6814 mocchiut 1.2 };
6815 mocchiut 1.1
6816 mocchiut 1.2 //==============================================================
6817     // If the last calibration is close to the run less than this time,
6818     // it is enough to say that there are no missing calibrations
6819     //==============================================================
6820     // the long time interval bewteen runs might be due to download
6821     if ( IsDebug() )printf("Short time between calib and run start %u :-) ==> OK! \n",t2 - trkcalib->FROM_TIME);
6822 mocchiut 1.12 if ( trkcalib->VALIDATION ) return(0);
6823     if ( IsDebug() )printf("Calibration is not validated... :-/ ==> OK but with VALIDATION=2! \n");
6824     return(2);
6825 mocchiut 1.1
6826     };
6827     /**
6828     * Assign VALIDATION value to a GL_RUN entry
6829     * @param idrun Run ID
6830     * @param validation true/false
6831     */
6832     Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){
6833 mocchiut 1.12 return(this->assignVALIDATION(idrun,(UInt_t)validation));
6834     }
6835    
6836     Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, UInt_t validation){
6837 mocchiut 1.2 TSQLResult *result = 0;
6838     stringstream oss;
6839     oss.str("");
6840     oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";
6841     //
6842     // if ( IsDebug() )
6843     // printf(" Set VALIDATION = %i for run %i \n",validation,idrun);
6844     if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());
6845     result = conn->Query(oss.str().c_str());
6846     if ( !result ) throw -4;
6847     return(0);
6848 mocchiut 1.1 }
6849    
6850    
6851    
6852     // Insert TLEs from file tlefilename in the table GL_TLE in the db
6853     // opened by conn, sorting them by date from older to newer, if each
6854     // TLE has not been alread inserted.
6855     Int_t PamelaDBOperations::populateTLE()//(TSQLServer *conn, char *tleFile)
6856     {
6857     fstream tlefile(tlefilename, ios::in);
6858    
6859     if ( !tlefile ) throw -7;
6860    
6861     vector<cTle*> ctles;
6862     vector<cTle*>::iterator iter;
6863     int present = 0;
6864    
6865     // Get three lines from tlefile, create a cTle object and put it
6866     // into ctles
6867     while(1) {
6868     cTle *tlef;
6869     string str1, str2, str3;
6870    
6871     getline(tlefile, str1);
6872     if(tlefile.eof()) break;
6873    
6874     getline(tlefile, str2);
6875     if(tlefile.eof()) break;
6876    
6877     getline(tlefile, str3);
6878     if(tlefile.eof()) break;
6879    
6880     // We now have three good lines for a cTle.
6881     tlef = new cTle(str1, str2, str3);
6882     ctles.push_back(tlef);
6883     }
6884    
6885     tlefile.close();
6886    
6887     // Sort by date
6888     sort(ctles.begin(), ctles.end(), compTLE);
6889    
6890     // Now we insert each TLE into the db
6891     for(iter = ctles.begin(); iter != ctles.end(); iter++) {
6892     cTle *tle = *iter;
6893    
6894     // Do nothing if it's already present in the db. Just increase
6895     // the counter present.
6896     if (! isTlePresent(tle))
6897     {
6898     int status = insertTle(tle);
6899    
6900     // Insert query failed. Return 1.
6901     if(status == EXIT_FAILURE) {
6902    
6903     if( IsDebug() ) {
6904     cerr << "Error: inserting TLE:" << endl
6905     << tle->getName() << endl
6906     << tle->getLine1() << endl
6907     << tle->getLine2() << endl;
6908     }
6909    
6910     throw -4;
6911     return 1;
6912     }
6913    
6914     }
6915     else
6916     present++;
6917    
6918     }
6919    
6920     int inserted = ctles.size() - present; // Number of inserted TLE.
6921     if ( IsDebug() )
6922     cout << "\nProcessed TLEs ranging from " << getTleDatetime(ctles[0]) << " to " << getTleDatetime(ctles[ctles.size()-1]) << "." << endl
6923     << inserted << " newly inserted TLEs out of " << ctles.size() << " processed." << endl;
6924    
6925     ctles.clear();
6926    
6927    
6928     // Return 2 if no new TLE has been inserted. 0 otherwise.
6929     if(! inserted ) return 2;
6930     return 0;
6931     }
6932    
6933    
6934     // Insert tle in the table GL_TLE using the connection conn.
6935     Int_t PamelaDBOperations::insertTle(cTle *tle)
6936     {
6937     stringstream oss;
6938     TSQLResult *result = 0;
6939    
6940     oss.str("");
6941     oss << " INSERT INTO GL_TLE (TLE1, TLE2, TLE3, FROM_TIME)"
6942     << " VALUES ( '"
6943     << tle->getName() << "', '"
6944     << tle->getLine1() << "', '"
6945     << tle->getLine2() << "', '"
6946     << getTleDatetime(tle) << "')";
6947    
6948     // cout << oss.str().c_str() << endl;
6949     result = conn->Query(oss.str().c_str());
6950     if (result == NULL)
6951     return EXIT_FAILURE;
6952    
6953     return EXIT_SUCCESS;
6954     }
6955    
6956    
6957     // Return whether tle is already in the db connected by conn.
6958     bool PamelaDBOperations::isTlePresent(cTle *tle)
6959     {
6960     stringstream oss;
6961     TSQLResult *result = 0;
6962    
6963     oss.str("");
6964     oss << "SELECT * FROM GL_TLE WHERE FROM_TIME = '"
6965     << getTleDatetime(tle) << "'";
6966    
6967     result = conn->Query(oss.str().c_str());
6968     if (result == NULL) throw -4;
6969    
6970     if (result->GetRowCount())
6971     return true;
6972     else
6973     return false;
6974     }
6975    
6976    
6977     // Return whether the first TLE is dated early than the second
6978     bool compTLE (cTle *tle1, cTle *tle2)
6979     {
6980     return getTleJulian(tle1) < getTleJulian(tle2);
6981     }
6982    
6983    
6984     // Return the date of the tle using the format (year-2000)*1e3 +
6985     // julian day. e.g. 6365 is the 31th Dec 2006.
6986     // It does *not* return a cJulian date.
6987     float getTleJulian(cTle *tle) {
6988     return tle->getField(cTle::FLD_EPOCHYEAR)*1e3 + tle->getField(cTle::FLD_EPOCHDAY);
6989     }
6990    
6991    
6992     // Return a string like YYYY-MM-DD hh:mm:ss, usable for mysql datetime
6993     // format.
6994     string getTleDatetime(cTle *tle)
6995     {
6996     int year, mon, day, hh, mm, ss;
6997     double dom; // day of month (is double!)
6998     stringstream date; // date in datetime format
6999    
7000     // create a cJulian from the date in tle
7001     cJulian jdate = cJulian( 2000 + (int) tle->getField(cTle::FLD_EPOCHYEAR), tle->getField(cTle::FLD_EPOCHDAY));
7002    
7003     // get year, month, day of month
7004     jdate.getComponent(&year, &mon, &dom);
7005    
7006     // build a datetime YYYY-MM-DD hh:mm:ss
7007     date.str("");
7008     day = (int) floor(dom);
7009     hh = (int) floor( (dom - day) * 24);
7010     mm = (int) floor( ((dom - day) * 24 - hh) * 60);
7011     ss = (int) floor( ((((dom - day) * 24 - hh) * 60 - mm) * 60));
7012     // ms = (int) floor( (((((dom - day) * 24 - hh) * 60 - mm) * 60) - ss) * 1000);
7013    
7014     date << year << "-" << mon << "-" << day << " " << hh << ":" << mm << ":" << ss;
7015    
7016     return date.str();
7017     }
7018    
7019     /**
7020     * Remove a file from the DB, delete on cascade all entries related to that file
7021     * rearrange GL_RUN and GL_XXX_CALIB tables, turn off validation till the following
7022     * calibration
7023     **/
7024     Int_t PamelaDBOperations::removeFile(TString remfile){
7025     //
7026     // Determine ID_ROOT_L0 and ID_RAW
7027     //
7028     TSQLResult *pResult;
7029     TSQLRow *Row;
7030     stringstream myquery;
7031     //
7032     myquery.str("");
7033 mocchiut 1.10 myquery << " SELECT ID,ID_RAW,ID_TIMESYNC FROM GL_ROOT where NAME='"<<remfile.Data() <<"';";
7034 mocchiut 1.1 //
7035     pResult = conn->Query(myquery.str().c_str());
7036     //
7037     Row = pResult->Next();
7038     if( !Row ){
7039     if ( strcmp(remfile.Data(),GetRootName().Data()) ){
7040     if ( IsDebug() ) printf(" No file to be removed even if option \"-remove file\" was used!!\n");
7041     return(1);
7042     };
7043     if ( IsDebug() ) printf(" No file to be removed (force mode)! \n");
7044     return(0);
7045     };
7046     //
7047     this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));
7048     this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));
7049 mocchiut 1.10 UInt_t idtsy=(UInt_t)atoll(Row->GetField(2));
7050 mocchiut 1.1 //
7051     this->ValidationOFF();
7052     //
7053     this->RemoveCALIBS();
7054     //
7055     this->RemoveRUNS();
7056     //
7057 mocchiut 1.10 this->RemoveFILES(idtsy);
7058 mocchiut 1.1 //
7059     this->SetID_ROOT(0);
7060     this->SetID_RAW(0);
7061     //
7062     return(0);
7063     };
7064    
7065     /**
7066     *
7067     * Set validation bit to zero for runs following the removing file till
7068     * 1) a run with TRK_CALIB_USED=140
7069     * 2) a run with VALIDATION = 0
7070     * 3) the next calibration
7071     *
7072     **/
7073     void PamelaDBOperations::ValidationOFF(){
7074     TSQLResult *pResult;
7075     TSQLRow *Row;
7076     stringstream myquery;
7077     Int_t unv = 0;
7078     //select ID from GL_RUN where RUNHEADER_TIME>=1152671382 AND (VALIDATION=0 OR TRK_CALIB_USED=104) order by RUNHEADER_TIME asc limit 1;
7079     myquery.str("");
7080     myquery << " SELECT MAX(RUNTRAILER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
7081     //
7082     pResult = conn->Query(myquery.str().c_str());
7083     //
7084     Row = pResult->Next();
7085     if( !Row->GetField(0) ){
7086     //
7087     if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
7088     //
7089     } else {
7090     //
7091     UInt_t runhtime = (UInt_t)atoll(Row->GetField(0));
7092     UInt_t caltime = 0;
7093     //
7094     myquery.str("");
7095     myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
7096     myquery << " order by FROM_TIME asc limit 1;";
7097     //
7098     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
7099     //
7100     //
7101     delete pResult;
7102     pResult = conn->Query(myquery.str().c_str());
7103     //
7104     Row = pResult->Next();
7105     if( !Row ){
7106     caltime = runhtime;
7107     } else {
7108     caltime = (UInt_t)atoll(Row->GetField(0));
7109     };
7110     //
7111     myquery.str("");
7112     myquery << " SELECT ID,RUNHEADER_TIME from GL_RUN where RUNHEADER_TIME>="<< runhtime <<" AND (VALIDATION=0 OR TRK_CALIB_USED=104 OR RUNHEADER_TIME>" ;
7113     myquery << caltime << ") order by RUNHEADER_TIME asc LIMIT 1";
7114     //
7115     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
7116     //
7117     pResult = conn->Query(myquery.str().c_str());
7118     //
7119     Row = pResult->Next();
7120     if( !Row ){
7121     //
7122     if ( IsDebug() ) printf(" NO RUN NEED TO BE UNVALIDATED \n");
7123     //
7124     } else {
7125     myquery.str("");
7126     myquery << " SELECT ID from GL_RUN where RUNHEADER_TIME<"<< Row->GetField(1) <<" AND ";
7127     myquery << " RUNHEADER_TIME>=" <<runhtime;
7128     myquery << " order by RUNHEADER_TIME asc;";
7129     //
7130     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
7131     //
7132     pResult = conn->Query(myquery.str().c_str());
7133     //
7134     Row = pResult->Next();
7135     while ( Row ){
7136     //
7137     unv++;
7138     this->assignVALIDATION((UInt_t)atoll(Row->GetField(0)), false);
7139     Row = pResult->Next();
7140     //
7141     };
7142     };
7143     };
7144     if ( IsDebug() ) printf(" %u runs have been unvalidated \n",unv);
7145     };
7146    
7147     /**
7148     *
7149     * Rearrange GL_RUN table and remove runs
7150     *
7151     **/
7152     void PamelaDBOperations::RemoveRUNS(){
7153     TSQLResult *pResult;
7154     TSQLRow *Row;
7155     stringstream myquery;
7156     UInt_t drun = 0;
7157     GL_RUN *delrun = new GL_RUN();
7158     //
7159     myquery.str("");
7160     myquery << " SELECT ID FROM GL_RUN where ID_RUN_FRAG=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
7161     //
7162     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
7163     //
7164     pResult = conn->Query(myquery.str().c_str());
7165     //
7166     Row = pResult->Next();
7167     //
7168     //
7169     if ( !Row ){
7170     if ( IsDebug() ) printf(" No run with ID_RUN_FRAG=0 belonged to this file \n");
7171     } else {
7172     if ( IsDebug() ) printf(" Deleting run from GL_RUN table \n");
7173     while ( Row ){
7174     delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
7175     if ( IsDebug() ) printf(" del run %u \n",(UInt_t)atoll(Row->GetField(0)));
7176     drun++;
7177     Row = pResult->Next();
7178     };
7179     };
7180     //
7181     //
7182     myquery.str("");
7183     myquery << " SELECT ID,ID_RUN_FRAG FROM GL_RUN where ID_RUN_FRAG!=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
7184     //
7185     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
7186     //
7187     pResult = conn->Query(myquery.str().c_str());
7188     //
7189     Row = pResult->Next();
7190     //
7191     if ( !Row ){
7192     if ( IsDebug() ) printf(" No run with ID_RUN_FRAG!=0 belonged to this file \n");
7193     } else {
7194     if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN table \n");
7195     while ( Row ){
7196     if ( IsDebug() ) printf(" restore run %u \n",(UInt_t)atoll(Row->GetField(1)));
7197     delrun->RestoreRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN_FRAGMENTS");
7198     if ( IsDebug() ) printf(" del run %u \n",(UInt_t)atoll(Row->GetField(1)));
7199     delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN");
7200     if ( (UInt_t)atoll(Row->GetField(1)) != (UInt_t)atoll(Row->GetField(0)) ){
7201     if ( IsDebug() ) printf(" del run %u \n",(UInt_t)atoll(Row->GetField(0)));
7202     delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
7203     };
7204     drun++;
7205     Row = pResult->Next();
7206     };
7207     };
7208     //
7209     if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN table \n",drun);
7210     //
7211     //
7212     //
7213     drun = 0;
7214     //
7215     myquery.str("");
7216     myquery << " SELECT ID_TRASH FROM GL_RUN_TRASH where BELONGED_TO='GL_RUN_FRAGMENTS' AND ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
7217     //
7218     pResult = conn->Query(myquery.str().c_str());
7219     //
7220     Row = pResult->Next();
7221     //
7222     if ( !Row ){
7223     if ( IsDebug() ) printf(" No run from GL_RUN_FRAGMENTS table in the trash table for this file \n");
7224     } else {
7225     if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_TRASH table \n");
7226     while ( Row ){
7227     if ( IsDebug() ) printf(" del run idtrash %u \n",(UInt_t)atoll(Row->GetField(0)));
7228     myquery.str("");
7229     myquery << " DELETE FROM GL_RUN_TRASH where ID_TRASH=" << Row->GetField(0) <<";";
7230     conn->Query(myquery.str().c_str());
7231     drun++;
7232     Row = pResult->Next();
7233     };
7234     };
7235     //
7236     if ( IsDebug() ) printf(" Deleted %u run(s) from GL_RUN_TRASH table \n",drun);
7237     //
7238     //
7239     //
7240     drun = 0;
7241     //
7242     myquery.str("");
7243     myquery << " SELECT ID FROM GL_RUN_FRAGMENTS where ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
7244     //
7245     pResult = conn->Query(myquery.str().c_str());
7246     //
7247     Row = pResult->Next();
7248     //
7249     if ( !Row ){
7250     if ( IsDebug() ) printf(" No run in the GL_RUN_FRAGMENTS table for this file \n");
7251     } else {
7252     if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_FRAGMENTS table \n");
7253     while ( Row ){
7254     if ( IsDebug() ) printf(" del run %u \n",(UInt_t)atoll(Row->GetField(0)));
7255     myquery.str("");
7256     myquery << " DELETE FROM GL_RUN_FRAGMENTS where ID=" << Row->GetField(0) <<";";
7257     conn->Query(myquery.str().c_str());
7258     drun++;
7259     Row = pResult->Next();
7260     };
7261     };
7262     //
7263     if ( IsDebug() ) printf(" Deleted %u run(s) from GL_RUN_FRAGMENTS table \n",drun);
7264     //
7265     //
7266     //
7267     delete delrun;
7268     //
7269     };
7270    
7271    
7272     /**
7273     *
7274     * Rearrange calibration tables
7275     *
7276     **/
7277 mocchiut 1.10 void PamelaDBOperations::RemoveFILES(UInt_t idtsy){
7278 mocchiut 1.1 stringstream myquery;
7279     //
7280     myquery.str("");
7281     myquery << " DELETE FROM GL_RAW WHERE ID=" <<this->GetID_RAW() <<";";
7282     //
7283     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
7284     //
7285     conn->Query(myquery.str().c_str());
7286     //
7287 mocchiut 1.10 myquery.str("");
7288     myquery << " DELETE FROM GL_ROOT WHERE ID=" <<this->GetID_ROOT() <<";";
7289     //
7290     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
7291     //
7292     conn->Query(myquery.str().c_str()); //
7293     //
7294     if ( !chewbacca ){
7295     myquery.str("");
7296     myquery << " DELETE FROM GL_TIMESYNC WHERE ID=" << idtsy <<";";
7297     //
7298     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
7299     //
7300     conn->Query(myquery.str().c_str());
7301     };
7302     //
7303 mocchiut 1.1 };
7304    
7305     /**
7306     *
7307     * Rearrange calibration tables
7308     *
7309     **/
7310     void PamelaDBOperations::RemoveCALIBS(){
7311     TSQLResult *pResult;
7312     TSQLRow *Row;
7313     stringstream myquery;
7314     //
7315     //
7316     // Calorimeter
7317     //
7318     for (Int_t section = 0; section < 4; section++){
7319     myquery.str("");
7320     myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_CALO_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<" AND ";
7321     myquery << " SECTION=" << section << ";";
7322     //
7323     pResult = conn->Query(myquery.str().c_str());
7324     //
7325     Row = pResult->Next();
7326     if( !Row->GetField(0) || !Row->GetField(1) ){
7327     //
7328     if ( IsDebug() ) printf(" NO CALO CALIBRATION SECTION %i ASSOCIATED TO THIS FILE! \n",section);
7329     //
7330     } else {
7331     //
7332     myquery.str("");
7333     myquery << " UPDATE GL_CALO_CALIB SET TO_TIME=" << Row->GetField(1);
7334     myquery << " WHERE TO_TIME="<< Row->GetField(0) << " AND ";
7335     myquery << " SECTION=" << section << ";";
7336     //
7337     pResult = conn->Query(myquery.str().c_str());
7338     //
7339     if( !pResult ){
7340     //
7341     if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
7342     //
7343     throw -4;
7344     //
7345     };
7346     //
7347     };
7348     };
7349     Bool_t OLDDB = false;
7350     for (Int_t section = 0; section < 4; section++){
7351     myquery.str("");
7352     myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_CALOPULSE_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<" AND ";
7353     myquery << " SECTION=" << section << ";";
7354     //
7355     pResult = conn->Query(myquery.str().c_str());
7356     //
7357     if ( conn->GetErrorCode() ){
7358     printf(" Section %i : warning, old databse structure no GL_CALOPULSE_CALIB table!\n",section);
7359     OLDDB=true;
7360     } else {
7361     Row = pResult->Next();
7362     if( !Row->GetField(0) || !Row->GetField(1) ){
7363     //
7364     if ( IsDebug() ) printf(" NO PULSE CALO CALIBRATION SECTION %i ASSOCIATED TO THIS FILE! \n",section);
7365     //
7366     } else {
7367     //
7368     myquery.str("");
7369     myquery << " UPDATE GL_CALOPULSE_CALIB SET TO_TIME=" << Row->GetField(1);
7370     myquery << " WHERE TO_TIME="<< Row->GetField(0) << " AND ";
7371     myquery << " SECTION=" << section << ";";
7372     //
7373     pResult = conn->Query(myquery.str().c_str());
7374     //
7375     if( !pResult ){
7376     //
7377     if ( IsDebug() ) printf(" ERROR DELETING CALO PULSE CALIBRATIONS \n");
7378     //
7379     throw -4;
7380     //
7381     };
7382     //
7383     };
7384     };
7385     };
7386     myquery.str("");
7387     myquery << " DELETE FROM GL_CALO_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT() << ";";
7388     //
7389     pResult = conn->Query(myquery.str().c_str());
7390     //
7391     if( !pResult ){
7392     //
7393     if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
7394     //
7395     throw -4;
7396     //
7397     };
7398     //
7399     myquery.str("");
7400     myquery << " DELETE FROM GL_CALOPULSE_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT() << ";";
7401     //
7402     pResult = conn->Query(myquery.str().c_str());
7403     if ( IsDebug() ) printf(" Delete from GL_CALOPULSE_CALIB query is %s \n",myquery.str().c_str());
7404     if ( !OLDDB ){
7405     //
7406     if( !pResult ){
7407     //
7408     if ( IsDebug() ) printf(" ERROR DELETING PULSE CALO CALIBRATIONS \n");
7409     //
7410     throw -4;
7411     //
7412     };
7413     };
7414     //
7415     // Tracker
7416     //
7417     myquery.str("");
7418     myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_TRK_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
7419     //
7420     pResult = conn->Query(myquery.str().c_str());
7421     //
7422     Row = pResult->Next();
7423     if( !Row->GetField(0) || !Row->GetField(1) ){
7424     //
7425     if ( IsDebug() ) printf(" NO TRK CALIBRATION ASSOCIATED TO THIS FILE! \n");
7426     //
7427     } else {
7428     //
7429     myquery.str("");
7430     myquery << " UPDATE GL_TRK_CALIB SET TO_TIME=" << Row->GetField(1);
7431     myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
7432     //
7433     pResult = conn->Query(myquery.str().c_str());
7434     //
7435     if( !pResult ){
7436     //
7437     if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
7438     //
7439     throw -4;
7440     //
7441     };
7442     //
7443     myquery.str("");
7444     myquery << " DELETE FROM GL_TRK_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT() << ";";
7445     //
7446     pResult = conn->Query(myquery.str().c_str());
7447     //
7448     if( !pResult ){
7449     //
7450     if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
7451     //
7452     throw -4;
7453     //
7454     };
7455     };
7456     //
7457     //
7458     // S4
7459     //
7460     myquery.str("");
7461     myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_S4_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
7462     //
7463     pResult = conn->Query(myquery.str().c_str());
7464     //
7465     Row = pResult->Next();
7466     if( !Row->GetField(0) || !Row->GetField(1) ){
7467     //
7468     if ( IsDebug() ) printf(" NO S4 CALIBRATION ASSOCIATED TO THIS FILE! \n");
7469     //
7470     } else {
7471     //
7472     myquery.str("");
7473     myquery << " UPDATE GL_S4_CALIB SET TO_TIME=" << Row->GetField(1);
7474     myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
7475     //
7476     pResult = conn->Query(myquery.str().c_str());
7477     //
7478     if( !pResult ){
7479     //
7480     if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
7481     //
7482     throw -4;
7483     //
7484     };
7485     //
7486     myquery.str("");
7487     myquery << " DELETE FROM GL_S4_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT() << ";";
7488     //
7489     pResult = conn->Query(myquery.str().c_str());
7490     //
7491     if( !pResult ){
7492     //
7493     if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
7494     //
7495     throw -4;
7496     //
7497     };
7498     //
7499     };
7500     };
7501    
7502     /**
7503     *
7504     * Rearrange calibration tables
7505     *
7506     **/
7507 pam-fi 1.4 UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh , TFile *file){
7508    
7509     if(!caltrk) return 0;
7510    
7511     if ( IsDebug() ) cout << "ValidateTrkCalib:"<<endl;
7512    
7513     UInt_t validate = 1;
7514     Int_t vorder[]={5,5,3,3,4,4,2,2,1,1,0,0};
7515     UInt_t timeaftercalib=120000; //2000;
7516     TString classname = caltrk->GetName();
7517    
7518     // ----------------------------------
7519     // Check CRCs and failed calibrations
7520     // ----------------------------------
7521     for(Int_t ipkt=0; ipkt<6; ipkt++){
7522     if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
7523     if( caltrk->crc_hcal[ipkt] ){
7524     // if(IsDebug())cout<<"(CRC Header)";
7525     validate = 0;
7526     if(IsDebug())cout <<endl<<" *** CRC *** (header DSPn "<<caltrk->DSPnumber[ipkt]<<")";
7527    
7528     }
7529     for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] ){
7530     // if(IsDebug())cout<<"(CRC Pkt-"<<ilad<<")";
7531     if(IsDebug())cout <<endl<<" *** CRC *** (data DSPn "<<caltrk->DSPnumber[ipkt]<<" ladder "<<ilad<<")";
7532     validate = 0;
7533     }
7534     if( !(caltrk->ncalib_event[ipkt]==0 && caltrk->cal_flag[ipkt]==0) ){
7535     if(IsDebug())cout <<endl<<" *** FAILURE *** (data DSPn "<<caltrk->DSPnumber[ipkt]<<")";
7536     validate = 0;
7537     }
7538     }else{
7539     // validate=0;
7540     if(IsDebug())cout <<endl<<" *** DSPn *** ("<< caltrk->DSPnumber[ipkt] <<" @pkt "<<ipkt<<")";
7541     }
7542     }
7543    
7544     // -----------------------
7545     // Check missing packets:
7546     // -----------------------
7547     // Readout order:
7548     // ------------------
7549     // DSP packet board
7550     // ------------------
7551     // 12 0 1
7552     // 10 1 1
7553     // 8 2 1
7554     // 4 3 1
7555     // 6 4 1
7556     // 2 5 1
7557     // ------------------
7558     // 11 0 2
7559     // 9 1 2
7560     // 7 2 2
7561     // 3 3 2
7562     // 5 4 2
7563     // 1 5 2
7564     // ------------------
7565     // -------------------------------------------------
7566     // Check if it is first or second calibration packet
7567     // -------------------------------------------------
7568     UInt_t build=0;
7569     UInt_t base=0;
7570     UInt_t mask=0;
7571     if(classname.Contains("CalibTrk1Event")){
7572     base=12;
7573     mask=0x03F000;
7574     }
7575     if(classname.Contains("CalibTrk2Event")){
7576     base=18;
7577     mask=0xFC0000;
7578     }
7579     // ----------------------------------------------------
7580     // Count number of valid packets and set build variable
7581     // ----------------------------------------------------
7582     if(IsDebug())cout <<endl<< " DSP: ";
7583     Int_t npkts=0;
7584     for(Int_t ipkt=0; ipkt<6; ipkt++){
7585     if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
7586     if(IsDebug())cout <<" "<<caltrk->DSPnumber[ipkt];
7587     npkts++;
7588     build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );
7589     // cout << caltrk->DSPnumber[ipkt]
7590     };
7591     }
7592     if(IsDebug())cout << " ==> "<< hex << build << dec;
7593     // ----------------------------------------------------
7594     // If the number of valid packets is 6, ok exit...
7595     // ----------------------------------------------------
7596     if( npkts==6 ){
7597     return validate; // exit
7598     }
7599     ////////////////////////////////////////////////////////
7600     // ...otherwise there might be some missing packets
7601     //
7602     // In this case check the acq configuration
7603     // (some DSPs might be excluded from acquisition)
7604     ////////////////////////////////////////////////////////
7605    
7606     if(!eh || !file || (file&&file->IsZombie()) ){
7607     if ( IsDebug() )cout << " *** MISSING VIEW *** eh="<<eh<<" file="<<file<<" cannot validate"<<endl;
7608     return (0);
7609     }
7610    
7611     // -----------------------------------------------
7612     // retrieve the first run header after calib
7613     // -----------------------------------------------
7614    
7615     PacketType *pctp;
7616     EventCounter *cod;
7617     cod = eh->GetCounter();
7618     Int_t irun = cod->Get(pctp->RunHeader);
7619     TTree *rh=(TTree*)file->Get("RunHeader");
7620     if ( !rh || rh->IsZombie() ) throw -17;
7621     if( rh->GetEntries() <= irun ){
7622     if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (1) -- cannot validate :-( "<<endl;
7623     return 0; // :-(
7624     }
7625     RunHeaderEvent *run = 0;
7626     EventHeader *hrun = 0;
7627     rh->SetBranchAddress("RunHeader", &run);
7628     rh->SetBranchAddress("Header", &hrun);
7629     rh->GetEntry(irun);
7630     if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){
7631     if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (2) -- cannot validate :-( "<<endl;
7632     return 0; // :-(
7633     }
7634    
7635     UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());
7636     if( dtime > timeaftercalib ){
7637     if ( IsDebug() ) cout << " *** MISSING-PKT *** run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;
7638     return 0; // :-(
7639     }
7640    
7641     if ( IsDebug() ) cout <<endl<< " ACQ_BUILD_INFO ==> "<<hex<<(run->ACQ_BUILD_INFO & mask)<<dec;
7642    
7643     if( (run->ACQ_BUILD_INFO & mask) != build ){
7644     validate=0; // :-(
7645     cout <<endl<< " *** MISSING-PKT *** packet mismatch: ACQ_BUILD_INFO="<<hex<<(run->ACQ_BUILD_INFO&mask)<<" != "<<build<<dec;
7646     };
7647    
7648     return validate;
7649 mocchiut 1.1
7650 mocchiut 1.2
7651 pam-fi 1.4 }
7652 mocchiut 1.1
7653     /**
7654     *
7655     * Check the DB (only for overlapping runs at the moment)
7656     *
7657     **/
7658     UInt_t PamelaDBOperations::Check(){
7659 mocchiut 1.2 return(this->Check(0,0));
7660 mocchiut 1.1 }
7661    
7662     UInt_t PamelaDBOperations::Check(UInt_t from, UInt_t to){
7663     //
7664 mocchiut 1.2 if ( IsDebug() ) printf(" from %u to %u \n",from,to);
7665 mocchiut 1.1 //
7666     UInt_t test = 0;
7667     //
7668     UInt_t thisrht = 0;
7669     UInt_t thisrtt = 0;
7670     UInt_t thisid = 0;
7671     UInt_t prevrht = 0;
7672     UInt_t prevrtt = 0;
7673     UInt_t previd = 0;
7674     //
7675     UInt_t prevl0id = 0;
7676     UInt_t thisl0id = 0;
7677     //
7678     stringstream oss;
7679     TSQLResult *result = 0;
7680     TSQLRow *row = 0;
7681     TSQLResult *result2 = 0;
7682     TSQLRow *row2 = 0;
7683     TSQLResult *result3 = 0;
7684     TSQLRow *row3 = 0;
7685     oss.str("");
7686     oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME,NEVENTS FROM GL_RUN order by RUNHEADER_TIME asc;";
7687     // oss << "SELECT ID,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN where ID>10170 and ID<10190 order by RUNHEADER_TIME asc;";
7688     result = conn->Query(oss.str().c_str());
7689     //
7690     if ( !result ) throw -4;;
7691     //
7692     row = result->Next();
7693     UInt_t nid = 0;
7694     //
7695     while ( row ){
7696     nid++;
7697     if ( !(nid%1000) && nid ) printf(" %iK run scanned \n",nid/1000);
7698     thisid = (UInt_t)atoll(row->GetField(0));
7699     thisl0id = (UInt_t)atoll(row->GetField(1));
7700     thisrht = (UInt_t)atoll(row->GetField(2));
7701     thisrtt = (UInt_t)atoll(row->GetField(3));
7702     //
7703     if ( from > 0 && nid <= from ) goto ss;
7704     if ( to > 0 && nid >= to ) goto ss;
7705 mocchiut 1.2 //
7706 mocchiut 1.1 if ( (UInt_t)atoll(row->GetField(4)) > 1 ){
7707     //
7708     //
7709     //
7710     oss.str("");
7711     oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN WHERE ID!="
7712     << thisid << " AND ( RUNHEADER_TIME="
7713     << thisrht << " OR RUNTRAILER_TIME="
7714     << thisrtt << " ) AND NEVENTS!=0 AND NEVENTS!=1 order by RUNHEADER_TIME asc;";
7715     result3 = conn->Query(oss.str().c_str());
7716     if ( IsDebug() ) printf(" query is %s \n",oss.str().c_str());
7717     if ( result3 ){
7718     //
7719     oss.str("");
7720     oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN WHERE ID!="
7721     << thisid << " AND RUNHEADER_TIME="
7722     << thisrht << " AND RUNTRAILER_TIME!="
7723     << thisrtt << " AND NEVENTS!=0 AND NEVENTS!=1 order by RUNHEADER_TIME asc;";
7724     result3 = conn->Query(oss.str().c_str());
7725     if ( IsDebug() ) printf(" query is %s \n",oss.str().c_str());
7726     if ( result3 ){
7727     row3 = result3->Next();
7728     //
7729     while ( row3 ){
7730     //
7731     // 2 runs with same runheader
7732     //
7733     printf(" CHECK n.4 RUNs %u and %u HAVE SAME RUNHEADER \n",thisid,(UInt_t)atoll(row3->GetField(0)));
7734     row3 = result3->Next();
7735     };
7736 mocchiut 1.2 // delete result3;
7737 mocchiut 1.1
7738     };
7739     //
7740     oss.str("");
7741     oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN WHERE ID!="
7742     << thisid << " AND RUNHEADER_TIME!="
7743     << thisrht << " AND RUNTRAILER_TIME="
7744     << thisrtt << " AND NEVENTS!=0 AND NEVENTS!=1 order by RUNHEADER_TIME asc;";
7745     result3 = conn->Query(oss.str().c_str());
7746     if ( IsDebug() ) printf(" query is %s \n",oss.str().c_str());
7747     if ( result3 ){
7748     row3 = result3->Next();
7749     //
7750     while ( row3 ){
7751     //
7752     // 2 runs with same runtrailer
7753     //
7754     printf(" CHECK n.5 RUNs %u and %u HAVE SAME RUNTRAILER \n",thisid,(UInt_t)atoll(row3->GetField(0)));
7755     row3 = result3->Next();
7756     };
7757 mocchiut 1.2 // delete result3;
7758 mocchiut 1.1 };
7759     //
7760     oss.str("");
7761     oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN WHERE ID!="
7762     << thisid << " AND RUNHEADER_TIME="
7763     << thisrht << " AND RUNTRAILER_TIME="
7764     << thisrtt << " AND ID_RUN_FRAG!="
7765     << thisid << " order by RUNHEADER_TIME asc;";
7766     result3 = conn->Query(oss.str().c_str());
7767     if ( result3 ){
7768     row3 = result3->Next();
7769     //
7770     while ( row3 ){
7771     //
7772     // duplicated run
7773     //
7774     printf(" CHECK n.7 RUNs %u and %u HAVE SAME RUNTRAILER AND RUNHEADER (ARE THE SAME?) \n",thisid,(UInt_t)atoll(row3->GetField(0)));
7775     row3 = result3->Next();
7776     };
7777 mocchiut 1.2 // delete result3;
7778 mocchiut 1.1
7779     };
7780     };
7781     //
7782     oss.str("");
7783     oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN WHERE ID!="
7784     << thisid << " AND RUNHEADER_TIME>"
7785     << thisrht << " AND RUNTRAILER_TIME<"
7786     << thisrtt << " order by RUNHEADER_TIME asc;";
7787     result3 = conn->Query(oss.str().c_str());
7788     if ( result3 ){
7789     row3 = result3->Next();
7790     //
7791     while ( row3 ){
7792     //
7793     // run contained in the checked one
7794     //
7795     printf(" CHECK n.6 RUN %u CONTAINS RUN %u \n",thisid,(UInt_t)atoll(row3->GetField(0)));
7796     row3 = result3->Next();
7797     };
7798 mocchiut 1.2 // delete result3;
7799 mocchiut 1.1 };
7800     //
7801     };
7802     //
7803     // if ( thisrht < prevrtt || thisrtt < prevrht || thisrht > thisrtt && !(!prevrht && !prevrtt &&!previd) ){
7804     // if ( (thisrht < prevrtt || thisrtt < prevrht || thisrht > thisrtt) && (thisrht != prevrht) ){
7805     if ( (thisrht < prevrtt) && (thisrht != prevrht) ){
7806     if ( IsDebug() ) printf(" IDprev %u ID %u prevrht %u prevrtt %u thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
7807     printf(" CHECK n.1 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrht-prevrtt),previd,thisid);
7808     TString prevf = "";
7809     TString thisf = "";
7810     oss.str("");
7811     oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
7812     result2 = conn->Query(oss.str().c_str());
7813     if ( !result2 ) throw -4;;
7814     row2 = result2->Next();
7815     prevf = (TString)row2->GetField(0);
7816     oss.str("");
7817     oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
7818     result2 = conn->Query(oss.str().c_str());
7819     if ( !result2 ) throw -4;;
7820     row2 = result2->Next();
7821     thisf = (TString)row2->GetField(0);
7822     if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7823     test = 1;
7824 mocchiut 1.2 // delete result2;
7825 mocchiut 1.1 };
7826     //
7827     if ( (thisrtt < prevrht) && (thisrht != prevrht) ){
7828     if ( IsDebug() ) printf(" IDprev %u ID %u prevrht %u prevrtt %u thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
7829     printf(" CHECK n.2 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrtt-prevrht),previd,thisid);
7830     TString prevf = "";
7831     TString thisf = "";
7832     oss.str("");
7833     oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
7834     result2 = conn->Query(oss.str().c_str());
7835     if ( !result2 ) throw -4;
7836     row2 = result2->Next();
7837     prevf = (TString)row2->GetField(0);
7838     oss.str("");
7839     oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
7840     result2 = conn->Query(oss.str().c_str());
7841     if ( !result2 ) throw -4;;
7842     row2 = result2->Next();
7843     thisf = (TString)row2->GetField(0);
7844     if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7845     test = 1;
7846 mocchiut 1.2 // delete result2;
7847 mocchiut 1.1 };
7848     //
7849     if ( (thisrht > thisrtt) && (thisrht != prevrht) ){
7850     if ( IsDebug() ) printf(" IDprev %u ID %u prevrht %u prevrtt %u thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
7851     printf(" CHECK n.3 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrht-thisrtt),previd,thisid);
7852     TString prevf = "";
7853     TString thisf = "";
7854     oss.str("");
7855     oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
7856     result2 = conn->Query(oss.str().c_str());
7857     if ( !result2 ) throw -4;;
7858     row2 = result2->Next();
7859     prevf = (TString)row2->GetField(0);
7860     oss.str("");
7861     oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
7862     result2 = conn->Query(oss.str().c_str());
7863     if ( !result2 ) throw -4;;
7864     row2 = result2->Next();
7865     thisf = (TString)row2->GetField(0);
7866     if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7867     test = 1;
7868 mocchiut 1.2 // delete result2;
7869 mocchiut 1.1 };
7870 mocchiut 1.2 ss:
7871 mocchiut 1.1 //
7872     prevrht = thisrht;
7873     prevrtt = thisrtt;
7874     previd = thisid;
7875     prevl0id = thisl0id;
7876     row = result->Next();
7877 mocchiut 1.2 // if ( result2 ) delete result2;
7878     // if ( result3 ) delete result3;
7879 mocchiut 1.1 };
7880     //
7881     return(test);
7882     //
7883     };

  ViewVC Help
Powered by ViewVC 1.1.23