/[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.30 - (hide annotations) (download)
Mon Dec 28 08:39:24 2009 UTC (14 years, 11 months ago) by mocchiut
Branch: MAIN
Changes since 1.29: +12 -6 lines
Bug in YP gpamela conflict between processes fixed, Q2TH ROOT 5.26 compat bug fixed

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

  ViewVC Help
Powered by ViewVC 1.1.23