/[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.27 - (hide annotations) (download)
Wed Nov 25 11:19:26 2009 UTC (15 years ago) by mocchiut
Branch: MAIN
Changes since 1.26: +15 -3 lines
YodaProfiler: bug in validation of calorimeter calibration fixed

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

  ViewVC Help
Powered by ViewVC 1.1.23