/[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.17 - (hide annotations) (download)
Fri Dec 12 20:08:13 2008 UTC (16 years ago) by mocchiut
Branch: MAIN
Changes since 1.16: +3 -3 lines
Bug which leads to error -14 fixed

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

  ViewVC Help
Powered by ViewVC 1.1.23