/[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.39 - (hide annotations) (download)
Tue Oct 14 12:59:14 2014 UTC (10 years, 1 month ago) by mocchiut
Branch: MAIN
Changes since 1.38: +4 -3 lines
10RED bug fixed: wrong timesync association into GL_ROOT table (back to the future bug)

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

  ViewVC Help
Powered by ViewVC 1.1.23