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

  ViewVC Help
Powered by ViewVC 1.1.23