/[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.3 - (hide annotations) (download)
Thu Sep 25 15:30:10 2008 UTC (16 years, 2 months ago) by mocchiut
Branch: MAIN
Changes since 1.2: +9 -4 lines
Empty run (lastev = -1) bug fixed

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

  ViewVC Help
Powered by ViewVC 1.1.23