/[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.2 by mocchiut, Fri Sep 1 12:47:13 2006 UTC revision 1.30 by mocchiut, Mon Apr 30 08:09:50 2007 UTC
# Line 8  Line 8 
8  #include <list>  #include <list>
9  #include <errno.h>  #include <errno.h>
10  //  //
11    #include <TFile.h>
12    #include <TSystem.h>
13  #include <TSQLResult.h>  #include <TSQLResult.h>
 #include <TRFIOFile.h>  
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 30  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 46  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, UInt_t dwinput, Bool_t staticp){
60    //    //
61      STATIC=false;
62      if ( staticp ) STATIC=true;
63    //    //
64    SetConnection(host,user,password);    SetConnection(host,user,password);
65    //    //
# Line 61  PamelaDBOperations::PamelaDBOperations(T Line 72  PamelaDBOperations::PamelaDBOperations(T
72    SetTsync(tsync);    SetTsync(tsync);
73    SetObt0(obt0);    SetObt0(obt0);
74    //    //
75      SetTLEPath(tlefilename);
76    //    //
   SetRootName(filerootname);  
   SetRawName(filerawname);  
77    //    //
78    this->OpenFile();    INSERT_RAW =!filerawname.IsNull();
79      if(INSERT_RAW)SetRawName(filerawname);
80      //
81      INSERT_ROOT = !filerootname.IsNull();
82      if( INSERT_ROOT ){
83        this->SetRootName(filerootname);
84        this->SetOrbitNo(dwinput);
85        file = TFile::Open(this->GetRootName().Data());
86      } else {
87        this->SetRootName("");
88      };
89    //    //
90    this->SetID_RAW(0);    this->SetID_RAW(0);
91    this->SetID_ROOT(0);    this->SetID_ROOT(0);
92    
93      VALIDATE = false;
94      
95    //    //
96  };  };
97    
# Line 77  PamelaDBOperations::PamelaDBOperations(T Line 100  PamelaDBOperations::PamelaDBOperations(T
100   */   */
101  void PamelaDBOperations::Close(){  void PamelaDBOperations::Close(){
102    if( conn && conn->IsConnected() ) conn->Close();    if( conn && conn->IsConnected() ) conn->Close();
103      delete clean_time;
104    delete glrun;    delete glrun;
105    delete this;    delete this;
106  };  };
# Line 85  void PamelaDBOperations::Close(){ Line 109  void PamelaDBOperations::Close(){
109  // SETTERS  // SETTERS
110  //  //
111    
112    //
113    // must be out of the constructor in order to FORCE the validation of the latest runs in case you run the validation together with the latest file
114    //
115    void PamelaDBOperations::CheckValidate(Long64_t olderthan){
116      clean_time = new TDatime();
117      //
118      if(olderthan >= 0){
119        VALIDATE = true;
120        UInt_t timelim = 0;
121        timelim =  (UInt_t)clean_time->Convert(true) - olderthan;
122        clean_time->Set(timelim,false);
123      };
124    };
125    
126  /**  /**
127   * Open the DB connection   * Open the DB connection
128   * @param host         hostname for the SQL connection.   * @param host         hostname for the SQL connection.
# Line 92  void PamelaDBOperations::Close(){ Line 130  void PamelaDBOperations::Close(){
130   * @param password     password for the SQL connection.   * @param password     password for the SQL connection.
131   */   */
132  void PamelaDBOperations::SetConnection(TString host, TString user, TString password){  void PamelaDBOperations::SetConnection(TString host, TString user, TString password){
133      if ( IsDebug() ) printf(" Connecting using host = %s user = %s password = %s \n",host.Data(),user.Data(),password.Data());
134    conn = TSQLServer::Connect(host.Data(),user.Data(),password.Data());    conn = TSQLServer::Connect(host.Data(),user.Data(),password.Data());
135  };  };
136    
# Line 120  void PamelaDBOperations::SetDebugFlag(Bo Line 159  void PamelaDBOperations::SetDebugFlag(Bo
159  };  };
160    
161  /**  /**
162     * Set the autoboot flag
163     *
164     */
165    void PamelaDBOperations::SetAutoBoot(Bool_t dbg){
166      AUTOBOOT = dbg;
167    };
168    
169    /**
170     * Set the nofrag flag
171     *
172     */
173    void PamelaDBOperations::SetNoFrag(Bool_t nf){
174      NOFRAG = nf;
175    };
176    
177    /**
178   * Store the BOOT number of the RAW file.   * Store the BOOT number of the RAW file.
179   * @param boot    BOOT number of the RAW file   * @param boot    BOOT number of the RAW file
180   */   */
# Line 160  void PamelaDBOperations::SetRootName(TSt Line 215  void PamelaDBOperations::SetRootName(TSt
215  };  };
216    
217  /**  /**
218     * Store the downlink orbit number from filename.
219     */
220    void PamelaDBOperations::SetOrbitNo(UInt_t dwinput){
221      dworbit = 0;
222      //
223      if ( dwinput ){
224        dworbit = dwinput;
225        if ( IsDebug() ) printf(" Downlink orbit given by hand: %i  \n",dworbit);
226        return;
227      };
228      //
229      TString name = this->GetRootFile();
230      Int_t nlength = name.Length();
231      if ( nlength < 5 ) return;
232      TString dwo = 0;
233      for (Int_t i = 0; i<5; i++){
234        dwo.Append(name[i],1);
235      };
236      if ( dwo.IsDigit() ){
237        dworbit = (UInt_t)dwo.Atoi();
238      } else {
239        dwo="";
240        for (Int_t i = 8; i<13; i++){
241          dwo.Append(name[i],1);
242        };    
243        if ( dwo.IsDigit() ) dworbit = (UInt_t)dwo.Atoi();
244      };
245      if ( IsDebug() ) printf(" Downlink orbit is %i (dwo = %s) \n",dworbit,dwo.Data());
246      return;
247    };
248    
249    
250    
251    /**
252   * Store the NOBOOT flag.   * Store the NOBOOT flag.
253   * @param noboot    true/false.   * @param noboot    true/false.
254   */   */
# Line 168  void PamelaDBOperations::SetNOBOOT(Bool_ Line 257  void PamelaDBOperations::SetNOBOOT(Bool_
257  };  };
258    
259  /**  /**
260     * Store path to the TLE file.
261     */
262    void PamelaDBOperations::SetTLEPath(TString str){
263      tlefilename = str;
264    };
265    
266    TString PamelaDBOperations::GetRawPath(){
267      if ( STATIC ){
268        return((TString)gSystem->DirName(filerawname.Data())+'/');
269      } else {
270        return((TString)gSystem->ExpandPathName("$PAM_RAW")+'/');
271      };
272    };
273    
274    TString PamelaDBOperations::GetRootPath(){
275      if ( STATIC ){
276        return((TString)gSystem->DirName(filerootname.Data())+'/');
277      } else {
278        return((TString)gSystem->ExpandPathName("$PAM_L0")+'/');
279      };
280    };
281    
282    /**
283   * Store the olderthan variable   * Store the olderthan variable
284   * @param olderthan   * @param olderthan
285   */   */
286  void PamelaDBOperations::SetOlderThan(Long64_t oldthan){  // void PamelaDBOperations::SetOlderThan(Long64_t oldthan){
287    olderthan = oldthan;  //   olderthan = oldthan;
288  };  // };
289    
290  /**  /**
291   * Retrieve the ID_RAW, if exists, returns NULL if does not exist.   * Retrieve the ID_RAW, if exists, returns NULL if does not exist.
# Line 183  Bool_t PamelaDBOperations::SetID_RAW(){ Line 295  Bool_t PamelaDBOperations::SetID_RAW(){
295    TSQLResult *result = 0;    TSQLResult *result = 0;
296    TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
297    oss.str("");    oss.str("");
298    oss << "SELECT ID FROM GL_RAW WHERE "    if ( STATIC ){
299        << " PATH = '" << this->GetRawPath().Data() << "' AND "      oss << "SELECT ID FROM GL_RAW WHERE "
300        << " NAME = '" << this->GetRawFile().Data() << "' ";          << " PATH = '" << this->GetRawPath().Data() << "' AND "
301            << " NAME = '" << this->GetRawFile().Data() << "' ";  
302      } else {
303        oss << "SELECT ID FROM GL_RAW WHERE "
304            << " PATH = '$PAM_RAW' AND "
305            << " NAME = '" << this->GetRawFile().Data() << "' ";  
306      }
307    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
308    if ( result == NULL ) throw -4;    if ( result == NULL ) throw -4;
309    row = result->Next();    row = result->Next();
# Line 216  Int_t PamelaDBOperations::SetUpperLimits Line 334  Int_t PamelaDBOperations::SetUpperLimits
334    UInt_t nevent = 0;    UInt_t nevent = 0;
335    UInt_t pktlast = 0;    UInt_t pktlast = 0;
336    UInt_t obtlast = 0;    UInt_t obtlast = 0;
337    UInt_t t_pktlast = 0;    Long64_t t_pktlast = 0LL;
338    UInt_t t_obtlast = 0;    //  UInt_t t_obtlast = 0;
339    UInt_t upperpkt2 = 0;    Long64_t t_obtlast = 0LL;
340    ULong64_t upperobt2 = 0;    Long64_t upperpkt2 = 0LL;
341      Long64_t upperobt2 = 0LL;
342    UInt_t zomp = 0;    UInt_t zomp = 0;
343    UInt_t jump = 50000; // was 5000    UInt_t jump = 50000; // was 5000
344      EventCounter *code=0;
345      //
346      Long64_t deltapkt = 5000LL;
347      Long64_t deltaobt = 50000LL;
348      //
349      pcksList packetsNames;
350      pcksList::iterator Iter;
351      getPacketsNames(packetsNames);
352    //    //
353    pktfirst = 0;    pktfirst = 0;
354    obtfirst = 0;    obtfirst = 0;
355      ppktfirst = 0;
356      pobtfirst = 0;
357    //    //
358    TTree *T = 0;    TTree *T = 0;
359    T = (TTree*)file->Get("Physics");    T = (TTree*)file->Get("Physics");
# Line 238  Int_t PamelaDBOperations::SetUpperLimits Line 367  Int_t PamelaDBOperations::SetUpperLimits
367    ph = eh->GetPscuHeader();    ph = eh->GetPscuHeader();
368    pktfirst = ph->GetCounter();    pktfirst = ph->GetCounter();
369    obtfirst = ph->GetOrbitalTime();      obtfirst = ph->GetOrbitalTime();  
370      ppktfirst = pktfirst;
371      pobtfirst = obtfirst;
372      //
373      code = eh->GetCounter();
374      UInt_t en = 0;
375      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
376        en = code->Get(GetPacketType(*Iter));
377        if ( !strcmp("CalibCalPed",*Iter) || !strcmp("CalibTrk1",*Iter) || !strcmp("CalibTrk2",*Iter) || !strcmp("CalibS4",*Iter) ){
378          if ( IsDebug() ) printf(" We have a calibration before the first physic packet: packet type is %s, entries: %i \n",*Iter,en);
379          //
380          TTree *TC = 0;
381          TC = (TTree*)file->Get("CalibCalPed");
382          if ( !TC || TC->IsZombie() ) throw -16;
383          EventHeader *ehc = 0;
384          PscuHeader *phc = 0;
385          TC->SetBranchAddress("Header", &ehc);
386          TC->GetEntry(0);
387          phc = ehc->GetPscuHeader();
388          pktfirst = phc->GetCounter();
389          obtfirst = phc->GetOrbitalTime();  
390          //
391        };
392      };  
393    //    //
394    T->GetEntry(nevent-1);    T->GetEntry(nevent-1);
395    ph = eh->GetPscuHeader();    ph = eh->GetPscuHeader();
# Line 248  Int_t PamelaDBOperations::SetUpperLimits Line 400  Int_t PamelaDBOperations::SetUpperLimits
400    upperobt = OBT(obtlast);    upperobt = OBT(obtlast);
401    upperentry = nevent-1;    upperentry = nevent-1;
402    //    //
403    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);
404    //    //
405    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);
406    //    //
407    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);
408    //    //
409    if ( !nevent ) return(2);    if ( !nevent ) return(2);
410    //    //
411    if ( nevent < 2 ) return(4);    if ( nevent < 2 ) return(4);
412      if ( nevent < jump ) jump = 1;
413      //  if ( nevent < jump ) jump = int(nevent/10);
414      //  if ( !jump ) jump = 1;
415    //    //
416    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) && nevent > deltapkt ){
417        //
418        if ( IsDebug() ) printf(" starting jump %i \n",jump);
419      // go back      // go back
420      zomp = nevent - 2;      zomp = nevent - 2;
421      //      //
# Line 280  Int_t PamelaDBOperations::SetUpperLimits Line 437  Int_t PamelaDBOperations::SetUpperLimits
437          upperpkt2 = PKT(ph->GetCounter());          upperpkt2 = PKT(ph->GetCounter());
438          upperobt2 = OBT(ph->GetOrbitalTime());          upperobt2 = OBT(ph->GetOrbitalTime());
439          //          //
440          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) ){
441              if ( IsDebug() ) printf(" .-. upperpkt2 %lld upperobt2 %lld \n",upperpkt2,upperobt2);  
442              if ( IsDebug() ) printf(" .-. upperpkt %lld t_pktlast %lld upperobt %lld t_obtlast %lld \n",upperpkt,t_pktlast,upperobt,t_obtlast);    
443              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);    
444              throw -13;    
445            };
446          //          //
447          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 ){
448            zomp = i + jump + 1;            zomp = i + jump + 1;
449            if ( zomp > nevent-2 ) zomp = nevent - 2;            if ( zomp > nevent-2 ) zomp = nevent - 2;
450            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);
451            break;            break;
452          };          };
453          //          //
# Line 307  Int_t PamelaDBOperations::SetUpperLimits Line 469  Int_t PamelaDBOperations::SetUpperLimits
469    // check if last runtrailer is within limits, if not extend limits (one should check for all packets but we need only runtrailer)    // check if last runtrailer is within limits, if not extend limits (one should check for all packets but we need only runtrailer)
470    //    //
471    PacketType *pctp=0;    PacketType *pctp=0;
   EventCounter *code=0;  
   T->GetEntry(upperentry);  
   code = eh->GetCounter();  
   Int_t lasttrail = code->Get(pctp->RunTrailer);  
   Int_t lasthead = code->Get(pctp->RunHeader);  
472    TTree *rh=(TTree*)file->Get("RunHeader");    TTree *rh=(TTree*)file->Get("RunHeader");
473    if ( !rh || rh->IsZombie() ) throw -17;    if ( !rh || rh->IsZombie() ) throw -17;
474    TTree *rt=(TTree*)file->Get("RunTrailer");    TTree *rt=(TTree*)file->Get("RunTrailer");
# Line 325  Int_t PamelaDBOperations::SetUpperLimits Line 482  Int_t PamelaDBOperations::SetUpperLimits
482    //    //
483    rhev = rh->GetEntries();    rhev = rh->GetEntries();
484    rtev = rt->GetEntries();    rtev = rt->GetEntries();
485    UInt_t pktt = 0;    Long64_t sobtt = 0LL;
486    ULong64_t obtt = 0;    Long64_t sobth = 0LL;
487    UInt_t pkth = 0;    Long64_t spktt = 0LL;
488    ULong64_t obth = 0;    Long64_t spkth = 0LL;
489      Long64_t pktt = 0LL;
490      Long64_t obtt = 0LL;
491      Long64_t pkth = 0LL;
492      Long64_t obth = 0LL;
493    //    //
494    if ( lasttrail < rtev ){    if ( rhev || rtev ){
495      rt->GetEntry(lasttrail);  
496      pht = eht->GetPscuHeader();      T->GetEntry(upperentry);
497      pktt = PKT(pht->GetCounter());      code = eh->GetCounter();
498      obtt = OBT(pht->GetOrbitalTime());      Int_t lasttrail = code->Get(pctp->RunTrailer);
499        Int_t lasthead = code->Get(pctp->RunHeader);
500        if ( lasttrail < rtev ){
501          rt->GetEntry(lasttrail);
502          pht = eht->GetPscuHeader();
503          pktt = PKT(pht->GetCounter());
504          obtt = OBT(pht->GetOrbitalTime());
505        };
506        //
507        if ( lasthead < rhev ){
508          rh->GetEntry(lasthead);
509          phh = ehh->GetPscuHeader();
510          pkth = PKT(phh->GetCounter());
511          obth = OBT(phh->GetOrbitalTime());
512        };
513        //
514        if ( IsDebug() ) printf(" rhev before %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
515        if ( pkth > upperpkt && obth > upperobt ){
516          if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %lld upperp %lld oh %lld uppero %lld \n",pkth,upperpkt,obth,upperobt);
517          upperpkt = pkth;
518          upperobt = obth;
519          rhev = lasthead+1;
520        } else {
521          rhev = lasthead;
522        };
523        if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
524        //
525        if ( IsDebug() ) printf(" rtev beforev %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
526        if ( pktt > upperpkt && obtt > upperobt ){
527          if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %lld upperp %lld ot %lld uppero %lld \n",pktt,upperpkt,obtt,upperobt);
528          upperpkt = pktt;
529          upperobt = obtt;
530          rtev = lasttrail+1;
531        } else {
532          rtev = lasttrail;
533        };
534        if ( IsDebug() ) printf(" rtev after %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
535        //  goto kikko;
536        //
537        //
538        // Check if runtrailer/runheader are within lower limits
539        //
540        //
541        pkth = 0LL;
542        obth = 0LL;
543        spkth = 0LL;
544        sobth = 0LL;
545        for (Int_t k=0; k<rhev; k++){
546          if ( k > 0 ){
547            spkth = pkth;
548            sobth = obth;
549          };
550          rh->GetEntry(k);
551          phh = ehh->GetPscuHeader();
552          pkth = PKT(phh->GetCounter());
553          obth = OBT(phh->GetOrbitalTime());
554          //
555          //    if ( IsDebug() ) printf(" k %i rhev before %i ph %u upperp %u oh %u uppero %u \n",k,rhev,pkth,spkth,obth,sobth);
556          //
557          if ( pkth < spkth && obth < sobth ){
558            if ( IsDebug() ) printf(" RH PROBLEMS determining the event repetition at the end of the file lasthead %i  \n",rhev);
559            //
560            rhev = k-1;
561            rh->GetEntry(rhev);
562            pkth = spkth;
563            obth = sobth;
564            //
565            UInt_t evbefh = 0;
566            code = ehh->GetCounter();
567            evbefh = code->Get(pctp->Physics);    
568            if ( evbefh >= 0 ){
569              T->GetEntry(evbefh);
570              ph = eh->GetPscuHeader();
571              t_pktlast = PKT(ph->GetCounter());
572              t_obtlast = OBT(ph->GetOrbitalTime());
573              if ( t_pktlast <= spkth && t_obtlast <= sobth ){ // jump
574                upperpkt = pkth;
575                upperobt = obth;
576                upperentry = evbefh-1;
577              } else {
578                while ( t_pktlast > spkth && t_obtlast > sobth && evbefh < nevent ){
579                  evbefh++;
580                  T->GetEntry(evbefh);
581                  ph = eh->GetPscuHeader();
582                  t_pktlast = PKT(ph->GetCounter());
583                  t_obtlast = OBT(ph->GetOrbitalTime());
584                };
585                T->GetEntry(evbefh-1);
586                ph = eh->GetPscuHeader();
587                upperpkt = PKT(ph->GetCounter());
588                upperobt = OBT(ph->GetOrbitalTime());
589                upperentry = evbefh-1;
590              };    
591            };
592            if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
593            goto kikko0;
594          };
595        };
596      kikko0:
597        //
598        //
599        //
600        pktt = 0LL;
601        obtt = 0LL;
602        spktt = 0LL;
603        sobtt = 0LL;
604        for (Int_t k=0; k<rtev; k++){
605          if ( k > 0 ){
606            spktt = pktt;
607            sobtt = obtt;
608          };
609          rt->GetEntry(k);
610          pht = eht->GetPscuHeader();
611          pktt = PKT(pht->GetCounter());
612          obtt = OBT(pht->GetOrbitalTime());
613          //
614          //    if ( IsDebug() ) printf(" k %i rtev beforev %i  pt %i upperp %i ot %llu uppero %llu \n",k,rtev,pktt,spktt,obtt,sobtt);
615          //
616          if ( pktt < spktt && obtt < sobtt ){
617            if ( IsDebug() ) printf(" RT PROBLEMS determining the event repetition at the end of the file lasttrail %i \n",rtev);
618            //
619            rtev = k-1;
620            rt->GetEntry(rtev);
621            pktt = spktt;
622            obtt = sobtt;
623            if ( IsDebug() ) printf(" lasttrail %i pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
624            //
625            UInt_t evbeft = 0;
626            code = eht->GetCounter();
627            evbeft = code->Get(pctp->Physics);    
628            if ( evbeft >= 0 ){
629              T->GetEntry(evbeft);
630              ph = eh->GetPscuHeader();
631              t_pktlast = PKT(ph->GetCounter());
632              t_obtlast = OBT(ph->GetOrbitalTime());
633              if ( t_pktlast <= spktt && t_obtlast <= sobtt ){ // jump
634                upperpkt = pktt;
635                upperobt = obtt;
636                upperentry = evbeft-1;
637              } else {
638                while ( t_pktlast > spktt && t_obtlast > sobtt && evbeft < nevent ){
639                  evbeft++;
640                  T->GetEntry(evbeft);
641                  ph = eh->GetPscuHeader();
642                  t_pktlast = PKT(ph->GetCounter());
643                  t_obtlast = OBT(ph->GetOrbitalTime());
644                };
645                T->GetEntry(evbeft-1);
646                ph = eh->GetPscuHeader();
647                upperpkt = PKT(ph->GetCounter());
648                upperobt = OBT(ph->GetOrbitalTime());
649                upperentry = evbeft-1;
650              };
651            };
652            if ( IsDebug() ) printf(" rtev after %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
653            goto kikko;
654            //      break;
655            //
656          };
657          //  
658        };
659        //
660      kikko:
661        //
662        T->GetEntry(upperentry);
663        code = eh->GetCounter();
664        lasttrail = code->Get(pctp->RunTrailer);
665        lasthead = code->Get(pctp->RunHeader);
666        if ( lasttrail < rtev ){
667          rt->GetEntry(lasttrail);
668          pht = eht->GetPscuHeader();
669          pktt = PKT(pht->GetCounter());
670          obtt = OBT(pht->GetOrbitalTime());
671        };
672        //
673        if ( lasthead < rhev ){
674          rh->GetEntry(lasthead);
675          phh = ehh->GetPscuHeader();
676          pkth = PKT(phh->GetCounter());
677          obth = OBT(phh->GetOrbitalTime());
678        };
679        //
680        if ( IsDebug() ) printf(" rhev before %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
681        if ( pkth > upperpkt && obth > upperobt ){
682          if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %lld upperp %lld oh %lld uppero %lld \n",pkth,upperpkt,obth,upperobt);
683          upperpkt = pkth;
684          upperobt = obth;
685          rhev = lasthead+1;
686        } else {
687          rhev = lasthead;
688        };
689        if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
690        //
691        if ( IsDebug() ) printf(" rtev beforev %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
692        if ( pktt > upperpkt && obtt > upperobt ){
693          if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %lld upperp %lld ot %lld uppero %lld \n",pktt,upperpkt,obtt,upperobt);
694          upperpkt = pktt;
695          upperobt = obtt;
696          rtev = lasttrail+1;
697        } else {
698          rtev = lasttrail;
699        };
700        if ( IsDebug() ) printf(" rtev after %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
701        //
702    };    };
703    //    //
704    if ( IsDebug() ) printf(" rtev beforev %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);    if ( IsDebug() ) printf(" Upper limits are: OBT %lld pkt_num %lld upper entry %i \n",upperobt,upperpkt,upperentry);
   if ( pktt > upperpkt && obtt > upperobt ){  
     if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %i upperp %i ot %llu uppero %llu \n",pktt,upperpkt,obtt,upperobt);  
     upperpkt = pktt;  
     upperobt = obtt;  
     rtev = lasttrail+1;  
   } else {  
     rtev = lasttrail;  
   };  
   if ( IsDebug() ) printf(" rtev after %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);  
705    //    //
706    if ( lasthead < rhev ){    return(0);
707      rh->GetEntry(lasthead);  }
708      phh = ehh->GetPscuHeader();  
709      pkth = PKT(pht->GetCounter());  /**
710      obth = OBT(pht->GetOrbitalTime());   *
711    };   * Trick to have unique RUN ID numbers even when runs are deleted and mysql deamon restarted.
712     * Entries in the _RUNID_GEN table are never deleted.
713     *
714     **/
715    UInt_t PamelaDBOperations::AssignRunID(){
716    //    //
717    if ( IsDebug() ) printf(" rhev before %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);    TSQLResult *result = 0;
718    if ( pkth > upperpkt && obth > upperobt ){    TSQLRow *row = 0;
719      if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %i upperp %i oh %llu uppero %llu \n",pkth,upperpkt,obth,upperobt);    UInt_t runid = 0;
720      upperpkt = pkth;    //
721      upperobt = obth;    stringstream   oss;
722      rhev = lasthead+1;    //  
723    } else {    oss.str("");
724      rhev = lasthead;    oss << "INSERT INTO _RUNID_GEN VALUES (NULL);";
725    };    result = conn->Query(oss.str().c_str());
726    if ( IsDebug() ) printf(" rhev after %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);    if ( !result ) throw -10;
727      oss.str("");
728      oss << "SELECT ID FROM _RUNID_GEN ORDER BY ID DESC LIMIT 1;";
729      result = conn->Query(oss.str().c_str());
730      if ( !result ) throw -10;
731      //
732      row = result->Next();
733    //    //
734    if ( IsDebug() ) printf(" Upper limits are: OBT %llu pkt_num %i upper entry %i \n",upperobt,upperpkt,upperentry);    if ( !row ) throw -28;
735    //    //
736    return(0);    runid = (UInt_t)atoll(row->GetField(0));
737  }    //
738      return(runid);
739    };
740    
741  //  //
742  // GETTERS  // GETTERS
# Line 446  const PacketType* PamelaDBOperations::Ge Line 813  const PacketType* PamelaDBOperations::Ge
813  // PRIVATE FUNCTIONS  // PRIVATE FUNCTIONS
814  //  //
815    
816  /**  // /**
817   * Open the ROOT filename for reading  // * Open the ROOT filename for reading
818   */  // */
819  void PamelaDBOperations::OpenFile(){  // void PamelaDBOperations::OpenFile(){
820    file = TFile::Open(this->GetRootName().Data());  //   file = TFile::Open(this->GetRootName().Data());
821    //   //
822    
823    void PamelaDBOperations::CheckFile(){  
824      if ( !file ) throw -12;
825  };  };
826    
827    
828  /**  /**
829   * Check if LEVEL0 file and DB connection have really be opened   * Check if LEVEL0 file and DB connection have really be opened
830   */   */
831  void PamelaDBOperations::CheckFile(){    void PamelaDBOperations::CheckConnection(){  
   //  
   if ( !file ) throw -12;  
832    //    //
833    // check connection    // check connection
834    //    //
835    if( !conn ) throw -1;        if( !conn ) throw -1;
836    bool connect = conn->IsConnected();    bool connect = conn->IsConnected();
837    if( !connect ) throw -1;        if( !connect ) throw -1;
838      //
839      if ( IsDebug() ) printf("\n DB INFORMATIONS:\n SQL: %s Version: %s Host %s Port %i \n\n",conn->GetDBMS(),conn->ServerInfo(),conn->GetHost(),conn->GetPort());
840      //
841      if ( !dworbit && strcmp(this->GetRootName().Data(),"") ) throw -27;
842      //
843      // set DB timezone to UTC
844      //
845      stringstream oss;
846      //  
847      oss.str("");
848      oss << "SET time_zone='+0:00';";
849      TSQLResult *result = 0;
850      result = conn->Query(oss.str().c_str());
851      if ( !result ) throw -10;
852      oss.str("");
853      oss << "SET wait_timeout=173000;";
854      conn->Query(oss.str().c_str());
855      //
856  };  };
857    
858  /**  /**
859   * Return the correct packet number if we went back to zero   * Return the correct packet number if we went back to zero
860   */   */
861  UInt_t PamelaDBOperations::PKT(UInt_t pkt_num){    Long64_t PamelaDBOperations::PKT(UInt_t pkt_num){  
862    //    //
863    //  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,ppktfirst,(UInt_t)(16777214/2));
864    //    //
865    if ( pkt_num < (pktfirst/2) && pktfirst > (16777214/2)  ) return((pkt_num+16777215));    if ( pkt_num < (ppktfirst/2) && ppktfirst > (16777214/2)  ){
866        if ( IsDebug() ) printf(" rise up pktnum %lld \n",(Long64_t)pkt_num+16777215LL);
867        return((Long64_t)pkt_num+16777215LL);
868      };
869    //    //
870    if ( pkt_num > pktfirst*2 && pkt_num > (16777214/2) ){    if ( pkt_num > ppktfirst*2 && pkt_num > (16777214/2) ){
871      if ( (pkt_num-16777215) < 0 ){      if ( IsDebug() ) printf(" rise down pktnum %lld \n",(Long64_t)pkt_num-16777215LL);
872        return((16777215-pkt_num));      return((Long64_t)pkt_num-16777215LL);
     } else {  
       return((pkt_num-16777215));  
     };  
873    };    };
874    //    //
875    return(pkt_num);    if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)pkt_num);
876      return((Long64_t)pkt_num);
877    //    //
878  };  };
879    
880  /**  /**
881   * Return the correct On Board Time if we went back to zero   * Return the correct On Board Time if we went back to zero
882   */   */
883  ULong64_t PamelaDBOperations::OBT(UInt_t obt){    Long64_t PamelaDBOperations::OBT(UInt_t obt){  
884    //    //
885    if ( obt < (obtfirst/2) && obtfirst > (numeric_limits<UInt_t>::max()/2) ) return((ULong64_t)(obt+numeric_limits<UInt_t>::max()));    if ( IsDebug() ) printf(" obt conversion: ob is %u obtfirst is %u  (numeric_limits<UInt_t>::max()/2) is %u  \n",obt,pobtfirst,(UInt_t)(numeric_limits<UInt_t>::max()/2));
886    //    //
887    if ( obt > (obtfirst*2) && obt > (numeric_limits<UInt_t>::max()/2) ){    if ( obt < (pobtfirst/2) && pobtfirst > (numeric_limits<UInt_t>::max()/2) ) return((Long64_t)(obt+numeric_limits<UInt_t>::max()));
888      if ( (obt-numeric_limits<UInt_t>::max()) < 0  ){    //
889        return((ULong64_t)(numeric_limits<UInt_t>::max()-obt));    if ( obt > (pobtfirst*2) && obt > (numeric_limits<UInt_t>::max()/2) ){
890      } else {      return((Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());
       return((ULong64_t)(obt-numeric_limits<UInt_t>::max()));  
     };  
891    };    };
892    //    //
893    return((ULong64_t)obt);    return((Long64_t)obt);
894  };  };
895    
896  /**  /**
# Line 619  Int_t PamelaDBOperations::insertPamelaRa Line 1005  Int_t PamelaDBOperations::insertPamelaRa
1005    if ( idr ) return(1);    if ( idr ) return(1);
1006    //    //
1007    oss.str("");    oss.str("");
1008    oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"    if ( STATIC ){
1009        << this->GetRawPath().Data() << "', '" << this->GetRawFile().Data() << "')";      oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"
1010            << this->GetRawPath().Data() << "', '" << this->GetRawFile().Data() << "')";
1011      } else {
1012        oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('$PAM_RAW', '" << this->GetRawFile().Data() << "')";
1013      };
1014    if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;    if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
1015    //    //
1016    idr =  this->SetID_RAW();    idr =  this->SetID_RAW();
# Line 645  Int_t PamelaDBOperations::insertPamelaGL Line 1035  Int_t PamelaDBOperations::insertPamelaGL
1035    if ( this->GetID_RAW() == 0 )  throw -11;    if ( this->GetID_RAW() == 0 )  throw -11;
1036    //    //
1037    oss.str("");    oss.str("");
1038    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='"
1039        << id << " AND TO_ID_RAW >= "        << this->GetRawFile().Data() << "';";
       << id << ";";  
1040    if ( IsDebug() ) printf(" %s \n",oss.str().c_str());    if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
1041    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1042    if ( !result ) throw -10;    if ( !result ) throw -10;
1043    row = result->Next();    row = result->Next();
   if ( !row ) throw -10;  
1044    //    //
1045    t0 = (UInt_t)TDatime(row->GetField(0)).Convert();    if ( !row ){
1046        oss.str("");
1047        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< "
1048            << dworbit << " order by FROM_ORBIT desc limit 1;";
1049        if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
1050        result = conn->Query(oss.str().c_str());
1051        if ( !result ) throw -10;
1052        row = result->Next();
1053        if ( !row ) throw -10;
1054      };
1055      //
1056      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);
1057      t0 = (UInt_t)tu.GetSec();
1058      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));
1059      //
1060    /*    /*
1061     * Verify that the TIMESYNC have been not already processed     * Verify that the TIMESYNC have been not already processed
1062     */     */
# Line 669  Int_t PamelaDBOperations::insertPamelaGL Line 1071  Int_t PamelaDBOperations::insertPamelaGL
1071    if (result == NULL) throw -10;    if (result == NULL) throw -10;
1072    row = result->Next();    row = result->Next();
1073    if ((row != NULL) && ((UInt_t)atoll(row->GetField(0)) > 0)){    if ((row != NULL) && ((UInt_t)atoll(row->GetField(0)) > 0)){
1074        if ( IsDebug() ) printf(" found a timesync t0 is %u \n",t0);
1075      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;
1076        //
1077        tsync = (UInt_t)atoll(row->GetField(2));
1078        obt0 = (UInt_t)atoll(row->GetField(1));
1079        //
1080      return(1);      return(1);
1081    };    };
1082    //    //
# Line 726  Int_t PamelaDBOperations::insertPamelaGL Line 1133  Int_t PamelaDBOperations::insertPamelaGL
1133          //          //
1134          TYPE = 55;//224;          TYPE = 55;//224;
1135          //          //
1136            if ( IsDebug() ) printf("mcmd tsync %i tsync %u obt %u \n",i,TSYNC,OBT);
1137            //
1138          if ( TSYNC && OBT ){          if ( TSYNC && OBT ){
1139            existsts = true;            existsts = true;
1140            goto eout;            goto eout;
# Line 748  Int_t PamelaDBOperations::insertPamelaGL Line 1157  Int_t PamelaDBOperations::insertPamelaGL
1157      //      //
1158      rt->SetBranchAddress("RunTrailer", &runt);      rt->SetBranchAddress("RunTrailer", &runt);
1159      //      //
1160      if ( rhev > 0 ){      Int_t nrhev = rh->GetEntries();
1161        rh->GetEntry(0);      Int_t nrtev = rt->GetEntries();
1162        //      if ( IsDebug() ) printf(" ou nevent %i rhev %i rtev %i \n",nevent,nrhev,nrtev);
1163        TSYNC = runh->LAST_TIME_SYNC_INFO;      //
1164        OBT = runh->OBT_TIME_SYNC * 1000;      if ( nrhev > 0 ){
1165        //        for (Int_t i=0; i<nrhev; i++){
1166        TYPE = 20;          //
1167        //          rh->GetEntry(i);
1168        if ( TSYNC && OBT ){          //
1169          existsts = true;          TSYNC = runh->LAST_TIME_SYNC_INFO;
1170          goto eout;          OBT = runh->OBT_TIME_SYNC * 1000;
1171            //
1172            TYPE = 20;
1173            //
1174            if ( IsDebug() ) printf("runheader %i tsync %u obt %u \n",i,TSYNC,OBT);
1175            //
1176            if ( TSYNC && OBT ){
1177              existsts = true;
1178              goto eout;
1179            };
1180        };        };
1181        //        //
1182      };      };
1183      if ( rtev > 0 ){      if ( nrtev > 0 ){
1184        //        //
1185        if ( IsDebug() ) printf(" No runheader \n");        if ( IsDebug() ) printf(" No runheader \n");
1186        signal = 6;        signal = 6;
1187        //        //
1188        rt->GetEntry(0);        for (Int_t i=0; i<nrtev; i++){
1189        //          //
1190        TSYNC = runt->LAST_TYME_SYNC_INFO;          rt->GetEntry(i);
1191        OBT = runt->OBT_TYME_SYNC * 1000;          //
1192        //          TSYNC = runt->LAST_TYME_SYNC_INFO;
1193        TYPE = 21;          OBT = runt->OBT_TYME_SYNC * 1000;
1194        //          //
1195        if ( TSYNC && OBT ){          TYPE = 21;
1196          existsts = true;          //
1197          goto eout;          if ( IsDebug() ) printf("runtrailer %i tsync %u obt %u \n",i,TSYNC,OBT);
1198            //
1199            if ( TSYNC && OBT ){
1200              existsts = true;
1201              goto eout;
1202            };
1203        };        };
1204        //        //
1205      } else {      } else {
# Line 847  Int_t PamelaDBOperations::insertPamelaGL Line 1270  Int_t PamelaDBOperations::insertPamelaGL
1270    conn->Query(oss.str().c_str());    conn->Query(oss.str().c_str());
1271    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());
1272    //    //
1273      if ( IsDebug() ) printf(" found a timesync t0 is %u \n",t0);
1274    toffset = (UInt_t)TSYNC - (UInt_t)(this->OBT(OBT)/1000) + t0;    toffset = (UInt_t)TSYNC - (UInt_t)(this->OBT(OBT)/1000) + t0;
1275    //    //
1276      tsync = TSYNC;
1277      obt0 = OBT;
1278      //
1279    delete result;    delete result;
1280    return(signal);    return(signal);
1281  }  }
# Line 864  Int_t PamelaDBOperations::insertPamelaRo Line 1291  Int_t PamelaDBOperations::insertPamelaRo
1291    UInt_t idtimesync = 0;    UInt_t idtimesync = 0;
1292    //    //
1293    oss.str("");    oss.str("");
1294    oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "    if ( STATIC ){
1295        << " LEFT JOIN GL_ROOT "      oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1296        << " ON GL_RAW.ID = GL_ROOT.ID_RAW "          << " LEFT JOIN GL_ROOT "
1297        << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "          << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1298        << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";          << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "
1299            << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1300      } else {
1301        oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1302            << " LEFT JOIN GL_ROOT "
1303            << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1304            << " WHERE GL_RAW.PATH = '$PAM_RAW' AND "
1305            << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1306      };
1307    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1308    //    //
1309    if ( !result ) throw -12;    if ( !result ) throw -12;
# Line 895  Int_t PamelaDBOperations::insertPamelaRo Line 1330  Int_t PamelaDBOperations::insertPamelaRo
1330    idtimesync = (UInt_t)atoll(row->GetField(0));    idtimesync = (UInt_t)atoll(row->GetField(0));
1331    //    //
1332    oss.str("");    oss.str("");
1333    oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"    if ( STATIC ){
1334        << this->GetID_RAW() << "', '" << idtimesync << "', '" << this->GetRootPath().Data() << "', '" << this->GetRootFile().Data() << "')";      oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
1335            << this->GetID_RAW() << "', '" << idtimesync << "', '" << this->GetRootPath().Data() << "', '" << this->GetRootFile().Data() << "')";
1336      } else {
1337        oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
1338            << this->GetID_RAW() << "', '" << idtimesync << "', '$PAM_L0', '" << this->GetRootFile().Data() << "')";
1339      };
1340    //    //
1341    if (conn->Query(oss.str().c_str()) == 0) throw -4;    if (conn->Query(oss.str().c_str()) == 0) throw -4;
1342    //    //
# Line 923  Int_t PamelaDBOperations::assignBOOT_NUM Line 1363  Int_t PamelaDBOperations::assignBOOT_NUM
1363    TSQLResult *result = 0;    TSQLResult *result = 0;
1364    TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
1365    oss.str("");    oss.str("");
1366    oss << "SELECT ID, BOOT_NUMBER FROM GL_RAW WHERE "    if ( STATIC ){
1367        << " PATH = '" << this->GetRawPath().Data() << "' AND "      oss << "SELECT ID, BOOT_NUMBER FROM GL_RAW WHERE "
1368        << " NAME = '" << this->GetRawFile().Data() << "' ";          << " PATH = '" << this->GetRawPath().Data() << "' AND "
1369            << " NAME = '" << this->GetRawFile().Data() << "' ";
1370      } else {
1371        oss << "SELECT ID, BOOT_NUMBER FROM GL_RAW WHERE "
1372            << " PATH = '$PAM_RAW' AND "
1373            << " NAME = '" << this->GetRawFile().Data() << "' ";
1374      };
1375    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1376    //    //
1377    if ( !result ) throw -4;;    if ( !result ) throw -4;;
# Line 948  Int_t PamelaDBOperations::assignBOOT_NUM Line 1394  Int_t PamelaDBOperations::assignBOOT_NUM
1394    VarDumpEvent  *vde = 0;    VarDumpEvent  *vde = 0;
1395    VarDumpRecord *vdr = 0;    VarDumpRecord *vdr = 0;
1396    //    //
1397      Bool_t found = false;
1398    trDumpEv->SetBranchAddress("VarDump", &vde);    trDumpEv->SetBranchAddress("VarDump", &vde);
1399    if ( trDumpEv->GetEntries() > 0 ){    if ( trDumpEv->GetEntries() > 0 ){
1400      Bool_t found = false;      found = false;
1401      for ( Int_t i = 0; i < trDumpEv->GetEntries(); i++){      for ( Int_t i = 0; i < trDumpEv->GetEntries(); i++){
1402        trDumpEv->GetEntry(i);        trDumpEv->GetEntry(i);
1403        vde->Records->GetEntries();        //      vde->Records->GetEntries();
1404        if ( vde->Records->GetEntries()>0 ){        if ( vde->Records->GetEntries()>5 ){
1405          found = true;          found = true;
1406          goto fill;          goto fill;
1407        };        };
# Line 967  Int_t PamelaDBOperations::assignBOOT_NUM Line 1414  Int_t PamelaDBOperations::assignBOOT_NUM
1414        this->SetBOOTnumber((Int_t)vdr->VAR_VALUE);        this->SetBOOTnumber((Int_t)vdr->VAR_VALUE);
1415        //        //
1416      } else {      } else {
1417        if ( !this->GetBOOTnumber() ) return(4);        if ( !this->GetBOOTnumber() && !this->AutoBoot()) return(4);
1418        };
1419      } else {
1420        if ( !this->GetBOOTnumber() && !this->AutoBoot()) return(2);
1421      };
1422      //
1423      UInt_t bn = 0;
1424      Bool_t afound = false;
1425      if ( !found && this->AutoBoot()){
1426        afound = true;
1427        //
1428        // Search for other files with similar timesync
1429        //
1430        if ( IsDebug() ) printf(" tsync %u obt0 %u \n",tsync,obt0);
1431        UInt_t upperts = tsync-(obt0/1000)+5;
1432        UInt_t lowerts = tsync-(obt0/1000)-5;
1433        oss.str("");
1434        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)<"
1435            << upperts
1436            << " AND TIMESYNC-(OBT0/1000)>"
1437            << lowerts
1438            << " AND GL_RAW.BOOT_NUMBER>0 GROUP BY GL_TIMESYNC.OBT0;";
1439        result = conn->Query(oss.str().c_str());
1440        if ( IsDebug() ) printf(" Query the GL_TIMESYNC table to find boot number:\n %s \n",oss.str().c_str());
1441        //
1442        if ( !result ) throw -4;;
1443        found = true;
1444        if ( result->GetRowCount()<3 ){
1445          if ( IsDebug() ) printf(" AGH! no results!\n");
1446          found = false;
1447        } else {
1448          row = result->Next();      
1449          bn = (UInt_t)atoll(row->GetField(0));
1450          for ( Int_t r=1; r<result->GetRowCount() ;r++){
1451            if ( !row ) throw -4;
1452            if ( IsDebug() ) printf(" BOOT number is %s \n",row->GetField(0));
1453            if ( bn != (UInt_t)atoll(row->GetField(0)) ){
1454              if ( IsDebug() ) printf(" AGH! bn = %u here instead %u \n",bn,(UInt_t)atoll(row->GetField(0)));
1455              found = false;
1456            };
1457            row = result->Next();
1458          };
1459      };      };
1460      };
1461      //
1462      Int_t sgn = 0;
1463      //
1464      if ( !found && !BOOTNO ){
1465        throw -29;
1466    } else {    } else {
1467      if ( !this->GetBOOTnumber() ) return(2);      if ( afound ){
1468          this->SetBOOTnumber(bn);
1469          sgn = 8;
1470        };
1471    };    };
1472    //    //
1473    oss.str("");    oss.str("");
# Line 980  Int_t PamelaDBOperations::assignBOOT_NUM Line 1477  Int_t PamelaDBOperations::assignBOOT_NUM
1477    conn->Query(oss.str().c_str());          conn->Query(oss.str().c_str());      
1478    //    //
1479    delete result;    delete result;
1480    return(0);    return(sgn);
1481  };  };
1482    
1483  /**  /**
# Line 1243  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1740  Bool_t PamelaDBOperations::IsRunAlreadyI
1740      if ( glrun->GetNEVENTS() > (UInt_t)atoll(row->GetField(1)) ){      if ( glrun->GetNEVENTS() > (UInt_t)atoll(row->GetField(1)) ){
1741        //        //
1742        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");
1743        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1744        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1745        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) <<";";
1746        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1747    //       conn->Query(oss.str().c_str());
1748        if ( signal ) signal = false;        if ( signal ) signal = false;
1749        goto gonext;              goto gonext;      
1750        //        //
# Line 1260  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1758  Bool_t PamelaDBOperations::IsRunAlreadyI
1758        //        //
1759        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");
1760        //        //
1761        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1762        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1763        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) <<";";
1764        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1765    //       conn->Query(oss.str().c_str());
1766        //        //
1767        if ( signal ) signal = false;        if ( signal ) signal = false;
1768        goto gonext;        goto gonext;
# Line 1277  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1776  Bool_t PamelaDBOperations::IsRunAlreadyI
1776        //        //
1777        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");
1778        //        //
1779        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1780        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1781        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) <<";";
1782        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1783    //       conn->Query(oss.str().c_str());
1784        if ( signal ) signal = false;        if ( signal ) signal = false;
1785        //        //
1786      };      };
# Line 1295  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1795  Bool_t PamelaDBOperations::IsRunAlreadyI
1795    delete result;    delete result;
1796    //    //
1797    if ( signal && IsDebug() ) printf(" The run has already been inserted \n");        if ( signal && IsDebug() ) printf(" The run has already been inserted \n");    
1798      if ( !signal && IsDebug() ) printf(" The run existed and was deleted, fill the DB \n");
1799    return(signal);    return(signal);
1800  };  };
1801    
# Line 1316  void PamelaDBOperations::HandleRun(){   Line 1817  void PamelaDBOperations::HandleRun(){  
1817      //      //
1818      this->FillClass();      this->FillClass();
1819      //      //
1820      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);      if ( !IsRunAlreadyInserted() ){
1821          glrun->SetID(this->AssignRunID());
1822          glrun->SetID_RUN_FRAG(0);
1823          glrun->Fill_GL_RUN(conn);
1824        };
1825    } else {    } else {
1826      //      //
1827      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 1339  void PamelaDBOperations::HandleRunFragme Line 1844  void PamelaDBOperations::HandleRunFragme
1844    UInt_t rhfirstev = firstev;    UInt_t rhfirstev = firstev;
1845    UInt_t rtlastev = lastev;    UInt_t rtlastev = lastev;
1846    Bool_t found = false;    Bool_t found = false;
1847      Bool_t foundinrun = false;
1848    //    //
1849    TSQLResult *result = 0;    TSQLResult *result = 0;
1850    TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
# Line 1365  void PamelaDBOperations::HandleRunFragme Line 1871  void PamelaDBOperations::HandleRunFragme
1871    //    //
1872    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");
1873    //    //
1874    // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?    // First of all insert the run in the fragment table...
1875    //        //
1876    if ( mishead && rhfirstev == firstev ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is    oss.str("");
1877                                             // missing it no way we can found a piece in the frag table    oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
1878      //        << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
1879      oss.str("");        << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
1880      oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "        << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
1881          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "        << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
1882          << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME()        << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
1883          << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!        << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
1884      //        << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
1885      if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());        << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1886      result = conn->Query(oss.str().c_str());        << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
1887          << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
1888          << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
1889          << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
1890          << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
1891      //
1892      if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
1893      result = conn->Query(oss.str().c_str());
1894      //
1895      if ( !result ) throw -4;
1896      //
1897      row = result->Next();
1898      //
1899      if ( !row ){
1900        //
1901        // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
1902        //
1903        if ( IsDebug() ) printf(" The run is new \n");
1904        if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
1905        //
1906        glrun->SetID(this->AssignRunID());
1907        glrun->SetID_RUN_FRAG(0);
1908        glrun->Fill_GL_RUN_FRAGMENTS(conn);
1909        //
1910      } else {
1911        if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
1912        return;
1913      };
1914      //
1915      //
1916      // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
1917      //    
1918      if ( mishead && rhfirstev == firstev ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
1919                                               // missing it no way we can found a piece in the frag table
1920        //
1921        oss.str("");
1922        oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "
1923            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
1924            << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1925            << " ID != " << glrun->ID
1926            << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
1927        //
1928        if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());
1929        result = conn->Query(oss.str().c_str());
1930      //      //
1931      if ( !result ) throw -4;      if ( !result ) throw -4;
1932      //      //
1933      row = result->Next();      row = result->Next();
1934      //      //
1935        if ( !row && NoFrag() ){
1936          //
1937          oss.str("");
1938          oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
1939              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
1940              << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1941              << " ID != " << glrun->ID
1942              << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
1943          //
1944          if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
1945          result = conn->Query(oss.str().c_str());
1946          //
1947          if ( !result ) throw -4;
1948          //
1949          foundinrun = true;
1950          //
1951          row = result->Next();
1952          //
1953        };
1954        //
1955      if ( !row ){      if ( !row ){
1956        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
1957        found = false;        found = false;
# Line 1457  void PamelaDBOperations::HandleRunFragme Line 2026  void PamelaDBOperations::HandleRunFragme
2026        //        //
2027        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 ");
2028        //        //
2029          if ( foundinrun ){
2030            glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2031            glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2032          };
2033          //
2034        GL_RUN *glrun1 = new GL_RUN();        GL_RUN *glrun1 = new GL_RUN();
2035        //        //
2036        UInt_t idfrag = (UInt_t)atoll(row->GetField(0));        //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
2037        //        //
2038        oss.str("");        oss.str("");
2039        oss << " ID="<<row->GetField(0)<<";";        oss << " ID="<<row->GetField(0)<<";";
# Line 1488  void PamelaDBOperations::HandleRunFragme Line 2062  void PamelaDBOperations::HandleRunFragme
2062        };        };
2063        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);
2064        //        //
       glrun1->SetID(0);  
2065        glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());        glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
2066        glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());        glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
2067        glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());        glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
# Line 1497  void PamelaDBOperations::HandleRunFragme Line 2070  void PamelaDBOperations::HandleRunFragme
2070        //        //
2071        glrun->SetEV_FROM(firstev);        glrun->SetEV_FROM(firstev);
2072        glrun->SetNEVENTS(lastev-firstev+1);        glrun->SetNEVENTS(lastev-firstev+1);
2073          //
2074        glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());        glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
2075        glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());        glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
2076        glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());        glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
# Line 1516  void PamelaDBOperations::HandleRunFragme Line 2090  void PamelaDBOperations::HandleRunFragme
2090        //        //
2091        if ( !IsRunAlreadyInserted() ){        if ( !IsRunAlreadyInserted() ){
2092          //          //
2093            //      glrun->SetID(this->AssignRunID());
2094            glrun->SetID_RUN_FRAG(glrun1->GetID());
2095          glrun->Fill_GL_RUN(conn);          glrun->Fill_GL_RUN(conn);
2096          //          //
2097          // 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);  
2098          //          //
2099            glrun1->SetID_RUN_FRAG(glrun->GetID());
2100          glrun1->Fill_GL_RUN(conn);          glrun1->Fill_GL_RUN(conn);
2101          //          //
         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;  
         //  
2102        };        };
       //  
       delete glrun1;  
       //  
2103        // delete old entry in fragment table        // delete old entry in fragment table
2104        //        //
2105        oss.str("");        glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2106          glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2107        //        //
2108        oss << " DELETE FROM GL_RUN_FRAGMENTS WHERE ID = " << idfrag << ";";        delete glrun1;
2109        //        //
       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;  
2110        //        //
2111        return;        return;
2112        //        //
# Line 1585  void PamelaDBOperations::HandleRunFragme Line 2115  void PamelaDBOperations::HandleRunFragme
2115    };    };
2116    //    //
2117    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
2118                                             // 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
2119      //      //
2120      oss.str("");      oss.str("");
2121      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 "
2122          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2123          << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME()          << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2124            << " ID != " << glrun->ID
2125          << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";          << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2126      //      //
2127      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 1600  void PamelaDBOperations::HandleRunFragme Line 2131  void PamelaDBOperations::HandleRunFragme
2131      //      //
2132      row = result->Next();      row = result->Next();
2133      //      //
2134        if ( !row && NoFrag() ){
2135          //
2136          oss.str("");
2137          oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN WHERE "
2138              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2139              << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2140              << " ID != " << glrun->ID
2141              << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2142          //
2143          if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
2144          result = conn->Query(oss.str().c_str());
2145          //
2146          if ( !result ) throw -4;
2147          //
2148          foundinrun = true;
2149          row = result->Next();
2150          //
2151        };
2152        //
2153      if ( !row ){      if ( !row ){
2154        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2155        found = false;        found = false;
# Line 1673  void PamelaDBOperations::HandleRunFragme Line 2223  void PamelaDBOperations::HandleRunFragme
2223        //        //
2224        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 ");
2225        //        //
2226          if ( foundinrun ){
2227            glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2228            glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2229          };
2230          //
2231        GL_RUN *glrun1 = new GL_RUN();        GL_RUN *glrun1 = new GL_RUN();
2232        //        //
2233        UInt_t idfrag = (UInt_t)atoll(row->GetField(0));        //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
2234        //        //
2235        oss.str("");        oss.str("");
2236        oss << " ID="<<row->GetField(0)<<";";        oss << " ID="<<row->GetField(0)<<";";
# Line 1712  void PamelaDBOperations::HandleRunFragme Line 2267  void PamelaDBOperations::HandleRunFragme
2267        glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());        glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());
2268        glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());        glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());
2269        //        //
       glrun1->SetID(0);  
2270        glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());        glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());
2271        glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());        glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());
2272        glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());        glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());
# Line 1732  void PamelaDBOperations::HandleRunFragme Line 2286  void PamelaDBOperations::HandleRunFragme
2286        //        //
2287        if ( !IsRunAlreadyInserted() ){        if ( !IsRunAlreadyInserted() ){
2288          //          //
2289          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();  
2290          //          //
2291          UInt_t idrun0 = 0;          glrun->SetID_RUN_FRAG(glrun1->GetID());
2292          if ( !row ){          glrun->Fill_GL_RUN(conn);
           throw -10;  
         } else {  
           idrun0 = (UInt_t)atoll(row->GetField(0));  
         };  
2293          //          //
2294          glrun1->SetID_RUN_FRAG(idrun0);          // set id number
2295          //          //
2296            glrun1->SetID_RUN_FRAG(glrun->GetID());
2297          glrun1->Fill_GL_RUN(conn);          glrun1->Fill_GL_RUN(conn);
2298          //          //
         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;  
         //  
2299        };        };
2300        //        //
2301        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 << ";";  
2302        //        //
2303        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");
2304        result =  conn->Query(oss.str().c_str());        glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
       if ( !result ) throw -4;  
2305        //        //
2306          delete glrun1;
2307        //        //
2308        return;        return;
2309        //        //
# Line 1830  void PamelaDBOperations::HandleRunFragme Line 2340  void PamelaDBOperations::HandleRunFragme
2340      //      //
2341      row = result->Next();      row = result->Next();
2342      //      //
2343      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 {  
2344        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");
2345        } else {
2346          if ( NoFrag() ){
2347            glrun->SetID_RUN_FRAG(glrun->GetID());
2348            glrun->Fill_GL_RUN(conn);      
2349            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2350          };    
2351      };      };
2352    };    };
2353    //    //
# Line 1894  void PamelaDBOperations::HandleMissingHo Line 2373  void PamelaDBOperations::HandleMissingHo
2373      //      //
2374      this->FillClass(mishead,mistrail,firstev,lastev);      this->FillClass(mishead,mistrail,firstev,lastev);
2375      //      //
2376      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);          if ( !IsRunAlreadyInserted() ){
2377          glrun->SetID(this->AssignRunID());
2378          glrun->SetID_RUN_FRAG(0);
2379          glrun->Fill_GL_RUN(conn);    
2380        };
2381      //      //
2382    };    };
2383    //    //
# Line 2061  Bool_t PamelaDBOperations::IsRunConsiste Line 2544  Bool_t PamelaDBOperations::IsRunConsiste
2544            //                  //      
2545            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
2546            //            //
2547            if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                  if ( !IsRunAlreadyInserted() ){
2548                glrun->SetID(this->AssignRunID());
2549                glrun->SetID_RUN_FRAG(0);
2550                glrun->Fill_GL_RUN(conn);      
2551              };
2552            //            //
2553            firstevno = lastentry + 1;            firstevno = lastentry + 1;
2554            //            //
# Line 2137  void PamelaDBOperations::HandleSuspiciou Line 2624  void PamelaDBOperations::HandleSuspiciou
2624      if ( IsDebug() ) printf(" Checking but no events in the run! \n");      if ( IsDebug() ) printf(" Checking but no events in the run! \n");
2625      //      //
2626      this->FillClass();      this->FillClass();
2627      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);          if ( !IsRunAlreadyInserted() ){
2628          glrun->SetID(this->AssignRunID());
2629          glrun->SetID_RUN_FRAG(0);
2630          glrun->Fill_GL_RUN(conn);    
2631        };
2632      //      //
2633    } else {    } else {
2634      //      //
# Line 2165  void PamelaDBOperations::HandleSuspiciou Line 2656  void PamelaDBOperations::HandleSuspiciou
2656        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");
2657        //        //
2658        this->FillClass();        this->FillClass();
2659        if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                if ( !IsRunAlreadyInserted() ){
2660            glrun->SetID(this->AssignRunID());
2661            glrun->SetID_RUN_FRAG(0);
2662            glrun->Fill_GL_RUN(conn);        
2663          };
2664        //        //
2665      } else {      } else {
2666        //        //
# Line 2263  void PamelaDBOperations::HandleSuspiciou Line 2758  void PamelaDBOperations::HandleSuspiciou
2758            //                  //      
2759            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
2760            //            //
2761            if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                  if ( !IsRunAlreadyInserted() ){
2762                glrun->SetID(this->AssignRunID());
2763                glrun->SetID_RUN_FRAG(0);
2764                glrun->Fill_GL_RUN(conn);      
2765              };
2766            //            //
2767            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...
2768              //              //
# Line 2298  void PamelaDBOperations::HandleSuspiciou Line 2797  void PamelaDBOperations::HandleSuspiciou
2797              //                  //    
2798              this->SetCommonGLRUN(firstTime,lastTime);              this->SetCommonGLRUN(firstTime,lastTime);
2799              //              //
2800              if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                    if ( !IsRunAlreadyInserted() ){
2801                  glrun->SetID(this->AssignRunID());
2802                  glrun->SetID_RUN_FRAG(0);
2803                  glrun->Fill_GL_RUN(conn);      
2804                };
2805            };            };
2806            //            //
2807            firstevno = lastentry + 1;            firstevno = lastentry + 1;
# Line 2405  Int_t PamelaDBOperations::insertCALO_CAL Line 2908  Int_t PamelaDBOperations::insertCALO_CAL
2908                // no calibrations in the db contain our calibration                // no calibrations in the db contain our calibration
2909                //                //
2910                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);
2911                if ( fromtime < 1150863400 ){                if ( fromtime < 1150871000 ){ //1150866904
2912                  if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);                  if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);
2913                  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
2914                };                };
# Line 2468  Int_t PamelaDBOperations::insertCALO_CAL Line 2971  Int_t PamelaDBOperations::insertCALO_CAL
2971            //            //
2972          } else {          } else {
2973            //            //
2974            if ( IsDebug() ) printf(" Repetead calo calibration for section %i at time %i obt %i pkt %i \n",section,fromtime,obt,pkt);            if ( IsDebug() ) printf(" Repeated calo calibration for section %i at time %i obt %i pkt %i \n",section,fromtime,obt,pkt);
2975            //            //
2976          };                };      
2977          //                //      
# Line 2550  void PamelaDBOperations::HandleTRK_CALIB Line 3053  void PamelaDBOperations::HandleTRK_CALIB
3053        // no calibrations in the db contain our calibration        // no calibrations in the db contain our calibration
3054        //        //
3055        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");
3056        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
3057        //        //
3058        oss.str("");        oss.str("");
3059        oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "        oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "
# Line 2679  Int_t PamelaDBOperations::insertTRK_CALI Line 3182  Int_t PamelaDBOperations::insertTRK_CALI
3182      pkt1 = ph1->GetCounter();        pkt1 = ph1->GetCounter();  
3183      fromtime = this->GetAbsTime(ph1->GetOrbitalTime());        fromtime = this->GetAbsTime(ph1->GetOrbitalTime());  
3184      //      //
3185      valid = 1;  //     valid = 1;
3186      //  //     //
3187      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
3188      //      //
3189      //      //
3190      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) ){
3191        //        //
3192        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);
3193          //      
3194          valid = ValidateTrkCalib( caltrk1, eh1 );
3195          if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;
3196        //        //
3197        // Do we have the second calibration packet?        // Do we have the second calibration packet?
3198        //        //
# Line 2703  Int_t PamelaDBOperations::insertTRK_CALI Line 3209  Int_t PamelaDBOperations::insertTRK_CALI
3209            obt2 = ph2->GetOrbitalTime();              obt2 = ph2->GetOrbitalTime();  
3210            pkt2 = ph2->GetCounter();              pkt2 = ph2->GetCounter();  
3211            //            //
3212            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
3213            //                  //      
3214          } else {          } else {
3215            //            //
# Line 2734  Int_t PamelaDBOperations::insertTRK_CALI Line 3240  Int_t PamelaDBOperations::insertTRK_CALI
3240          //          //
3241          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);
3242          //          //
3243            UInt_t valid2 = ValidateTrkCalib( caltrk2, eh2 );
3244            if ( IsDebug() ) cout << " pkt2 validation --> "<<valid2<<endl;
3245            valid = valid & valid2;
3246            //
3247          // Handle good calib          // Handle good calib
3248          //          //
3249          this->HandleTRK_CALIB(true,true);          this->HandleTRK_CALIB(true,true);
# Line 2906  Int_t PamelaDBOperations::insertS4_CALIB Line 3416  Int_t PamelaDBOperations::insertS4_CALIB
3416            // no calibrations in the db contain our calibration            // no calibrations in the db contain our calibration
3417            //            //
3418            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");
3419            if ( fromtime < 1150863400 ){            if ( fromtime < 1150871000 ){  
3420              if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);              if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);
3421              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
3422            };            };
# Line 2979  Int_t PamelaDBOperations::insertS4_CALIB Line 3489  Int_t PamelaDBOperations::insertS4_CALIB
3489   * 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
3490   */   */
3491  Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(){  Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(){
3492      return(this->CleanGL_RUN_FRAGMENTS(""));
3493    };
3494    
3495    /**
3496     * Scan the fragment table and move old fragments to the GL_RUN table
3497     */
3498    Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(TString fcleanfile){
3499    //    //
3500    TSQLResult *result = 0;    TSQLResult *result = 0;
3501    TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
# Line 2986  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 3503  Int_t PamelaDBOperations::CleanGL_RUN_FR
3503    TSQLRow    *row2   = 0;    TSQLRow    *row2   = 0;
3504    //    //
3505    UInt_t moved = 0;    UInt_t moved = 0;
   UInt_t timelim = 0;  
   TDatime *time = new TDatime();  
3506    //    //
3507    stringstream oss;    stringstream oss;
3508    oss.str("");    oss.str("");
3509    //    //
3510    //    if ( !strcmp(fcleanfile.Data(),"") ){
3511    //      //
3512    if ( olderthan < 0 ){      // check if there are entries older than "olderthan" seconds from now
3513      if ( IsDebug() ) printf(" Do not clean GL_RUN_FRAGMENTS table \n");      //
3514      return(1);      oss.str("");
3515        oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
3516            << " INSERT_TIME <= '" << clean_time->AsSQLString() << "';";
3517        //
3518        if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS runs older than %s : query is \n %s \n",clean_time->AsSQLString(),oss.str().c_str());
3519        result = conn->Query(oss.str().c_str());
3520        //
3521      } else {
3522        oss.str("");
3523        oss << " SELECT ID FROM GL_ROOT WHERE NAME='" << fcleanfile.Data() << "';";
3524        if ( IsDebug() ) printf(" Getting ID_ROOT_L0 query %s \n",oss.str().c_str());
3525        result = conn->Query(oss.str().c_str());
3526        //    
3527        if ( result ){
3528          //
3529          row = result->Next();
3530          //
3531          if ( row ){
3532            oss.str("");
3533            oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
3534                << " ID_ROOT_L0=" << row->GetField(0) << ";";
3535            //
3536            if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS for ROOT file query is \n %s \n",oss.str().c_str());
3537            result = conn->Query(oss.str().c_str());
3538            //    
3539          };
3540        } else {
3541          return(2);
3542        };
3543    };    };
3544    //    //
   // timelim = now - olderthan  
   //  
   time->Set();  
   timelim =  (UInt_t)time->Convert() - olderthan;  
   time->Set(timelim,false);  
   //  
   // check if there are entries older than "olderthan" seconds from now  
   //  
   oss.str("");  
   oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"  
       << " INSERT_TIME <= '" << time->AsSQLString() << "';";  
   //  
   if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS runs older than %s : query is \n %s \n",time->AsSQLString(),oss.str().c_str());  
   result = conn->Query(oss.str().c_str());  
   //  
3545    if ( result ){    if ( result ){
3546      //      //
3547      row = result->Next();      row = result->Next();
3548      //      //
3549      if ( row ){      while ( row ){
3550        //        //
3551        oss.str("");        oss.str("");
3552        oss << " ID= "<< row->GetField(0);        oss << " ID= "<< row->GetField(0);
# Line 3053  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 3581  Int_t PamelaDBOperations::CleanGL_RUN_FR
3581          if ( IsDebug() ) printf(" The run is new \n");          if ( IsDebug() ) printf(" The run is new \n");
3582          if ( IsDebug() ) printf(" -> fill the DB \n");                if ( IsDebug() ) printf(" -> fill the DB \n");      
3583          //          //
3584          glrun->SetID(0);          //      glrun->SetID(this->AssignRunID()); we use the old run number!
3585            glrun->SetID_RUN_FRAG(glrun->GetID());
3586          glrun->Fill_GL_RUN(conn);            glrun->Fill_GL_RUN(conn);  
3587          //          //
3588          oss.str("");  //      oss.str("");
3589          oss << " SELECT ID FROM GL_RUN WHERE "  //      oss << " SELECT ID FROM GL_RUN WHERE "
3590              << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "  //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
3591              << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "  //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
3592              << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "  //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
3593              << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "  //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
3594              << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";  //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
3595          //  //      //
3596          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());
3597          result2 = conn->Query(oss.str().c_str());  //      result2 = conn->Query(oss.str().c_str());
3598          //  //      //
3599          if ( !result2 ) throw -4;  //      if ( !result2 ) throw -4;
3600          //  //      //
3601          row2 = result2->Next();  //      row2 = result2->Next();
3602          //  //      //
3603          if ( !row2 ) throw -25;  //      if ( !row2 ) throw -25;
3604          //  //      //
3605          oss.str("");  //      oss.str("");
3606          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);
3607          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());
3608          result2 = conn->Query(oss.str().c_str());  //      result2 = conn->Query(oss.str().c_str());
3609          //  //      //
3610          if ( !result2 ) throw -4;  //      if ( !result2 ) throw -4;
3611          //          //
3612          moved++;          moved++;
3613          //          //
# Line 3088  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 3617  Int_t PamelaDBOperations::CleanGL_RUN_FR
3617        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));      
3618        //        //
3619        //        //
3620        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3621        oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);  //      oss.str("");
3622        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);
3623        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());
3624        //  //       result2 = conn->Query(oss.str().c_str());
3625        if ( !result2 ) throw -4;  //      //
3626        //  //      if ( !result2 ) throw -4;
3627    //      //
3628          row = result->Next();
3629      };      };
3630    };    };
3631    if ( IsDebug() ) printf(" Moved %u runs\n",moved);    if ( IsDebug() ) printf(" Moved %u runs\n",moved);
# Line 3105  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 3636  Int_t PamelaDBOperations::CleanGL_RUN_FR
3636   * 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..
3637   */   */
3638  Int_t PamelaDBOperations::ValidateRuns(){  Int_t PamelaDBOperations::ValidateRuns(){
3639      return(this->ValidateRuns(""));
3640    };
3641    
3642    /**
3643     * Check if runs are good, i.e. if the tracker calibration is correctly associated..
3644     */
3645    Int_t PamelaDBOperations::ValidateRuns(TString valfile){
3646    //    //
3647    TSQLResult *result = 0;    TSQLResult *result = 0;
3648    // TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
3649    //    //
3650    UInt_t timelim = 0;    UInt_t calibtime = 50;
   TDatime *time = new TDatime();  
3651    //    //
3652    stringstream oss;    stringstream oss;
3653    oss.str("");    oss.str("");
3654    //    //
3655    //    // =======================================================
3656    //    // validate runs by checking missing calibrations
3657    if ( olderthan < 0 ){    // =======================================================
3658      if ( IsDebug() ) printf(" Do not validate runs \n");    UInt_t t_stop  = 0;
3659      return(1);    UInt_t t_start = 0;
3660    };    if ( !strcmp(valfile.Data(),"") ) {
3661    //      // --------------------------------------------------------------
3662    // timelim = now - olderthan      // 1) get the OBT of the last run inserted after clean-time limit
3663    //      // --------------------------------------------------------------
3664    time->Set();      oss.str("");
3665    timelim =  (UInt_t)time->Convert() - olderthan;      oss << " SELECT * FROM GL_RUN  WHERE INSERT_TIME <= '" << clean_time->AsSQLString()
3666    time->Set(timelim,false);          << "' ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
3667    //      if ( IsDebug() ) printf(" Get start validation-time: query is \n %s \n",oss.str().c_str());
3668    // First of all validate runs with default calibration:      result = conn->Query(oss.str().c_str());
3669    //      if ( !result ) throw -4;
3670    oss.str("");      if ( !result->GetRowCount() ) {
3671    oss << " UPDATE GL_RUN SET VALIDATION=1 WHERE"        printf(" No runs to validate \n");
3672        << " VALIDATION = 0 AND TRK_CALIB_USED=104 AND "        return(1);
3673        << " INSERT_TIME <= '" << time->AsSQLString() << "';";      }else{
3674    //        row = result->Next();
3675    if ( IsDebug() ) printf(" Validate runs with trk default calibration inserted before %s : query is \n %s \n",time->AsSQLString(),oss.str().c_str());        t_start = (UInt_t)atoll(row->GetField(4));
3676    result = conn->Query(oss.str().c_str());      };  
3677    //      // --------------------------------------------------------------
3678    if ( !result ) throw -4;      // 2) get the OBT of the last validated run
3679    //      // --------------------------------------------------------------
3680    return(0);      oss.str("");
3681        oss << " SELECT * FROM GL_RUN  WHERE VALIDATION=1 AND RUNHEADER_TIME<="<< t_start
3682            <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
3683        if ( IsDebug() ) printf(" Get stop validation-time: query is \n %s \n",oss.str().c_str());
3684        result = conn->Query(oss.str().c_str());
3685        if ( !result ) throw -4;
3686        if ( result->GetRowCount() ){
3687          row = result->Next();
3688          t_stop = (UInt_t)atoll(row->GetField(4));
3689        };
3690        if ( IsDebug() ) printf("Validation interval: from time %i - to time %i \n\n",t_stop,t_start);
3691        // --------------------------------------------------------------
3692        // now retrieves runs to be validated
3693        // --------------------------------------------------------------
3694        oss.str("");
3695        oss << " SELECT * FROM GL_RUN  WHERE  RUNHEADER_TIME <=" << t_start;
3696        oss << " AND RUNHEADER_TIME >="<< t_stop;
3697        oss << " ORDER BY RUNHEADER_TIME DESC;";
3698        if ( IsDebug() )printf(" Check runs for validation: query is \n %s \n",oss.str().c_str());
3699        result = conn->Query(oss.str().c_str());
3700      } else {
3701        //
3702        stringstream myquery;
3703        UInt_t myid = 0;
3704        myquery.str("");
3705        myquery << " SELECT ID FROM GL_ROOT where NAME='"<<valfile.Data() <<"';";
3706        //
3707        result = conn->Query(myquery.str().c_str());
3708        //
3709        row = result->Next();      
3710        if( !row ){
3711          if ( strcmp(valfile.Data(),GetRootName().Data()) ){
3712            if ( IsDebug() ) printf(" No file to be validated even if option \"-validate file\" was used!!\n");
3713            return(2);
3714          };
3715          if ( IsDebug() ) printf(" No file to be validated (force mode)! \n");
3716          return(0);
3717        };
3718        myid=(UInt_t)atoll(row->GetField(0));
3719        //
3720        myquery.str("");
3721        myquery << " SELECT MAX(RUNTRAILER_TIME),MIN(RUNHEADER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< myid <<";";
3722        //
3723        result = conn->Query(myquery.str().c_str());
3724        //
3725        row = result->Next();      
3726        if( !row->GetField(0) || !row->GetField(1)){
3727          //
3728          if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
3729          //
3730          return(0);
3731          //
3732        } else {  
3733          //
3734          UInt_t runhtime = (UInt_t)atoll(row->GetField(0));
3735          UInt_t runttime = (UInt_t)atoll(row->GetField(1));
3736          UInt_t caltime = 0;
3737          //
3738          myquery.str("");
3739          myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
3740          myquery << " order by FROM_TIME asc limit 1;";
3741          //
3742          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
3743          //
3744          //
3745          result = conn->Query(myquery.str().c_str());
3746          //
3747          row = result->Next();      
3748          if( !row ){
3749            caltime = runhtime;
3750          } else {
3751            caltime = (UInt_t)atoll(row->GetField(0));
3752          };
3753          //
3754          myquery.str("");
3755          myquery << " SELECT * from GL_RUN where RUNHEADER_TIME>="<< runttime <<" AND RUNHEADER_TIME<=" ;
3756          myquery << caltime << " order by RUNHEADER_TIME DESC";
3757          //
3758          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
3759          //
3760          result = conn->Query(myquery.str().c_str());
3761          //
3762        };
3763      };
3764      //
3765      if ( !result ) throw -4;
3766      if ( !result->GetRowCount() && IsDebug() ) printf(" No runs to validate \n");
3767      //
3768      Int_t nrow = 0;
3769      GL_RUN* this_run = new GL_RUN();
3770      GL_RUN* next_run = new GL_RUN();
3771      Int_t   nseq_max = 1000;
3772    //  UInt_t* sequence = new UInt_t[100];
3773      vector<UInt_t> sequence(nseq_max);
3774      Int_t   nseq = 0;
3775      Bool_t CHECK = false;
3776      Bool_t this_ONLINE = false;
3777      Bool_t next_ONLINE = false;
3778      UInt_t t1=0,t2=0;
3779      // ---------------------------------------------------------------------------------
3780      // - loop over runs, back in time,
3781      // - select sequences of runs close in time (less than calibtime s apart),
3782      //   which could be preceeded by a calibration
3783      // - check if there might be a missing calibration
3784      // ---------------------------------------------------------------------------------
3785      while(1){
3786              
3787              row = result->Next();
3788              if( row == NULL ) break;
3789              
3790              //------------
3791              //get run info
3792              //------------
3793              this_run->Set_GL_RUN(row);
3794                      
3795              Bool_t this_BAD = false;
3796              if(this_run->GetTRK_CALIB_USED() == 1 || this_run->GetTRK_CALIB_USED() == 2) this_ONLINE = true;
3797              else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;
3798              else{
3799    //                printf("Missing or corrupted header!! \n");
3800                      this_ONLINE = false;
3801                      this_BAD = true;
3802              };
3803    
3804              //-----------------------------------
3805              //compare with previous(next in time)
3806              //-----------------------------------
3807              CHECK = false;
3808              UInt_t interval=0;
3809              
3810              if( nrow != 0){
3811            
3812                      
3813                      t1 = this_run->GetRUNTRAILER_TIME();
3814                      t2 = next_run->GetRUNHEADER_TIME();
3815                      interval = (t2-t1);
3816                      
3817                      if(this_ONLINE && next_ONLINE){                               // this: ON-LINE + next: ON-LINE
3818                              
3819                              if( this_run->ID == next_run->ID_RUN_FRAG ) interval = 0;     //=> run fragments
3820                              
3821                              if( interval >= calibtime )CHECK = true;                      //more than calibtime s => there might be a calibration
3822                              
3823                              if( !CHECK && this_run->VALIDATION ){
3824                                      for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
3825                                      nseq=0;
3826                              }
3827                      
3828                      }else if( !this_ONLINE && next_ONLINE) {              // this: DEFAULT + next:ON-LINE
3829                              
3830                              CHECK = true;
3831    
3832                      }else if( !next_ONLINE ){                                             // this:ANY + next:DEFAULT
3833                              
3834                              assignVALIDATION(next_run->ID,true);
3835                              nseq=0;
3836                      }
3837              }
3838    
3839              //----------------------------
3840              //check run sequence for calib
3841              //----------------------------
3842              if( CHECK ){
3843                      // check if calibration exists
3844                      if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);
3845                      Bool_t MISSING = MissingTRK_CALIB(t1,t2);
3846                      for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],!MISSING);
3847                      nseq=0;
3848              };
3849              //--------------
3850              //store run info
3851              //--------------
3852              *next_run   = *this_run;
3853              next_ONLINE = this_ONLINE;
3854              if( !this_BAD ){
3855                      if(nseq < nseq_max){
3856                              sequence[nseq] = this_run->ID;
3857                              nseq++;
3858                      }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);
3859              };
3860              
3861              if ( IsDebug() ) printf("%i Run %i \n",nrow,this_run->ID);
3862              nrow++;
3863              
3864      };
3865      delete this_run;
3866      delete next_run;
3867      //
3868      return(0);
3869    };
3870    /**
3871     * Check if there might be a missing tracker calibration in a given time interval
3872     * @param t1 From absolute time
3873     * @param t2 To absolute time
3874     * @return true if there might be a missing calibration
3875     */
3876    Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
3877            
3878            GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();
3879            
3880            // get the closest VALIDATED calibration before the run start (t2)
3881            if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true);      //>>> missing
3882            
3883            if ( trkcalib->TO_TIME  < t2 ) return(true);                                    //>>> missing
3884            
3885            //==============================================================
3886            // Check is done first on the basis of time between calibration,
3887            // which should be equal to the time between ascending-nodes.
3888            //==============================================================
3889            if ( t2 - trkcalib->FROM_TIME > 5700) {
3890                    if ( IsDebug() )printf("Long time between calib and run start %i :-( ==> there might be a missing calib \n",t2 - trkcalib->FROM_TIME);
3891            //==============================================================
3892            // there might be a missing calibration, due to:
3893            // - MM full
3894            // - corrupted packets
3895            // - loss of data
3896            // There is an exception in case a download was done during ascending node
3897            //==============================================================
3898                    Bool_t DOWNLOAD = false;
3899                    // check if the calib was skipped becouse of download .... DA FARE!!
3900                    if(DOWNLOAD)return(false);
3901                    
3902                    return(true);                                   //>>> missing
3903                    
3904            };
3905            
3906            //==============================================================
3907            // If the last calibration is close to the run less than this time,
3908            // it is enough to say that there are no missing calibrations
3909            //==============================================================
3910            // the long time interval bewteen runs might be due to download
3911            if ( IsDebug() )printf("Short time between calib and run start %i :-) ==> OK! \n",t2 - trkcalib->FROM_TIME);
3912            return(false);
3913            
3914    };
3915    /**
3916     * Assign VALIDATION value to a GL_RUN entry
3917     * @param idrun Run ID
3918     * @param validation true/false
3919     */
3920    Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){
3921            TSQLResult *result = 0;
3922            stringstream oss;
3923            oss.str("");
3924            oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";
3925            //
3926    //      if ( IsDebug() )
3927    //      printf(" Set VALIDATION = %i for run %i \n",validation,idrun);
3928            if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());
3929            result = conn->Query(oss.str().c_str());
3930            if ( !result ) throw -4;
3931            return(0);
3932    }
3933    
3934    
3935    
3936    // Insert TLEs from file tlefilename in the table GL_TLE in the db
3937    // opened by conn, sorting them by date from older to newer, if each
3938    // TLE has not been alread inserted.
3939    Int_t PamelaDBOperations::populateTLE()//(TSQLServer *conn, char *tleFile)
3940    {
3941      fstream tlefile(tlefilename, ios::in);
3942    
3943      if ( !tlefile ) throw -7;
3944    
3945      vector<cTle*> ctles;
3946      vector<cTle*>::iterator iter;
3947      int present = 0;
3948    
3949      // Get three lines from tlefile, create a cTle object and put it
3950      // into ctles
3951      while(1) {
3952        cTle *tlef;
3953        string str1, str2, str3;
3954    
3955        getline(tlefile, str1);
3956        if(tlefile.eof()) break;
3957    
3958        getline(tlefile, str2);
3959        if(tlefile.eof()) break;
3960    
3961        getline(tlefile, str3);
3962        if(tlefile.eof()) break;
3963    
3964        // We now have three good lines for a cTle.
3965        tlef = new cTle(str1, str2, str3);
3966        ctles.push_back(tlef);
3967      }
3968    
3969      tlefile.close();
3970    
3971      // Sort by date
3972      sort(ctles.begin(), ctles.end(), compTLE);
3973    
3974      // Now we insert each TLE into the db
3975      for(iter = ctles.begin(); iter != ctles.end(); iter++) {
3976        cTle *tle = *iter;
3977    
3978        // Do nothing if it's already present in the db.  Just increase
3979        // the counter present.
3980        if (! isTlePresent(tle))
3981          {
3982            int status = insertTle(tle);
3983    
3984            // Insert query failed.  Return 1.
3985            if(status == EXIT_FAILURE) {
3986              
3987              if( IsDebug() ) {
3988                cerr << "Error: inserting TLE:" << endl
3989                     << tle->getName() << endl
3990                     << tle->getLine1() << endl
3991                     << tle->getLine2() << endl;
3992              }
3993    
3994              throw -4;
3995              return 1;
3996            }
3997    
3998          }
3999        else
4000          present++;
4001    
4002      }
4003    
4004      int inserted = ctles.size() - present;  // Number of inserted TLE.
4005      if ( IsDebug() )
4006        cout << "\nProcessed TLEs ranging from " << getTleDatetime(ctles[0]) << " to " << getTleDatetime(ctles[ctles.size()-1]) << "." << endl
4007             << inserted << " newly inserted TLEs out of " << ctles.size() << " processed." << endl;
4008    
4009      ctles.clear();
4010    
4011    
4012      // Return 2 if no new TLE has been inserted.  0 otherwise.
4013      if(! inserted ) return 2;
4014      return 0;
4015    }
4016    
4017    
4018    // Insert tle in the table GL_TLE using the connection conn.
4019    Int_t PamelaDBOperations::insertTle(cTle *tle)
4020    {
4021      stringstream oss;
4022      TSQLResult *result = 0;
4023    
4024      oss.str("");
4025      oss << " INSERT INTO GL_TLE (TLE1, TLE2, TLE3, FROM_TIME)"
4026          << " VALUES ( '"
4027          << tle->getName() << "', '"
4028          << tle->getLine1() << "', '"
4029          << tle->getLine2() << "', '"
4030          << getTleDatetime(tle) << "')";
4031    
4032      //  cout << oss.str().c_str() << endl;
4033      result = conn->Query(oss.str().c_str());
4034      if (result == NULL)
4035        return EXIT_FAILURE;
4036    
4037      return EXIT_SUCCESS;
4038    }
4039    
4040    
4041    // Return whether tle is already in the db connected by conn.
4042    bool PamelaDBOperations::isTlePresent(cTle *tle)
4043    {
4044      stringstream oss;
4045      TSQLResult *result = 0;
4046    
4047      oss.str("");
4048      oss << "SELECT * FROM GL_TLE WHERE FROM_TIME = '"
4049          << getTleDatetime(tle) << "'";
4050    
4051      result = conn->Query(oss.str().c_str());
4052      if (result == NULL) throw -4;
4053    
4054      if (result->GetRowCount())
4055        return true;
4056      else
4057        return false;
4058    }
4059    
4060    
4061    // Return whether the first TLE is dated early than the second
4062    bool compTLE (cTle *tle1, cTle *tle2)
4063    {
4064      return getTleJulian(tle1) < getTleJulian(tle2);
4065    }
4066    
4067    
4068    // Return the date of the tle using the format (year-2000)*1e3 +
4069    // julian day.  e.g. 6365 is the 31th Dec 2006.
4070    // It does *not* return a cJulian date.
4071    float getTleJulian(cTle *tle) {
4072      return tle->getField(cTle::FLD_EPOCHYEAR)*1e3 + tle->getField(cTle::FLD_EPOCHDAY);
4073    }
4074    
4075    
4076    // Return a string like YYYY-MM-DD hh:mm:ss, usable for mysql datetime
4077    // format.
4078    string getTleDatetime(cTle *tle)
4079    {
4080      int year, mon, day, hh, mm, ss;
4081      double dom; // day of month (is double!)
4082      stringstream date; // date in datetime format
4083    
4084      // create a cJulian from the date in tle
4085      cJulian jdate = cJulian( 2000 + (int) tle->getField(cTle::FLD_EPOCHYEAR), tle->getField(cTle::FLD_EPOCHDAY));
4086    
4087      // get year, month, day of month
4088      jdate.getComponent(&year, &mon, &dom);
4089    
4090      // build a datetime YYYY-MM-DD hh:mm:ss
4091      date.str("");
4092      day = (int) floor(dom);
4093      hh = (int) floor( (dom - day) * 24);
4094      mm = (int) floor( ((dom - day) * 24 - hh) * 60);
4095      ss = (int) floor( ((((dom - day) * 24 - hh) * 60 - mm) * 60));
4096      //  ms = (int) floor( (((((dom - day) * 24 - hh) * 60 - mm) * 60) - ss) * 1000);
4097    
4098      date << year << "-" << mon << "-" << day << " " << hh << ":" << mm << ":" << ss;
4099    
4100      return date.str();
4101    }
4102    
4103    /**
4104     * Remove a file from the DB, delete on cascade all entries related to that file
4105     * rearrange GL_RUN and GL_XXX_CALIB tables, turn off validation till the following
4106     * calibration
4107     **/
4108    Int_t PamelaDBOperations::removeFile(TString remfile){
4109      //
4110      // Determine ID_ROOT_L0 and ID_RAW
4111      //
4112      TSQLResult *pResult;
4113      TSQLRow *Row;
4114      stringstream myquery;
4115      //  
4116      myquery.str("");
4117      myquery << " SELECT ID, ID_RAW FROM GL_ROOT where NAME='"<<remfile.Data() <<"';";
4118      //
4119      pResult = conn->Query(myquery.str().c_str());
4120      //
4121      Row = pResult->Next();      
4122      if( !Row ){
4123        if ( strcmp(remfile.Data(),GetRootName().Data()) ){
4124          if ( IsDebug() ) printf(" No file to be removed even if option \"-remove file\" was used!!\n");
4125          return(1);
4126        };
4127        if ( IsDebug() ) printf(" No file to be removed (force mode)! \n");
4128        return(0);
4129      };
4130      //
4131      this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));
4132      this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));
4133      //
4134      this->ValidationOFF();
4135      //
4136      this->RemoveCALIBS();
4137      //
4138      this->RemoveRUNS();
4139      //
4140      this->RemoveFILES();
4141      //
4142      this->SetID_ROOT(0);
4143      this->SetID_RAW(0);
4144      //
4145      return(0);
4146    };
4147    
4148    /**
4149     *
4150     * Set validation bit to zero for runs following the removing file till
4151     * 1) a run with TRK_CALIB_USED=140
4152     * 2) a run with VALIDATION = 0
4153     * 3) the next calibration
4154     *
4155     **/
4156    void PamelaDBOperations::ValidationOFF(){
4157      TSQLResult *pResult;
4158      TSQLRow *Row;
4159      stringstream myquery;
4160      Int_t unv = 0;
4161      //select ID from GL_RUN where RUNHEADER_TIME>=1152671382 AND (VALIDATION=0 OR TRK_CALIB_USED=104) order by RUNHEADER_TIME asc limit 1;
4162      myquery.str("");
4163      myquery << " SELECT MAX(RUNTRAILER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
4164      //
4165      pResult = conn->Query(myquery.str().c_str());
4166      //
4167      Row = pResult->Next();      
4168      if( !Row->GetField(0) ){
4169        //
4170        if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
4171        //
4172      } else {  
4173        //
4174        UInt_t runhtime = (UInt_t)atoll(Row->GetField(0));
4175        UInt_t caltime = 0;
4176        //
4177        myquery.str("");
4178        myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
4179        myquery << " order by FROM_TIME asc limit 1;";
4180        //
4181        if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4182        //
4183        //
4184        delete pResult;
4185        pResult = conn->Query(myquery.str().c_str());
4186        //
4187        Row = pResult->Next();      
4188        if( !Row ){
4189          caltime = runhtime;
4190        } else {
4191          caltime = (UInt_t)atoll(Row->GetField(0));
4192        };
4193        //
4194        myquery.str("");
4195        myquery << " SELECT ID,RUNHEADER_TIME from GL_RUN where RUNHEADER_TIME>="<< runhtime <<" AND (VALIDATION=0 OR TRK_CALIB_USED=104 OR RUNHEADER_TIME>" ;
4196        myquery << caltime << ") order by RUNHEADER_TIME asc LIMIT 1";
4197        //
4198        if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4199        //
4200        pResult = conn->Query(myquery.str().c_str());
4201        //
4202        Row = pResult->Next();      
4203        if( !Row ){
4204          //
4205          if ( IsDebug() ) printf(" NO RUN NEED TO BE UNVALIDATED \n");
4206          //
4207        } else {
4208          myquery.str("");
4209          myquery << " SELECT ID from GL_RUN where RUNHEADER_TIME<"<< Row->GetField(1) <<" AND ";
4210          myquery << " RUNHEADER_TIME>=" <<runhtime;
4211          myquery << " order by RUNHEADER_TIME asc;";
4212          //
4213          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4214          //
4215          pResult = conn->Query(myquery.str().c_str());
4216          //
4217          Row = pResult->Next();  
4218          while ( Row ){
4219            //      
4220            unv++;
4221            this->assignVALIDATION((UInt_t)atoll(Row->GetField(0)), false);
4222            Row = pResult->Next();  
4223            //
4224          };
4225        };
4226      };
4227      if ( IsDebug() ) printf(" %i runs have been unvalidated \n",unv);
4228    };
4229    
4230    /**
4231     *
4232     * Rearrange GL_RUN table and remove runs
4233     *
4234     **/
4235    void PamelaDBOperations::RemoveRUNS(){
4236      TSQLResult *pResult;
4237      TSQLRow *Row;
4238      stringstream myquery;
4239      UInt_t drun = 0;
4240      GL_RUN *delrun = new GL_RUN();
4241      //
4242      myquery.str("");
4243      myquery << " SELECT ID FROM GL_RUN where ID_RUN_FRAG=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4244      //
4245      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4246      //
4247      pResult = conn->Query(myquery.str().c_str());
4248      //
4249      Row = pResult->Next();    
4250      //
4251      //
4252      if ( !Row ){
4253        if ( IsDebug() ) printf(" No run with ID_RUN_FRAG=0 belonged to this file \n");
4254      } else {
4255        if ( IsDebug() ) printf(" Deleting run from GL_RUN table \n");    
4256        while ( Row ){
4257          delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
4258          if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(0)));
4259          drun++;
4260          Row = pResult->Next();    
4261        };
4262      };
4263      //
4264      //
4265      myquery.str("");
4266      myquery << " SELECT ID,ID_RUN_FRAG FROM GL_RUN where ID_RUN_FRAG!=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4267      //
4268      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4269      //
4270      pResult = conn->Query(myquery.str().c_str());
4271      //
4272      Row = pResult->Next();    
4273      //
4274      if ( !Row ){
4275        if ( IsDebug() ) printf(" No run with ID_RUN_FRAG!=0 belonged to this file \n");
4276      } else {
4277        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN table \n");    
4278        while ( Row ){
4279          if ( IsDebug() ) printf(" restore run %i \n",(UInt_t)atoll(Row->GetField(1)));
4280          delrun->RestoreRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN_FRAGMENTS");
4281          if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(1)));
4282          delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN");
4283          if ( (UInt_t)atoll(Row->GetField(1)) != (UInt_t)atoll(Row->GetField(0)) ){
4284            if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(0)));
4285            delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
4286          };
4287          drun++;
4288          Row = pResult->Next();    
4289        };
4290      };
4291      //
4292      if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN table \n",drun);    
4293      //
4294      //
4295      //
4296      drun = 0;
4297      //
4298      myquery.str("");
4299      myquery << " SELECT ID_TRASH FROM GL_RUN_TRASH where BELONGED_TO='GL_RUN_FRAGMENTS' AND ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4300      //
4301      pResult = conn->Query(myquery.str().c_str());
4302      //
4303      Row = pResult->Next();    
4304      //
4305      if ( !Row ){
4306        if ( IsDebug() ) printf(" No run from GL_RUN_FRAGMENTS table in the trash table for this file \n");
4307      } else {
4308        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_TRASH table \n");    
4309        while ( Row ){
4310          if ( IsDebug() ) printf(" del run idtrash %i \n",(UInt_t)atoll(Row->GetField(0)));
4311          myquery.str("");
4312          myquery << " DELETE FROM GL_RUN_TRASH where ID_TRASH=" << Row->GetField(0) <<";";      
4313          conn->Query(myquery.str().c_str());
4314          drun++;
4315          Row = pResult->Next();    
4316        };
4317      };
4318      //  
4319      if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN_TRASH table \n",drun);    
4320      //
4321      //
4322      //
4323      drun = 0;
4324      //
4325      myquery.str("");
4326      myquery << " SELECT ID FROM GL_RUN_FRAGMENTS where ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4327      //
4328      pResult = conn->Query(myquery.str().c_str());
4329      //
4330      Row = pResult->Next();    
4331      //
4332      if ( !Row ){
4333        if ( IsDebug() ) printf(" No run in the GL_RUN_FRAGMENTS table for this file \n");
4334      } else {
4335        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_FRAGMENTS table \n");    
4336        while ( Row ){
4337          if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(0)));
4338          myquery.str("");
4339          myquery << " DELETE FROM GL_RUN_FRAGMENTS where ID=" << Row->GetField(0) <<";";
4340          conn->Query(myquery.str().c_str());
4341          drun++;
4342          Row = pResult->Next();    
4343        };
4344      };
4345      //  
4346      if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN_FRAGMENTS table \n",drun);    
4347      //
4348      //
4349      //
4350      delete delrun;
4351      //
4352    };
4353    
4354    
4355    /**
4356     *
4357     * Rearrange calibration tables
4358     *
4359     **/
4360    void PamelaDBOperations::RemoveFILES(){
4361      stringstream myquery;
4362      //
4363      myquery.str("");
4364      myquery << " DELETE FROM GL_RAW WHERE ID=" <<this->GetID_RAW() <<";";
4365      //
4366      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4367      //
4368      conn->Query(myquery.str().c_str());
4369      //
4370    };
4371    
4372    /**
4373     *
4374     * Rearrange calibration tables
4375     *
4376     **/
4377    void PamelaDBOperations::RemoveCALIBS(){
4378      TSQLResult *pResult;
4379      TSQLRow *Row;
4380      stringstream myquery;
4381      //  
4382      //
4383      // Calorimeter
4384      //
4385      for (Int_t section = 0; section < 4; section++){
4386        myquery.str("");
4387        myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_CALO_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<" AND ";
4388        myquery << " SECTION=" << section << ";";
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 CALO CALIBRATION SECTION %i ASSOCIATED TO THIS FILE! \n",section);
4396          //
4397        } else {
4398          //
4399          myquery.str("");
4400          myquery << " UPDATE GL_CALO_CALIB SET TO_TIME=" << Row->GetField(1);
4401          myquery << " WHERE TO_TIME="<< Row->GetField(0) << " AND ";
4402          myquery << " SECTION=" << section << ";";
4403          //
4404          pResult = conn->Query(myquery.str().c_str());
4405          //
4406          if( !pResult ){
4407            //
4408            if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
4409            //
4410            throw -4;
4411            //
4412          };
4413          //
4414        };
4415      };
4416      myquery.str("");
4417      myquery << " DELETE FROM GL_CALO_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4418      //
4419      pResult = conn->Query(myquery.str().c_str());
4420      //
4421      if( !pResult ){
4422        //
4423        if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
4424        //
4425        throw -4;
4426        //
4427      };
4428      //
4429      // Tracker
4430      //
4431      myquery.str("");
4432      myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_TRK_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
4433      //
4434      pResult = conn->Query(myquery.str().c_str());
4435      //
4436      Row = pResult->Next();      
4437      if( !Row->GetField(0) || !Row->GetField(1) ){
4438        //
4439        if ( IsDebug() ) printf(" NO TRK CALIBRATION ASSOCIATED TO THIS FILE! \n");
4440        //
4441      } else {
4442        //
4443        myquery.str("");
4444        myquery << " UPDATE GL_TRK_CALIB SET TO_TIME=" << Row->GetField(1);
4445        myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
4446        //
4447        pResult = conn->Query(myquery.str().c_str());
4448        //
4449        if( !pResult ){
4450          //
4451          if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
4452          //
4453          throw -4;
4454          //
4455        };
4456        //
4457        myquery.str("");
4458        myquery << " DELETE FROM GL_TRK_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4459        //
4460        pResult = conn->Query(myquery.str().c_str());
4461        //
4462        if( !pResult ){
4463          //
4464          if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
4465          //
4466          throw -4;
4467          //
4468        };
4469      };
4470      //
4471      //
4472      // S4
4473      //
4474      myquery.str("");
4475      myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_S4_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
4476      //
4477      pResult = conn->Query(myquery.str().c_str());
4478      //
4479      Row = pResult->Next();      
4480      if( !Row->GetField(0) || !Row->GetField(1) ){
4481        //
4482        if ( IsDebug() ) printf(" NO S4 CALIBRATION ASSOCIATED TO THIS FILE! \n");
4483        //
4484      } else {
4485        //
4486        myquery.str("");
4487        myquery << " UPDATE GL_S4_CALIB SET TO_TIME=" << Row->GetField(1);
4488        myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
4489        //
4490        pResult = conn->Query(myquery.str().c_str());
4491        //
4492        if( !pResult ){
4493          //
4494          if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
4495          //
4496          throw -4;
4497          //
4498        };
4499        //
4500        myquery.str("");
4501        myquery << " DELETE FROM GL_S4_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4502        //
4503        pResult = conn->Query(myquery.str().c_str());
4504        //
4505        if( !pResult ){
4506          //
4507          if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
4508          //
4509          throw -4;
4510          //
4511        };
4512        //
4513      };
4514    };
4515    
4516    /**
4517     *
4518     * Rearrange calibration tables
4519     *
4520     **/
4521    UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh ){
4522    
4523        Int_t vorder[]={5,5,3,3,4,4,2,2,1,1,0,0};
4524        UInt_t timeaftercalib=120000; //2000;
4525    //  ----------
4526    //  Check CRCs
4527    //  ----------
4528        for(Int_t ipkt=0; ipkt<6; ipkt++){
4529            if( caltrk->crc_hcal[ipkt] )return 0; // :-(
4530            for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] )return 0; // :-(
4531        }
4532    //  -----------------------
4533    //  Check missing packets:
4534    //  -----------------------
4535    //    Readout order:
4536    //    ------------------
4537    //    DSP   packet board
4538    //    ------------------
4539    //    12    0      1
4540    //    10    1      1
4541    //     8    2      1
4542    //     4    3      1
4543    //     6    4      1
4544    //     2    5      1
4545    //    ------------------
4546    //    11    0      2
4547    //     9    1      2
4548    //     7    2      2
4549    //     3    3      2
4550    //     5    4      2
4551    //     1    5      2
4552    //    ------------------
4553    //  -------------------------------------------------
4554    //  Check if it is first or second calibration packet
4555    //  -------------------------------------------------
4556        UInt_t build=0;
4557        TString classname = caltrk->GetName();
4558        UInt_t base=0;
4559        UInt_t mask=0;
4560        if(classname.Contains("CalibTrk1Event")){
4561            base=12;
4562            mask=0x03F000;
4563        }
4564        if(classname.Contains("CalibTrk2Event")){
4565            base=18;
4566            mask=0xFC0000;
4567        }
4568    //  -------------------------------------------------
4569    //  Count number of packets and set build variable
4570    //  -------------------------------------------------
4571        Int_t  npkts=0;
4572        for(Int_t ipkt=0; ipkt<6; ipkt++){
4573            if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
4574                npkts++;
4575                build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );
4576            }
4577        }
4578    //    if( npkts==6 )return 1; // :-)
4579    
4580    //    cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime()<<endl;
4581    
4582    //  -----------------------------------------------
4583    //  If missing packets: check the acq configuration
4584    //  (some DSPs might be excluded from acquisition)
4585    //  -----------------------------------------------
4586    
4587    //  -----------------------------------------------
4588    //  retrieve the first run header after calib
4589    //  -----------------------------------------------
4590         PacketType *pctp;
4591         EventCounter *cod;
4592         cod = eh->GetCounter();
4593         Int_t irun = cod->Get(pctp->RunHeader);
4594         TTree *rh=(TTree*)file->Get("RunHeader");
4595         if ( !rh || rh->IsZombie() ) throw -17;
4596         if( rh->GetEntries() == irun ){
4597              if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (1)  -- cannot validate :-( "<<endl;
4598             return 0; // :-(
4599         }
4600    
4601         RunHeaderEvent *run  = 0;
4602         EventHeader    *hrun = 0;
4603         rh->SetBranchAddress("RunHeader", &run);
4604         rh->SetBranchAddress("Header", &hrun);
4605         rh->GetEntry(irun);
4606    //     cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime() << " Run " << hrun->GetPscuHeader()->GetOrbitalTime() <<endl;
4607    
4608         if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){
4609              if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (2) -- cannot validate :-( "<<endl;
4610             return 0; // :-(
4611         }
4612        
4613         if( !run->RM_ACQ_AFTER_CALIB ){
4614              if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) RM_ACQ_AFTER_CALIB=0    -- cannot validate :-( "<<endl;
4615             return 0; // :-(
4616         }
4617    
4618         UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());
4619         if( dtime > timeaftercalib ){
4620             if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;
4621             return 0; // :-(
4622         }
4623        
4624    
4625    
4626         if( (run->ACQ_BUILD_INFO & mask) != build ){
4627             if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) ACQ_BUILD_INFO= >>> "<<hex << (run->ACQ_BUILD_INFO&mask) << " != "<< build << dec<<endl;
4628             return 0; // :-(
4629         }
4630         return 1; // :-)
4631    
4632    }
4633    
4634    /**
4635     *
4636     * Check the DB (only for overlapping runs at the moment)
4637     *
4638     **/
4639    UInt_t PamelaDBOperations::Check(){
4640      //
4641      UInt_t test = 0;
4642      //
4643      UInt_t thisrht = 0;
4644      UInt_t thisrtt = 0;
4645      UInt_t thisid = 0;
4646      UInt_t prevrht = 0;
4647      UInt_t prevrtt = 0;
4648      UInt_t previd = 0;
4649      //
4650      UInt_t prevl0id = 0;
4651      UInt_t thisl0id = 0;
4652      //
4653      stringstream oss;
4654      TSQLResult *result = 0;
4655      TSQLRow    *row    = 0;
4656      TSQLResult *result2 = 0;
4657      TSQLRow    *row2    = 0;
4658      oss.str("");
4659      oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN order by RUNHEADER_TIME asc;";
4660      //  oss << "SELECT ID,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN where ID>10170 and ID<10190 order by RUNHEADER_TIME asc;";
4661      result = conn->Query(oss.str().c_str());
4662      //
4663      if ( !result ) throw -4;;
4664      //
4665      row = result->Next();
4666      //
4667      while ( row ){
4668        thisid = (UInt_t)atoll(row->GetField(0));
4669        thisl0id = (UInt_t)atoll(row->GetField(1));
4670        thisrht = (UInt_t)atoll(row->GetField(2));
4671        thisrtt = (UInt_t)atoll(row->GetField(3));
4672        //
4673        //    if ( thisrht < prevrtt || thisrtt < prevrht || thisrht > thisrtt && !(!prevrht && !prevrtt &&!previd) ){
4674        //    if ( (thisrht < prevrtt || thisrtt < prevrht || thisrht > thisrtt) && (thisrht != prevrht) ){
4675        if ( (thisrht < prevrtt) && (thisrht != prevrht) ){
4676          if ( IsDebug() ) printf(" IDprev %u ID %u    prevrht %u prevrtt %u  thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
4677          printf(" CHECK n.1 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrht-prevrtt),previd,thisid);
4678          TString prevf = "";
4679          TString thisf = "";
4680          oss.str("");
4681          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
4682          result2 = conn->Query(oss.str().c_str());
4683          if ( !result2 ) throw -4;;
4684          row2 = result2->Next();
4685          prevf = (TString)row2->GetField(0);
4686          oss.str("");
4687          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
4688          result2 = conn->Query(oss.str().c_str());
4689          if ( !result2 ) throw -4;;
4690          row2 = result2->Next();
4691          thisf = (TString)row2->GetField(0);
4692          if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
4693          test = 1;
4694        };
4695        //
4696        if ( (thisrtt < prevrht) && (thisrht != prevrht) ){
4697          if ( IsDebug() ) printf(" IDprev %u ID %u    prevrht %u prevrtt %u  thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
4698          printf(" CHECK n.2 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrtt-prevrht),previd,thisid);
4699          TString prevf = "";
4700          TString thisf = "";
4701          oss.str("");
4702          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
4703          result2 = conn->Query(oss.str().c_str());
4704          if ( !result2 ) throw -4;;
4705          row2 = result2->Next();
4706          prevf = (TString)row2->GetField(0);
4707          oss.str("");
4708          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
4709          result2 = conn->Query(oss.str().c_str());
4710          if ( !result2 ) throw -4;;
4711          row2 = result2->Next();
4712          thisf = (TString)row2->GetField(0);
4713          if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
4714          test = 1;
4715        };
4716        //
4717        if ( (thisrht > thisrtt) && (thisrht != prevrht) ){
4718          if ( IsDebug() ) printf(" IDprev %u ID %u    prevrht %u prevrtt %u  thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
4719          printf(" CHECK n.3 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrht-thisrtt),previd,thisid);
4720          TString prevf = "";
4721          TString thisf = "";
4722          oss.str("");
4723          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
4724          result2 = conn->Query(oss.str().c_str());
4725          if ( !result2 ) throw -4;;
4726          row2 = result2->Next();
4727          prevf = (TString)row2->GetField(0);
4728          oss.str("");
4729          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
4730          result2 = conn->Query(oss.str().c_str());
4731          if ( !result2 ) throw -4;;
4732          row2 = result2->Next();
4733          thisf = (TString)row2->GetField(0);
4734          if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
4735          test = 1;
4736        };
4737    
4738        //
4739        prevrht = thisrht;
4740        prevrtt = thisrtt;
4741        previd = thisid;
4742        prevl0id = thisl0id;
4743        row = result->Next();
4744      };
4745      //
4746      return(test);
4747      //
4748  };  };

Legend:
Removed from v.1.2  
changed lines
  Added in v.1.30

  ViewVC Help
Powered by ViewVC 1.1.23