/[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.10 - (hide annotations) (download)
Fri Nov 7 08:56:13 2008 UTC (16 years, 1 month ago) by mocchiut
Branch: MAIN
Changes since 1.9: +45 -6 lines
Some bugs fixed

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

  ViewVC Help
Powered by ViewVC 1.1.23