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

  ViewVC Help
Powered by ViewVC 1.1.23