/[PAMELA software]/YodaProfiler/src/PamelaDBOperations.cpp
ViewVC logotype

Diff of /YodaProfiler/src/PamelaDBOperations.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.9 by mocchiut, Tue Sep 12 07:28:46 2006 UTC revision 1.25 by mocchiut, Tue Jan 23 17:04:12 2007 UTC
# Line 14  Line 14 
14  #include <TSQLRow.h>  #include <TSQLRow.h>
15  #include <TTree.h>  #include <TTree.h>
16  #include <TGraph.h>  #include <TGraph.h>
17  #include <TDatime.h>  #include <TTimeStamp.h>
18  #include <TF1.h>  #include <TF1.h>
19  //  //
20  #include <EventHeader.h>  #include <EventHeader.h>
# Line 31  Line 31 
31  #include <varDump/VarDumpRecord.h>  #include <varDump/VarDumpRecord.h>
32  #include <physics/S4/S4Event.h>  #include <physics/S4/S4Event.h>
33  //  //
34    #include <sgp4.h>
35    
36  #include <PamelaDBOperations.h>  #include <PamelaDBOperations.h>
37  //  //
38  using namespace std;  using namespace std;
39  using namespace pamela;  using namespace pamela;
40    
41    // Some function to work with cTle stuff.
42    bool compTLE(cTle* tle1, cTle *tle2);
43    float getTleJulian(cTle *);
44    string getTleDatetime(cTle*);
45    
46  /**  /**
47   * Constructor.   * Constructor.
48   * @param host         hostname for the SQL connection.   * @param host         hostname for the SQL connection.
# Line 47  using namespace pamela; Line 54  using namespace pamela;
54   * @param obt0         file obt0.   * @param obt0         file obt0.
55   * @param tsync        file timesync.   * @param tsync        file timesync.
56   * @param debug        debug flag.   * @param debug        debug flag.
57     * @param tlefilename  ascii file with TLE 3 line elements.
58   */   */
59  PamelaDBOperations::PamelaDBOperations(TString host, TString user, TString password, TString filerawname, TString filerootname, UInt_t boot, UInt_t tsync, UInt_t obt0, Bool_t debug){  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){
60    //    //
61    //    //
62    SetConnection(host,user,password);    SetConnection(host,user,password);
# Line 62  PamelaDBOperations::PamelaDBOperations(T Line 70  PamelaDBOperations::PamelaDBOperations(T
70    SetTsync(tsync);    SetTsync(tsync);
71    SetObt0(obt0);    SetObt0(obt0);
72    //    //
73      SetTLEPath(tlefilename);
74      //
75    //    //
76    INSERT_RAW =!filerawname.IsNull();    INSERT_RAW =!filerawname.IsNull();
77    if(INSERT_RAW)SetRawName(filerawname);    if(INSERT_RAW)SetRawName(filerawname);
78    //    //
79    INSERT_ROOT = !filerootname.IsNull();    INSERT_ROOT = !filerootname.IsNull();
80    if( INSERT_ROOT ){    if( INSERT_ROOT ){
81        this->SetRootName(filerootname);
82        this->SetOrbitNo();
83      file = TFile::Open(this->GetRootName().Data());      file = TFile::Open(this->GetRootName().Data());
84      //    if ( !file ) INSERT_ROOT = false;    } else {
85        this->SetRootName("");
86    };    };
   //  this->OpenFile();  
87    //    //
88    this->SetID_RAW(0);    this->SetID_RAW(0);
89    this->SetID_ROOT(0);    this->SetID_ROOT(0);
# Line 100  void PamelaDBOperations::Close(){ Line 112  void PamelaDBOperations::Close(){
112  //  //
113  void PamelaDBOperations::CheckValidate(Long64_t olderthan){  void PamelaDBOperations::CheckValidate(Long64_t olderthan){
114    clean_time = new TDatime();    clean_time = new TDatime();
115      //
116    if(olderthan >= 0){    if(olderthan >= 0){
117      VALIDATE = true;      VALIDATE = true;
118      UInt_t timelim = 0;      UInt_t timelim = 0;
119      timelim =  (UInt_t)clean_time->Convert() - olderthan;      timelim =  (UInt_t)clean_time->Convert(true) - olderthan;
120      clean_time->Set(timelim,false);      clean_time->Set(timelim,false);
121    };    };
122  };  };
# Line 115  void PamelaDBOperations::CheckValidate(L Line 128  void PamelaDBOperations::CheckValidate(L
128   * @param password     password for the SQL connection.   * @param password     password for the SQL connection.
129   */   */
130  void PamelaDBOperations::SetConnection(TString host, TString user, TString password){  void PamelaDBOperations::SetConnection(TString host, TString user, TString password){
131      if ( IsDebug() ) printf(" Connecting using host = %s user = %s password = %s \n",host.Data(),user.Data(),password.Data());
132    conn = TSQLServer::Connect(host.Data(),user.Data(),password.Data());    conn = TSQLServer::Connect(host.Data(),user.Data(),password.Data());
133  };  };
134    
# Line 143  void PamelaDBOperations::SetDebugFlag(Bo Line 157  void PamelaDBOperations::SetDebugFlag(Bo
157  };  };
158    
159  /**  /**
160     * Set the autoboot flag
161     *
162     */
163    void PamelaDBOperations::SetAutoBoot(Bool_t dbg){
164      AUTOBOOT = dbg;
165    };
166    
167    /**
168     * Set the nofrag flag
169     *
170     */
171    void PamelaDBOperations::SetNoFrag(Bool_t nf){
172      NOFRAG = nf;
173    };
174    
175    /**
176   * Store the BOOT number of the RAW file.   * Store the BOOT number of the RAW file.
177   * @param boot    BOOT number of the RAW file   * @param boot    BOOT number of the RAW file
178   */   */
# Line 183  void PamelaDBOperations::SetRootName(TSt Line 213  void PamelaDBOperations::SetRootName(TSt
213  };  };
214    
215  /**  /**
216     * Store the downlink orbit number from filename.
217     */
218    void PamelaDBOperations::SetOrbitNo(){
219      dworbit = 0;
220      TString name = this->GetRootFile();
221      Int_t nlength = name.Length();
222      if ( nlength < 5 ) return;
223      TString dwo = 0;
224      for (Int_t i = 0; i<5; i++){
225        dwo.Append(name[i],1);
226      };
227      if ( dwo.IsDigit() ){
228        dworbit = (UInt_t)dwo.Atoi();
229      } else {
230        dwo="";
231        for (Int_t i = 8; i<13; i++){
232          dwo.Append(name[i],1);
233        };    
234        if ( dwo.IsDigit() ) dworbit = (UInt_t)dwo.Atoi();
235      };
236      if ( IsDebug() ) printf(" Downlink orbit is %i (dwo = %s) \n",dworbit,dwo.Data());
237      return;
238    };
239    
240    
241    
242    /**
243   * Store the NOBOOT flag.   * Store the NOBOOT flag.
244   * @param noboot    true/false.   * @param noboot    true/false.
245   */   */
# Line 191  void PamelaDBOperations::SetNOBOOT(Bool_ Line 248  void PamelaDBOperations::SetNOBOOT(Bool_
248  };  };
249    
250  /**  /**
251     * Store path to the TLE file.
252     */
253    void PamelaDBOperations::SetTLEPath(TString str){
254      tlefilename = str;
255    };
256    
257    /**
258   * Store the olderthan variable   * Store the olderthan variable
259   * @param olderthan   * @param olderthan
260   */   */
# Line 209  Bool_t PamelaDBOperations::SetID_RAW(){ Line 273  Bool_t PamelaDBOperations::SetID_RAW(){
273    oss << "SELECT ID FROM GL_RAW WHERE "    oss << "SELECT ID FROM GL_RAW WHERE "
274        << " PATH = '" << this->GetRawPath().Data() << "' AND "        << " PATH = '" << this->GetRawPath().Data() << "' AND "
275        << " NAME = '" << this->GetRawFile().Data() << "' ";        << " NAME = '" << this->GetRawFile().Data() << "' ";
276    
277    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
278    if ( result == NULL ) throw -4;    if ( result == NULL ) throw -4;
279    row = result->Next();    row = result->Next();
# Line 239  Int_t PamelaDBOperations::SetUpperLimits Line 304  Int_t PamelaDBOperations::SetUpperLimits
304    UInt_t nevent = 0;    UInt_t nevent = 0;
305    UInt_t pktlast = 0;    UInt_t pktlast = 0;
306    UInt_t obtlast = 0;    UInt_t obtlast = 0;
307    UInt_t t_pktlast = 0;    Long64_t t_pktlast = 0LL;
308    UInt_t t_obtlast = 0;    //  UInt_t t_obtlast = 0;
309    UInt_t upperpkt2 = 0;    Long64_t t_obtlast = 0LL;
310    ULong64_t upperobt2 = 0;    Long64_t upperpkt2 = 0LL;
311      Long64_t upperobt2 = 0LL;
312    UInt_t zomp = 0;    UInt_t zomp = 0;
313    UInt_t jump = 50000; // was 5000    UInt_t jump = 50000; // was 5000
314    EventCounter *code=0;    EventCounter *code=0;
315    //    //
316      Long64_t deltapkt = 5000LL;
317      Long64_t deltaobt = 50000LL;
318      //
319    //   pcksList packetsNames;    //   pcksList packetsNames;
320    //   pcksList::iterator Iter;    //   pcksList::iterator Iter;
321    //   getPacketsNames(packetsNames);    //   getPacketsNames(packetsNames);
# Line 283  Int_t PamelaDBOperations::SetUpperLimits Line 352  Int_t PamelaDBOperations::SetUpperLimits
352    upperobt = OBT(obtlast);    upperobt = OBT(obtlast);
353    upperentry = nevent-1;    upperentry = nevent-1;
354    //    //
355    if ( IsDebug() ) printf(" First entries are: OBT %llu pkt_num %i \n",obtfirst,pktfirst);    if ( IsDebug() ) printf(" First entries are: OBT %i pkt_num %i \n",obtfirst,pktfirst);
356    //    //
357    if ( IsDebug() ) printf(" Last entries are: OBT %llu pkt_num %i entry %i\n",upperobt,upperpkt,upperentry);    if ( IsDebug() ) printf(" Last entries are: OBT %lld pkt_num %lld entry %i\n",upperobt,upperpkt,upperentry);
358    //    //
359    if ( (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) > OBT(obtfirst)) || (PKT(pktlast) > PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) ) return(1);    if ( (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) > OBT(obtfirst)) || (PKT(pktlast) > PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) ) return(1);
360    //    //
# Line 293  Int_t PamelaDBOperations::SetUpperLimits Line 362  Int_t PamelaDBOperations::SetUpperLimits
362    //    //
363    if ( nevent < 2 ) return(4);    if ( nevent < 2 ) return(4);
364    //    //
365    if ( PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst) ){    if ( (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) || (labs(PKT(pktlast)-PKT(pktfirst))<deltapkt && labs(OBT(obtlast)-OBT(obtfirst))<deltaobt) ){
366        //
367      // go back      // go back
368      zomp = nevent - 2;      zomp = nevent - 2;
369      //      //
# Line 315  Int_t PamelaDBOperations::SetUpperLimits Line 385  Int_t PamelaDBOperations::SetUpperLimits
385          upperpkt2 = PKT(ph->GetCounter());          upperpkt2 = PKT(ph->GetCounter());
386          upperobt2 = OBT(ph->GetOrbitalTime());          upperobt2 = OBT(ph->GetOrbitalTime());
387          //          //
388          if ( (t_pktlast < upperpkt && t_obtlast > upperobt) || (t_pktlast < upperpkt2 && t_obtlast > upperobt2) ) throw -13;              if ( (t_pktlast < upperpkt && t_obtlast > upperobt) || (t_pktlast < upperpkt2 && t_obtlast > upperobt2) ){
389              if ( IsDebug() ) printf(" .-. upperpkt2 %lld upperobt2 %lld \n",upperpkt2,upperobt2);  
390              if ( IsDebug() ) printf(" .-. upperpkt %lld t_pktlast %lld upperobt %lld t_obtlast %lld \n",upperpkt,t_pktlast,upperobt,t_obtlast);    
391              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);    
392              throw -13;    
393            };
394          //          //
395          if ( t_pktlast < upperpkt && t_obtlast < upperobt && t_pktlast < upperpkt2 && t_obtlast < upperobt2 ){          if ( t_pktlast < upperpkt && t_obtlast < upperobt && t_pktlast < upperpkt2 && t_obtlast < upperobt2 ){
396            zomp = i + jump + 1;            zomp = i + jump + 1;
397            if ( zomp > nevent-2 ) zomp = nevent - 2;            if ( zomp > nevent-2 ) zomp = nevent - 2;
398            if ( IsDebug() ) printf(" .-. jump %i zomp %i upperpkt %i pktlast %i upperobt %llu obtlast %u last entry is %i \n",jump,zomp,upperpkt,pktlast,upperobt,obtlast,i);            if ( IsDebug() ) printf(" .-. jump %i zomp %i upperpkt %lld pktlast %i upperobt %lld obtlast %u last entry is %i \n",jump,zomp,upperpkt,pktlast,upperobt,obtlast,i);
399            break;            break;
400          };          };
401          //          //
# Line 355  Int_t PamelaDBOperations::SetUpperLimits Line 430  Int_t PamelaDBOperations::SetUpperLimits
430    //    //
431    rhev = rh->GetEntries();    rhev = rh->GetEntries();
432    rtev = rt->GetEntries();    rtev = rt->GetEntries();
433    UInt_t sobtt = 0;    Long64_t sobtt = 0LL;
434    UInt_t sobth = 0;    Long64_t sobth = 0LL;
435    UInt_t spktt = 0;    Long64_t spktt = 0LL;
436    UInt_t spkth = 0;    Long64_t spkth = 0LL;
437    UInt_t pktt = 0;    Long64_t pktt = 0LL;
438    ULong64_t obtt = 0;    Long64_t obtt = 0LL;
439    UInt_t pkth = 0;    Long64_t pkth = 0LL;
440    ULong64_t obth = 0;    Long64_t obth = 0LL;
441    //    //
442    T->GetEntry(upperentry);    T->GetEntry(upperentry);
443    code = eh->GetCounter();    code = eh->GetCounter();
# Line 382  Int_t PamelaDBOperations::SetUpperLimits Line 457  Int_t PamelaDBOperations::SetUpperLimits
457      obth = OBT(phh->GetOrbitalTime());      obth = OBT(phh->GetOrbitalTime());
458    };    };
459    //    //
460    if ( IsDebug() ) printf(" rhev before %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);    if ( IsDebug() ) printf(" rhev before %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
461    if ( pkth > upperpkt && obth > upperobt ){    if ( pkth > upperpkt && obth > upperobt ){
462      if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %i upperp %i oh %llu uppero %llu \n",pkth,upperpkt,obth,upperobt);      if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %lld upperp %lld oh %lld uppero %lld \n",pkth,upperpkt,obth,upperobt);
463      upperpkt = pkth;      upperpkt = pkth;
464      upperobt = obth;      upperobt = obth;
465      rhev = lasthead+1;      rhev = lasthead+1;
466    } else {    } else {
467      rhev = lasthead;      rhev = lasthead;
468    };    };
469    if ( IsDebug() ) printf(" rhev after %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);    if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
470    //    //
471    if ( IsDebug() ) printf(" rtev beforev %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);    if ( IsDebug() ) printf(" rtev beforev %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
472    if ( pktt > upperpkt && obtt > upperobt ){    if ( pktt > upperpkt && obtt > upperobt ){
473      if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %i upperp %i ot %llu uppero %llu \n",pktt,upperpkt,obtt,upperobt);      if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %lld upperp %lld ot %lld uppero %lld \n",pktt,upperpkt,obtt,upperobt);
474      upperpkt = pktt;      upperpkt = pktt;
475      upperobt = obtt;      upperobt = obtt;
476      rtev = lasttrail+1;      rtev = lasttrail+1;
477    } else {    } else {
478      rtev = lasttrail;      rtev = lasttrail;
479    };    };
480    if ( IsDebug() ) printf(" rtev after %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);    if ( IsDebug() ) printf(" rtev after %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
481    //  goto kikko;    //  goto kikko;
482    //    //
483    //    //
484    // Check if runtrailer/runheader are within lower limits    // Check if runtrailer/runheader are within lower limits
485    //    //
486    //    //
487    pkth = 0;    pkth = 0LL;
488    obth = 0;    obth = 0LL;
489    spkth = 0;    spkth = 0LL;
490    sobth = 0;    sobth = 0LL;
491    for (Int_t k=0; k<rhev; k++){    for (Int_t k=0; k<rhev; k++){
492      if ( k > 0 ){      if ( k > 0 ){
493        spkth = pkth;        spkth = pkth;
# Line 460  Int_t PamelaDBOperations::SetUpperLimits Line 535  Int_t PamelaDBOperations::SetUpperLimits
535            upperentry = evbefh-1;            upperentry = evbefh-1;
536          };              };    
537        };        };
538        if ( IsDebug() ) printf(" rhev after %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);        if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
539        goto kikko0;        goto kikko0;
540      };      };
541    };    };
# Line 468  Int_t PamelaDBOperations::SetUpperLimits Line 543  Int_t PamelaDBOperations::SetUpperLimits
543    //    //
544    //    //
545    //    //
546    pktt = 0;    pktt = 0LL;
547    obtt = 0;    obtt = 0LL;
548    spktt = 0;    spktt = 0LL;
549    sobtt = 0;    sobtt = 0LL;
550    for (Int_t k=0; k<rtev; k++){    for (Int_t k=0; k<rtev; k++){
551      if ( k > 0 ){      if ( k > 0 ){
552        spktt = pktt;        spktt = pktt;
# Line 491  Int_t PamelaDBOperations::SetUpperLimits Line 566  Int_t PamelaDBOperations::SetUpperLimits
566        rt->GetEntry(rtev);        rt->GetEntry(rtev);
567        pktt = spktt;        pktt = spktt;
568        obtt = sobtt;        obtt = sobtt;
569        if ( IsDebug() ) printf(" lasttrail %i pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);        if ( IsDebug() ) printf(" lasttrail %i pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
570        //        //
571        UInt_t evbeft = 0;        UInt_t evbeft = 0;
572        code = eht->GetCounter();        code = eht->GetCounter();
# Line 520  Int_t PamelaDBOperations::SetUpperLimits Line 595  Int_t PamelaDBOperations::SetUpperLimits
595            upperentry = evbeft-1;            upperentry = evbeft-1;
596          };          };
597        };        };
598        if ( IsDebug() ) printf(" rtev after %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);        if ( IsDebug() ) printf(" rtev after %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
599        goto kikko;        goto kikko;
600        //      break;        //      break;
601        //        //
# Line 548  Int_t PamelaDBOperations::SetUpperLimits Line 623  Int_t PamelaDBOperations::SetUpperLimits
623      obth = OBT(phh->GetOrbitalTime());      obth = OBT(phh->GetOrbitalTime());
624    };    };
625    //    //
626    if ( IsDebug() ) printf(" rhev before %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);    if ( IsDebug() ) printf(" rhev before %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
627    if ( pkth > upperpkt && obth > upperobt ){    if ( pkth > upperpkt && obth > upperobt ){
628      if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %i upperp %i oh %llu uppero %llu \n",pkth,upperpkt,obth,upperobt);      if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %lld upperp %lld oh %lld uppero %lld \n",pkth,upperpkt,obth,upperobt);
629      upperpkt = pkth;      upperpkt = pkth;
630      upperobt = obth;      upperobt = obth;
631      rhev = lasthead+1;      rhev = lasthead+1;
632    } else {    } else {
633      rhev = lasthead;      rhev = lasthead;
634    };    };
635    if ( IsDebug() ) printf(" rhev after %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);    if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
636    //    //
637    if ( IsDebug() ) printf(" rtev beforev %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);    if ( IsDebug() ) printf(" rtev beforev %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
638    if ( pktt > upperpkt && obtt > upperobt ){    if ( pktt > upperpkt && obtt > upperobt ){
639      if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %i upperp %i ot %llu uppero %llu \n",pktt,upperpkt,obtt,upperobt);      if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %lld upperp %lld ot %lld uppero %lld \n",pktt,upperpkt,obtt,upperobt);
640      upperpkt = pktt;      upperpkt = pktt;
641      upperobt = obtt;      upperobt = obtt;
642      rtev = lasttrail+1;      rtev = lasttrail+1;
643    } else {    } else {
644      rtev = lasttrail;      rtev = lasttrail;
645    };    };
646    if ( IsDebug() ) printf(" rtev after %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);    if ( IsDebug() ) printf(" rtev after %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
647    //    //
648    if ( IsDebug() ) printf(" Upper limits are: OBT %llu pkt_num %i upper entry %i \n",upperobt,upperpkt,upperentry);    if ( IsDebug() ) printf(" Upper limits are: OBT %lld pkt_num %lld upper entry %i \n",upperobt,upperpkt,upperentry);
649    //    //
650    return(0);    return(0);
651  }  }
652    
653    /**
654     *
655     * Trick to have unique RUN ID numbers even when runs are deleted and mysql deamon restarted.
656     * Entries in the _RUNID_GEN table are never deleted.
657     *
658     **/
659    UInt_t PamelaDBOperations::AssignRunID(){
660      //
661      TSQLResult *result = 0;
662      TSQLRow *row = 0;
663      UInt_t runid = 0;
664      //
665      stringstream   oss;
666      //  
667      oss.str("");
668      oss << "INSERT INTO _RUNID_GEN VALUES (NULL);";
669      result = conn->Query(oss.str().c_str());
670      if ( !result ) throw -10;
671      oss.str("");
672      oss << "SELECT ID FROM _RUNID_GEN ORDER BY ID DESC LIMIT 1;";
673      result = conn->Query(oss.str().c_str());
674      if ( !result ) throw -10;
675      //
676      row = result->Next();
677      //
678      if ( !row ) throw -28;
679      //
680      runid = (UInt_t)atoll(row->GetField(0));
681      //
682      return(runid);
683    };
684    
685  //  //
686  // GETTERS  // GETTERS
687  //  //
# Line 672  void PamelaDBOperations::CheckConnection Line 779  void PamelaDBOperations::CheckConnection
779    if( !conn ) throw -1;    if( !conn ) throw -1;
780    bool connect = conn->IsConnected();    bool connect = conn->IsConnected();
781    if( !connect ) throw -1;    if( !connect ) throw -1;
782      if ( !dworbit && strcmp(this->GetRootName().Data(),"") ) throw -27;
783      //
784      // set DB timezone to UTC
785      //
786      stringstream oss;
787      //  
788      oss.str("");
789      oss << "SET time_zone='+0:00';";
790      TSQLResult *result = 0;
791      result = conn->Query(oss.str().c_str());
792      if ( !result ) throw -10;
793      //
794  };  };
795    
796  /**  /**
797   * Return the correct packet number if we went back to zero   * Return the correct packet number if we went back to zero
798   */   */
799  UInt_t PamelaDBOperations::PKT(UInt_t pkt_num){    Long64_t PamelaDBOperations::PKT(UInt_t pkt_num){  
800    //    //
801    //  if ( IsDebug() ) printf(" pkt conversion: pkt_num is %u pktfirst is %u (pktfirst - (UInt_t)(16777212/2)) is %u  \n",pkt_num,pktfirst,(pktfirst - (UInt_t)(16777212/2)));    if ( IsDebug() ) printf(" pkt conversion: pkt_num is %u pktfirst is %u  (UInt_t)(16777214/2)) is %u  \n",pkt_num,pktfirst,(UInt_t)(16777214/2));
802    //    //
803    if ( pkt_num < (pktfirst/2) && pktfirst > (16777214/2)  ) return((pkt_num+16777215));    if ( pkt_num < (pktfirst/2) && pktfirst > (16777214/2)  ){
804        if ( IsDebug() ) printf(" rise up pktnum %lld \n",(Long64_t)pkt_num+16777215LL);
805        return((Long64_t)pkt_num+16777215LL);
806      };
807    //    //
808    if ( pkt_num > pktfirst*2 && pkt_num > (16777214/2) ){    if ( pkt_num > pktfirst*2 && pkt_num > (16777214/2) ){
809      if ( (pkt_num-16777215) < 0 ){      if ( IsDebug() ) printf(" rise down pktnum %lld \n",(Long64_t)pkt_num-16777215LL);
810        return((16777215-pkt_num));      return((Long64_t)pkt_num-16777215LL);
     } else {  
       return((pkt_num-16777215));  
     };  
811    };    };
812    //    //
813    return(pkt_num);    if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)pkt_num);
814      return((Long64_t)pkt_num);
815    //    //
816  };  };
817    
818  /**  /**
819   * Return the correct On Board Time if we went back to zero   * Return the correct On Board Time if we went back to zero
820   */   */
821  ULong64_t PamelaDBOperations::OBT(UInt_t obt){    Long64_t PamelaDBOperations::OBT(UInt_t obt){  
822    //    //
823    if ( obt < (obtfirst/2) && obtfirst > (numeric_limits<UInt_t>::max()/2) ) return((ULong64_t)(obt+numeric_limits<UInt_t>::max()));    if ( obt < (obtfirst/2) && obtfirst > (numeric_limits<UInt_t>::max()/2) ) return((Long64_t)(obt+numeric_limits<UInt_t>::max()));
824    //    //
825    if ( obt > (obtfirst*2) && obt > (numeric_limits<UInt_t>::max()/2) ){    if ( obt > (obtfirst*2) && obt > (numeric_limits<UInt_t>::max()/2) ){
826      if ( (obt-numeric_limits<UInt_t>::max()) < 0  ){      return((Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());
       return((ULong64_t)(numeric_limits<UInt_t>::max()-obt));  
     } else {  
       return((ULong64_t)(obt-numeric_limits<UInt_t>::max()));  
     };  
827    };    };
828    //    //
829    return((ULong64_t)obt);    return((Long64_t)obt);
830  };  };
831    
832  /**  /**
# Line 851  Int_t PamelaDBOperations::insertPamelaGL Line 967  Int_t PamelaDBOperations::insertPamelaGL
967    if ( this->GetID_RAW() == 0 )  throw -11;    if ( this->GetID_RAW() == 0 )  throw -11;
968    //    //
969    oss.str("");    oss.str("");
970    oss << "SELECT OFFSET_DATE FROM GL_RESURS_OFFSET WHERE FROM_ID_RAW<= "    oss << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE) FROM GL_RESURS_OFFSET WHERE SPECIAL_FILE='"
971        << id << " AND TO_ID_RAW >= "        << this->GetRawFile().Data() << "';";
       << id << ";";  
972    if ( IsDebug() ) printf(" %s \n",oss.str().c_str());    if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
973    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
974    if ( !result ) throw -10;    if ( !result ) throw -10;
975    row = result->Next();    row = result->Next();
   if ( !row ) throw -10;  
976    //    //
977    t0 = (UInt_t)TDatime(row->GetField(0)).Convert();    if ( !row ){
978        oss.str("");
979        oss << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE) FROM GL_RESURS_OFFSET WHERE FROM_ORBIT< "
980            << dworbit << " order by FROM_ORBIT desc limit 1;";
981        if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
982        result = conn->Query(oss.str().c_str());
983        if ( !result ) throw -10;
984        row = result->Next();
985        if ( !row ) throw -10;
986      };
987      //
988      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);
989      t0 = (UInt_t)tu.GetSec();
990      if ( IsDebug() ) printf(" t0 is %u ti is %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));
991      //
992    /*    /*
993     * Verify that the TIMESYNC have been not already processed     * Verify that the TIMESYNC have been not already processed
994     */     */
# Line 875  Int_t PamelaDBOperations::insertPamelaGL Line 1003  Int_t PamelaDBOperations::insertPamelaGL
1003    if (result == NULL) throw -10;    if (result == NULL) throw -10;
1004    row = result->Next();    row = result->Next();
1005    if ((row != NULL) && ((UInt_t)atoll(row->GetField(0)) > 0)){    if ((row != NULL) && ((UInt_t)atoll(row->GetField(0)) > 0)){
1006        if ( IsDebug() ) printf(" found a timesync t0 is %u \n",t0);
1007      toffset = (UInt_t)atoll(row->GetField(2)) - (UInt_t)(this->OBT((UInt_t)atoll(row->GetField(1)))/1000) + t0;      toffset = (UInt_t)atoll(row->GetField(2)) - (UInt_t)(this->OBT((UInt_t)atoll(row->GetField(1)))/1000) + t0;
1008        //
1009        tsync = (UInt_t)atoll(row->GetField(2));
1010        obt0 = (UInt_t)atoll(row->GetField(1));
1011        //
1012      return(1);      return(1);
1013    };    };
1014    //    //
# Line 932  Int_t PamelaDBOperations::insertPamelaGL Line 1065  Int_t PamelaDBOperations::insertPamelaGL
1065          //          //
1066          TYPE = 55;//224;          TYPE = 55;//224;
1067          //          //
1068            if ( IsDebug() ) printf("mcmd tsync %i tsync %u obt %u \n",i,TSYNC,OBT);
1069            //
1070          if ( TSYNC && OBT ){          if ( TSYNC && OBT ){
1071            existsts = true;            existsts = true;
1072            goto eout;            goto eout;
# Line 954  Int_t PamelaDBOperations::insertPamelaGL Line 1089  Int_t PamelaDBOperations::insertPamelaGL
1089      //      //
1090      rt->SetBranchAddress("RunTrailer", &runt);      rt->SetBranchAddress("RunTrailer", &runt);
1091      //      //
1092      if ( rhev > 0 ){      Int_t nrhev = rh->GetEntries();
1093        rh->GetEntry(0);      Int_t nrtev = rt->GetEntries();
1094        //      if ( IsDebug() ) printf(" ou nevent %i rhev %i rtev %i \n",nevent,nrhev,nrtev);
1095        TSYNC = runh->LAST_TIME_SYNC_INFO;      //
1096        OBT = runh->OBT_TIME_SYNC * 1000;      if ( nrhev > 0 ){
1097        //        for (Int_t i=0; i<nrhev; i++){
1098        TYPE = 20;          //
1099        //          rh->GetEntry(i);
1100        if ( TSYNC && OBT ){          //
1101          existsts = true;          TSYNC = runh->LAST_TIME_SYNC_INFO;
1102          goto eout;          OBT = runh->OBT_TIME_SYNC * 1000;
1103            //
1104            TYPE = 20;
1105            //
1106            if ( IsDebug() ) printf("runheader %i tsync %u obt %u \n",i,TSYNC,OBT);
1107            //
1108            if ( TSYNC && OBT ){
1109              existsts = true;
1110              goto eout;
1111            };
1112        };        };
1113        //        //
1114      };      };
1115      if ( rtev > 0 ){      if ( nrtev > 0 ){
1116        //        //
1117        if ( IsDebug() ) printf(" No runheader \n");        if ( IsDebug() ) printf(" No runheader \n");
1118        signal = 6;        signal = 6;
1119        //        //
1120        rt->GetEntry(0);        for (Int_t i=0; i<nrtev; i++){
1121        //          //
1122        TSYNC = runt->LAST_TYME_SYNC_INFO;          rt->GetEntry(i);
1123        OBT = runt->OBT_TYME_SYNC * 1000;          //
1124        //          TSYNC = runt->LAST_TYME_SYNC_INFO;
1125        TYPE = 21;          OBT = runt->OBT_TYME_SYNC * 1000;
1126        //          //
1127        if ( TSYNC && OBT ){          TYPE = 21;
1128          existsts = true;          //
1129          goto eout;          if ( IsDebug() ) printf("runtrailer %i tsync %u obt %u \n",i,TSYNC,OBT);
1130            //
1131            if ( TSYNC && OBT ){
1132              existsts = true;
1133              goto eout;
1134            };
1135        };        };
1136        //        //
1137      } else {      } else {
# Line 1053  Int_t PamelaDBOperations::insertPamelaGL Line 1202  Int_t PamelaDBOperations::insertPamelaGL
1202    conn->Query(oss.str().c_str());    conn->Query(oss.str().c_str());
1203    if ( IsDebug() ) printf(" Query the GL_TIMESYNC table to fill it:\n %s \n",oss.str().c_str());    if ( IsDebug() ) printf(" Query the GL_TIMESYNC table to fill it:\n %s \n",oss.str().c_str());
1204    //    //
1205      if ( IsDebug() ) printf(" found a timesync t0 is %u \n",t0);
1206    toffset = (UInt_t)TSYNC - (UInt_t)(this->OBT(OBT)/1000) + t0;    toffset = (UInt_t)TSYNC - (UInt_t)(this->OBT(OBT)/1000) + t0;
1207    //    //
1208      tsync = TSYNC;
1209      obt0 = OBT;
1210      //
1211    delete result;    delete result;
1212    return(signal);    return(signal);
1213  }  }
# Line 1154  Int_t PamelaDBOperations::assignBOOT_NUM Line 1307  Int_t PamelaDBOperations::assignBOOT_NUM
1307    VarDumpEvent  *vde = 0;    VarDumpEvent  *vde = 0;
1308    VarDumpRecord *vdr = 0;    VarDumpRecord *vdr = 0;
1309    //    //
1310      Bool_t found = false;
1311    trDumpEv->SetBranchAddress("VarDump", &vde);    trDumpEv->SetBranchAddress("VarDump", &vde);
1312    if ( trDumpEv->GetEntries() > 0 ){    if ( trDumpEv->GetEntries() > 0 ){
1313      Bool_t found = false;      found = false;
1314      for ( Int_t i = 0; i < trDumpEv->GetEntries(); i++){      for ( Int_t i = 0; i < trDumpEv->GetEntries(); i++){
1315        trDumpEv->GetEntry(i);        trDumpEv->GetEntry(i);
1316        vde->Records->GetEntries();        //      vde->Records->GetEntries();
1317        if ( vde->Records->GetEntries()>0 ){        if ( vde->Records->GetEntries()>5 ){
1318          found = true;          found = true;
1319          goto fill;          goto fill;
1320        };        };
# Line 1173  Int_t PamelaDBOperations::assignBOOT_NUM Line 1327  Int_t PamelaDBOperations::assignBOOT_NUM
1327        this->SetBOOTnumber((Int_t)vdr->VAR_VALUE);        this->SetBOOTnumber((Int_t)vdr->VAR_VALUE);
1328        //        //
1329      } else {      } else {
1330        if ( !this->GetBOOTnumber() ) return(4);        if ( !this->GetBOOTnumber() && !this->AutoBoot()) return(4);
1331        };
1332      } else {
1333        if ( !this->GetBOOTnumber() && !this->AutoBoot()) return(2);
1334      };
1335      //
1336      UInt_t bn = 0;
1337      Bool_t afound = false;
1338      if ( !found && this->AutoBoot()){
1339        afound = true;
1340        //
1341        // Search for other files with similar timesync
1342        //
1343        if ( IsDebug() ) printf(" tsync %u obt0 %u \n",tsync,obt0);
1344        UInt_t upperts = tsync-(obt0/1000)+5;
1345        UInt_t lowerts = tsync-(obt0/1000)-5;
1346        oss.str("");
1347        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)<"
1348            << upperts
1349            << " AND TIMESYNC-(OBT0/1000)>"
1350            << lowerts
1351            << " AND GL_RAW.BOOT_NUMBER>0 GROUP BY GL_TIMESYNC.OBT0;";
1352        result = conn->Query(oss.str().c_str());
1353        if ( IsDebug() ) printf(" Query the GL_TIMESYNC table to find boot number:\n %s \n",oss.str().c_str());
1354        //
1355        if ( !result ) throw -4;;
1356        found = true;
1357        if ( result->GetRowCount()<3 ){
1358          if ( IsDebug() ) printf(" AGH! no results!\n");
1359          found = false;
1360        } else {
1361          row = result->Next();      
1362          bn = (UInt_t)atoll(row->GetField(0));
1363          for ( Int_t r=1; r<result->GetRowCount() ;r++){
1364            if ( !row ) throw -4;
1365            if ( IsDebug() ) printf(" BOOT number is %s \n",row->GetField(0));
1366            if ( bn != (UInt_t)atoll(row->GetField(0)) ){
1367              if ( IsDebug() ) printf(" AGH! bn = %u here instead %u \n",bn,(UInt_t)atoll(row->GetField(0)));
1368              found = false;
1369            };
1370            row = result->Next();
1371          };
1372      };      };
1373      };
1374      //
1375      Int_t sgn = 0;
1376      //
1377      if ( !found ){
1378        throw -29;
1379    } else {    } else {
1380      if ( !this->GetBOOTnumber() ) return(2);      if ( afound ){
1381          this->SetBOOTnumber(bn);
1382          sgn = 8;
1383        };
1384    };    };
1385    //    //
1386    oss.str("");    oss.str("");
# Line 1186  Int_t PamelaDBOperations::assignBOOT_NUM Line 1390  Int_t PamelaDBOperations::assignBOOT_NUM
1390    conn->Query(oss.str().c_str());          conn->Query(oss.str().c_str());      
1391    //    //
1392    delete result;    delete result;
1393    return(0);    return(sgn);
1394  };  };
1395    
1396  /**  /**
# Line 1449  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1653  Bool_t PamelaDBOperations::IsRunAlreadyI
1653      if ( glrun->GetNEVENTS() > (UInt_t)atoll(row->GetField(1)) ){      if ( glrun->GetNEVENTS() > (UInt_t)atoll(row->GetField(1)) ){
1654        //        //
1655        if ( IsDebug() ) printf(" The new run has more events than the old one \n");        if ( IsDebug() ) printf(" The new run has more events than the old one \n");
1656        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1657        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1658        if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
1659        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1660    //       conn->Query(oss.str().c_str());
1661        if ( signal ) signal = false;        if ( signal ) signal = false;
1662        goto gonext;              goto gonext;      
1663        //        //
# Line 1466  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1671  Bool_t PamelaDBOperations::IsRunAlreadyI
1671        //        //
1672        if ( IsDebug() ) printf(" The new run has the same number of events and the runheader the old one miss the runheader \n");        if ( IsDebug() ) printf(" The new run has the same number of events and the runheader the old one miss the runheader \n");
1673        //        //
1674        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1675        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1676        if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
1677        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1678    //       conn->Query(oss.str().c_str());
1679        //        //
1680        if ( signal ) signal = false;        if ( signal ) signal = false;
1681        goto gonext;        goto gonext;
# Line 1483  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1689  Bool_t PamelaDBOperations::IsRunAlreadyI
1689        //        //
1690        if ( IsDebug() ) printf(" The new run has the same number of events, the runheader and the runtrailer the old one miss the runtrailer \n");        if ( IsDebug() ) printf(" The new run has the same number of events, the runheader and the runtrailer the old one miss the runtrailer \n");
1691        //        //
1692        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1693        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1694        if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
1695        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1696    //       conn->Query(oss.str().c_str());
1697        if ( signal ) signal = false;        if ( signal ) signal = false;
1698        //        //
1699      };      };
# Line 1501  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1708  Bool_t PamelaDBOperations::IsRunAlreadyI
1708    delete result;    delete result;
1709    //    //
1710    if ( signal && IsDebug() ) printf(" The run has already been inserted \n");        if ( signal && IsDebug() ) printf(" The run has already been inserted \n");    
1711      if ( !signal && IsDebug() ) printf(" The run existed and was deleted, fill the DB \n");
1712    return(signal);    return(signal);
1713  };  };
1714    
# Line 1522  void PamelaDBOperations::HandleRun(){   Line 1730  void PamelaDBOperations::HandleRun(){  
1730      //      //
1731      this->FillClass();      this->FillClass();
1732      //      //
1733      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);      if ( !IsRunAlreadyInserted() ){
1734          glrun->SetID(this->AssignRunID());
1735          glrun->SetID_RUN_FRAG(0);
1736          glrun->Fill_GL_RUN(conn);
1737        };
1738    } else {    } else {
1739      //      //
1740      if ( IsDebug() ) printf(" oh no! the distance between runheader and runtrailer seems wrong: check %llu pktt %llu \n",chkpkt,pktt);      if ( IsDebug() ) printf(" oh no! the distance between runheader and runtrailer seems wrong: check %llu pktt %llu \n",chkpkt,pktt);
# Line 1545  void PamelaDBOperations::HandleRunFragme Line 1757  void PamelaDBOperations::HandleRunFragme
1757    UInt_t rhfirstev = firstev;    UInt_t rhfirstev = firstev;
1758    UInt_t rtlastev = lastev;    UInt_t rtlastev = lastev;
1759    Bool_t found = false;    Bool_t found = false;
1760      Bool_t foundinrun = false;
1761    //    //
1762    TSQLResult *result = 0;    TSQLResult *result = 0;
1763    TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
# Line 1571  void PamelaDBOperations::HandleRunFragme Line 1784  void PamelaDBOperations::HandleRunFragme
1784    //    //
1785    if ( IsDebug() ) printf("The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");    if ( IsDebug() ) printf("The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
1786    //    //
1787      // First of all insert the run in the fragment table...
1788      //
1789      oss.str("");
1790      oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
1791          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
1792          << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
1793          << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
1794          << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
1795          << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
1796          << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
1797          << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
1798          << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1799          << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
1800          << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
1801          << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
1802          << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
1803          << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
1804      //
1805      if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
1806      result = conn->Query(oss.str().c_str());
1807      //
1808      if ( !result ) throw -4;
1809      //
1810      row = result->Next();
1811      //
1812      if ( !row ){
1813        //
1814        // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
1815        //
1816        if ( IsDebug() ) printf(" The run is new \n");
1817        if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
1818        //
1819        glrun->SetID(this->AssignRunID());
1820        glrun->SetID_RUN_FRAG(0);
1821        glrun->Fill_GL_RUN_FRAGMENTS(conn);
1822        //
1823      } else {
1824        if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
1825        return;
1826      };
1827      //
1828      //
1829    // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?    // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
1830    //        //    
1831    if ( mishead && rhfirstev == firstev ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is    if ( mishead && rhfirstev == firstev ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
# Line 1579  void PamelaDBOperations::HandleRunFragme Line 1834  void PamelaDBOperations::HandleRunFragme
1834      oss.str("");      oss.str("");
1835      oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "      oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "
1836          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
1837          << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME()          << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1838            << " ID != " << glrun->ID
1839          << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!          << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
1840      //      //
1841      if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());      if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());
# Line 1589  void PamelaDBOperations::HandleRunFragme Line 1845  void PamelaDBOperations::HandleRunFragme
1845      //      //
1846      row = result->Next();      row = result->Next();
1847      //      //
1848        if ( !row && NoFrag() ){
1849          //
1850          oss.str("");
1851          oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
1852              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
1853              << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1854              << " ID != " << glrun->ID
1855              << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
1856          //
1857          if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
1858          result = conn->Query(oss.str().c_str());
1859          //
1860          if ( !result ) throw -4;
1861          //
1862          foundinrun = true;
1863          //
1864          row = result->Next();
1865          //
1866        };
1867        //
1868      if ( !row ){      if ( !row ){
1869        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
1870        found = false;        found = false;
# Line 1663  void PamelaDBOperations::HandleRunFragme Line 1939  void PamelaDBOperations::HandleRunFragme
1939        //        //
1940        if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");        if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
1941        //        //
1942          if ( foundinrun ){
1943            glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
1944            glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1945          };
1946          //
1947        GL_RUN *glrun1 = new GL_RUN();        GL_RUN *glrun1 = new GL_RUN();
1948        //        //
1949        UInt_t idfrag = (UInt_t)atoll(row->GetField(0));        //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
1950        //        //
1951        oss.str("");        oss.str("");
1952        oss << " ID="<<row->GetField(0)<<";";        oss << " ID="<<row->GetField(0)<<";";
# Line 1694  void PamelaDBOperations::HandleRunFragme Line 1975  void PamelaDBOperations::HandleRunFragme
1975        };        };
1976        if ( IsDebug() ) printf(" Check overlapping events done: %i %i %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);        if ( IsDebug() ) printf(" Check overlapping events done: %i %i %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
1977        //        //
       glrun1->SetID(0);  
1978        glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());        glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
1979        glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());        glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
1980        glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());        glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
# Line 1703  void PamelaDBOperations::HandleRunFragme Line 1983  void PamelaDBOperations::HandleRunFragme
1983        //        //
1984        glrun->SetEV_FROM(firstev);        glrun->SetEV_FROM(firstev);
1985        glrun->SetNEVENTS(lastev-firstev+1);        glrun->SetNEVENTS(lastev-firstev+1);
1986          //
1987        glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());        glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
1988        glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());        glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
1989        glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());        glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
# Line 1722  void PamelaDBOperations::HandleRunFragme Line 2003  void PamelaDBOperations::HandleRunFragme
2003        //        //
2004        if ( !IsRunAlreadyInserted() ){        if ( !IsRunAlreadyInserted() ){
2005          //          //
2006            //      glrun->SetID(this->AssignRunID());
2007            glrun->SetID_RUN_FRAG(glrun1->GetID());
2008          glrun->Fill_GL_RUN(conn);          glrun->Fill_GL_RUN(conn);
2009          //          //
2010          // get id number          // set id number
         //  
         oss.str("");  
         oss << " SELECT ID FROM GL_RUN WHERE BOOT_NUMBER="<<this->GetBOOTnumber()<<" AND "  
             << " RUNHEADER_OBT="<<glrun->GetRUNHEADER_OBT()<<" AND "  
             << " RUNTRAILER_OBT="<<glrun->GetRUNTRAILER_OBT()<<";";  
         //  
         if ( IsDebug() ) printf(" search for idrun0 , query is : \n%s\n",oss.str().c_str());  
         //  
         result =  conn->Query(oss.str().c_str());  
         if ( !result ) throw -4;  
         row = result->Next();  
         //  
         UInt_t idrun0 = 0;  
         if ( !row ){  
           throw -10;  
         } else {  
           idrun0 = (UInt_t)atoll(row->GetField(0));  
         };  
         //  
         glrun1->SetID_RUN_FRAG(idrun0);  
2011          //          //
2012            glrun1->SetID_RUN_FRAG(glrun->GetID());
2013          glrun1->Fill_GL_RUN(conn);          glrun1->Fill_GL_RUN(conn);
2014          //          //
         oss.str("");  
         oss << " SELECT ID FROM GL_RUN WHERE ID_RUN_FRAG="<<idrun0<<" ;";  
         //  
         if ( IsDebug() ) printf(" search for idrun1 , query is : \n%s\n",oss.str().c_str());  
         //  
         result =  conn->Query(oss.str().c_str());  
         if ( !result ) throw -4;  
         row = result->Next();  
         //  
         UInt_t idrun1 = 0;  
         if ( !row ){  
           throw -10;  
         } else {  
           idrun1 = (UInt_t)atoll(row->GetField(0));  
         };  
         //  
         oss.str("");  
         oss << " UPDATE GL_RUN SET ID_RUN_FRAG="<<idrun1<<" WHERE ID="<<idrun0<<" ;";  
         //  
         result =  conn->Query(oss.str().c_str());  
         if ( !result ) throw -4;  
         //  
2015        };        };
       //  
       delete glrun1;  
       //  
2016        // delete old entry in fragment table        // delete old entry in fragment table
2017        //        //
2018        oss.str("");        glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2019          glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2020        //        //
2021        oss << " DELETE FROM GL_RUN_FRAGMENTS WHERE ID = " << idfrag << ";";        delete glrun1;
2022        //        //
       if ( IsDebug() ) printf(" Delete from frag table the old run :\n query is \n %s \n",oss.str().c_str());  
       result =  conn->Query(oss.str().c_str());  
       if ( !result ) throw -4;  
2023        //        //
2024        return;        return;
2025        //        //
# Line 1791  void PamelaDBOperations::HandleRunFragme Line 2028  void PamelaDBOperations::HandleRunFragme
2028    };    };
2029    //    //
2030    if ( mistrail && rtlastev == lastev ) { // look for runtrailer (only when at the end of the file, if at the beginning and the runh is    if ( mistrail && rtlastev == lastev ) { // look for runtrailer (only when at the end of the file, if at the beginning and the runh is
2031                                             // missing it no way we can found a piece in the frag table      // missing it no way we can found a piece in the frag table
2032      //      //
2033      oss.str("");      oss.str("");
2034      oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN_FRAGMENTS WHERE "      oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN_FRAGMENTS WHERE "
2035          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2036          << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME()          << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2037            << " ID != " << glrun->ID
2038          << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";          << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2039      //      //
2040      if ( IsDebug() ) printf(" look for runtrailer in the fragments table: query is \n %s \n",oss.str().c_str());      if ( IsDebug() ) printf(" look for runtrailer in the fragments table: query is \n %s \n",oss.str().c_str());
# Line 1806  void PamelaDBOperations::HandleRunFragme Line 2044  void PamelaDBOperations::HandleRunFragme
2044      //      //
2045      row = result->Next();      row = result->Next();
2046      //      //
2047        if ( !row && NoFrag() ){
2048          //
2049          oss.str("");
2050          oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN WHERE "
2051              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2052              << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2053              << " ID != " << glrun->ID
2054              << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2055          //
2056          if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
2057          result = conn->Query(oss.str().c_str());
2058          //
2059          if ( !result ) throw -4;
2060          //
2061          foundinrun = true;
2062          row = result->Next();
2063          //
2064        };
2065        //
2066      if ( !row ){      if ( !row ){
2067        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2068        found = false;        found = false;
# Line 1879  void PamelaDBOperations::HandleRunFragme Line 2136  void PamelaDBOperations::HandleRunFragme
2136        //        //
2137        if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");        if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
2138        //        //
2139          if ( foundinrun ){
2140            glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2141            glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2142          };
2143          //
2144        GL_RUN *glrun1 = new GL_RUN();        GL_RUN *glrun1 = new GL_RUN();
2145        //        //
2146        UInt_t idfrag = (UInt_t)atoll(row->GetField(0));        //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
2147        //        //
2148        oss.str("");        oss.str("");
2149        oss << " ID="<<row->GetField(0)<<";";        oss << " ID="<<row->GetField(0)<<";";
# Line 1918  void PamelaDBOperations::HandleRunFragme Line 2180  void PamelaDBOperations::HandleRunFragme
2180        glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());        glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());
2181        glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());        glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());
2182        //        //
       glrun1->SetID(0);  
2183        glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());        glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());
2184        glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());        glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());
2185        glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());        glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());
# Line 1938  void PamelaDBOperations::HandleRunFragme Line 2199  void PamelaDBOperations::HandleRunFragme
2199        //        //
2200        if ( !IsRunAlreadyInserted() ){        if ( !IsRunAlreadyInserted() ){
2201          //          //
2202          glrun->Fill_GL_RUN(conn);          //      glrun->SetID(this->AssignRunID());
         //  
         // get id number  
         //  
         oss.str("");  
         oss << " SELECT ID FROM GL_RUN WHERE BOOT_NUMBER="<<this->GetBOOTnumber()<<" AND "  
             << " RUNHEADER_OBT="<<glrun->GetRUNHEADER_OBT()<<" AND "  
             << " RUNTRAILER_OBT="<<glrun->GetRUNTRAILER_OBT()<<";";  
         //  
         if ( IsDebug() ) printf(" search for idrun0 , query is : \n%s\n",oss.str().c_str());  
         //  
         result =  conn->Query(oss.str().c_str());  
         if ( !result ) throw -4;  
         row = result->Next();  
2203          //          //
2204          UInt_t idrun0 = 0;          glrun->SetID_RUN_FRAG(glrun1->GetID());
2205          if ( !row ){          glrun->Fill_GL_RUN(conn);
           throw -10;  
         } else {  
           idrun0 = (UInt_t)atoll(row->GetField(0));  
         };  
2206          //          //
2207          glrun1->SetID_RUN_FRAG(idrun0);          // set id number
2208          //          //
2209            glrun1->SetID_RUN_FRAG(glrun->GetID());
2210          glrun1->Fill_GL_RUN(conn);          glrun1->Fill_GL_RUN(conn);
2211          //          //
         oss.str("");  
         oss << " SELECT ID FROM GL_RUN WHERE ID_RUN_FRAG="<<idrun0<<" ;";  
         //  
         if ( IsDebug() ) printf(" search for idrun1 , query is : \n%s\n",oss.str().c_str());  
         //  
         result =  conn->Query(oss.str().c_str());  
         if ( !result ) throw -4;  
         row = result->Next();  
         //  
         UInt_t idrun1 = 0;  
         if ( !row ){  
           throw -10;  
         } else {  
           idrun1 = (UInt_t)atoll(row->GetField(0));  
         };  
         //  
         oss.str("");  
         oss << " UPDATE GL_RUN SET ID_RUN_FRAG="<<idrun1<<" WHERE ID="<<idrun0<<" ;";  
         //  
         result =  conn->Query(oss.str().c_str());  
         if ( !result ) throw -4;  
         //  
2212        };        };
2213        //        //
2214        delete glrun1;        // delete old entries in fragment table
       //  
       // delete old entry in fragment table  
       //  
       oss.str("");  
       //  
       oss << " DELETE FROM GL_RUN_FRAGMENTS WHERE ID = " << idfrag << ";";  
2215        //        //
2216        if ( IsDebug() ) printf(" Delete from frag table the old run :\n query is \n %s \n",oss.str().c_str());        glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2217        result =  conn->Query(oss.str().c_str());        glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
       if ( !result ) throw -4;  
2218        //        //
2219          delete glrun1;
2220        //        //
2221        return;        return;
2222        //        //
# Line 2036  void PamelaDBOperations::HandleRunFragme Line 2253  void PamelaDBOperations::HandleRunFragme
2253      //      //
2254      row = result->Next();      row = result->Next();
2255      //      //
2256      if ( !row ){      if ( row ){
       //  
       oss.str("");  
       oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "  
           << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("  
           << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "  
           << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("  
           << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "  
           << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("  
           << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "  
           << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "  
           << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "  
           << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("  
           << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "  
           << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("  
           << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "  
           << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";  
       //  
       if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());  
       result = conn->Query(oss.str().c_str());  
       //  
       if ( !result ) throw -4;  
       //  
       row = result->Next();  
       //  
       if ( !row ){  
         //  
         // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)  
         //  
         if ( IsDebug() ) printf(" The run is new \n");  
         if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");  
         //  
         glrun->Fill_GL_RUN_FRAGMENTS(conn);  
         //  
       } else {  
         if ( IsDebug() ) printf(" The run is already present in the fragment table \n");  
       };  
     } else {  
2257        if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");        if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");
2258        } else {
2259          if ( NoFrag() ){
2260            glrun->SetID_RUN_FRAG(glrun->GetID());
2261            glrun->Fill_GL_RUN(conn);      
2262            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2263          };    
2264      };      };
2265    };    };
2266    //    //
# Line 2100  void PamelaDBOperations::HandleMissingHo Line 2286  void PamelaDBOperations::HandleMissingHo
2286      //      //
2287      this->FillClass(mishead,mistrail,firstev,lastev);      this->FillClass(mishead,mistrail,firstev,lastev);
2288      //      //
2289      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);          if ( !IsRunAlreadyInserted() ){
2290          glrun->SetID(this->AssignRunID());
2291          glrun->SetID_RUN_FRAG(0);
2292          glrun->Fill_GL_RUN(conn);    
2293        };
2294      //      //
2295    };    };
2296    //    //
# Line 2267  Bool_t PamelaDBOperations::IsRunConsiste Line 2457  Bool_t PamelaDBOperations::IsRunConsiste
2457            //                  //      
2458            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
2459            //            //
2460            if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                  if ( !IsRunAlreadyInserted() ){
2461                glrun->SetID(this->AssignRunID());
2462                glrun->SetID_RUN_FRAG(0);
2463                glrun->Fill_GL_RUN(conn);      
2464              };
2465            //            //
2466            firstevno = lastentry + 1;            firstevno = lastentry + 1;
2467            //            //
# Line 2343  void PamelaDBOperations::HandleSuspiciou Line 2537  void PamelaDBOperations::HandleSuspiciou
2537      if ( IsDebug() ) printf(" Checking but no events in the run! \n");      if ( IsDebug() ) printf(" Checking but no events in the run! \n");
2538      //      //
2539      this->FillClass();      this->FillClass();
2540      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);          if ( !IsRunAlreadyInserted() ){
2541          glrun->SetID(this->AssignRunID());
2542          glrun->SetID_RUN_FRAG(0);
2543          glrun->Fill_GL_RUN(conn);    
2544        };
2545      //      //
2546    } else {    } else {
2547      //      //
# Line 2371  void PamelaDBOperations::HandleSuspiciou Line 2569  void PamelaDBOperations::HandleSuspiciou
2569        if ( IsDebug() ) printf(" No packets but physics inside the run, I will consider it as good\n");        if ( IsDebug() ) printf(" No packets but physics inside the run, I will consider it as good\n");
2570        //        //
2571        this->FillClass();        this->FillClass();
2572        if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                if ( !IsRunAlreadyInserted() ){
2573            glrun->SetID(this->AssignRunID());
2574            glrun->SetID_RUN_FRAG(0);
2575            glrun->Fill_GL_RUN(conn);        
2576          };
2577        //        //
2578      } else {      } else {
2579        //        //
# Line 2469  void PamelaDBOperations::HandleSuspiciou Line 2671  void PamelaDBOperations::HandleSuspiciou
2671            //                  //      
2672            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
2673            //            //
2674            if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                  if ( !IsRunAlreadyInserted() ){
2675                glrun->SetID(this->AssignRunID());
2676                glrun->SetID_RUN_FRAG(0);
2677                glrun->Fill_GL_RUN(conn);      
2678              };
2679            //            //
2680            if ( i == lastev && checkfirst < check ){ // if the last event gives a wrong check...            if ( i == lastev && checkfirst < check ){ // if the last event gives a wrong check...
2681              //              //
# Line 2504  void PamelaDBOperations::HandleSuspiciou Line 2710  void PamelaDBOperations::HandleSuspiciou
2710              //                  //    
2711              this->SetCommonGLRUN(firstTime,lastTime);              this->SetCommonGLRUN(firstTime,lastTime);
2712              //              //
2713              if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                    if ( !IsRunAlreadyInserted() ){
2714                  glrun->SetID(this->AssignRunID());
2715                  glrun->SetID_RUN_FRAG(0);
2716                  glrun->Fill_GL_RUN(conn);      
2717                };
2718            };            };
2719            //            //
2720            firstevno = lastentry + 1;            firstevno = lastentry + 1;
# Line 2611  Int_t PamelaDBOperations::insertCALO_CAL Line 2821  Int_t PamelaDBOperations::insertCALO_CAL
2821                // no calibrations in the db contain our calibration                // no calibrations in the db contain our calibration
2822                //                //
2823                if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB for section %i \n",section);                if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB for section %i \n",section);
2824                if ( fromtime < 1150863400 ){                if ( fromtime < 1150871000 ){ //1150866904
2825                  if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);                  if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);
2826                  fromtime = 0;// the first flight calibration was taken at about  1156429100 s, this line allow to analyze first runs in raw mode                  fromtime = 0;// the first flight calibration was taken at about  1156429100 s, this line allow to analyze first runs in raw mode
2827                };                };
# Line 2756  void PamelaDBOperations::HandleTRK_CALIB Line 2966  void PamelaDBOperations::HandleTRK_CALIB
2966        // no calibrations in the db contain our calibration        // no calibrations in the db contain our calibration
2967        //        //
2968        if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB\n");        if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB\n");
2969        if ( fromtime < 1150863400 ) fromtime = 0; // the first flight calibration was taken at about 1150863300 s, this line allows to analyze first runs in raw mode        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
2970        //        //
2971        oss.str("");        oss.str("");
2972        oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "        oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "
# Line 2885  Int_t PamelaDBOperations::insertTRK_CALI Line 3095  Int_t PamelaDBOperations::insertTRK_CALI
3095      pkt1 = ph1->GetCounter();        pkt1 = ph1->GetCounter();  
3096      fromtime = this->GetAbsTime(ph1->GetOrbitalTime());        fromtime = this->GetAbsTime(ph1->GetOrbitalTime());  
3097      //      //
3098      valid = 1;  //     valid = 1;
3099      //  //     //
3100      if ( caltrk1->unpackError != 0 && caltrk1->good0 == 0 ) valid = 0;// CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT1  //     if ( caltrk1->unpackError != 0 && caltrk1->good0 == 0 ) valid = 0;// CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT1
3101      //      //
3102      //      //
3103      if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->OBT(obt1) >= this->OBT(obtfirst) ){      if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->OBT(obt1) >= this->OBT(obtfirst) ){
3104        //        //
3105        if ( IsDebug() ) printf(" Trk calibration1 at time %i obt %i pkt %i \n",fromtime,obt1,pkt1);        if ( IsDebug() ) printf(" Trk calibration1 at time %i obt %i pkt %i \n",fromtime,obt1,pkt1);
3106          //      
3107          valid = ValidateTrkCalib( caltrk1, eh1 );
3108          if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;
3109        //        //
3110        // Do we have the second calibration packet?        // Do we have the second calibration packet?
3111        //        //
# Line 2909  Int_t PamelaDBOperations::insertTRK_CALI Line 3122  Int_t PamelaDBOperations::insertTRK_CALI
3122            obt2 = ph2->GetOrbitalTime();              obt2 = ph2->GetOrbitalTime();  
3123            pkt2 = ph2->GetCounter();              pkt2 = ph2->GetCounter();  
3124            //            //
3125            if ( caltrk2->unpackError != 0 || caltrk2->good0 == 0 ) valid = 0; // CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT2  //        if ( caltrk2->unpackError != 0 || caltrk2->good0 == 0 ) valid = 0; // CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT2
3126            //                  //      
3127          } else {          } else {
3128            //            //
# Line 2940  Int_t PamelaDBOperations::insertTRK_CALI Line 3153  Int_t PamelaDBOperations::insertTRK_CALI
3153          //          //
3154          if ( IsDebug() ) printf(" The trk calibration2 at obt %i pkt %i t2 is %i is good \n",obt2,pkt2,t2);          if ( IsDebug() ) printf(" The trk calibration2 at obt %i pkt %i t2 is %i is good \n",obt2,pkt2,t2);
3155          //          //
3156            UInt_t valid2 = ValidateTrkCalib( caltrk2, eh2 );
3157            if ( IsDebug() ) cout << " pkt2 validation --> "<<valid2<<endl;
3158            valid = valid & valid2;
3159            //
3160          // Handle good calib          // Handle good calib
3161          //          //
3162          this->HandleTRK_CALIB(true,true);          this->HandleTRK_CALIB(true,true);
# Line 3112  Int_t PamelaDBOperations::insertS4_CALIB Line 3329  Int_t PamelaDBOperations::insertS4_CALIB
3329            // no calibrations in the db contain our calibration            // no calibrations in the db contain our calibration
3330            //            //
3331            if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB \n");            if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB \n");
3332            if ( fromtime < 1150863400 ){            if ( fromtime < 1150871000 ){  
3333              if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);              if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);
3334              fromtime = 0;// the first flight calibration was taken at about  1156429100 s, this line allow to analyze first runs in raw mode              fromtime = 0;// the first flight calibration was taken at about  1156429100 s, this line allow to analyze first runs in raw mode
3335            };            };
# Line 3185  Int_t PamelaDBOperations::insertS4_CALIB Line 3402  Int_t PamelaDBOperations::insertS4_CALIB
3402   * Scan the fragment table and move old fragments to the GL_RUN table   * Scan the fragment table and move old fragments to the GL_RUN table
3403   */   */
3404  Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(){  Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(){
3405      return(this->CleanGL_RUN_FRAGMENTS(""));
3406    };
3407    
3408    /**
3409     * Scan the fragment table and move old fragments to the GL_RUN table
3410     */
3411    Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(TString fcleanfile){
3412    //    //
3413    TSQLResult *result = 0;    TSQLResult *result = 0;
3414    TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
# Line 3192  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 3416  Int_t PamelaDBOperations::CleanGL_RUN_FR
3416    TSQLRow    *row2   = 0;    TSQLRow    *row2   = 0;
3417    //    //
3418    UInt_t moved = 0;    UInt_t moved = 0;
 //  UInt_t timelim = 0;  
 //  TDatime *time = new TDatime();  
3419    //    //
3420    stringstream oss;    stringstream oss;
3421    oss.str("");    oss.str("");
3422    //    //
3423    //    if ( !strcmp(fcleanfile.Data(),"") ){
3424    // check if there are entries older than "olderthan" seconds from now      //
3425    //      // check if there are entries older than "olderthan" seconds from now
3426    oss.str("");      //
3427    oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"      oss.str("");
3428        << " INSERT_TIME <= '" << clean_time->AsSQLString() << "';";      oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
3429    //          << " INSERT_TIME <= '" << clean_time->AsSQLString() << "';";
3430    if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS runs older than %s : query is \n %s \n",clean_time->AsSQLString(),oss.str().c_str());      //
3431    result = conn->Query(oss.str().c_str());      if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS runs older than %s : query is \n %s \n",clean_time->AsSQLString(),oss.str().c_str());
3432        result = conn->Query(oss.str().c_str());
3433        //
3434      } else {
3435        oss.str("");
3436        oss << " SELECT ID FROM GL_ROOT WHERE NAME='" << fcleanfile.Data() << "';";
3437        if ( IsDebug() ) printf(" Getting ID_ROOT_L0 query %s \n",oss.str().c_str());
3438        result = conn->Query(oss.str().c_str());
3439        //    
3440        if ( result ){
3441          //
3442          row = result->Next();
3443          //
3444          if ( row ){
3445            oss.str("");
3446            oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
3447                << " ID_ROOT_L0=" << row->GetField(0) << ";";
3448            //
3449            if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS for ROOT file query is \n %s \n",oss.str().c_str());
3450            result = conn->Query(oss.str().c_str());
3451            //    
3452          };
3453        } else {
3454          return(2);
3455        };
3456      };
3457    //    //
3458    if ( result ){    if ( result ){
3459      //      //
3460      row = result->Next();      row = result->Next();
3461      //      //
3462      if ( row ){      while ( row ){
3463        //        //
3464        oss.str("");        oss.str("");
3465        oss << " ID= "<< row->GetField(0);        oss << " ID= "<< row->GetField(0);
# Line 3247  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 3494  Int_t PamelaDBOperations::CleanGL_RUN_FR
3494          if ( IsDebug() ) printf(" The run is new \n");          if ( IsDebug() ) printf(" The run is new \n");
3495          if ( IsDebug() ) printf(" -> fill the DB \n");                if ( IsDebug() ) printf(" -> fill the DB \n");      
3496          //          //
3497          glrun->SetID(0);          //      glrun->SetID(this->AssignRunID()); we use the old run number!
3498            glrun->SetID_RUN_FRAG(glrun->GetID());
3499          glrun->Fill_GL_RUN(conn);            glrun->Fill_GL_RUN(conn);  
3500          //          //
3501          oss.str("");  //      oss.str("");
3502          oss << " SELECT ID FROM GL_RUN WHERE "  //      oss << " SELECT ID FROM GL_RUN WHERE "
3503              << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "  //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
3504              << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "  //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
3505              << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "  //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
3506              << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "  //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
3507              << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";  //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
3508          //  //      //
3509          if ( IsDebug() ) printf(" Look for the ID of the inserted run: query is \n %s \n",oss.str().c_str());  //      if ( IsDebug() ) printf(" Look for the ID of the inserted run: query is \n %s \n",oss.str().c_str());
3510          result2 = conn->Query(oss.str().c_str());  //      result2 = conn->Query(oss.str().c_str());
3511          //  //      //
3512          if ( !result2 ) throw -4;  //      if ( !result2 ) throw -4;
3513          //  //      //
3514          row2 = result2->Next();  //      row2 = result2->Next();
3515          //  //      //
3516          if ( !row2 ) throw -25;  //      if ( !row2 ) throw -25;
3517          //  //      //
3518          oss.str("");  //      oss.str("");
3519          oss << " UPDATE GL_RUN SET ID_RUN_FRAG = " << row2->GetField(0) << " WHERE ID = " << row2->GetField(0);  //      oss << " UPDATE GL_RUN SET ID_RUN_FRAG = " << row2->GetField(0) << " WHERE ID = " << row2->GetField(0);
3520          if ( IsDebug() ) printf(" Update the ID_RUN_FRAG of the inserted run: query is \n %s \n",oss.str().c_str());  //      if ( IsDebug() ) printf(" Update the ID_RUN_FRAG of the inserted run: query is \n %s \n",oss.str().c_str());
3521          result2 = conn->Query(oss.str().c_str());  //      result2 = conn->Query(oss.str().c_str());
3522          //  //      //
3523          if ( !result2 ) throw -4;  //      if ( !result2 ) throw -4;
3524          //          //
3525          moved++;          moved++;
3526          //          //
# Line 3282  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 3530  Int_t PamelaDBOperations::CleanGL_RUN_FR
3530        if ( IsDebug() ) printf(" Delete run %s from the GL_RUN_FRAGMENTS table \n",row->GetField(0));              if ( IsDebug() ) printf(" Delete run %s from the GL_RUN_FRAGMENTS table \n",row->GetField(0));      
3531        //        //
3532        //        //
3533        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3534        oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);  //      oss.str("");
3535        if ( IsDebug() ) printf(" Clean the GL_RUN_FRAGMENTS table: query is \n %s \n",oss.str().c_str());  //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);
3536        result2 = conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" Clean the GL_RUN_FRAGMENTS table: query is \n %s \n",oss.str().c_str());
3537        //  //       result2 = conn->Query(oss.str().c_str());
3538        if ( !result2 ) throw -4;  //      //
3539        //  //      if ( !result2 ) throw -4;
3540    //      //
3541          row = result->Next();
3542      };      };
3543    };    };
3544    if ( IsDebug() ) printf(" Moved %u runs\n",moved);    if ( IsDebug() ) printf(" Moved %u runs\n",moved);
# Line 3299  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 3549  Int_t PamelaDBOperations::CleanGL_RUN_FR
3549   * Check if runs are good, i.e. if the tracker calibration is correctly associated..   * Check if runs are good, i.e. if the tracker calibration is correctly associated..
3550   */   */
3551  Int_t PamelaDBOperations::ValidateRuns(){  Int_t PamelaDBOperations::ValidateRuns(){
3552      return(this->ValidateRuns(""));
3553    };
3554    
3555    /**
3556     * Check if runs are good, i.e. if the tracker calibration is correctly associated..
3557     */
3558    Int_t PamelaDBOperations::ValidateRuns(TString valfile){
3559    //    //
3560    TSQLResult *result = 0;    TSQLResult *result = 0;
3561    TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
3562    //    //
3563      UInt_t calibtime = 50;
3564      //
3565    stringstream oss;    stringstream oss;
3566    oss.str("");    oss.str("");
3567    //    //
# Line 3311  Int_t PamelaDBOperations::ValidateRuns() Line 3570  Int_t PamelaDBOperations::ValidateRuns()
3570    // =======================================================    // =======================================================
3571    UInt_t t_stop  = 0;    UInt_t t_stop  = 0;
3572    UInt_t t_start = 0;    UInt_t t_start = 0;
3573    // --------------------------------------------------------------    if ( !strcmp(valfile.Data(),"") ) {
3574    // 1) get the OBT of the last run inserted after clean-time limit      // --------------------------------------------------------------
3575    // --------------------------------------------------------------      // 1) get the OBT of the last run inserted after clean-time limit
3576    oss.str("");      // --------------------------------------------------------------
3577    oss << " SELECT * FROM GL_RUN  WHERE INSERT_TIME <= '" << clean_time->AsSQLString()      oss.str("");
3578            << "' ORDER BY RUNHEADER_TIME DESC LIMIT 1;";      oss << " SELECT * FROM GL_RUN  WHERE INSERT_TIME <= '" << clean_time->AsSQLString()
3579    if ( IsDebug() ) printf(" Get start validation-time: query is \n %s \n",oss.str().c_str());          << "' ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
3580    result = conn->Query(oss.str().c_str());      if ( IsDebug() ) printf(" Get start validation-time: query is \n %s \n",oss.str().c_str());
3581    if ( !result ) throw -4;      result = conn->Query(oss.str().c_str());
3582    if ( !result->GetRowCount() ) {      if ( !result ) throw -4;
3583            printf(" No runs to validate \n");      if ( !result->GetRowCount() ) {
3584            return(1);        printf(" No runs to validate \n");
3585    }else{        return(1);
3586          row = result->Next();      }else{
3587          t_start = (UInt_t)atoll(row->GetField(4));        row = result->Next();
3588    };          t_start = (UInt_t)atoll(row->GetField(4));
3589    // --------------------------------------------------------------      };  
3590    // 2) get the OBT of the last validated run      // --------------------------------------------------------------
3591    // --------------------------------------------------------------      // 2) get the OBT of the last validated run
3592    oss.str("");      // --------------------------------------------------------------
3593    oss << " SELECT * FROM GL_RUN  WHERE VALIDATION=1 AND RUNHEADER_TIME<="<< t_start      oss.str("");
3594        <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";      oss << " SELECT * FROM GL_RUN  WHERE VALIDATION=1 AND RUNHEADER_TIME<="<< t_start
3595    if ( IsDebug() ) printf(" Get stop validation-time: query is \n %s \n",oss.str().c_str());          <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
3596    result = conn->Query(oss.str().c_str());      if ( IsDebug() ) printf(" Get stop validation-time: query is \n %s \n",oss.str().c_str());
3597    if ( !result ) throw -4;      result = conn->Query(oss.str().c_str());
3598    if ( result->GetRowCount() ){      if ( !result ) throw -4;
3599            row = result->Next();      if ( result->GetRowCount() ){
3600            t_stop = (UInt_t)atoll(row->GetField(4));        row = result->Next();
3601          t_stop = (UInt_t)atoll(row->GetField(4));
3602        };
3603        if ( IsDebug() ) printf("Validation interval: from time %i - to time %i \n\n",t_stop,t_start);
3604        // --------------------------------------------------------------
3605        // now retrieves runs to be validated
3606        // --------------------------------------------------------------
3607        oss.str("");
3608        oss << " SELECT * FROM GL_RUN  WHERE  RUNHEADER_TIME <=" << t_start;
3609        oss << " AND RUNHEADER_TIME >="<< t_stop;
3610        oss << " ORDER BY RUNHEADER_TIME DESC;";
3611        if ( IsDebug() )printf(" Check runs for validation: query is \n %s \n",oss.str().c_str());
3612        result = conn->Query(oss.str().c_str());
3613      } else {
3614        //
3615        stringstream myquery;
3616        UInt_t myid = 0;
3617        myquery.str("");
3618        myquery << " SELECT ID FROM GL_ROOT where NAME='"<<valfile.Data() <<"';";
3619        //
3620        result = conn->Query(myquery.str().c_str());
3621        //
3622        row = result->Next();      
3623        if( !row ){
3624          if ( strcmp(valfile.Data(),GetRootName().Data()) ){
3625            if ( IsDebug() ) printf(" No file to be validated even if option \"-validate file\" was used!!\n");
3626            return(2);
3627          };
3628          if ( IsDebug() ) printf(" No file to be validated (force mode)! \n");
3629          return(0);
3630        };
3631        myid=(UInt_t)atoll(row->GetField(0));
3632        //
3633        myquery.str("");
3634        myquery << " SELECT MAX(RUNTRAILER_TIME),MIN(RUNHEADER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< myid <<";";
3635        //
3636        result = conn->Query(myquery.str().c_str());
3637        //
3638        row = result->Next();      
3639        if( !row->GetField(0) || !row->GetField(1)){
3640          //
3641          if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
3642          //
3643          return(0);
3644          //
3645        } else {  
3646          //
3647          UInt_t runhtime = (UInt_t)atoll(row->GetField(0));
3648          UInt_t runttime = (UInt_t)atoll(row->GetField(1));
3649          UInt_t caltime = 0;
3650          //
3651          myquery.str("");
3652          myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
3653          myquery << " order by FROM_TIME asc limit 1;";
3654          //
3655          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
3656          //
3657          //
3658          result = conn->Query(myquery.str().c_str());
3659          //
3660          row = result->Next();      
3661          if( !row ){
3662            caltime = runhtime;
3663          } else {
3664            caltime = (UInt_t)atoll(row->GetField(0));
3665          };
3666          //
3667          myquery.str("");
3668          myquery << " SELECT * from GL_RUN where RUNHEADER_TIME>="<< runttime <<" AND RUNHEADER_TIME<=" ;
3669          myquery << caltime << " order by RUNHEADER_TIME DESC";
3670          //
3671          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
3672          //
3673          result = conn->Query(myquery.str().c_str());
3674          //
3675        };
3676    };    };
3677    if ( IsDebug() ) printf("Validation interval: from time %i - to time %i \n\n",t_stop,t_start);    //
   // --------------------------------------------------------------  
   // now retrieves runs to be validated  
   // --------------------------------------------------------------  
   oss.str("");  
   oss << " SELECT * FROM GL_RUN  WHERE  RUNHEADER_TIME <=" << t_start;  
   oss << " AND RUNHEADER_TIME >="<< t_stop;  
   oss << " ORDER BY RUNHEADER_TIME DESC;";  
 //  if ( IsDebug() )  
   if ( IsDebug() )printf(" Check runs for validation: query is \n %s \n",oss.str().c_str());  
   result = conn->Query(oss.str().c_str());  
3678    if ( !result ) throw -4;    if ( !result ) throw -4;
3679    if ( !result->GetRowCount() ) printf(" No runs to validate \n");    if ( !result->GetRowCount() && IsDebug() ) printf(" No runs to validate \n");
3680  //  printf("------------------------------------------------------------------------------- \n");    //
     
3681    Int_t nrow = 0;    Int_t nrow = 0;
3682    GL_RUN* this_run = new GL_RUN();    GL_RUN* this_run = new GL_RUN();
3683    GL_RUN* next_run = new GL_RUN();    GL_RUN* next_run = new GL_RUN();
# Line 3368  Int_t PamelaDBOperations::ValidateRuns() Line 3691  Int_t PamelaDBOperations::ValidateRuns()
3691    UInt_t t1=0,t2=0;    UInt_t t1=0,t2=0;
3692    // ---------------------------------------------------------------------------------    // ---------------------------------------------------------------------------------
3693    // - loop over runs, back in time,    // - loop over runs, back in time,
3694    // - select sequences of runs close in time (less than 60 s apart),    // - select sequences of runs close in time (less than calibtime s apart),
3695    //   which could be preceeded by a calibration    //   which could be preceeded by a calibration
3696    // - check if there might be a missing calibration    // - check if there might be a missing calibration
3697    // ---------------------------------------------------------------------------------    // ---------------------------------------------------------------------------------
# Line 3408  Int_t PamelaDBOperations::ValidateRuns() Line 3731  Int_t PamelaDBOperations::ValidateRuns()
3731                                                        
3732                            if( this_run->ID == next_run->ID_RUN_FRAG ) interval = 0;     //=> run fragments                            if( this_run->ID == next_run->ID_RUN_FRAG ) interval = 0;     //=> run fragments
3733                                                        
3734                            if( interval >= 60 )CHECK = true;                     //more than 60 s => there might be a calibration                            if( interval >= calibtime )CHECK = true;                      //more than calibtime s => there might be a calibration
3735                                                        
3736                            if( !CHECK && this_run->VALIDATION ){                            if( !CHECK && this_run->VALIDATION ){
3737                                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);                                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
# Line 3523  Int_t PamelaDBOperations::assignVALIDATI Line 3846  Int_t PamelaDBOperations::assignVALIDATI
3846    
3847    
3848    
3849    // Insert TLEs from file tlefilename in the table GL_TLE in the db
3850    // opened by conn, sorting them by date from older to newer, if each
3851    // TLE has not been alread inserted.
3852    Int_t PamelaDBOperations::populateTLE()//(TSQLServer *conn, char *tleFile)
3853    {
3854      fstream tlefile(tlefilename, ios::in);
3855    
3856      if ( !tlefile ) throw -7;
3857    
3858      vector<cTle*> ctles;
3859      vector<cTle*>::iterator iter;
3860      int present = 0;
3861    
3862      // Get three lines from tlefile, create a cTle object and put it
3863      // into ctles
3864      while(1) {
3865        cTle *tlef;
3866        string str1, str2, str3;
3867    
3868        getline(tlefile, str1);
3869        if(tlefile.eof()) break;
3870    
3871        getline(tlefile, str2);
3872        if(tlefile.eof()) break;
3873    
3874        getline(tlefile, str3);
3875        if(tlefile.eof()) break;
3876    
3877        // We now have three good lines for a cTle.
3878        tlef = new cTle(str1, str2, str3);
3879        ctles.push_back(tlef);
3880      }
3881    
3882      tlefile.close();
3883    
3884      // Sort by date
3885      sort(ctles.begin(), ctles.end(), compTLE);
3886    
3887      // Now we insert each TLE into the db
3888      for(iter = ctles.begin(); iter != ctles.end(); iter++) {
3889        cTle *tle = *iter;
3890    
3891        // Do nothing if it's already present in the db.  Just increase
3892        // the counter present.
3893        if (! isTlePresent(tle))
3894          {
3895            int status = insertTle(tle);
3896    
3897            // Insert query failed.  Return 1.
3898            if(status == EXIT_FAILURE) {
3899              
3900              if( IsDebug() ) {
3901                cerr << "Error: inserting TLE:" << endl
3902                     << tle->getName() << endl
3903                     << tle->getLine1() << endl
3904                     << tle->getLine2() << endl;
3905              }
3906    
3907              throw -4;
3908              return 1;
3909            }
3910    
3911          }
3912        else
3913          present++;
3914    
3915      }
3916    
3917      int inserted = ctles.size() - present;  // Number of inserted TLE.
3918      if ( IsDebug() )
3919        cout << "\nProcessed TLEs ranging from " << getTleDatetime(ctles[0]) << " to " << getTleDatetime(ctles[ctles.size()-1]) << "." << endl
3920             << inserted << " newly inserted TLEs out of " << ctles.size() << " processed." << endl;
3921    
3922      ctles.clear();
3923    
3924    
3925      // Return 2 if no new TLE has been inserted.  0 otherwise.
3926      if(! inserted ) return 2;
3927      return 0;
3928    }
3929    
3930    
3931    // Insert tle in the table GL_TLE using the connection conn.
3932    Int_t PamelaDBOperations::insertTle(cTle *tle)
3933    {
3934      stringstream oss;
3935      TSQLResult *result = 0;
3936    
3937      oss.str("");
3938      oss << " INSERT INTO GL_TLE (TLE1, TLE2, TLE3, FROM_TIME)"
3939          << " VALUES ( '"
3940          << tle->getName() << "', '"
3941          << tle->getLine1() << "', '"
3942          << tle->getLine2() << "', '"
3943          << getTleDatetime(tle) << "')";
3944    
3945      //  cout << oss.str().c_str() << endl;
3946      result = conn->Query(oss.str().c_str());
3947      if (result == NULL)
3948        return EXIT_FAILURE;
3949    
3950      return EXIT_SUCCESS;
3951    }
3952    
3953    
3954    // Return whether tle is already in the db connected by conn.
3955    bool PamelaDBOperations::isTlePresent(cTle *tle)
3956    {
3957      stringstream oss;
3958      TSQLResult *result = 0;
3959    
3960      oss.str("");
3961      oss << "SELECT * FROM GL_TLE WHERE FROM_TIME = '"
3962          << getTleDatetime(tle) << "'";
3963    
3964      result = conn->Query(oss.str().c_str());
3965      if (result == NULL) throw -4;
3966    
3967      if (result->GetRowCount())
3968        return true;
3969      else
3970        return false;
3971    }
3972    
3973    
3974    // Return whether the first TLE is dated early than the second
3975    bool compTLE (cTle *tle1, cTle *tle2)
3976    {
3977      return getTleJulian(tle1) < getTleJulian(tle2);
3978    }
3979    
3980    
3981    // Return the date of the tle using the format (year-2000)*1e3 +
3982    // julian day.  e.g. 6365 is the 31th Dec 2006.
3983    // It does *not* return a cJulian date.
3984    float getTleJulian(cTle *tle) {
3985      return tle->getField(cTle::FLD_EPOCHYEAR)*1e3 + tle->getField(cTle::FLD_EPOCHDAY);
3986    }
3987    
3988    
3989    // Return a string like YYYY-MM-DD hh:mm:ss, usable for mysql datetime
3990    // format.
3991    string getTleDatetime(cTle *tle)
3992    {
3993      int year, mon, day, hh, mm, ss;
3994      double dom; // day of month (is double!)
3995      stringstream date; // date in datetime format
3996    
3997      // create a cJulian from the date in tle
3998      cJulian jdate = cJulian( 2000 + (int) tle->getField(cTle::FLD_EPOCHYEAR), tle->getField(cTle::FLD_EPOCHDAY));
3999    
4000      // get year, month, day of month
4001      jdate.getComponent(&year, &mon, &dom);
4002    
4003      // build a datetime YYYY-MM-DD hh:mm:ss
4004      date.str("");
4005      day = (int) floor(dom);
4006      hh = (int) floor( (dom - day) * 24);
4007      mm = (int) floor( ((dom - day) * 24 - hh) * 60);
4008      ss = (int) floor( ((((dom - day) * 24 - hh) * 60 - mm) * 60));
4009      //  ms = (int) floor( (((((dom - day) * 24 - hh) * 60 - mm) * 60) - ss) * 1000);
4010    
4011      date << year << "-" << mon << "-" << day << " " << hh << ":" << mm << ":" << ss;
4012    
4013      return date.str();
4014    }
4015    
4016    /**
4017     * Remove a file from the DB, delete on cascade all entries related to that file
4018     * rearrange GL_RUN and GL_XXX_CALIB tables, turn off validation till the following
4019     * calibration
4020     **/
4021    Int_t PamelaDBOperations::removeFile(TString remfile){
4022      //
4023      // Determine ID_ROOT_L0 and ID_RAW
4024      //
4025      TSQLResult *pResult;
4026      TSQLRow *Row;
4027      stringstream myquery;
4028      //  
4029      myquery.str("");
4030      myquery << " SELECT ID, ID_RAW FROM GL_ROOT where NAME='"<<remfile.Data() <<"';";
4031      //
4032      pResult = conn->Query(myquery.str().c_str());
4033      //
4034      Row = pResult->Next();      
4035      if( !Row ){
4036        if ( strcmp(remfile.Data(),GetRootName().Data()) ){
4037          if ( IsDebug() ) printf(" No file to be removed even if option \"-remove file\" was used!!\n");
4038          return(1);
4039        };
4040        if ( IsDebug() ) printf(" No file to be removed (force mode)! \n");
4041        return(0);
4042      };
4043      //
4044      this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));
4045      this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));
4046      //
4047      this->ValidationOFF();
4048      //
4049      this->RemoveCALIBS();
4050      //
4051      this->RemoveRUNS();
4052      //
4053      this->RemoveFILES();
4054      //
4055      this->SetID_ROOT(0);
4056      this->SetID_RAW(0);
4057      //
4058      return(0);
4059    };
4060    
4061    /**
4062     *
4063     * Set validation bit to zero for runs following the removing file till
4064     * 1) a run with TRK_CALIB_USED=140
4065     * 2) a run with VALIDATION = 0
4066     * 3) the next calibration
4067     *
4068     **/
4069    void PamelaDBOperations::ValidationOFF(){
4070      TSQLResult *pResult;
4071      TSQLRow *Row;
4072      stringstream myquery;
4073      Int_t unv = 0;
4074      //select ID from GL_RUN where RUNHEADER_TIME>=1152671382 AND (VALIDATION=0 OR TRK_CALIB_USED=104) order by RUNHEADER_TIME asc limit 1;
4075      myquery.str("");
4076      myquery << " SELECT MAX(RUNTRAILER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
4077      //
4078      pResult = conn->Query(myquery.str().c_str());
4079      //
4080      Row = pResult->Next();      
4081      if( !Row->GetField(0) ){
4082        //
4083        if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
4084        //
4085      } else {  
4086        //
4087        UInt_t runhtime = (UInt_t)atoll(Row->GetField(0));
4088        UInt_t caltime = 0;
4089        //
4090        myquery.str("");
4091        myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
4092        myquery << " order by FROM_TIME asc limit 1;";
4093        //
4094        if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4095        //
4096        //
4097        delete pResult;
4098        pResult = conn->Query(myquery.str().c_str());
4099        //
4100        Row = pResult->Next();      
4101        if( !Row ){
4102          caltime = runhtime;
4103        } else {
4104          caltime = (UInt_t)atoll(Row->GetField(0));
4105        };
4106        //
4107        myquery.str("");
4108        myquery << " SELECT ID,RUNHEADER_TIME from GL_RUN where RUNHEADER_TIME>="<< runhtime <<" AND (VALIDATION=0 OR TRK_CALIB_USED=104 OR RUNHEADER_TIME>" ;
4109        myquery << caltime << ") order by RUNHEADER_TIME asc LIMIT 1";
4110        //
4111        if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4112        //
4113        pResult = conn->Query(myquery.str().c_str());
4114        //
4115        Row = pResult->Next();      
4116        if( !Row ){
4117          //
4118          if ( IsDebug() ) printf(" NO RUN NEED TO BE UNVALIDATED \n");
4119          //
4120        } else {
4121          myquery.str("");
4122          myquery << " SELECT ID from GL_RUN where RUNHEADER_TIME<"<< Row->GetField(1) <<" AND ";
4123          myquery << " RUNHEADER_TIME>=" <<runhtime;
4124          myquery << " order by RUNHEADER_TIME asc;";
4125          //
4126          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4127          //
4128          pResult = conn->Query(myquery.str().c_str());
4129          //
4130          Row = pResult->Next();  
4131          while ( Row ){
4132            //      
4133            unv++;
4134            this->assignVALIDATION((UInt_t)atoll(Row->GetField(0)), false);
4135            Row = pResult->Next();  
4136            //
4137          };
4138        };
4139      };
4140      if ( IsDebug() ) printf(" %i runs have been unvalidated \n",unv);
4141    };
4142    
4143    /**
4144     *
4145     * Rearrange GL_RUN table and remove runs
4146     *
4147     **/
4148    void PamelaDBOperations::RemoveRUNS(){
4149      TSQLResult *pResult;
4150      TSQLRow *Row;
4151      stringstream myquery;
4152      UInt_t drun = 0;
4153      GL_RUN *delrun = new GL_RUN();
4154      //
4155      myquery.str("");
4156      myquery << " SELECT ID FROM GL_RUN where ID_RUN_FRAG=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4157      //
4158      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4159      //
4160      pResult = conn->Query(myquery.str().c_str());
4161      //
4162      Row = pResult->Next();    
4163      //
4164      //
4165      if ( !Row ){
4166        if ( IsDebug() ) printf(" No run with ID_RUN_FRAG=0 belonged to this file \n");
4167      } else {
4168        if ( IsDebug() ) printf(" Deleting run from GL_RUN table \n");    
4169        while ( Row ){
4170          delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
4171          if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(0)));
4172          drun++;
4173          Row = pResult->Next();    
4174        };
4175      };
4176      //
4177      //
4178      myquery.str("");
4179      myquery << " SELECT ID,ID_RUN_FRAG FROM GL_RUN where ID_RUN_FRAG!=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4180      //
4181      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4182      //
4183      pResult = conn->Query(myquery.str().c_str());
4184      //
4185      Row = pResult->Next();    
4186      //
4187      if ( !Row ){
4188        if ( IsDebug() ) printf(" No run with ID_RUN_FRAG!=0 belonged to this file \n");
4189      } else {
4190        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN table \n");    
4191        while ( Row ){
4192          if ( IsDebug() ) printf(" restore run %i \n",(UInt_t)atoll(Row->GetField(1)));
4193          delrun->RestoreRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN_FRAGMENTS");
4194          if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(1)));
4195          delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN");
4196          if ( (UInt_t)atoll(Row->GetField(1)) != (UInt_t)atoll(Row->GetField(0)) ){
4197            if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(0)));
4198            delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
4199          };
4200          drun++;
4201          Row = pResult->Next();    
4202        };
4203      };
4204      //
4205      if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN table \n",drun);    
4206      //
4207      //
4208      //
4209      drun = 0;
4210      //
4211      myquery.str("");
4212      myquery << " SELECT ID_TRASH FROM GL_RUN_TRASH where BELONGED_TO='GL_RUN_FRAGMENTS' AND ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4213      //
4214      pResult = conn->Query(myquery.str().c_str());
4215      //
4216      Row = pResult->Next();    
4217      //
4218      if ( !Row ){
4219        if ( IsDebug() ) printf(" No run from GL_RUN_FRAGMENTS table in the trash table for this file \n");
4220      } else {
4221        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_TRASH table \n");    
4222        while ( Row ){
4223          if ( IsDebug() ) printf(" del run idtrash %i \n",(UInt_t)atoll(Row->GetField(0)));
4224          myquery.str("");
4225          myquery << " DELETE FROM GL_RUN_TRASH where ID_TRASH=" << Row->GetField(0) <<";";      
4226          conn->Query(myquery.str().c_str());
4227          drun++;
4228          Row = pResult->Next();    
4229        };
4230      };
4231      //  
4232      if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN_TRASH table \n",drun);    
4233      //
4234      //
4235      //
4236      drun = 0;
4237      //
4238      myquery.str("");
4239      myquery << " SELECT ID FROM GL_RUN_FRAGMENTS where ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4240      //
4241      pResult = conn->Query(myquery.str().c_str());
4242      //
4243      Row = pResult->Next();    
4244      //
4245      if ( !Row ){
4246        if ( IsDebug() ) printf(" No run in the GL_RUN_FRAGMENTS table for this file \n");
4247      } else {
4248        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_FRAGMENTS table \n");    
4249        while ( Row ){
4250          if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(0)));
4251          myquery.str("");
4252          myquery << " DELETE FROM GL_RUN_FRAGMENTS where ID=" << Row->GetField(0) <<";";
4253          conn->Query(myquery.str().c_str());
4254          drun++;
4255          Row = pResult->Next();    
4256        };
4257      };
4258      //  
4259      if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN_FRAGMENTS table \n",drun);    
4260      //
4261      //
4262      //
4263      delete delrun;
4264      //
4265    };
4266    
4267    
4268    /**
4269     *
4270     * Rearrange calibration tables
4271     *
4272     **/
4273    void PamelaDBOperations::RemoveFILES(){
4274      stringstream myquery;
4275      //
4276      myquery.str("");
4277      myquery << " DELETE FROM GL_RAW WHERE ID=" <<this->GetID_RAW() <<";";
4278      //
4279      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4280      //
4281      conn->Query(myquery.str().c_str());
4282      //
4283    };
4284    
4285    /**
4286     *
4287     * Rearrange calibration tables
4288     *
4289     **/
4290    void PamelaDBOperations::RemoveCALIBS(){
4291      TSQLResult *pResult;
4292      TSQLRow *Row;
4293      stringstream myquery;
4294      //  
4295      //
4296      // Calorimeter
4297      //
4298      for (Int_t section = 0; section < 4; section++){
4299        myquery.str("");
4300        myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_CALO_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<" AND ";
4301        myquery << " SECTION=" << section << ";";
4302        //
4303        pResult = conn->Query(myquery.str().c_str());
4304        //
4305        Row = pResult->Next();      
4306        if( !Row->GetField(0) || !Row->GetField(1) ){
4307          //
4308          if ( IsDebug() ) printf(" NO CALO CALIBRATION SECTION %i ASSOCIATED TO THIS FILE! \n",section);
4309          //
4310        } else {
4311          //
4312          myquery.str("");
4313          myquery << " UPDATE GL_CALO_CALIB SET TO_TIME=" << Row->GetField(1);
4314          myquery << " WHERE TO_TIME="<< Row->GetField(0) << " AND ";
4315          myquery << " SECTION=" << section << ";";
4316          //
4317          pResult = conn->Query(myquery.str().c_str());
4318          //
4319          if( !pResult ){
4320            //
4321            if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
4322            //
4323            throw -4;
4324            //
4325          };
4326          //
4327        };
4328      };
4329      myquery.str("");
4330      myquery << " DELETE FROM GL_CALO_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4331      //
4332      pResult = conn->Query(myquery.str().c_str());
4333      //
4334      if( !pResult ){
4335        //
4336        if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
4337        //
4338        throw -4;
4339        //
4340      };
4341      //
4342      // Tracker
4343      //
4344      myquery.str("");
4345      myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_TRK_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
4346      //
4347      pResult = conn->Query(myquery.str().c_str());
4348      //
4349      Row = pResult->Next();      
4350      if( !Row->GetField(0) || !Row->GetField(1) ){
4351        //
4352        if ( IsDebug() ) printf(" NO TRK CALIBRATION ASSOCIATED TO THIS FILE! \n");
4353        //
4354      } else {
4355        //
4356        myquery.str("");
4357        myquery << " UPDATE GL_TRK_CALIB SET TO_TIME=" << Row->GetField(1);
4358        myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
4359        //
4360        pResult = conn->Query(myquery.str().c_str());
4361        //
4362        if( !pResult ){
4363          //
4364          if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
4365          //
4366          throw -4;
4367          //
4368        };
4369        //
4370        myquery.str("");
4371        myquery << " DELETE FROM GL_TRK_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4372        //
4373        pResult = conn->Query(myquery.str().c_str());
4374        //
4375        if( !pResult ){
4376          //
4377          if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
4378          //
4379          throw -4;
4380          //
4381        };
4382      };
4383      //
4384      //
4385      // S4
4386      //
4387      myquery.str("");
4388      myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_S4_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
4389      //
4390      pResult = conn->Query(myquery.str().c_str());
4391      //
4392      Row = pResult->Next();      
4393      if( !Row->GetField(0) || !Row->GetField(1) ){
4394        //
4395        if ( IsDebug() ) printf(" NO S4 CALIBRATION ASSOCIATED TO THIS FILE! \n");
4396        //
4397      } else {
4398        //
4399        myquery.str("");
4400        myquery << " UPDATE GL_S4_CALIB SET TO_TIME=" << Row->GetField(1);
4401        myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
4402        //
4403        pResult = conn->Query(myquery.str().c_str());
4404        //
4405        if( !pResult ){
4406          //
4407          if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
4408          //
4409          throw -4;
4410          //
4411        };
4412        //
4413        myquery.str("");
4414        myquery << " DELETE FROM GL_S4_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4415        //
4416        pResult = conn->Query(myquery.str().c_str());
4417        //
4418        if( !pResult ){
4419          //
4420          if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
4421          //
4422          throw -4;
4423          //
4424        };
4425        //
4426      };
4427    };
4428    
4429    /**
4430     *
4431     * Rearrange calibration tables
4432     *
4433     **/
4434    UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh ){
4435    
4436        Int_t vorder[]={5,5,3,3,4,4,2,2,1,1,0,0};
4437        UInt_t timeaftercalib=120000; //2000;
4438    //  ----------
4439    //  Check CRCs
4440    //  ----------
4441        for(Int_t ipkt=0; ipkt<6; ipkt++){
4442            if( caltrk->crc_hcal[ipkt] )return 0; // :-(
4443            for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] )return 0; // :-(
4444        }
4445    //  -----------------------
4446    //  Check missing packets:
4447    //  -----------------------
4448    //    Readout order:
4449    //    ------------------
4450    //    DSP   packet board
4451    //    ------------------
4452    //    12    0      1
4453    //    10    1      1
4454    //     8    2      1
4455    //     4    3      1
4456    //     6    4      1
4457    //     2    5      1
4458    //    ------------------
4459    //    11    0      2
4460    //     9    1      2
4461    //     7    2      2
4462    //     3    3      2
4463    //     5    4      2
4464    //     1    5      2
4465    //    ------------------
4466    //  -------------------------------------------------
4467    //  Check if it is first or second calibration packet
4468    //  -------------------------------------------------
4469        UInt_t build=0;
4470        TString classname = caltrk->GetName();
4471        UInt_t base=0;
4472        UInt_t mask=0;
4473        if(classname.Contains("CalibTrk1Event")){
4474            base=12;
4475            mask=0x03F000;
4476        }
4477        if(classname.Contains("CalibTrk2Event")){
4478            base=18;
4479            mask=0xFC0000;
4480        }
4481    //  -------------------------------------------------
4482    //  Count number of packets and set build variable
4483    //  -------------------------------------------------
4484        Int_t  npkts=0;
4485        for(Int_t ipkt=0; ipkt<6; ipkt++){
4486            if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
4487                npkts++;
4488                build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );
4489            }
4490        }
4491    //    if( npkts==6 )return 1; // :-)
4492    
4493    //    cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime()<<endl;
4494    
4495    //  -----------------------------------------------
4496    //  If missing packets: check the acq configuration
4497    //  (some DSPs might be excluded from acquisition)
4498    //  -----------------------------------------------
4499    
4500    //  -----------------------------------------------
4501    //  retrieve the first run header after calib
4502    //  -----------------------------------------------
4503         PacketType *pctp;
4504         EventCounter *cod;
4505         cod = eh->GetCounter();
4506         Int_t irun = cod->Get(pctp->RunHeader);
4507         TTree *rh=(TTree*)file->Get("RunHeader");
4508         if ( !rh || rh->IsZombie() ) throw -17;
4509         if( rh->GetEntries() == irun ){
4510              if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (1)  -- cannot validate :-( "<<endl;
4511             return 0; // :-(
4512         }
4513    
4514         RunHeaderEvent *run  = 0;
4515         EventHeader    *hrun = 0;
4516         rh->SetBranchAddress("RunHeader", &run);
4517         rh->SetBranchAddress("Header", &hrun);
4518         rh->GetEntry(irun);
4519    //     cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime() << " Run " << hrun->GetPscuHeader()->GetOrbitalTime() <<endl;
4520    
4521         if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){
4522              if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (2) -- cannot validate :-( "<<endl;
4523             return 0; // :-(
4524         }
4525        
4526         if( !run->RM_ACQ_AFTER_CALIB ){
4527              if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) RM_ACQ_AFTER_CALIB=0    -- cannot validate :-( "<<endl;
4528             return 0; // :-(
4529         }
4530    
4531         UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());
4532         if( dtime > timeaftercalib ){
4533             if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;
4534             return 0; // :-(
4535         }
4536        
4537    
4538    
4539         if( (run->ACQ_BUILD_INFO & mask) != build ){
4540             if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) ACQ_BUILD_INFO= >>> "<<hex << (run->ACQ_BUILD_INFO&mask) << " != "<< build << dec<<endl;
4541             return 0; // :-(
4542         }
4543         return 1; // :-)
4544    
4545    }
4546    
4547    /**
4548     *
4549     * Check the DB (only for overlapping runs at the moment)
4550     *
4551     **/
4552    UInt_t PamelaDBOperations::Check(){
4553      //
4554      UInt_t test = 0;
4555      //
4556      UInt_t thisrht = 0;
4557      UInt_t thisrtt = 0;
4558      UInt_t thisid = 0;
4559      UInt_t prevrht = 0;
4560      UInt_t prevrtt = 0;
4561      UInt_t previd = 0;
4562      //
4563      UInt_t prevl0id = 0;
4564      UInt_t thisl0id = 0;
4565      //
4566      stringstream oss;
4567      TSQLResult *result = 0;
4568      TSQLRow    *row    = 0;
4569      TSQLResult *result2 = 0;
4570      TSQLRow    *row2    = 0;
4571      oss.str("");
4572      oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN order by RUNHEADER_TIME asc;";
4573      //  oss << "SELECT ID,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN where ID>10170 and ID<10190 order by RUNHEADER_TIME asc;";
4574      result = conn->Query(oss.str().c_str());
4575      //
4576      if ( !result ) throw -4;;
4577      //
4578      row = result->Next();
4579      //
4580      while ( row ){
4581        thisid = (UInt_t)atoll(row->GetField(0));
4582        thisl0id = (UInt_t)atoll(row->GetField(1));
4583        thisrht = (UInt_t)atoll(row->GetField(2));
4584        thisrtt = (UInt_t)atoll(row->GetField(3));
4585        //
4586        //    if ( thisrht < prevrtt || thisrtt < prevrht || thisrht > thisrtt && !(!prevrht && !prevrtt &&!previd) ){
4587        //    if ( (thisrht < prevrtt || thisrtt < prevrht || thisrht > thisrtt) && (thisrht != prevrht) ){
4588        if ( (thisrht < prevrtt) && (thisrht != prevrht) ){
4589          if ( IsDebug() ) printf(" IDprev %u ID %u    prevrht %u prevrtt %u  thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
4590          printf(" CHECK n.1 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrht-prevrtt),previd,thisid);
4591          TString prevf = "";
4592          TString thisf = "";
4593          oss.str("");
4594          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
4595          result2 = conn->Query(oss.str().c_str());
4596          if ( !result2 ) throw -4;;
4597          row2 = result2->Next();
4598          prevf = (TString)row2->GetField(0);
4599          oss.str("");
4600          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
4601          result2 = conn->Query(oss.str().c_str());
4602          if ( !result2 ) throw -4;;
4603          row2 = result2->Next();
4604          thisf = (TString)row2->GetField(0);
4605          if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
4606          test = 1;
4607        };
4608        //
4609        if ( (thisrtt < prevrht) && (thisrht != prevrht) ){
4610          if ( IsDebug() ) printf(" IDprev %u ID %u    prevrht %u prevrtt %u  thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
4611          printf(" CHECK n.2 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrtt-prevrht),previd,thisid);
4612          TString prevf = "";
4613          TString thisf = "";
4614          oss.str("");
4615          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
4616          result2 = conn->Query(oss.str().c_str());
4617          if ( !result2 ) throw -4;;
4618          row2 = result2->Next();
4619          prevf = (TString)row2->GetField(0);
4620          oss.str("");
4621          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
4622          result2 = conn->Query(oss.str().c_str());
4623          if ( !result2 ) throw -4;;
4624          row2 = result2->Next();
4625          thisf = (TString)row2->GetField(0);
4626          if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
4627          test = 1;
4628        };
4629        //
4630        if ( (thisrht > thisrtt) && (thisrht != prevrht) ){
4631          if ( IsDebug() ) printf(" IDprev %u ID %u    prevrht %u prevrtt %u  thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
4632          printf(" CHECK n.3 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrht-thisrtt),previd,thisid);
4633          TString prevf = "";
4634          TString thisf = "";
4635          oss.str("");
4636          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
4637          result2 = conn->Query(oss.str().c_str());
4638          if ( !result2 ) throw -4;;
4639          row2 = result2->Next();
4640          prevf = (TString)row2->GetField(0);
4641          oss.str("");
4642          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
4643          result2 = conn->Query(oss.str().c_str());
4644          if ( !result2 ) throw -4;;
4645          row2 = result2->Next();
4646          thisf = (TString)row2->GetField(0);
4647          if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
4648          test = 1;
4649        };
4650    
4651        //
4652        prevrht = thisrht;
4653        prevrtt = thisrtt;
4654        previd = thisid;
4655        prevl0id = thisl0id;
4656        row = result->Next();
4657      };
4658      //
4659      return(test);
4660      //
4661    };

Legend:
Removed from v.1.9  
changed lines
  Added in v.1.25

  ViewVC Help
Powered by ViewVC 1.1.23