/[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.1 by mocchiut, Wed Aug 30 11:18:13 2006 UTC revision 1.26 by mocchiut, Wed Jan 31 16:15:03 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 29  Line 30 
30  #include <varDump/VarDumpEvent.h>  #include <varDump/VarDumpEvent.h>
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  //using namespace yngn::util;  
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.
# Line 48  using namespace pamela; Line 54  using namespace pamela;
54   * @param obt0         file obt0.   * @param obt0         file obt0.
55   * @param tsync        file timesync.   * @param tsync        file timesync.
56   * @param debug        debug flag.   * @param debug        debug flag.
57     * @param tlefilename  ascii file with TLE 3 line elements.
58   */   */
59  PamelaDBOperations::PamelaDBOperations(TString host, TString user, TString password, TString filerawname, TString filerootname, UInt_t boot, UInt_t tsync, UInt_t obt0, Bool_t debug){  PamelaDBOperations::PamelaDBOperations(TString host, TString user, TString password, TString filerawname, TString filerootname, UInt_t boot, UInt_t tsync, UInt_t obt0, Bool_t debug, TString tlefilename){
60    //    //
61    //    //
62    SetConnection(host,user,password);    SetConnection(host,user,password);
# Line 63  PamelaDBOperations::PamelaDBOperations(T Line 70  PamelaDBOperations::PamelaDBOperations(T
70    SetTsync(tsync);    SetTsync(tsync);
71    SetObt0(obt0);    SetObt0(obt0);
72    //    //
73      SetTLEPath(tlefilename);
74      //
75    //    //
76    SetRootName(filerootname);    INSERT_RAW =!filerawname.IsNull();
77    SetRawName(filerawname);    if(INSERT_RAW)SetRawName(filerawname);
78    //    //
79    this->OpenFile();    INSERT_ROOT = !filerootname.IsNull();
80      if( INSERT_ROOT ){
81        this->SetRootName(filerootname);
82        this->SetOrbitNo();
83        file = TFile::Open(this->GetRootName().Data());
84      } else {
85        this->SetRootName("");
86      };
87    //    //
88    this->SetID_RAW(0);    this->SetID_RAW(0);
89    this->SetID_ROOT(0);    this->SetID_ROOT(0);
90    
91      VALIDATE = false;
92      
93    //    //
94  };  };
95    
# Line 79  PamelaDBOperations::PamelaDBOperations(T Line 98  PamelaDBOperations::PamelaDBOperations(T
98   */   */
99  void PamelaDBOperations::Close(){  void PamelaDBOperations::Close(){
100    if( conn && conn->IsConnected() ) conn->Close();    if( conn && conn->IsConnected() ) conn->Close();
101      delete clean_time;
102    delete glrun;    delete glrun;
103    delete this;    delete this;
104  };  };
# Line 87  void PamelaDBOperations::Close(){ Line 107  void PamelaDBOperations::Close(){
107  // SETTERS  // SETTERS
108  //  //
109    
110    //
111    // 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
112    //
113    void PamelaDBOperations::CheckValidate(Long64_t olderthan){
114      clean_time = new TDatime();
115      //
116      if(olderthan >= 0){
117        VALIDATE = true;
118        UInt_t timelim = 0;
119        timelim =  (UInt_t)clean_time->Convert(true) - olderthan;
120        clean_time->Set(timelim,false);
121      };
122    };
123    
124  /**  /**
125   * Open the DB connection   * Open the DB connection
126   * @param host         hostname for the SQL connection.   * @param host         hostname for the SQL connection.
# Line 94  void PamelaDBOperations::Close(){ Line 128  void PamelaDBOperations::Close(){
128   * @param password     password for the SQL connection.   * @param password     password for the SQL connection.
129   */   */
130  void PamelaDBOperations::SetConnection(TString host, TString user, TString password){  void PamelaDBOperations::SetConnection(TString host, TString user, TString password){
131      if ( IsDebug() ) printf(" Connecting using host = %s user = %s password = %s \n",host.Data(),user.Data(),password.Data());
132    conn = TSQLServer::Connect(host.Data(),user.Data(),password.Data());    conn = TSQLServer::Connect(host.Data(),user.Data(),password.Data());
133  };  };
134    
# Line 122  void PamelaDBOperations::SetDebugFlag(Bo Line 157  void PamelaDBOperations::SetDebugFlag(Bo
157  };  };
158    
159  /**  /**
160     * Set the autoboot flag
161     *
162     */
163    void PamelaDBOperations::SetAutoBoot(Bool_t dbg){
164      AUTOBOOT = dbg;
165    };
166    
167    /**
168     * Set the nofrag flag
169     *
170     */
171    void PamelaDBOperations::SetNoFrag(Bool_t nf){
172      NOFRAG = nf;
173    };
174    
175    /**
176   * Store the BOOT number of the RAW file.   * Store the BOOT number of the RAW file.
177   * @param boot    BOOT number of the RAW file   * @param boot    BOOT number of the RAW file
178   */   */
# Line 162  void PamelaDBOperations::SetRootName(TSt Line 213  void PamelaDBOperations::SetRootName(TSt
213  };  };
214    
215  /**  /**
216     * Store the downlink orbit number from filename.
217     */
218    void PamelaDBOperations::SetOrbitNo(){
219      dworbit = 0;
220      TString name = this->GetRootFile();
221      Int_t nlength = name.Length();
222      if ( nlength < 5 ) return;
223      TString dwo = 0;
224      for (Int_t i = 0; i<5; i++){
225        dwo.Append(name[i],1);
226      };
227      if ( dwo.IsDigit() ){
228        dworbit = (UInt_t)dwo.Atoi();
229      } else {
230        dwo="";
231        for (Int_t i = 8; i<13; i++){
232          dwo.Append(name[i],1);
233        };    
234        if ( dwo.IsDigit() ) dworbit = (UInt_t)dwo.Atoi();
235      };
236      if ( IsDebug() ) printf(" Downlink orbit is %i (dwo = %s) \n",dworbit,dwo.Data());
237      return;
238    };
239    
240    
241    
242    /**
243   * Store the NOBOOT flag.   * Store the NOBOOT flag.
244   * @param noboot    true/false.   * @param noboot    true/false.
245   */   */
# Line 170  void PamelaDBOperations::SetNOBOOT(Bool_ Line 248  void PamelaDBOperations::SetNOBOOT(Bool_
248  };  };
249    
250  /**  /**
251     * Store path to the TLE file.
252     */
253    void PamelaDBOperations::SetTLEPath(TString str){
254      tlefilename = str;
255    };
256    
257    /**
258     * Store the olderthan variable
259     * @param olderthan
260     */
261    // void PamelaDBOperations::SetOlderThan(Long64_t oldthan){
262    //   olderthan = oldthan;
263    // };
264    
265    /**
266   * Retrieve the ID_RAW, if exists, returns NULL if does not exist.   * Retrieve the ID_RAW, if exists, returns NULL if does not exist.
267   */   */
268  Bool_t PamelaDBOperations::SetID_RAW(){  Bool_t PamelaDBOperations::SetID_RAW(){
# Line 180  Bool_t PamelaDBOperations::SetID_RAW(){ Line 273  Bool_t PamelaDBOperations::SetID_RAW(){
273    oss << "SELECT ID FROM GL_RAW WHERE "    oss << "SELECT ID FROM GL_RAW WHERE "
274        << " PATH = '" << this->GetRawPath().Data() << "' AND "        << " PATH = '" << this->GetRawPath().Data() << "' AND "
275        << " NAME = '" << this->GetRawFile().Data() << "' ";        << " NAME = '" << this->GetRawFile().Data() << "' ";
276    
277    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
278    if (result == NULL) throw -4;    if ( result == NULL ) throw -4;
279    row = result->Next();    row = result->Next();
280    if (row == NULL) return false;    if ( !row ) return(false);
281    delete result;    delete result;
282    id = (UInt_t)atoll(row->GetField(0));    id = (UInt_t)atoll(row->GetField(0));
283    return(true);    return(true);
# Line 210  Int_t PamelaDBOperations::SetUpperLimits Line 304  Int_t PamelaDBOperations::SetUpperLimits
304    UInt_t nevent = 0;    UInt_t nevent = 0;
305    UInt_t pktlast = 0;    UInt_t pktlast = 0;
306    UInt_t obtlast = 0;    UInt_t obtlast = 0;
307    UInt_t t_pktlast = 0;    Long64_t t_pktlast = 0LL;
308    UInt_t t_obtlast = 0;    //  UInt_t t_obtlast = 0;
309    UInt_t upperpkt2 = 0;    Long64_t t_obtlast = 0LL;
310    ULong64_t upperobt2 = 0;    Long64_t upperpkt2 = 0LL;
311      Long64_t upperobt2 = 0LL;
312    UInt_t zomp = 0;    UInt_t zomp = 0;
313    UInt_t jump = 50000; // was 5000    UInt_t jump = 50000; // was 5000
314      EventCounter *code=0;
315      //
316      Long64_t deltapkt = 5000LL;
317      Long64_t deltaobt = 50000LL;
318      //
319      //   pcksList packetsNames;
320      //   pcksList::iterator Iter;
321      //   getPacketsNames(packetsNames);
322    //    //
323    pktfirst = 0;    pktfirst = 0;
324    obtfirst = 0;    obtfirst = 0;
# Line 233  Int_t PamelaDBOperations::SetUpperLimits Line 336  Int_t PamelaDBOperations::SetUpperLimits
336    pktfirst = ph->GetCounter();    pktfirst = ph->GetCounter();
337    obtfirst = ph->GetOrbitalTime();      obtfirst = ph->GetOrbitalTime();  
338    //    //
339      //   code = eh->GetCounter();
340      //   UInt_t en = 0;
341      //   for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
342      //     en = code->Get(GetPacketType(*Iter));
343      //     if ( en ) printf(" Packet type is %s, entries: %i \n",*Iter,en);
344      //};  
345      //
346    T->GetEntry(nevent-1);    T->GetEntry(nevent-1);
347    ph = eh->GetPscuHeader();    ph = eh->GetPscuHeader();
348    pktlast = ph->GetCounter();    pktlast = ph->GetCounter();
# Line 242  Int_t PamelaDBOperations::SetUpperLimits Line 352  Int_t PamelaDBOperations::SetUpperLimits
352    upperobt = OBT(obtlast);    upperobt = OBT(obtlast);
353    upperentry = nevent-1;    upperentry = nevent-1;
354    //    //
355    if ( IsDebug() ) printf(" First entries are: OBT %llu pkt_num %i \n",obtfirst,pktfirst);    if ( IsDebug() ) printf(" First entries are: OBT %i pkt_num %i \n",obtfirst,pktfirst);
356    //    //
357    if ( IsDebug() ) printf(" Last entries are: OBT %llu pkt_num %i entry %i\n",upperobt,upperpkt,upperentry);    if ( IsDebug() ) printf(" Last entries are: OBT %lld pkt_num %lld entry %i\n",upperobt,upperpkt,upperentry);
358    //    //
359    if ( (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) > OBT(obtfirst)) || (PKT(pktlast) > PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) ) return(1);    if ( (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) > OBT(obtfirst)) || (PKT(pktlast) > PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) ) return(1);
360    //    //
# Line 252  Int_t PamelaDBOperations::SetUpperLimits Line 362  Int_t PamelaDBOperations::SetUpperLimits
362    //    //
363    if ( nevent < 2 ) return(4);    if ( nevent < 2 ) return(4);
364    //    //
365    if ( PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst) ){    if ( (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) || (labs(PKT(pktlast)-PKT(pktfirst))<deltapkt && labs(OBT(obtlast)-OBT(obtfirst))<deltaobt) ){
366        //
367      // go back      // go back
368      zomp = nevent - 2;      zomp = nevent - 2;
369      //      //
# Line 274  Int_t PamelaDBOperations::SetUpperLimits Line 385  Int_t PamelaDBOperations::SetUpperLimits
385          upperpkt2 = PKT(ph->GetCounter());          upperpkt2 = PKT(ph->GetCounter());
386          upperobt2 = OBT(ph->GetOrbitalTime());          upperobt2 = OBT(ph->GetOrbitalTime());
387          //          //
388          if ( (t_pktlast < upperpkt && t_obtlast > upperobt) || (t_pktlast < upperpkt2 && t_obtlast > upperobt2) ) throw -13;              if ( (t_pktlast < upperpkt && t_obtlast > upperobt) || (t_pktlast < upperpkt2 && t_obtlast > upperobt2) ){
389              if ( IsDebug() ) printf(" .-. upperpkt2 %lld upperobt2 %lld \n",upperpkt2,upperobt2);  
390              if ( IsDebug() ) printf(" .-. upperpkt %lld t_pktlast %lld upperobt %lld t_obtlast %lld \n",upperpkt,t_pktlast,upperobt,t_obtlast);    
391              if ( IsDebug() ) printf(" .-. jump %i zomp %i upperpkt %lld pktlast %u upperobt %lld obtlast %u last entry is %i \n",jump,zomp,upperpkt,pktlast,upperobt,obtlast,i);    
392              throw -13;    
393            };
394          //          //
395          if ( t_pktlast < upperpkt && t_obtlast < upperobt && t_pktlast < upperpkt2 && t_obtlast < upperobt2 ){          if ( t_pktlast < upperpkt && t_obtlast < upperobt && t_pktlast < upperpkt2 && t_obtlast < upperobt2 ){
396            zomp = i + jump + 1;            zomp = i + jump + 1;
397            if ( zomp > nevent-2 ) zomp = nevent - 2;            if ( zomp > nevent-2 ) zomp = nevent - 2;
398            if ( IsDebug() ) printf(" .-. jump %i zomp %i upperpkt %i pktlast %i upperobt %llu obtlast %u last entry is %i \n",jump,zomp,upperpkt,pktlast,upperobt,obtlast,i);            if ( IsDebug() ) printf(" .-. jump %i zomp %i upperpkt %lld pktlast %i upperobt %lld obtlast %u last entry is %i \n",jump,zomp,upperpkt,pktlast,upperobt,obtlast,i);
399            break;            break;
400          };          };
401          //          //
# Line 301  Int_t PamelaDBOperations::SetUpperLimits Line 417  Int_t PamelaDBOperations::SetUpperLimits
417    // 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)
418    //    //
419    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);  
420    TTree *rh=(TTree*)file->Get("RunHeader");    TTree *rh=(TTree*)file->Get("RunHeader");
421    if ( !rh || rh->IsZombie() ) throw -17;    if ( !rh || rh->IsZombie() ) throw -17;
422    TTree *rt=(TTree*)file->Get("RunTrailer");    TTree *rt=(TTree*)file->Get("RunTrailer");
# Line 319  Int_t PamelaDBOperations::SetUpperLimits Line 430  Int_t PamelaDBOperations::SetUpperLimits
430    //    //
431    rhev = rh->GetEntries();    rhev = rh->GetEntries();
432    rtev = rt->GetEntries();    rtev = rt->GetEntries();
433    UInt_t pktt = 0;    Long64_t sobtt = 0LL;
434    ULong64_t obtt = 0;    Long64_t sobth = 0LL;
435    UInt_t pkth = 0;    Long64_t spktt = 0LL;
436    ULong64_t obth = 0;    Long64_t spkth = 0LL;
437      Long64_t pktt = 0LL;
438      Long64_t obtt = 0LL;
439      Long64_t pkth = 0LL;
440      Long64_t obth = 0LL;
441    //    //
442      T->GetEntry(upperentry);
443      code = eh->GetCounter();
444      Int_t lasttrail = code->Get(pctp->RunTrailer);
445      Int_t lasthead = code->Get(pctp->RunHeader);
446    if ( lasttrail < rtev ){    if ( lasttrail < rtev ){
447      rt->GetEntry(lasttrail);      rt->GetEntry(lasttrail);
448      pht = eht->GetPscuHeader();      pht = eht->GetPscuHeader();
# Line 331  Int_t PamelaDBOperations::SetUpperLimits Line 450  Int_t PamelaDBOperations::SetUpperLimits
450      obtt = OBT(pht->GetOrbitalTime());      obtt = OBT(pht->GetOrbitalTime());
451    };    };
452    //    //
453    if ( IsDebug() ) printf(" rtev beforev %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);    if ( lasthead < rhev ){
454        rh->GetEntry(lasthead);
455        phh = ehh->GetPscuHeader();
456        pkth = PKT(phh->GetCounter());
457        obth = OBT(phh->GetOrbitalTime());
458      };
459      //
460      if ( IsDebug() ) printf(" rhev before %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
461      if ( pkth > upperpkt && obth > upperobt ){
462        if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %lld upperp %lld oh %lld uppero %lld \n",pkth,upperpkt,obth,upperobt);
463        upperpkt = pkth;
464        upperobt = obth;
465        rhev = lasthead+1;
466      } else {
467        rhev = lasthead;
468      };
469      if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
470      //
471      if ( IsDebug() ) printf(" rtev beforev %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
472    if ( pktt > upperpkt && obtt > upperobt ){    if ( pktt > upperpkt && obtt > upperobt ){
473      if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %i upperp %i ot %llu uppero %llu \n",pktt,upperpkt,obtt,upperobt);      if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %lld upperp %lld ot %lld uppero %lld \n",pktt,upperpkt,obtt,upperobt);
474      upperpkt = pktt;      upperpkt = pktt;
475      upperobt = obtt;      upperobt = obtt;
476      rtev = lasttrail+1;      rtev = lasttrail+1;
477    } else {    } else {
478      rtev = lasttrail;      rtev = lasttrail;
479    };    };
480    if ( IsDebug() ) printf(" rtev after %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);    if ( IsDebug() ) printf(" rtev after %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
481      //  goto kikko;
482      //
483      //
484      // Check if runtrailer/runheader are within lower limits
485      //
486      //
487      pkth = 0LL;
488      obth = 0LL;
489      spkth = 0LL;
490      sobth = 0LL;
491      for (Int_t k=0; k<rhev; k++){
492        if ( k > 0 ){
493          spkth = pkth;
494          sobth = obth;
495        };
496        rh->GetEntry(k);
497        phh = ehh->GetPscuHeader();
498        pkth = PKT(phh->GetCounter());
499        obth = OBT(phh->GetOrbitalTime());
500        //
501    //    if ( IsDebug() ) printf(" k %i rhev before %i ph %u upperp %u oh %u uppero %u \n",k,rhev,pkth,spkth,obth,sobth);
502        //
503        if ( pkth < spkth && obth < sobth ){
504          if ( IsDebug() ) printf(" RH PROBLEMS determining the event repetition at the end of the file lasthead %i  \n",rhev);
505          //
506          rhev = k-1;
507          rh->GetEntry(rhev);
508          pkth = spkth;
509          obth = sobth;
510          //
511          UInt_t evbefh = 0;
512          code = ehh->GetCounter();
513          evbefh = code->Get(pctp->Physics);    
514          if ( evbefh >= 0 ){
515            T->GetEntry(evbefh);
516            ph = eh->GetPscuHeader();
517            t_pktlast = PKT(ph->GetCounter());
518            t_obtlast = OBT(ph->GetOrbitalTime());
519            if ( t_pktlast <= spkth && t_obtlast <= sobth ){ // jump
520              upperpkt = pkth;
521              upperobt = obth;
522              upperentry = evbefh-1;
523            } else {
524              while ( t_pktlast > spkth && t_obtlast > sobth && evbefh < nevent ){
525                evbefh++;  
526                T->GetEntry(evbefh);
527                ph = eh->GetPscuHeader();
528                t_pktlast = PKT(ph->GetCounter());
529                t_obtlast = OBT(ph->GetOrbitalTime());
530              };
531              T->GetEntry(evbefh-1);
532              ph = eh->GetPscuHeader();
533              upperpkt = PKT(ph->GetCounter());
534              upperobt = OBT(ph->GetOrbitalTime());
535              upperentry = evbefh-1;
536            };    
537          };
538          if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
539          goto kikko0;
540        };
541      };
542     kikko0:
543      //
544      //
545      //
546      pktt = 0LL;
547      obtt = 0LL;
548      spktt = 0LL;
549      sobtt = 0LL;
550      for (Int_t k=0; k<rtev; k++){
551        if ( k > 0 ){
552          spktt = pktt;
553          sobtt = obtt;
554        };
555        rt->GetEntry(k);
556        pht = eht->GetPscuHeader();
557        pktt = PKT(pht->GetCounter());
558        obtt = OBT(pht->GetOrbitalTime());
559        //
560    //    if ( IsDebug() ) printf(" k %i rtev beforev %i  pt %i upperp %i ot %llu uppero %llu \n",k,rtev,pktt,spktt,obtt,sobtt);
561        //
562        if ( pktt < spktt && obtt < sobtt ){
563          if ( IsDebug() ) printf(" RT PROBLEMS determining the event repetition at the end of the file lasttrail %i \n",rtev);
564          //
565          rtev = k-1;
566          rt->GetEntry(rtev);
567          pktt = spktt;
568          obtt = sobtt;
569          if ( IsDebug() ) printf(" lasttrail %i pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
570          //
571          UInt_t evbeft = 0;
572          code = eht->GetCounter();
573          evbeft = code->Get(pctp->Physics);    
574          if ( evbeft >= 0 ){
575            T->GetEntry(evbeft);
576            ph = eh->GetPscuHeader();
577            t_pktlast = PKT(ph->GetCounter());
578            t_obtlast = OBT(ph->GetOrbitalTime());
579            if ( t_pktlast <= spktt && t_obtlast <= sobtt ){ // jump
580              upperpkt = pktt;
581              upperobt = obtt;
582              upperentry = evbeft-1;
583            } else {
584              while ( t_pktlast > spktt && t_obtlast > sobtt && evbeft < nevent ){
585                evbeft++;  
586                T->GetEntry(evbeft);
587                ph = eh->GetPscuHeader();
588                t_pktlast = PKT(ph->GetCounter());
589                t_obtlast = OBT(ph->GetOrbitalTime());
590              };
591              T->GetEntry(evbeft-1);
592              ph = eh->GetPscuHeader();
593              upperpkt = PKT(ph->GetCounter());
594              upperobt = OBT(ph->GetOrbitalTime());
595              upperentry = evbeft-1;
596            };
597          };
598          if ( IsDebug() ) printf(" rtev after %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
599          goto kikko;
600          //      break;
601          //
602        };
603        //  
604      };
605      //
606     kikko:
607      //
608      T->GetEntry(upperentry);
609      code = eh->GetCounter();
610      lasttrail = code->Get(pctp->RunTrailer);
611      lasthead = code->Get(pctp->RunHeader);
612      if ( lasttrail < rtev ){
613        rt->GetEntry(lasttrail);
614        pht = eht->GetPscuHeader();
615        pktt = PKT(pht->GetCounter());
616        obtt = OBT(pht->GetOrbitalTime());
617      };
618    //    //
619    if ( lasthead < rhev ){    if ( lasthead < rhev ){
620      rh->GetEntry(lasthead);      rh->GetEntry(lasthead);
621      phh = ehh->GetPscuHeader();      phh = ehh->GetPscuHeader();
622      pkth = PKT(pht->GetCounter());      pkth = PKT(phh->GetCounter());
623      obth = OBT(pht->GetOrbitalTime());      obth = OBT(phh->GetOrbitalTime());
624    };    };
625    //    //
626    if ( IsDebug() ) printf(" rhev before %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);    if ( IsDebug() ) printf(" rhev before %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
627    if ( pkth > upperpkt && obth > upperobt ){    if ( pkth > upperpkt && obth > upperobt ){
628      if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %i upperp %i oh %llu uppero %llu \n",pkth,upperpkt,obth,upperobt);      if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %lld upperp %lld oh %lld uppero %lld \n",pkth,upperpkt,obth,upperobt);
629      upperpkt = pkth;      upperpkt = pkth;
630      upperobt = obth;      upperobt = obth;
631      rhev = lasthead+1;      rhev = lasthead+1;
632    } else {    } else {
633      rhev = lasthead;      rhev = lasthead;
634    };    };
635    if ( IsDebug() ) printf(" rhev after %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);    if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
636      //
637      if ( IsDebug() ) printf(" rtev beforev %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
638      if ( pktt > upperpkt && obtt > upperobt ){
639        if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %lld upperp %lld ot %lld uppero %lld \n",pktt,upperpkt,obtt,upperobt);
640        upperpkt = pktt;
641        upperobt = obtt;
642        rtev = lasttrail+1;
643      } else {
644        rtev = lasttrail;
645      };
646      if ( IsDebug() ) printf(" rtev after %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
647    //    //
648    if ( IsDebug() ) printf(" Upper limits are: OBT %llu pkt_num %i upper entry %i \n",upperobt,upperpkt,upperentry);    if ( IsDebug() ) printf(" Upper limits are: OBT %lld pkt_num %lld upper entry %i \n",upperobt,upperpkt,upperentry);
649    //    //
650    return(0);    return(0);
651  }  }
652    
653    /**
654     *
655     * Trick to have unique RUN ID numbers even when runs are deleted and mysql deamon restarted.
656     * Entries in the _RUNID_GEN table are never deleted.
657     *
658     **/
659    UInt_t PamelaDBOperations::AssignRunID(){
660      //
661      TSQLResult *result = 0;
662      TSQLRow *row = 0;
663      UInt_t runid = 0;
664      //
665      stringstream   oss;
666      //  
667      oss.str("");
668      oss << "INSERT INTO _RUNID_GEN VALUES (NULL);";
669      result = conn->Query(oss.str().c_str());
670      if ( !result ) throw -10;
671      oss.str("");
672      oss << "SELECT ID FROM _RUNID_GEN ORDER BY ID DESC LIMIT 1;";
673      result = conn->Query(oss.str().c_str());
674      if ( !result ) throw -10;
675      //
676      row = result->Next();
677      //
678      if ( !row ) throw -28;
679      //
680      runid = (UInt_t)atoll(row->GetField(0));
681      //
682      return(runid);
683    };
684    
685  //  //
686  // GETTERS  // GETTERS
687  //  //
# Line 440  const PacketType* PamelaDBOperations::Ge Line 757  const PacketType* PamelaDBOperations::Ge
757  // PRIVATE FUNCTIONS  // PRIVATE FUNCTIONS
758  //  //
759    
760  /**  // /**
761   * Open the ROOT filename for reading  // * Open the ROOT filename for reading
762   */  // */
763  void PamelaDBOperations::OpenFile(){  // void PamelaDBOperations::OpenFile(){
764    file = TFile::Open(this->GetRootName().Data());  //   file = TFile::Open(this->GetRootName().Data());
765    //   //
766    
767    void PamelaDBOperations::CheckFile(){  
768      if ( !file ) throw -12;
769  };  };
770    
771    
772  /**  /**
773   * Check if LEVEL0 file and DB connection have really be opened   * Check if LEVEL0 file and DB connection have really be opened
774   */   */
775  void PamelaDBOperations::CheckFile(){    void PamelaDBOperations::CheckConnection(){  
   //  
   if ( !file ) throw -12;  
776    //    //
777    // check connection    // check connection
778    //    //
779    if( !conn ) throw -1;        if( !conn ) throw -1;
780    bool connect = conn->IsConnected();    bool connect = conn->IsConnected();
781    if( !connect ) throw -1;        if( !connect ) throw -1;
782      //
783      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());
784      //
785      if ( !dworbit && strcmp(this->GetRootName().Data(),"") ) throw -27;
786      //
787      // set DB timezone to UTC
788      //
789      stringstream oss;
790      //  
791      oss.str("");
792      oss << "SET time_zone='+0:00';";
793      TSQLResult *result = 0;
794      result = conn->Query(oss.str().c_str());
795      if ( !result ) throw -10;
796      oss.str("");
797      oss << "SET wait_timeout=173000;";
798      conn->Query(oss.str().c_str());
799      //
800  };  };
801    
802  /**  /**
803   * Return the correct packet number if we went back to zero   * Return the correct packet number if we went back to zero
804   */   */
805  UInt_t PamelaDBOperations::PKT(UInt_t pkt_num){    Long64_t PamelaDBOperations::PKT(UInt_t pkt_num){  
806    //    //
807    //  if ( IsDebug() ) printf(" pkt conversion: pkt_num is %u pktfirst is %u (pktfirst - (UInt_t)(16777212/2)) is %u  \n",pkt_num,pktfirst,(pktfirst - (UInt_t)(16777212/2)));    if ( IsDebug() ) printf(" pkt conversion: pkt_num is %u pktfirst is %u  (UInt_t)(16777214/2)) is %u  \n",pkt_num,pktfirst,(UInt_t)(16777214/2));
808    //    //
809    if ( pkt_num < (pktfirst/2) && pktfirst > (16777214/2)  ) return((pkt_num+16777215));    if ( pkt_num < (pktfirst/2) && pktfirst > (16777214/2)  ){
810        if ( IsDebug() ) printf(" rise up pktnum %lld \n",(Long64_t)pkt_num+16777215LL);
811        return((Long64_t)pkt_num+16777215LL);
812      };
813    //    //
814    if ( pkt_num > pktfirst*2 && pkt_num > (16777214/2) ){    if ( pkt_num > pktfirst*2 && pkt_num > (16777214/2) ){
815      if ( (pkt_num-16777215) < 0 ){      if ( IsDebug() ) printf(" rise down pktnum %lld \n",(Long64_t)pkt_num-16777215LL);
816        return((16777215-pkt_num));      return((Long64_t)pkt_num-16777215LL);
     } else {  
       return((pkt_num-16777215));  
     };  
817    };    };
818    //    //
819    return(pkt_num);    if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)pkt_num);
820      return((Long64_t)pkt_num);
821    //    //
822  };  };
823    
824  /**  /**
825   * Return the correct On Board Time if we went back to zero   * Return the correct On Board Time if we went back to zero
826   */   */
827  ULong64_t PamelaDBOperations::OBT(UInt_t obt){    Long64_t PamelaDBOperations::OBT(UInt_t obt){  
828    //    //
829    if ( obt < (obtfirst/2) && obtfirst > (numeric_limits<UInt_t>::max()/2) ) return((ULong64_t)(obt+numeric_limits<UInt_t>::max()));    if ( obt < (obtfirst/2) && obtfirst > (numeric_limits<UInt_t>::max()/2) ) return((Long64_t)(obt+numeric_limits<UInt_t>::max()));
830    //    //
831    if ( obt > (obtfirst*2) && obt > (numeric_limits<UInt_t>::max()/2) ){    if ( obt > (obtfirst*2) && obt > (numeric_limits<UInt_t>::max()/2) ){
832      if ( (obt-numeric_limits<UInt_t>::max()) < 0  ){      return((Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());
       return((ULong64_t)(numeric_limits<UInt_t>::max()-obt));  
     } else {  
       return((ULong64_t)(obt-numeric_limits<UInt_t>::max()));  
     };  
833    };    };
834    //    //
835    return((ULong64_t)obt);    return((Long64_t)obt);
836  };  };
837    
838  /**  /**
# Line 550  void PamelaDBOperations::FillClass(Bool_ Line 884  void PamelaDBOperations::FillClass(Bool_
884      lastPkt = glrun->GetRUNTRAILER_PKT();      lastPkt = glrun->GetRUNTRAILER_PKT();
885    };    };
886    //    //
887    if ( mishead && mistrail && lastev+1 == firstev ) throw -14; // run with no events, no runtrailer, no runheader... unsupported    if ( mishead && mistrail && lastev+1 == firstev ) throw -14; // run with no events, no runtrailer, no runheader... unsupported should never arrive here
888    //    //
889    if ( mishead ) {    if ( mishead ) {
890      glrun->Set_GL_RUNH0();      glrun->Set_GL_RUNH0();
# Line 639  Int_t PamelaDBOperations::insertPamelaGL Line 973  Int_t PamelaDBOperations::insertPamelaGL
973    if ( this->GetID_RAW() == 0 )  throw -11;    if ( this->GetID_RAW() == 0 )  throw -11;
974    //    //
975    oss.str("");    oss.str("");
976    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='"
977        << id << " AND TO_ID_RAW >= "        << this->GetRawFile().Data() << "';";
       << id << ";";  
978    if ( IsDebug() ) printf(" %s \n",oss.str().c_str());    if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
979    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
980    if ( !result ) throw -10;    if ( !result ) throw -10;
981    row = result->Next();    row = result->Next();
   if ( !row ) throw -10;  
982    //    //
983    t0 = (UInt_t)TDatime(row->GetField(0)).Convert();    if ( !row ){
984        oss.str("");
985        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< "
986            << dworbit << " order by FROM_ORBIT desc limit 1;";
987        if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
988        result = conn->Query(oss.str().c_str());
989        if ( !result ) throw -10;
990        row = result->Next();
991        if ( !row ) throw -10;
992      };
993      //
994      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);
995      t0 = (UInt_t)tu.GetSec();
996      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));
997      //
998    /*    /*
999     * Verify that the TIMESYNC have been not already processed     * Verify that the TIMESYNC have been not already processed
1000     */     */
# Line 663  Int_t PamelaDBOperations::insertPamelaGL Line 1009  Int_t PamelaDBOperations::insertPamelaGL
1009    if (result == NULL) throw -10;    if (result == NULL) throw -10;
1010    row = result->Next();    row = result->Next();
1011    if ((row != NULL) && ((UInt_t)atoll(row->GetField(0)) > 0)){    if ((row != NULL) && ((UInt_t)atoll(row->GetField(0)) > 0)){
1012        if ( IsDebug() ) printf(" found a timesync t0 is %u \n",t0);
1013      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;
1014        //
1015        tsync = (UInt_t)atoll(row->GetField(2));
1016        obt0 = (UInt_t)atoll(row->GetField(1));
1017        //
1018      return(1);      return(1);
1019    };    };
1020    //    //
1021    TTree *T = 0;    TTree *T = 0;
1022      Int_t signal = 0;
1023    //    //
1024    UInt_t nevent = 0;    UInt_t nevent = 0;
1025    UInt_t recEntries = 0;    UInt_t recEntries = 0;
# Line 719  Int_t PamelaDBOperations::insertPamelaGL Line 1071  Int_t PamelaDBOperations::insertPamelaGL
1071          //          //
1072          TYPE = 55;//224;          TYPE = 55;//224;
1073          //          //
1074            if ( IsDebug() ) printf("mcmd tsync %i tsync %u obt %u \n",i,TSYNC,OBT);
1075            //
1076          if ( TSYNC && OBT ){          if ( TSYNC && OBT ){
1077            existsts = true;            existsts = true;
1078            goto out;            goto eout;
1079          };          };
1080          //          //
1081        };        };
# Line 729  Int_t PamelaDBOperations::insertPamelaGL Line 1083  Int_t PamelaDBOperations::insertPamelaGL
1083    };    };
1084    if ( !existsts ) { // try with runheader and runtrailer    if ( !existsts ) { // try with runheader and runtrailer
1085      //      //
1086        if ( IsDebug() ) printf(" No ts mcmd \n");
1087        signal = 2;
1088        //
1089      TTree *rh=(TTree*)file->Get("RunHeader");      TTree *rh=(TTree*)file->Get("RunHeader");
1090      if ( !rh || rh->IsZombie() ) throw -17;      if ( !rh || rh->IsZombie() ) throw -17;
1091      TTree *rt=(TTree*)file->Get("RunTrailer");      TTree *rt=(TTree*)file->Get("RunTrailer");
# Line 738  Int_t PamelaDBOperations::insertPamelaGL Line 1095  Int_t PamelaDBOperations::insertPamelaGL
1095      //      //
1096      rt->SetBranchAddress("RunTrailer", &runt);      rt->SetBranchAddress("RunTrailer", &runt);
1097      //      //
1098      //    Int_t rhev = rh->GetEntries();      Int_t nrhev = rh->GetEntries();
1099      //    Int_t rtev = rt->GetEntries();      Int_t nrtev = rt->GetEntries();
1100        if ( IsDebug() ) printf(" ou nevent %i rhev %i rtev %i \n",nevent,nrhev,nrtev);
1101      //      //
1102      if ( rhev > 0 ){      if ( nrhev > 0 ){
1103        rh->GetEntry(0);        for (Int_t i=0; i<nrhev; i++){
1104        //          //
1105        TSYNC = runh->LAST_TIME_SYNC_INFO;          rh->GetEntry(i);
1106        OBT = runh->OBT_TIME_SYNC * 1000;          //
1107        //          TSYNC = runh->LAST_TIME_SYNC_INFO;
1108        TYPE = 20;          OBT = runh->OBT_TIME_SYNC * 1000;
1109        //          //
1110        if ( TSYNC && OBT ){          TYPE = 20;
1111          existsts = true;          //
1112          goto out;          if ( IsDebug() ) printf("runheader %i tsync %u obt %u \n",i,TSYNC,OBT);
1113            //
1114            if ( TSYNC && OBT ){
1115              existsts = true;
1116              goto eout;
1117            };
1118        };        };
1119        //        //
1120      };      };
1121      if ( rtev > 0 ){      if ( nrtev > 0 ){
       rt->GetEntry(0);  
       //  
       TSYNC = runt->LAST_TYME_SYNC_INFO;  
       OBT = runt->OBT_TYME_SYNC * 1000;  
1122        //        //
1123        TYPE = 21;        if ( IsDebug() ) printf(" No runheader \n");
1124          signal = 6;
1125        //        //
1126        if ( TSYNC && OBT ){        for (Int_t i=0; i<nrtev; i++){
1127          existsts = true;          //
1128          goto out;          rt->GetEntry(i);
1129            //
1130            TSYNC = runt->LAST_TYME_SYNC_INFO;
1131            OBT = runt->OBT_TYME_SYNC * 1000;
1132            //
1133            TYPE = 21;
1134            //
1135            if ( IsDebug() ) printf("runtrailer %i tsync %u obt %u \n",i,TSYNC,OBT);
1136            //
1137            if ( TSYNC && OBT ){
1138              existsts = true;
1139              goto eout;
1140            };
1141        };        };
1142        //        //
1143        } else {
1144          if ( IsDebug() ) printf(" No runheader \n");
1145      };      };
1146    };    };
1147    //    //
1148    if ( !existsts ){ // try with inclination mcmd    if ( !existsts ){ // try with inclination mcmd
1149        //
1150        if ( IsDebug() ) printf(" No runtrailer \n");
1151        signal = 14;
1152        //
1153      Double_t timesync = 0.;      Double_t timesync = 0.;
1154      for (UInt_t i=0; i<nevent;i++){      for (UInt_t i=0; i<nevent;i++){
1155        //        //
# Line 800  Int_t PamelaDBOperations::insertPamelaGL Line 1178  Int_t PamelaDBOperations::insertPamelaGL
1178        TYPE = 666;        TYPE = 666;
1179        if ( TSYNC && OBT ){        if ( TSYNC && OBT ){
1180          existsts = true;          existsts = true;
1181          goto out;          goto eout;
1182        };        };
1183      };      };
1184    };    };
1185    //    //
1186    if ( !existsts && obt0 ){ // insert timesync by hand    if ( !existsts && obt0 ){ // insert timesync by hand
1187        //
1188        if ( IsDebug() ) printf(" No incl mcmd \n");
1189        signal = 30;
1190        //
1191      OBT = obt0;      OBT = obt0;
1192      TSYNC = tsync;      TSYNC = tsync;
1193      TYPE = 999;      TYPE = 999;
1194      existsts = true;      existsts = true;
1195      goto out;      goto eout;
1196    };    };
1197    //    //
1198   out:   eout:
1199    //    //
1200    if ( !existsts ) throw -3;    if ( !existsts ) throw -3;
1201    //    //
# Line 826  Int_t PamelaDBOperations::insertPamelaGL Line 1208  Int_t PamelaDBOperations::insertPamelaGL
1208    conn->Query(oss.str().c_str());    conn->Query(oss.str().c_str());
1209    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());
1210    //    //
1211      if ( IsDebug() ) printf(" found a timesync t0 is %u \n",t0);
1212    toffset = (UInt_t)TSYNC - (UInt_t)(this->OBT(OBT)/1000) + t0;    toffset = (UInt_t)TSYNC - (UInt_t)(this->OBT(OBT)/1000) + t0;
1213    //    //
1214      tsync = TSYNC;
1215      obt0 = OBT;
1216      //
1217    delete result;    delete result;
1218    return(0);    return(signal);
1219  }  }
1220    
1221  /**  /**
# Line 907  Int_t PamelaDBOperations::assignBOOT_NUM Line 1293  Int_t PamelaDBOperations::assignBOOT_NUM
1293        << " NAME = '" << this->GetRawFile().Data() << "' ";        << " NAME = '" << this->GetRawFile().Data() << "' ";
1294    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1295    //    //
1296    if ( !result ) return(8);    if ( !result ) throw -4;;
1297    row = result->Next();    row = result->Next();
1298    if ( !row ) return(16);    if ( !row ) return(16);
1299    if ( row->GetField(1) ){    if ( row->GetField(1) ){
1300      this->SetBOOTnumber((UInt_t)atoll(row->GetField(1)));      this->SetBOOTnumber((UInt_t)atoll(row->GetField(1)));
1301      return(1);      return(1);
1302    };    };
1303    if ( !row->GetField(0) ) return(8);    if ( !row->GetField(0) ) throw -26;
1304    //    //
1305    UInt_t idRaw = (UInt_t)atoll(row->GetField(0));    UInt_t idRaw = (UInt_t)atoll(row->GetField(0));
1306    //    //
# Line 924  Int_t PamelaDBOperations::assignBOOT_NUM Line 1310  Int_t PamelaDBOperations::assignBOOT_NUM
1310    trDumpEv = (TTree*)file->Get("VarDump");    trDumpEv = (TTree*)file->Get("VarDump");
1311    if ( !trDumpEv || trDumpEv->IsZombie() ) throw -20;    if ( !trDumpEv || trDumpEv->IsZombie() ) throw -20;
1312    //    //
   if (trDumpEv == NULL) return(2);  
   //      
1313    VarDumpEvent  *vde = 0;    VarDumpEvent  *vde = 0;
1314    VarDumpRecord *vdr = 0;    VarDumpRecord *vdr = 0;
1315    //    //
1316      Bool_t found = false;
1317    trDumpEv->SetBranchAddress("VarDump", &vde);    trDumpEv->SetBranchAddress("VarDump", &vde);
1318    if (trDumpEv->GetEntries() > 0){    if ( trDumpEv->GetEntries() > 0 ){
1319      trDumpEv->GetEntry(0);      found = false;
1320      vde->Records->GetEntries();      for ( Int_t i = 0; i < trDumpEv->GetEntries(); i++){
1321      if ( !vde->Records->GetEntries() ){        trDumpEv->GetEntry(i);
1322        if ( !this->GetBOOTnumber() ) return(4);        //      vde->Records->GetEntries();
1323      } else {        if ( vde->Records->GetEntries()>5 ){
1324            found = true;
1325            goto fill;
1326          };
1327        };
1328      fill:
1329        if ( found ){
1330          //
1331        vdr = (VarDumpRecord*)vde->Records->At(6);        vdr = (VarDumpRecord*)vde->Records->At(6);
1332          //
1333        this->SetBOOTnumber((Int_t)vdr->VAR_VALUE);        this->SetBOOTnumber((Int_t)vdr->VAR_VALUE);
1334          //
1335        } else {
1336          if ( !this->GetBOOTnumber() && !this->AutoBoot()) return(4);
1337        };
1338      } else {
1339        if ( !this->GetBOOTnumber() && !this->AutoBoot()) return(2);
1340      };
1341      //
1342      UInt_t bn = 0;
1343      Bool_t afound = false;
1344      if ( !found && this->AutoBoot()){
1345        afound = true;
1346        //
1347        // Search for other files with similar timesync
1348        //
1349        if ( IsDebug() ) printf(" tsync %u obt0 %u \n",tsync,obt0);
1350        UInt_t upperts = tsync-(obt0/1000)+5;
1351        UInt_t lowerts = tsync-(obt0/1000)-5;
1352        oss.str("");
1353        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)<"
1354            << upperts
1355            << " AND TIMESYNC-(OBT0/1000)>"
1356            << lowerts
1357            << " AND GL_RAW.BOOT_NUMBER>0 GROUP BY GL_TIMESYNC.OBT0;";
1358        result = conn->Query(oss.str().c_str());
1359        if ( IsDebug() ) printf(" Query the GL_TIMESYNC table to find boot number:\n %s \n",oss.str().c_str());
1360        //
1361        if ( !result ) throw -4;;
1362        found = true;
1363        if ( result->GetRowCount()<3 ){
1364          if ( IsDebug() ) printf(" AGH! no results!\n");
1365          found = false;
1366        } else {
1367          row = result->Next();      
1368          bn = (UInt_t)atoll(row->GetField(0));
1369          for ( Int_t r=1; r<result->GetRowCount() ;r++){
1370            if ( !row ) throw -4;
1371            if ( IsDebug() ) printf(" BOOT number is %s \n",row->GetField(0));
1372            if ( bn != (UInt_t)atoll(row->GetField(0)) ){
1373              if ( IsDebug() ) printf(" AGH! bn = %u here instead %u \n",bn,(UInt_t)atoll(row->GetField(0)));
1374              found = false;
1375            };
1376            row = result->Next();
1377          };
1378      };      };
1379      };
1380      //
1381      Int_t sgn = 0;
1382      //
1383      if ( !found ){
1384        throw -29;
1385    } else {    } else {
1386      if ( !this->GetBOOTnumber() ) return(2);      if ( afound ){
1387          this->SetBOOTnumber(bn);
1388          sgn = 8;
1389        };
1390    };    };
1391    //    //
1392    oss.str("");    oss.str("");
# Line 950  Int_t PamelaDBOperations::assignBOOT_NUM Line 1396  Int_t PamelaDBOperations::assignBOOT_NUM
1396    conn->Query(oss.str().c_str());          conn->Query(oss.str().c_str());      
1397    //    //
1398    delete result;    delete result;
1399    return(0);    return(sgn);
1400  };  };
1401    
1402  /**  /**
# Line 1023  Int_t PamelaDBOperations::insertPamelaRU Line 1469  Int_t PamelaDBOperations::insertPamelaRU
1469          //          //
1470          if ( IsDebug() ) printf(" Missing header %i %i %i\n",ptht,pth,ptt);          if ( IsDebug() ) printf(" Missing header %i %i %i\n",ptht,pth,ptt);
1471          //          //
1472          if ( (ptt-1) < 0 ) throw -15;          if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
1473          rt->GetEntry(ptt-1);          rt->GetEntry(ptt-1);
1474          cod = eht->GetCounter();          cod = eht->GetCounter();
1475          evbefh = cod->Get(pctp->Physics);          evbefh = cod->Get(pctp->Physics);
# Line 1129  Int_t PamelaDBOperations::insertPamelaRU Line 1575  Int_t PamelaDBOperations::insertPamelaRU
1575            if ( (UInt_t)evbeft < upperentry-1 ){            if ( (UInt_t)evbeft < upperentry-1 ){
1576              if ( IsDebug() ) printf(" Piece of run at the end of the file with NO RUNHEADER!\n");              if ( IsDebug() ) printf(" Piece of run at the end of the file with NO RUNHEADER!\n");
1577              //              //
1578              if ( (ptt-1) < 0 ) throw -15;              if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
1579              rt->GetEntry(ptt-1);              rt->GetEntry(ptt-1);
1580              cod = eht->GetCounter();              cod = eht->GetCounter();
1581              evbefh = cod->Get(pctp->Physics);              evbefh = cod->Get(pctp->Physics);
# Line 1213  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1659  Bool_t PamelaDBOperations::IsRunAlreadyI
1659      if ( glrun->GetNEVENTS() > (UInt_t)atoll(row->GetField(1)) ){      if ( glrun->GetNEVENTS() > (UInt_t)atoll(row->GetField(1)) ){
1660        //        //
1661        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");
1662        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1663        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1664        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) <<";";
1665        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1666    //       conn->Query(oss.str().c_str());
1667        if ( signal ) signal = false;        if ( signal ) signal = false;
1668        goto gonext;              goto gonext;      
1669        //        //
# Line 1230  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1677  Bool_t PamelaDBOperations::IsRunAlreadyI
1677        //        //
1678        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");
1679        //        //
1680        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1681        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1682        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) <<";";
1683        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1684    //       conn->Query(oss.str().c_str());
1685        //        //
1686        if ( signal ) signal = false;        if ( signal ) signal = false;
1687        goto gonext;        goto gonext;
# Line 1247  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1695  Bool_t PamelaDBOperations::IsRunAlreadyI
1695        //        //
1696        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");
1697        //        //
1698        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1699        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1700        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) <<";";
1701        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1702    //       conn->Query(oss.str().c_str());
1703        if ( signal ) signal = false;        if ( signal ) signal = false;
1704        //        //
1705      };      };
# Line 1265  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1714  Bool_t PamelaDBOperations::IsRunAlreadyI
1714    delete result;    delete result;
1715    //    //
1716    if ( signal && IsDebug() ) printf(" The run has already been inserted \n");        if ( signal && IsDebug() ) printf(" The run has already been inserted \n");    
1717      if ( !signal && IsDebug() ) printf(" The run existed and was deleted, fill the DB \n");
1718    return(signal);    return(signal);
1719  };  };
1720    
# Line 1286  void PamelaDBOperations::HandleRun(){   Line 1736  void PamelaDBOperations::HandleRun(){  
1736      //      //
1737      this->FillClass();      this->FillClass();
1738      //      //
1739      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);      if ( !IsRunAlreadyInserted() ){
1740          glrun->SetID(this->AssignRunID());
1741          glrun->SetID_RUN_FRAG(0);
1742          glrun->Fill_GL_RUN(conn);
1743        };
1744    } else {    } else {
1745      //      //
1746      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 1309  void PamelaDBOperations::HandleRunFragme Line 1763  void PamelaDBOperations::HandleRunFragme
1763    UInt_t rhfirstev = firstev;    UInt_t rhfirstev = firstev;
1764    UInt_t rtlastev = lastev;    UInt_t rtlastev = lastev;
1765    Bool_t found = false;    Bool_t found = false;
1766      Bool_t foundinrun = false;
1767    //    //
1768    TSQLResult *result = 0;    TSQLResult *result = 0;
1769    TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
# Line 1335  void PamelaDBOperations::HandleRunFragme Line 1790  void PamelaDBOperations::HandleRunFragme
1790    //    //
1791    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");
1792    //    //
1793    // 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...
1794    //        //
1795    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("");
1796                                             // missing it no way we can found a piece in the frag table    oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
1797      //        << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
1798      oss.str("");        << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
1799      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 ("
1800          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "        << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
1801          << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME()        << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
1802          << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
1803          << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
1804          << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1805          << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
1806          << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
1807          << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
1808          << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
1809          << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
1810      //
1811      if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
1812      result = conn->Query(oss.str().c_str());
1813      //
1814      if ( !result ) throw -4;
1815      //
1816      row = result->Next();
1817      //
1818      if ( !row ){
1819        //
1820        // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
1821        //
1822        if ( IsDebug() ) printf(" The run is new \n");
1823        if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
1824        //
1825        glrun->SetID(this->AssignRunID());
1826        glrun->SetID_RUN_FRAG(0);
1827        glrun->Fill_GL_RUN_FRAGMENTS(conn);
1828        //
1829      } else {
1830        if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
1831        return;
1832      };
1833      //
1834      //
1835      // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
1836      //    
1837      if ( mishead && rhfirstev == firstev ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
1838                                               // missing it no way we can found a piece in the frag table
1839        //
1840        oss.str("");
1841        oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "
1842            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
1843            << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1844            << " ID != " << glrun->ID
1845          << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!          << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
1846      //      //
1847      if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());      if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());
# Line 1353  void PamelaDBOperations::HandleRunFragme Line 1851  void PamelaDBOperations::HandleRunFragme
1851      //      //
1852      row = result->Next();      row = result->Next();
1853      //      //
1854        if ( !row && NoFrag() ){
1855          //
1856          oss.str("");
1857          oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
1858              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
1859              << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1860              << " ID != " << glrun->ID
1861              << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
1862          //
1863          if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
1864          result = conn->Query(oss.str().c_str());
1865          //
1866          if ( !result ) throw -4;
1867          //
1868          foundinrun = true;
1869          //
1870          row = result->Next();
1871          //
1872        };
1873        //
1874      if ( !row ){      if ( !row ){
1875        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
1876        found = false;        found = false;
# Line 1427  void PamelaDBOperations::HandleRunFragme Line 1945  void PamelaDBOperations::HandleRunFragme
1945        //        //
1946        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 ");
1947        //        //
1948          if ( foundinrun ){
1949            glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
1950            glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1951          };
1952          //
1953        GL_RUN *glrun1 = new GL_RUN();        GL_RUN *glrun1 = new GL_RUN();
1954        //        //
1955        UInt_t idfrag = (UInt_t)atoll(row->GetField(0));        //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
1956        //        //
1957        oss.str("");        oss.str("");
1958        oss << " ID="<<row->GetField(0)<<";";        oss << " ID="<<row->GetField(0)<<";";
# Line 1458  void PamelaDBOperations::HandleRunFragme Line 1981  void PamelaDBOperations::HandleRunFragme
1981        };        };
1982        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);
1983        //        //
       glrun1->SetID(0);  
1984        glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());        glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
1985        glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());        glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
1986        glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());        glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
# Line 1467  void PamelaDBOperations::HandleRunFragme Line 1989  void PamelaDBOperations::HandleRunFragme
1989        //        //
1990        glrun->SetEV_FROM(firstev);        glrun->SetEV_FROM(firstev);
1991        glrun->SetNEVENTS(lastev-firstev+1);        glrun->SetNEVENTS(lastev-firstev+1);
1992          //
1993        glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());        glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
1994        glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());        glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
1995        glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());        glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
# Line 1486  void PamelaDBOperations::HandleRunFragme Line 2009  void PamelaDBOperations::HandleRunFragme
2009        //        //
2010        if ( !IsRunAlreadyInserted() ){        if ( !IsRunAlreadyInserted() ){
2011          //          //
2012            //      glrun->SetID(this->AssignRunID());
2013            glrun->SetID_RUN_FRAG(glrun1->GetID());
2014          glrun->Fill_GL_RUN(conn);          glrun->Fill_GL_RUN(conn);
2015          //          //
2016          // 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);  
2017          //          //
2018            glrun1->SetID_RUN_FRAG(glrun->GetID());
2019          glrun1->Fill_GL_RUN(conn);          glrun1->Fill_GL_RUN(conn);
2020          //          //
         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;  
         //  
2021        };        };
       //  
       delete glrun1;  
       //  
2022        // delete old entry in fragment table        // delete old entry in fragment table
2023        //        //
2024        oss.str("");        glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2025          glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2026        //        //
2027        oss << " DELETE FROM GL_RUN_FRAGMENTS WHERE ID = " << idfrag << ";";        delete glrun1;
2028        //        //
       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;  
2029        //        //
2030        return;        return;
2031        //        //
# Line 1555  void PamelaDBOperations::HandleRunFragme Line 2034  void PamelaDBOperations::HandleRunFragme
2034    };    };
2035    //    //
2036    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
2037                                             // 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
2038      //      //
2039      oss.str("");      oss.str("");
2040      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 "
2041          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2042          << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME()          << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2043            << " ID != " << glrun->ID
2044          << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";          << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2045      //      //
2046      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 1570  void PamelaDBOperations::HandleRunFragme Line 2050  void PamelaDBOperations::HandleRunFragme
2050      //      //
2051      row = result->Next();      row = result->Next();
2052      //      //
2053        if ( !row && NoFrag() ){
2054          //
2055          oss.str("");
2056          oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN WHERE "
2057              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2058              << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2059              << " ID != " << glrun->ID
2060              << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2061          //
2062          if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
2063          result = conn->Query(oss.str().c_str());
2064          //
2065          if ( !result ) throw -4;
2066          //
2067          foundinrun = true;
2068          row = result->Next();
2069          //
2070        };
2071        //
2072      if ( !row ){      if ( !row ){
2073        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2074        found = false;        found = false;
# Line 1643  void PamelaDBOperations::HandleRunFragme Line 2142  void PamelaDBOperations::HandleRunFragme
2142        //        //
2143        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 ");
2144        //        //
2145          if ( foundinrun ){
2146            glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2147            glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2148          };
2149          //
2150        GL_RUN *glrun1 = new GL_RUN();        GL_RUN *glrun1 = new GL_RUN();
2151        //        //
2152        UInt_t idfrag = (UInt_t)atoll(row->GetField(0));        //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
2153        //        //
2154        oss.str("");        oss.str("");
2155        oss << " ID="<<row->GetField(0)<<";";        oss << " ID="<<row->GetField(0)<<";";
# Line 1682  void PamelaDBOperations::HandleRunFragme Line 2186  void PamelaDBOperations::HandleRunFragme
2186        glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());        glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());
2187        glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());        glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());
2188        //        //
       glrun1->SetID(0);  
2189        glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());        glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());
2190        glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());        glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());
2191        glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());        glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());
# Line 1702  void PamelaDBOperations::HandleRunFragme Line 2205  void PamelaDBOperations::HandleRunFragme
2205        //        //
2206        if ( !IsRunAlreadyInserted() ){        if ( !IsRunAlreadyInserted() ){
2207          //          //
2208          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();  
2209          //          //
2210          UInt_t idrun0 = 0;          glrun->SetID_RUN_FRAG(glrun1->GetID());
2211          if ( !row ){          glrun->Fill_GL_RUN(conn);
           throw -10;  
         } else {  
           idrun0 = (UInt_t)atoll(row->GetField(0));  
         };  
2212          //          //
2213          glrun1->SetID_RUN_FRAG(idrun0);          // set id number
2214          //          //
2215            glrun1->SetID_RUN_FRAG(glrun->GetID());
2216          glrun1->Fill_GL_RUN(conn);          glrun1->Fill_GL_RUN(conn);
2217          //          //
         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;  
         //  
2218        };        };
2219        //        //
2220        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 << ";";  
2221        //        //
2222        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");
2223        result =  conn->Query(oss.str().c_str());        glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
       if ( !result ) throw -4;  
2224        //        //
2225          delete glrun1;
2226        //        //
2227        return;        return;
2228        //        //
# Line 1800  void PamelaDBOperations::HandleRunFragme Line 2259  void PamelaDBOperations::HandleRunFragme
2259      //      //
2260      row = result->Next();      row = result->Next();
2261      //      //
2262      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 {  
2263        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");
2264        } else {
2265          if ( NoFrag() ){
2266            glrun->SetID_RUN_FRAG(glrun->GetID());
2267            glrun->Fill_GL_RUN(conn);      
2268            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2269          };    
2270      };      };
2271    };    };
2272    //    //
# Line 1864  void PamelaDBOperations::HandleMissingHo Line 2292  void PamelaDBOperations::HandleMissingHo
2292      //      //
2293      this->FillClass(mishead,mistrail,firstev,lastev);      this->FillClass(mishead,mistrail,firstev,lastev);
2294      //      //
2295      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);          if ( !IsRunAlreadyInserted() ){
2296          glrun->SetID(this->AssignRunID());
2297          glrun->SetID_RUN_FRAG(0);
2298          glrun->Fill_GL_RUN(conn);    
2299        };
2300      //      //
2301    };    };
2302    //    //
# Line 2031  Bool_t PamelaDBOperations::IsRunConsiste Line 2463  Bool_t PamelaDBOperations::IsRunConsiste
2463            //                  //      
2464            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
2465            //            //
2466            if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                  if ( !IsRunAlreadyInserted() ){
2467                glrun->SetID(this->AssignRunID());
2468                glrun->SetID_RUN_FRAG(0);
2469                glrun->Fill_GL_RUN(conn);      
2470              };
2471            //            //
2472            firstevno = lastentry + 1;            firstevno = lastentry + 1;
2473            //            //
# Line 2106  void PamelaDBOperations::HandleSuspiciou Line 2542  void PamelaDBOperations::HandleSuspiciou
2542    if ( firstev == lastev+1 ) { // no events inside the run!    if ( firstev == lastev+1 ) { // no events inside the run!
2543      if ( IsDebug() ) printf(" Checking but no events in the run! \n");      if ( IsDebug() ) printf(" Checking but no events in the run! \n");
2544      //      //
     //    if ( IsDebug() ) printf(" -> fill the DB \n");  
     //  
2545      this->FillClass();      this->FillClass();
2546      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);          if ( !IsRunAlreadyInserted() ){
2547          glrun->SetID(this->AssignRunID());
2548          glrun->SetID_RUN_FRAG(0);
2549          glrun->Fill_GL_RUN(conn);    
2550        };
2551      //      //
2552    } else {    } else {
2553      //      //
# Line 2137  void PamelaDBOperations::HandleSuspiciou Line 2575  void PamelaDBOperations::HandleSuspiciou
2575        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");
2576        //        //
2577        this->FillClass();        this->FillClass();
2578        if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                if ( !IsRunAlreadyInserted() ){
2579            glrun->SetID(this->AssignRunID());
2580            glrun->SetID_RUN_FRAG(0);
2581            glrun->Fill_GL_RUN(conn);        
2582          };
2583        //        //
2584      } else {      } else {
2585        //        //
# Line 2235  void PamelaDBOperations::HandleSuspiciou Line 2677  void PamelaDBOperations::HandleSuspiciou
2677            //                  //      
2678            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
2679            //            //
2680            if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                  if ( !IsRunAlreadyInserted() ){
2681                glrun->SetID(this->AssignRunID());
2682                glrun->SetID_RUN_FRAG(0);
2683                glrun->Fill_GL_RUN(conn);      
2684              };
2685            //            //
2686            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...
2687              //              //
# Line 2270  void PamelaDBOperations::HandleSuspiciou Line 2716  void PamelaDBOperations::HandleSuspiciou
2716              //                  //    
2717              this->SetCommonGLRUN(firstTime,lastTime);              this->SetCommonGLRUN(firstTime,lastTime);
2718              //              //
2719              if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                    if ( !IsRunAlreadyInserted() ){
2720                  glrun->SetID(this->AssignRunID());
2721                  glrun->SetID_RUN_FRAG(0);
2722                  glrun->Fill_GL_RUN(conn);      
2723                };
2724            };            };
2725            //            //
2726            firstevno = lastentry + 1;            firstevno = lastentry + 1;
# Line 2318  Int_t PamelaDBOperations::insertCALO_CAL Line 2768  Int_t PamelaDBOperations::insertCALO_CAL
2768    tr->SetBranchAddress("Header", &eh);    tr->SetBranchAddress("Header", &eh);
2769    nevents = tr->GetEntries();    nevents = tr->GetEntries();
2770    //    //
2771    if ( !nevents ) return(0);    if ( !nevents ) return(1);
2772    //    //
2773    for (UInt_t i=0; i < nevents; i++){    for (UInt_t i=0; i < nevents; i++){
2774      tr->GetEntry(i);      tr->GetEntry(i);
# Line 2377  Int_t PamelaDBOperations::insertCALO_CAL Line 2827  Int_t PamelaDBOperations::insertCALO_CAL
2827                // no calibrations in the db contain our calibration                // no calibrations in the db contain our calibration
2828                //                //
2829                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);
2830                if ( fromtime < 1150863400 ){                if ( fromtime < 1150871000 ){ //1150866904
2831                  if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);                  if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);
2832                  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
2833                };                };
# Line 2522  void PamelaDBOperations::HandleTRK_CALIB Line 2972  void PamelaDBOperations::HandleTRK_CALIB
2972        // no calibrations in the db contain our calibration        // no calibrations in the db contain our calibration
2973        //        //
2974        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");
2975        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
2976        //        //
2977        oss.str("");        oss.str("");
2978        oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "        oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "
# Line 2635  Int_t PamelaDBOperations::insertTRK_CALI Line 3085  Int_t PamelaDBOperations::insertTRK_CALI
3085    tr2->SetBranchAddress("Header", &eh2);    tr2->SetBranchAddress("Header", &eh2);
3086    nevents2 = tr2->GetEntries();    nevents2 = tr2->GetEntries();
3087    //    //
3088    if ( !nevents1 && !nevents2 ) return(0);    if ( !nevents1 && !nevents2 ) return(1);
3089    //    //
3090    t2 = -1;    t2 = -1;
3091    Int_t pret2 = 0;    Int_t pret2 = 0;
# Line 2651  Int_t PamelaDBOperations::insertTRK_CALI Line 3101  Int_t PamelaDBOperations::insertTRK_CALI
3101      pkt1 = ph1->GetCounter();        pkt1 = ph1->GetCounter();  
3102      fromtime = this->GetAbsTime(ph1->GetOrbitalTime());        fromtime = this->GetAbsTime(ph1->GetOrbitalTime());  
3103      //      //
3104      valid = 1;  //     valid = 1;
3105      //  //     //
3106      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
3107      //      //
3108      //      //
3109      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) ){
3110        //        //
3111        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);
3112          //      
3113          valid = ValidateTrkCalib( caltrk1, eh1 );
3114          if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;
3115        //        //
3116        // Do we have the second calibration packet?        // Do we have the second calibration packet?
3117        //        //
# Line 2675  Int_t PamelaDBOperations::insertTRK_CALI Line 3128  Int_t PamelaDBOperations::insertTRK_CALI
3128            obt2 = ph2->GetOrbitalTime();              obt2 = ph2->GetOrbitalTime();  
3129            pkt2 = ph2->GetCounter();              pkt2 = ph2->GetCounter();  
3130            //            //
3131            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
3132            //                  //      
3133          } else {          } else {
3134            //            //
# Line 2706  Int_t PamelaDBOperations::insertTRK_CALI Line 3159  Int_t PamelaDBOperations::insertTRK_CALI
3159          //          //
3160          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);
3161          //          //
3162            UInt_t valid2 = ValidateTrkCalib( caltrk2, eh2 );
3163            if ( IsDebug() ) cout << " pkt2 validation --> "<<valid2<<endl;
3164            valid = valid & valid2;
3165            //
3166          // Handle good calib          // Handle good calib
3167          //          //
3168          this->HandleTRK_CALIB(true,true);          this->HandleTRK_CALIB(true,true);
# Line 2807  Int_t PamelaDBOperations::insertS4_CALIB Line 3264  Int_t PamelaDBOperations::insertS4_CALIB
3264    stringstream oss;    stringstream oss;
3265    oss.str("");    oss.str("");
3266    //    //
   CalibS4Event *calibS4    = new  CalibS4Event();  
3267    TTree *tr = 0;    TTree *tr = 0;
3268    EventHeader *eh = 0;    EventHeader *eh = 0;
3269    PscuHeader *ph = 0;    PscuHeader *ph = 0;
# Line 2821  Int_t PamelaDBOperations::insertS4_CALIB Line 3277  Int_t PamelaDBOperations::insertS4_CALIB
3277    tr = (TTree*)file->Get("CalibS4");    tr = (TTree*)file->Get("CalibS4");
3278    if ( !tr || tr->IsZombie() ) throw -24;    if ( !tr || tr->IsZombie() ) throw -24;
3279    //    //
   tr->SetBranchAddress("CalibS4", &calibS4);  
3280    tr->SetBranchAddress("Header", &eh);    tr->SetBranchAddress("Header", &eh);
3281    //    //
3282    nevents = tr->GetEntries();    nevents = tr->GetEntries();
3283    //    //
3284    if ( !nevents ) return(0);    if ( !nevents ) return(1);
3285    //    //
3286    for (UInt_t i = 0; i < nevents; i++){    for (UInt_t i = 0; i < nevents; i++){
3287      //      //
3288      tr->GetEntry(i);      tr->GetEntry(i);
     TArrayD params = S4_paramfit(calibS4);  
3289      //      //
3290      ph = eh->GetPscuHeader();      ph = eh->GetPscuHeader();
3291      obt = ph->GetOrbitalTime();        obt = ph->GetOrbitalTime();  
# Line 2881  Int_t PamelaDBOperations::insertS4_CALIB Line 3335  Int_t PamelaDBOperations::insertS4_CALIB
3335            // no calibrations in the db contain our calibration            // no calibrations in the db contain our calibration
3336            //            //
3337            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");
3338            if ( fromtime < 1150863400 ){            if ( fromtime < 1150871000 ){  
3339              if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);              if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);
3340              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
3341            };            };
# Line 2921  Int_t PamelaDBOperations::insertS4_CALIB Line 3375  Int_t PamelaDBOperations::insertS4_CALIB
3375          };          };
3376          //          //
3377          oss.str("");          oss.str("");
3378          oss << " INSERT INTO GL_S4_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,PARAM_FIT0,PARAM_FIT1,OBT,PKT,BOOT_NUMBER,VALIDATION) "          oss << " INSERT INTO GL_S4_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,OBT,PKT,BOOT_NUMBER) "
3379              << " VALUES (NULL,' "              << " VALUES (NULL,' "
3380              << idroot << "','"              << idroot << "','"
3381              << i << "','"              << i << "','"
3382              << fromtime << "','"              << fromtime << "','"
3383              << totime << "','"              << totime << "','"
             << dec << params.At(0) << "','"  
             << dec << params.At(1) << "','"        
3384              << obt << "','"              << obt << "','"
3385              << pkt << "','"              << pkt << "','"
3386              << this->GetBOOTnumber() << "','"              << this->GetBOOTnumber() << "');";
             << valid << "');";  
3387          //          //
3388          if ( IsDebug() ) printf(" Insert the new calibration: query is \n %s \n",oss.str().c_str());          if ( IsDebug() ) printf(" Insert the new calibration: query is \n %s \n",oss.str().c_str());
3389          //          //
# Line 2953  Int_t PamelaDBOperations::insertS4_CALIB Line 3404  Int_t PamelaDBOperations::insertS4_CALIB
3404    return(0);    return(0);
3405  };  };
3406    
3407    /**
3408  /*   * Scan the fragment table and move old fragments to the GL_RUN table
  * Fit function Received from Valeria Malvezzi 06/02/2006  
3409   */   */
3410  Double_t fitf(Double_t *x, Double_t *par){    Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(){
3411    Double_t fitval =(par[0]*x[0])+par[1];    return(this->CleanGL_RUN_FRAGMENTS(""));
3412    return fitval;  };
 }  
3413    
3414  /*  /**
3415   * Fit the S4 calibration with a straight line - Received from Valeria Malvezzi 06/02/2006   * Scan the fragment table and move old fragments to the GL_RUN table
3416   */   */
3417  TArrayD PamelaDBOperations::S4_paramfit(pamela::CalibS4Event *S4CalibEvent){        Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(TString fcleanfile){
3418      //
3419    //----------- variable initialization -------------------------------------------------    TSQLResult *result = 0;
3420      TSQLRow    *row    = 0;
3421    Double_t mip[3]={1, 30, 300};    TSQLResult *result2 = 0;
3422    Double_t adc[3] = {0.,0.,0.};    TSQLRow    *row2   = 0;
3423        //
3424    TArrayD parametri(2);    UInt_t moved = 0;
3425      //
3426    valid = 1;    stringstream oss;
3427      oss.str("");
3428    //------------ Fit calibrations and find parameters to calibrate data ------------------    //
3429    pamela::S4::S4Event  *s4Record;    if ( !strcmp(fcleanfile.Data(),"") ){
3430        //
3431    for (Int_t j = 0; j < 4; j++){      // check if there are entries older than "olderthan" seconds from now
3432      for (Int_t i = 0; i < 128; i++){      //
3433        s4Record = (pamela::S4::S4Event*)S4CalibEvent->Records->At((j*128 + i));      oss.str("");
3434        switch (j) {      oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
3435        case 0 :{          << " INSERT_TIME <= '" << clean_time->AsSQLString() << "';";
3436          adc[0]=adc[0]+((s4Record->S4_DATA)-32);      //
3437          break;      if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS runs older than %s : query is \n %s \n",clean_time->AsSQLString(),oss.str().c_str());
3438        };      result = conn->Query(oss.str().c_str());
3439        case 1 :{      //
3440          adc[1]=adc[1]+((s4Record->S4_DATA)-32);    } else {
3441          break;      oss.str("");
3442        };      oss << " SELECT ID FROM GL_ROOT WHERE NAME='" << fcleanfile.Data() << "';";
3443        case 3 :{      if ( IsDebug() ) printf(" Getting ID_ROOT_L0 query %s \n",oss.str().c_str());
3444          adc[2]=adc[2]+((s4Record->S4_DATA)-32);      result = conn->Query(oss.str().c_str());
3445          break;      //    
3446        if ( result ){
3447          //
3448          row = result->Next();
3449          //
3450          if ( row ){
3451            oss.str("");
3452            oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
3453                << " ID_ROOT_L0=" << row->GetField(0) << ";";
3454            //
3455            if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS for ROOT file query is \n %s \n",oss.str().c_str());
3456            result = conn->Query(oss.str().c_str());
3457            //    
3458        };        };
3459        } else {
3460          return(2);
3461        };
3462      };
3463      //
3464      if ( result ){
3465        //
3466        row = result->Next();
3467        //
3468        while ( row ){
3469          //
3470          oss.str("");
3471          oss << " ID= "<< row->GetField(0);
3472          //
3473          glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);  
3474          //
3475          oss.str("");
3476          oss << " SELECT ID,NEVENTS,TRK_CALIB_USED,PKT_COUNTER FROM GL_RUN WHERE "
3477              << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND ("
3478              << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3479              << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3480              << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3481              << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3482              << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3483              << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3484              << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3485              << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3486              << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3487              << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3488              << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3489              << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3490          //
3491          if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3492          result2 = conn->Query(oss.str().c_str());
3493          //
3494          if ( !result2 ) throw -4;
3495          //
3496          row2 = result2->Next();
3497          //
3498          if ( !row2 ){
3499            //
3500            if ( IsDebug() ) printf(" The run is new \n");
3501            if ( IsDebug() ) printf(" -> fill the DB \n");      
3502            //
3503            //      glrun->SetID(this->AssignRunID()); we use the old run number!
3504            glrun->SetID_RUN_FRAG(glrun->GetID());
3505            glrun->Fill_GL_RUN(conn);  
3506            //
3507    //      oss.str("");
3508    //      oss << " SELECT ID FROM GL_RUN WHERE "
3509    //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
3510    //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
3511    //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
3512    //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
3513    //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
3514    //      //
3515    //      if ( IsDebug() ) printf(" Look for the ID of the inserted run: query is \n %s \n",oss.str().c_str());
3516    //      result2 = conn->Query(oss.str().c_str());
3517    //      //
3518    //      if ( !result2 ) throw -4;
3519    //      //
3520    //      row2 = result2->Next();
3521    //      //
3522    //      if ( !row2 ) throw -25;
3523    //      //
3524    //      oss.str("");
3525    //      oss << " UPDATE GL_RUN SET ID_RUN_FRAG = " << row2->GetField(0) << " WHERE ID = " << row2->GetField(0);
3526    //      if ( IsDebug() ) printf(" Update the ID_RUN_FRAG of the inserted run: query is \n %s \n",oss.str().c_str());
3527    //      result2 = conn->Query(oss.str().c_str());
3528    //      //
3529    //      if ( !result2 ) throw -4;
3530            //
3531            moved++;
3532            //
3533          } else {
3534            if ( IsDebug() ) printf(" The already exist in the GL_RUN table! \n");
3535        };        };
3536          if ( IsDebug() ) printf(" Delete run %s from the GL_RUN_FRAGMENTS table \n",row->GetField(0));      
3537          //
3538          //
3539          glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3540    //      oss.str("");
3541    //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);
3542    //       if ( IsDebug() ) printf(" Clean the GL_RUN_FRAGMENTS table: query is \n %s \n",oss.str().c_str());
3543    //       result2 = conn->Query(oss.str().c_str());
3544    //      //
3545    //      if ( !result2 ) throw -4;
3546    //      //
3547          row = result->Next();
3548      };      };
3549    };    };
3550        if ( IsDebug() ) printf(" Moved %u runs\n",moved);
3551    adc[0]=adc[0]/128;    return(0);
3552    adc[1]=adc[1]/128;  };
   adc[2]=adc[2]/128;  
     
   TGraph *fitpar = new TGraph (3, adc, mip);  
   TF1 *func = new TF1("fitf", fitf, -0., 1000., 2); // definizione della funzione, 2 = num. parametri  
     
   func->SetParameters(0.3,1.);        //inizializzazione dei parametri a 1  
   func->SetParNames("m","q");      //definisce il nome dei parametri  
   fitpar->Fit(func,"qr");          //fitta fitpar con la funzione func nel range definito nella funzione  
   //fitpar->Fit(func,"r");          //fitta fitpar con la funzione func nel range definito nella funzione  
       
   parametri[0] = func -> GetParameter(0);  
   parametri[1] = func -> GetParameter(1);  
   
   if ( parametri[0] < 0. || parametri[0] > 0.5 || parametri[1] < 0.8 || parametri[1] > 1. ) valid = 0;  
3553    
3554    if ( IsDebug() ) printf(" par1 = %g par2 = %g\n",parametri[0],parametri[1]);  /**
3555     * Check if runs are good, i.e. if the tracker calibration is correctly associated..
3556    return parametri;   */
3557    Int_t PamelaDBOperations::ValidateRuns(){
3558      return(this->ValidateRuns(""));
3559    };
3560    
3561    /**
3562     * Check if runs are good, i.e. if the tracker calibration is correctly associated..
3563     */
3564    Int_t PamelaDBOperations::ValidateRuns(TString valfile){
3565      //
3566      TSQLResult *result = 0;
3567      TSQLRow    *row    = 0;
3568      //
3569      UInt_t calibtime = 50;
3570      //
3571      stringstream oss;
3572      oss.str("");
3573      //
3574      // =======================================================
3575      // validate runs by checking missing calibrations
3576      // =======================================================
3577      UInt_t t_stop  = 0;
3578      UInt_t t_start = 0;
3579      if ( !strcmp(valfile.Data(),"") ) {
3580        // --------------------------------------------------------------
3581        // 1) get the OBT of the last run inserted after clean-time limit
3582        // --------------------------------------------------------------
3583        oss.str("");
3584        oss << " SELECT * FROM GL_RUN  WHERE INSERT_TIME <= '" << clean_time->AsSQLString()
3585            << "' ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
3586        if ( IsDebug() ) printf(" Get start validation-time: query is \n %s \n",oss.str().c_str());
3587        result = conn->Query(oss.str().c_str());
3588        if ( !result ) throw -4;
3589        if ( !result->GetRowCount() ) {
3590          printf(" No runs to validate \n");
3591          return(1);
3592        }else{
3593          row = result->Next();
3594          t_start = (UInt_t)atoll(row->GetField(4));
3595        };  
3596        // --------------------------------------------------------------
3597        // 2) get the OBT of the last validated run
3598        // --------------------------------------------------------------
3599        oss.str("");
3600        oss << " SELECT * FROM GL_RUN  WHERE VALIDATION=1 AND RUNHEADER_TIME<="<< t_start
3601            <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
3602        if ( IsDebug() ) printf(" Get stop validation-time: query is \n %s \n",oss.str().c_str());
3603        result = conn->Query(oss.str().c_str());
3604        if ( !result ) throw -4;
3605        if ( result->GetRowCount() ){
3606          row = result->Next();
3607          t_stop = (UInt_t)atoll(row->GetField(4));
3608        };
3609        if ( IsDebug() ) printf("Validation interval: from time %i - to time %i \n\n",t_stop,t_start);
3610        // --------------------------------------------------------------
3611        // now retrieves runs to be validated
3612        // --------------------------------------------------------------
3613        oss.str("");
3614        oss << " SELECT * FROM GL_RUN  WHERE  RUNHEADER_TIME <=" << t_start;
3615        oss << " AND RUNHEADER_TIME >="<< t_stop;
3616        oss << " ORDER BY RUNHEADER_TIME DESC;";
3617        if ( IsDebug() )printf(" Check runs for validation: query is \n %s \n",oss.str().c_str());
3618        result = conn->Query(oss.str().c_str());
3619      } else {
3620        //
3621        stringstream myquery;
3622        UInt_t myid = 0;
3623        myquery.str("");
3624        myquery << " SELECT ID FROM GL_ROOT where NAME='"<<valfile.Data() <<"';";
3625        //
3626        result = conn->Query(myquery.str().c_str());
3627        //
3628        row = result->Next();      
3629        if( !row ){
3630          if ( strcmp(valfile.Data(),GetRootName().Data()) ){
3631            if ( IsDebug() ) printf(" No file to be validated even if option \"-validate file\" was used!!\n");
3632            return(2);
3633          };
3634          if ( IsDebug() ) printf(" No file to be validated (force mode)! \n");
3635          return(0);
3636        };
3637        myid=(UInt_t)atoll(row->GetField(0));
3638        //
3639        myquery.str("");
3640        myquery << " SELECT MAX(RUNTRAILER_TIME),MIN(RUNHEADER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< myid <<";";
3641        //
3642        result = conn->Query(myquery.str().c_str());
3643        //
3644        row = result->Next();      
3645        if( !row->GetField(0) || !row->GetField(1)){
3646          //
3647          if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
3648          //
3649          return(0);
3650          //
3651        } else {  
3652          //
3653          UInt_t runhtime = (UInt_t)atoll(row->GetField(0));
3654          UInt_t runttime = (UInt_t)atoll(row->GetField(1));
3655          UInt_t caltime = 0;
3656          //
3657          myquery.str("");
3658          myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
3659          myquery << " order by FROM_TIME asc limit 1;";
3660          //
3661          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
3662          //
3663          //
3664          result = conn->Query(myquery.str().c_str());
3665          //
3666          row = result->Next();      
3667          if( !row ){
3668            caltime = runhtime;
3669          } else {
3670            caltime = (UInt_t)atoll(row->GetField(0));
3671          };
3672          //
3673          myquery.str("");
3674          myquery << " SELECT * from GL_RUN where RUNHEADER_TIME>="<< runttime <<" AND RUNHEADER_TIME<=" ;
3675          myquery << caltime << " order by RUNHEADER_TIME DESC";
3676          //
3677          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
3678          //
3679          result = conn->Query(myquery.str().c_str());
3680          //
3681        };
3682      };
3683      //
3684      if ( !result ) throw -4;
3685      if ( !result->GetRowCount() && IsDebug() ) printf(" No runs to validate \n");
3686      //
3687      Int_t nrow = 0;
3688      GL_RUN* this_run = new GL_RUN();
3689      GL_RUN* next_run = new GL_RUN();
3690      Int_t   nseq_max = 1000;
3691    //  UInt_t* sequence = new UInt_t[100];
3692      vector<UInt_t> sequence(nseq_max);
3693      Int_t   nseq = 0;
3694      Bool_t CHECK = false;
3695      Bool_t this_ONLINE = false;
3696      Bool_t next_ONLINE = false;
3697      UInt_t t1=0,t2=0;
3698      // ---------------------------------------------------------------------------------
3699      // - loop over runs, back in time,
3700      // - select sequences of runs close in time (less than calibtime s apart),
3701      //   which could be preceeded by a calibration
3702      // - check if there might be a missing calibration
3703      // ---------------------------------------------------------------------------------
3704      while(1){
3705              
3706              row = result->Next();
3707              if( row == NULL ) break;
3708              
3709              //------------
3710              //get run info
3711              //------------
3712              this_run->Set_GL_RUN(row);
3713                      
3714              Bool_t this_BAD = false;
3715              if(this_run->GetTRK_CALIB_USED() == 1 || this_run->GetTRK_CALIB_USED() == 2) this_ONLINE = true;
3716              else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;
3717              else{
3718    //                printf("Missing or corrupted header!! \n");
3719                      this_ONLINE = false;
3720                      this_BAD = true;
3721              };
3722    
3723              //-----------------------------------
3724              //compare with previous(next in time)
3725              //-----------------------------------
3726              CHECK = false;
3727              UInt_t interval=0;
3728              
3729              if( nrow != 0){
3730            
3731                      
3732                      t1 = this_run->GetRUNTRAILER_TIME();
3733                      t2 = next_run->GetRUNHEADER_TIME();
3734                      interval = (t2-t1);
3735                      
3736                      if(this_ONLINE && next_ONLINE){                               // this: ON-LINE + next: ON-LINE
3737                              
3738                              if( this_run->ID == next_run->ID_RUN_FRAG ) interval = 0;     //=> run fragments
3739                              
3740                              if( interval >= calibtime )CHECK = true;                      //more than calibtime s => there might be a calibration
3741                              
3742                              if( !CHECK && this_run->VALIDATION ){
3743                                      for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
3744                                      nseq=0;
3745                              }
3746                      
3747                      }else if( !this_ONLINE && next_ONLINE) {              // this: DEFAULT + next:ON-LINE
3748                              
3749                              CHECK = true;
3750    
3751                      }else if( !next_ONLINE ){                                             // this:ANY + next:DEFAULT
3752                              
3753                              assignVALIDATION(next_run->ID,true);
3754                              nseq=0;
3755                      }
3756              }
3757    
3758              //----------------------------
3759              //check run sequence for calib
3760              //----------------------------
3761              if( CHECK ){
3762                      // check if calibration exists
3763                      if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);
3764                      Bool_t MISSING = MissingTRK_CALIB(t1,t2);
3765                      for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],!MISSING);
3766                      nseq=0;
3767              };
3768              //--------------
3769              //store run info
3770              //--------------
3771              *next_run   = *this_run;
3772              next_ONLINE = this_ONLINE;
3773              if( !this_BAD ){
3774                      if(nseq < nseq_max){
3775                              sequence[nseq] = this_run->ID;
3776                              nseq++;
3777                      }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);
3778              };
3779              
3780              if ( IsDebug() ) printf("%i Run %i \n",nrow,this_run->ID);
3781              nrow++;
3782              
3783      };
3784      delete this_run;
3785      delete next_run;
3786      //
3787      return(0);
3788    };
3789    /**
3790     * Check if there might be a missing tracker calibration in a given time interval
3791     * @param t1 From absolute time
3792     * @param t2 To absolute time
3793     * @return true if there might be a missing calibration
3794     */
3795    Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
3796            
3797            GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();
3798            
3799            // get the closest VALIDATED calibration before the run start (t2)
3800            if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true);      //>>> missing
3801            
3802            if ( trkcalib->TO_TIME  < t2 ) return(true);                                    //>>> missing
3803            
3804            //==============================================================
3805            // Check is done first on the basis of time between calibration,
3806            // which should be equal to the time between ascending-nodes.
3807            //==============================================================
3808            if ( t2 - trkcalib->FROM_TIME > 5700) {
3809                    if ( IsDebug() )printf("Long time between calib and run start %i :-( ==> there might be a missing calib \n",t2 - trkcalib->FROM_TIME);
3810            //==============================================================
3811            // there might be a missing calibration, due to:
3812            // - MM full
3813            // - corrupted packets
3814            // - loss of data
3815            // There is an exception in case a download was done during ascending node
3816            //==============================================================
3817                    Bool_t DOWNLOAD = false;
3818                    // check if the calib was skipped becouse of download .... DA FARE!!
3819                    if(DOWNLOAD)return(false);
3820                    
3821                    return(true);                                   //>>> missing
3822                    
3823            };
3824            
3825            //==============================================================
3826            // If the last calibration is close to the run less than this time,
3827            // it is enough to say that there are no missing calibrations
3828            //==============================================================
3829            // the long time interval bewteen runs might be due to download
3830            if ( IsDebug() )printf("Short time between calib and run start %i :-) ==> OK! \n",t2 - trkcalib->FROM_TIME);
3831            return(false);
3832            
3833    };
3834    /**
3835     * Assign VALIDATION value to a GL_RUN entry
3836     * @param idrun Run ID
3837     * @param validation true/false
3838     */
3839    Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){
3840            TSQLResult *result = 0;
3841            stringstream oss;
3842            oss.str("");
3843            oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";
3844            //
3845    //      if ( IsDebug() )
3846    //      printf(" Set VALIDATION = %i for run %i \n",validation,idrun);
3847            if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());
3848            result = conn->Query(oss.str().c_str());
3849            if ( !result ) throw -4;
3850            return(0);
3851    }
3852    
3853    
3854    
3855    // Insert TLEs from file tlefilename in the table GL_TLE in the db
3856    // opened by conn, sorting them by date from older to newer, if each
3857    // TLE has not been alread inserted.
3858    Int_t PamelaDBOperations::populateTLE()//(TSQLServer *conn, char *tleFile)
3859    {
3860      fstream tlefile(tlefilename, ios::in);
3861    
3862      if ( !tlefile ) throw -7;
3863    
3864      vector<cTle*> ctles;
3865      vector<cTle*>::iterator iter;
3866      int present = 0;
3867    
3868      // Get three lines from tlefile, create a cTle object and put it
3869      // into ctles
3870      while(1) {
3871        cTle *tlef;
3872        string str1, str2, str3;
3873    
3874        getline(tlefile, str1);
3875        if(tlefile.eof()) break;
3876    
3877        getline(tlefile, str2);
3878        if(tlefile.eof()) break;
3879    
3880        getline(tlefile, str3);
3881        if(tlefile.eof()) break;
3882    
3883        // We now have three good lines for a cTle.
3884        tlef = new cTle(str1, str2, str3);
3885        ctles.push_back(tlef);
3886      }
3887    
3888      tlefile.close();
3889    
3890      // Sort by date
3891      sort(ctles.begin(), ctles.end(), compTLE);
3892    
3893      // Now we insert each TLE into the db
3894      for(iter = ctles.begin(); iter != ctles.end(); iter++) {
3895        cTle *tle = *iter;
3896    
3897        // Do nothing if it's already present in the db.  Just increase
3898        // the counter present.
3899        if (! isTlePresent(tle))
3900          {
3901            int status = insertTle(tle);
3902    
3903            // Insert query failed.  Return 1.
3904            if(status == EXIT_FAILURE) {
3905              
3906              if( IsDebug() ) {
3907                cerr << "Error: inserting TLE:" << endl
3908                     << tle->getName() << endl
3909                     << tle->getLine1() << endl
3910                     << tle->getLine2() << endl;
3911              }
3912    
3913              throw -4;
3914              return 1;
3915            }
3916    
3917          }
3918        else
3919          present++;
3920    
3921      }
3922    
3923      int inserted = ctles.size() - present;  // Number of inserted TLE.
3924      if ( IsDebug() )
3925        cout << "\nProcessed TLEs ranging from " << getTleDatetime(ctles[0]) << " to " << getTleDatetime(ctles[ctles.size()-1]) << "." << endl
3926             << inserted << " newly inserted TLEs out of " << ctles.size() << " processed." << endl;
3927    
3928      ctles.clear();
3929    
3930    
3931      // Return 2 if no new TLE has been inserted.  0 otherwise.
3932      if(! inserted ) return 2;
3933      return 0;
3934    }
3935    
3936    
3937    // Insert tle in the table GL_TLE using the connection conn.
3938    Int_t PamelaDBOperations::insertTle(cTle *tle)
3939    {
3940      stringstream oss;
3941      TSQLResult *result = 0;
3942    
3943      oss.str("");
3944      oss << " INSERT INTO GL_TLE (TLE1, TLE2, TLE3, FROM_TIME)"
3945          << " VALUES ( '"
3946          << tle->getName() << "', '"
3947          << tle->getLine1() << "', '"
3948          << tle->getLine2() << "', '"
3949          << getTleDatetime(tle) << "')";
3950    
3951      //  cout << oss.str().c_str() << endl;
3952      result = conn->Query(oss.str().c_str());
3953      if (result == NULL)
3954        return EXIT_FAILURE;
3955    
3956      return EXIT_SUCCESS;
3957    }
3958    
3959    
3960    // Return whether tle is already in the db connected by conn.
3961    bool PamelaDBOperations::isTlePresent(cTle *tle)
3962    {
3963      stringstream oss;
3964      TSQLResult *result = 0;
3965    
3966      oss.str("");
3967      oss << "SELECT * FROM GL_TLE WHERE FROM_TIME = '"
3968          << getTleDatetime(tle) << "'";
3969    
3970      result = conn->Query(oss.str().c_str());
3971      if (result == NULL) throw -4;
3972    
3973      if (result->GetRowCount())
3974        return true;
3975      else
3976        return false;
3977    }
3978    
3979    
3980    // Return whether the first TLE is dated early than the second
3981    bool compTLE (cTle *tle1, cTle *tle2)
3982    {
3983      return getTleJulian(tle1) < getTleJulian(tle2);
3984    }
3985    
3986    
3987    // Return the date of the tle using the format (year-2000)*1e3 +
3988    // julian day.  e.g. 6365 is the 31th Dec 2006.
3989    // It does *not* return a cJulian date.
3990    float getTleJulian(cTle *tle) {
3991      return tle->getField(cTle::FLD_EPOCHYEAR)*1e3 + tle->getField(cTle::FLD_EPOCHDAY);
3992    }
3993    
3994    
3995    // Return a string like YYYY-MM-DD hh:mm:ss, usable for mysql datetime
3996    // format.
3997    string getTleDatetime(cTle *tle)
3998    {
3999      int year, mon, day, hh, mm, ss;
4000      double dom; // day of month (is double!)
4001      stringstream date; // date in datetime format
4002    
4003      // create a cJulian from the date in tle
4004      cJulian jdate = cJulian( 2000 + (int) tle->getField(cTle::FLD_EPOCHYEAR), tle->getField(cTle::FLD_EPOCHDAY));
4005    
4006      // get year, month, day of month
4007      jdate.getComponent(&year, &mon, &dom);
4008    
4009      // build a datetime YYYY-MM-DD hh:mm:ss
4010      date.str("");
4011      day = (int) floor(dom);
4012      hh = (int) floor( (dom - day) * 24);
4013      mm = (int) floor( ((dom - day) * 24 - hh) * 60);
4014      ss = (int) floor( ((((dom - day) * 24 - hh) * 60 - mm) * 60));
4015      //  ms = (int) floor( (((((dom - day) * 24 - hh) * 60 - mm) * 60) - ss) * 1000);
4016    
4017      date << year << "-" << mon << "-" << day << " " << hh << ":" << mm << ":" << ss;
4018    
4019      return date.str();
4020    }
4021    
4022    /**
4023     * Remove a file from the DB, delete on cascade all entries related to that file
4024     * rearrange GL_RUN and GL_XXX_CALIB tables, turn off validation till the following
4025     * calibration
4026     **/
4027    Int_t PamelaDBOperations::removeFile(TString remfile){
4028      //
4029      // Determine ID_ROOT_L0 and ID_RAW
4030      //
4031      TSQLResult *pResult;
4032      TSQLRow *Row;
4033      stringstream myquery;
4034      //  
4035      myquery.str("");
4036      myquery << " SELECT ID, ID_RAW FROM GL_ROOT where NAME='"<<remfile.Data() <<"';";
4037      //
4038      pResult = conn->Query(myquery.str().c_str());
4039      //
4040      Row = pResult->Next();      
4041      if( !Row ){
4042        if ( strcmp(remfile.Data(),GetRootName().Data()) ){
4043          if ( IsDebug() ) printf(" No file to be removed even if option \"-remove file\" was used!!\n");
4044          return(1);
4045        };
4046        if ( IsDebug() ) printf(" No file to be removed (force mode)! \n");
4047        return(0);
4048      };
4049      //
4050      this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));
4051      this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));
4052      //
4053      this->ValidationOFF();
4054      //
4055      this->RemoveCALIBS();
4056      //
4057      this->RemoveRUNS();
4058      //
4059      this->RemoveFILES();
4060      //
4061      this->SetID_ROOT(0);
4062      this->SetID_RAW(0);
4063      //
4064      return(0);
4065    };
4066    
4067    /**
4068     *
4069     * Set validation bit to zero for runs following the removing file till
4070     * 1) a run with TRK_CALIB_USED=140
4071     * 2) a run with VALIDATION = 0
4072     * 3) the next calibration
4073     *
4074     **/
4075    void PamelaDBOperations::ValidationOFF(){
4076      TSQLResult *pResult;
4077      TSQLRow *Row;
4078      stringstream myquery;
4079      Int_t unv = 0;
4080      //select ID from GL_RUN where RUNHEADER_TIME>=1152671382 AND (VALIDATION=0 OR TRK_CALIB_USED=104) order by RUNHEADER_TIME asc limit 1;
4081      myquery.str("");
4082      myquery << " SELECT MAX(RUNTRAILER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
4083      //
4084      pResult = conn->Query(myquery.str().c_str());
4085      //
4086      Row = pResult->Next();      
4087      if( !Row->GetField(0) ){
4088        //
4089        if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
4090        //
4091      } else {  
4092        //
4093        UInt_t runhtime = (UInt_t)atoll(Row->GetField(0));
4094        UInt_t caltime = 0;
4095        //
4096        myquery.str("");
4097        myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
4098        myquery << " order by FROM_TIME asc limit 1;";
4099        //
4100        if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4101        //
4102        //
4103        delete pResult;
4104        pResult = conn->Query(myquery.str().c_str());
4105        //
4106        Row = pResult->Next();      
4107        if( !Row ){
4108          caltime = runhtime;
4109        } else {
4110          caltime = (UInt_t)atoll(Row->GetField(0));
4111        };
4112        //
4113        myquery.str("");
4114        myquery << " SELECT ID,RUNHEADER_TIME from GL_RUN where RUNHEADER_TIME>="<< runhtime <<" AND (VALIDATION=0 OR TRK_CALIB_USED=104 OR RUNHEADER_TIME>" ;
4115        myquery << caltime << ") order by RUNHEADER_TIME asc LIMIT 1";
4116        //
4117        if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4118        //
4119        pResult = conn->Query(myquery.str().c_str());
4120        //
4121        Row = pResult->Next();      
4122        if( !Row ){
4123          //
4124          if ( IsDebug() ) printf(" NO RUN NEED TO BE UNVALIDATED \n");
4125          //
4126        } else {
4127          myquery.str("");
4128          myquery << " SELECT ID from GL_RUN where RUNHEADER_TIME<"<< Row->GetField(1) <<" AND ";
4129          myquery << " RUNHEADER_TIME>=" <<runhtime;
4130          myquery << " order by RUNHEADER_TIME asc;";
4131          //
4132          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4133          //
4134          pResult = conn->Query(myquery.str().c_str());
4135          //
4136          Row = pResult->Next();  
4137          while ( Row ){
4138            //      
4139            unv++;
4140            this->assignVALIDATION((UInt_t)atoll(Row->GetField(0)), false);
4141            Row = pResult->Next();  
4142            //
4143          };
4144        };
4145      };
4146      if ( IsDebug() ) printf(" %i runs have been unvalidated \n",unv);
4147    };
4148    
4149    /**
4150     *
4151     * Rearrange GL_RUN table and remove runs
4152     *
4153     **/
4154    void PamelaDBOperations::RemoveRUNS(){
4155      TSQLResult *pResult;
4156      TSQLRow *Row;
4157      stringstream myquery;
4158      UInt_t drun = 0;
4159      GL_RUN *delrun = new GL_RUN();
4160      //
4161      myquery.str("");
4162      myquery << " SELECT ID FROM GL_RUN where ID_RUN_FRAG=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4163      //
4164      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4165      //
4166      pResult = conn->Query(myquery.str().c_str());
4167      //
4168      Row = pResult->Next();    
4169      //
4170      //
4171      if ( !Row ){
4172        if ( IsDebug() ) printf(" No run with ID_RUN_FRAG=0 belonged to this file \n");
4173      } else {
4174        if ( IsDebug() ) printf(" Deleting run from GL_RUN table \n");    
4175        while ( Row ){
4176          delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
4177          if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(0)));
4178          drun++;
4179          Row = pResult->Next();    
4180        };
4181      };
4182      //
4183      //
4184      myquery.str("");
4185      myquery << " SELECT ID,ID_RUN_FRAG FROM GL_RUN where ID_RUN_FRAG!=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4186      //
4187      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4188      //
4189      pResult = conn->Query(myquery.str().c_str());
4190      //
4191      Row = pResult->Next();    
4192      //
4193      if ( !Row ){
4194        if ( IsDebug() ) printf(" No run with ID_RUN_FRAG!=0 belonged to this file \n");
4195      } else {
4196        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN table \n");    
4197        while ( Row ){
4198          if ( IsDebug() ) printf(" restore run %i \n",(UInt_t)atoll(Row->GetField(1)));
4199          delrun->RestoreRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN_FRAGMENTS");
4200          if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(1)));
4201          delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN");
4202          if ( (UInt_t)atoll(Row->GetField(1)) != (UInt_t)atoll(Row->GetField(0)) ){
4203            if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(0)));
4204            delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
4205          };
4206          drun++;
4207          Row = pResult->Next();    
4208        };
4209      };
4210      //
4211      if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN table \n",drun);    
4212      //
4213      //
4214      //
4215      drun = 0;
4216      //
4217      myquery.str("");
4218      myquery << " SELECT ID_TRASH FROM GL_RUN_TRASH where BELONGED_TO='GL_RUN_FRAGMENTS' AND ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4219      //
4220      pResult = conn->Query(myquery.str().c_str());
4221      //
4222      Row = pResult->Next();    
4223      //
4224      if ( !Row ){
4225        if ( IsDebug() ) printf(" No run from GL_RUN_FRAGMENTS table in the trash table for this file \n");
4226      } else {
4227        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_TRASH table \n");    
4228        while ( Row ){
4229          if ( IsDebug() ) printf(" del run idtrash %i \n",(UInt_t)atoll(Row->GetField(0)));
4230          myquery.str("");
4231          myquery << " DELETE FROM GL_RUN_TRASH where ID_TRASH=" << Row->GetField(0) <<";";      
4232          conn->Query(myquery.str().c_str());
4233          drun++;
4234          Row = pResult->Next();    
4235        };
4236      };
4237      //  
4238      if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN_TRASH table \n",drun);    
4239      //
4240      //
4241      //
4242      drun = 0;
4243      //
4244      myquery.str("");
4245      myquery << " SELECT ID FROM GL_RUN_FRAGMENTS where ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4246      //
4247      pResult = conn->Query(myquery.str().c_str());
4248      //
4249      Row = pResult->Next();    
4250      //
4251      if ( !Row ){
4252        if ( IsDebug() ) printf(" No run in the GL_RUN_FRAGMENTS table for this file \n");
4253      } else {
4254        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_FRAGMENTS table \n");    
4255        while ( Row ){
4256          if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(0)));
4257          myquery.str("");
4258          myquery << " DELETE FROM GL_RUN_FRAGMENTS where ID=" << Row->GetField(0) <<";";
4259          conn->Query(myquery.str().c_str());
4260          drun++;
4261          Row = pResult->Next();    
4262        };
4263      };
4264      //  
4265      if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN_FRAGMENTS table \n",drun);    
4266      //
4267      //
4268      //
4269      delete delrun;
4270      //
4271    };
4272    
4273    
4274    /**
4275     *
4276     * Rearrange calibration tables
4277     *
4278     **/
4279    void PamelaDBOperations::RemoveFILES(){
4280      stringstream myquery;
4281      //
4282      myquery.str("");
4283      myquery << " DELETE FROM GL_RAW WHERE ID=" <<this->GetID_RAW() <<";";
4284      //
4285      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4286      //
4287      conn->Query(myquery.str().c_str());
4288      //
4289    };
4290    
4291    /**
4292     *
4293     * Rearrange calibration tables
4294     *
4295     **/
4296    void PamelaDBOperations::RemoveCALIBS(){
4297      TSQLResult *pResult;
4298      TSQLRow *Row;
4299      stringstream myquery;
4300      //  
4301      //
4302      // Calorimeter
4303      //
4304      for (Int_t section = 0; section < 4; section++){
4305        myquery.str("");
4306        myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_CALO_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<" AND ";
4307        myquery << " SECTION=" << section << ";";
4308        //
4309        pResult = conn->Query(myquery.str().c_str());
4310        //
4311        Row = pResult->Next();      
4312        if( !Row->GetField(0) || !Row->GetField(1) ){
4313          //
4314          if ( IsDebug() ) printf(" NO CALO CALIBRATION SECTION %i ASSOCIATED TO THIS FILE! \n",section);
4315          //
4316        } else {
4317          //
4318          myquery.str("");
4319          myquery << " UPDATE GL_CALO_CALIB SET TO_TIME=" << Row->GetField(1);
4320          myquery << " WHERE TO_TIME="<< Row->GetField(0) << " AND ";
4321          myquery << " SECTION=" << section << ";";
4322          //
4323          pResult = conn->Query(myquery.str().c_str());
4324          //
4325          if( !pResult ){
4326            //
4327            if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
4328            //
4329            throw -4;
4330            //
4331          };
4332          //
4333        };
4334      };
4335      myquery.str("");
4336      myquery << " DELETE FROM GL_CALO_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4337      //
4338      pResult = conn->Query(myquery.str().c_str());
4339      //
4340      if( !pResult ){
4341        //
4342        if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
4343        //
4344        throw -4;
4345        //
4346      };
4347      //
4348      // Tracker
4349      //
4350      myquery.str("");
4351      myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_TRK_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
4352      //
4353      pResult = conn->Query(myquery.str().c_str());
4354      //
4355      Row = pResult->Next();      
4356      if( !Row->GetField(0) || !Row->GetField(1) ){
4357        //
4358        if ( IsDebug() ) printf(" NO TRK CALIBRATION ASSOCIATED TO THIS FILE! \n");
4359        //
4360      } else {
4361        //
4362        myquery.str("");
4363        myquery << " UPDATE GL_TRK_CALIB SET TO_TIME=" << Row->GetField(1);
4364        myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
4365        //
4366        pResult = conn->Query(myquery.str().c_str());
4367        //
4368        if( !pResult ){
4369          //
4370          if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
4371          //
4372          throw -4;
4373          //
4374        };
4375        //
4376        myquery.str("");
4377        myquery << " DELETE FROM GL_TRK_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4378        //
4379        pResult = conn->Query(myquery.str().c_str());
4380        //
4381        if( !pResult ){
4382          //
4383          if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
4384          //
4385          throw -4;
4386          //
4387        };
4388      };
4389      //
4390      //
4391      // S4
4392      //
4393      myquery.str("");
4394      myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_S4_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
4395      //
4396      pResult = conn->Query(myquery.str().c_str());
4397      //
4398      Row = pResult->Next();      
4399      if( !Row->GetField(0) || !Row->GetField(1) ){
4400        //
4401        if ( IsDebug() ) printf(" NO S4 CALIBRATION ASSOCIATED TO THIS FILE! \n");
4402        //
4403      } else {
4404        //
4405        myquery.str("");
4406        myquery << " UPDATE GL_S4_CALIB SET TO_TIME=" << Row->GetField(1);
4407        myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
4408        //
4409        pResult = conn->Query(myquery.str().c_str());
4410        //
4411        if( !pResult ){
4412          //
4413          if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
4414          //
4415          throw -4;
4416          //
4417        };
4418        //
4419        myquery.str("");
4420        myquery << " DELETE FROM GL_S4_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4421        //
4422        pResult = conn->Query(myquery.str().c_str());
4423        //
4424        if( !pResult ){
4425          //
4426          if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
4427          //
4428          throw -4;
4429          //
4430        };
4431        //
4432      };
4433    };
4434    
4435    /**
4436     *
4437     * Rearrange calibration tables
4438     *
4439     **/
4440    UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh ){
4441    
4442        Int_t vorder[]={5,5,3,3,4,4,2,2,1,1,0,0};
4443        UInt_t timeaftercalib=120000; //2000;
4444    //  ----------
4445    //  Check CRCs
4446    //  ----------
4447        for(Int_t ipkt=0; ipkt<6; ipkt++){
4448            if( caltrk->crc_hcal[ipkt] )return 0; // :-(
4449            for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] )return 0; // :-(
4450        }
4451    //  -----------------------
4452    //  Check missing packets:
4453    //  -----------------------
4454    //    Readout order:
4455    //    ------------------
4456    //    DSP   packet board
4457    //    ------------------
4458    //    12    0      1
4459    //    10    1      1
4460    //     8    2      1
4461    //     4    3      1
4462    //     6    4      1
4463    //     2    5      1
4464    //    ------------------
4465    //    11    0      2
4466    //     9    1      2
4467    //     7    2      2
4468    //     3    3      2
4469    //     5    4      2
4470    //     1    5      2
4471    //    ------------------
4472    //  -------------------------------------------------
4473    //  Check if it is first or second calibration packet
4474    //  -------------------------------------------------
4475        UInt_t build=0;
4476        TString classname = caltrk->GetName();
4477        UInt_t base=0;
4478        UInt_t mask=0;
4479        if(classname.Contains("CalibTrk1Event")){
4480            base=12;
4481            mask=0x03F000;
4482        }
4483        if(classname.Contains("CalibTrk2Event")){
4484            base=18;
4485            mask=0xFC0000;
4486        }
4487    //  -------------------------------------------------
4488    //  Count number of packets and set build variable
4489    //  -------------------------------------------------
4490        Int_t  npkts=0;
4491        for(Int_t ipkt=0; ipkt<6; ipkt++){
4492            if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
4493                npkts++;
4494                build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );
4495            }
4496        }
4497    //    if( npkts==6 )return 1; // :-)
4498    
4499    //    cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime()<<endl;
4500    
4501    //  -----------------------------------------------
4502    //  If missing packets: check the acq configuration
4503    //  (some DSPs might be excluded from acquisition)
4504    //  -----------------------------------------------
4505    
4506    //  -----------------------------------------------
4507    //  retrieve the first run header after calib
4508    //  -----------------------------------------------
4509         PacketType *pctp;
4510         EventCounter *cod;
4511         cod = eh->GetCounter();
4512         Int_t irun = cod->Get(pctp->RunHeader);
4513         TTree *rh=(TTree*)file->Get("RunHeader");
4514         if ( !rh || rh->IsZombie() ) throw -17;
4515         if( rh->GetEntries() == irun ){
4516              if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (1)  -- cannot validate :-( "<<endl;
4517             return 0; // :-(
4518         }
4519    
4520         RunHeaderEvent *run  = 0;
4521         EventHeader    *hrun = 0;
4522         rh->SetBranchAddress("RunHeader", &run);
4523         rh->SetBranchAddress("Header", &hrun);
4524         rh->GetEntry(irun);
4525    //     cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime() << " Run " << hrun->GetPscuHeader()->GetOrbitalTime() <<endl;
4526    
4527         if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){
4528              if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (2) -- cannot validate :-( "<<endl;
4529             return 0; // :-(
4530         }
4531        
4532         if( !run->RM_ACQ_AFTER_CALIB ){
4533              if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) RM_ACQ_AFTER_CALIB=0    -- cannot validate :-( "<<endl;
4534             return 0; // :-(
4535         }
4536    
4537         UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());
4538         if( dtime > timeaftercalib ){
4539             if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;
4540             return 0; // :-(
4541         }
4542        
4543    
4544    
4545         if( (run->ACQ_BUILD_INFO & mask) != build ){
4546             if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) ACQ_BUILD_INFO= >>> "<<hex << (run->ACQ_BUILD_INFO&mask) << " != "<< build << dec<<endl;
4547             return 0; // :-(
4548         }
4549         return 1; // :-)
4550    
4551    }
4552    
4553    /**
4554     *
4555     * Check the DB (only for overlapping runs at the moment)
4556     *
4557     **/
4558    UInt_t PamelaDBOperations::Check(){
4559      //
4560      UInt_t test = 0;
4561      //
4562      UInt_t thisrht = 0;
4563      UInt_t thisrtt = 0;
4564      UInt_t thisid = 0;
4565      UInt_t prevrht = 0;
4566      UInt_t prevrtt = 0;
4567      UInt_t previd = 0;
4568      //
4569      UInt_t prevl0id = 0;
4570      UInt_t thisl0id = 0;
4571      //
4572      stringstream oss;
4573      TSQLResult *result = 0;
4574      TSQLRow    *row    = 0;
4575      TSQLResult *result2 = 0;
4576      TSQLRow    *row2    = 0;
4577      oss.str("");
4578      oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN order by RUNHEADER_TIME asc;";
4579      //  oss << "SELECT ID,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN where ID>10170 and ID<10190 order by RUNHEADER_TIME asc;";
4580      result = conn->Query(oss.str().c_str());
4581      //
4582      if ( !result ) throw -4;;
4583      //
4584      row = result->Next();
4585      //
4586      while ( row ){
4587        thisid = (UInt_t)atoll(row->GetField(0));
4588        thisl0id = (UInt_t)atoll(row->GetField(1));
4589        thisrht = (UInt_t)atoll(row->GetField(2));
4590        thisrtt = (UInt_t)atoll(row->GetField(3));
4591        //
4592        //    if ( thisrht < prevrtt || thisrtt < prevrht || thisrht > thisrtt && !(!prevrht && !prevrtt &&!previd) ){
4593        //    if ( (thisrht < prevrtt || thisrtt < prevrht || thisrht > thisrtt) && (thisrht != prevrht) ){
4594        if ( (thisrht < prevrtt) && (thisrht != prevrht) ){
4595          if ( IsDebug() ) printf(" IDprev %u ID %u    prevrht %u prevrtt %u  thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
4596          printf(" CHECK n.1 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrht-prevrtt),previd,thisid);
4597          TString prevf = "";
4598          TString thisf = "";
4599          oss.str("");
4600          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
4601          result2 = conn->Query(oss.str().c_str());
4602          if ( !result2 ) throw -4;;
4603          row2 = result2->Next();
4604          prevf = (TString)row2->GetField(0);
4605          oss.str("");
4606          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
4607          result2 = conn->Query(oss.str().c_str());
4608          if ( !result2 ) throw -4;;
4609          row2 = result2->Next();
4610          thisf = (TString)row2->GetField(0);
4611          if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
4612          test = 1;
4613        };
4614        //
4615        if ( (thisrtt < prevrht) && (thisrht != prevrht) ){
4616          if ( IsDebug() ) printf(" IDprev %u ID %u    prevrht %u prevrtt %u  thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
4617          printf(" CHECK n.2 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrtt-prevrht),previd,thisid);
4618          TString prevf = "";
4619          TString thisf = "";
4620          oss.str("");
4621          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
4622          result2 = conn->Query(oss.str().c_str());
4623          if ( !result2 ) throw -4;;
4624          row2 = result2->Next();
4625          prevf = (TString)row2->GetField(0);
4626          oss.str("");
4627          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
4628          result2 = conn->Query(oss.str().c_str());
4629          if ( !result2 ) throw -4;;
4630          row2 = result2->Next();
4631          thisf = (TString)row2->GetField(0);
4632          if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
4633          test = 1;
4634        };
4635        //
4636        if ( (thisrht > thisrtt) && (thisrht != prevrht) ){
4637          if ( IsDebug() ) printf(" IDprev %u ID %u    prevrht %u prevrtt %u  thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
4638          printf(" CHECK n.3 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrht-thisrtt),previd,thisid);
4639          TString prevf = "";
4640          TString thisf = "";
4641          oss.str("");
4642          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
4643          result2 = conn->Query(oss.str().c_str());
4644          if ( !result2 ) throw -4;;
4645          row2 = result2->Next();
4646          prevf = (TString)row2->GetField(0);
4647          oss.str("");
4648          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
4649          result2 = conn->Query(oss.str().c_str());
4650          if ( !result2 ) throw -4;;
4651          row2 = result2->Next();
4652          thisf = (TString)row2->GetField(0);
4653          if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
4654          test = 1;
4655        };
4656    
4657        //
4658        prevrht = thisrht;
4659        prevrtt = thisrtt;
4660        previd = thisid;
4661        prevl0id = thisl0id;
4662        row = result->Next();
4663      };
4664      //
4665      return(test);
4666      //
4667  };  };

Legend:
Removed from v.1.1  
changed lines
  Added in v.1.26

  ViewVC Help
Powered by ViewVC 1.1.23