/[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.28 by mocchiut, Wed Feb 14 10:55:00 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, UInt_t dwinput){
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(dwinput);
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(UInt_t dwinput){
219      dworbit = 0;
220      //
221      if ( dwinput ){
222        dworbit = dwinput;
223        if ( IsDebug() ) printf(" Downlink orbit given by hand: %i  \n",dworbit);
224        return;
225      };
226      //
227      TString name = this->GetRootFile();
228      Int_t nlength = name.Length();
229      if ( nlength < 5 ) return;
230      TString dwo = 0;
231      for (Int_t i = 0; i<5; i++){
232        dwo.Append(name[i],1);
233      };
234      if ( dwo.IsDigit() ){
235        dworbit = (UInt_t)dwo.Atoi();
236      } else {
237        dwo="";
238        for (Int_t i = 8; i<13; i++){
239          dwo.Append(name[i],1);
240        };    
241        if ( dwo.IsDigit() ) dworbit = (UInt_t)dwo.Atoi();
242      };
243      if ( IsDebug() ) printf(" Downlink orbit is %i (dwo = %s) \n",dworbit,dwo.Data());
244      return;
245    };
246    
247    
248    
249    /**
250   * Store the NOBOOT flag.   * Store the NOBOOT flag.
251   * @param noboot    true/false.   * @param noboot    true/false.
252   */   */
# Line 170  void PamelaDBOperations::SetNOBOOT(Bool_ Line 255  void PamelaDBOperations::SetNOBOOT(Bool_
255  };  };
256    
257  /**  /**
258     * Store path to the TLE file.
259     */
260    void PamelaDBOperations::SetTLEPath(TString str){
261      tlefilename = str;
262    };
263    
264    /**
265     * Store the olderthan variable
266     * @param olderthan
267     */
268    // void PamelaDBOperations::SetOlderThan(Long64_t oldthan){
269    //   olderthan = oldthan;
270    // };
271    
272    /**
273   * Retrieve the ID_RAW, if exists, returns NULL if does not exist.   * Retrieve the ID_RAW, if exists, returns NULL if does not exist.
274   */   */
275  Bool_t PamelaDBOperations::SetID_RAW(){  Bool_t PamelaDBOperations::SetID_RAW(){
# Line 180  Bool_t PamelaDBOperations::SetID_RAW(){ Line 280  Bool_t PamelaDBOperations::SetID_RAW(){
280    oss << "SELECT ID FROM GL_RAW WHERE "    oss << "SELECT ID FROM GL_RAW WHERE "
281        << " PATH = '" << this->GetRawPath().Data() << "' AND "        << " PATH = '" << this->GetRawPath().Data() << "' AND "
282        << " NAME = '" << this->GetRawFile().Data() << "' ";        << " NAME = '" << this->GetRawFile().Data() << "' ";
283    
284    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
285    if (result == NULL) throw -4;    if ( result == NULL ) throw -4;
286    row = result->Next();    row = result->Next();
287    if (row == NULL) return false;    if ( !row ) return(false);
288    delete result;    delete result;
289    id = (UInt_t)atoll(row->GetField(0));    id = (UInt_t)atoll(row->GetField(0));
290    return(true);    return(true);
# Line 210  Int_t PamelaDBOperations::SetUpperLimits Line 311  Int_t PamelaDBOperations::SetUpperLimits
311    UInt_t nevent = 0;    UInt_t nevent = 0;
312    UInt_t pktlast = 0;    UInt_t pktlast = 0;
313    UInt_t obtlast = 0;    UInt_t obtlast = 0;
314    UInt_t t_pktlast = 0;    Long64_t t_pktlast = 0LL;
315    UInt_t t_obtlast = 0;    //  UInt_t t_obtlast = 0;
316    UInt_t upperpkt2 = 0;    Long64_t t_obtlast = 0LL;
317    ULong64_t upperobt2 = 0;    Long64_t upperpkt2 = 0LL;
318      Long64_t upperobt2 = 0LL;
319    UInt_t zomp = 0;    UInt_t zomp = 0;
320    UInt_t jump = 50000; // was 5000    UInt_t jump = 50000; // was 5000
321      EventCounter *code=0;
322      //
323      Long64_t deltapkt = 5000LL;
324      Long64_t deltaobt = 50000LL;
325      //
326      pcksList packetsNames;
327      pcksList::iterator Iter;
328      getPacketsNames(packetsNames);
329    //    //
330    pktfirst = 0;    pktfirst = 0;
331    obtfirst = 0;    obtfirst = 0;
332      ppktfirst = 0;
333      pobtfirst = 0;
334    //    //
335    TTree *T = 0;    TTree *T = 0;
336    T = (TTree*)file->Get("Physics");    T = (TTree*)file->Get("Physics");
# Line 232  Int_t PamelaDBOperations::SetUpperLimits Line 344  Int_t PamelaDBOperations::SetUpperLimits
344    ph = eh->GetPscuHeader();    ph = eh->GetPscuHeader();
345    pktfirst = ph->GetCounter();    pktfirst = ph->GetCounter();
346    obtfirst = ph->GetOrbitalTime();      obtfirst = ph->GetOrbitalTime();  
347      ppktfirst = pktfirst;
348      pobtfirst = obtfirst;
349      //
350      code = eh->GetCounter();
351      UInt_t en = 0;
352      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
353        en = code->Get(GetPacketType(*Iter));
354        if ( !strcmp("CalibCalPed",*Iter) || !strcmp("CalibTrk1",*Iter) || !strcmp("CalibTrk2",*Iter) || !strcmp("CalibS4",*Iter) ){
355          if ( IsDebug() ) printf(" We have a calibration before the first physic packet: packet type is %s, entries: %i \n",*Iter,en);
356          //
357          TTree *TC = 0;
358          TC = (TTree*)file->Get("CalibCalPed");
359          if ( !TC || TC->IsZombie() ) throw -16;
360          EventHeader *ehc = 0;
361          PscuHeader *phc = 0;
362          TC->SetBranchAddress("Header", &ehc);
363          TC->GetEntry(0);
364          phc = ehc->GetPscuHeader();
365          pktfirst = phc->GetCounter();
366          obtfirst = phc->GetOrbitalTime();  
367          //
368        };
369      };  
370    //    //
371    T->GetEntry(nevent-1);    T->GetEntry(nevent-1);
372    ph = eh->GetPscuHeader();    ph = eh->GetPscuHeader();
# Line 242  Int_t PamelaDBOperations::SetUpperLimits Line 377  Int_t PamelaDBOperations::SetUpperLimits
377    upperobt = OBT(obtlast);    upperobt = OBT(obtlast);
378    upperentry = nevent-1;    upperentry = nevent-1;
379    //    //
380    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);
381    //    //
382    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);
383    //    //
384    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);
385    //    //
386    if ( !nevent ) return(2);    if ( !nevent ) return(2);
387    //    //
388    if ( nevent < 2 ) return(4);    if ( nevent < 2 ) return(4);
389      if ( nevent < jump ) jump = 1;
390      //  if ( nevent < jump ) jump = int(nevent/10);
391      //  if ( !jump ) jump = 1;
392    //    //
393    if ( PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst) ){    if ( (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) || (labs(PKT(pktlast)-PKT(pktfirst))<deltapkt && labs(OBT(obtlast)-OBT(obtfirst))<deltaobt) && nevent > deltapkt ){
394        //
395        if ( IsDebug() ) printf(" starting jump %i \n",jump);
396      // go back      // go back
397      zomp = nevent - 2;      zomp = nevent - 2;
398      //      //
# Line 274  Int_t PamelaDBOperations::SetUpperLimits Line 414  Int_t PamelaDBOperations::SetUpperLimits
414          upperpkt2 = PKT(ph->GetCounter());          upperpkt2 = PKT(ph->GetCounter());
415          upperobt2 = OBT(ph->GetOrbitalTime());          upperobt2 = OBT(ph->GetOrbitalTime());
416          //          //
417          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) ){
418              if ( IsDebug() ) printf(" .-. upperpkt2 %lld upperobt2 %lld \n",upperpkt2,upperobt2);  
419              if ( IsDebug() ) printf(" .-. upperpkt %lld t_pktlast %lld upperobt %lld t_obtlast %lld \n",upperpkt,t_pktlast,upperobt,t_obtlast);    
420              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);    
421              throw -13;    
422            };
423          //          //
424          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 ){
425            zomp = i + jump + 1;            zomp = i + jump + 1;
426            if ( zomp > nevent-2 ) zomp = nevent - 2;            if ( zomp > nevent-2 ) zomp = nevent - 2;
427            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);
428            break;            break;
429          };          };
430          //          //
# Line 301  Int_t PamelaDBOperations::SetUpperLimits Line 446  Int_t PamelaDBOperations::SetUpperLimits
446    // 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)
447    //    //
448    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);  
449    TTree *rh=(TTree*)file->Get("RunHeader");    TTree *rh=(TTree*)file->Get("RunHeader");
450    if ( !rh || rh->IsZombie() ) throw -17;    if ( !rh || rh->IsZombie() ) throw -17;
451    TTree *rt=(TTree*)file->Get("RunTrailer");    TTree *rt=(TTree*)file->Get("RunTrailer");
# Line 319  Int_t PamelaDBOperations::SetUpperLimits Line 459  Int_t PamelaDBOperations::SetUpperLimits
459    //    //
460    rhev = rh->GetEntries();    rhev = rh->GetEntries();
461    rtev = rt->GetEntries();    rtev = rt->GetEntries();
462    UInt_t pktt = 0;    Long64_t sobtt = 0LL;
463    ULong64_t obtt = 0;    Long64_t sobth = 0LL;
464    UInt_t pkth = 0;    Long64_t spktt = 0LL;
465    ULong64_t obth = 0;    Long64_t spkth = 0LL;
466      Long64_t pktt = 0LL;
467      Long64_t obtt = 0LL;
468      Long64_t pkth = 0LL;
469      Long64_t obth = 0LL;
470    //    //
471    if ( lasttrail < rtev ){    if ( rhev || rtev ){
472      rt->GetEntry(lasttrail);  
473      pht = eht->GetPscuHeader();      T->GetEntry(upperentry);
474      pktt = PKT(pht->GetCounter());      code = eh->GetCounter();
475      obtt = OBT(pht->GetOrbitalTime());      Int_t lasttrail = code->Get(pctp->RunTrailer);
476        Int_t lasthead = code->Get(pctp->RunHeader);
477        if ( lasttrail < rtev ){
478          rt->GetEntry(lasttrail);
479          pht = eht->GetPscuHeader();
480          pktt = PKT(pht->GetCounter());
481          obtt = OBT(pht->GetOrbitalTime());
482        };
483        //
484        if ( lasthead < rhev ){
485          rh->GetEntry(lasthead);
486          phh = ehh->GetPscuHeader();
487          pkth = PKT(phh->GetCounter());
488          obth = OBT(phh->GetOrbitalTime());
489        };
490        //
491        if ( IsDebug() ) printf(" rhev before %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
492        if ( pkth > upperpkt && obth > upperobt ){
493          if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %lld upperp %lld oh %lld uppero %lld \n",pkth,upperpkt,obth,upperobt);
494          upperpkt = pkth;
495          upperobt = obth;
496          rhev = lasthead+1;
497        } else {
498          rhev = lasthead;
499        };
500        if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
501        //
502        if ( IsDebug() ) printf(" rtev beforev %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
503        if ( pktt > upperpkt && obtt > upperobt ){
504          if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %lld upperp %lld ot %lld uppero %lld \n",pktt,upperpkt,obtt,upperobt);
505          upperpkt = pktt;
506          upperobt = obtt;
507          rtev = lasttrail+1;
508        } else {
509          rtev = lasttrail;
510        };
511        if ( IsDebug() ) printf(" rtev after %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
512        //  goto kikko;
513        //
514        //
515        // Check if runtrailer/runheader are within lower limits
516        //
517        //
518        pkth = 0LL;
519        obth = 0LL;
520        spkth = 0LL;
521        sobth = 0LL;
522        for (Int_t k=0; k<rhev; k++){
523          if ( k > 0 ){
524            spkth = pkth;
525            sobth = obth;
526          };
527          rh->GetEntry(k);
528          phh = ehh->GetPscuHeader();
529          pkth = PKT(phh->GetCounter());
530          obth = OBT(phh->GetOrbitalTime());
531          //
532          //    if ( IsDebug() ) printf(" k %i rhev before %i ph %u upperp %u oh %u uppero %u \n",k,rhev,pkth,spkth,obth,sobth);
533          //
534          if ( pkth < spkth && obth < sobth ){
535            if ( IsDebug() ) printf(" RH PROBLEMS determining the event repetition at the end of the file lasthead %i  \n",rhev);
536            //
537            rhev = k-1;
538            rh->GetEntry(rhev);
539            pkth = spkth;
540            obth = sobth;
541            //
542            UInt_t evbefh = 0;
543            code = ehh->GetCounter();
544            evbefh = code->Get(pctp->Physics);    
545            if ( evbefh >= 0 ){
546              T->GetEntry(evbefh);
547              ph = eh->GetPscuHeader();
548              t_pktlast = PKT(ph->GetCounter());
549              t_obtlast = OBT(ph->GetOrbitalTime());
550              if ( t_pktlast <= spkth && t_obtlast <= sobth ){ // jump
551                upperpkt = pkth;
552                upperobt = obth;
553                upperentry = evbefh-1;
554              } else {
555                while ( t_pktlast > spkth && t_obtlast > sobth && evbefh < nevent ){
556                  evbefh++;
557                  T->GetEntry(evbefh);
558                  ph = eh->GetPscuHeader();
559                  t_pktlast = PKT(ph->GetCounter());
560                  t_obtlast = OBT(ph->GetOrbitalTime());
561                };
562                T->GetEntry(evbefh-1);
563                ph = eh->GetPscuHeader();
564                upperpkt = PKT(ph->GetCounter());
565                upperobt = OBT(ph->GetOrbitalTime());
566                upperentry = evbefh-1;
567              };    
568            };
569            if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
570            goto kikko0;
571          };
572        };
573      kikko0:
574        //
575        //
576        //
577        pktt = 0LL;
578        obtt = 0LL;
579        spktt = 0LL;
580        sobtt = 0LL;
581        for (Int_t k=0; k<rtev; k++){
582          if ( k > 0 ){
583            spktt = pktt;
584            sobtt = obtt;
585          };
586          rt->GetEntry(k);
587          pht = eht->GetPscuHeader();
588          pktt = PKT(pht->GetCounter());
589          obtt = OBT(pht->GetOrbitalTime());
590          //
591          //    if ( IsDebug() ) printf(" k %i rtev beforev %i  pt %i upperp %i ot %llu uppero %llu \n",k,rtev,pktt,spktt,obtt,sobtt);
592          //
593          if ( pktt < spktt && obtt < sobtt ){
594            if ( IsDebug() ) printf(" RT PROBLEMS determining the event repetition at the end of the file lasttrail %i \n",rtev);
595            //
596            rtev = k-1;
597            rt->GetEntry(rtev);
598            pktt = spktt;
599            obtt = sobtt;
600            if ( IsDebug() ) printf(" lasttrail %i pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
601            //
602            UInt_t evbeft = 0;
603            code = eht->GetCounter();
604            evbeft = code->Get(pctp->Physics);    
605            if ( evbeft >= 0 ){
606              T->GetEntry(evbeft);
607              ph = eh->GetPscuHeader();
608              t_pktlast = PKT(ph->GetCounter());
609              t_obtlast = OBT(ph->GetOrbitalTime());
610              if ( t_pktlast <= spktt && t_obtlast <= sobtt ){ // jump
611                upperpkt = pktt;
612                upperobt = obtt;
613                upperentry = evbeft-1;
614              } else {
615                while ( t_pktlast > spktt && t_obtlast > sobtt && evbeft < nevent ){
616                  evbeft++;
617                  T->GetEntry(evbeft);
618                  ph = eh->GetPscuHeader();
619                  t_pktlast = PKT(ph->GetCounter());
620                  t_obtlast = OBT(ph->GetOrbitalTime());
621                };
622                T->GetEntry(evbeft-1);
623                ph = eh->GetPscuHeader();
624                upperpkt = PKT(ph->GetCounter());
625                upperobt = OBT(ph->GetOrbitalTime());
626                upperentry = evbeft-1;
627              };
628            };
629            if ( IsDebug() ) printf(" rtev after %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
630            goto kikko;
631            //      break;
632            //
633          };
634          //  
635        };
636        //
637      kikko:
638        //
639        T->GetEntry(upperentry);
640        code = eh->GetCounter();
641        lasttrail = code->Get(pctp->RunTrailer);
642        lasthead = code->Get(pctp->RunHeader);
643        if ( lasttrail < rtev ){
644          rt->GetEntry(lasttrail);
645          pht = eht->GetPscuHeader();
646          pktt = PKT(pht->GetCounter());
647          obtt = OBT(pht->GetOrbitalTime());
648        };
649        //
650        if ( lasthead < rhev ){
651          rh->GetEntry(lasthead);
652          phh = ehh->GetPscuHeader();
653          pkth = PKT(phh->GetCounter());
654          obth = OBT(phh->GetOrbitalTime());
655        };
656        //
657        if ( IsDebug() ) printf(" rhev before %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
658        if ( pkth > upperpkt && obth > upperobt ){
659          if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %lld upperp %lld oh %lld uppero %lld \n",pkth,upperpkt,obth,upperobt);
660          upperpkt = pkth;
661          upperobt = obth;
662          rhev = lasthead+1;
663        } else {
664          rhev = lasthead;
665        };
666        if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
667        //
668        if ( IsDebug() ) printf(" rtev beforev %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
669        if ( pktt > upperpkt && obtt > upperobt ){
670          if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %lld upperp %lld ot %lld uppero %lld \n",pktt,upperpkt,obtt,upperobt);
671          upperpkt = pktt;
672          upperobt = obtt;
673          rtev = lasttrail+1;
674        } else {
675          rtev = lasttrail;
676        };
677        if ( IsDebug() ) printf(" rtev after %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
678        //
679    };    };
680    //    //
681    if ( IsDebug() ) printf(" rtev beforev %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);    if ( IsDebug() ) printf(" Upper limits are: OBT %lld pkt_num %lld upper entry %i \n",upperobt,upperpkt,upperentry);
   if ( pktt > upperpkt && obtt > upperobt ){  
     if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %i upperp %i ot %llu uppero %llu \n",pktt,upperpkt,obtt,upperobt);  
     upperpkt = pktt;  
     upperobt = obtt;  
     rtev = lasttrail+1;  
   } else {  
     rtev = lasttrail;  
   };  
   if ( IsDebug() ) printf(" rtev after %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);  
682    //    //
683    if ( lasthead < rhev ){    return(0);
684      rh->GetEntry(lasthead);  }
685      phh = ehh->GetPscuHeader();  
686      pkth = PKT(pht->GetCounter());  /**
687      obth = OBT(pht->GetOrbitalTime());   *
688    };   * Trick to have unique RUN ID numbers even when runs are deleted and mysql deamon restarted.
689     * Entries in the _RUNID_GEN table are never deleted.
690     *
691     **/
692    UInt_t PamelaDBOperations::AssignRunID(){
693    //    //
694    if ( IsDebug() ) printf(" rhev before %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);    TSQLResult *result = 0;
695    if ( pkth > upperpkt && obth > upperobt ){    TSQLRow *row = 0;
696      if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %i upperp %i oh %llu uppero %llu \n",pkth,upperpkt,obth,upperobt);    UInt_t runid = 0;
697      upperpkt = pkth;    //
698      upperobt = obth;    stringstream   oss;
699      rhev = lasthead+1;    //  
700    } else {    oss.str("");
701      rhev = lasthead;    oss << "INSERT INTO _RUNID_GEN VALUES (NULL);";
702    };    result = conn->Query(oss.str().c_str());
703    if ( IsDebug() ) printf(" rhev after %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);    if ( !result ) throw -10;
704      oss.str("");
705      oss << "SELECT ID FROM _RUNID_GEN ORDER BY ID DESC LIMIT 1;";
706      result = conn->Query(oss.str().c_str());
707      if ( !result ) throw -10;
708    //    //
709    if ( IsDebug() ) printf(" Upper limits are: OBT %llu pkt_num %i upper entry %i \n",upperobt,upperpkt,upperentry);    row = result->Next();
710    //    //
711    return(0);    if ( !row ) throw -28;
712  }    //
713      runid = (UInt_t)atoll(row->GetField(0));
714      //
715      return(runid);
716    };
717    
718  //  //
719  // GETTERS  // GETTERS
# Line 440  const PacketType* PamelaDBOperations::Ge Line 790  const PacketType* PamelaDBOperations::Ge
790  // PRIVATE FUNCTIONS  // PRIVATE FUNCTIONS
791  //  //
792    
793  /**  // /**
794   * Open the ROOT filename for reading  // * Open the ROOT filename for reading
795   */  // */
796  void PamelaDBOperations::OpenFile(){  // void PamelaDBOperations::OpenFile(){
797    file = TFile::Open(this->GetRootName().Data());  //   file = TFile::Open(this->GetRootName().Data());
798    //   //
799    
800    void PamelaDBOperations::CheckFile(){  
801      if ( !file ) throw -12;
802  };  };
803    
804    
805  /**  /**
806   * Check if LEVEL0 file and DB connection have really be opened   * Check if LEVEL0 file and DB connection have really be opened
807   */   */
808  void PamelaDBOperations::CheckFile(){    void PamelaDBOperations::CheckConnection(){  
   //  
   if ( !file ) throw -12;  
809    //    //
810    // check connection    // check connection
811    //    //
812    if( !conn ) throw -1;        if( !conn ) throw -1;
813    bool connect = conn->IsConnected();    bool connect = conn->IsConnected();
814    if( !connect ) throw -1;        if( !connect ) throw -1;
815      //
816      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());
817      //
818      if ( !dworbit && strcmp(this->GetRootName().Data(),"") ) throw -27;
819      //
820      // set DB timezone to UTC
821      //
822      stringstream oss;
823      //  
824      oss.str("");
825      oss << "SET time_zone='+0:00';";
826      TSQLResult *result = 0;
827      result = conn->Query(oss.str().c_str());
828      if ( !result ) throw -10;
829      oss.str("");
830      oss << "SET wait_timeout=173000;";
831      conn->Query(oss.str().c_str());
832      //
833  };  };
834    
835  /**  /**
836   * Return the correct packet number if we went back to zero   * Return the correct packet number if we went back to zero
837   */   */
838  UInt_t PamelaDBOperations::PKT(UInt_t pkt_num){    Long64_t PamelaDBOperations::PKT(UInt_t pkt_num){  
839    //    //
840    //  if ( IsDebug() ) printf(" pkt conversion: pkt_num is %u pktfirst is %u (pktfirst - (UInt_t)(16777212/2)) is %u  \n",pkt_num,pktfirst,(pktfirst - (UInt_t)(16777212/2)));    if ( IsDebug() ) printf(" pkt conversion: pkt_num is %u pktfirst is %u  (UInt_t)(16777214/2)) is %u  \n",pkt_num,ppktfirst,(UInt_t)(16777214/2));
841    //    //
842    if ( pkt_num < (pktfirst/2) && pktfirst > (16777214/2)  ) return((pkt_num+16777215));    if ( pkt_num < (ppktfirst/2) && ppktfirst > (16777214/2)  ){
843        if ( IsDebug() ) printf(" rise up pktnum %lld \n",(Long64_t)pkt_num+16777215LL);
844        return((Long64_t)pkt_num+16777215LL);
845      };
846    //    //
847    if ( pkt_num > pktfirst*2 && pkt_num > (16777214/2) ){    if ( pkt_num > ppktfirst*2 && pkt_num > (16777214/2) ){
848      if ( (pkt_num-16777215) < 0 ){      if ( IsDebug() ) printf(" rise down pktnum %lld \n",(Long64_t)pkt_num-16777215LL);
849        return((16777215-pkt_num));      return((Long64_t)pkt_num-16777215LL);
     } else {  
       return((pkt_num-16777215));  
     };  
850    };    };
851    //    //
852    return(pkt_num);    if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)pkt_num);
853      return((Long64_t)pkt_num);
854    //    //
855  };  };
856    
857  /**  /**
858   * Return the correct On Board Time if we went back to zero   * Return the correct On Board Time if we went back to zero
859   */   */
860  ULong64_t PamelaDBOperations::OBT(UInt_t obt){    Long64_t PamelaDBOperations::OBT(UInt_t obt){  
861    //    //
862    if ( obt < (obtfirst/2) && obtfirst > (numeric_limits<UInt_t>::max()/2) ) return((ULong64_t)(obt+numeric_limits<UInt_t>::max()));    if ( obt < (pobtfirst/2) && pobtfirst > (numeric_limits<UInt_t>::max()/2) ) return((Long64_t)(obt+numeric_limits<UInt_t>::max()));
863    //    //
864    if ( obt > (obtfirst*2) && obt > (numeric_limits<UInt_t>::max()/2) ){    if ( obt > (pobtfirst*2) && obt > (numeric_limits<UInt_t>::max()/2) ){
865      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()));  
     };  
866    };    };
867    //    //
868    return((ULong64_t)obt);    return((Long64_t)obt);
869  };  };
870    
871  /**  /**
# Line 550  void PamelaDBOperations::FillClass(Bool_ Line 917  void PamelaDBOperations::FillClass(Bool_
917      lastPkt = glrun->GetRUNTRAILER_PKT();      lastPkt = glrun->GetRUNTRAILER_PKT();
918    };    };
919    //    //
920    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
921    //    //
922    if ( mishead ) {    if ( mishead ) {
923      glrun->Set_GL_RUNH0();      glrun->Set_GL_RUNH0();
# Line 639  Int_t PamelaDBOperations::insertPamelaGL Line 1006  Int_t PamelaDBOperations::insertPamelaGL
1006    if ( this->GetID_RAW() == 0 )  throw -11;    if ( this->GetID_RAW() == 0 )  throw -11;
1007    //    //
1008    oss.str("");    oss.str("");
1009    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='"
1010        << id << " AND TO_ID_RAW >= "        << this->GetRawFile().Data() << "';";
       << id << ";";  
1011    if ( IsDebug() ) printf(" %s \n",oss.str().c_str());    if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
1012    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1013    if ( !result ) throw -10;    if ( !result ) throw -10;
1014    row = result->Next();    row = result->Next();
   if ( !row ) throw -10;  
1015    //    //
1016    t0 = (UInt_t)TDatime(row->GetField(0)).Convert();    if ( !row ){
1017        oss.str("");
1018        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< "
1019            << dworbit << " order by FROM_ORBIT desc limit 1;";
1020        if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
1021        result = conn->Query(oss.str().c_str());
1022        if ( !result ) throw -10;
1023        row = result->Next();
1024        if ( !row ) throw -10;
1025      };
1026      //
1027      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);
1028      t0 = (UInt_t)tu.GetSec();
1029      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));
1030      //
1031    /*    /*
1032     * Verify that the TIMESYNC have been not already processed     * Verify that the TIMESYNC have been not already processed
1033     */     */
# Line 663  Int_t PamelaDBOperations::insertPamelaGL Line 1042  Int_t PamelaDBOperations::insertPamelaGL
1042    if (result == NULL) throw -10;    if (result == NULL) throw -10;
1043    row = result->Next();    row = result->Next();
1044    if ((row != NULL) && ((UInt_t)atoll(row->GetField(0)) > 0)){    if ((row != NULL) && ((UInt_t)atoll(row->GetField(0)) > 0)){
1045        if ( IsDebug() ) printf(" found a timesync t0 is %u \n",t0);
1046      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;
1047        //
1048        tsync = (UInt_t)atoll(row->GetField(2));
1049        obt0 = (UInt_t)atoll(row->GetField(1));
1050        //
1051      return(1);      return(1);
1052    };    };
1053    //    //
1054    TTree *T = 0;    TTree *T = 0;
1055      Int_t signal = 0;
1056    //    //
1057    UInt_t nevent = 0;    UInt_t nevent = 0;
1058    UInt_t recEntries = 0;    UInt_t recEntries = 0;
# Line 719  Int_t PamelaDBOperations::insertPamelaGL Line 1104  Int_t PamelaDBOperations::insertPamelaGL
1104          //          //
1105          TYPE = 55;//224;          TYPE = 55;//224;
1106          //          //
1107            if ( IsDebug() ) printf("mcmd tsync %i tsync %u obt %u \n",i,TSYNC,OBT);
1108            //
1109          if ( TSYNC && OBT ){          if ( TSYNC && OBT ){
1110            existsts = true;            existsts = true;
1111            goto out;            goto eout;
1112          };          };
1113          //          //
1114        };        };
# Line 729  Int_t PamelaDBOperations::insertPamelaGL Line 1116  Int_t PamelaDBOperations::insertPamelaGL
1116    };    };
1117    if ( !existsts ) { // try with runheader and runtrailer    if ( !existsts ) { // try with runheader and runtrailer
1118      //      //
1119        if ( IsDebug() ) printf(" No ts mcmd \n");
1120        signal = 2;
1121        //
1122      TTree *rh=(TTree*)file->Get("RunHeader");      TTree *rh=(TTree*)file->Get("RunHeader");
1123      if ( !rh || rh->IsZombie() ) throw -17;      if ( !rh || rh->IsZombie() ) throw -17;
1124      TTree *rt=(TTree*)file->Get("RunTrailer");      TTree *rt=(TTree*)file->Get("RunTrailer");
# Line 738  Int_t PamelaDBOperations::insertPamelaGL Line 1128  Int_t PamelaDBOperations::insertPamelaGL
1128      //      //
1129      rt->SetBranchAddress("RunTrailer", &runt);      rt->SetBranchAddress("RunTrailer", &runt);
1130      //      //
1131      //    Int_t rhev = rh->GetEntries();      Int_t nrhev = rh->GetEntries();
1132      //    Int_t rtev = rt->GetEntries();      Int_t nrtev = rt->GetEntries();
1133        if ( IsDebug() ) printf(" ou nevent %i rhev %i rtev %i \n",nevent,nrhev,nrtev);
1134      //      //
1135      if ( rhev > 0 ){      if ( nrhev > 0 ){
1136        rh->GetEntry(0);        for (Int_t i=0; i<nrhev; i++){
1137        //          //
1138        TSYNC = runh->LAST_TIME_SYNC_INFO;          rh->GetEntry(i);
1139        OBT = runh->OBT_TIME_SYNC * 1000;          //
1140        //          TSYNC = runh->LAST_TIME_SYNC_INFO;
1141        TYPE = 20;          OBT = runh->OBT_TIME_SYNC * 1000;
1142        //          //
1143        if ( TSYNC && OBT ){          TYPE = 20;
1144          existsts = true;          //
1145          goto out;          if ( IsDebug() ) printf("runheader %i tsync %u obt %u \n",i,TSYNC,OBT);
1146            //
1147            if ( TSYNC && OBT ){
1148              existsts = true;
1149              goto eout;
1150            };
1151        };        };
1152        //        //
1153      };      };
1154      if ( rtev > 0 ){      if ( nrtev > 0 ){
       rt->GetEntry(0);  
1155        //        //
1156        TSYNC = runt->LAST_TYME_SYNC_INFO;        if ( IsDebug() ) printf(" No runheader \n");
1157        OBT = runt->OBT_TYME_SYNC * 1000;        signal = 6;
1158        //        //
1159        TYPE = 21;        for (Int_t i=0; i<nrtev; i++){
1160        //          //
1161        if ( TSYNC && OBT ){          rt->GetEntry(i);
1162          existsts = true;          //
1163          goto out;          TSYNC = runt->LAST_TYME_SYNC_INFO;
1164            OBT = runt->OBT_TYME_SYNC * 1000;
1165            //
1166            TYPE = 21;
1167            //
1168            if ( IsDebug() ) printf("runtrailer %i tsync %u obt %u \n",i,TSYNC,OBT);
1169            //
1170            if ( TSYNC && OBT ){
1171              existsts = true;
1172              goto eout;
1173            };
1174        };        };
1175        //        //
1176        } else {
1177          if ( IsDebug() ) printf(" No runheader \n");
1178      };      };
1179    };    };
1180    //    //
1181    if ( !existsts ){ // try with inclination mcmd    if ( !existsts ){ // try with inclination mcmd
1182        //
1183        if ( IsDebug() ) printf(" No runtrailer \n");
1184        signal = 14;
1185        //
1186      Double_t timesync = 0.;      Double_t timesync = 0.;
1187      for (UInt_t i=0; i<nevent;i++){      for (UInt_t i=0; i<nevent;i++){
1188        //        //
# Line 800  Int_t PamelaDBOperations::insertPamelaGL Line 1211  Int_t PamelaDBOperations::insertPamelaGL
1211        TYPE = 666;        TYPE = 666;
1212        if ( TSYNC && OBT ){        if ( TSYNC && OBT ){
1213          existsts = true;          existsts = true;
1214          goto out;          goto eout;
1215        };        };
1216      };      };
1217    };    };
1218    //    //
1219    if ( !existsts && obt0 ){ // insert timesync by hand    if ( !existsts && obt0 ){ // insert timesync by hand
1220        //
1221        if ( IsDebug() ) printf(" No incl mcmd \n");
1222        signal = 30;
1223        //
1224      OBT = obt0;      OBT = obt0;
1225      TSYNC = tsync;      TSYNC = tsync;
1226      TYPE = 999;      TYPE = 999;
1227      existsts = true;      existsts = true;
1228      goto out;      goto eout;
1229    };    };
1230    //    //
1231   out:   eout:
1232    //    //
1233    if ( !existsts ) throw -3;    if ( !existsts ) throw -3;
1234    //    //
# Line 826  Int_t PamelaDBOperations::insertPamelaGL Line 1241  Int_t PamelaDBOperations::insertPamelaGL
1241    conn->Query(oss.str().c_str());    conn->Query(oss.str().c_str());
1242    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());
1243    //    //
1244      if ( IsDebug() ) printf(" found a timesync t0 is %u \n",t0);
1245    toffset = (UInt_t)TSYNC - (UInt_t)(this->OBT(OBT)/1000) + t0;    toffset = (UInt_t)TSYNC - (UInt_t)(this->OBT(OBT)/1000) + t0;
1246    //    //
1247      tsync = TSYNC;
1248      obt0 = OBT;
1249      //
1250    delete result;    delete result;
1251    return(0);    return(signal);
1252  }  }
1253    
1254  /**  /**
# Line 907  Int_t PamelaDBOperations::assignBOOT_NUM Line 1326  Int_t PamelaDBOperations::assignBOOT_NUM
1326        << " NAME = '" << this->GetRawFile().Data() << "' ";        << " NAME = '" << this->GetRawFile().Data() << "' ";
1327    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1328    //    //
1329    if ( !result ) return(8);    if ( !result ) throw -4;;
1330    row = result->Next();    row = result->Next();
1331    if ( !row ) return(16);    if ( !row ) return(16);
1332    if ( row->GetField(1) ){    if ( row->GetField(1) ){
1333      this->SetBOOTnumber((UInt_t)atoll(row->GetField(1)));      this->SetBOOTnumber((UInt_t)atoll(row->GetField(1)));
1334      return(1);      return(1);
1335    };    };
1336    if ( !row->GetField(0) ) return(8);    if ( !row->GetField(0) ) throw -26;
1337    //    //
1338    UInt_t idRaw = (UInt_t)atoll(row->GetField(0));    UInt_t idRaw = (UInt_t)atoll(row->GetField(0));
1339    //    //
# Line 924  Int_t PamelaDBOperations::assignBOOT_NUM Line 1343  Int_t PamelaDBOperations::assignBOOT_NUM
1343    trDumpEv = (TTree*)file->Get("VarDump");    trDumpEv = (TTree*)file->Get("VarDump");
1344    if ( !trDumpEv || trDumpEv->IsZombie() ) throw -20;    if ( !trDumpEv || trDumpEv->IsZombie() ) throw -20;
1345    //    //
   if (trDumpEv == NULL) return(2);  
   //      
1346    VarDumpEvent  *vde = 0;    VarDumpEvent  *vde = 0;
1347    VarDumpRecord *vdr = 0;    VarDumpRecord *vdr = 0;
1348    //    //
1349      Bool_t found = false;
1350    trDumpEv->SetBranchAddress("VarDump", &vde);    trDumpEv->SetBranchAddress("VarDump", &vde);
1351    if (trDumpEv->GetEntries() > 0){    if ( trDumpEv->GetEntries() > 0 ){
1352      trDumpEv->GetEntry(0);      found = false;
1353      vde->Records->GetEntries();      for ( Int_t i = 0; i < trDumpEv->GetEntries(); i++){
1354      if ( !vde->Records->GetEntries() ){        trDumpEv->GetEntry(i);
1355        if ( !this->GetBOOTnumber() ) return(4);        //      vde->Records->GetEntries();
1356      } else {        if ( vde->Records->GetEntries()>5 ){
1357            found = true;
1358            goto fill;
1359          };
1360        };
1361      fill:
1362        if ( found ){
1363          //
1364        vdr = (VarDumpRecord*)vde->Records->At(6);        vdr = (VarDumpRecord*)vde->Records->At(6);
1365          //
1366        this->SetBOOTnumber((Int_t)vdr->VAR_VALUE);        this->SetBOOTnumber((Int_t)vdr->VAR_VALUE);
1367          //
1368        } else {
1369          if ( !this->GetBOOTnumber() && !this->AutoBoot()) return(4);
1370        };
1371      } else {
1372        if ( !this->GetBOOTnumber() && !this->AutoBoot()) return(2);
1373      };
1374      //
1375      UInt_t bn = 0;
1376      Bool_t afound = false;
1377      if ( !found && this->AutoBoot()){
1378        afound = true;
1379        //
1380        // Search for other files with similar timesync
1381        //
1382        if ( IsDebug() ) printf(" tsync %u obt0 %u \n",tsync,obt0);
1383        UInt_t upperts = tsync-(obt0/1000)+5;
1384        UInt_t lowerts = tsync-(obt0/1000)-5;
1385        oss.str("");
1386        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)<"
1387            << upperts
1388            << " AND TIMESYNC-(OBT0/1000)>"
1389            << lowerts
1390            << " AND GL_RAW.BOOT_NUMBER>0 GROUP BY GL_TIMESYNC.OBT0;";
1391        result = conn->Query(oss.str().c_str());
1392        if ( IsDebug() ) printf(" Query the GL_TIMESYNC table to find boot number:\n %s \n",oss.str().c_str());
1393        //
1394        if ( !result ) throw -4;;
1395        found = true;
1396        if ( result->GetRowCount()<3 ){
1397          if ( IsDebug() ) printf(" AGH! no results!\n");
1398          found = false;
1399        } else {
1400          row = result->Next();      
1401          bn = (UInt_t)atoll(row->GetField(0));
1402          for ( Int_t r=1; r<result->GetRowCount() ;r++){
1403            if ( !row ) throw -4;
1404            if ( IsDebug() ) printf(" BOOT number is %s \n",row->GetField(0));
1405            if ( bn != (UInt_t)atoll(row->GetField(0)) ){
1406              if ( IsDebug() ) printf(" AGH! bn = %u here instead %u \n",bn,(UInt_t)atoll(row->GetField(0)));
1407              found = false;
1408            };
1409            row = result->Next();
1410          };
1411      };      };
1412      };
1413      //
1414      Int_t sgn = 0;
1415      //
1416      if ( !found && !BOOTNO ){
1417        throw -29;
1418    } else {    } else {
1419      if ( !this->GetBOOTnumber() ) return(2);      if ( afound ){
1420          this->SetBOOTnumber(bn);
1421          sgn = 8;
1422        };
1423    };    };
1424    //    //
1425    oss.str("");    oss.str("");
# Line 950  Int_t PamelaDBOperations::assignBOOT_NUM Line 1429  Int_t PamelaDBOperations::assignBOOT_NUM
1429    conn->Query(oss.str().c_str());          conn->Query(oss.str().c_str());      
1430    //    //
1431    delete result;    delete result;
1432    return(0);    return(sgn);
1433  };  };
1434    
1435  /**  /**
# Line 1023  Int_t PamelaDBOperations::insertPamelaRU Line 1502  Int_t PamelaDBOperations::insertPamelaRU
1502          //          //
1503          if ( IsDebug() ) printf(" Missing header %i %i %i\n",ptht,pth,ptt);          if ( IsDebug() ) printf(" Missing header %i %i %i\n",ptht,pth,ptt);
1504          //          //
1505          if ( (ptt-1) < 0 ) throw -15;          if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
1506          rt->GetEntry(ptt-1);          rt->GetEntry(ptt-1);
1507          cod = eht->GetCounter();          cod = eht->GetCounter();
1508          evbefh = cod->Get(pctp->Physics);          evbefh = cod->Get(pctp->Physics);
# Line 1129  Int_t PamelaDBOperations::insertPamelaRU Line 1608  Int_t PamelaDBOperations::insertPamelaRU
1608            if ( (UInt_t)evbeft < upperentry-1 ){            if ( (UInt_t)evbeft < upperentry-1 ){
1609              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");
1610              //              //
1611              if ( (ptt-1) < 0 ) throw -15;              if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
1612              rt->GetEntry(ptt-1);              rt->GetEntry(ptt-1);
1613              cod = eht->GetCounter();              cod = eht->GetCounter();
1614              evbefh = cod->Get(pctp->Physics);              evbefh = cod->Get(pctp->Physics);
# Line 1213  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1692  Bool_t PamelaDBOperations::IsRunAlreadyI
1692      if ( glrun->GetNEVENTS() > (UInt_t)atoll(row->GetField(1)) ){      if ( glrun->GetNEVENTS() > (UInt_t)atoll(row->GetField(1)) ){
1693        //        //
1694        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");
1695        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1696        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1697        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) <<";";
1698        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1699    //       conn->Query(oss.str().c_str());
1700        if ( signal ) signal = false;        if ( signal ) signal = false;
1701        goto gonext;              goto gonext;      
1702        //        //
# Line 1230  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1710  Bool_t PamelaDBOperations::IsRunAlreadyI
1710        //        //
1711        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");
1712        //        //
1713        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1714        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1715        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) <<";";
1716        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1717    //       conn->Query(oss.str().c_str());
1718        //        //
1719        if ( signal ) signal = false;        if ( signal ) signal = false;
1720        goto gonext;        goto gonext;
# Line 1247  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1728  Bool_t PamelaDBOperations::IsRunAlreadyI
1728        //        //
1729        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");
1730        //        //
1731        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1732        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1733        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) <<";";
1734        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1735    //       conn->Query(oss.str().c_str());
1736        if ( signal ) signal = false;        if ( signal ) signal = false;
1737        //        //
1738      };      };
# Line 1265  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1747  Bool_t PamelaDBOperations::IsRunAlreadyI
1747    delete result;    delete result;
1748    //    //
1749    if ( signal && IsDebug() ) printf(" The run has already been inserted \n");        if ( signal && IsDebug() ) printf(" The run has already been inserted \n");    
1750      if ( !signal && IsDebug() ) printf(" The run existed and was deleted, fill the DB \n");
1751    return(signal);    return(signal);
1752  };  };
1753    
# Line 1286  void PamelaDBOperations::HandleRun(){   Line 1769  void PamelaDBOperations::HandleRun(){  
1769      //      //
1770      this->FillClass();      this->FillClass();
1771      //      //
1772      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);      if ( !IsRunAlreadyInserted() ){
1773          glrun->SetID(this->AssignRunID());
1774          glrun->SetID_RUN_FRAG(0);
1775          glrun->Fill_GL_RUN(conn);
1776        };
1777    } else {    } else {
1778      //      //
1779      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 1796  void PamelaDBOperations::HandleRunFragme
1796    UInt_t rhfirstev = firstev;    UInt_t rhfirstev = firstev;
1797    UInt_t rtlastev = lastev;    UInt_t rtlastev = lastev;
1798    Bool_t found = false;    Bool_t found = false;
1799      Bool_t foundinrun = false;
1800    //    //
1801    TSQLResult *result = 0;    TSQLResult *result = 0;
1802    TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
# Line 1335  void PamelaDBOperations::HandleRunFragme Line 1823  void PamelaDBOperations::HandleRunFragme
1823    //    //
1824    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");
1825    //    //
1826    // 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...
1827    //        //
1828    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("");
1829                                             // missing it no way we can found a piece in the frag table    oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
1830      //        << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
1831      oss.str("");        << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
1832      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 ("
1833          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "        << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
1834          << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME()        << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
1835          << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!        << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
1836      //        << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
1837      if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());        << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1838      result = conn->Query(oss.str().c_str());        << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
1839      //        << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
1840          << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
1841          << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
1842          << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
1843      //
1844      if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
1845      result = conn->Query(oss.str().c_str());
1846      //
1847      if ( !result ) throw -4;
1848      //
1849      row = result->Next();
1850      //
1851      if ( !row ){
1852        //
1853        // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
1854        //
1855        if ( IsDebug() ) printf(" The run is new \n");
1856        if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
1857        //
1858        glrun->SetID(this->AssignRunID());
1859        glrun->SetID_RUN_FRAG(0);
1860        glrun->Fill_GL_RUN_FRAGMENTS(conn);
1861        //
1862      } else {
1863        if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
1864        return;
1865      };
1866      //
1867      //
1868      // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
1869      //    
1870      if ( mishead && rhfirstev == firstev ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
1871                                               // missing it no way we can found a piece in the frag table
1872        //
1873        oss.str("");
1874        oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "
1875            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
1876            << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1877            << " ID != " << glrun->ID
1878            << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
1879        //
1880        if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());
1881        result = conn->Query(oss.str().c_str());
1882        //
1883      if ( !result ) throw -4;      if ( !result ) throw -4;
1884      //      //
1885      row = result->Next();      row = result->Next();
1886      //      //
1887        if ( !row && NoFrag() ){
1888          //
1889          oss.str("");
1890          oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
1891              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
1892              << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1893              << " ID != " << glrun->ID
1894              << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
1895          //
1896          if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
1897          result = conn->Query(oss.str().c_str());
1898          //
1899          if ( !result ) throw -4;
1900          //
1901          foundinrun = true;
1902          //
1903          row = result->Next();
1904          //
1905        };
1906        //
1907      if ( !row ){      if ( !row ){
1908        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
1909        found = false;        found = false;
# Line 1427  void PamelaDBOperations::HandleRunFragme Line 1978  void PamelaDBOperations::HandleRunFragme
1978        //        //
1979        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 ");
1980        //        //
1981          if ( foundinrun ){
1982            glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
1983            glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1984          };
1985          //
1986        GL_RUN *glrun1 = new GL_RUN();        GL_RUN *glrun1 = new GL_RUN();
1987        //        //
1988        UInt_t idfrag = (UInt_t)atoll(row->GetField(0));        //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
1989        //        //
1990        oss.str("");        oss.str("");
1991        oss << " ID="<<row->GetField(0)<<";";        oss << " ID="<<row->GetField(0)<<";";
# Line 1458  void PamelaDBOperations::HandleRunFragme Line 2014  void PamelaDBOperations::HandleRunFragme
2014        };        };
2015        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);
2016        //        //
       glrun1->SetID(0);  
2017        glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());        glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
2018        glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());        glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
2019        glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());        glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
# Line 1467  void PamelaDBOperations::HandleRunFragme Line 2022  void PamelaDBOperations::HandleRunFragme
2022        //        //
2023        glrun->SetEV_FROM(firstev);        glrun->SetEV_FROM(firstev);
2024        glrun->SetNEVENTS(lastev-firstev+1);        glrun->SetNEVENTS(lastev-firstev+1);
2025          //
2026        glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());        glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
2027        glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());        glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
2028        glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());        glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
# Line 1486  void PamelaDBOperations::HandleRunFragme Line 2042  void PamelaDBOperations::HandleRunFragme
2042        //        //
2043        if ( !IsRunAlreadyInserted() ){        if ( !IsRunAlreadyInserted() ){
2044          //          //
2045            //      glrun->SetID(this->AssignRunID());
2046            glrun->SetID_RUN_FRAG(glrun1->GetID());
2047          glrun->Fill_GL_RUN(conn);          glrun->Fill_GL_RUN(conn);
2048          //          //
2049          // 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);  
2050          //          //
2051            glrun1->SetID_RUN_FRAG(glrun->GetID());
2052          glrun1->Fill_GL_RUN(conn);          glrun1->Fill_GL_RUN(conn);
2053          //          //
         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;  
         //  
2054        };        };
       //  
       delete glrun1;  
       //  
2055        // delete old entry in fragment table        // delete old entry in fragment table
2056        //        //
2057        oss.str("");        glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2058          glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2059        //        //
2060        oss << " DELETE FROM GL_RUN_FRAGMENTS WHERE ID = " << idfrag << ";";        delete glrun1;
2061        //        //
       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;  
2062        //        //
2063        return;        return;
2064        //        //
# Line 1555  void PamelaDBOperations::HandleRunFragme Line 2067  void PamelaDBOperations::HandleRunFragme
2067    };    };
2068    //    //
2069    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
2070                                             // 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
2071      //      //
2072      oss.str("");      oss.str("");
2073      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 "
2074          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2075          << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME()          << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2076            << " ID != " << glrun->ID
2077          << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";          << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2078      //      //
2079      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 2083  void PamelaDBOperations::HandleRunFragme
2083      //      //
2084      row = result->Next();      row = result->Next();
2085      //      //
2086        if ( !row && NoFrag() ){
2087          //
2088          oss.str("");
2089          oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN WHERE "
2090              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2091              << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2092              << " ID != " << glrun->ID
2093              << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2094          //
2095          if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
2096          result = conn->Query(oss.str().c_str());
2097          //
2098          if ( !result ) throw -4;
2099          //
2100          foundinrun = true;
2101          row = result->Next();
2102          //
2103        };
2104        //
2105      if ( !row ){      if ( !row ){
2106        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2107        found = false;        found = false;
# Line 1643  void PamelaDBOperations::HandleRunFragme Line 2175  void PamelaDBOperations::HandleRunFragme
2175        //        //
2176        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 ");
2177        //        //
2178          if ( foundinrun ){
2179            glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2180            glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2181          };
2182          //
2183        GL_RUN *glrun1 = new GL_RUN();        GL_RUN *glrun1 = new GL_RUN();
2184        //        //
2185        UInt_t idfrag = (UInt_t)atoll(row->GetField(0));        //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
2186        //        //
2187        oss.str("");        oss.str("");
2188        oss << " ID="<<row->GetField(0)<<";";        oss << " ID="<<row->GetField(0)<<";";
# Line 1682  void PamelaDBOperations::HandleRunFragme Line 2219  void PamelaDBOperations::HandleRunFragme
2219        glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());        glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());
2220        glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());        glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());
2221        //        //
       glrun1->SetID(0);  
2222        glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());        glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());
2223        glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());        glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());
2224        glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());        glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());
# Line 1702  void PamelaDBOperations::HandleRunFragme Line 2238  void PamelaDBOperations::HandleRunFragme
2238        //        //
2239        if ( !IsRunAlreadyInserted() ){        if ( !IsRunAlreadyInserted() ){
2240          //          //
2241          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();  
2242          //          //
2243          UInt_t idrun0 = 0;          glrun->SetID_RUN_FRAG(glrun1->GetID());
2244          if ( !row ){          glrun->Fill_GL_RUN(conn);
           throw -10;  
         } else {  
           idrun0 = (UInt_t)atoll(row->GetField(0));  
         };  
2245          //          //
2246          glrun1->SetID_RUN_FRAG(idrun0);          // set id number
2247          //          //
2248            glrun1->SetID_RUN_FRAG(glrun->GetID());
2249          glrun1->Fill_GL_RUN(conn);          glrun1->Fill_GL_RUN(conn);
2250          //          //
         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;  
         //  
2251        };        };
2252        //        //
2253        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 << ";";  
2254        //        //
2255        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");
2256        result =  conn->Query(oss.str().c_str());        glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
       if ( !result ) throw -4;  
2257        //        //
2258          delete glrun1;
2259        //        //
2260        return;        return;
2261        //        //
# Line 1800  void PamelaDBOperations::HandleRunFragme Line 2292  void PamelaDBOperations::HandleRunFragme
2292      //      //
2293      row = result->Next();      row = result->Next();
2294      //      //
2295      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 {  
2296        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");
2297        } else {
2298          if ( NoFrag() ){
2299            glrun->SetID_RUN_FRAG(glrun->GetID());
2300            glrun->Fill_GL_RUN(conn);      
2301            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2302          };    
2303      };      };
2304    };    };
2305    //    //
# Line 1864  void PamelaDBOperations::HandleMissingHo Line 2325  void PamelaDBOperations::HandleMissingHo
2325      //      //
2326      this->FillClass(mishead,mistrail,firstev,lastev);      this->FillClass(mishead,mistrail,firstev,lastev);
2327      //      //
2328      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);          if ( !IsRunAlreadyInserted() ){
2329          glrun->SetID(this->AssignRunID());
2330          glrun->SetID_RUN_FRAG(0);
2331          glrun->Fill_GL_RUN(conn);    
2332        };
2333      //      //
2334    };    };
2335    //    //
# Line 2031  Bool_t PamelaDBOperations::IsRunConsiste Line 2496  Bool_t PamelaDBOperations::IsRunConsiste
2496            //                  //      
2497            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
2498            //            //
2499            if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                  if ( !IsRunAlreadyInserted() ){
2500                glrun->SetID(this->AssignRunID());
2501                glrun->SetID_RUN_FRAG(0);
2502                glrun->Fill_GL_RUN(conn);      
2503              };
2504            //            //
2505            firstevno = lastentry + 1;            firstevno = lastentry + 1;
2506            //            //
# Line 2106  void PamelaDBOperations::HandleSuspiciou Line 2575  void PamelaDBOperations::HandleSuspiciou
2575    if ( firstev == lastev+1 ) { // no events inside the run!    if ( firstev == lastev+1 ) { // no events inside the run!
2576      if ( IsDebug() ) printf(" Checking but no events in the run! \n");      if ( IsDebug() ) printf(" Checking but no events in the run! \n");
2577      //      //
     //    if ( IsDebug() ) printf(" -> fill the DB \n");  
     //  
2578      this->FillClass();      this->FillClass();
2579      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);          if ( !IsRunAlreadyInserted() ){
2580          glrun->SetID(this->AssignRunID());
2581          glrun->SetID_RUN_FRAG(0);
2582          glrun->Fill_GL_RUN(conn);    
2583        };
2584      //      //
2585    } else {    } else {
2586      //      //
# Line 2137  void PamelaDBOperations::HandleSuspiciou Line 2608  void PamelaDBOperations::HandleSuspiciou
2608        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");
2609        //        //
2610        this->FillClass();        this->FillClass();
2611        if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                if ( !IsRunAlreadyInserted() ){
2612            glrun->SetID(this->AssignRunID());
2613            glrun->SetID_RUN_FRAG(0);
2614            glrun->Fill_GL_RUN(conn);        
2615          };
2616        //        //
2617      } else {      } else {
2618        //        //
# Line 2235  void PamelaDBOperations::HandleSuspiciou Line 2710  void PamelaDBOperations::HandleSuspiciou
2710            //                  //      
2711            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
2712            //            //
2713            if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                  if ( !IsRunAlreadyInserted() ){
2714                glrun->SetID(this->AssignRunID());
2715                glrun->SetID_RUN_FRAG(0);
2716                glrun->Fill_GL_RUN(conn);      
2717              };
2718            //            //
2719            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...
2720              //              //
# Line 2270  void PamelaDBOperations::HandleSuspiciou Line 2749  void PamelaDBOperations::HandleSuspiciou
2749              //                  //    
2750              this->SetCommonGLRUN(firstTime,lastTime);              this->SetCommonGLRUN(firstTime,lastTime);
2751              //              //
2752              if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                    if ( !IsRunAlreadyInserted() ){
2753                  glrun->SetID(this->AssignRunID());
2754                  glrun->SetID_RUN_FRAG(0);
2755                  glrun->Fill_GL_RUN(conn);      
2756                };
2757            };            };
2758            //            //
2759            firstevno = lastentry + 1;            firstevno = lastentry + 1;
# Line 2318  Int_t PamelaDBOperations::insertCALO_CAL Line 2801  Int_t PamelaDBOperations::insertCALO_CAL
2801    tr->SetBranchAddress("Header", &eh);    tr->SetBranchAddress("Header", &eh);
2802    nevents = tr->GetEntries();    nevents = tr->GetEntries();
2803    //    //
2804    if ( !nevents ) return(0);    if ( !nevents ) return(1);
2805    //    //
2806    for (UInt_t i=0; i < nevents; i++){    for (UInt_t i=0; i < nevents; i++){
2807      tr->GetEntry(i);      tr->GetEntry(i);
# Line 2377  Int_t PamelaDBOperations::insertCALO_CAL Line 2860  Int_t PamelaDBOperations::insertCALO_CAL
2860                // no calibrations in the db contain our calibration                // no calibrations in the db contain our calibration
2861                //                //
2862                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);
2863                if ( fromtime < 1150863400 ){                if ( fromtime < 1150871000 ){ //1150866904
2864                  if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);                  if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);
2865                  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
2866                };                };
# Line 2440  Int_t PamelaDBOperations::insertCALO_CAL Line 2923  Int_t PamelaDBOperations::insertCALO_CAL
2923            //            //
2924          } else {          } else {
2925            //            //
2926            if ( IsDebug() ) printf(" Repetead calo calibration for section %i at time %i obt %i pkt %i \n",section,fromtime,obt,pkt);            if ( IsDebug() ) printf(" Repeated calo calibration for section %i at time %i obt %i pkt %i \n",section,fromtime,obt,pkt);
2927            //            //
2928          };                };      
2929          //                //      
# Line 2522  void PamelaDBOperations::HandleTRK_CALIB Line 3005  void PamelaDBOperations::HandleTRK_CALIB
3005        // no calibrations in the db contain our calibration        // no calibrations in the db contain our calibration
3006        //        //
3007        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");
3008        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
3009        //        //
3010        oss.str("");        oss.str("");
3011        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 3118  Int_t PamelaDBOperations::insertTRK_CALI
3118    tr2->SetBranchAddress("Header", &eh2);    tr2->SetBranchAddress("Header", &eh2);
3119    nevents2 = tr2->GetEntries();    nevents2 = tr2->GetEntries();
3120    //    //
3121    if ( !nevents1 && !nevents2 ) return(0);    if ( !nevents1 && !nevents2 ) return(1);
3122    //    //
3123    t2 = -1;    t2 = -1;
3124    Int_t pret2 = 0;    Int_t pret2 = 0;
# Line 2651  Int_t PamelaDBOperations::insertTRK_CALI Line 3134  Int_t PamelaDBOperations::insertTRK_CALI
3134      pkt1 = ph1->GetCounter();        pkt1 = ph1->GetCounter();  
3135      fromtime = this->GetAbsTime(ph1->GetOrbitalTime());        fromtime = this->GetAbsTime(ph1->GetOrbitalTime());  
3136      //      //
3137      valid = 1;  //     valid = 1;
3138      //  //     //
3139      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
3140      //      //
3141      //      //
3142      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) ){
3143        //        //
3144        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);
3145          //      
3146          valid = ValidateTrkCalib( caltrk1, eh1 );
3147          if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;
3148        //        //
3149        // Do we have the second calibration packet?        // Do we have the second calibration packet?
3150        //        //
# Line 2675  Int_t PamelaDBOperations::insertTRK_CALI Line 3161  Int_t PamelaDBOperations::insertTRK_CALI
3161            obt2 = ph2->GetOrbitalTime();              obt2 = ph2->GetOrbitalTime();  
3162            pkt2 = ph2->GetCounter();              pkt2 = ph2->GetCounter();  
3163            //            //
3164            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
3165            //                  //      
3166          } else {          } else {
3167            //            //
# Line 2706  Int_t PamelaDBOperations::insertTRK_CALI Line 3192  Int_t PamelaDBOperations::insertTRK_CALI
3192          //          //
3193          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);
3194          //          //
3195            UInt_t valid2 = ValidateTrkCalib( caltrk2, eh2 );
3196            if ( IsDebug() ) cout << " pkt2 validation --> "<<valid2<<endl;
3197            valid = valid & valid2;
3198            //
3199          // Handle good calib          // Handle good calib
3200          //          //
3201          this->HandleTRK_CALIB(true,true);          this->HandleTRK_CALIB(true,true);
# Line 2807  Int_t PamelaDBOperations::insertS4_CALIB Line 3297  Int_t PamelaDBOperations::insertS4_CALIB
3297    stringstream oss;    stringstream oss;
3298    oss.str("");    oss.str("");
3299    //    //
   CalibS4Event *calibS4    = new  CalibS4Event();  
3300    TTree *tr = 0;    TTree *tr = 0;
3301    EventHeader *eh = 0;    EventHeader *eh = 0;
3302    PscuHeader *ph = 0;    PscuHeader *ph = 0;
# Line 2821  Int_t PamelaDBOperations::insertS4_CALIB Line 3310  Int_t PamelaDBOperations::insertS4_CALIB
3310    tr = (TTree*)file->Get("CalibS4");    tr = (TTree*)file->Get("CalibS4");
3311    if ( !tr || tr->IsZombie() ) throw -24;    if ( !tr || tr->IsZombie() ) throw -24;
3312    //    //
   tr->SetBranchAddress("CalibS4", &calibS4);  
3313    tr->SetBranchAddress("Header", &eh);    tr->SetBranchAddress("Header", &eh);
3314    //    //
3315    nevents = tr->GetEntries();    nevents = tr->GetEntries();
3316    //    //
3317    if ( !nevents ) return(0);    if ( !nevents ) return(1);
3318    //    //
3319    for (UInt_t i = 0; i < nevents; i++){    for (UInt_t i = 0; i < nevents; i++){
3320      //      //
3321      tr->GetEntry(i);      tr->GetEntry(i);
     TArrayD params = S4_paramfit(calibS4);  
3322      //      //
3323      ph = eh->GetPscuHeader();      ph = eh->GetPscuHeader();
3324      obt = ph->GetOrbitalTime();        obt = ph->GetOrbitalTime();  
# Line 2881  Int_t PamelaDBOperations::insertS4_CALIB Line 3368  Int_t PamelaDBOperations::insertS4_CALIB
3368            // no calibrations in the db contain our calibration            // no calibrations in the db contain our calibration
3369            //            //
3370            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");
3371            if ( fromtime < 1150863400 ){            if ( fromtime < 1150871000 ){  
3372              if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);              if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);
3373              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
3374            };            };
# Line 2921  Int_t PamelaDBOperations::insertS4_CALIB Line 3408  Int_t PamelaDBOperations::insertS4_CALIB
3408          };          };
3409          //          //
3410          oss.str("");          oss.str("");
3411          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) "
3412              << " VALUES (NULL,' "              << " VALUES (NULL,' "
3413              << idroot << "','"              << idroot << "','"
3414              << i << "','"              << i << "','"
3415              << fromtime << "','"              << fromtime << "','"
3416              << totime << "','"              << totime << "','"
             << dec << params.At(0) << "','"  
             << dec << params.At(1) << "','"        
3417              << obt << "','"              << obt << "','"
3418              << pkt << "','"              << pkt << "','"
3419              << this->GetBOOTnumber() << "','"              << this->GetBOOTnumber() << "');";
             << valid << "');";  
3420          //          //
3421          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());
3422          //          //
# Line 2953  Int_t PamelaDBOperations::insertS4_CALIB Line 3437  Int_t PamelaDBOperations::insertS4_CALIB
3437    return(0);    return(0);
3438  };  };
3439    
3440    /**
3441  /*   * Scan the fragment table and move old fragments to the GL_RUN table
  * Fit function Received from Valeria Malvezzi 06/02/2006  
3442   */   */
3443  Double_t fitf(Double_t *x, Double_t *par){    Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(){
3444    Double_t fitval =(par[0]*x[0])+par[1];    return(this->CleanGL_RUN_FRAGMENTS(""));
3445    return fitval;  };
 }  
3446    
3447  /*  /**
3448   * 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
3449   */   */
3450  TArrayD PamelaDBOperations::S4_paramfit(pamela::CalibS4Event *S4CalibEvent){        Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(TString fcleanfile){
3451      //
3452    //----------- variable initialization -------------------------------------------------    TSQLResult *result = 0;
3453      TSQLRow    *row    = 0;
3454    Double_t mip[3]={1, 30, 300};    TSQLResult *result2 = 0;
3455    Double_t adc[3] = {0.,0.,0.};    TSQLRow    *row2   = 0;
3456        //
3457    TArrayD parametri(2);    UInt_t moved = 0;
3458      //
3459    valid = 1;    stringstream oss;
3460      oss.str("");
3461    //------------ Fit calibrations and find parameters to calibrate data ------------------    //
3462    pamela::S4::S4Event  *s4Record;    if ( !strcmp(fcleanfile.Data(),"") ){
3463        //
3464    for (Int_t j = 0; j < 4; j++){      // check if there are entries older than "olderthan" seconds from now
3465      for (Int_t i = 0; i < 128; i++){      //
3466        s4Record = (pamela::S4::S4Event*)S4CalibEvent->Records->At((j*128 + i));      oss.str("");
3467        switch (j) {      oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
3468        case 0 :{          << " INSERT_TIME <= '" << clean_time->AsSQLString() << "';";
3469          adc[0]=adc[0]+((s4Record->S4_DATA)-32);      //
3470          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());
3471        };      result = conn->Query(oss.str().c_str());
3472        case 1 :{      //
3473          adc[1]=adc[1]+((s4Record->S4_DATA)-32);    } else {
3474          break;      oss.str("");
3475        };      oss << " SELECT ID FROM GL_ROOT WHERE NAME='" << fcleanfile.Data() << "';";
3476        case 3 :{      if ( IsDebug() ) printf(" Getting ID_ROOT_L0 query %s \n",oss.str().c_str());
3477          adc[2]=adc[2]+((s4Record->S4_DATA)-32);      result = conn->Query(oss.str().c_str());
3478          break;      //    
3479        };      if ( result ){
3480          //
3481          row = result->Next();
3482          //
3483          if ( row ){
3484            oss.str("");
3485            oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
3486                << " ID_ROOT_L0=" << row->GetField(0) << ";";
3487            //
3488            if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS for ROOT file query is \n %s \n",oss.str().c_str());
3489            result = conn->Query(oss.str().c_str());
3490            //    
3491        };        };
3492        } else {
3493          return(2);
3494      };      };
3495    };    };
3496        //
3497    adc[0]=adc[0]/128;    if ( result ){
3498    adc[1]=adc[1]/128;      //
3499    adc[2]=adc[2]/128;      row = result->Next();
3500          //
3501    TGraph *fitpar = new TGraph (3, adc, mip);      while ( row ){
3502    TF1 *func = new TF1("fitf", fitf, -0., 1000., 2); // definizione della funzione, 2 = num. parametri        //
3503            oss.str("");
3504    func->SetParameters(0.3,1.);        //inizializzazione dei parametri a 1        oss << " ID= "<< row->GetField(0);
3505    func->SetParNames("m","q");      //definisce il nome dei parametri        //
3506    fitpar->Fit(func,"qr");          //fitta fitpar con la funzione func nel range definito nella funzione        glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);  
3507    //fitpar->Fit(func,"r");          //fitta fitpar con la funzione func nel range definito nella funzione        //
3508              oss.str("");
3509    parametri[0] = func -> GetParameter(0);        oss << " SELECT ID,NEVENTS,TRK_CALIB_USED,PKT_COUNTER FROM GL_RUN WHERE "
3510    parametri[1] = func -> GetParameter(1);            << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND ("
3511              << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3512    if ( parametri[0] < 0. || parametri[0] > 0.5 || parametri[1] < 0.8 || parametri[1] > 1. ) valid = 0;            << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3513              << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3514    if ( IsDebug() ) printf(" par1 = %g par2 = %g\n",parametri[0],parametri[1]);            << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3515              << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3516    return parametri;            << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3517              << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3518              << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3519              << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3520              << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3521              << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3522              << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3523          //
3524          if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3525          result2 = conn->Query(oss.str().c_str());
3526          //
3527          if ( !result2 ) throw -4;
3528          //
3529          row2 = result2->Next();
3530          //
3531          if ( !row2 ){
3532            //
3533            if ( IsDebug() ) printf(" The run is new \n");
3534            if ( IsDebug() ) printf(" -> fill the DB \n");      
3535            //
3536            //      glrun->SetID(this->AssignRunID()); we use the old run number!
3537            glrun->SetID_RUN_FRAG(glrun->GetID());
3538            glrun->Fill_GL_RUN(conn);  
3539            //
3540    //      oss.str("");
3541    //      oss << " SELECT ID FROM GL_RUN WHERE "
3542    //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
3543    //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
3544    //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
3545    //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
3546    //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
3547    //      //
3548    //      if ( IsDebug() ) printf(" Look for the ID of the inserted run: query is \n %s \n",oss.str().c_str());
3549    //      result2 = conn->Query(oss.str().c_str());
3550    //      //
3551    //      if ( !result2 ) throw -4;
3552    //      //
3553    //      row2 = result2->Next();
3554    //      //
3555    //      if ( !row2 ) throw -25;
3556    //      //
3557    //      oss.str("");
3558    //      oss << " UPDATE GL_RUN SET ID_RUN_FRAG = " << row2->GetField(0) << " WHERE ID = " << row2->GetField(0);
3559    //      if ( IsDebug() ) printf(" Update the ID_RUN_FRAG of the inserted run: query is \n %s \n",oss.str().c_str());
3560    //      result2 = conn->Query(oss.str().c_str());
3561    //      //
3562    //      if ( !result2 ) throw -4;
3563            //
3564            moved++;
3565            //
3566          } else {
3567            if ( IsDebug() ) printf(" The already exist in the GL_RUN table! \n");
3568          };
3569          if ( IsDebug() ) printf(" Delete run %s from the GL_RUN_FRAGMENTS table \n",row->GetField(0));      
3570          //
3571          //
3572          glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3573    //      oss.str("");
3574    //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);
3575    //       if ( IsDebug() ) printf(" Clean the GL_RUN_FRAGMENTS table: query is \n %s \n",oss.str().c_str());
3576    //       result2 = conn->Query(oss.str().c_str());
3577    //      //
3578    //      if ( !result2 ) throw -4;
3579    //      //
3580          row = result->Next();
3581        };
3582      };
3583      if ( IsDebug() ) printf(" Moved %u runs\n",moved);
3584      return(0);
3585    };
3586    
3587    /**
3588     * Check if runs are good, i.e. if the tracker calibration is correctly associated..
3589     */
3590    Int_t PamelaDBOperations::ValidateRuns(){
3591      return(this->ValidateRuns(""));
3592    };
3593    
3594    /**
3595     * Check if runs are good, i.e. if the tracker calibration is correctly associated..
3596     */
3597    Int_t PamelaDBOperations::ValidateRuns(TString valfile){
3598      //
3599      TSQLResult *result = 0;
3600      TSQLRow    *row    = 0;
3601      //
3602      UInt_t calibtime = 50;
3603      //
3604      stringstream oss;
3605      oss.str("");
3606      //
3607      // =======================================================
3608      // validate runs by checking missing calibrations
3609      // =======================================================
3610      UInt_t t_stop  = 0;
3611      UInt_t t_start = 0;
3612      if ( !strcmp(valfile.Data(),"") ) {
3613        // --------------------------------------------------------------
3614        // 1) get the OBT of the last run inserted after clean-time limit
3615        // --------------------------------------------------------------
3616        oss.str("");
3617        oss << " SELECT * FROM GL_RUN  WHERE INSERT_TIME <= '" << clean_time->AsSQLString()
3618            << "' ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
3619        if ( IsDebug() ) printf(" Get start validation-time: query is \n %s \n",oss.str().c_str());
3620        result = conn->Query(oss.str().c_str());
3621        if ( !result ) throw -4;
3622        if ( !result->GetRowCount() ) {
3623          printf(" No runs to validate \n");
3624          return(1);
3625        }else{
3626          row = result->Next();
3627          t_start = (UInt_t)atoll(row->GetField(4));
3628        };  
3629        // --------------------------------------------------------------
3630        // 2) get the OBT of the last validated run
3631        // --------------------------------------------------------------
3632        oss.str("");
3633        oss << " SELECT * FROM GL_RUN  WHERE VALIDATION=1 AND RUNHEADER_TIME<="<< t_start
3634            <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
3635        if ( IsDebug() ) printf(" Get stop validation-time: query is \n %s \n",oss.str().c_str());
3636        result = conn->Query(oss.str().c_str());
3637        if ( !result ) throw -4;
3638        if ( result->GetRowCount() ){
3639          row = result->Next();
3640          t_stop = (UInt_t)atoll(row->GetField(4));
3641        };
3642        if ( IsDebug() ) printf("Validation interval: from time %i - to time %i \n\n",t_stop,t_start);
3643        // --------------------------------------------------------------
3644        // now retrieves runs to be validated
3645        // --------------------------------------------------------------
3646        oss.str("");
3647        oss << " SELECT * FROM GL_RUN  WHERE  RUNHEADER_TIME <=" << t_start;
3648        oss << " AND RUNHEADER_TIME >="<< t_stop;
3649        oss << " ORDER BY RUNHEADER_TIME DESC;";
3650        if ( IsDebug() )printf(" Check runs for validation: query is \n %s \n",oss.str().c_str());
3651        result = conn->Query(oss.str().c_str());
3652      } else {
3653        //
3654        stringstream myquery;
3655        UInt_t myid = 0;
3656        myquery.str("");
3657        myquery << " SELECT ID FROM GL_ROOT where NAME='"<<valfile.Data() <<"';";
3658        //
3659        result = conn->Query(myquery.str().c_str());
3660        //
3661        row = result->Next();      
3662        if( !row ){
3663          if ( strcmp(valfile.Data(),GetRootName().Data()) ){
3664            if ( IsDebug() ) printf(" No file to be validated even if option \"-validate file\" was used!!\n");
3665            return(2);
3666          };
3667          if ( IsDebug() ) printf(" No file to be validated (force mode)! \n");
3668          return(0);
3669        };
3670        myid=(UInt_t)atoll(row->GetField(0));
3671        //
3672        myquery.str("");
3673        myquery << " SELECT MAX(RUNTRAILER_TIME),MIN(RUNHEADER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< myid <<";";
3674        //
3675        result = conn->Query(myquery.str().c_str());
3676        //
3677        row = result->Next();      
3678        if( !row->GetField(0) || !row->GetField(1)){
3679          //
3680          if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
3681          //
3682          return(0);
3683          //
3684        } else {  
3685          //
3686          UInt_t runhtime = (UInt_t)atoll(row->GetField(0));
3687          UInt_t runttime = (UInt_t)atoll(row->GetField(1));
3688          UInt_t caltime = 0;
3689          //
3690          myquery.str("");
3691          myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
3692          myquery << " order by FROM_TIME asc limit 1;";
3693          //
3694          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
3695          //
3696          //
3697          result = conn->Query(myquery.str().c_str());
3698          //
3699          row = result->Next();      
3700          if( !row ){
3701            caltime = runhtime;
3702          } else {
3703            caltime = (UInt_t)atoll(row->GetField(0));
3704          };
3705          //
3706          myquery.str("");
3707          myquery << " SELECT * from GL_RUN where RUNHEADER_TIME>="<< runttime <<" AND RUNHEADER_TIME<=" ;
3708          myquery << caltime << " order by RUNHEADER_TIME DESC";
3709          //
3710          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
3711          //
3712          result = conn->Query(myquery.str().c_str());
3713          //
3714        };
3715      };
3716      //
3717      if ( !result ) throw -4;
3718      if ( !result->GetRowCount() && IsDebug() ) printf(" No runs to validate \n");
3719      //
3720      Int_t nrow = 0;
3721      GL_RUN* this_run = new GL_RUN();
3722      GL_RUN* next_run = new GL_RUN();
3723      Int_t   nseq_max = 1000;
3724    //  UInt_t* sequence = new UInt_t[100];
3725      vector<UInt_t> sequence(nseq_max);
3726      Int_t   nseq = 0;
3727      Bool_t CHECK = false;
3728      Bool_t this_ONLINE = false;
3729      Bool_t next_ONLINE = false;
3730      UInt_t t1=0,t2=0;
3731      // ---------------------------------------------------------------------------------
3732      // - loop over runs, back in time,
3733      // - select sequences of runs close in time (less than calibtime s apart),
3734      //   which could be preceeded by a calibration
3735      // - check if there might be a missing calibration
3736      // ---------------------------------------------------------------------------------
3737      while(1){
3738              
3739              row = result->Next();
3740              if( row == NULL ) break;
3741              
3742              //------------
3743              //get run info
3744              //------------
3745              this_run->Set_GL_RUN(row);
3746                      
3747              Bool_t this_BAD = false;
3748              if(this_run->GetTRK_CALIB_USED() == 1 || this_run->GetTRK_CALIB_USED() == 2) this_ONLINE = true;
3749              else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;
3750              else{
3751    //                printf("Missing or corrupted header!! \n");
3752                      this_ONLINE = false;
3753                      this_BAD = true;
3754              };
3755    
3756              //-----------------------------------
3757              //compare with previous(next in time)
3758              //-----------------------------------
3759              CHECK = false;
3760              UInt_t interval=0;
3761              
3762              if( nrow != 0){
3763            
3764                      
3765                      t1 = this_run->GetRUNTRAILER_TIME();
3766                      t2 = next_run->GetRUNHEADER_TIME();
3767                      interval = (t2-t1);
3768                      
3769                      if(this_ONLINE && next_ONLINE){                               // this: ON-LINE + next: ON-LINE
3770                              
3771                              if( this_run->ID == next_run->ID_RUN_FRAG ) interval = 0;     //=> run fragments
3772                              
3773                              if( interval >= calibtime )CHECK = true;                      //more than calibtime s => there might be a calibration
3774                              
3775                              if( !CHECK && this_run->VALIDATION ){
3776                                      for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
3777                                      nseq=0;
3778                              }
3779                      
3780                      }else if( !this_ONLINE && next_ONLINE) {              // this: DEFAULT + next:ON-LINE
3781                              
3782                              CHECK = true;
3783    
3784                      }else if( !next_ONLINE ){                                             // this:ANY + next:DEFAULT
3785                              
3786                              assignVALIDATION(next_run->ID,true);
3787                              nseq=0;
3788                      }
3789              }
3790    
3791              //----------------------------
3792              //check run sequence for calib
3793              //----------------------------
3794              if( CHECK ){
3795                      // check if calibration exists
3796                      if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);
3797                      Bool_t MISSING = MissingTRK_CALIB(t1,t2);
3798                      for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],!MISSING);
3799                      nseq=0;
3800              };
3801              //--------------
3802              //store run info
3803              //--------------
3804              *next_run   = *this_run;
3805              next_ONLINE = this_ONLINE;
3806              if( !this_BAD ){
3807                      if(nseq < nseq_max){
3808                              sequence[nseq] = this_run->ID;
3809                              nseq++;
3810                      }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);
3811              };
3812              
3813              if ( IsDebug() ) printf("%i Run %i \n",nrow,this_run->ID);
3814              nrow++;
3815              
3816      };
3817      delete this_run;
3818      delete next_run;
3819      //
3820      return(0);
3821    };
3822    /**
3823     * Check if there might be a missing tracker calibration in a given time interval
3824     * @param t1 From absolute time
3825     * @param t2 To absolute time
3826     * @return true if there might be a missing calibration
3827     */
3828    Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
3829            
3830            GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();
3831            
3832            // get the closest VALIDATED calibration before the run start (t2)
3833            if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true);      //>>> missing
3834            
3835            if ( trkcalib->TO_TIME  < t2 ) return(true);                                    //>>> missing
3836            
3837            //==============================================================
3838            // Check is done first on the basis of time between calibration,
3839            // which should be equal to the time between ascending-nodes.
3840            //==============================================================
3841            if ( t2 - trkcalib->FROM_TIME > 5700) {
3842                    if ( IsDebug() )printf("Long time between calib and run start %i :-( ==> there might be a missing calib \n",t2 - trkcalib->FROM_TIME);
3843            //==============================================================
3844            // there might be a missing calibration, due to:
3845            // - MM full
3846            // - corrupted packets
3847            // - loss of data
3848            // There is an exception in case a download was done during ascending node
3849            //==============================================================
3850                    Bool_t DOWNLOAD = false;
3851                    // check if the calib was skipped becouse of download .... DA FARE!!
3852                    if(DOWNLOAD)return(false);
3853                    
3854                    return(true);                                   //>>> missing
3855                    
3856            };
3857            
3858            //==============================================================
3859            // If the last calibration is close to the run less than this time,
3860            // it is enough to say that there are no missing calibrations
3861            //==============================================================
3862            // the long time interval bewteen runs might be due to download
3863            if ( IsDebug() )printf("Short time between calib and run start %i :-) ==> OK! \n",t2 - trkcalib->FROM_TIME);
3864            return(false);
3865            
3866    };
3867    /**
3868     * Assign VALIDATION value to a GL_RUN entry
3869     * @param idrun Run ID
3870     * @param validation true/false
3871     */
3872    Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){
3873            TSQLResult *result = 0;
3874            stringstream oss;
3875            oss.str("");
3876            oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";
3877            //
3878    //      if ( IsDebug() )
3879    //      printf(" Set VALIDATION = %i for run %i \n",validation,idrun);
3880            if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());
3881            result = conn->Query(oss.str().c_str());
3882            if ( !result ) throw -4;
3883            return(0);
3884    }
3885    
3886    
3887    
3888    // Insert TLEs from file tlefilename in the table GL_TLE in the db
3889    // opened by conn, sorting them by date from older to newer, if each
3890    // TLE has not been alread inserted.
3891    Int_t PamelaDBOperations::populateTLE()//(TSQLServer *conn, char *tleFile)
3892    {
3893      fstream tlefile(tlefilename, ios::in);
3894    
3895      if ( !tlefile ) throw -7;
3896    
3897      vector<cTle*> ctles;
3898      vector<cTle*>::iterator iter;
3899      int present = 0;
3900    
3901      // Get three lines from tlefile, create a cTle object and put it
3902      // into ctles
3903      while(1) {
3904        cTle *tlef;
3905        string str1, str2, str3;
3906    
3907        getline(tlefile, str1);
3908        if(tlefile.eof()) break;
3909    
3910        getline(tlefile, str2);
3911        if(tlefile.eof()) break;
3912    
3913        getline(tlefile, str3);
3914        if(tlefile.eof()) break;
3915    
3916        // We now have three good lines for a cTle.
3917        tlef = new cTle(str1, str2, str3);
3918        ctles.push_back(tlef);
3919      }
3920    
3921      tlefile.close();
3922    
3923      // Sort by date
3924      sort(ctles.begin(), ctles.end(), compTLE);
3925    
3926      // Now we insert each TLE into the db
3927      for(iter = ctles.begin(); iter != ctles.end(); iter++) {
3928        cTle *tle = *iter;
3929    
3930        // Do nothing if it's already present in the db.  Just increase
3931        // the counter present.
3932        if (! isTlePresent(tle))
3933          {
3934            int status = insertTle(tle);
3935    
3936            // Insert query failed.  Return 1.
3937            if(status == EXIT_FAILURE) {
3938              
3939              if( IsDebug() ) {
3940                cerr << "Error: inserting TLE:" << endl
3941                     << tle->getName() << endl
3942                     << tle->getLine1() << endl
3943                     << tle->getLine2() << endl;
3944              }
3945    
3946              throw -4;
3947              return 1;
3948            }
3949    
3950          }
3951        else
3952          present++;
3953    
3954      }
3955    
3956      int inserted = ctles.size() - present;  // Number of inserted TLE.
3957      if ( IsDebug() )
3958        cout << "\nProcessed TLEs ranging from " << getTleDatetime(ctles[0]) << " to " << getTleDatetime(ctles[ctles.size()-1]) << "." << endl
3959             << inserted << " newly inserted TLEs out of " << ctles.size() << " processed." << endl;
3960    
3961      ctles.clear();
3962    
3963    
3964      // Return 2 if no new TLE has been inserted.  0 otherwise.
3965      if(! inserted ) return 2;
3966      return 0;
3967    }
3968    
3969    
3970    // Insert tle in the table GL_TLE using the connection conn.
3971    Int_t PamelaDBOperations::insertTle(cTle *tle)
3972    {
3973      stringstream oss;
3974      TSQLResult *result = 0;
3975    
3976      oss.str("");
3977      oss << " INSERT INTO GL_TLE (TLE1, TLE2, TLE3, FROM_TIME)"
3978          << " VALUES ( '"
3979          << tle->getName() << "', '"
3980          << tle->getLine1() << "', '"
3981          << tle->getLine2() << "', '"
3982          << getTleDatetime(tle) << "')";
3983    
3984      //  cout << oss.str().c_str() << endl;
3985      result = conn->Query(oss.str().c_str());
3986      if (result == NULL)
3987        return EXIT_FAILURE;
3988    
3989      return EXIT_SUCCESS;
3990    }
3991    
3992    
3993    // Return whether tle is already in the db connected by conn.
3994    bool PamelaDBOperations::isTlePresent(cTle *tle)
3995    {
3996      stringstream oss;
3997      TSQLResult *result = 0;
3998    
3999      oss.str("");
4000      oss << "SELECT * FROM GL_TLE WHERE FROM_TIME = '"
4001          << getTleDatetime(tle) << "'";
4002    
4003      result = conn->Query(oss.str().c_str());
4004      if (result == NULL) throw -4;
4005    
4006      if (result->GetRowCount())
4007        return true;
4008      else
4009        return false;
4010    }
4011    
4012    
4013    // Return whether the first TLE is dated early than the second
4014    bool compTLE (cTle *tle1, cTle *tle2)
4015    {
4016      return getTleJulian(tle1) < getTleJulian(tle2);
4017    }
4018    
4019    
4020    // Return the date of the tle using the format (year-2000)*1e3 +
4021    // julian day.  e.g. 6365 is the 31th Dec 2006.
4022    // It does *not* return a cJulian date.
4023    float getTleJulian(cTle *tle) {
4024      return tle->getField(cTle::FLD_EPOCHYEAR)*1e3 + tle->getField(cTle::FLD_EPOCHDAY);
4025    }
4026    
4027    
4028    // Return a string like YYYY-MM-DD hh:mm:ss, usable for mysql datetime
4029    // format.
4030    string getTleDatetime(cTle *tle)
4031    {
4032      int year, mon, day, hh, mm, ss;
4033      double dom; // day of month (is double!)
4034      stringstream date; // date in datetime format
4035    
4036      // create a cJulian from the date in tle
4037      cJulian jdate = cJulian( 2000 + (int) tle->getField(cTle::FLD_EPOCHYEAR), tle->getField(cTle::FLD_EPOCHDAY));
4038    
4039      // get year, month, day of month
4040      jdate.getComponent(&year, &mon, &dom);
4041    
4042      // build a datetime YYYY-MM-DD hh:mm:ss
4043      date.str("");
4044      day = (int) floor(dom);
4045      hh = (int) floor( (dom - day) * 24);
4046      mm = (int) floor( ((dom - day) * 24 - hh) * 60);
4047      ss = (int) floor( ((((dom - day) * 24 - hh) * 60 - mm) * 60));
4048      //  ms = (int) floor( (((((dom - day) * 24 - hh) * 60 - mm) * 60) - ss) * 1000);
4049    
4050      date << year << "-" << mon << "-" << day << " " << hh << ":" << mm << ":" << ss;
4051    
4052      return date.str();
4053    }
4054    
4055    /**
4056     * Remove a file from the DB, delete on cascade all entries related to that file
4057     * rearrange GL_RUN and GL_XXX_CALIB tables, turn off validation till the following
4058     * calibration
4059     **/
4060    Int_t PamelaDBOperations::removeFile(TString remfile){
4061      //
4062      // Determine ID_ROOT_L0 and ID_RAW
4063      //
4064      TSQLResult *pResult;
4065      TSQLRow *Row;
4066      stringstream myquery;
4067      //  
4068      myquery.str("");
4069      myquery << " SELECT ID, ID_RAW FROM GL_ROOT where NAME='"<<remfile.Data() <<"';";
4070      //
4071      pResult = conn->Query(myquery.str().c_str());
4072      //
4073      Row = pResult->Next();      
4074      if( !Row ){
4075        if ( strcmp(remfile.Data(),GetRootName().Data()) ){
4076          if ( IsDebug() ) printf(" No file to be removed even if option \"-remove file\" was used!!\n");
4077          return(1);
4078        };
4079        if ( IsDebug() ) printf(" No file to be removed (force mode)! \n");
4080        return(0);
4081      };
4082      //
4083      this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));
4084      this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));
4085      //
4086      this->ValidationOFF();
4087      //
4088      this->RemoveCALIBS();
4089      //
4090      this->RemoveRUNS();
4091      //
4092      this->RemoveFILES();
4093      //
4094      this->SetID_ROOT(0);
4095      this->SetID_RAW(0);
4096      //
4097      return(0);
4098    };
4099    
4100    /**
4101     *
4102     * Set validation bit to zero for runs following the removing file till
4103     * 1) a run with TRK_CALIB_USED=140
4104     * 2) a run with VALIDATION = 0
4105     * 3) the next calibration
4106     *
4107     **/
4108    void PamelaDBOperations::ValidationOFF(){
4109      TSQLResult *pResult;
4110      TSQLRow *Row;
4111      stringstream myquery;
4112      Int_t unv = 0;
4113      //select ID from GL_RUN where RUNHEADER_TIME>=1152671382 AND (VALIDATION=0 OR TRK_CALIB_USED=104) order by RUNHEADER_TIME asc limit 1;
4114      myquery.str("");
4115      myquery << " SELECT MAX(RUNTRAILER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
4116      //
4117      pResult = conn->Query(myquery.str().c_str());
4118      //
4119      Row = pResult->Next();      
4120      if( !Row->GetField(0) ){
4121        //
4122        if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
4123        //
4124      } else {  
4125        //
4126        UInt_t runhtime = (UInt_t)atoll(Row->GetField(0));
4127        UInt_t caltime = 0;
4128        //
4129        myquery.str("");
4130        myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
4131        myquery << " order by FROM_TIME asc limit 1;";
4132        //
4133        if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4134        //
4135        //
4136        delete pResult;
4137        pResult = conn->Query(myquery.str().c_str());
4138        //
4139        Row = pResult->Next();      
4140        if( !Row ){
4141          caltime = runhtime;
4142        } else {
4143          caltime = (UInt_t)atoll(Row->GetField(0));
4144        };
4145        //
4146        myquery.str("");
4147        myquery << " SELECT ID,RUNHEADER_TIME from GL_RUN where RUNHEADER_TIME>="<< runhtime <<" AND (VALIDATION=0 OR TRK_CALIB_USED=104 OR RUNHEADER_TIME>" ;
4148        myquery << caltime << ") order by RUNHEADER_TIME asc LIMIT 1";
4149        //
4150        if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4151        //
4152        pResult = conn->Query(myquery.str().c_str());
4153        //
4154        Row = pResult->Next();      
4155        if( !Row ){
4156          //
4157          if ( IsDebug() ) printf(" NO RUN NEED TO BE UNVALIDATED \n");
4158          //
4159        } else {
4160          myquery.str("");
4161          myquery << " SELECT ID from GL_RUN where RUNHEADER_TIME<"<< Row->GetField(1) <<" AND ";
4162          myquery << " RUNHEADER_TIME>=" <<runhtime;
4163          myquery << " order by RUNHEADER_TIME asc;";
4164          //
4165          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4166          //
4167          pResult = conn->Query(myquery.str().c_str());
4168          //
4169          Row = pResult->Next();  
4170          while ( Row ){
4171            //      
4172            unv++;
4173            this->assignVALIDATION((UInt_t)atoll(Row->GetField(0)), false);
4174            Row = pResult->Next();  
4175            //
4176          };
4177        };
4178      };
4179      if ( IsDebug() ) printf(" %i runs have been unvalidated \n",unv);
4180    };
4181    
4182    /**
4183     *
4184     * Rearrange GL_RUN table and remove runs
4185     *
4186     **/
4187    void PamelaDBOperations::RemoveRUNS(){
4188      TSQLResult *pResult;
4189      TSQLRow *Row;
4190      stringstream myquery;
4191      UInt_t drun = 0;
4192      GL_RUN *delrun = new GL_RUN();
4193      //
4194      myquery.str("");
4195      myquery << " SELECT ID FROM GL_RUN where ID_RUN_FRAG=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4196      //
4197      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4198      //
4199      pResult = conn->Query(myquery.str().c_str());
4200      //
4201      Row = pResult->Next();    
4202      //
4203      //
4204      if ( !Row ){
4205        if ( IsDebug() ) printf(" No run with ID_RUN_FRAG=0 belonged to this file \n");
4206      } else {
4207        if ( IsDebug() ) printf(" Deleting run from GL_RUN table \n");    
4208        while ( Row ){
4209          delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
4210          if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(0)));
4211          drun++;
4212          Row = pResult->Next();    
4213        };
4214      };
4215      //
4216      //
4217      myquery.str("");
4218      myquery << " SELECT ID,ID_RUN_FRAG FROM GL_RUN where ID_RUN_FRAG!=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4219      //
4220      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4221      //
4222      pResult = conn->Query(myquery.str().c_str());
4223      //
4224      Row = pResult->Next();    
4225      //
4226      if ( !Row ){
4227        if ( IsDebug() ) printf(" No run with ID_RUN_FRAG!=0 belonged to this file \n");
4228      } else {
4229        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN table \n");    
4230        while ( Row ){
4231          if ( IsDebug() ) printf(" restore run %i \n",(UInt_t)atoll(Row->GetField(1)));
4232          delrun->RestoreRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN_FRAGMENTS");
4233          if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(1)));
4234          delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN");
4235          if ( (UInt_t)atoll(Row->GetField(1)) != (UInt_t)atoll(Row->GetField(0)) ){
4236            if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(0)));
4237            delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
4238          };
4239          drun++;
4240          Row = pResult->Next();    
4241        };
4242      };
4243      //
4244      if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN table \n",drun);    
4245      //
4246      //
4247      //
4248      drun = 0;
4249      //
4250      myquery.str("");
4251      myquery << " SELECT ID_TRASH FROM GL_RUN_TRASH where BELONGED_TO='GL_RUN_FRAGMENTS' AND ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4252      //
4253      pResult = conn->Query(myquery.str().c_str());
4254      //
4255      Row = pResult->Next();    
4256      //
4257      if ( !Row ){
4258        if ( IsDebug() ) printf(" No run from GL_RUN_FRAGMENTS table in the trash table for this file \n");
4259      } else {
4260        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_TRASH table \n");    
4261        while ( Row ){
4262          if ( IsDebug() ) printf(" del run idtrash %i \n",(UInt_t)atoll(Row->GetField(0)));
4263          myquery.str("");
4264          myquery << " DELETE FROM GL_RUN_TRASH where ID_TRASH=" << Row->GetField(0) <<";";      
4265          conn->Query(myquery.str().c_str());
4266          drun++;
4267          Row = pResult->Next();    
4268        };
4269      };
4270      //  
4271      if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN_TRASH table \n",drun);    
4272      //
4273      //
4274      //
4275      drun = 0;
4276      //
4277      myquery.str("");
4278      myquery << " SELECT ID FROM GL_RUN_FRAGMENTS where ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4279      //
4280      pResult = conn->Query(myquery.str().c_str());
4281      //
4282      Row = pResult->Next();    
4283      //
4284      if ( !Row ){
4285        if ( IsDebug() ) printf(" No run in the GL_RUN_FRAGMENTS table for this file \n");
4286      } else {
4287        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_FRAGMENTS table \n");    
4288        while ( Row ){
4289          if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(0)));
4290          myquery.str("");
4291          myquery << " DELETE FROM GL_RUN_FRAGMENTS where ID=" << Row->GetField(0) <<";";
4292          conn->Query(myquery.str().c_str());
4293          drun++;
4294          Row = pResult->Next();    
4295        };
4296      };
4297      //  
4298      if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN_FRAGMENTS table \n",drun);    
4299      //
4300      //
4301      //
4302      delete delrun;
4303      //
4304    };
4305    
4306    
4307    /**
4308     *
4309     * Rearrange calibration tables
4310     *
4311     **/
4312    void PamelaDBOperations::RemoveFILES(){
4313      stringstream myquery;
4314      //
4315      myquery.str("");
4316      myquery << " DELETE FROM GL_RAW WHERE ID=" <<this->GetID_RAW() <<";";
4317      //
4318      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4319      //
4320      conn->Query(myquery.str().c_str());
4321      //
4322    };
4323    
4324    /**
4325     *
4326     * Rearrange calibration tables
4327     *
4328     **/
4329    void PamelaDBOperations::RemoveCALIBS(){
4330      TSQLResult *pResult;
4331      TSQLRow *Row;
4332      stringstream myquery;
4333      //  
4334      //
4335      // Calorimeter
4336      //
4337      for (Int_t section = 0; section < 4; section++){
4338        myquery.str("");
4339        myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_CALO_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<" AND ";
4340        myquery << " SECTION=" << section << ";";
4341        //
4342        pResult = conn->Query(myquery.str().c_str());
4343        //
4344        Row = pResult->Next();      
4345        if( !Row->GetField(0) || !Row->GetField(1) ){
4346          //
4347          if ( IsDebug() ) printf(" NO CALO CALIBRATION SECTION %i ASSOCIATED TO THIS FILE! \n",section);
4348          //
4349        } else {
4350          //
4351          myquery.str("");
4352          myquery << " UPDATE GL_CALO_CALIB SET TO_TIME=" << Row->GetField(1);
4353          myquery << " WHERE TO_TIME="<< Row->GetField(0) << " AND ";
4354          myquery << " SECTION=" << section << ";";
4355          //
4356          pResult = conn->Query(myquery.str().c_str());
4357          //
4358          if( !pResult ){
4359            //
4360            if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
4361            //
4362            throw -4;
4363            //
4364          };
4365          //
4366        };
4367      };
4368      myquery.str("");
4369      myquery << " DELETE FROM GL_CALO_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4370      //
4371      pResult = conn->Query(myquery.str().c_str());
4372      //
4373      if( !pResult ){
4374        //
4375        if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
4376        //
4377        throw -4;
4378        //
4379      };
4380      //
4381      // Tracker
4382      //
4383      myquery.str("");
4384      myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_TRK_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
4385      //
4386      pResult = conn->Query(myquery.str().c_str());
4387      //
4388      Row = pResult->Next();      
4389      if( !Row->GetField(0) || !Row->GetField(1) ){
4390        //
4391        if ( IsDebug() ) printf(" NO TRK CALIBRATION ASSOCIATED TO THIS FILE! \n");
4392        //
4393      } else {
4394        //
4395        myquery.str("");
4396        myquery << " UPDATE GL_TRK_CALIB SET TO_TIME=" << Row->GetField(1);
4397        myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
4398        //
4399        pResult = conn->Query(myquery.str().c_str());
4400        //
4401        if( !pResult ){
4402          //
4403          if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
4404          //
4405          throw -4;
4406          //
4407        };
4408        //
4409        myquery.str("");
4410        myquery << " DELETE FROM GL_TRK_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4411        //
4412        pResult = conn->Query(myquery.str().c_str());
4413        //
4414        if( !pResult ){
4415          //
4416          if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
4417          //
4418          throw -4;
4419          //
4420        };
4421      };
4422      //
4423      //
4424      // S4
4425      //
4426      myquery.str("");
4427      myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_S4_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
4428      //
4429      pResult = conn->Query(myquery.str().c_str());
4430      //
4431      Row = pResult->Next();      
4432      if( !Row->GetField(0) || !Row->GetField(1) ){
4433        //
4434        if ( IsDebug() ) printf(" NO S4 CALIBRATION ASSOCIATED TO THIS FILE! \n");
4435        //
4436      } else {
4437        //
4438        myquery.str("");
4439        myquery << " UPDATE GL_S4_CALIB SET TO_TIME=" << Row->GetField(1);
4440        myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
4441        //
4442        pResult = conn->Query(myquery.str().c_str());
4443        //
4444        if( !pResult ){
4445          //
4446          if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
4447          //
4448          throw -4;
4449          //
4450        };
4451        //
4452        myquery.str("");
4453        myquery << " DELETE FROM GL_S4_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4454        //
4455        pResult = conn->Query(myquery.str().c_str());
4456        //
4457        if( !pResult ){
4458          //
4459          if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
4460          //
4461          throw -4;
4462          //
4463        };
4464        //
4465      };
4466    };
4467    
4468    /**
4469     *
4470     * Rearrange calibration tables
4471     *
4472     **/
4473    UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh ){
4474    
4475        Int_t vorder[]={5,5,3,3,4,4,2,2,1,1,0,0};
4476        UInt_t timeaftercalib=120000; //2000;
4477    //  ----------
4478    //  Check CRCs
4479    //  ----------
4480        for(Int_t ipkt=0; ipkt<6; ipkt++){
4481            if( caltrk->crc_hcal[ipkt] )return 0; // :-(
4482            for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] )return 0; // :-(
4483        }
4484    //  -----------------------
4485    //  Check missing packets:
4486    //  -----------------------
4487    //    Readout order:
4488    //    ------------------
4489    //    DSP   packet board
4490    //    ------------------
4491    //    12    0      1
4492    //    10    1      1
4493    //     8    2      1
4494    //     4    3      1
4495    //     6    4      1
4496    //     2    5      1
4497    //    ------------------
4498    //    11    0      2
4499    //     9    1      2
4500    //     7    2      2
4501    //     3    3      2
4502    //     5    4      2
4503    //     1    5      2
4504    //    ------------------
4505    //  -------------------------------------------------
4506    //  Check if it is first or second calibration packet
4507    //  -------------------------------------------------
4508        UInt_t build=0;
4509        TString classname = caltrk->GetName();
4510        UInt_t base=0;
4511        UInt_t mask=0;
4512        if(classname.Contains("CalibTrk1Event")){
4513            base=12;
4514            mask=0x03F000;
4515        }
4516        if(classname.Contains("CalibTrk2Event")){
4517            base=18;
4518            mask=0xFC0000;
4519        }
4520    //  -------------------------------------------------
4521    //  Count number of packets and set build variable
4522    //  -------------------------------------------------
4523        Int_t  npkts=0;
4524        for(Int_t ipkt=0; ipkt<6; ipkt++){
4525            if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
4526                npkts++;
4527                build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );
4528            }
4529        }
4530    //    if( npkts==6 )return 1; // :-)
4531    
4532    //    cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime()<<endl;
4533    
4534    //  -----------------------------------------------
4535    //  If missing packets: check the acq configuration
4536    //  (some DSPs might be excluded from acquisition)
4537    //  -----------------------------------------------
4538    
4539    //  -----------------------------------------------
4540    //  retrieve the first run header after calib
4541    //  -----------------------------------------------
4542         PacketType *pctp;
4543         EventCounter *cod;
4544         cod = eh->GetCounter();
4545         Int_t irun = cod->Get(pctp->RunHeader);
4546         TTree *rh=(TTree*)file->Get("RunHeader");
4547         if ( !rh || rh->IsZombie() ) throw -17;
4548         if( rh->GetEntries() == irun ){
4549              if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (1)  -- cannot validate :-( "<<endl;
4550             return 0; // :-(
4551         }
4552    
4553         RunHeaderEvent *run  = 0;
4554         EventHeader    *hrun = 0;
4555         rh->SetBranchAddress("RunHeader", &run);
4556         rh->SetBranchAddress("Header", &hrun);
4557         rh->GetEntry(irun);
4558    //     cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime() << " Run " << hrun->GetPscuHeader()->GetOrbitalTime() <<endl;
4559    
4560         if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){
4561              if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (2) -- cannot validate :-( "<<endl;
4562             return 0; // :-(
4563         }
4564        
4565         if( !run->RM_ACQ_AFTER_CALIB ){
4566              if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) RM_ACQ_AFTER_CALIB=0    -- cannot validate :-( "<<endl;
4567             return 0; // :-(
4568         }
4569    
4570         UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());
4571         if( dtime > timeaftercalib ){
4572             if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;
4573             return 0; // :-(
4574         }
4575        
4576    
4577    
4578         if( (run->ACQ_BUILD_INFO & mask) != build ){
4579             if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) ACQ_BUILD_INFO= >>> "<<hex << (run->ACQ_BUILD_INFO&mask) << " != "<< build << dec<<endl;
4580             return 0; // :-(
4581         }
4582         return 1; // :-)
4583    
4584    }
4585    
4586    /**
4587     *
4588     * Check the DB (only for overlapping runs at the moment)
4589     *
4590     **/
4591    UInt_t PamelaDBOperations::Check(){
4592      //
4593      UInt_t test = 0;
4594      //
4595      UInt_t thisrht = 0;
4596      UInt_t thisrtt = 0;
4597      UInt_t thisid = 0;
4598      UInt_t prevrht = 0;
4599      UInt_t prevrtt = 0;
4600      UInt_t previd = 0;
4601      //
4602      UInt_t prevl0id = 0;
4603      UInt_t thisl0id = 0;
4604      //
4605      stringstream oss;
4606      TSQLResult *result = 0;
4607      TSQLRow    *row    = 0;
4608      TSQLResult *result2 = 0;
4609      TSQLRow    *row2    = 0;
4610      oss.str("");
4611      oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN order by RUNHEADER_TIME asc;";
4612      //  oss << "SELECT ID,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN where ID>10170 and ID<10190 order by RUNHEADER_TIME asc;";
4613      result = conn->Query(oss.str().c_str());
4614      //
4615      if ( !result ) throw -4;;
4616      //
4617      row = result->Next();
4618      //
4619      while ( row ){
4620        thisid = (UInt_t)atoll(row->GetField(0));
4621        thisl0id = (UInt_t)atoll(row->GetField(1));
4622        thisrht = (UInt_t)atoll(row->GetField(2));
4623        thisrtt = (UInt_t)atoll(row->GetField(3));
4624        //
4625        //    if ( thisrht < prevrtt || thisrtt < prevrht || thisrht > thisrtt && !(!prevrht && !prevrtt &&!previd) ){
4626        //    if ( (thisrht < prevrtt || thisrtt < prevrht || thisrht > thisrtt) && (thisrht != prevrht) ){
4627        if ( (thisrht < prevrtt) && (thisrht != prevrht) ){
4628          if ( IsDebug() ) printf(" IDprev %u ID %u    prevrht %u prevrtt %u  thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
4629          printf(" CHECK n.1 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrht-prevrtt),previd,thisid);
4630          TString prevf = "";
4631          TString thisf = "";
4632          oss.str("");
4633          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
4634          result2 = conn->Query(oss.str().c_str());
4635          if ( !result2 ) throw -4;;
4636          row2 = result2->Next();
4637          prevf = (TString)row2->GetField(0);
4638          oss.str("");
4639          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
4640          result2 = conn->Query(oss.str().c_str());
4641          if ( !result2 ) throw -4;;
4642          row2 = result2->Next();
4643          thisf = (TString)row2->GetField(0);
4644          if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
4645          test = 1;
4646        };
4647        //
4648        if ( (thisrtt < prevrht) && (thisrht != prevrht) ){
4649          if ( IsDebug() ) printf(" IDprev %u ID %u    prevrht %u prevrtt %u  thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
4650          printf(" CHECK n.2 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrtt-prevrht),previd,thisid);
4651          TString prevf = "";
4652          TString thisf = "";
4653          oss.str("");
4654          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
4655          result2 = conn->Query(oss.str().c_str());
4656          if ( !result2 ) throw -4;;
4657          row2 = result2->Next();
4658          prevf = (TString)row2->GetField(0);
4659          oss.str("");
4660          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
4661          result2 = conn->Query(oss.str().c_str());
4662          if ( !result2 ) throw -4;;
4663          row2 = result2->Next();
4664          thisf = (TString)row2->GetField(0);
4665          if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
4666          test = 1;
4667        };
4668        //
4669        if ( (thisrht > thisrtt) && (thisrht != prevrht) ){
4670          if ( IsDebug() ) printf(" IDprev %u ID %u    prevrht %u prevrtt %u  thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
4671          printf(" CHECK n.3 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrht-thisrtt),previd,thisid);
4672          TString prevf = "";
4673          TString thisf = "";
4674          oss.str("");
4675          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
4676          result2 = conn->Query(oss.str().c_str());
4677          if ( !result2 ) throw -4;;
4678          row2 = result2->Next();
4679          prevf = (TString)row2->GetField(0);
4680          oss.str("");
4681          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
4682          result2 = conn->Query(oss.str().c_str());
4683          if ( !result2 ) throw -4;;
4684          row2 = result2->Next();
4685          thisf = (TString)row2->GetField(0);
4686          if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
4687          test = 1;
4688        };
4689    
4690        //
4691        prevrht = thisrht;
4692        prevrtt = thisrtt;
4693        previd = thisid;
4694        prevl0id = thisl0id;
4695        row = result->Next();
4696      };
4697      //
4698      return(test);
4699      //
4700  };  };

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

  ViewVC Help
Powered by ViewVC 1.1.23