/[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.15 - (hide annotations) (download)
Thu Dec 4 09:00:18 2008 UTC (16 years ago) by mocchiut
Branch: MAIN
Changes since 1.14: +3 -2 lines
Piece of run at the end of the file with NO RUNHEADER bug fixed

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

  ViewVC Help
Powered by ViewVC 1.1.23