/[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.1.1.1 - (hide annotations) (download) (vendor branch)
Tue Sep 23 07:20:33 2008 UTC (16 years, 2 months ago) by mocchiut
Branch: v0r00
CVS Tags: start
Changes since 1.1: +0 -0 lines
Imported sources, 23/09/2008

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

  ViewVC Help
Powered by ViewVC 1.1.23