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

  ViewVC Help
Powered by ViewVC 1.1.23