/[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.14 - (hide annotations) (download)
Wed Dec 3 19:57:52 2008 UTC (16 years ago) by mocchiut
Branch: MAIN
Changes since 1.13: +1 -0 lines
New special time offset for chewbacca

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     if ( !tcod ) tcod = 1;
2252     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     if ( !tcod ) tcod = 1;
2291     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     if ( !tcod ) tcod = 1;
2353     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     if ( ptht < rhev ){
2395     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     if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
2423 mocchiut 1.10 // rt->GetEntry(ptt-1);
2424     rt->GetEntry(rtev-1);
2425 mocchiut 1.1 cod = eht->GetCounter();
2426 mocchiut 1.10 tcod = (UInt_t)cod->Get(pctp->Physics)+1;
2427 mocchiut 1.1 evbefh = TMath::Max(chminentry,tcod);
2428     // evbefh = cod->Get(pctp->Physics);
2429     rt->GetEntry(ptt);
2430     pht = eht->GetPscuHeader();
2431     this->HandleRunFragments(true,true,evbefh,upperentry);
2432     };
2433     };
2434     };
2435     //
2436     };
2437     };
2438     };
2439     //
2440     return(signal);
2441     };
2442    
2443     /**
2444     *
2445     * Check if the run has already been inserted
2446     *
2447     */
2448     Bool_t PamelaDBOperations::IsRunAlreadyInserted(){
2449     //
2450     TSQLResult *result = 0;
2451     TSQLRow *row = 0;
2452     //
2453     stringstream oss;
2454     oss.str("");
2455     //
2456     // the where clause is of the type: boot_number = _our_boot && (
2457     // ( runhead_time >= (_our_runhead_time-10) && runtrail_time <= (_our_runtrail_time+10) &&
2458     // ( runhead_obt >= _our_runheadobt || runhead_pkt >= _our_runheadpkt ) &&
2459     // ( runtrail_obt >= _our_runtrailobt || runtrail_pkt >= _our_runtrailpkt ) )
2460     // ||
2461     // ( runhead_time <= _our_runhead_time && runtrail_time >= _our_runtrail_time &&
2462     // ( runhead_obt <= _our_runheadobt || runhead_pkt <= _our_runheadpkt ) &&
2463     // ( runtrail_obt <= _our_runtrailobt || runtrail_pkt <= _our_runtrailpkt ) )
2464     // ||
2465     // ( runhead_time = _our_runhead_time && runtrail_time = _our_runtrail_time && nevents > 100 )
2466     // )
2467     // ||
2468     // ( runhead_time = _our_runhead_time && runtrail_time > _our_runtrail_time && nevents > 100 )
2469     // )
2470     // ||
2471     // ( runhead_time < _our_runhead_time && runtrail_time = _our_runtrail_time && nevents > 100 )
2472     // )
2473     //
2474     oss << " SELECT ID,NEVENTS,TRK_CALIB_USED,PKT_COUNTER FROM GL_RUN WHERE "
2475     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
2476     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
2477     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
2478     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
2479     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2480     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
2481     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
2482     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2483     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
2484     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
2485     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2486     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR ";
2487     if ( glrun->GetNEVENTS() < 100 ){
2488     oss<<" RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << "))); ";
2489     } else {
2490     oss << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ")) OR "
2491     << " (RUNHEADER_TIME=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND " // these two lines in a certain way disable the patch below...
2492     << " RUNTRAILER_TIME=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND NEVENTS>100) OR" //
2493     << " (RUNHEADER_TIME=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND " //
2494     << " RUNTRAILER_TIME>" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND NEVENTS>100) OR" //
2495     << " (RUNHEADER_TIME<" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND " //
2496     << " RUNTRAILER_TIME=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND NEVENTS>100)" //
2497     << " );";
2498     };
2499     //
2500     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());
2501     if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
2502     result = conn->Query(oss.str().c_str());
2503     //
2504     if ( !result ) throw -4;
2505     //
2506     row = result->Next();
2507     //
2508     if ( !row ){
2509     if ( IsDebug() ) printf(" The run is new \n");
2510     if ( IsDebug() ) printf(" -> fill the DB \n");
2511     return(false); // the file has not been inserted in the DB, go on.
2512     };
2513     //
2514     Bool_t signal = true;
2515     //
2516     while ( row != NULL ){
2517     if ( IsDebug() ) printf(" A run exists with runheader and runtrailer time and packets compatible with this one \n");
2518     //
2519     // the run has already been inserted
2520     //
2521     if ( signal && IsDebug() ) printf(" The run has already been inserted\n");
2522     if ( PEDANTIC ) throw -86;
2523     return(true); //<<<<<<<<<<<<<<<<<<<<<<<< patch follows, uncomment here
2524     //
2525     // PATCH!
2526     // 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
2527     // while the old run doesn't have it 3) we have more events than the old run
2528     //
2529     if ( glrun->GetNEVENTS() > (UInt_t)atoll(row->GetField(1)) ){
2530     //
2531     if ( IsDebug() ) printf(" The new run has more events than the old one \n");
2532     glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2533 mocchiut 1.2 // oss.str("");
2534     // oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2535     // if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());
2536     // conn->Query(oss.str().c_str());
2537 mocchiut 1.1 if ( signal ) signal = false;
2538     goto gonext;
2539     //
2540     } else if ( glrun->GetNEVENTS() < (UInt_t)atoll(row->GetField(1)) ){
2541     if ( IsDebug() ) printf(" The new run has less events than the old one \n");
2542     if ( IsDebug() ) printf(" The run is already inserted \n");
2543     goto gonext;
2544     };
2545     //
2546     if ( glrun->GetTRK_CALIB() && !(UInt_t)atoll(row->GetField(2)) ){
2547     //
2548     if ( IsDebug() ) printf(" The new run has the same number of events and the runheader the old one miss the runheader \n");
2549     //
2550     glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2551 mocchiut 1.2 // oss.str("");
2552     // oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2553     // if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());
2554     // conn->Query(oss.str().c_str());
2555 mocchiut 1.1 //
2556     if ( signal ) signal = false;
2557     goto gonext;
2558     } else if ( !glrun->GetTRK_CALIB() && (UInt_t)atoll(row->GetField(2)) ){
2559     if ( IsDebug() ) printf(" The new run has the same number of events but miss the runheader the old has the runheader \n");
2560     if ( IsDebug() ) printf(" The run is already inserted \n");
2561     goto gonext;
2562     };
2563     //
2564     if ( glrun->GetPKT_COUNTER() && !(UInt_t)atoll(row->GetField(3)) ){
2565     //
2566     if ( IsDebug() ) printf(" The new run has the same number of events, the runheader and the runtrailer the old one miss the runtrailer \n");
2567     //
2568     glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2569 mocchiut 1.2 // oss.str("");
2570     // oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2571     // if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());
2572     // conn->Query(oss.str().c_str());
2573 mocchiut 1.1 if ( signal ) signal = false;
2574     //
2575     };
2576     //
2577     gonext:
2578     // END PATCH!
2579     //
2580     row = result->Next();
2581     //
2582     };
2583     //
2584     delete result;
2585     //
2586     if ( signal && IsDebug() ) printf(" The run has already been inserted \n");
2587     if ( !signal && IsDebug() ) printf(" The run existed and has been overridden, fill the DB \n");
2588     if ( PEDANTIC ) throw -86;
2589     return(signal);
2590     };
2591    
2592     /**
2593     * Handle runs which seems to be good ones.
2594     **/
2595     void PamelaDBOperations::HandleRun(){
2596     ULong64_t chkpkt = 0;
2597     ULong64_t pktt = (ULong64_t)PKT(pht->GetCounter());
2598     ULong64_t pkth = (ULong64_t)PKT(phh->GetCounter());
2599     //
2600     chkpkt = pkth + (ULong64_t)runt->PKT_COUNTER + 1ULL + 1ULL;
2601     //
2602     if ( labs(chkpkt-pktt)<2 ){
2603     //
2604     if ( IsDebug() ) printf(" check %llu pktt %llu \n",chkpkt,pktt);
2605     //
2606     // it must be a good run, fill the db
2607     //
2608     this->FillClass();
2609     //
2610     if ( !IsRunAlreadyInserted() ){
2611     glrun->SetID(this->AssignRunID());
2612     glrun->SetID_RUN_FRAG(0);
2613     glrun->Fill_GL_RUN(conn);
2614     };
2615     } else {
2616     //
2617     if ( IsDebug() ) printf(" oh no! the distance between runheader and runtrailer seems wrong: check %llu pktt %llu \n",chkpkt,pktt);
2618     if ( IsDebug() ) printf(" try to recover run(s) without runheader and runtrailer between runheader and runtrailer\n");
2619     //
2620     this->HandleSuspiciousRun();
2621     //
2622     };
2623     //
2624     //
2625     return;
2626     };
2627    
2628    
2629     /**
2630     * Handle run fragments at the beginning or at the end of the file
2631     **/
2632     void PamelaDBOperations::HandleRunFragments(Bool_t mishead, Bool_t mistrail, UInt_t firstev, UInt_t lastev){
2633     //
2634     UInt_t rhfirstev = firstev;
2635     UInt_t rtlastev = lastev;
2636     Bool_t found = false;
2637     Bool_t foundinrun = false;
2638     //
2639     TSQLResult *result = 0;
2640     TSQLRow *row = 0;
2641     //
2642     stringstream oss;
2643     oss.str("");
2644     //
2645     // is the piece of run good (no other packets inside)?
2646     //
2647     if ( !this->IsRunConsistent(mishead,mistrail,firstev,lastev)){
2648     //
2649     // if not, handle other pieces and continue with the first one
2650     //
2651     if ( IsDebug() ) printf("The run is not consistent, it contains non-physics packets! The run has been handled \n");
2652     //
2653     } else {
2654     //
2655 mocchiut 1.2 // we have now the good first piece of a run, fill the glrun object
2656     //
2657     if ( rhfirstev != firstev && !mishead ) mishead = true;
2658     if ( rtlastev != lastev && !mistrail ) mistrail = true;
2659 mocchiut 1.1 //
2660 mocchiut 1.2 this->FillClass(mishead,mistrail,firstev,lastev);
2661 mocchiut 1.1 //
2662 mocchiut 1.2 if ( IsDebug() ) printf("The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
2663     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());
2664 mocchiut 1.1 //
2665 mocchiut 1.2 // First of all insert the run in the fragment table...
2666 mocchiut 1.1 //
2667     oss.str("");
2668 mocchiut 1.2 oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
2669     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
2670     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
2671     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
2672     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
2673     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2674     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
2675     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
2676     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2677     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
2678     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
2679     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2680     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
2681     << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
2682 mocchiut 1.1 //
2683 mocchiut 1.2 if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
2684 mocchiut 1.1 result = conn->Query(oss.str().c_str());
2685     //
2686     if ( !result ) throw -4;
2687     //
2688     row = result->Next();
2689     //
2690 mocchiut 1.2 if ( !row ){
2691     //
2692     // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
2693     //
2694     if ( IsDebug() ) printf(" The run is new \n");
2695     if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
2696     //
2697     glrun->SetID(this->AssignRunID());
2698     glrun->SetID_RUN_FRAG(0);
2699     glrun->Fill_GL_RUN_FRAGMENTS(conn);
2700     //
2701     } else {
2702     if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
2703     if ( PEDANTIC ) throw -69;
2704     return;
2705     };
2706     //
2707     if ( chewbacca && mishead && mistrail ) goto justcheck;
2708     //
2709     // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
2710     //
2711     if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
2712     // missing it no way we can found a piece in the frag table
2713 mocchiut 1.1 //
2714     oss.str("");
2715 mocchiut 1.2 oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "
2716 mocchiut 1.1 << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2717     << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2718     << " ID != " << glrun->ID
2719 mocchiut 1.2 << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
2720 mocchiut 1.1 //
2721 mocchiut 1.2 if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());
2722 mocchiut 1.1 result = conn->Query(oss.str().c_str());
2723     //
2724     if ( !result ) throw -4;
2725     //
2726     row = result->Next();
2727     //
2728 mocchiut 1.2 if ( !row && NoFrag() ){
2729     //
2730     oss.str("");
2731     oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
2732     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2733     << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2734     << " ID != " << glrun->ID
2735     << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
2736     //
2737     if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
2738     result = conn->Query(oss.str().c_str());
2739     //
2740     if ( !result ) throw -4;
2741     //
2742     foundinrun = true;
2743     //
2744     row = result->Next();
2745     //
2746     };
2747 mocchiut 1.1 //
2748 mocchiut 1.2 if ( !row ){
2749     if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2750     found = false;
2751     } else {
2752     //
2753     found = false; // default value
2754     //
2755     if ( IsDebug() ) printf(" Found a possible candidate, checking if it is the good one... \n");
2756 mocchiut 1.1 //
2757 mocchiut 1.2 // if we have both runheader and runtrailer we can check with pkt_counter:
2758 mocchiut 1.1 //
2759 mocchiut 1.2 if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){
2760     ULong64_t chkpkt = 0;
2761     ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
2762     ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
2763     //
2764     chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;
2765 mocchiut 1.1 //
2766 mocchiut 1.2 if ( labs(chkpkt-pktt)<2 ){
2767     //
2768     if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
2769     //
2770     found = true;
2771     //
2772     } else {
2773     //
2774     if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);
2775     //
2776     found = false;
2777     //
2778     };
2779     };
2780     if ( !found && chewbacca ) goto justcheck;
2781     if ( !found ){
2782 mocchiut 1.1 //
2783 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
2784 mocchiut 1.1 //
2785 mocchiut 1.2 ULong64_t chkpkt1 = 0;
2786     ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
2787     ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
2788     chkpkt1 = labs(orunh1-dbrunt1);
2789 mocchiut 1.1 //
2790 mocchiut 1.2 ULong64_t chkpkt2 = 0;
2791     ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());
2792     ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
2793     chkpkt2 = labs(orunh2-dbrunt2);
2794 mocchiut 1.1 //
2795 mocchiut 1.2 ULong64_t chkpkt3 = 0;
2796     ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());
2797     ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
2798     chkpkt3 = labs(orunh3-dbrunt3);
2799 mocchiut 1.1 //
2800 mocchiut 1.2 if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
2801     // if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){
2802     //
2803     if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
2804     //
2805     found = true;
2806     //
2807     } else {
2808     //
2809     if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
2810     //
2811     found = false;
2812     //
2813     };
2814 mocchiut 1.1 };
2815     };
2816 mocchiut 1.2 //
2817     if ( found ){
2818     //
2819     // 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
2820     //
2821     if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
2822     //
2823     if ( foundinrun ){
2824     glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2825     glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2826     };
2827 mocchiut 1.1 //
2828 mocchiut 1.2 GL_RUN *glrun1 = new GL_RUN();
2829 mocchiut 1.1 //
2830 mocchiut 1.2 // UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
2831     //
2832     oss.str("");
2833     oss << " ID="<<row->GetField(0)<<";";
2834     //
2835     glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos
2836     //
2837     // merge infos
2838     //
2839     UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());
2840     ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
2841     UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
2842     ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
2843     if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2844     TTree *T= 0;
2845     T = (TTree*)file->Get("Physics");
2846     if ( !T || T->IsZombie() ) throw -16;
2847     EventHeader *eh = 0;
2848     PscuHeader *ph = 0;
2849     T->SetBranchAddress("Header", &eh);
2850     while ( apkt > bpkt && aobt > bobt && firstev < lastev ){
2851     T->GetEntry(firstev);
2852     ph = eh->GetPscuHeader();
2853     bpkt = PKT(ph->GetCounter());
2854     bobt = OBT(ph->GetOrbitalTime());
2855     firstev++;
2856     if ( PEDANTIC ) throw -71;
2857     };
2858     if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2859 mocchiut 1.1 //
2860 mocchiut 1.2 glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
2861     glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
2862     glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
2863     glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());
2864     glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());
2865     //
2866     glrun->SetEV_FROM(firstev);
2867     glrun->SetNEVENTS(lastev-firstev+1);
2868     //
2869     glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
2870     glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
2871     glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
2872     glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());
2873     glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());
2874     glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());
2875     glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());
2876     glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());
2877     glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());
2878     glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());
2879     glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());
2880     glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());
2881     glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());
2882     glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());
2883     glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());
2884     glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());
2885     //
2886     if ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
2887     if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
2888     //
2889     if ( !IsRunAlreadyInserted() ){
2890     //
2891     // glrun->SetID(this->AssignRunID());
2892     glrun->SetID_RUN_FRAG(glrun1->GetID());
2893     glrun->Fill_GL_RUN(conn);
2894 mocchiut 1.1 //
2895 mocchiut 1.2 // set id number
2896 mocchiut 1.1 //
2897 mocchiut 1.2 glrun1->SetID_RUN_FRAG(glrun->GetID());
2898     glrun1->Fill_GL_RUN(conn);
2899 mocchiut 1.1 //
2900     };
2901 mocchiut 1.2 // delete old entry in fragment table
2902     //
2903     glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2904     glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2905 mocchiut 1.1 //
2906 mocchiut 1.2 delete glrun1;
2907 mocchiut 1.1 //
2908     //
2909 mocchiut 1.2 return;
2910 mocchiut 1.1 //
2911     };
2912     //
2913     };
2914     //
2915 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
2916     // missing it no way we can found a piece in the frag table
2917 mocchiut 1.1 //
2918     oss.str("");
2919 mocchiut 1.2 oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN_FRAGMENTS WHERE "
2920 mocchiut 1.1 << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2921     << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2922     << " ID != " << glrun->ID
2923 mocchiut 1.2 << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2924 mocchiut 1.1 //
2925 mocchiut 1.2 if ( IsDebug() ) printf(" look for runtrailer in the fragments table: query is \n %s \n",oss.str().c_str());
2926 mocchiut 1.1 result = conn->Query(oss.str().c_str());
2927     //
2928     if ( !result ) throw -4;
2929     //
2930     row = result->Next();
2931     //
2932 mocchiut 1.2 if ( !row && NoFrag() ){
2933     //
2934     oss.str("");
2935     oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN WHERE "
2936     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2937     << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2938     << " ID != " << glrun->ID
2939     << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2940     //
2941     if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
2942     result = conn->Query(oss.str().c_str());
2943     //
2944     if ( !result ) throw -4;
2945     //
2946     foundinrun = true;
2947     row = result->Next();
2948     //
2949     };
2950 mocchiut 1.1 //
2951 mocchiut 1.2 if ( !row ){
2952     if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2953     found = false;
2954     } else {
2955     //
2956     found = false; // default value
2957     //
2958     if ( IsDebug() ) printf(" Found a possible candidate, checking if it is the good one... \n");
2959 mocchiut 1.1 //
2960 mocchiut 1.2 // if we have both runheader and runtrailer we can check with pkt_counter:
2961 mocchiut 1.1 //
2962 mocchiut 1.2 if ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){
2963     ULong64_t chkpkt = 0;
2964     ULong64_t pktt = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
2965     ULong64_t pkth = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
2966 mocchiut 1.1 //
2967 mocchiut 1.2 chkpkt = pkth + (ULong64_t)((UInt_t)atoll(row->GetField(1))) + 1ULL + 1ULL;
2968 mocchiut 1.1 //
2969 mocchiut 1.2 if ( labs(chkpkt-pktt)<2 ){
2970     //
2971     if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
2972     //
2973     found = true;
2974     //
2975     } else {
2976     //
2977     if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);
2978     //
2979     found = false;
2980     //
2981     };
2982     };
2983     if ( !found && chewbacca ) goto justcheck;
2984     if ( !found ){
2985     //
2986     // 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
2987 mocchiut 1.1 //
2988 mocchiut 1.2 ULong64_t chkpkt1 = 0;
2989     ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
2990     ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
2991     chkpkt1 = labs(orunh1-dbrunt1);
2992 mocchiut 1.1 //
2993 mocchiut 1.2 ULong64_t chkpkt2 = 0;
2994     ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNTRAILER_OBT());
2995     ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
2996     chkpkt2 = labs(orunh2-dbrunt2);
2997 mocchiut 1.1 //
2998 mocchiut 1.2 ULong64_t chkpkt3 = 0;
2999     ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNTRAILER_TIME());
3000     ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
3001     chkpkt3 = labs(orunh3-dbrunt3);
3002 mocchiut 1.1 //
3003 mocchiut 1.2 if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
3004     //
3005     if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
3006     //
3007     found = true;
3008     //
3009     } else {
3010     //
3011     if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
3012     //
3013     found = false;
3014     //
3015     };
3016 mocchiut 1.1 };
3017     };
3018 mocchiut 1.2 //
3019     if ( found ){
3020     //
3021     // 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
3022     //
3023     if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
3024     //
3025     if ( foundinrun ){
3026     glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3027     glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
3028     };
3029 mocchiut 1.1 //
3030 mocchiut 1.2 GL_RUN *glrun1 = new GL_RUN();
3031 mocchiut 1.1 //
3032 mocchiut 1.2 // UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
3033 mocchiut 1.1 //
3034 mocchiut 1.2 oss.str("");
3035     oss << " ID="<<row->GetField(0)<<";";
3036     //
3037     glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runtrailer infos
3038 mocchiut 1.1 //
3039 mocchiut 1.2 // merge infos
3040 mocchiut 1.1 //
3041 mocchiut 1.2 UInt_t apkt = PKT(glrun->GetRUNTRAILER_PKT());
3042     ULong64_t aobt = OBT(glrun->GetRUNTRAILER_OBT());
3043     UInt_t bpkt = PKT(glrun1->GetRUNHEADER_PKT());
3044     ULong64_t bobt = OBT(glrun1->GetRUNHEADER_OBT());
3045     if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
3046     TTree *T= 0;
3047     T = (TTree*)file->Get("Physics");
3048     if ( !T || T->IsZombie() ) throw -16;
3049     EventHeader *eh = 0;
3050     PscuHeader *ph = 0;
3051     T->SetBranchAddress("Header", &eh);
3052     while ( apkt > bpkt && aobt > bobt && lastev > 0 ){
3053     T->GetEntry(lastev);
3054     ph = eh->GetPscuHeader();
3055     apkt = PKT(ph->GetCounter());
3056     aobt = OBT(ph->GetOrbitalTime());
3057     lastev--;
3058     if ( PEDANTIC ) throw -72;
3059     };
3060     if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
3061     //
3062     glrun->SetEV_TO(lastev);
3063     glrun->SetNEVENTS(lastev-firstev+1);
3064     glrun->SetPKT_COUNTER(glrun1->GetPKT_COUNTER());
3065     glrun->SetPKT_READY_COUNTER(glrun1->GetPKT_READY_COUNTER());
3066     glrun->SetRUNTRAILER_TIME(glrun1->GetRUNTRAILER_TIME());
3067     glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());
3068     glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());
3069     //
3070     glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());
3071     glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());
3072     glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());
3073     glrun1->SetCOMPILATIONTIMESTAMP(glrun->GetCOMPILATIONTIMESTAMP());
3074     glrun1->SetFAV_WRK_SCHEDULE(glrun->GetFAV_WRK_SCHEDULE());
3075     glrun1->SetEFF_WRK_SCHEDULE(glrun->GetEFF_WRK_SCHEDULE());
3076     glrun1->SetPRH_VAR_TRG_MODE_A(glrun->GetPRH_VAR_TRG_MODE_A());
3077     glrun1->SetPRH_VAR_TRG_MODE_B(glrun->GetPRH_VAR_TRG_MODE_B());
3078     glrun1->SetACQ_BUILD_INFO(glrun->GetACQ_BUILD_INFO());
3079     glrun1->SetACQ_VAR_INFO(glrun->GetACQ_VAR_INFO());
3080     glrun1->SetRM_ACQ_AFTER_CALIB(glrun->GetRM_ACQ_AFTER_CALIB());
3081     glrun1->SetRM_ACQ_SETTING_MODE(glrun->GetRM_ACQ_SETTING_MODE());
3082     glrun1->SetTRK_CALIB_USED(glrun->GetTRK_CALIB_USED());
3083     glrun1->SetCAL_DSP_MASK(glrun->GetCAL_DSP_MASK());
3084     glrun1->SetLAST_TIMESYNC(glrun->GetLAST_TIMESYNC());
3085     glrun1->SetOBT_TIMESYNC(glrun->GetOBT_TIMESYNC());
3086     //
3087     if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ) glrun1->SetPHYSENDRUN_MASK_S3S2S12(glrun->GetPHYSENDRUN_MASK_S3S2S12());
3088     if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) glrun1->SetPHYSENDRUN_MASK_S11CRC(glrun->GetPHYSENDRUN_MASK_S11CRC());
3089     //
3090     if ( !IsRunAlreadyInserted() ){
3091     //
3092     // glrun->SetID(this->AssignRunID());
3093 mocchiut 1.1 //
3094 mocchiut 1.2 glrun->SetID_RUN_FRAG(glrun1->GetID());
3095     glrun->Fill_GL_RUN(conn);
3096 mocchiut 1.1 //
3097 mocchiut 1.2 // set id number
3098 mocchiut 1.1 //
3099 mocchiut 1.2 glrun1->SetID_RUN_FRAG(glrun->GetID());
3100     glrun1->Fill_GL_RUN(conn);
3101 mocchiut 1.1 //
3102     };
3103 mocchiut 1.2 //
3104     // delete old entries in fragment table
3105     //
3106     glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3107     glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3108     //
3109     delete glrun1;
3110     //
3111     return;
3112     //
3113 mocchiut 1.1 };
3114 mocchiut 1.2 //
3115 mocchiut 1.1 };
3116     //
3117 mocchiut 1.2 justcheck:
3118     //
3119     if ( !found ){
3120 mocchiut 1.1 //
3121 mocchiut 1.2 if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");
3122 mocchiut 1.1 //
3123 mocchiut 1.2 // not found, has this run already inserted in the GL_RUN or in the GL_RUN_FRAGMENTS table?
3124 mocchiut 1.1 //
3125     oss.str("");
3126 mocchiut 1.2 oss << " SELECT ID FROM GL_RUN WHERE "
3127     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3128     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3129     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3130     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3131     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3132     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3133     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3134     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3135     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3136     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3137     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3138     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3139     << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3140 mocchiut 1.1 //
3141 mocchiut 1.2 if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3142     result = conn->Query(oss.str().c_str());
3143 mocchiut 1.1 //
3144 mocchiut 1.2 if ( !result ) throw -4;
3145 mocchiut 1.1 //
3146 mocchiut 1.2 row = result->Next();
3147 mocchiut 1.1 //
3148 mocchiut 1.2 if ( row ){
3149     if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");
3150     if ( PEDANTIC ) throw -70;
3151     } else {
3152     if ( NoFrag() ){
3153     glrun->SetID_RUN_FRAG(glrun->GetID());
3154     glrun->Fill_GL_RUN(conn);
3155     glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3156     };
3157 mocchiut 1.1 };
3158     };
3159     }; // EEE
3160     //
3161     return;
3162     };
3163    
3164    
3165     /**
3166     * Handle run without header or trailer
3167     **/
3168     void PamelaDBOperations::HandleMissingHoT(Bool_t mishead, Bool_t mistrail, UInt_t firstev, UInt_t lastev){
3169     //
3170     //
3171     // is the piece of run good (no other packets inside)?
3172     //
3173     if ( !this->IsRunConsistent(mishead,mistrail,firstev,lastev)){
3174     //
3175     // if not, handle other pieces and continue with the first one
3176     //
3177     if ( IsDebug() ) printf("The run is not consistent, it contains non-physics packets! The run has been handled \n");
3178     //
3179     } else {
3180     //
3181     this->FillClass(mishead,mistrail,firstev,lastev);
3182     //
3183     if ( !IsRunAlreadyInserted() ){
3184     glrun->SetID(this->AssignRunID());
3185     glrun->SetID_RUN_FRAG(0);
3186     glrun->Fill_GL_RUN(conn); // it'ok we arrive here only inside a file hence in the middle of the runs...
3187     };
3188     //
3189     };
3190     //
3191     return;
3192     };
3193    
3194     /**
3195     *
3196     * check if we have non-physics packets inside the run
3197     *
3198     */
3199     Bool_t PamelaDBOperations::IsRunConsistent(Bool_t mishead, Bool_t mistrail, UInt_t &firstev, UInt_t &lastev){
3200     //
3201     EventCounter *code=0;
3202     //
3203     UInt_t nevent = 0;
3204     UInt_t checkfirst = 0;
3205     UInt_t checklast = 0;
3206     UInt_t firstentry = 0;
3207     UInt_t lastentry = 0;
3208     UInt_t firstTime = 0;
3209     UInt_t lastTime = 0;
3210     UInt_t firstPkt = 0;
3211     UInt_t lastPkt = 0;
3212     UInt_t firstObt = 0;
3213     UInt_t lastObt = 0;
3214     //
3215     pcksList packetsNames;
3216     pcksList::iterator Iter;
3217     getPacketsNames(packetsNames);
3218     //
3219     TTree *T= 0;
3220     T =(TTree*)file->Get("Physics");
3221     if ( !T || T->IsZombie() ) throw -16;
3222     EventHeader *eh = 0;
3223     PscuHeader *ph = 0;
3224     T->SetBranchAddress("Header", &eh);
3225     nevent = T->GetEntries();
3226     //
3227     //
3228     if ( firstev == lastev+1 || lastev == firstev ) { // no events inside the run!
3229     //if ( firstev <= lastev+1 ) { // no events inside the run!
3230     if ( IsDebug() ) printf(" Checking but no events in the run! \n");
3231     // return true is correct
3232     return(true);
3233     //
3234     } else {
3235     //
3236     T->GetEntry(firstev);
3237     code = eh->GetCounter();
3238     checkfirst = 0;
3239     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3240 mocchiut 1.2 if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
3241     };
3242 mocchiut 1.1 if ( IsDebug() ) printf(" Check first is %i firstev is %i\n",checkfirst,firstev);
3243     //
3244     T->GetEntry(lastev);
3245     code = eh->GetCounter();
3246     checklast = 0;
3247     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3248 mocchiut 1.2 if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
3249     };
3250 mocchiut 1.1 if ( IsDebug() ) printf(" Check last is %i lastev is %i\n",checklast,lastev);
3251     //
3252     if ( checkfirst == checklast ){
3253     //
3254     if ( IsDebug() ) printf(" No packets but physics inside the run, I will consider it as good\n");
3255     //
3256     return(true);
3257     //
3258     } else {
3259     //
3260 mocchiut 1.10 if ( IsDebug() ) printf(" There are no-physics packets inside the run!\n");
3261 mocchiut 1.1 //
3262     // HERE WE MUST HANDLE THAT RUNS AND GO BACK
3263     //
3264 mocchiut 1.2 // if ( IsDebug() ) printf(" Never seen this case, try to handle it anyway, it was throw -95\n");
3265 mocchiut 1.1 //
3266     Bool_t emptyruns = false;
3267     UInt_t check = 0;
3268     UInt_t lastevtemp = lastev;
3269     UInt_t firstevno = firstev;
3270 mocchiut 1.10 UInt_t rhchko=0;
3271     UInt_t rhchk=0;
3272 mocchiut 1.1 //
3273     for (UInt_t i=firstev; i<=lastev; i++){
3274     //
3275     T->GetEntry(i);
3276     code = eh->GetCounter();
3277     //
3278     check = 0;
3279     //
3280 mocchiut 1.10
3281     // if we have a runheader set lastev then exit
3282     //
3283 mocchiut 1.1 for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3284     if ( strcmp(*Iter,"Physics") ) check += code->Get(GetPacketType(*Iter));
3285     };
3286 mocchiut 1.10 // check here if we have a runheader
3287     rhchko = rhchk;
3288     rhchk = code->Get(GetPacketType("RunHeader"));
3289 mocchiut 1.1 //
3290     if ( checkfirst < check || i == lastev ){
3291     //
3292     firstentry = firstevno;
3293     //
3294     if ( checkfirst < check ){
3295     lastentry = i-1;
3296     } else {
3297     lastentry = i;
3298     };
3299     //
3300     if ( IsDebug() ) printf(" Run between %i and %i entries\n",firstentry,lastentry);
3301     //
3302     glrun->SetEV_FROM(firstentry);
3303     glrun->SetEV_TO(lastentry);
3304     if ( lastentry == (firstentry-1) ){ // no physics packets inside physics run with no runheader no runtrailer
3305     if ( IsDebug() ) printf(" no physics packets inside physics run with no runheader no runtrailer\n");
3306     lastentry--;
3307     };
3308     glrun->SetNEVENTS(lastentry-firstentry+1);
3309     //
3310     glrun->Set_GL_RUNH0();
3311     glrun->Set_GL_RUNT0();
3312     //
3313     glrun->SetLAST_TIMESYNC(0);
3314     glrun->SetOBT_TIMESYNC(0);
3315     //
3316     T->GetEntry(firstentry);
3317     ph = eh->GetPscuHeader();
3318     firstObt = ph->GetOrbitalTime();
3319     firstTime = this->GetAbsTime(firstObt);
3320     firstPkt = ph->GetCounter();
3321     //
3322     T->GetEntry(lastentry);
3323     ph = eh->GetPscuHeader();
3324     lastObt = ph->GetOrbitalTime();
3325     lastTime = this->GetAbsTime(lastObt);
3326     lastPkt = ph->GetCounter();
3327     //
3328     glrun->SetRUNHEADER_PKT(firstPkt);
3329 mocchiut 1.2 glrun->SetRUNTRAILER_PKT(lastPkt);
3330     //
3331     glrun->SetRUNHEADER_OBT(firstObt);
3332     glrun->SetRUNTRAILER_OBT(lastObt);
3333     //
3334     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());
3335     if ( firstev == firstentry && !emptyruns && !mishead ){
3336     glrun->Set_GL_RUNH(runh,phh);
3337     firstTime = this->GetAbsTime(phh->GetOrbitalTime());
3338     if ( IsDebug() ) printf(" We have the runheader \n");
3339     };
3340     if ( lastev == i && !mistrail ){
3341     glrun->Set_GL_RUNT(runt,pht);
3342     lastTime = this->GetAbsTime(pht->GetOrbitalTime());
3343     if ( IsDebug() ) printf(" We have the runtrailer \n");
3344     };
3345     //
3346     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());
3347     if ( lastentry == (firstentry-2) ){ // no events in the run
3348     emptyruns = true;
3349     if ( IsDebug() ) printf(" No events in the run \n");
3350     lastTime = firstTime;
3351     if ( (UInt_t)firstTime == this->GetAbsTime(phh->GetOrbitalTime()) ){
3352     lastObt = glrun->RUNHEADER_OBT;
3353     lastPkt = glrun->RUNHEADER_PKT;
3354     } else {
3355     lastObt = firstObt;
3356     lastPkt = firstPkt;
3357     };
3358     glrun->SetRUNTRAILER_PKT(lastPkt);
3359     glrun->SetRUNTRAILER_OBT(lastObt);
3360     lastentry++;
3361     };
3362     //
3363     this->SetCommonGLRUN(firstTime,lastTime);
3364     this->SetPhysEndRunVariables();
3365     //
3366     if ( chminentry == firstentry ){ // EEE
3367     if ( IsDebug() ) printf(" Inside isrunconsistent found a fragment of run at the beginning of the file, put it in the fragment table \n");
3368     //
3369     // 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
3370     //
3371    
3372     mishead = true;
3373    
3374    
3375     UInt_t rhfirstev = firstentry;
3376     // UInt_t rtlastev = lastentry;
3377     Bool_t found = false;
3378     Bool_t foundinrun = false;
3379     //
3380     TSQLResult *result = 0;
3381     TSQLRow *row = 0;
3382     //
3383     stringstream oss;
3384     oss.str("");
3385     //
3386     // we have now the good first piece of a run, fill the glrun object
3387     //
3388     // if ( rhfirstev != firstev && !mishead ) mishead = true;
3389     // if ( rtlastev != lastev && !mistrail ) mistrail = true;
3390     //
3391     // this->FillClass(mishead,mistrail,firstev,lastev);
3392     //
3393     if ( IsDebug() ) printf("zz The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
3394     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());
3395     //
3396     // First of all insert the run in the fragment table...
3397     //
3398     oss.str("");
3399     oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
3400     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3401     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3402     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3403     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3404     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3405     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3406     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3407     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3408     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3409     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3410     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3411     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3412     << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3413     //
3414     if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3415     result = conn->Query(oss.str().c_str());
3416     //
3417     if ( !result ) throw -4;
3418     //
3419     row = result->Next();
3420     //
3421     if ( !row ){
3422     //
3423     // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
3424     //
3425     if ( IsDebug() ) printf(" The run is new \n");
3426     if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
3427     //
3428     glrun->SetID(this->AssignRunID());
3429     glrun->SetID_RUN_FRAG(0);
3430     glrun->Fill_GL_RUN_FRAGMENTS(conn);
3431     //
3432     } else {
3433     if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
3434     if ( PEDANTIC ) throw -69;
3435     // return;
3436     };
3437     //
3438     if ( chewbacca && mishead && mistrail ) goto zjustcheck;
3439     //
3440     // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
3441     //
3442     if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
3443     // missing it no way we can found a piece in the frag table
3444     //
3445     oss.str("");
3446     oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "
3447     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3448     << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3449     << " ID != " << glrun->ID
3450     << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
3451     //
3452     if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());
3453     result = conn->Query(oss.str().c_str());
3454     //
3455     if ( !result ) throw -4;
3456     //
3457     row = result->Next();
3458     //
3459     if ( !row && NoFrag() ){
3460     //
3461     oss.str("");
3462     oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
3463     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3464     << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3465     << " ID != " << glrun->ID
3466     << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
3467     //
3468     if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
3469     result = conn->Query(oss.str().c_str());
3470     //
3471     if ( !result ) throw -4;
3472     //
3473     foundinrun = true;
3474     //
3475     row = result->Next();
3476     //
3477     };
3478     //
3479     if ( !row ){
3480     if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
3481     found = false;
3482     } else {
3483     //
3484     found = false; // default value
3485     //
3486     if ( IsDebug() ) printf(" Found a possible candidate, checking if it is the good one... \n");
3487     //
3488     // if we have both runheader and runtrailer we can check with pkt_counter:
3489     //
3490     if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){
3491     ULong64_t chkpkt = 0;
3492     ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
3493     ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
3494     //
3495     chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;
3496     //
3497     if ( labs(chkpkt-pktt)<2 ){
3498     //
3499     if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
3500     //
3501     found = true;
3502     //
3503     } else {
3504     //
3505     if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);
3506     //
3507     found = false;
3508     //
3509     };
3510     };
3511     if ( !found && chewbacca ) goto zjustcheck;
3512     if ( !found ){
3513     //
3514     // 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
3515     //
3516     ULong64_t chkpkt1 = 0;
3517     ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
3518     ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
3519     chkpkt1 = labs(orunh1-dbrunt1);
3520     //
3521     ULong64_t chkpkt2 = 0;
3522     ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());
3523     ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
3524     chkpkt2 = labs(orunh2-dbrunt2);
3525     //
3526     ULong64_t chkpkt3 = 0;
3527     ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());
3528     ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
3529     chkpkt3 = labs(orunh3-dbrunt3);
3530     //
3531     if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
3532     // if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){
3533     //
3534     if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
3535     //
3536     found = true;
3537     //
3538     } else {
3539     //
3540     if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
3541     //
3542     found = false;
3543     //
3544     };
3545     };
3546     };
3547     //
3548     if ( found ){
3549     //
3550     // 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
3551     //
3552     if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
3553     //
3554     if ( foundinrun ){
3555     glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3556     glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
3557     };
3558     //
3559     GL_RUN *glrun1 = new GL_RUN();
3560     //
3561     // UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
3562     //
3563     oss.str("");
3564     oss << " ID="<<row->GetField(0)<<";";
3565     //
3566     glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos
3567     //
3568     // merge infos
3569     //
3570     UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());
3571     ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
3572     UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
3573     ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
3574     if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
3575     TTree *T= 0;
3576     T = (TTree*)file->Get("Physics");
3577     if ( !T || T->IsZombie() ) throw -16;
3578     EventHeader *eh = 0;
3579     PscuHeader *ph = 0;
3580     T->SetBranchAddress("Header", &eh);
3581     while ( apkt > bpkt && aobt > bobt && firstev < lastev ){
3582     T->GetEntry(firstev);
3583     ph = eh->GetPscuHeader();
3584     bpkt = PKT(ph->GetCounter());
3585     bobt = OBT(ph->GetOrbitalTime());
3586     firstev++;
3587     if ( PEDANTIC ) throw -71;
3588     };
3589     if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
3590     //
3591     glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
3592     glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
3593     glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
3594     glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());
3595     glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());
3596     //
3597     glrun->SetEV_FROM(firstev);
3598     glrun->SetNEVENTS(lastev-firstev+1);
3599     //
3600     glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
3601     glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
3602     glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
3603     glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());
3604     glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());
3605     glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());
3606     glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());
3607     glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());
3608     glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());
3609     glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());
3610     glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());
3611     glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());
3612     glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());
3613     glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());
3614     glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());
3615     glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());
3616     //
3617     if ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
3618     if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
3619     //
3620     if ( !IsRunAlreadyInserted() ){
3621     //
3622     // glrun->SetID(this->AssignRunID());
3623     glrun->SetID_RUN_FRAG(glrun1->GetID());
3624     glrun->Fill_GL_RUN(conn);
3625     //
3626     // set id number
3627     //
3628     glrun1->SetID_RUN_FRAG(glrun->GetID());
3629     glrun1->Fill_GL_RUN(conn);
3630     //
3631     };
3632     // delete old entry in fragment table
3633     //
3634     glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3635     glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3636     //
3637     delete glrun1;
3638     //
3639     //
3640     // return;
3641     //
3642     };
3643     //
3644 mocchiut 1.1 };
3645 mocchiut 1.2 //
3646     //
3647     zjustcheck:
3648     //
3649     if ( !found ){
3650     //
3651     if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");
3652     //
3653     // not found, has this run already inserted in the GL_RUN or in the GL_RUN_FRAGMENTS table?
3654     //
3655     oss.str("");
3656     oss << " SELECT ID FROM GL_RUN WHERE "
3657     << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3658     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3659     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3660     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3661     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3662     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3663     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3664     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3665     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3666     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3667     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3668     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3669     << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3670     //
3671     if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3672     result = conn->Query(oss.str().c_str());
3673     //
3674     if ( !result ) throw -4;
3675     //
3676     row = result->Next();
3677     //
3678     if ( row ){
3679     if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");
3680     if ( PEDANTIC ) throw -70;
3681     } else {
3682     if ( NoFrag() ){
3683     glrun->SetID_RUN_FRAG(glrun->GetID());
3684     glrun->Fill_GL_RUN(conn);
3685     glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3686     };
3687     };
3688     }; // EEE
3689 mocchiut 1.1
3690    
3691     } else {
3692 mocchiut 1.2 if ( !IsRunAlreadyInserted() ){
3693     glrun->SetID(this->AssignRunID());
3694     glrun->SetID_RUN_FRAG(0);
3695     glrun->Fill_GL_RUN(conn);
3696     };
3697 mocchiut 1.1 }; // EEE
3698     //
3699     firstevno = lastentry + 1;
3700     //
3701     checkfirst = check;
3702     //
3703     };
3704     //
3705 mocchiut 1.10 if ( i > firstev ){
3706     if ( rhchko != rhchk ){
3707     if ( IsDebug() ) printf("oh oh... we have a runheader! stop here and handle later the remaining piece\n");
3708     lastev = i;
3709     return(false);
3710     };
3711     };
3712     //
3713 mocchiut 1.1 if ( check == checklast && i != lastev ){
3714     lastevtemp = i - 1;
3715     i = lastev - 1;
3716     };
3717     //
3718     };
3719     //
3720     lastev = lastevtemp;
3721     //
3722     return(false);
3723     //
3724     };
3725     };
3726     //
3727     return(false); // should never arrive here
3728     };
3729    
3730     /**
3731     *
3732     * 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
3733     * 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
3734     * looking for non-physics packets inside.
3735     *
3736     */
3737     void PamelaDBOperations::HandleSuspiciousRun(){
3738     //
3739     PacketType *pctp=0;
3740     EventCounter *codt=0;
3741     EventCounter *codh=0;
3742     EventCounter *code=0;
3743     UInt_t firstev = 0;
3744     UInt_t lastev = 0;
3745     UInt_t nevent = 0;
3746     UInt_t checkfirst = 0;
3747     UInt_t checklast = 0;
3748     UInt_t firstentry = 0;
3749     UInt_t lastentry = 0;
3750     UInt_t firstTime = 0;
3751     UInt_t lastTime = 0;
3752     UInt_t firstPkt = 0;
3753     UInt_t lastPkt = 0;
3754     UInt_t firstObt = 0;
3755     UInt_t lastObt = 0;
3756     //
3757     pcksList packetsNames;
3758     pcksList::iterator Iter;
3759     getPacketsNames(packetsNames);
3760     //
3761     TTree *rh=0;
3762     rh = (TTree*)file->Get("RunHeader");
3763     if ( !rh || rh->IsZombie() ) throw -17;
3764     TTree *T=0;
3765     T =(TTree*)file->Get("Physics");
3766     if ( !T || T->IsZombie() ) throw -16;
3767     EventHeader *eh = 0;
3768     PscuHeader *ph = 0;
3769     T->SetBranchAddress("Header", &eh);
3770     nevent = T->GetEntries();
3771     //
3772     codt = eht->GetCounter();
3773     codh = ehh->GetCounter();
3774     firstev = codh->Get(pctp->Physics);
3775     lastev = codt->Get(pctp->Physics)-1;
3776     if ( IsDebug() ) printf(" From the current runheader firstev is %u from the runtrailer lastev is %u \n",firstev,lastev);
3777     //
3778     if ( firstev == lastev+1 ) { // no events inside the run!
3779     if ( IsDebug() ) printf(" Checking but no events in the run! \n");
3780     //
3781     this->FillClass();
3782     if ( !IsRunAlreadyInserted() ){
3783     glrun->SetID(this->AssignRunID());
3784     glrun->SetID_RUN_FRAG(0);
3785     glrun->Fill_GL_RUN(conn);
3786     };
3787     //
3788     } else {
3789     //
3790     UInt_t nrunh = 0 + codh->Get(pctp->RunHeader);
3791     UInt_t nrunh1 = 0 + codh->Get(pctp->RunHeader);
3792     T->GetEntry(firstev);
3793     code = eh->GetCounter();
3794     checkfirst = 0;
3795     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3796 mocchiut 1.2 if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
3797     if ( !strcmp(*Iter,"RunHeader") ) nrunh1++;
3798     };
3799 mocchiut 1.1 if ( IsDebug() ) printf(" Check first is %i \n",checkfirst);
3800     //
3801     T->GetEntry(lastev);
3802     code = eh->GetCounter();
3803     checklast = 0;
3804     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3805 mocchiut 1.2 if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
3806     };
3807 mocchiut 1.1 if ( IsDebug() ) printf(" Check last is %i \n",checklast);
3808     //
3809     if ( checkfirst == checklast ){
3810     //
3811     if ( IsDebug() ) printf(" No packets but physics inside the run, I will consider it as good\n");
3812     //
3813     this->FillClass();
3814     if ( !IsRunAlreadyInserted() ){
3815     glrun->SetID(this->AssignRunID());
3816     glrun->SetID_RUN_FRAG(0);
3817     glrun->Fill_GL_RUN(conn);
3818     };
3819     //
3820     } else {
3821     //
3822     if ( IsDebug() ) printf(" There are no-physics packets inside the run, try to separate runs \n");
3823     //
3824     Bool_t emptyruns = false;
3825     UInt_t check = 0;
3826     UInt_t firstevno = firstev;
3827     //
3828     for (UInt_t i=firstev; i<=lastev; i++){
3829     //
3830     T->GetEntry(i);
3831     code = eh->GetCounter();
3832     //
3833     check = 0;
3834     //
3835     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3836     if ( strcmp(*Iter,"Physics") ) check += code->Get(GetPacketType(*Iter));
3837     if ( !strcmp(*Iter,"RunHeader") ) nrunh++;
3838     };
3839     //
3840     if ( checkfirst < check || i == lastev ){
3841     //
3842     firstentry = firstevno;
3843     //
3844     if ( checkfirst < check ){
3845     lastentry = i-1;
3846     } else {
3847     lastentry = i;
3848     };
3849     //
3850     if ( IsDebug() ) printf(" Run between %i and %i entries\n",firstentry,lastentry);
3851     //
3852     glrun->SetEV_FROM(firstentry);
3853     glrun->SetEV_TO(lastentry);
3854     if ( lastentry == (firstentry-1) ){ // no physics packets inside physics run with no runheader no runtrailer
3855     if ( IsDebug() ) printf(" no physics packets inside physics run with no runheader no runtrailer\n");
3856     lastentry--;
3857     };
3858     glrun->SetNEVENTS(lastentry-firstentry+1);
3859     //
3860     glrun->Set_GL_RUNH0();
3861     glrun->Set_GL_RUNT0();
3862     //
3863     glrun->SetLAST_TIMESYNC(0);
3864     glrun->SetOBT_TIMESYNC(0);
3865     //
3866     T->GetEntry(firstentry);
3867     ph = eh->GetPscuHeader();
3868     firstObt = ph->GetOrbitalTime();
3869     firstTime = this->GetAbsTime(firstObt);
3870     firstPkt = ph->GetCounter();
3871     //
3872     T->GetEntry(lastentry);
3873     ph = eh->GetPscuHeader();
3874     lastObt = ph->GetOrbitalTime();
3875     lastTime = this->GetAbsTime(lastObt);
3876     lastPkt = ph->GetCounter();
3877     //
3878     glrun->SetRUNHEADER_PKT(firstPkt);
3879     glrun->SetRUNTRAILER_PKT(lastPkt);
3880     //
3881     glrun->SetRUNHEADER_OBT(firstObt);
3882     glrun->SetRUNTRAILER_OBT(lastObt);
3883     //
3884     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());
3885     //
3886     if ( (firstev == firstentry && !emptyruns) || nrunh == (nrunh1 + 1) ){
3887     rh->GetEntry(nrunh1-1);
3888     phh = ehh->GetPscuHeader();
3889     nrunh1++;
3890     glrun->Set_GL_RUNH(runh,phh);
3891     firstTime = this->GetAbsTime(phh->GetOrbitalTime());
3892     if ( IsDebug() ) printf(" We have the runheader \n");
3893     };
3894     if ( lastev == i && checkfirst == check ){
3895     glrun->Set_GL_RUNT(runt,pht);
3896     lastTime = this->GetAbsTime(pht->GetOrbitalTime());
3897     if ( IsDebug() ) printf(" We have the runtrailer \n");
3898     };
3899     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());
3900     //
3901     if ( lastentry == (firstentry-2) ){ // no events in the run
3902     emptyruns = true;
3903     if ( IsDebug() ) printf(" No events in the run \n");
3904     lastTime = firstTime;
3905     if ( (UInt_t)firstTime == this->GetAbsTime(phh->GetOrbitalTime()) ){
3906     lastObt = glrun->RUNHEADER_OBT;
3907     lastPkt = glrun->RUNHEADER_PKT;
3908     } else {
3909     lastObt = firstObt;
3910     lastPkt = firstPkt;
3911     };
3912     glrun->SetRUNTRAILER_PKT(lastPkt);
3913     glrun->SetRUNTRAILER_OBT(lastObt);
3914     lastentry++;
3915     };
3916     //
3917     this->SetCommonGLRUN(firstTime,lastTime);
3918 mocchiut 1.2 this->SetPhysEndRunVariables();
3919 mocchiut 1.1 //
3920     if ( !IsRunAlreadyInserted() ){
3921     glrun->SetID(this->AssignRunID());
3922     glrun->SetID_RUN_FRAG(0);
3923     glrun->Fill_GL_RUN(conn);
3924     };
3925     //
3926     if ( i == lastev && checkfirst < check ){ // if the last event gives a wrong check...
3927     //
3928     firstentry = i;
3929     //
3930     lastentry = i;
3931     //
3932     if ( IsDebug() ) printf(" Run between %i and %i entries\n",firstentry,lastentry);
3933     //
3934     glrun->SetEV_FROM(firstentry);
3935     glrun->SetEV_TO(lastentry);
3936     glrun->SetNEVENTS(lastentry-firstentry+1);
3937     //
3938     glrun->Set_GL_RUNH0();
3939     //
3940     glrun->SetLAST_TIMESYNC(0);
3941     glrun->SetOBT_TIMESYNC(0);
3942     //
3943     T->GetEntry(firstentry);
3944     ph = eh->GetPscuHeader();
3945     firstObt = ph->GetOrbitalTime();
3946     firstTime = this->GetAbsTime(firstObt);
3947     firstPkt = ph->GetCounter();
3948     //
3949     glrun->SetRUNHEADER_PKT(firstPkt);
3950     //
3951     glrun->SetRUNHEADER_OBT(firstObt);
3952     //
3953     glrun->Set_GL_RUNT(runt,pht);
3954     lastTime = this->GetAbsTime(pht->GetOrbitalTime());
3955     if ( IsDebug() ) printf(" We have the runtrailer \n");
3956     //
3957     this->SetCommonGLRUN(firstTime,lastTime);
3958 mocchiut 1.2 this->SetPhysEndRunVariables();
3959 mocchiut 1.1 //
3960     if ( !IsRunAlreadyInserted() ){
3961     glrun->SetID(this->AssignRunID());
3962     glrun->SetID_RUN_FRAG(0);
3963     glrun->Fill_GL_RUN(conn);
3964     };
3965     };
3966     //
3967     firstevno = lastentry + 1;
3968     //
3969     checkfirst = check;
3970     //
3971     };
3972     //
3973     if ( check == checklast && i != lastev ) i = lastev - 1; // >>>>>>>>>>>>>>>>>>>>>>
3974     //
3975     };
3976     };
3977     };
3978     //
3979     return;
3980     };
3981    
3982    
3983     /**
3984     * Scan calorimeter calibrations packets, fill the GL_CALO_CALIB table
3985     */
3986     Int_t PamelaDBOperations::insertCALO_CALIB(){
3987     //
3988     TSQLResult *result = 0;
3989     TSQLRow *row = 0;
3990     //
3991     stringstream oss;
3992     oss.str("");
3993     //
3994     CalibCalPedEvent *calibCalPed = 0;
3995     TTree *tr = 0;
3996     EventHeader *eh = 0;
3997     PscuHeader *ph = 0;
3998     //
3999     UInt_t nevents = 0;
4000     UInt_t fromtime = 0;
4001     UInt_t totime = 0;
4002     UInt_t obt = 0;
4003     UInt_t pkt = 0;
4004     //
4005     tr = (TTree*)file->Get("CalibCalPed");
4006     if ( !tr || tr->IsZombie() ) throw -21;
4007     //
4008     tr->SetBranchAddress("CalibCalPed", &calibCalPed);
4009     tr->SetBranchAddress("Header", &eh);
4010     nevents = tr->GetEntries();
4011     //
4012     if ( !nevents ) return(1);
4013     //
4014     for (UInt_t i=0; i < nevents; i++){
4015     tr->GetEntry(i);
4016     for (UInt_t section = 0; section < 4; section++){
4017     //
4018     if ( calibCalPed->cstwerr[section] ){
4019     valid = 1;
4020     if ( calibCalPed->cperror[section] ) valid = 0;
4021     ph = eh->GetPscuHeader();
4022     obt = ph->GetOrbitalTime();
4023     pkt = ph->GetCounter();
4024     fromtime = this->GetAbsTime(ph->GetOrbitalTime());
4025     if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->PKT(pkt) <= upperpkt && this->OBT(obt) >= this->OBT(obtfirst) && this->OBT(obt) <= upperobt ){
4026     //
4027     if ( IsDebug() ) printf(" Calo calibration for section %i at time %u obt %u pkt %u \n",section,fromtime,obt,pkt);
4028     //
4029     // check if the calibration has already been inserted
4030     //
4031     oss.str("");
4032     oss << " SELECT ID FROM GL_CALO_CALIB WHERE "
4033     << " SECTION = "<< section << " AND "
4034     << " BOOT_NUMBER = "<< this->GetBOOTnumber() << " AND "
4035     << " OBT = "<< obt << " AND "
4036     << " PKT = "<< pkt << ";";
4037     //
4038     if ( IsDebug() ) printf(" Check if the calo calibration has already been inserted: query is \n %s \n",oss.str().c_str());
4039     result = conn->Query(oss.str().c_str());
4040     //
4041     if ( !result ) throw -4;
4042     //
4043     row = result->Next();
4044     //
4045     if ( row ){
4046     //
4047     if ( IsDebug() ) printf(" Calo calibration already inserted in the DB\n");
4048     if ( PEDANTIC ) throw -73;
4049     //
4050     } else {
4051     //
4052     // we have to insert a new calibration, check where to place it
4053     //
4054     oss.str("");
4055     oss << " SELECT ID,TO_TIME FROM GL_CALO_CALIB WHERE "
4056     << " SECTION = "<< section << " AND "
4057     << " FROM_TIME < "<< fromtime << " AND "
4058     << " TO_TIME > "<< fromtime << ";";
4059     //
4060     if ( IsDebug() ) printf(" Check where to place the calo calibration: query is \n %s \n",oss.str().c_str());
4061     result = conn->Query(oss.str().c_str());
4062     //
4063     if ( !result ) throw -4;
4064     //
4065     row = result->Next();
4066     //
4067     if ( !row ){
4068     //
4069     // no calibrations in the db contain our calibration
4070     //
4071     if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB for section %i \n",section);
4072     if ( fromtime < 1150871000 ){ //1150866904
4073     if ( IsDebug() ) printf(" First PAMELA flight calibration at time %u \n",fromtime);
4074     fromtime = 0;// the first flight calibration was taken at about 1156429100 s, this line allow to analyze first runs in raw mode
4075     };
4076     //
4077     oss.str("");
4078     oss << " SELECT FROM_TIME FROM GL_CALO_CALIB WHERE "
4079     << " SECTION = "<< section << " AND "
4080     << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
4081     //
4082     if ( IsDebug() ) printf(" Check the upper limit for calibration: query is \n %s \n",oss.str().c_str());
4083     result = conn->Query(oss.str().c_str());
4084     //
4085     if ( !result ) throw -4;
4086     //
4087     row = result->Next();
4088     if ( !row ){
4089     totime = numeric_limits<UInt_t>::max();
4090     } else {
4091     totime = (UInt_t)atoll(row->GetField(0));
4092     };
4093     //
4094     } else {
4095     //
4096     // determine upper and lower limits and make space for the new calibration
4097     //
4098     totime = (UInt_t)atoll(row->GetField(1));
4099     //
4100     oss.str("");
4101     oss << " UPDATE GL_CALO_CALIB SET "
4102     << " TO_TIME = "<< fromtime << " WHERE " // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
4103     << " ID = "<< row->GetField(0) << ";";
4104     //
4105     if ( IsDebug() ) printf(" Make space for the new calibration: query is \n %s \n",oss.str().c_str());
4106     result = conn->Query(oss.str().c_str());
4107     //
4108     if ( !result ) throw -4;
4109     //
4110     };
4111     //
4112     oss.str("");
4113     oss << " INSERT INTO GL_CALO_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,SECTION,OBT,PKT,BOOT_NUMBER,VALIDATION) "
4114     << " VALUES (NULL,' "
4115     << idroot << "','"
4116     << i << "','"
4117     << fromtime << "','"
4118     << totime << "','"
4119     << section << "','"
4120     << obt << "','"
4121     << pkt << "','"
4122     << this->GetBOOTnumber() << "','"
4123     << valid << "');";
4124     //
4125     if ( IsDebug() ) printf(" Insert the new calibration: query is \n %s \n",oss.str().c_str());
4126     //
4127     result = conn->Query(oss.str().c_str());
4128     //
4129     if ( !result ) throw -4;
4130     //
4131     };
4132     //
4133     } else {
4134     //
4135     if ( IsDebug() ) printf(" Calo calibration for section %i at time %u obt %u pkt %u OUTSIDE the considered interval \n",section,fromtime,obt,pkt);
4136     // if ( PEDANTIC ) throw -74;
4137     //
4138     };
4139     //
4140     };
4141     };
4142     };
4143     //
4144     return(0);
4145     };
4146    
4147    
4148     /**
4149     * Scan calorimeter calibrations packets, fill the GL_CALO_CALIB table
4150     */
4151     Int_t PamelaDBOperations::insertCALOPULSE_CALIB(){
4152     //
4153     TSQLResult *result = 0;
4154     TSQLRow *row = 0;
4155     //
4156     stringstream oss;
4157     oss.str("");
4158     //
4159     oss << " DESCRIBE GL_CALOPULSE_CALIB;";
4160     if ( IsDebug() ) printf(" Check if the GL_CALOPULSE_CALIB table exists: query is \n %s \n",oss.str().c_str());
4161     result = conn->Query(oss.str().c_str());
4162     //
4163     if ( conn->GetErrorCode() ){
4164     if ( IsDebug() ) printf(" The GL_CALOPULSE_CALIB table does not exists! \n");
4165     throw -30;
4166     };
4167     //
4168     // CaloPulse1
4169     //
4170     CalibCalPulse1Event *cp1 = 0;
4171     TTree *tr = 0;
4172     EventHeader *eh = 0;
4173     PscuHeader *ph = 0;
4174     //
4175     UInt_t nevents = 0;
4176     UInt_t fromtime = 0;
4177     UInt_t totime = 0;
4178     UInt_t obt = 0;
4179     UInt_t pkt = 0;
4180     //
4181     tr = (TTree*)file->Get("CalibCalPulse1");
4182     if ( !tr || tr->IsZombie() ) throw -31;
4183     //
4184     tr->SetBranchAddress("CalibCalPulse1", &cp1);
4185     tr->SetBranchAddress("Header", &eh);
4186     nevents = tr->GetEntries();
4187     //
4188     if ( nevents > 0 ){
4189     //
4190     for (UInt_t i=0; i < nevents; i++){
4191     tr->GetEntry(i);
4192     for (UInt_t section = 0; section < 4; section++){
4193     //
4194     if ( cp1->pstwerr[section] && cp1->unpackError == 0 ){
4195     valid = 1;
4196     if ( cp1->pperror[section] ) valid = 0;
4197     ph = eh->GetPscuHeader();
4198     obt = ph->GetOrbitalTime();
4199     pkt = ph->GetCounter();
4200     fromtime = this->GetAbsTime(ph->GetOrbitalTime());
4201     if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->PKT(pkt) <= upperpkt && this->OBT(obt) >= this->OBT(obtfirst) && this->OBT(obt) <= upperobt ){
4202     // if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->OBT(obt) >= this->OBT(obtfirst) ){
4203     //
4204     if ( IsDebug() ) printf(" Calo pulse1 calibration for section %i at time %u obt %u pkt %u \n",section,fromtime,obt,pkt);
4205     //
4206     // check if the calibration has already been inserted
4207     //
4208     oss.str("");
4209     oss << " SELECT ID FROM GL_CALOPULSE_CALIB WHERE "
4210     << " SECTION = "<< section << " AND "
4211     << " PULSE_AMPLITUDE = 0 AND "
4212     << " BOOT_NUMBER = "<< this->GetBOOTnumber() << " AND "
4213     << " OBT = "<< obt << " AND "
4214     << " PKT = "<< pkt << ";";
4215     //
4216     if ( IsDebug() ) printf(" Check if the calo pulse1 calibration has already been inserted: query is \n %s \n",oss.str().c_str());
4217     result = conn->Query(oss.str().c_str());
4218     //
4219     if ( !result ) throw -4;
4220     //
4221     row = result->Next();
4222     //
4223     if ( row ){
4224     //
4225     if ( IsDebug() ) printf(" Calo pulse1 calibration already inserted in the DB\n");
4226     if ( PEDANTIC ) throw -75;
4227     //
4228     } else {
4229     //
4230     // we have to insert a new calibration, check where to place it
4231     //
4232     oss.str("");
4233     oss << " SELECT ID,TO_TIME FROM GL_CALOPULSE_CALIB WHERE "
4234     << " SECTION = "<< section << " AND "
4235     << " PULSE_AMPLITUDE = 0 AND "
4236     << " SECTION = "<< section << " AND "
4237     << " FROM_TIME < "<< fromtime << " AND "
4238     << " TO_TIME > "<< fromtime << ";";
4239     //
4240     if ( IsDebug() ) printf(" Check where to place the pulse1 calo calibration: query is \n %s \n",oss.str().c_str());
4241     result = conn->Query(oss.str().c_str());
4242     //
4243     if ( !result ) throw -4;
4244     //
4245     row = result->Next();
4246     //
4247     if ( !row ){
4248     //
4249     // no calibrations in the db contain our calibration
4250     //
4251     if ( IsDebug() ) printf(" Pulse1 calibration with fromtime lower than others to be inserted in the DB for section %i \n",section);
4252     if ( fromtime < 1150871000 ){ //1150866904
4253     if ( IsDebug() ) printf(" First PAMELA flight calibration at time %u \n",fromtime);
4254     fromtime = 0;// the first flight calibration was taken at about 1156429100 s, this line allow to analyze first runs in raw mode
4255     };
4256     //
4257     oss.str("");
4258     oss << " SELECT FROM_TIME FROM GL_CALOPULSE_CALIB WHERE "
4259     << " PULSE_AMPLITUDE = 0 AND "
4260     << " SECTION = "<< section << " AND "
4261     << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
4262     //
4263     if ( IsDebug() ) printf(" Check the upper limit for pulse1 calibration: query is \n %s \n",oss.str().c_str());
4264     result = conn->Query(oss.str().c_str());
4265     //
4266     if ( !result ) throw -4;
4267     //
4268     row = result->Next();
4269     if ( !row ){
4270     totime = numeric_limits<UInt_t>::max();
4271     } else {
4272     totime = (UInt_t)atoll(row->GetField(0));
4273     };
4274     //
4275     } else {
4276     //
4277     // determine upper and lower limits and make space for the new calibration
4278     //
4279     totime = (UInt_t)atoll(row->GetField(1));
4280     //
4281     oss.str("");
4282     oss << " UPDATE GL_CALOPULSE_CALIB SET "
4283     << " TO_TIME = "<< fromtime << " WHERE " // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
4284     << " ID = "<< row->GetField(0) << ";";
4285     //
4286     if ( IsDebug() ) printf(" Make space for the new pulse1 calibration: query is \n %s \n",oss.str().c_str());
4287     result = conn->Query(oss.str().c_str());
4288     //
4289     if ( !result ) throw -4;
4290     //
4291     };
4292     //
4293     oss.str("");
4294     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) "
4295     << " VALUES (NULL,' "
4296     << idroot << "','"
4297     << i << "','"
4298     << fromtime << "','"
4299     << totime << "','"
4300     << section << "',NULL,'0','"
4301     << obt << "','"
4302     << pkt << "','"
4303     << this->GetBOOTnumber() << "','"
4304     << valid << "');";
4305     //
4306     if ( IsDebug() ) printf(" Insert the new pulse1 calibration: query is \n %s \n",oss.str().c_str());
4307     //
4308     result = conn->Query(oss.str().c_str());
4309     //
4310     if ( !result ) throw -4;
4311     //
4312     };
4313     //
4314     } else {
4315     //
4316     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);
4317     // if ( PEDANTIC ) throw -76;
4318     //
4319     };
4320     //
4321     };
4322     };
4323     };
4324     };
4325     //
4326     // CaloPulse2
4327     //
4328     tr->Reset();
4329     CalibCalPulse2Event *cp2 = 0;
4330     tr = 0;
4331     //
4332     nevents = 0;
4333     fromtime = 0;
4334     totime = 0;
4335     obt = 0;
4336     pkt = 0;
4337     //
4338     tr = (TTree*)file->Get("CalibCalPulse2");
4339     if ( !tr || tr->IsZombie() ) throw -32;
4340     //
4341     tr->SetBranchAddress("CalibCalPulse2", &cp2);
4342     tr->SetBranchAddress("Header", &eh);
4343     nevents = tr->GetEntries();
4344     //
4345     if ( nevents > 0 ){
4346     //
4347     for (UInt_t i=0; i < nevents; i++){
4348     tr->GetEntry(i);
4349     for (UInt_t section = 0; section < 4; section++){
4350     //
4351     if ( cp2->pstwerr[section] && cp2->unpackError == 0 ){
4352     valid = 1;
4353     if ( cp2->pperror[section] ) valid = 0;
4354     ph = eh->GetPscuHeader();
4355     obt = ph->GetOrbitalTime();
4356     pkt = ph->GetCounter();
4357     fromtime = this->GetAbsTime(ph->GetOrbitalTime());
4358     if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->PKT(pkt) <= upperpkt && this->OBT(obt) >= this->OBT(obtfirst) && this->OBT(obt) <= upperobt ){
4359     // if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->OBT(obt) >= this->OBT(obtfirst) ){
4360     //
4361     if ( IsDebug() ) printf(" Calo pulse2 calibration for section %i at time %u obt %u pkt %u \n",section,fromtime,obt,pkt);
4362     //
4363     // check if the calibration has already been inserted
4364     //
4365     oss.str("");
4366     oss << " SELECT ID FROM GL_CALOPULSE_CALIB WHERE "
4367     << " SECTION = "<< section << " AND "
4368     << " PULSE_AMPLITUDE != 0 AND "
4369     << " BOOT_NUMBER = "<< this->GetBOOTnumber() << " AND "
4370     << " OBT = "<< obt << " AND "
4371     << " PKT = "<< pkt << ";";
4372     //
4373     if ( IsDebug() ) printf(" Check if the calo pulse2 calibration has already been inserted: query is \n %s \n",oss.str().c_str());
4374     result = conn->Query(oss.str().c_str());
4375     //
4376     if ( !result ) throw -4;
4377     //
4378     row = result->Next();
4379     //
4380     if ( row ){
4381     //
4382     if ( IsDebug() ) printf(" Calo pulse2 calibration already inserted in the DB\n");
4383     if ( PEDANTIC ) throw -77;
4384     //
4385     } else {
4386     //
4387     // we have to insert a new calibration
4388     //
4389     //
4390     // Determine the amplitude of the pulse
4391     //
4392     UInt_t pampli = 1;
4393     UInt_t pstrip = 0;
4394     UInt_t se = 0;
4395     if ( section == 1 ) se = 2;
4396     if ( section == 2 ) se = 3;
4397     if ( section == 3 ) se = 1;
4398     for (Int_t ii=0;ii<16;ii++){
4399     if ( cp2->calpuls[se][0][ii] > 10000. ){
4400     pampli = 2;
4401     pstrip = ii;
4402     };
4403     };
4404     if ( pampli == 1 ){
4405     Bool_t found = false;
4406     Float_t delta=0.;
4407     UInt_t cstr = 0;
4408     while ( !found && cstr < 16 ){
4409     for (Int_t ii=0;ii<16;ii++){
4410     delta = cp2->calpuls[se][0][ii] - cp2->calpuls[se][0][cstr];
4411     if ( IsDebug() ) printf(" cstr is %u ii is %i delta is %f \n",cstr,ii,delta);
4412     if ( delta > 500. ){
4413     pampli = 1;
4414     pstrip = ii;
4415     found = true;
4416     if ( IsDebug() ) printf(" FOUND cstr is %u ii is %i delta is %f \n",cstr,ii,delta);
4417     };
4418     };
4419     cstr++;
4420     };
4421     if ( !found ) pstrip = 100;
4422     };
4423     if ( IsDebug() ) printf(" The amplitude of the pulser is %u (where 1 = low pulse, 2 = high pulse), pulsed strip is %u \n",pampli,pstrip);
4424     //
4425     // we have to insert a new calibration, check where to place it
4426     //
4427     oss.str("");
4428     oss << " SELECT ID,TO_TIME FROM GL_CALOPULSE_CALIB WHERE "
4429     << " SECTION = "<< section << " AND "
4430     << " PULSE_AMPLITUDE = " << pampli << " AND "
4431     << " SECTION = "<< section << " AND "
4432     << " FROM_TIME < "<< fromtime << " AND "
4433     << " TO_TIME > "<< fromtime << ";";
4434     //
4435     if ( IsDebug() ) printf(" Check where to place the pulse2 calo calibration: query is \n %s \n",oss.str().c_str());
4436     result = conn->Query(oss.str().c_str());
4437     //
4438     if ( !result ) throw -4;
4439     //
4440     row = result->Next();
4441     //
4442     if ( !row ){
4443     //
4444     // no calibrations in the db contain our calibration
4445     //
4446     if ( IsDebug() ) printf(" Pulse2 calibration with fromtime lower than others to be inserted in the DB for section %i \n",section);
4447     if ( fromtime < 1150871000 ){ //1150866904
4448     if ( IsDebug() ) printf(" First PAMELA flight calibration at time %u \n",fromtime);
4449     fromtime = 0;// the first flight calibration was taken at about 1156429100 s, this line allow to analyze first runs in raw mode
4450     };
4451     //
4452     oss.str("");
4453     oss << " SELECT FROM_TIME FROM GL_CALOPULSE_CALIB WHERE "
4454     << " PULSE_AMPLITUDE = " << pampli << " AND "
4455     << " SECTION = "<< section << " AND "
4456     << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
4457     //
4458     if ( IsDebug() ) printf(" Check the upper limit for pulse2 calibration: query is \n %s \n",oss.str().c_str());
4459     result = conn->Query(oss.str().c_str());
4460     //
4461     if ( !result ) throw -4;
4462     //
4463     row = result->Next();
4464     if ( !row ){
4465     totime = numeric_limits<UInt_t>::max();
4466     } else {
4467     totime = (UInt_t)atoll(row->GetField(0));
4468     };
4469     //
4470     } else {
4471     //
4472     // determine upper and lower limits and make space for the new calibration
4473     //
4474     totime = (UInt_t)atoll(row->GetField(1));
4475     //
4476     oss.str("");
4477     oss << " UPDATE GL_CALOPULSE_CALIB SET "
4478     << " TO_TIME = "<< fromtime << " WHERE " // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
4479     << " ID = "<< row->GetField(0) << ";";
4480     //
4481     if ( IsDebug() ) printf(" Make space for the new pulse2 calibration: query is \n %s \n",oss.str().c_str());
4482     result = conn->Query(oss.str().c_str());
4483     //
4484     if ( !result ) throw -4;
4485     //
4486     };
4487     //
4488     // Fill the DB
4489     //
4490     oss.str("");
4491     // oss << " INSERT INTO GL_CALOPULSE_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,SECTION,OBT,PKT,BOOT_NUMBER,VALIDATION) "
4492     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) "
4493     << " VALUES (NULL,' "
4494     << idroot << "','"
4495     << i << "','"
4496     << fromtime << "','"
4497     << totime << "','"
4498     << section << "','"
4499     << pstrip << "','"
4500     << pampli << "','"
4501     << obt << "','"
4502     << pkt << "','"
4503     << this->GetBOOTnumber() << "','"
4504     << valid << "');";
4505     //
4506     if ( IsDebug() ) printf(" Insert the new pulse2 calibration: query is \n %s \n",oss.str().c_str());
4507     //
4508     result = conn->Query(oss.str().c_str());
4509     //
4510     if ( !result ) throw -4;
4511     //
4512     };
4513     //
4514     } else {
4515     //
4516     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);
4517     // if ( PEDANTIC ) throw -78;
4518     //
4519     };
4520     //
4521     };
4522     };
4523     };
4524     };
4525     //
4526     return(0);
4527     };
4528    
4529     /**
4530     * Fill the GL_TRK_CALIB table
4531     */
4532     void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){
4533 pam-fi 1.4
4534     GL_TRK_CALIB *glcal = new GL_TRK_CALIB();
4535     //
4536     glcal->ID = 0;
4537     glcal->ID_ROOT_L0 = GetID_ROOT();
4538     glcal->EV_ROOT_CALIBTRK1 = t1;
4539     glcal->EV_ROOT_CALIBTRK2 = t2;
4540     glcal->FROM_TIME = fromtime;
4541     glcal->TO_TIME = 0;
4542     glcal->OBT1 = obt1;
4543     glcal->OBT2 = obt2;
4544     glcal->PKT1 = pkt1;
4545     glcal->PKT2 = pkt2;
4546     glcal->BOOT_NUMBER = GetBOOTnumber();
4547     glcal->VALIDATION = valid;
4548     //
4549     HandleTRK_CALIB(glcal);
4550     //
4551     delete glcal;
4552     }
4553     /**
4554     * Fill the GL_TRK_CALIB table
4555     */
4556     void PamelaDBOperations::HandleTRK_CALIB(GL_TRK_CALIB *glcal){
4557    
4558     Bool_t pk1 = (glcal->OBT1>0&&glcal->PKT1>0);
4559     Bool_t pk2 = (glcal->OBT2>0&&glcal->PKT2>0);
4560     UInt_t boot_number = glcal->BOOT_NUMBER;
4561     UInt_t obt1 = glcal->OBT1;
4562     UInt_t obt2 = glcal->OBT2;
4563     UInt_t pkt1 = glcal->PKT1;
4564     UInt_t pkt2 = glcal->PKT2;
4565     UInt_t fromtime = glcal->FROM_TIME;
4566     UInt_t totime = 0;
4567     UInt_t idroot = glcal->ID_ROOT_L0;
4568     UInt_t t1 = glcal->EV_ROOT_CALIBTRK1;
4569     UInt_t t2 = glcal->EV_ROOT_CALIBTRK2;
4570     UInt_t valid = glcal->VALIDATION;
4571     //
4572     TSQLResult *result = 0;
4573     TSQLRow *row = 0;
4574     //
4575     stringstream oss;
4576     oss.str("");
4577 mocchiut 1.1 //
4578     //
4579 pam-fi 1.4 if ( !pk1 && !pk2 ){
4580     if ( IsDebug() ) printf(" Cannot handle trk calibration with both packet missing!\n");
4581     return;
4582     };
4583 mocchiut 1.1 //
4584 pam-fi 1.4 // check if the calibration has already been inserted
4585 mocchiut 1.1 //
4586     oss.str("");
4587 pam-fi 1.4 oss << " SELECT ID FROM GL_TRK_CALIB WHERE "
4588     << " BOOT_NUMBER = "<< boot_number; //
4589     oss << " AND FROM_TIME="<<fromtime; /// NEWNEWNEW -- VA BENE ?!?!?!?!
4590     oss << " AND ( ( ";
4591     if ( pk1 ){
4592     oss << " OBT1 = "<< obt1 << " AND "
4593     << " PKT1 = "<< pkt1
4594     << " ) OR ( ";
4595     } else {
4596     oss << " PKT1 = "<< pkt2-1
4597     << " ) OR ( ";
4598     };
4599     if ( pk2 ){
4600     oss << " OBT2 = "<< obt2 << " AND "
4601     << " PKT2 = "<< pkt2;
4602     } else {
4603     oss << " PKT2 = "<< pkt1+1;
4604     };
4605     oss << " ) );";
4606 mocchiut 1.1 //
4607 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());
4608 mocchiut 1.1 result = conn->Query(oss.str().c_str());
4609     //
4610     if ( !result ) throw -4;
4611     //
4612     row = result->Next();
4613     //
4614 pam-fi 1.4 if ( row ){
4615     //
4616     if ( IsDebug() ) printf(" Trk calibration already inserted in the DB\n");
4617     if ( PEDANTIC ) throw -80;
4618     //
4619 mocchiut 1.1 } else {
4620 pam-fi 1.4 //
4621     // we have to insert a new calibration, check where to place it
4622     //
4623     oss.str("");
4624     oss << " SELECT ID,TO_TIME FROM GL_TRK_CALIB WHERE "
4625     << " FROM_TIME < "<< fromtime << " AND "
4626     << " TO_TIME > "<< fromtime << ";";
4627     //
4628     if ( IsDebug() ) printf(" Check where to place the trk calibration: query is \n %s \n",oss.str().c_str());
4629     result = conn->Query(oss.str().c_str());
4630     //
4631     if ( !result ) throw -4;
4632     //
4633     row = result->Next();
4634     //
4635     if ( !row ){
4636     //
4637     // no calibrations in the db contain our calibration
4638     //
4639     if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB\n");
4640     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
4641     //
4642     oss.str("");
4643     oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "
4644     << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
4645     //
4646     if ( IsDebug() ) printf(" Check the upper limit for calibration: query is \n %s \n",oss.str().c_str());
4647     result = conn->Query(oss.str().c_str());
4648     //
4649     if ( !result ) throw -4;
4650     //
4651     row = result->Next();
4652     if ( !row ){
4653     totime = numeric_limits<UInt_t>::max();
4654     } else {
4655     totime = (UInt_t)atoll(row->GetField(0));
4656     };
4657     //
4658     } else {
4659     //
4660     // determine upper and lower limits and make space for the new calibration
4661     //
4662     totime = (UInt_t)atoll(row->GetField(1));
4663     //
4664     oss.str("");
4665     oss << " UPDATE GL_TRK_CALIB SET "
4666     << " TO_TIME = "<< fromtime << " WHERE " // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
4667     << " ID = "<< row->GetField(0) << ";";
4668     //
4669     if ( IsDebug() ) printf(" Make space for the new trk calibration: query is \n %s \n",oss.str().c_str());
4670     result = conn->Query(oss.str().c_str());
4671     //
4672     if ( !result ) throw -4;
4673     //
4674     };
4675     //
4676     oss.str("");
4677     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) "
4678     << " VALUES (NULL,' "
4679     << idroot << "',";
4680     //
4681     if ( !pk1 ){
4682     oss << "NULL,";
4683     } else {
4684     oss << "'"
4685     << t1 << "',";
4686     };
4687     //
4688     if ( !pk2 ){
4689     oss << "NULL,'";
4690     } else {
4691     oss << "'"
4692     << t2 << "','";
4693     };
4694     //
4695     oss << fromtime << "','"
4696     << totime << "','"
4697     << obt1 << "','"
4698     << pkt1 << "','"
4699     << obt2 << "','"
4700     << pkt2 << "','"
4701     << boot_number << "','"
4702     << valid << "');";
4703     //
4704     if ( IsDebug() ) printf(" Insert the new trk calibration: query is \n %s \n",oss.str().c_str());
4705     //
4706     result = conn->Query(oss.str().c_str());
4707     //
4708     if ( !result ) throw -4;
4709     //
4710 mocchiut 1.1 };
4711 pam-fi 1.4
4712 mocchiut 1.1 oss.str("");
4713 pam-fi 1.4 oss << " SELECT ID FROM GL_TRK_CALIB ORDER BY ID DESC LIMIT 1 ;";
4714     if ( IsDebug() ) cout << oss.str().c_str() << endl;
4715 mocchiut 1.1 result = conn->Query(oss.str().c_str());
4716 pam-fi 1.4 if ( !result ) throw -4;;
4717     row = result->Next();
4718     if(row)glcal->ID = (UInt_t)atoll(row->GetField(0));
4719    
4720 mocchiut 1.1 //
4721     };
4722    
4723     /**
4724     * Scan tracker calibrations packets, fill the GL_TRK_CALIB table
4725     */
4726     Int_t PamelaDBOperations::insertTRK_CALIB(){
4727     //
4728 pam-fi 1.4 CalibTrk1Event *caltrk1 = 0;
4729     CalibTrk2Event *caltrk2 = 0;
4730     TTree *tr1 = 0;
4731     TTree *tr2 = 0;
4732     EventHeader *eh1 = 0;
4733     PscuHeader *ph1 = 0;
4734     EventHeader *eh2 = 0;
4735     PscuHeader *ph2 = 0;
4736     //
4737     PacketType *pctp=0;
4738     EventCounter *codt2=0;
4739     //
4740     Int_t nevents1 = 0;
4741     Int_t nevents2 = 0;
4742 mocchiut 1.1 //
4743 pam-fi 1.4 fromtime = 0;
4744 mocchiut 1.1 //
4745 pam-fi 1.4 obt1 = 0;
4746     pkt1 = 0;
4747     obt2 = 0;
4748     pkt2 = 0;
4749 mocchiut 1.1 //
4750 pam-fi 1.4 tr1 = (TTree*)file->Get("CalibTrk1");
4751     if ( !tr1 || tr1->IsZombie() ) throw -22;
4752     tr2 = (TTree*)file->Get("CalibTrk2");
4753     if ( !tr2 || tr2->IsZombie() ) throw -23;
4754     //
4755     tr1->SetBranchAddress("CalibTrk1", &caltrk1);
4756     tr1->SetBranchAddress("Header", &eh1);
4757     nevents1 = tr1->GetEntries();
4758     tr2->SetBranchAddress("CalibTrk2", &caltrk2);
4759     tr2->SetBranchAddress("Header", &eh2);
4760     nevents2 = tr2->GetEntries();
4761     //
4762     if ( !nevents1 && !nevents2 ) return(1);
4763     //
4764     t2 = -1;
4765     Int_t pret2 = 0;
4766     Int_t t2t1cal = 0;
4767     //
4768     bool MISSING_pkt1 = true;
4769     bool MISSING_pkt2 = true;
4770     int ncalib = 0;
4771     bool try_to_recover = false;
4772 mocchiut 1.1 //
4773 pam-fi 1.4 for (t1=0; t1 < nevents1; t1++){//loop over packet1
4774     //
4775     pret2 = t2;
4776     tr1->GetEntry(t1);
4777 mocchiut 1.1 //
4778 pam-fi 1.4 ph1 = eh1->GetPscuHeader();
4779     obt1 = ph1->GetOrbitalTime();
4780     pkt1 = ph1->GetCounter();
4781     fromtime = GetAbsTime(ph1->GetOrbitalTime());
4782 mocchiut 1.1 //
4783 pam-fi 1.4 // chek if the packet number and obt are consistent with the other packets ???
4784 mocchiut 1.1 //
4785 pam-fi 1.4 if ( PKT(pkt1) >= PKT(pktfirst) && PKT(pkt1) <= upperpkt && OBT(obt1) >= OBT(obtfirst) && OBT(obt1) <= upperobt ){
4786     // if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->OBT(obt1) >= this->OBT(obtfirst) ){
4787     //
4788     if ( IsDebug() ) printf("\n Trk calibration1 %u at time %u obt %u pkt %u \n",t1,fromtime,obt1,pkt1);
4789     //
4790     valid = ValidateTrkCalib( caltrk1, eh1 );
4791     if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;
4792     //
4793     // Do we have the second calibration packet?
4794     //
4795     if ( IsDebug() ) cout << " Loop over calibration2 to search associated calibration: "<<endl;
4796     while ( t2t1cal < t1+1 ){ // get the calibration packet2 that follows the packet1
4797     //
4798     t2++;
4799     //
4800     pret2 = t2 - 1; // EMILIANO
4801     //
4802     if ( t2 < nevents2 ){
4803     tr2->GetEntry(t2);
4804     codt2 = eh2->GetCounter();
4805     t2t1cal = codt2->Get(pctp->CalibTrk1);
4806     //
4807     ph2 = eh2->GetPscuHeader();
4808     obt2 = ph2->GetOrbitalTime();
4809     pkt2 = ph2->GetCounter();
4810     //
4811     if ( IsDebug() ) printf(" >> trk calibration2 at obt %u pkt %u t2 is %u , t2t1cal is %u \n",obt2,pkt2,t2,t2t1cal);
4812     // if ( caltrk2->unpackError != 0 || caltrk2->good0 == 0 ) valid = 0; // CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT2
4813     //
4814     } else {
4815     //
4816     // running out of vector without finding the corresponding calibration, sig
4817     //
4818     if ( IsDebug() ) printf(" t2 >= nevents2 \n");
4819     pret2 = t2;
4820     obt2 = 0;
4821     // pkt2 = pkt1+2;
4822     pkt2 = 0;
4823     t2t1cal = t1+1;
4824     };
4825     // if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) && (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){
4826    
4827     // EMILIANO
4828     // if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) || (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){
4829     // // if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){
4830     // if ( IsDebug() ) printf(" running out of vector without finding the corresponding calibration, sig \n");
4831     // //
4832     // // running out of vector without finding the corresponding calibration, sig
4833     // //
4834     // pret2 = t2;
4835     // obt2 = 0;
4836     // // pkt2 = pkt1+2;
4837     // pkt2 = 0;
4838     // t2t1cal = t1+1;
4839     // };
4840    
4841    
4842     //
4843     };
4844     //
4845     if ( IsDebug() ) printf(" Check if trk calibration2 is the right one \n");
4846     //
4847     // EMILIANO
4848     if ( ( PKT(pkt2) < PKT(pktfirst) || PKT(pkt2) > upperpkt) || (OBT(obt2) < OBT(obtfirst) || OBT(obt2) > upperobt) ){
4849     // if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){
4850     if ( IsDebug() ) printf(" *WARNING* The calibration found is outside the interval, sig \n");
4851     //
4852     // running out of vector without finding the corresponding calibration, sig
4853     //
4854     pret2 = t2;
4855     obt2 = 0;
4856     pkt2 = 0;
4857     };
4858     if ( PKT(pkt2) == PKT(pkt1)+1 ){
4859     if ( IsDebug() ) cout << " ...OK"<<endl;
4860     // =======================
4861     // The calibration is good
4862     // =======================
4863     //
4864     // if ( IsDebug() ) printf(" Found trk calibration2 at obt %u pkt %u t2 is %u \n",obt2,pkt2,t2);
4865     // if ( IsDebug() ) printf(" Trk calibration2 at obt %u pkt %u t2 is %u is good \n",obt2,pkt2,t2);
4866     // if ( IsDebug() ) printf("\n Trk calibration2 at time %u obt %u pkt %u \n",fromtime,obt2,pkt2);
4867     if ( IsDebug() ) printf(" Trk calibration2 %u at time %u obt %u pkt %u \n",t2,fromtime,obt2,pkt2);
4868     //
4869     UInt_t valid2 = ValidateTrkCalib( caltrk2, eh2 );
4870     if ( IsDebug() ) cout << " pkt2 validation --> "<<valid2<<endl;
4871     // valid = valid & valid2;
4872     valid = valid & valid2; //QUESTO VA CAMBIATO
4873     //
4874     // Handle good calib
4875     //
4876     MISSING_pkt1 = false;
4877     MISSING_pkt2 = false;
4878     // this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4879     //
4880     // Check for missing calibtrk1
4881     //
4882     if ( t2 != pret2+1 ){
4883     //
4884     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);
4885     //
4886     while ( t2 > pret2+1 ){
4887     //
4888     // handle missing calib1
4889     //
4890     pret2++;
4891     //
4892     obt1 = 0;
4893     pkt1 = 0;
4894     //
4895     tr2->GetEntry(pret2);
4896     ph2 = eh2->GetPscuHeader();
4897     obt2 = ph2->GetOrbitalTime();
4898     pkt2 = ph2->GetCounter();
4899     //
4900     fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
4901     //
4902     valid = 0;
4903     MISSING_pkt1 = true;
4904     MISSING_pkt2 = false;
4905     // this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4906     //
4907     };
4908     //
4909     };
4910     //
4911     } else if ( this->PKT(pkt2) > this->PKT(pkt1)+1 ){
4912     //
4913     // Check for missing calibtrk2
4914     //
4915     if ( IsDebug() ) printf(" Missing the trk calibration2! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);
4916     t2 = pret2;
4917     //
4918     // handle missing calib2
4919     //
4920     obt2 = 0;
4921     pkt2 = 0;
4922     valid = 0;
4923     MISSING_pkt1 = false;
4924     MISSING_pkt2 = true;
4925     // this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4926     //
4927     };
4928     //
4929 mocchiut 1.7
4930     if( !(MISSING_pkt1&MISSING_pkt2) ){
4931     this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4932     ncalib++;
4933     if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
4934     }
4935    
4936    
4937 mocchiut 1.1 } else {
4938 mocchiut 1.7 //
4939 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);
4940     // if ( PEDANTIC ) throw -79;
4941     //
4942 mocchiut 1.1 };
4943 pam-fi 1.4 //
4944    
4945     }; //end loop on pkt1
4946 mocchiut 1.1
4947    
4948    
4949 pam-fi 1.4 //
4950     // we have one more calib pkt2 !
4951     //
4952     t2++;
4953     while ( t2 < nevents2 ){
4954 mocchiut 1.1 //
4955 pam-fi 1.4 // handle missing calib1
4956 mocchiut 1.1 //
4957 pam-fi 1.4 if ( IsDebug() ) printf(" t2 is %u nevents2 is %u \n",t2,nevents2);
4958     obt1 = 0;
4959     pkt1 = 0;
4960 mocchiut 1.1 //
4961 pam-fi 1.4 tr2->GetEntry(t2);
4962     ph2 = eh2->GetPscuHeader();
4963     obt2 = ph2->GetOrbitalTime();
4964     pkt2 = ph2->GetCounter();
4965 mocchiut 1.1 //
4966 pam-fi 1.4 fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
4967     valid = 0;
4968     // if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->PKT(pkt1) <= upperpkt && this->OBT(obt1) >= this->OBT(obtfirst) && this->OBT(obt1) <= upperobt ){
4969     // EMILIANO
4970     if ( this->PKT(pkt2) >= this->PKT(pktfirst) && this->PKT(pkt2 <= upperpkt) && this->OBT(obt2) >= this->OBT(obtfirst) && this->OBT(obt2) <= upperobt ){
4971     // if ( this->PKT(pkt2) > this->PKT(pktfirst) || this->OBT(obt2) > this->OBT(obtfirst) ){
4972 mocchiut 1.1 //
4973 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);
4974 mocchiut 1.1 //
4975 pam-fi 1.4 MISSING_pkt1 = true;
4976     MISSING_pkt2 = false;
4977     this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4978     ncalib++;
4979     if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
4980 mocchiut 1.1 //
4981     };
4982     //
4983 pam-fi 1.4 t2++;
4984 mocchiut 1.1 //
4985 pam-fi 1.4 };
4986    
4987     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4988     // -----------------------------------------------------------------
4989     // in case of corruption, check if the calibration can be recovered
4990     // from another chewbacca file
4991     // -----------------------------------------------------------------
4992     // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
4993    
4994     // cout <<" TRY TO RECOVER ?? "<<try_to_recover<<endl;
4995    
4996     if(chewbacca&&try_to_recover){
4997    
4998    
4999     if ( IsDebug() ) cout << endl << ">>>> TRY TO RECOVER TRACKER CALIBRATIONS <<<<"<<endl;
5000    
5001     TSQLResult *result = 0;
5002     TSQLRow *row = 0;
5003 mocchiut 1.1 //
5004 pam-fi 1.4 stringstream oss;
5005     oss.str("");
5006 mocchiut 1.1 //
5007 pam-fi 1.4
5008     ////////////////////////////////////////////////////////////////////////
5009     // retrieve the name of the current file:
5010     ////////////////////////////////////////////////////////////////////////
5011     oss.str("");
5012     oss << "SELECT NAME FROM GL_ROOT where ID=" << GetID_ROOT() <<";";
5013     if ( IsDebug() ) cout << oss.str().c_str() << endl;
5014    
5015     result = conn->Query(oss.str().c_str());
5016     if ( !result ) throw -4;;
5017     row = result->Next();
5018     TString thisfilename = (TString)row->GetField(0);
5019     if ( IsDebug() ) cout << "Current file ==> "<<thisfilename<<endl;
5020    
5021     ////////////////////////////////////////////////////////////////////////
5022     // read all the calibrations inserted
5023     ////////////////////////////////////////////////////////////////////////
5024     oss.str("");
5025     oss << " SELECT ";
5026     oss << " ID,FROM_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,TO_TIME";
5027     oss << " FROM GL_TRK_CALIB ";
5028     oss << " ORDER BY ID DESC LIMIT "<<ncalib<<"; ";
5029     if ( IsDebug() ) cout << oss.str().c_str() << endl;
5030    
5031     result = conn->Query(oss.str().c_str());
5032     if ( !result ) throw -4;;
5033     if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5034    
5035     // -----------------------------------
5036     // loop over calibrations ...
5037     // -----------------------------------
5038     UInt_t nn=0;
5039     do {
5040     row = result->Next();
5041     if(!row)break;
5042    
5043     UInt_t id = (UInt_t)atoll(row->GetField(0));
5044     UInt_t fromtime = (UInt_t)atoll(row->GetField(1));
5045     UInt_t obt1 = (UInt_t)atoll(row->GetField(2));
5046     UInt_t pkt1 = (UInt_t)atoll(row->GetField(3));
5047     UInt_t obt2 = (UInt_t)atoll(row->GetField(4));
5048     UInt_t pkt2 = (UInt_t)atoll(row->GetField(5));
5049     UInt_t boot = (UInt_t)atoll(row->GetField(6));
5050     UInt_t valid = (UInt_t)atoll(row->GetField(7));
5051     bool MISSING_pkt1 = (row->GetFieldLength(8)==0);
5052     bool MISSING_pkt2 = (row->GetFieldLength(9)==0);
5053     UInt_t totime = (UInt_t)atoll(row->GetField(10));
5054    
5055     // -------------------------------------
5056     // ...check if the entry is corrupted...
5057     // -------------------------------------
5058     cout <<"*** "<< MISSING_pkt1 << MISSING_pkt2 << valid <<endl;
5059     bool CORRUPTED = (MISSING_pkt1||MISSING_pkt2||!valid);
5060    
5061     if ( IsDebug() ) cout << "("<<nn<<") ID = "<<id<<" from GL_TRK_CALIB ==> corrupted ? "<<CORRUPTED<<endl;
5062    
5063     // if( !CORRUPTED )continue; // nothing to do
5064    
5065     /////////////////////////////////////////////////////////
5066     // if it is corrupted, ...look for ather chewbacca files
5067     // containing the same calibrations ...
5068     /////////////////////////////////////////////////////////
5069    
5070     bool this_MISSING_pkt1 = false;
5071     bool this_MISSING_pkt2 = false;
5072     int this_t1=0;
5073     int this_t2=0;;
5074     UInt_t this_valid = 0;
5075    
5076     TString path = "";
5077     TString name = "";
5078     TString raw = "";
5079     UInt_t obt0 = 0;
5080     UInt_t timesync = 0;
5081     UInt_t boot_number = 0;
5082     bool FOUND = false;
5083    
5084     if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
5085    
5086     // for(int itable=0; itable<2; itable++){
5087     for(int itable=0; itable<1; itable++){
5088    
5089     // ------------------------------------------------------
5090     // loop over both ROOT_TABLE and ROOT_TABLE_BAD
5091     // ------------------------------------------------------
5092    
5093     TString table = "ROOT_TABLE";
5094     if(itable==1)table = "ROOT_TABLE_BAD";
5095    
5096     oss.str("");
5097     oss << " SELECT ";
5098     oss << " FOLDER_NAME,FILE_NAME,OBT_TIME_SYNC,LAST_TIME_SYNC_INFO,BOOT_NUMBER,INPUT_NAME ";
5099     oss << " FROM "<<table;
5100     oss << " WHERE 1 " << endl;
5101     oss << " AND FILE_NAME != \""<< thisfilename<<"\"";
5102     if( !MISSING_pkt1 ){
5103     oss << " AND ";
5104     oss << " PKT_NUMBER_INIT < "<<pkt1;
5105     oss << " AND ";
5106     oss << " PKT_NUMBER_FINAL > "<<pkt1;
5107     oss << " AND ";
5108     oss << " PKT_OBT_INIT < "<<obt1;
5109     oss << " AND ";
5110     oss << " PKT_OBT_FINAL > "<<obt1;
5111     }else{
5112     if(pkt2>1) pkt1 = pkt2-1;//serve dopo
5113     }
5114     if( !MISSING_pkt2 ){
5115     oss << " AND ";
5116     oss << " PKT_NUMBER_INIT < "<<pkt2;
5117     oss << " AND ";
5118     oss << " PKT_NUMBER_FINAL > "<<pkt2;
5119     oss << " AND ";
5120     oss << " PKT_OBT_INIT < "<<obt2;
5121     oss << " AND ";
5122     oss << " PKT_OBT_FINAL > "<<obt2;
5123     }else{
5124     if(pkt1>0) pkt2 = pkt1+1;//serve dopo
5125     }
5126     if( boot> 0 ){
5127     oss << " AND ";
5128     oss << " BOOT_NUMBER = "<<boot;
5129     }else{
5130     }
5131     oss << " ORDER BY BAD_PKT_CALREAD ASC; ";
5132    
5133     TSQLResult *result2 = 0;
5134     TSQLRow *row2 = 0;
5135    
5136     if ( IsDebug() ) cout << oss.str().c_str() << endl;
5137     result2 = conn->Query(oss.str().c_str());
5138     if ( !result2 ) throw -4;;
5139     if ( IsDebug() ) cout <<"Rows: "<<result2->GetRowCount()<<endl;
5140    
5141     // ------------------------------------------------------
5142     // loop over files containing repetition (if any)
5143     // ------------------------------------------------------
5144     do {
5145     row2 = result2->Next();
5146     if(!row2)break;
5147    
5148     // ------------------------------------------------------
5149     // ... a repetition is found ...
5150     // ------------------------------------------------------
5151     path = (TString)row2->GetField(0);
5152     name = (TString)row2->GetField(1);
5153     raw = (TString)row2->GetField(5);
5154     obt0 = (UInt_t)atoll(row2->GetField(2));
5155     timesync = (UInt_t)atoll(row2->GetField(3));
5156     boot_number = (UInt_t)atoll(row2->GetField(4));
5157    
5158     if ( IsDebug() ) cout << "- - - - - - - - - - -" <<endl;
5159     // cout << path <<endl;
5160 mocchiut 1.5 // cout << "File : " <<name <<endl;
5161 pam-fi 1.4 // cout << obt0 <<endl;
5162     // cout << timesync <<endl;
5163 mocchiut 1.5 // cout << "boot n. : "<<boot_number <<endl;
5164 pam-fi 1.4 // cout << raw <<endl;
5165    
5166     // ------------------------------------------------------
5167     // ... retrieve the calibration packets.
5168     // ------------------------------------------------------
5169 mocchiut 1.7 if ( IsDebug() ) printf(" file is %s/%s \n",((TString)gSystem->ExpandPathName(path.Data())).Data(),name.Data());
5170     TFile *file = new TFile(((TString)gSystem->ExpandPathName(path.Data()))+"/"+name); // EM, path could be symbolic and we must expand it
5171 pam-fi 1.4 if(!file)throw -100;
5172     if(file->IsZombie())throw -100;
5173     //
5174     tr1 = (TTree*)file->Get("CalibTrk1");
5175     if ( !tr1 || tr1->IsZombie() ) throw -22;
5176     tr2 = (TTree*)file->Get("CalibTrk2");
5177     if ( !tr2 || tr2->IsZombie() ) throw -23;
5178     //
5179     tr1->SetBranchAddress("CalibTrk1", &caltrk1);
5180     tr1->SetBranchAddress("Header", &eh1);
5181     nevents1 = tr1->GetEntries();
5182     tr2->SetBranchAddress("CalibTrk2", &caltrk2);
5183     tr2->SetBranchAddress("Header", &eh2);
5184     nevents2 = tr2->GetEntries();
5185     for(this_t1=0; this_t1<nevents1; this_t1++){
5186     tr1->GetEntry(this_t1);
5187     if(
5188     (UInt_t)eh1->GetPscuHeader()->GetCounter() == pkt1 &&
5189     true) break;
5190     this_MISSING_pkt1 = true;
5191     }
5192     for(this_t2=0; this_t2<nevents2; this_t2++){
5193     tr2->GetEntry(this_t2);
5194     if(
5195     (UInt_t)eh2->GetPscuHeader()->GetCounter() == pkt2 &&
5196     true) break;
5197     this_MISSING_pkt2 = true;
5198     }
5199     this_valid =
5200     ValidateTrkCalib( caltrk1, eh1, file )
5201     *
5202     ValidateTrkCalib( caltrk2, eh2, file );
5203    
5204     // ---------------------------------------------------------------------
5205     // accept the calibration if it is better than the previous:
5206     //
5207     // - if the new calibration is perfect (both valid packets)
5208     // - if the new calibration has both the packets and the previous does not
5209     // ---------------------------------------------------------------------
5210     if(
5211     ( !this_MISSING_pkt1&&!this_MISSING_pkt2&&this_valid )||
5212     ( (MISSING_pkt1||MISSING_pkt2) && (!this_MISSING_pkt1&&!this_MISSING_pkt2) )||
5213     false)FOUND=true;
5214    
5215     if(file)file->Close();
5216    
5217     if(FOUND)break;
5218    
5219     }while(1);//endl loop over root table entries
5220    
5221     if(FOUND)break;
5222    
5223     }//end loop over tables
5224    
5225     if(FOUND){
5226    
5227     if ( IsDebug() ) cout << " >>> REPETITION FOUND :-) <<<" <<endl;
5228    
5229     ////////////////////////////////////////////
5230     // insert a new entry in GL_TRK_CALIB and
5231     // modify the time-tag of the previous one
5232     ////////////////////////////////////////////
5233    
5234     // ---------------------------------------------------------------------
5235     // step 1: insert a new raw file in GL_RAW
5236     // ---------------------------------------------------------------------
5237     //
5238     // check if the raw file already exist
5239     //
5240 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
5241     // oss.str("");
5242     // oss << "SELECT ID FROM GL_RAW where NAME=\"" << gSystem->BaseName(raw.Data()) <<"\";";
5243     // if ( IsDebug() ) cout << oss.str().c_str() << endl;
5244 pam-fi 1.4
5245 mocchiut 1.5 // result = conn->Query(oss.str().c_str());
5246     // if ( !result ) throw -4;;
5247     // if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5248     // if( result->GetRowCount() == 0){
5249     // if ( IsDebug() ) cout << " << Insert new RAW file >> "<<endl;
5250     // // - - - - - - - - - - -
5251     // // insert new raw file
5252     // // - - - - - - - - - - -
5253     // GL_RAW glraw = GL_RAW();
5254     // glraw.PATH = gSystem->DirName(raw.Data());
5255     // glraw.NAME = gSystem->BaseName(raw.Data());
5256     // glraw.BOOT_NUMBER = boot_number;
5257     // //
5258     // insertPamelaRawFile( &glraw );
5259     // //
5260     // id_raw = glraw.ID;
5261     // }else{
5262     // row = result->Next();
5263     // id_raw = (UInt_t)atoll(row->GetField(0));
5264     // }
5265     // if ( IsDebug() ) cout << "ID_RAW = "<<id_raw<<endl;
5266 pam-fi 1.4
5267     // ---------------------------------------------------------------------
5268     // step 1(bis): retrieve the timesync id associated to the file
5269     // (NB, uso lo stesso associato al file iniziale)
5270     // ---------------------------------------------------------------------
5271     UInt_t idtimesync = 0;
5272     oss.str("");
5273     oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" limit 1;";
5274     if ( debug ) printf(" %s \n",oss.str().c_str());
5275     result = conn->Query(oss.str().c_str());
5276     if ( !result ) throw -3;
5277     row = result->Next();
5278     if ( !row ) throw -3;
5279     idtimesync = (UInt_t)atoll(row->GetField(0));
5280     if ( IsDebug() ) cout << "ID_TIMESYNC = "<<idtimesync<<endl;
5281    
5282     // ---------------------------------------------------------------------
5283     // step 2: insert a new root file in GL_ROOT
5284     // ---------------------------------------------------------------------
5285     //
5286 mocchiut 1.5 // check if the root file already exist
5287 pam-fi 1.4 //
5288     UInt_t id_root = 0;
5289     oss.str("");
5290     oss << "SELECT ID FROM GL_ROOT where NAME=\"" << gSystem->BaseName(name.Data()) <<"\";";
5291     if ( IsDebug() ) cout << oss.str().c_str() << endl;
5292    
5293     result = conn->Query(oss.str().c_str());
5294     if ( !result ) throw -4;;
5295     if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5296     if( result->GetRowCount() == 0){
5297     if ( IsDebug() ) cout << " << Insert new ROOT file >> "<<endl;
5298     // - - - - - - - - - - -
5299     // insert new root file
5300     // - - - - - - - - - - -
5301     GL_ROOT glroot = GL_ROOT();
5302     glroot.ID_RAW = id_raw;
5303     glroot.ID_TIMESYNC = idtimesync;
5304 mocchiut 1.5 //
5305     // 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,
5306     // NOT STATIC NOT KEEPENV = $PAM_L0 must be used in the DB
5307     //
5308     if ( STATIC ){
5309     glroot.PATH = (TString)gSystem->ExpandPathName(path);
5310     } else {
5311     if ( KEEPENV ){
5312     glroot.PATH = path;
5313     } else {
5314     glroot.PATH = "$PAM_L0";
5315     };
5316     };
5317     // glroot.PATH = path;
5318 pam-fi 1.4 glroot.NAME = name;
5319     //
5320     insertPamelaRootFile( &glroot );
5321     //
5322     id_root = glroot.ID;
5323     }else{
5324     row = result->Next();
5325     if(row)id_root = (UInt_t)atoll(row->GetField(0));
5326     }
5327     if ( IsDebug() ) cout << "ID_ROOT = "<<id_root<<endl;
5328    
5329     // ---------------------------------------------------------------------
5330     // step 3: modify time-tag of corrupted GL_TRK_CALIB entry
5331     // ---------------------------------------------------------------------
5332     if ( IsDebug() ) cout << " << Modify time-tag of calibration ID="<<id<<" >> "<<endl;
5333     oss.str("");
5334     oss << " UPDATE GL_TRK_CALIB SET "
5335     << " TO_TIME=0 , FROM_TIME=0 WHERE "
5336     << " ID = "<< id << ";";
5337     if ( IsDebug() ) cout << oss.str().c_str() << endl;
5338     result = conn->Query(oss.str().c_str());
5339     if ( !result ) throw -4;;
5340    
5341     // ---------------------------------------------------------------------
5342     // step 4: insert the new calibration:
5343     // ---------------------------------------------------------------------
5344     if ( IsDebug() ) cout << " << Insert new TRK calibration >> "<<endl;
5345     //
5346     GL_TRK_CALIB glcal = GL_TRK_CALIB();
5347     //
5348     glcal.ID_ROOT_L0 = id_root;
5349     glcal.EV_ROOT_CALIBTRK1 = this_t1;
5350     glcal.EV_ROOT_CALIBTRK2 = this_t2;
5351     glcal.FROM_TIME = fromtime;
5352     glcal.TO_TIME = totime;
5353     glcal.OBT1 = obt1;
5354     glcal.OBT2 = obt2;
5355     glcal.PKT1 = pkt1;
5356     glcal.PKT2 = pkt1;
5357     glcal.BOOT_NUMBER = GetBOOTnumber();
5358     glcal.VALIDATION = this_valid;
5359     //
5360     HandleTRK_CALIB(&glcal);
5361     if ( IsDebug() ) cout << "ID = "<<glcal.ID<<endl;
5362     //
5363    
5364     }
5365     if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
5366    
5367     }while(1);//end loop over calibrations
5368    
5369    
5370     if( result )delete result;
5371     if( row )delete row;
5372    
5373    
5374    
5375    
5376    
5377    
5378     }
5379    
5380    
5381     // // ------------------------------
5382     // // try to recover the calibration
5383     // // ------------------------------
5384     // cout << "TRY TO RECOVER TRACKER CALIBRATION"<<endl;
5385     // //
5386     // ULong64_t time = 0; //absolute time
5387     // string path[100]; //mettere un limite massimo
5388     // int nrows = 0;
5389     // UInt_t pkt = 0;
5390     // UInt_t obt = 0;
5391     // char *type = "";
5392     // EventHeader *eh = new EventHeader();
5393     // CalibTrk1Event *c = new CalibTrk1Event();
5394    
5395     // //
5396     // if(which_is_not_valid==1 || which_is_not_valid==3){
5397     // //
5398     // cout << "PKT1 --> missing or corrupted "<<endl;
5399     // type = "CalibTrk1";
5400     // pkt = pkt1;
5401     // obt = obt1;
5402     // time = this->GetAbsTime(obt1);
5403     // if( pkt1 == 0 ){//missing
5404     // time = this->GetAbsTime(obt2);
5405     // pkt = pkt2-1;
5406     // }
5407     // //
5408     // }else if (which_is_not_valid==2 || which_is_not_valid==3){
5409     // //
5410     // cout << "PKT2--> missing or corrupted "<<endl;
5411     // type = "CalibTrk2 ";
5412     // pkt = pkt2;
5413     // obt = obt2;
5414     // time = this->GetAbsTime(obt2);
5415     // if( pkt2 == 0 ){//missing
5416     // time = this->GetAbsTime(obt1);
5417     // pkt = pkt1+1;
5418     // }
5419     // //
5420     // }else{
5421     // cout << "this should not happen!!! "<<endl;
5422     // trow -666;
5423     // }
5424    
5425     // nrows = Query_ROOT_TABLE(time,conn,path);// get the list of file which might contain the packet
5426    
5427    
5428     // for(int r=0; r<nrows; r++){ //loop over rows
5429     // if(path)cout << r << " >>>> "<<(path+r)->c_str() << endl;
5430     // /// verifica che il file non sia quello gia` aperto
5431     // }
5432    
5433     // ////////////////////////////////////////////////////////////////////////
5434    
5435     // TSQLResult *result = 0;
5436     // TSQLRow *row = 0;
5437     // //
5438     // stringstream oss;
5439     // oss.str("");
5440     // // ----------------------------------------
5441     // // read the id of last calibration inserted
5442     // // ----------------------------------------
5443     // oss.str("");
5444     // oss << " SELECT ";
5445     // oss << " (ID,ID_ROOT_L0,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,FROM_TIME,TO_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION) ";
5446     // oss << " ORDER BY ID DESC LIMIT 1; ";
5447    
5448     // result = conn->Query(oss.str().c_str());
5449     // row = result->Next();
5450     // if( !row )throw -666;
5451    
5452     // if( result )delete result;
5453     // if( row )delete row;
5454    
5455     // UInt_t id = (UInt_t)atoll(row->GetField(0));
5456    
5457     // // -------------------------------------
5458     // // ...and modify it with new parameters
5459     // // -------------------------------------
5460    
5461    
5462     // }
5463 mocchiut 1.1 //
5464     return(0);
5465     };
5466    
5467    
5468     /**
5469     * Scan S4 calibrations packets, fill the GL_S4_CALIB table
5470     */
5471     Int_t PamelaDBOperations::insertS4_CALIB(){
5472     //
5473     TSQLResult *result = 0;
5474     TSQLRow *row = 0;
5475     //
5476     stringstream oss;
5477     oss.str("");
5478     //
5479     TTree *tr = 0;
5480     EventHeader *eh = 0;
5481     PscuHeader *ph = 0;
5482     //
5483     UInt_t nevents = 0;
5484     UInt_t fromtime = 0;
5485     UInt_t totime = 0;
5486     UInt_t obt = 0;
5487     UInt_t pkt = 0;
5488     //
5489     tr = (TTree*)file->Get("CalibS4");
5490     if ( !tr || tr->IsZombie() ) throw -24;
5491     //
5492     tr->SetBranchAddress("Header", &eh);
5493     //
5494     nevents = tr->GetEntries();
5495     //
5496     if ( !nevents ) return(1);
5497     //
5498     for (UInt_t i = 0; i < nevents; i++){
5499     //
5500     tr->GetEntry(i);
5501     //
5502     ph = eh->GetPscuHeader();
5503     obt = ph->GetOrbitalTime();
5504     pkt = ph->GetCounter();
5505     fromtime = this->GetAbsTime(ph->GetOrbitalTime());
5506     if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->PKT(pkt) <= upperpkt && this->OBT(obt) >= this->OBT(obtfirst) && this->OBT(obt) <= upperobt ){
5507     // if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->OBT(obt) >= this->OBT(obtfirst) ){
5508     //
5509     if ( IsDebug() ) printf(" S4 calibration at time %u obt %u pkt %u \n",fromtime,obt,pkt);
5510     //
5511     // check if the calibration has already been inserted
5512     //
5513     oss.str("");
5514     oss << " SELECT ID FROM GL_S4_CALIB WHERE "
5515     << " BOOT_NUMBER = "<< this->GetBOOTnumber() << " AND "
5516     << " OBT = "<< obt << " AND "
5517     << " PKT = "<< pkt << ";";
5518     //
5519     if ( IsDebug() ) printf(" Check if the S4 calibration has already been inserted: query is \n %s \n",oss.str().c_str());
5520     result = conn->Query(oss.str().c_str());
5521     //
5522     if ( !result ) throw -4;
5523     //
5524     row = result->Next();
5525     //
5526     if ( row ){
5527     //
5528     if ( IsDebug() ) printf(" S4 calibration already inserted in the DB\n");
5529     if ( PEDANTIC ) throw -81;
5530     //
5531     } else {
5532     //
5533     // we have to insert a new calibration, check where to place it
5534     //
5535     oss.str("");
5536     oss << " SELECT ID,TO_TIME FROM GL_S4_CALIB WHERE "
5537     << " FROM_TIME < "<< fromtime << " AND "
5538     << " TO_TIME > "<< fromtime << ";";
5539     //
5540     if ( IsDebug() ) printf(" Check where to place the S4 calibration: query is \n %s \n",oss.str().c_str());
5541     result = conn->Query(oss.str().c_str());
5542     //
5543     if ( !result ) throw -4;
5544     //
5545     row = result->Next();
5546     //
5547     if ( !row ){
5548     //
5549     // no calibrations in the db contain our calibration
5550     //
5551     if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB \n");
5552     if ( fromtime < 1150871000 ){
5553     if ( IsDebug() ) printf(" First PAMELA flight calibration at time %u \n",fromtime);
5554     fromtime = 0;// the first flight calibration was taken at about 1156429100 s, this line allow to analyze first runs in raw mode
5555     };
5556     //
5557     oss.str("");
5558     oss << " SELECT FROM_TIME FROM GL_S4_CALIB WHERE "
5559     << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
5560     //
5561     if ( IsDebug() ) printf(" Check the upper limit for calibration: query is \n %s \n",oss.str().c_str());
5562     result = conn->Query(oss.str().c_str());
5563     //
5564     if ( !result ) throw -4;
5565     //
5566     row = result->Next();
5567     if ( !row ){
5568     totime = numeric_limits<UInt_t>::max();
5569     } else {
5570     totime = (UInt_t)atoll(row->GetField(0));
5571     };
5572     //
5573     } else {
5574     //
5575     // determine upper and lower limits and make space for the new calibration
5576     //
5577     totime = (UInt_t)atoll(row->GetField(1));
5578     //
5579     oss.str("");
5580     oss << " UPDATE GL_S4_CALIB SET "
5581     << " TO_TIME = "<< fromtime << " WHERE " // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
5582     << " ID = "<< row->GetField(0) << ";";
5583     //
5584     if ( IsDebug() ) printf(" Make space for the new calibration: query is \n %s \n",oss.str().c_str());
5585     result = conn->Query(oss.str().c_str());
5586     //
5587     if ( !result ) throw -4;
5588     //
5589     };
5590     //
5591     oss.str("");
5592     oss << " INSERT INTO GL_S4_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,OBT,PKT,BOOT_NUMBER) "
5593     << " VALUES (NULL,' "
5594     << idroot << "','"
5595     << i << "','"
5596     << fromtime << "','"
5597     << totime << "','"
5598     << obt << "','"
5599     << pkt << "','"
5600     << this->GetBOOTnumber() << "');";
5601     //
5602     if ( IsDebug() ) printf(" Insert the new calibration: query is \n %s \n",oss.str().c_str());
5603     //
5604     result = conn->Query(oss.str().c_str());
5605     //
5606     if ( !result ) throw -4;
5607     //
5608     };
5609     //
5610     } else {
5611     //
5612     if ( IsDebug() ) printf(" S4 calibration at time %u obt %u pkt %u OUTSIDE the considered time interval\n",fromtime,obt,pkt);
5613     // if ( PEDANTIC ) throw -82;
5614     //
5615     };
5616     //
5617     };
5618     //
5619     return(0);
5620     };
5621    
5622     /**
5623     * Scan the fragment table and move old fragments to the GL_RUN table
5624     */
5625     Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(){
5626     return(this->CleanGL_RUN_FRAGMENTS(""));
5627     };
5628    
5629     /**
5630     * Scan the fragment table and move old fragments to the GL_RUN table
5631     */
5632     Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(Bool_t runpieces){
5633     return(this->CleanGL_RUN_FRAGMENTS("",runpieces));
5634     };
5635    
5636     /**
5637     * Scan the fragment table and move old fragments to the GL_RUN table
5638     */
5639     Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(TString fcleanfile){
5640     return(this->CleanGL_RUN_FRAGMENTS("",false));
5641     };
5642    
5643     /**
5644     * Scan the fragment table and move old fragments to the GL_RUN table
5645     */
5646     Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(TString fcleanfile, Bool_t runpieces){
5647     //
5648     TSQLResult *nresult = 0;
5649     TSQLRow *nrow = 0;
5650     TSQLResult *nresult1 = 0;
5651     TSQLRow *nrow1 = 0;
5652     TSQLResult *result = 0;
5653     TSQLRow *row = 0;
5654     TSQLResult *result2 = 0;
5655     TSQLRow *row2 = 0;
5656     //
5657     UInt_t moved = 0;
5658     //
5659     stringstream oss;
5660     oss.str("");
5661     //
5662     // 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)
5663     //
5664     if ( runpieces ){
5665     //
5666     UInt_t nid = 0;
5667     UInt_t myid[500];
5668     memset(myid,0,500*sizeof(UInt_t));
5669     //
5670     oss.str("");
5671     oss << "SELECT ID,RUNTRAILER_TIME,RUNTRAILER_PKT,BOOT_NUMBER FROM GL_RUN_FRAGMENTS WHERE INSERT_TIME <= '" << clean_time->AsSQLString() << "'order BY RUNHEADER_TIME asc;";
5672     if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS runs older than %s : query is \n %s \n",clean_time->AsSQLString(),oss.str().c_str());
5673     nresult = conn->Query(oss.str().c_str());
5674     //
5675     if ( nresult ){
5676     //
5677     nrow = nresult->Next();
5678     //
5679     while ( nrow ){
5680     //
5681     UInt_t mbo = (UInt_t)atoll(nrow->GetField(3));
5682     UInt_t mrhp = (UInt_t)atoll(nrow->GetField(2));
5683     UInt_t mrht = (UInt_t)atoll(nrow->GetField(1));
5684     Bool_t anr = true;
5685     Bool_t runisthere = true;
5686     //
5687     for (UInt_t u=0; u<=nid; u++){
5688     if ( (UInt_t)atoll(nrow->GetField(0)) == myid[u] && (UInt_t)atoll(nrow->GetField(0)) != 0 ) runisthere = false;
5689     };
5690     //
5691     // check if the run is still in the fragment table or if we have just move it in the gl_run table!
5692     //
5693     if ( runisthere ){
5694     //
5695     memset(myid,0,500*sizeof(UInt_t));
5696     nid = 0;
5697     myid[nid] = (UInt_t)atoll(nrow->GetField(0));
5698     //
5699     while ( anr ){
5700     //
5701     oss.str("");
5702     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;";
5703     if ( IsDebug() ) printf(" In the loop searching for fragmented runs : query is \n %s \n",oss.str().c_str());
5704     //
5705     nresult1 = conn->Query(oss.str().c_str());
5706     //
5707     if ( nresult1 ){
5708     //
5709     if ( nresult1->GetRowCount() == 1 ){
5710     //
5711     // one piece is found
5712     //
5713     nrow1 = nresult1->Next();
5714     //
5715     if ( nrow1 ){
5716     //
5717     nid++;
5718     myid[nid] = (UInt_t)atoll(nrow1->GetField(0));
5719     mbo = (UInt_t)atoll(nrow1->GetField(3));
5720     mrhp = (UInt_t)atoll(nrow1->GetField(2));
5721     mrht = (UInt_t)atoll(nrow1->GetField(1));
5722     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);
5723     //
5724     nrow1->Close();
5725     } else {
5726     throw -88;
5727     };
5728     } else {
5729     anr = false;
5730     };
5731     nresult1->Close();
5732     } else {
5733     throw -88;
5734     };
5735     };
5736     //
5737     // handle these runs which are ordered and "good". Does the first contain a valid runheader?
5738     //
5739     oss.str("");
5740     oss << " ID= "<< myid[0];
5741     //
5742     glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);
5743     //
5744     if ( glrun->GetACQ_BUILD_INFO() != 0 ){
5745     //
5746     // the first piece contains a good runheader we can update all the other runs with correct infos!
5747     //
5748     for (UInt_t u=1; u <= nid ; u++){
5749     oss.str("");
5750     oss << "UPDATE GL_RUN_FRAGMENTS SET "
5751     << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , "
5752     << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "
5753     << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT()<< " , "
5754     << " COMPILATIONTIMESTAMP=" << glrun->GetCOMPILATIONTIMESTAMP()<< " , "
5755     << " FAV_WRK_SCHEDULE=" << glrun->GetFAV_WRK_SCHEDULE()<< " , "
5756     << " EFF_WRK_SCHEDULE=" << glrun->GetEFF_WRK_SCHEDULE()<< " , "
5757     << " PRH_VAR_TRG_MODE_A=" << glrun->GetPRH_VAR_TRG_MODE_A()<< " , "
5758     << " PRH_VAR_TRG_MODE_B=" << glrun->GetPRH_VAR_TRG_MODE_B()<< " , "
5759     << " ACQ_BUILD_INFO=" << glrun->GetACQ_BUILD_INFO()<< " , "
5760     << " ACQ_VAR_INFO=" << glrun->GetACQ_VAR_INFO()<< " , "
5761     << " RM_ACQ_AFTER_CALIB=" << glrun->GetRM_ACQ_AFTER_CALIB()<< " , "
5762     << " RM_ACQ_SETTING_MODE=" << glrun->GetRM_ACQ_SETTING_MODE()<< " , "
5763     << " TRK_CALIB_USED=" << glrun->GetTRK_CALIB_USED()<< " , "
5764     << " CAL_DSP_MASK=" << glrun->GetCAL_DSP_MASK()<< " , "
5765 mocchiut 1.2 << " LAST_TIMESYNC=" << glrun->GetLAST_TIMESYNC()<< " , ";
5766     //
5767     if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
5768     oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12() << " , ";
5769     if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
5770     oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC() << " , ";
5771     //
5772     oss << " OBT_TIMESYNC=" << glrun->GetOBT_TIMESYNC();
5773     oss << " WHERE ID=" << myid[u] << ";";
5774 mocchiut 1.1 conn->Query(oss.str().c_str());
5775     };
5776     //
5777     } else {
5778     //
5779     // sig no runheader, let set anyway what is possible...
5780     //
5781     for (UInt_t u=1; u <= nid ; u++){
5782     oss.str("");
5783     oss << "UPDATE GL_RUN_FRAGMENTS SET "
5784 mocchiut 1.2 << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , ";
5785     //
5786     if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
5787     oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , ";
5788     if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
5789     oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , ";
5790     //
5791     oss << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "
5792 mocchiut 1.1 << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT()<< ";";
5793     conn->Query(oss.str().c_str());
5794     };
5795     };
5796     //
5797     // now let's look for runtrailer if any in the last run
5798     //
5799     oss.str("");
5800     oss << " ID= "<< myid[nid];
5801     //
5802     glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);
5803     //
5804     if ( glrun->GetPKT_READY_COUNTER() != 0 ){
5805     //
5806     // the first piece contains a good runtrailer we can update all the other runs with correct infos!
5807     //
5808     for (UInt_t u=0; u < nid ; u++){
5809     oss.str("");
5810     oss << "UPDATE GL_RUN_FRAGMENTS SET "
5811     << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
5812     << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "
5813     << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< " , "
5814 mocchiut 1.2 << " PKT_COUNTER=" << glrun->GetPKT_COUNTER()<< " , ";
5815     //
5816     if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
5817     oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
5818     if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) {
5819     oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
5820     //
5821     oss << " PKT_READY_COUNTER=" << glrun->GetPKT_READY_COUNTER()
5822 mocchiut 1.1 << " WHERE ID=" << myid[u] << ";";
5823     conn->Query(oss.str().c_str());
5824     };
5825     //
5826     } else {
5827     //
5828     // sig no runtrailer, let set anyway what is possible...
5829     //
5830     for (UInt_t u=0; u < nid ; u++){
5831     oss.str("");
5832     oss << "UPDATE GL_RUN_FRAGMENTS SET "
5833     << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
5834 mocchiut 1.2 << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , ";
5835     //
5836     if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
5837     oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
5838     if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ){
5839     oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
5840     //
5841     oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< ";";
5842 mocchiut 1.1 conn->Query(oss.str().c_str());
5843     };
5844     };
5845     //
5846     // Now we want to cross indexize the runs
5847     //
5848     for (UInt_t u=0; u < nid ; u++){
5849     oss.str("");
5850     oss << "UPDATE GL_RUN_FRAGMENTS SET "
5851     << " ID_RUN_FRAG=" << myid[u+1] << " where ID=" << myid[u] <<";";
5852     conn->Query(oss.str().c_str());
5853     };
5854     oss.str("");
5855     oss << "UPDATE GL_RUN_FRAGMENTS SET "
5856     << " ID_RUN_FRAG=" << myid[0] << " where ID=" << myid[nid] <<";";
5857     conn->Query(oss.str().c_str());
5858     //
5859     // and now we can move the runs in the GL_RUN table
5860     //
5861     for (UInt_t u=0; u <= nid; u++){
5862     oss.str("");
5863     oss << " ID= "<< myid[u];
5864     //
5865     glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);
5866     //
5867     if ( u == 0 ){
5868     oss.str("");
5869     oss << " SELECT ID,NEVENTS,TRK_CALIB_USED,PKT_COUNTER FROM GL_RUN WHERE "
5870     << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND ("
5871     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
5872     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
5873     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
5874     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
5875     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
5876     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
5877     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
5878     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
5879     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
5880     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
5881     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
5882     << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
5883     //
5884     if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
5885     result2 = conn->Query(oss.str().c_str());
5886     //
5887     if ( !result2 ) throw -4;
5888     //
5889     row2 = result2->Next();
5890     //
5891     if ( row2 ){
5892     if ( IsDebug() ) printf(" The already exist in the GL_RUN table! \n");
5893     if ( PEDANTIC ) throw -83;
5894     row2->Close();
5895     };
5896     result2->Close();
5897     };
5898     //
5899     if ( IsDebug() ) printf(" The run is new \n");
5900     if ( IsDebug() ) printf(" -> fill the DB \n");
5901     //
5902     glrun->Fill_GL_RUN(conn);
5903     //
5904     if ( IsDebug() ) printf(" Delete run %u from the GL_RUN_FRAGMENTS table \n",myid[u]);
5905     //
5906     glrun->DeleteRun(conn,myid[u],"GL_RUN_FRAGMENTS");
5907     //
5908     moved++;
5909     //
5910     };
5911     //
5912     };
5913     //
5914     nrow = nresult->Next();
5915     };
5916     };
5917    
5918    
5919    
5920     };
5921     //
5922     if ( !strcmp(fcleanfile.Data(),"") ){
5923     //
5924     // check if there are entries older than "olderthan" seconds from now
5925     //
5926     oss.str("");
5927     oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
5928     << " INSERT_TIME <= '" << clean_time->AsSQLString() << "';";
5929     //
5930     if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS runs older than %s : query is \n %s \n",clean_time->AsSQLString(),oss.str().c_str());
5931     result = conn->Query(oss.str().c_str());
5932     //
5933     } else {
5934     oss.str("");
5935     oss << " SELECT ID FROM GL_ROOT WHERE NAME='" << fcleanfile.Data() << "';";
5936     if ( IsDebug() ) printf(" Getting ID_ROOT_L0 query %s \n",oss.str().c_str());
5937     result = conn->Query(oss.str().c_str());
5938     //
5939     if ( result ){
5940     //
5941     row = result->Next();
5942     //
5943     if ( row ){
5944     oss.str("");
5945     oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
5946     << " ID_ROOT_L0=" << row->GetField(0) << ";";
5947     //
5948     if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS for ROOT file query is \n %s \n",oss.str().c_str());
5949     result = conn->Query(oss.str().c_str());
5950     //
5951     };
5952     } else {
5953     return(2);
5954     };
5955     };
5956     //
5957     if ( result ){
5958     //
5959     row = result->Next();
5960     //
5961     while ( row ){
5962     //
5963     oss.str("");
5964     oss << " ID= "<< row->GetField(0);
5965     //
5966     glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);
5967     //
5968     oss.str("");
5969     oss << " SELECT ID,NEVENTS,TRK_CALIB_USED,PKT_COUNTER FROM GL_RUN WHERE "
5970     << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND ("
5971     << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
5972     << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
5973     << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
5974     << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
5975     << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
5976     << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
5977     << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
5978     << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
5979     << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
5980     << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
5981     << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
5982     << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
5983     //
5984     if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
5985     result2 = conn->Query(oss.str().c_str());
5986     //
5987     if ( !result2 ) throw -4;
5988     //
5989     row2 = result2->Next();
5990     //
5991     if ( !row2 ){
5992     //
5993     if ( IsDebug() ) printf(" The run is new \n");
5994     if ( IsDebug() ) printf(" -> fill the DB \n");
5995     //
5996     // glrun->SetID(this->AssignRunID()); we use the old run number!
5997     glrun->SetID_RUN_FRAG(glrun->GetID());
5998     glrun->Fill_GL_RUN(conn);
5999     //
6000 mocchiut 1.2 // oss.str("");
6001     // oss << " SELECT ID FROM GL_RUN WHERE "
6002     // << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
6003     // << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
6004     // << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
6005     // << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
6006     // << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
6007     // //
6008     // if ( IsDebug() ) printf(" Look for the ID of the inserted run: query is \n %s \n",oss.str().c_str());
6009     // result2 = conn->Query(oss.str().c_str());
6010     // //
6011     // if ( !result2 ) throw -4;
6012     // //
6013     // row2 = result2->Next();
6014     // //
6015     // if ( !row2 ) throw -25;
6016     // //
6017     // oss.str("");
6018     // oss << " UPDATE GL_RUN SET ID_RUN_FRAG = " << row2->GetField(0) << " WHERE ID = " << row2->GetField(0);
6019     // if ( IsDebug() ) printf(" Update the ID_RUN_FRAG of the inserted run: query is \n %s \n",oss.str().c_str());
6020     // result2 = conn->Query(oss.str().c_str());
6021     // //
6022     // if ( !result2 ) throw -4;
6023 mocchiut 1.1 //
6024     moved++;
6025     //
6026     } else {
6027     if ( IsDebug() ) printf(" The already exist in the GL_RUN table! \n");
6028     if ( PEDANTIC ) throw -83;
6029     };
6030     if ( IsDebug() ) printf(" Delete run %s from the GL_RUN_FRAGMENTS table \n",row->GetField(0));
6031     //
6032     //
6033     glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
6034 mocchiut 1.2 // oss.str("");
6035     // oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);
6036     // if ( IsDebug() ) printf(" Clean the GL_RUN_FRAGMENTS table: query is \n %s \n",oss.str().c_str());
6037     // result2 = conn->Query(oss.str().c_str());
6038     // //
6039     // if ( !result2 ) throw -4;
6040     // //
6041 mocchiut 1.1 row = result->Next();
6042     };
6043     };
6044     if ( IsDebug() ) printf(" Moved %u runs\n",moved);
6045     return(0);
6046     };
6047    
6048     /**
6049     * Check if runs are good, i.e. if the tracker calibration is correctly associated..
6050     */
6051     Int_t PamelaDBOperations::ValidateRuns(){
6052     return(this->ValidateRuns(""));
6053     };
6054    
6055     /**
6056     * Check if runs are good, i.e. if the tracker calibration is correctly associated..
6057     */
6058     Int_t PamelaDBOperations::ValidateRuns(TString valfile){
6059     //
6060     TSQLResult *result = 0;
6061     TSQLRow *row = 0;
6062     //
6063     UInt_t calibtime = 50;
6064     //
6065     stringstream oss;
6066     oss.str("");
6067     //
6068     // =======================================================
6069     // validate runs by checking missing calibrations
6070     // =======================================================
6071     UInt_t t_stop = 0;
6072     UInt_t t_start = 0;
6073     if ( !strcmp(valfile.Data(),"") ) {
6074     // --------------------------------------------------------------
6075     // 1) get the OBT of the last run inserted after clean-time limit
6076     // --------------------------------------------------------------
6077     oss.str("");
6078     oss << " SELECT * FROM GL_RUN WHERE INSERT_TIME <= '" << clean_time->AsSQLString()
6079     << "' ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
6080     if ( IsDebug() ) printf(" Get start validation-time: query is \n %s \n",oss.str().c_str());
6081     result = conn->Query(oss.str().c_str());
6082     if ( !result ) throw -4;
6083     if ( !result->GetRowCount() ) {
6084     printf(" No runs to validate \n");
6085     return(1);
6086     }else{
6087     row = result->Next();
6088     t_start = (UInt_t)atoll(row->GetField(4));
6089     };
6090     // --------------------------------------------------------------
6091     // 2) get the OBT of the last validated run
6092     // --------------------------------------------------------------
6093     oss.str("");
6094 mocchiut 1.12 // oss << " SELECT * FROM GL_RUN WHERE VALIDATION=1 AND RUNHEADER_TIME<="<< t_start
6095     oss << " SELECT * FROM GL_RUN WHERE VALIDATION>0 AND RUNHEADER_TIME<="<< t_start
6096 mocchiut 1.1 <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
6097     if ( IsDebug() ) printf(" Get stop validation-time: query is \n %s \n",oss.str().c_str());
6098     result = conn->Query(oss.str().c_str());
6099     if ( !result ) throw -4;
6100     if ( result->GetRowCount() ){
6101     row = result->Next();
6102     t_stop = (UInt_t)atoll(row->GetField(4));
6103     };
6104     if ( IsDebug() ) printf("Validation interval: from time %u - to time %u \n\n",t_stop,t_start);
6105     // --------------------------------------------------------------
6106     // now retrieves runs to be validated
6107     // --------------------------------------------------------------
6108     oss.str("");
6109     oss << " SELECT * FROM GL_RUN WHERE RUNHEADER_TIME <=" << t_start;
6110     oss << " AND RUNHEADER_TIME >="<< t_stop;
6111     oss << " ORDER BY RUNHEADER_TIME DESC;";
6112     if ( IsDebug() )printf(" Check runs for validation: query is \n %s \n",oss.str().c_str());
6113     result = conn->Query(oss.str().c_str());
6114     } else {
6115     //
6116     stringstream myquery;
6117     UInt_t myid = 0;
6118     myquery.str("");
6119     myquery << " SELECT ID FROM GL_ROOT where NAME='"<<valfile.Data() <<"';";
6120     //
6121     result = conn->Query(myquery.str().c_str());
6122     //
6123     row = result->Next();
6124     if( !row ){
6125     if ( strcmp(valfile.Data(),GetRootName().Data()) ){
6126     if ( IsDebug() ) printf(" No file to be validated even if option \"-validate file\" was used!!\n");
6127     return(2);
6128     };
6129     if ( IsDebug() ) printf(" No file to be validated (force mode)! \n");
6130     return(0);
6131     };
6132     myid=(UInt_t)atoll(row->GetField(0));
6133     //
6134     myquery.str("");
6135     myquery << " SELECT MAX(RUNTRAILER_TIME),MIN(RUNHEADER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< myid <<";";
6136     //
6137     result = conn->Query(myquery.str().c_str());
6138     //
6139     row = result->Next();
6140     if( !row->GetField(0) || !row->GetField(1)){
6141     //
6142     if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
6143     //
6144     return(0);
6145     //
6146     } else {
6147     //
6148     UInt_t runhtime = (UInt_t)atoll(row->GetField(0));
6149     UInt_t runttime = (UInt_t)atoll(row->GetField(1));
6150     UInt_t caltime = 0;
6151     //
6152     myquery.str("");
6153     myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
6154     myquery << " order by FROM_TIME asc limit 1;";
6155     //
6156     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
6157     //
6158     //
6159     result = conn->Query(myquery.str().c_str());
6160     //
6161     row = result->Next();
6162     if( !row ){
6163     caltime = runhtime;
6164     } else {
6165     caltime = (UInt_t)atoll(row->GetField(0));
6166     };
6167     //
6168     myquery.str("");
6169     myquery << " SELECT * from GL_RUN where RUNHEADER_TIME>="<< runttime <<" AND RUNHEADER_TIME<=" ;
6170     myquery << caltime << " order by RUNHEADER_TIME DESC";
6171     //
6172     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
6173     //
6174     result = conn->Query(myquery.str().c_str());
6175     //
6176     };
6177     };
6178     //
6179     if ( !result ) throw -4;
6180     if ( !result->GetRowCount() && IsDebug() ) printf(" No runs to validate \n");
6181     //
6182     Int_t nrow = 0;
6183     GL_RUN* this_run = new GL_RUN();
6184     GL_RUN* next_run = new GL_RUN();
6185     Int_t nseq_max = 1000;
6186 mocchiut 1.2 // UInt_t* sequence = new UInt_t[100];
6187 mocchiut 1.1 vector<UInt_t> sequence(nseq_max);
6188     Int_t nseq = 0;
6189     Bool_t CHECK = false;
6190     Bool_t this_ONLINE = false;
6191     Bool_t next_ONLINE = false;
6192     UInt_t t1=0,t2=0;
6193     // ---------------------------------------------------------------------------------
6194     // - loop over runs, back in time,
6195     // - select sequences of runs close in time (less than calibtime s apart),
6196     // which could be preceeded by a calibration
6197     // - check if there might be a missing calibration
6198     // ---------------------------------------------------------------------------------
6199     while(1){
6200    
6201 mocchiut 1.2 row = result->Next();
6202     if( row == NULL ) break;
6203 mocchiut 1.1
6204 mocchiut 1.2 //------------
6205     //get run info
6206     //------------
6207     this_run->Set_GL_RUN(row);
6208 mocchiut 1.1
6209 mocchiut 1.2 Bool_t this_BAD = false;
6210     if(this_run->GetTRK_CALIB_USED() == 1 || this_run->GetTRK_CALIB_USED() == 2) this_ONLINE = true;
6211     else if (this_run->GetTRK_CALIB_USED() == 104) this_ONLINE = false;
6212     else{
6213     // printf("Missing or corrupted header!! \n");
6214     this_ONLINE = false;
6215     this_BAD = true;
6216     };
6217 mocchiut 1.1
6218 mocchiut 1.2 //-----------------------------------
6219     //compare with previous(next in time)
6220     //-----------------------------------
6221     CHECK = false;
6222     UInt_t interval=0;
6223 mocchiut 1.1
6224 mocchiut 1.2 if( nrow != 0){
6225 mocchiut 1.1
6226    
6227 mocchiut 1.2 t1 = this_run->GetRUNTRAILER_TIME();
6228     t2 = next_run->GetRUNHEADER_TIME();
6229     interval = (t2-t1);
6230 mocchiut 1.1
6231 mocchiut 1.2 if(this_ONLINE && next_ONLINE){ // this: ON-LINE + next: ON-LINE
6232 mocchiut 1.1
6233 mocchiut 1.2 if( this_run->ID == next_run->ID_RUN_FRAG ) interval = 0; //=> run fragments
6234 mocchiut 1.1
6235 mocchiut 1.2 if( interval >= calibtime )CHECK = true; //more than calibtime s => there might be a calibration
6236 mocchiut 1.1
6237 mocchiut 1.2 if( !CHECK && this_run->VALIDATION ){
6238 mocchiut 1.12 // for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
6239     for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],this_run->VALIDATION);
6240 mocchiut 1.2 nseq=0;
6241     }
6242 mocchiut 1.1
6243 mocchiut 1.2 }else if( !this_ONLINE && next_ONLINE) { // this: DEFAULT + next:ON-LINE
6244 mocchiut 1.1
6245 mocchiut 1.2 CHECK = true;
6246 mocchiut 1.1
6247 mocchiut 1.2 }else if( !next_ONLINE ){ // this:ANY + next:DEFAULT
6248 mocchiut 1.1
6249 mocchiut 1.2 assignVALIDATION(next_run->ID,true);
6250     nseq=0;
6251     }
6252     }
6253 mocchiut 1.1
6254 mocchiut 1.2 //----------------------------
6255     //check run sequence for calib
6256     //----------------------------
6257     if( CHECK ){
6258     // check if calibration exists
6259     if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);
6260 mocchiut 1.12 // Bool_t MISSING = MissingTRK_CALIB(t1,t2);
6261     UInt_t MISSING = MissingTRK_CALIB(t1,t2);
6262     UInt_t val = 0;
6263     if ( MISSING == 1 ) val = 0;
6264     if ( MISSING == 0 ) val = 1;
6265     if ( MISSING == 2 ) val = 2;
6266     for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],val);
6267 mocchiut 1.2 nseq=0;
6268     };
6269     //--------------
6270     //store run info
6271     //--------------
6272     *next_run = *this_run;
6273     next_ONLINE = this_ONLINE;
6274     if( !this_BAD ){
6275     if(nseq < nseq_max){
6276     sequence[nseq] = this_run->ID;
6277     nseq++;
6278     }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);
6279     };
6280 mocchiut 1.1
6281 mocchiut 1.2 if ( IsDebug() ) printf("%i Run %u \n",nrow,this_run->ID);
6282     nrow++;
6283 mocchiut 1.1
6284     };
6285     delete this_run;
6286     delete next_run;
6287     //
6288     return(0);
6289     };
6290     /**
6291     * Check if there might be a missing tracker calibration in a given time interval
6292     * @param t1 From absolute time
6293     * @param t2 To absolute time
6294     * @return true if there might be a missing calibration
6295     */
6296 mocchiut 1.12 //Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
6297     UInt_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
6298 mocchiut 1.1
6299 mocchiut 1.2 GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();
6300 mocchiut 1.1
6301 pam-fi 1.4 // get the closest calibration before the run start (t2)
6302 mocchiut 1.12 // if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true); //>>> missing
6303     if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(1); //>>> missing
6304 mocchiut 1.1
6305 mocchiut 1.12 // if ( trkcalib->TO_TIME < t2 ) return(true); //>>> missing
6306     if ( trkcalib->TO_TIME < t2 ) return(1); //>>> missing
6307 mocchiut 1.1
6308 mocchiut 1.2 //==============================================================
6309     // Check is done first on the basis of time between calibration,
6310     // which should be equal to the time between ascending-nodes.
6311     //==============================================================
6312     if ( t2 - trkcalib->FROM_TIME > 5700) {
6313     if ( IsDebug() )printf("Long time between calib and run start %u :-( ==> there might be a missing calib \n",t2 - trkcalib->FROM_TIME);
6314     //==============================================================
6315     // there might be a missing calibration, due to:
6316     // - MM full
6317     // - corrupted packets
6318     // - loss of data
6319     // There is an exception in case a download was done during ascending node
6320     //==============================================================
6321     Bool_t DOWNLOAD = false;
6322     // check if the calib was skipped becouse of download .... DA FARE!!
6323 mocchiut 1.12 // if(DOWNLOAD)return(false);
6324     if(DOWNLOAD)return(0);
6325 mocchiut 1.1
6326 mocchiut 1.12 // return(true); //>>> missing
6327     return(1); //>>> missing
6328 mocchiut 1.1
6329 mocchiut 1.2 };
6330 mocchiut 1.1
6331 mocchiut 1.2 //==============================================================
6332     // If the last calibration is close to the run less than this time,
6333     // it is enough to say that there are no missing calibrations
6334     //==============================================================
6335     // the long time interval bewteen runs might be due to download
6336     if ( IsDebug() )printf("Short time between calib and run start %u :-) ==> OK! \n",t2 - trkcalib->FROM_TIME);
6337 mocchiut 1.12 if ( trkcalib->VALIDATION ) return(0);
6338     if ( IsDebug() )printf("Calibration is not validated... :-/ ==> OK but with VALIDATION=2! \n");
6339     return(2);
6340 mocchiut 1.1
6341     };
6342     /**
6343     * Assign VALIDATION value to a GL_RUN entry
6344     * @param idrun Run ID
6345     * @param validation true/false
6346     */
6347     Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){
6348 mocchiut 1.12 return(this->assignVALIDATION(idrun,(UInt_t)validation));
6349     }
6350    
6351     Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, UInt_t validation){
6352 mocchiut 1.2 TSQLResult *result = 0;
6353     stringstream oss;
6354     oss.str("");
6355     oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";
6356     //
6357     // if ( IsDebug() )
6358     // printf(" Set VALIDATION = %i for run %i \n",validation,idrun);
6359     if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());
6360     result = conn->Query(oss.str().c_str());
6361     if ( !result ) throw -4;
6362     return(0);
6363 mocchiut 1.1 }
6364    
6365    
6366    
6367     // Insert TLEs from file tlefilename in the table GL_TLE in the db
6368     // opened by conn, sorting them by date from older to newer, if each
6369     // TLE has not been alread inserted.
6370     Int_t PamelaDBOperations::populateTLE()//(TSQLServer *conn, char *tleFile)
6371     {
6372     fstream tlefile(tlefilename, ios::in);
6373    
6374     if ( !tlefile ) throw -7;
6375    
6376     vector<cTle*> ctles;
6377     vector<cTle*>::iterator iter;
6378     int present = 0;
6379    
6380     // Get three lines from tlefile, create a cTle object and put it
6381     // into ctles
6382     while(1) {
6383     cTle *tlef;
6384     string str1, str2, str3;
6385    
6386     getline(tlefile, str1);
6387     if(tlefile.eof()) break;
6388    
6389     getline(tlefile, str2);
6390     if(tlefile.eof()) break;
6391    
6392     getline(tlefile, str3);
6393     if(tlefile.eof()) break;
6394    
6395     // We now have three good lines for a cTle.
6396     tlef = new cTle(str1, str2, str3);
6397     ctles.push_back(tlef);
6398     }
6399    
6400     tlefile.close();
6401    
6402     // Sort by date
6403     sort(ctles.begin(), ctles.end(), compTLE);
6404    
6405     // Now we insert each TLE into the db
6406     for(iter = ctles.begin(); iter != ctles.end(); iter++) {
6407     cTle *tle = *iter;
6408    
6409     // Do nothing if it's already present in the db. Just increase
6410     // the counter present.
6411     if (! isTlePresent(tle))
6412     {
6413     int status = insertTle(tle);
6414    
6415     // Insert query failed. Return 1.
6416     if(status == EXIT_FAILURE) {
6417    
6418     if( IsDebug() ) {
6419     cerr << "Error: inserting TLE:" << endl
6420     << tle->getName() << endl
6421     << tle->getLine1() << endl
6422     << tle->getLine2() << endl;
6423     }
6424    
6425     throw -4;
6426     return 1;
6427     }
6428    
6429     }
6430     else
6431     present++;
6432    
6433     }
6434    
6435     int inserted = ctles.size() - present; // Number of inserted TLE.
6436     if ( IsDebug() )
6437     cout << "\nProcessed TLEs ranging from " << getTleDatetime(ctles[0]) << " to " << getTleDatetime(ctles[ctles.size()-1]) << "." << endl
6438     << inserted << " newly inserted TLEs out of " << ctles.size() << " processed." << endl;
6439    
6440     ctles.clear();
6441    
6442    
6443     // Return 2 if no new TLE has been inserted. 0 otherwise.
6444     if(! inserted ) return 2;
6445     return 0;
6446     }
6447    
6448    
6449     // Insert tle in the table GL_TLE using the connection conn.
6450     Int_t PamelaDBOperations::insertTle(cTle *tle)
6451     {
6452     stringstream oss;
6453     TSQLResult *result = 0;
6454    
6455     oss.str("");
6456     oss << " INSERT INTO GL_TLE (TLE1, TLE2, TLE3, FROM_TIME)"
6457     << " VALUES ( '"
6458     << tle->getName() << "', '"
6459     << tle->getLine1() << "', '"
6460     << tle->getLine2() << "', '"
6461     << getTleDatetime(tle) << "')";
6462    
6463     // cout << oss.str().c_str() << endl;
6464     result = conn->Query(oss.str().c_str());
6465     if (result == NULL)
6466     return EXIT_FAILURE;
6467    
6468     return EXIT_SUCCESS;
6469     }
6470    
6471    
6472     // Return whether tle is already in the db connected by conn.
6473     bool PamelaDBOperations::isTlePresent(cTle *tle)
6474     {
6475     stringstream oss;
6476     TSQLResult *result = 0;
6477    
6478     oss.str("");
6479     oss << "SELECT * FROM GL_TLE WHERE FROM_TIME = '"
6480     << getTleDatetime(tle) << "'";
6481    
6482     result = conn->Query(oss.str().c_str());
6483     if (result == NULL) throw -4;
6484    
6485     if (result->GetRowCount())
6486     return true;
6487     else
6488     return false;
6489     }
6490    
6491    
6492     // Return whether the first TLE is dated early than the second
6493     bool compTLE (cTle *tle1, cTle *tle2)
6494     {
6495     return getTleJulian(tle1) < getTleJulian(tle2);
6496     }
6497    
6498    
6499     // Return the date of the tle using the format (year-2000)*1e3 +
6500     // julian day. e.g. 6365 is the 31th Dec 2006.
6501     // It does *not* return a cJulian date.
6502     float getTleJulian(cTle *tle) {
6503     return tle->getField(cTle::FLD_EPOCHYEAR)*1e3 + tle->getField(cTle::FLD_EPOCHDAY);
6504     }
6505    
6506    
6507     // Return a string like YYYY-MM-DD hh:mm:ss, usable for mysql datetime
6508     // format.
6509     string getTleDatetime(cTle *tle)
6510     {
6511     int year, mon, day, hh, mm, ss;
6512     double dom; // day of month (is double!)
6513     stringstream date; // date in datetime format
6514    
6515     // create a cJulian from the date in tle
6516     cJulian jdate = cJulian( 2000 + (int) tle->getField(cTle::FLD_EPOCHYEAR), tle->getField(cTle::FLD_EPOCHDAY));
6517    
6518     // get year, month, day of month
6519     jdate.getComponent(&year, &mon, &dom);
6520    
6521     // build a datetime YYYY-MM-DD hh:mm:ss
6522     date.str("");
6523     day = (int) floor(dom);
6524     hh = (int) floor( (dom - day) * 24);
6525     mm = (int) floor( ((dom - day) * 24 - hh) * 60);
6526     ss = (int) floor( ((((dom - day) * 24 - hh) * 60 - mm) * 60));
6527     // ms = (int) floor( (((((dom - day) * 24 - hh) * 60 - mm) * 60) - ss) * 1000);
6528    
6529     date << year << "-" << mon << "-" << day << " " << hh << ":" << mm << ":" << ss;
6530    
6531     return date.str();
6532     }
6533    
6534     /**
6535     * Remove a file from the DB, delete on cascade all entries related to that file
6536     * rearrange GL_RUN and GL_XXX_CALIB tables, turn off validation till the following
6537     * calibration
6538     **/
6539     Int_t PamelaDBOperations::removeFile(TString remfile){
6540     //
6541     // Determine ID_ROOT_L0 and ID_RAW
6542     //
6543     TSQLResult *pResult;
6544     TSQLRow *Row;
6545     stringstream myquery;
6546     //
6547     myquery.str("");
6548 mocchiut 1.10 myquery << " SELECT ID,ID_RAW,ID_TIMESYNC FROM GL_ROOT where NAME='"<<remfile.Data() <<"';";
6549 mocchiut 1.1 //
6550     pResult = conn->Query(myquery.str().c_str());
6551     //
6552     Row = pResult->Next();
6553     if( !Row ){
6554     if ( strcmp(remfile.Data(),GetRootName().Data()) ){
6555     if ( IsDebug() ) printf(" No file to be removed even if option \"-remove file\" was used!!\n");
6556     return(1);
6557     };
6558     if ( IsDebug() ) printf(" No file to be removed (force mode)! \n");
6559     return(0);
6560     };
6561     //
6562     this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));
6563     this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));
6564 mocchiut 1.10 UInt_t idtsy=(UInt_t)atoll(Row->GetField(2));
6565 mocchiut 1.1 //
6566     this->ValidationOFF();
6567     //
6568     this->RemoveCALIBS();
6569     //
6570     this->RemoveRUNS();
6571     //
6572 mocchiut 1.10 this->RemoveFILES(idtsy);
6573 mocchiut 1.1 //
6574     this->SetID_ROOT(0);
6575     this->SetID_RAW(0);
6576     //
6577     return(0);
6578     };
6579    
6580     /**
6581     *
6582     * Set validation bit to zero for runs following the removing file till
6583     * 1) a run with TRK_CALIB_USED=140
6584     * 2) a run with VALIDATION = 0
6585     * 3) the next calibration
6586     *
6587     **/
6588     void PamelaDBOperations::ValidationOFF(){
6589     TSQLResult *pResult;
6590     TSQLRow *Row;
6591     stringstream myquery;
6592     Int_t unv = 0;
6593     //select ID from GL_RUN where RUNHEADER_TIME>=1152671382 AND (VALIDATION=0 OR TRK_CALIB_USED=104) order by RUNHEADER_TIME asc limit 1;
6594     myquery.str("");
6595     myquery << " SELECT MAX(RUNTRAILER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
6596     //
6597     pResult = conn->Query(myquery.str().c_str());
6598     //
6599     Row = pResult->Next();
6600     if( !Row->GetField(0) ){
6601     //
6602     if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
6603     //
6604     } else {
6605     //
6606     UInt_t runhtime = (UInt_t)atoll(Row->GetField(0));
6607     UInt_t caltime = 0;
6608     //
6609     myquery.str("");
6610     myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
6611     myquery << " order by FROM_TIME asc limit 1;";
6612     //
6613     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
6614     //
6615     //
6616     delete pResult;
6617     pResult = conn->Query(myquery.str().c_str());
6618     //
6619     Row = pResult->Next();
6620     if( !Row ){
6621     caltime = runhtime;
6622     } else {
6623     caltime = (UInt_t)atoll(Row->GetField(0));
6624     };
6625     //
6626     myquery.str("");
6627     myquery << " SELECT ID,RUNHEADER_TIME from GL_RUN where RUNHEADER_TIME>="<< runhtime <<" AND (VALIDATION=0 OR TRK_CALIB_USED=104 OR RUNHEADER_TIME>" ;
6628     myquery << caltime << ") order by RUNHEADER_TIME asc LIMIT 1";
6629     //
6630     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
6631     //
6632     pResult = conn->Query(myquery.str().c_str());
6633     //
6634     Row = pResult->Next();
6635     if( !Row ){
6636     //
6637     if ( IsDebug() ) printf(" NO RUN NEED TO BE UNVALIDATED \n");
6638     //
6639     } else {
6640     myquery.str("");
6641     myquery << " SELECT ID from GL_RUN where RUNHEADER_TIME<"<< Row->GetField(1) <<" AND ";
6642     myquery << " RUNHEADER_TIME>=" <<runhtime;
6643     myquery << " order by RUNHEADER_TIME asc;";
6644     //
6645     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
6646     //
6647     pResult = conn->Query(myquery.str().c_str());
6648     //
6649     Row = pResult->Next();
6650     while ( Row ){
6651     //
6652     unv++;
6653     this->assignVALIDATION((UInt_t)atoll(Row->GetField(0)), false);
6654     Row = pResult->Next();
6655     //
6656     };
6657     };
6658     };
6659     if ( IsDebug() ) printf(" %u runs have been unvalidated \n",unv);
6660     };
6661    
6662     /**
6663     *
6664     * Rearrange GL_RUN table and remove runs
6665     *
6666     **/
6667     void PamelaDBOperations::RemoveRUNS(){
6668     TSQLResult *pResult;
6669     TSQLRow *Row;
6670     stringstream myquery;
6671     UInt_t drun = 0;
6672     GL_RUN *delrun = new GL_RUN();
6673     //
6674     myquery.str("");
6675     myquery << " SELECT ID FROM GL_RUN where ID_RUN_FRAG=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
6676     //
6677     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
6678     //
6679     pResult = conn->Query(myquery.str().c_str());
6680     //
6681     Row = pResult->Next();
6682     //
6683     //
6684     if ( !Row ){
6685     if ( IsDebug() ) printf(" No run with ID_RUN_FRAG=0 belonged to this file \n");
6686     } else {
6687     if ( IsDebug() ) printf(" Deleting run from GL_RUN table \n");
6688     while ( Row ){
6689     delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
6690     if ( IsDebug() ) printf(" del run %u \n",(UInt_t)atoll(Row->GetField(0)));
6691     drun++;
6692     Row = pResult->Next();
6693     };
6694     };
6695     //
6696     //
6697     myquery.str("");
6698     myquery << " SELECT ID,ID_RUN_FRAG FROM GL_RUN where ID_RUN_FRAG!=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
6699     //
6700     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
6701     //
6702     pResult = conn->Query(myquery.str().c_str());
6703     //
6704     Row = pResult->Next();
6705     //
6706     if ( !Row ){
6707     if ( IsDebug() ) printf(" No run with ID_RUN_FRAG!=0 belonged to this file \n");
6708     } else {
6709     if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN table \n");
6710     while ( Row ){
6711     if ( IsDebug() ) printf(" restore run %u \n",(UInt_t)atoll(Row->GetField(1)));
6712     delrun->RestoreRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN_FRAGMENTS");
6713     if ( IsDebug() ) printf(" del run %u \n",(UInt_t)atoll(Row->GetField(1)));
6714     delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN");
6715     if ( (UInt_t)atoll(Row->GetField(1)) != (UInt_t)atoll(Row->GetField(0)) ){
6716     if ( IsDebug() ) printf(" del run %u \n",(UInt_t)atoll(Row->GetField(0)));
6717     delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
6718     };
6719     drun++;
6720     Row = pResult->Next();
6721     };
6722     };
6723     //
6724     if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN table \n",drun);
6725     //
6726     //
6727     //
6728     drun = 0;
6729     //
6730     myquery.str("");
6731     myquery << " SELECT ID_TRASH FROM GL_RUN_TRASH where BELONGED_TO='GL_RUN_FRAGMENTS' AND ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
6732     //
6733     pResult = conn->Query(myquery.str().c_str());
6734     //
6735     Row = pResult->Next();
6736     //
6737     if ( !Row ){
6738     if ( IsDebug() ) printf(" No run from GL_RUN_FRAGMENTS table in the trash table for this file \n");
6739     } else {
6740     if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_TRASH table \n");
6741     while ( Row ){
6742     if ( IsDebug() ) printf(" del run idtrash %u \n",(UInt_t)atoll(Row->GetField(0)));
6743     myquery.str("");
6744     myquery << " DELETE FROM GL_RUN_TRASH where ID_TRASH=" << Row->GetField(0) <<";";
6745     conn->Query(myquery.str().c_str());
6746     drun++;
6747     Row = pResult->Next();
6748     };
6749     };
6750     //
6751     if ( IsDebug() ) printf(" Deleted %u run(s) from GL_RUN_TRASH table \n",drun);
6752     //
6753     //
6754     //
6755     drun = 0;
6756     //
6757     myquery.str("");
6758     myquery << " SELECT ID FROM GL_RUN_FRAGMENTS where ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
6759     //
6760     pResult = conn->Query(myquery.str().c_str());
6761     //
6762     Row = pResult->Next();
6763     //
6764     if ( !Row ){
6765     if ( IsDebug() ) printf(" No run in the GL_RUN_FRAGMENTS table for this file \n");
6766     } else {
6767     if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_FRAGMENTS table \n");
6768     while ( Row ){
6769     if ( IsDebug() ) printf(" del run %u \n",(UInt_t)atoll(Row->GetField(0)));
6770     myquery.str("");
6771     myquery << " DELETE FROM GL_RUN_FRAGMENTS where ID=" << Row->GetField(0) <<";";
6772     conn->Query(myquery.str().c_str());
6773     drun++;
6774     Row = pResult->Next();
6775     };
6776     };
6777     //
6778     if ( IsDebug() ) printf(" Deleted %u run(s) from GL_RUN_FRAGMENTS table \n",drun);
6779     //
6780     //
6781     //
6782     delete delrun;
6783     //
6784     };
6785    
6786    
6787     /**
6788     *
6789     * Rearrange calibration tables
6790     *
6791     **/
6792 mocchiut 1.10 void PamelaDBOperations::RemoveFILES(UInt_t idtsy){
6793 mocchiut 1.1 stringstream myquery;
6794     //
6795     myquery.str("");
6796     myquery << " DELETE FROM GL_RAW WHERE ID=" <<this->GetID_RAW() <<";";
6797     //
6798     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
6799     //
6800     conn->Query(myquery.str().c_str());
6801     //
6802 mocchiut 1.10 myquery.str("");
6803     myquery << " DELETE FROM GL_ROOT WHERE ID=" <<this->GetID_ROOT() <<";";
6804     //
6805     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
6806     //
6807     conn->Query(myquery.str().c_str()); //
6808     //
6809     if ( !chewbacca ){
6810     myquery.str("");
6811     myquery << " DELETE FROM GL_TIMESYNC WHERE ID=" << idtsy <<";";
6812     //
6813     if ( IsDebug() ) printf(" query is \n %s \n",myquery.str().c_str());
6814     //
6815     conn->Query(myquery.str().c_str());
6816     };
6817     //
6818 mocchiut 1.1 };
6819    
6820     /**
6821     *
6822     * Rearrange calibration tables
6823     *
6824     **/
6825     void PamelaDBOperations::RemoveCALIBS(){
6826     TSQLResult *pResult;
6827     TSQLRow *Row;
6828     stringstream myquery;
6829     //
6830     //
6831     // Calorimeter
6832     //
6833     for (Int_t section = 0; section < 4; section++){
6834     myquery.str("");
6835     myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_CALO_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<" AND ";
6836     myquery << " SECTION=" << section << ";";
6837     //
6838     pResult = conn->Query(myquery.str().c_str());
6839     //
6840     Row = pResult->Next();
6841     if( !Row->GetField(0) || !Row->GetField(1) ){
6842     //
6843     if ( IsDebug() ) printf(" NO CALO CALIBRATION SECTION %i ASSOCIATED TO THIS FILE! \n",section);
6844     //
6845     } else {
6846     //
6847     myquery.str("");
6848     myquery << " UPDATE GL_CALO_CALIB SET TO_TIME=" << Row->GetField(1);
6849     myquery << " WHERE TO_TIME="<< Row->GetField(0) << " AND ";
6850     myquery << " SECTION=" << section << ";";
6851     //
6852     pResult = conn->Query(myquery.str().c_str());
6853     //
6854     if( !pResult ){
6855     //
6856     if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
6857     //
6858     throw -4;
6859     //
6860     };
6861     //
6862     };
6863     };
6864     Bool_t OLDDB = false;
6865     for (Int_t section = 0; section < 4; section++){
6866     myquery.str("");
6867     myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_CALOPULSE_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<" AND ";
6868     myquery << " SECTION=" << section << ";";
6869     //
6870     pResult = conn->Query(myquery.str().c_str());
6871     //
6872     if ( conn->GetErrorCode() ){
6873     printf(" Section %i : warning, old databse structure no GL_CALOPULSE_CALIB table!\n",section);
6874     OLDDB=true;
6875     } else {
6876     Row = pResult->Next();
6877     if( !Row->GetField(0) || !Row->GetField(1) ){
6878     //
6879     if ( IsDebug() ) printf(" NO PULSE CALO CALIBRATION SECTION %i ASSOCIATED TO THIS FILE! \n",section);
6880     //
6881     } else {
6882     //
6883     myquery.str("");
6884     myquery << " UPDATE GL_CALOPULSE_CALIB SET TO_TIME=" << Row->GetField(1);
6885     myquery << " WHERE TO_TIME="<< Row->GetField(0) << " AND ";
6886     myquery << " SECTION=" << section << ";";
6887     //
6888     pResult = conn->Query(myquery.str().c_str());
6889     //
6890     if( !pResult ){
6891     //
6892     if ( IsDebug() ) printf(" ERROR DELETING CALO PULSE CALIBRATIONS \n");
6893     //
6894     throw -4;
6895     //
6896     };
6897     //
6898     };
6899     };
6900     };
6901     myquery.str("");
6902     myquery << " DELETE FROM GL_CALO_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT() << ";";
6903     //
6904     pResult = conn->Query(myquery.str().c_str());
6905     //
6906     if( !pResult ){
6907     //
6908     if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
6909     //
6910     throw -4;
6911     //
6912     };
6913     //
6914     myquery.str("");
6915     myquery << " DELETE FROM GL_CALOPULSE_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT() << ";";
6916     //
6917     pResult = conn->Query(myquery.str().c_str());
6918     if ( IsDebug() ) printf(" Delete from GL_CALOPULSE_CALIB query is %s \n",myquery.str().c_str());
6919     if ( !OLDDB ){
6920     //
6921     if( !pResult ){
6922     //
6923     if ( IsDebug() ) printf(" ERROR DELETING PULSE CALO CALIBRATIONS \n");
6924     //
6925     throw -4;
6926     //
6927     };
6928     };
6929     //
6930     // Tracker
6931     //
6932     myquery.str("");
6933     myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_TRK_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
6934     //
6935     pResult = conn->Query(myquery.str().c_str());
6936     //
6937     Row = pResult->Next();
6938     if( !Row->GetField(0) || !Row->GetField(1) ){
6939     //
6940     if ( IsDebug() ) printf(" NO TRK CALIBRATION ASSOCIATED TO THIS FILE! \n");
6941     //
6942     } else {
6943     //
6944     myquery.str("");
6945     myquery << " UPDATE GL_TRK_CALIB SET TO_TIME=" << Row->GetField(1);
6946     myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
6947     //
6948     pResult = conn->Query(myquery.str().c_str());
6949     //
6950     if( !pResult ){
6951     //
6952     if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
6953     //
6954     throw -4;
6955     //
6956     };
6957     //
6958     myquery.str("");
6959     myquery << " DELETE FROM GL_TRK_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT() << ";";
6960     //
6961     pResult = conn->Query(myquery.str().c_str());
6962     //
6963     if( !pResult ){
6964     //
6965     if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
6966     //
6967     throw -4;
6968     //
6969     };
6970     };
6971     //
6972     //
6973     // S4
6974     //
6975     myquery.str("");
6976     myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_S4_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
6977     //
6978     pResult = conn->Query(myquery.str().c_str());
6979     //
6980     Row = pResult->Next();
6981     if( !Row->GetField(0) || !Row->GetField(1) ){
6982     //
6983     if ( IsDebug() ) printf(" NO S4 CALIBRATION ASSOCIATED TO THIS FILE! \n");
6984     //
6985     } else {
6986     //
6987     myquery.str("");
6988     myquery << " UPDATE GL_S4_CALIB SET TO_TIME=" << Row->GetField(1);
6989     myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
6990     //
6991     pResult = conn->Query(myquery.str().c_str());
6992     //
6993     if( !pResult ){
6994     //
6995     if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
6996     //
6997     throw -4;
6998     //
6999     };
7000     //
7001     myquery.str("");
7002     myquery << " DELETE FROM GL_S4_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT() << ";";
7003     //
7004     pResult = conn->Query(myquery.str().c_str());
7005     //
7006     if( !pResult ){
7007     //
7008     if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
7009     //
7010     throw -4;
7011     //
7012     };
7013     //
7014     };
7015     };
7016    
7017     /**
7018     *
7019     * Rearrange calibration tables
7020     *
7021     **/
7022 pam-fi 1.4 UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh , TFile *file){
7023    
7024     if(!caltrk) return 0;
7025    
7026     if ( IsDebug() ) cout << "ValidateTrkCalib:"<<endl;
7027    
7028     UInt_t validate = 1;
7029     Int_t vorder[]={5,5,3,3,4,4,2,2,1,1,0,0};
7030     UInt_t timeaftercalib=120000; //2000;
7031     TString classname = caltrk->GetName();
7032    
7033     // ----------------------------------
7034     // Check CRCs and failed calibrations
7035     // ----------------------------------
7036     for(Int_t ipkt=0; ipkt<6; ipkt++){
7037     if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
7038     if( caltrk->crc_hcal[ipkt] ){
7039     // if(IsDebug())cout<<"(CRC Header)";
7040     validate = 0;
7041     if(IsDebug())cout <<endl<<" *** CRC *** (header DSPn "<<caltrk->DSPnumber[ipkt]<<")";
7042    
7043     }
7044     for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] ){
7045     // if(IsDebug())cout<<"(CRC Pkt-"<<ilad<<")";
7046     if(IsDebug())cout <<endl<<" *** CRC *** (data DSPn "<<caltrk->DSPnumber[ipkt]<<" ladder "<<ilad<<")";
7047     validate = 0;
7048     }
7049     if( !(caltrk->ncalib_event[ipkt]==0 && caltrk->cal_flag[ipkt]==0) ){
7050     if(IsDebug())cout <<endl<<" *** FAILURE *** (data DSPn "<<caltrk->DSPnumber[ipkt]<<")";
7051     validate = 0;
7052     }
7053     }else{
7054     // validate=0;
7055     if(IsDebug())cout <<endl<<" *** DSPn *** ("<< caltrk->DSPnumber[ipkt] <<" @pkt "<<ipkt<<")";
7056     }
7057     }
7058    
7059     // -----------------------
7060     // Check missing packets:
7061     // -----------------------
7062     // Readout order:
7063     // ------------------
7064     // DSP packet board
7065     // ------------------
7066     // 12 0 1
7067     // 10 1 1
7068     // 8 2 1
7069     // 4 3 1
7070     // 6 4 1
7071     // 2 5 1
7072     // ------------------
7073     // 11 0 2
7074     // 9 1 2
7075     // 7 2 2
7076     // 3 3 2
7077     // 5 4 2
7078     // 1 5 2
7079     // ------------------
7080     // -------------------------------------------------
7081     // Check if it is first or second calibration packet
7082     // -------------------------------------------------
7083     UInt_t build=0;
7084     UInt_t base=0;
7085     UInt_t mask=0;
7086     if(classname.Contains("CalibTrk1Event")){
7087     base=12;
7088     mask=0x03F000;
7089     }
7090     if(classname.Contains("CalibTrk2Event")){
7091     base=18;
7092     mask=0xFC0000;
7093     }
7094     // ----------------------------------------------------
7095     // Count number of valid packets and set build variable
7096     // ----------------------------------------------------
7097     if(IsDebug())cout <<endl<< " DSP: ";
7098     Int_t npkts=0;
7099     for(Int_t ipkt=0; ipkt<6; ipkt++){
7100     if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
7101     if(IsDebug())cout <<" "<<caltrk->DSPnumber[ipkt];
7102     npkts++;
7103     build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );
7104     // cout << caltrk->DSPnumber[ipkt]
7105     };
7106     }
7107     if(IsDebug())cout << " ==> "<< hex << build << dec;
7108     // ----------------------------------------------------
7109     // If the number of valid packets is 6, ok exit...
7110     // ----------------------------------------------------
7111     if( npkts==6 ){
7112     return validate; // exit
7113     }
7114     ////////////////////////////////////////////////////////
7115     // ...otherwise there might be some missing packets
7116     //
7117     // In this case check the acq configuration
7118     // (some DSPs might be excluded from acquisition)
7119     ////////////////////////////////////////////////////////
7120    
7121     if(!eh || !file || (file&&file->IsZombie()) ){
7122     if ( IsDebug() )cout << " *** MISSING VIEW *** eh="<<eh<<" file="<<file<<" cannot validate"<<endl;
7123     return (0);
7124     }
7125    
7126     // -----------------------------------------------
7127     // retrieve the first run header after calib
7128     // -----------------------------------------------
7129    
7130     PacketType *pctp;
7131     EventCounter *cod;
7132     cod = eh->GetCounter();
7133     Int_t irun = cod->Get(pctp->RunHeader);
7134     TTree *rh=(TTree*)file->Get("RunHeader");
7135     if ( !rh || rh->IsZombie() ) throw -17;
7136     if( rh->GetEntries() <= irun ){
7137     if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (1) -- cannot validate :-( "<<endl;
7138     return 0; // :-(
7139     }
7140     RunHeaderEvent *run = 0;
7141     EventHeader *hrun = 0;
7142     rh->SetBranchAddress("RunHeader", &run);
7143     rh->SetBranchAddress("Header", &hrun);
7144     rh->GetEntry(irun);
7145     if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){
7146     if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (2) -- cannot validate :-( "<<endl;
7147     return 0; // :-(
7148     }
7149    
7150     UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());
7151     if( dtime > timeaftercalib ){
7152     if ( IsDebug() ) cout << " *** MISSING-PKT *** run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;
7153     return 0; // :-(
7154     }
7155    
7156     if ( IsDebug() ) cout <<endl<< " ACQ_BUILD_INFO ==> "<<hex<<(run->ACQ_BUILD_INFO & mask)<<dec;
7157    
7158     if( (run->ACQ_BUILD_INFO & mask) != build ){
7159     validate=0; // :-(
7160     cout <<endl<< " *** MISSING-PKT *** packet mismatch: ACQ_BUILD_INFO="<<hex<<(run->ACQ_BUILD_INFO&mask)<<" != "<<build<<dec;
7161     };
7162    
7163     return validate;
7164 mocchiut 1.1
7165 mocchiut 1.2
7166 pam-fi 1.4 }
7167 mocchiut 1.1
7168     /**
7169     *
7170     * Check the DB (only for overlapping runs at the moment)
7171     *
7172     **/
7173     UInt_t PamelaDBOperations::Check(){
7174 mocchiut 1.2 return(this->Check(0,0));
7175 mocchiut 1.1 }
7176    
7177     UInt_t PamelaDBOperations::Check(UInt_t from, UInt_t to){
7178     //
7179 mocchiut 1.2 if ( IsDebug() ) printf(" from %u to %u \n",from,to);
7180 mocchiut 1.1 //
7181     UInt_t test = 0;
7182     //
7183     UInt_t thisrht = 0;
7184     UInt_t thisrtt = 0;
7185     UInt_t thisid = 0;
7186     UInt_t prevrht = 0;
7187     UInt_t prevrtt = 0;
7188     UInt_t previd = 0;
7189     //
7190     UInt_t prevl0id = 0;
7191     UInt_t thisl0id = 0;
7192     //
7193     stringstream oss;
7194     TSQLResult *result = 0;
7195     TSQLRow *row = 0;
7196     TSQLResult *result2 = 0;
7197     TSQLRow *row2 = 0;
7198     TSQLResult *result3 = 0;
7199     TSQLRow *row3 = 0;
7200     oss.str("");
7201     oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME,NEVENTS FROM GL_RUN order by RUNHEADER_TIME asc;";
7202     // oss << "SELECT ID,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN where ID>10170 and ID<10190 order by RUNHEADER_TIME asc;";
7203     result = conn->Query(oss.str().c_str());
7204     //
7205     if ( !result ) throw -4;;
7206     //
7207     row = result->Next();
7208     UInt_t nid = 0;
7209     //
7210     while ( row ){
7211     nid++;
7212     if ( !(nid%1000) && nid ) printf(" %iK run scanned \n",nid/1000);
7213     thisid = (UInt_t)atoll(row->GetField(0));
7214     thisl0id = (UInt_t)atoll(row->GetField(1));
7215     thisrht = (UInt_t)atoll(row->GetField(2));
7216     thisrtt = (UInt_t)atoll(row->GetField(3));
7217     //
7218     if ( from > 0 && nid <= from ) goto ss;
7219     if ( to > 0 && nid >= to ) goto ss;
7220 mocchiut 1.2 //
7221 mocchiut 1.1 if ( (UInt_t)atoll(row->GetField(4)) > 1 ){
7222     //
7223     //
7224     //
7225     oss.str("");
7226     oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN WHERE ID!="
7227     << thisid << " AND ( RUNHEADER_TIME="
7228     << thisrht << " OR RUNTRAILER_TIME="
7229     << thisrtt << " ) AND NEVENTS!=0 AND NEVENTS!=1 order by RUNHEADER_TIME asc;";
7230     result3 = conn->Query(oss.str().c_str());
7231     if ( IsDebug() ) printf(" query is %s \n",oss.str().c_str());
7232     if ( result3 ){
7233     //
7234     oss.str("");
7235     oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN WHERE ID!="
7236     << thisid << " AND RUNHEADER_TIME="
7237     << thisrht << " AND RUNTRAILER_TIME!="
7238     << thisrtt << " AND NEVENTS!=0 AND NEVENTS!=1 order by RUNHEADER_TIME asc;";
7239     result3 = conn->Query(oss.str().c_str());
7240     if ( IsDebug() ) printf(" query is %s \n",oss.str().c_str());
7241     if ( result3 ){
7242     row3 = result3->Next();
7243     //
7244     while ( row3 ){
7245     //
7246     // 2 runs with same runheader
7247     //
7248     printf(" CHECK n.4 RUNs %u and %u HAVE SAME RUNHEADER \n",thisid,(UInt_t)atoll(row3->GetField(0)));
7249     row3 = result3->Next();
7250     };
7251 mocchiut 1.2 // delete result3;
7252 mocchiut 1.1
7253     };
7254     //
7255     oss.str("");
7256     oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN WHERE ID!="
7257     << thisid << " AND RUNHEADER_TIME!="
7258     << thisrht << " AND RUNTRAILER_TIME="
7259     << thisrtt << " AND NEVENTS!=0 AND NEVENTS!=1 order by RUNHEADER_TIME asc;";
7260     result3 = conn->Query(oss.str().c_str());
7261     if ( IsDebug() ) printf(" query is %s \n",oss.str().c_str());
7262     if ( result3 ){
7263     row3 = result3->Next();
7264     //
7265     while ( row3 ){
7266     //
7267     // 2 runs with same runtrailer
7268     //
7269     printf(" CHECK n.5 RUNs %u and %u HAVE SAME RUNTRAILER \n",thisid,(UInt_t)atoll(row3->GetField(0)));
7270     row3 = result3->Next();
7271     };
7272 mocchiut 1.2 // delete result3;
7273 mocchiut 1.1 };
7274     //
7275     oss.str("");
7276     oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN WHERE ID!="
7277     << thisid << " AND RUNHEADER_TIME="
7278     << thisrht << " AND RUNTRAILER_TIME="
7279     << thisrtt << " AND ID_RUN_FRAG!="
7280     << thisid << " order by RUNHEADER_TIME asc;";
7281     result3 = conn->Query(oss.str().c_str());
7282     if ( result3 ){
7283     row3 = result3->Next();
7284     //
7285     while ( row3 ){
7286     //
7287     // duplicated run
7288     //
7289     printf(" CHECK n.7 RUNs %u and %u HAVE SAME RUNTRAILER AND RUNHEADER (ARE THE SAME?) \n",thisid,(UInt_t)atoll(row3->GetField(0)));
7290     row3 = result3->Next();
7291     };
7292 mocchiut 1.2 // delete result3;
7293 mocchiut 1.1
7294     };
7295     };
7296     //
7297     oss.str("");
7298     oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN WHERE ID!="
7299     << thisid << " AND RUNHEADER_TIME>"
7300     << thisrht << " AND RUNTRAILER_TIME<"
7301     << thisrtt << " order by RUNHEADER_TIME asc;";
7302     result3 = conn->Query(oss.str().c_str());
7303     if ( result3 ){
7304     row3 = result3->Next();
7305     //
7306     while ( row3 ){
7307     //
7308     // run contained in the checked one
7309     //
7310     printf(" CHECK n.6 RUN %u CONTAINS RUN %u \n",thisid,(UInt_t)atoll(row3->GetField(0)));
7311     row3 = result3->Next();
7312     };
7313 mocchiut 1.2 // delete result3;
7314 mocchiut 1.1 };
7315     //
7316     };
7317     //
7318     // if ( thisrht < prevrtt || thisrtt < prevrht || thisrht > thisrtt && !(!prevrht && !prevrtt &&!previd) ){
7319     // if ( (thisrht < prevrtt || thisrtt < prevrht || thisrht > thisrtt) && (thisrht != prevrht) ){
7320     if ( (thisrht < prevrtt) && (thisrht != prevrht) ){
7321     if ( IsDebug() ) printf(" IDprev %u ID %u prevrht %u prevrtt %u thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
7322     printf(" CHECK n.1 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrht-prevrtt),previd,thisid);
7323     TString prevf = "";
7324     TString thisf = "";
7325     oss.str("");
7326     oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
7327     result2 = conn->Query(oss.str().c_str());
7328     if ( !result2 ) throw -4;;
7329     row2 = result2->Next();
7330     prevf = (TString)row2->GetField(0);
7331     oss.str("");
7332     oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
7333     result2 = conn->Query(oss.str().c_str());
7334     if ( !result2 ) throw -4;;
7335     row2 = result2->Next();
7336     thisf = (TString)row2->GetField(0);
7337     if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7338     test = 1;
7339 mocchiut 1.2 // delete result2;
7340 mocchiut 1.1 };
7341     //
7342     if ( (thisrtt < prevrht) && (thisrht != prevrht) ){
7343     if ( IsDebug() ) printf(" IDprev %u ID %u prevrht %u prevrtt %u thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
7344     printf(" CHECK n.2 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrtt-prevrht),previd,thisid);
7345     TString prevf = "";
7346     TString thisf = "";
7347     oss.str("");
7348     oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
7349     result2 = conn->Query(oss.str().c_str());
7350     if ( !result2 ) throw -4;
7351     row2 = result2->Next();
7352     prevf = (TString)row2->GetField(0);
7353     oss.str("");
7354     oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
7355     result2 = conn->Query(oss.str().c_str());
7356     if ( !result2 ) throw -4;;
7357     row2 = result2->Next();
7358     thisf = (TString)row2->GetField(0);
7359     if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7360     test = 1;
7361 mocchiut 1.2 // delete result2;
7362 mocchiut 1.1 };
7363     //
7364     if ( (thisrht > thisrtt) && (thisrht != prevrht) ){
7365     if ( IsDebug() ) printf(" IDprev %u ID %u prevrht %u prevrtt %u thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
7366     printf(" CHECK n.3 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrht-thisrtt),previd,thisid);
7367     TString prevf = "";
7368     TString thisf = "";
7369     oss.str("");
7370     oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
7371     result2 = conn->Query(oss.str().c_str());
7372     if ( !result2 ) throw -4;;
7373     row2 = result2->Next();
7374     prevf = (TString)row2->GetField(0);
7375     oss.str("");
7376     oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
7377     result2 = conn->Query(oss.str().c_str());
7378     if ( !result2 ) throw -4;;
7379     row2 = result2->Next();
7380     thisf = (TString)row2->GetField(0);
7381     if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7382     test = 1;
7383 mocchiut 1.2 // delete result2;
7384 mocchiut 1.1 };
7385 mocchiut 1.2 ss:
7386 mocchiut 1.1 //
7387     prevrht = thisrht;
7388     prevrtt = thisrtt;
7389     previd = thisid;
7390     prevl0id = thisl0id;
7391     row = result->Next();
7392 mocchiut 1.2 // if ( result2 ) delete result2;
7393     // if ( result3 ) delete result3;
7394 mocchiut 1.1 };
7395     //
7396     return(test);
7397     //
7398     };

  ViewVC Help
Powered by ViewVC 1.1.23