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

  ViewVC Help
Powered by ViewVC 1.1.23