/[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.19 - (hide annotations) (download)
Mon Dec 22 11:05:10 2008 UTC (15 years, 11 months ago) by mocchiut
Branch: MAIN
Changes since 1.18: +3 -2 lines
New 'special files' in the db, yp defaults changed, patch to recover boot_number

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

  ViewVC Help
Powered by ViewVC 1.1.23