/[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.26 - (hide annotations) (download)
Wed Nov 25 09:39:50 2009 UTC (15 years ago) by mocchiut
Branch: MAIN
Changes since 1.25: +39 -0 lines
YodaProfiler: bug in validation of calorimeter calibration fixed

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

  ViewVC Help
Powered by ViewVC 1.1.23