/[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.29 - (hide annotations) (download)
Wed Dec 23 07:19:32 2009 UTC (14 years, 11 months ago) by mocchiut
Branch: MAIN
Changes since 1.28: +44 -9 lines
New feature in finding BOOT number when missing implemented in YP

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

  ViewVC Help
Powered by ViewVC 1.1.23