/[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.5 - (hide annotations) (download)
Tue Nov 4 09:44:49 2008 UTC (16 years, 1 month ago) by mocchiut
Branch: MAIN
Changes since 1.4: +86 -368 lines
chewbacca upgrade, YP upgrade

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

  ViewVC Help
Powered by ViewVC 1.1.23