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

Diff of /YodaProfiler/src/PamelaDBOperations.cpp

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

revision 1.9 by mocchiut, Tue Sep 12 07:28:46 2006 UTC revision 1.54 by mocchiut, Wed Feb 6 12:22:02 2008 UTC
# Line 14  Line 14 
14  #include <TSQLRow.h>  #include <TSQLRow.h>
15  #include <TTree.h>  #include <TTree.h>
16  #include <TGraph.h>  #include <TGraph.h>
17  #include <TDatime.h>  #include <TTimeStamp.h>
18  #include <TF1.h>  #include <TF1.h>
19  //  //
20  #include <EventHeader.h>  #include <EventHeader.h>
# Line 24  Line 24 
24  #include <RunHeaderEvent.h>  #include <RunHeaderEvent.h>
25  #include <RunTrailerEvent.h>  #include <RunTrailerEvent.h>
26  #include <CalibCalPedEvent.h>  #include <CalibCalPedEvent.h>
27    #include <CalibCalPulse1Event.h>
28    #include <CalibCalPulse2Event.h>
29  #include <CalibS4Event.h>  #include <CalibS4Event.h>
30  #include <CalibTrk1Event.h>  #include <CalibTrk1Event.h>
31  #include <CalibTrk2Event.h>  #include <CalibTrk2Event.h>
# Line 31  Line 33 
33  #include <varDump/VarDumpRecord.h>  #include <varDump/VarDumpRecord.h>
34  #include <physics/S4/S4Event.h>  #include <physics/S4/S4Event.h>
35  //  //
36    #include <sgp4.h>
37    
38  #include <PamelaDBOperations.h>  #include <PamelaDBOperations.h>
39  //  //
40  using namespace std;  using namespace std;
41  using namespace pamela;  using namespace pamela;
42    
43    // Some function to work with cTle stuff.
44    bool compTLE(cTle* tle1, cTle *tle2);
45    float getTleJulian(cTle *);
46    string getTleDatetime(cTle*);
47    
48  /**  /**
49   * Constructor.   * Constructor.
50   * @param host         hostname for the SQL connection.   * @param host         hostname for the SQL connection.
# Line 47  using namespace pamela; Line 56  using namespace pamela;
56   * @param obt0         file obt0.   * @param obt0         file obt0.
57   * @param tsync        file timesync.   * @param tsync        file timesync.
58   * @param debug        debug flag.   * @param debug        debug flag.
59     * @param tlefilename  ascii file with TLE 3 line elements.
60   */   */
61  PamelaDBOperations::PamelaDBOperations(TString host, TString user, TString password, TString filerawname, TString filerootname, UInt_t boot, UInt_t tsync, UInt_t obt0, Bool_t debug){  PamelaDBOperations::PamelaDBOperations(TString host, TString user, TString password, TString filerawname, TString filerootname, UInt_t boot, UInt_t tsync, UInt_t obt0, Bool_t debug, TString tlefilename, UInt_t dwinput, Bool_t staticp, Bool_t gpamela){
62    //    //
63      STATIC=false;
64      if ( staticp ) STATIC=true;
65    //    //
66    SetConnection(host,user,password);    SetConnection(host,user,password);
67    //    //
# Line 58  PamelaDBOperations::PamelaDBOperations(T Line 70  PamelaDBOperations::PamelaDBOperations(T
70    glrun = new GL_RUN();    glrun = new GL_RUN();
71    //    //
72    if ( !boot ) SetNOBOOT(false);    if ( !boot ) SetNOBOOT(false);
73    SetBOOTnumber(boot);    SetTsync(tsync,gpamela);
74    SetTsync(tsync);    SetBOOTnumber(boot,gpamela);
75    SetObt0(obt0);    SetObt0(obt0);
76    //    //
77      SetTLEPath(tlefilename);
78      //
79    //    //
80    INSERT_RAW =!filerawname.IsNull();    INSERT_RAW =!filerawname.IsNull();
81    if(INSERT_RAW)SetRawName(filerawname);    if(INSERT_RAW)SetRawName(filerawname);
82    //    //
83    INSERT_ROOT = !filerootname.IsNull();    INSERT_ROOT = !filerootname.IsNull();
84    if( INSERT_ROOT ){    if( INSERT_ROOT ){
85        this->SetRootName(filerootname);
86        this->SetOrbitNo(dwinput);
87      file = TFile::Open(this->GetRootName().Data());      file = TFile::Open(this->GetRootName().Data());
88      //    if ( !file ) INSERT_ROOT = false;    } else {
89        this->SetRootName("");
90    };    };
   //  this->OpenFile();  
91    //    //
92    this->SetID_RAW(0);    this->SetID_RAW(0);
93    this->SetID_ROOT(0);    this->SetID_ROOT(0);
# Line 100  void PamelaDBOperations::Close(){ Line 116  void PamelaDBOperations::Close(){
116  //  //
117  void PamelaDBOperations::CheckValidate(Long64_t olderthan){  void PamelaDBOperations::CheckValidate(Long64_t olderthan){
118    clean_time = new TDatime();    clean_time = new TDatime();
119      //
120    if(olderthan >= 0){    if(olderthan >= 0){
121      VALIDATE = true;      VALIDATE = true;
122      UInt_t timelim = 0;      UInt_t timelim = 0;
123      timelim =  (UInt_t)clean_time->Convert() - olderthan;      timelim =  (UInt_t)clean_time->Convert(true) - olderthan;
124      clean_time->Set(timelim,false);      clean_time->Set(timelim,false);
125    };    };
126  };  };
# Line 115  void PamelaDBOperations::CheckValidate(L Line 132  void PamelaDBOperations::CheckValidate(L
132   * @param password     password for the SQL connection.   * @param password     password for the SQL connection.
133   */   */
134  void PamelaDBOperations::SetConnection(TString host, TString user, TString password){  void PamelaDBOperations::SetConnection(TString host, TString user, TString password){
135      if ( IsDebug() ) printf(" Connecting using host = %s user = %s password = %s \n",host.Data(),user.Data(),password.Data());
136    conn = TSQLServer::Connect(host.Data(),user.Data(),password.Data());    conn = TSQLServer::Connect(host.Data(),user.Data(),password.Data());
137  };  };
138    
# Line 143  void PamelaDBOperations::SetDebugFlag(Bo Line 161  void PamelaDBOperations::SetDebugFlag(Bo
161  };  };
162    
163  /**  /**
164     * Set the autoboot flag
165     *
166     */
167    void PamelaDBOperations::SetAutoBoot(Bool_t dbg){
168      AUTOBOOT = dbg;
169    };
170    
171    /**
172     * Set the pedantic flag
173     *
174     */
175    void PamelaDBOperations::SetPedantic(Bool_t dbg){
176      PEDANTIC = dbg;
177    };
178    
179    /**
180     * Set the nofrag flag
181     *
182     */
183    void PamelaDBOperations::SetNoFrag(Bool_t nf){
184      NOFRAG = nf;
185    };
186    
187    /**
188   * Store the BOOT number of the RAW file.   * Store the BOOT number of the RAW file.
189   * @param boot    BOOT number of the RAW file   * @param boot    BOOT number of the RAW file
190   */   */
191  void PamelaDBOperations::SetBOOTnumber(UInt_t boot){  void PamelaDBOperations::SetBOOTnumber(UInt_t boot){
192      this->SetBOOTnumber(boot,false);
193    };
194    
195    /**
196     * Store the BOOT number of the RAW file.
197     * @param boot    BOOT number of the RAW file
198     */
199    void PamelaDBOperations::SetBOOTnumber(UInt_t boot, Bool_t gpamela){
200    BOOTNO=boot;    BOOTNO=boot;
201      if ( gpamela ){
202        stringstream oss;
203        TSQLResult *result = 0;
204        TSQLRow    *row    = 0;    
205        if ( !boot ){
206          //
207          BOOTNO = 1;
208          //
209          // look in the DB for the last timesync and the last run
210          //
211          oss.str("");
212          oss << "SELECT BOOT_NUMBER FROM GL_RUN order by RUNHEADER_TIME desc limit 1;";
213          result = conn->Query(oss.str().c_str());
214          if ( result ){
215            row = result->Next();
216            if ( row ){
217              BOOTNO = (UInt_t)atoll(row->GetField(0)) + 1;
218            };
219          };
220        };
221      };
222  };  };
223    
224  /**  /**
# Line 155  void PamelaDBOperations::SetBOOTnumber(U Line 226  void PamelaDBOperations::SetBOOTnumber(U
226   * @param boot    time sync   * @param boot    time sync
227   */   */
228  void PamelaDBOperations::SetTsync(UInt_t ts){  void PamelaDBOperations::SetTsync(UInt_t ts){
229      this->SetTsync(ts,false);
230    };
231    
232    /**
233     * Store the time sync of the RAW file.
234     * @param boot    time sync
235     */
236    void PamelaDBOperations::SetTsync(UInt_t ts, Bool_t gpamela){
237      //
238      // if not gpamela or given tsync file set ts
239      //
240    tsync=ts;    tsync=ts;
241      if ( gpamela ){
242        stringstream oss;
243        TSQLResult *result = 0;
244        TSQLRow    *row    = 0;    
245        TSQLResult *result2 = 0;
246        TSQLRow    *row2    = 0;    
247        if ( !ts ){
248          //
249          tsync = 1;
250          //
251          // look in the DB for the last timesync and the last run
252          //
253          oss.str("");
254          oss << "SELECT TIMESYNC FROM GL_TIMESYNC order by TIMESYNC desc limit 1;";
255          result = conn->Query(oss.str().c_str());
256          if ( result ){
257            row = result->Next();
258            if ( row ){
259              tsync = (UInt_t)atoll(row->GetField(0)) + 1;
260              oss.str("");
261              oss << "SELECT (RUNTRAILER_TIME-RUNHEADER_TIME) FROM GL_RUN order by RUNHEADER_TIME desc limit 1;";
262              result2 = conn->Query(oss.str().c_str());
263              if ( result2 ){
264                row2 = result2->Next();
265                if ( row2 ){
266                  tsync += (UInt_t)atoll(row2->GetField(0));
267                };
268              }
269            };
270          };
271        };
272      };
273  };  };
274    
275  /**  /**
# Line 183  void PamelaDBOperations::SetRootName(TSt Line 297  void PamelaDBOperations::SetRootName(TSt
297  };  };
298    
299  /**  /**
300     * Store the downlink orbit number from filename.
301     */
302    void PamelaDBOperations::SetOrbitNo(UInt_t dwinput){
303      dworbit = 0;
304      //
305      if ( dwinput ){
306        dworbit = dwinput;
307        if ( IsDebug() ) printf(" Downlink orbit given by hand: %i  \n",dworbit);
308        return;
309      };
310      //
311      TString name = this->GetRootFile();
312      Int_t nlength = name.Length();
313      if ( nlength < 5 ) return;
314      TString dwo = 0;
315      for (Int_t i = 0; i<5; i++){
316        dwo.Append(name[i],1);
317      };
318      if ( dwo.IsDigit() ){
319        dworbit = (UInt_t)dwo.Atoi();
320      } else {
321        dwo="";
322        for (Int_t i = 8; i<13; i++){
323          dwo.Append(name[i],1);
324        };    
325        if ( dwo.IsDigit() ) dworbit = (UInt_t)dwo.Atoi();
326      };
327      if ( IsDebug() ) printf(" Downlink orbit is %i (dwo = %s) \n",dworbit,dwo.Data());
328      return;
329    };
330    
331    
332    
333    /**
334   * Store the NOBOOT flag.   * Store the NOBOOT flag.
335   * @param noboot    true/false.   * @param noboot    true/false.
336   */   */
# Line 191  void PamelaDBOperations::SetNOBOOT(Bool_ Line 339  void PamelaDBOperations::SetNOBOOT(Bool_
339  };  };
340    
341  /**  /**
342     * Store path to the TLE file.
343     */
344    void PamelaDBOperations::SetTLEPath(TString str){
345      tlefilename = str;
346    };
347    
348    TString PamelaDBOperations::GetRawPath(){
349      if ( STATIC ){
350        return((TString)gSystem->DirName(filerawname.Data())+'/');
351      } else {
352        return((TString)gSystem->ExpandPathName("$PAM_RAW")+'/');
353      };
354    };
355    
356    TString PamelaDBOperations::GetRootPath(){
357      if ( STATIC ){
358        return((TString)gSystem->DirName(filerootname.Data())+'/');
359      } else {
360        return((TString)gSystem->ExpandPathName("$PAM_L0")+'/');
361      };
362    };
363    
364    /**
365   * Store the olderthan variable   * Store the olderthan variable
366   * @param olderthan   * @param olderthan
367   */   */
# Line 206  Bool_t PamelaDBOperations::SetID_RAW(){ Line 377  Bool_t PamelaDBOperations::SetID_RAW(){
377    TSQLResult *result = 0;    TSQLResult *result = 0;
378    TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
379    oss.str("");    oss.str("");
380    oss << "SELECT ID FROM GL_RAW WHERE "    if ( STATIC ){
381        << " PATH = '" << this->GetRawPath().Data() << "' AND "      oss << "SELECT ID FROM GL_RAW WHERE "
382        << " NAME = '" << this->GetRawFile().Data() << "' ";          << " PATH = '" << this->GetRawPath().Data() << "' AND "
383            << " NAME = '" << this->GetRawFile().Data() << "' ";  
384      } else {
385        oss << "SELECT ID FROM GL_RAW WHERE "
386            << " PATH = '$PAM_RAW' AND "
387            << " NAME = '" << this->GetRawFile().Data() << "' ";  
388      }
389    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
390    if ( result == NULL ) throw -4;    if ( result == NULL ) throw -4;
391    row = result->Next();    row = result->Next();
392    if ( !row ) return(false);    if ( !row ) return(false);
   delete result;  
393    id = (UInt_t)atoll(row->GetField(0));    id = (UInt_t)atoll(row->GetField(0));
394      delete result;
395    return(true);    return(true);
396  }  }
397    
# Line 239  Int_t PamelaDBOperations::SetUpperLimits Line 416  Int_t PamelaDBOperations::SetUpperLimits
416    UInt_t nevent = 0;    UInt_t nevent = 0;
417    UInt_t pktlast = 0;    UInt_t pktlast = 0;
418    UInt_t obtlast = 0;    UInt_t obtlast = 0;
419    UInt_t t_pktlast = 0;    Long64_t t_pktlast = 0LL;
420    UInt_t t_obtlast = 0;    //  UInt_t t_obtlast = 0;
421    UInt_t upperpkt2 = 0;    Long64_t t_obtlast = 0LL;
422    ULong64_t upperobt2 = 0;    Long64_t upperpkt2 = 0LL;
423      Long64_t upperobt2 = 0LL;
424    UInt_t zomp = 0;    UInt_t zomp = 0;
425    UInt_t jump = 50000; // was 5000    UInt_t jump = 50000; // was 5000
426    EventCounter *code=0;    EventCounter *code=0;
427    //    //
428    //   pcksList packetsNames;    Long64_t deltapkt = 5000LL;
429    //   pcksList::iterator Iter;    Long64_t deltaobt = 50000LL;
430    //   getPacketsNames(packetsNames);    //
431      pcksList packetsNames;
432      pcksList::iterator Iter;
433      getPacketsNames(packetsNames);
434    //    //
435    pktfirst = 0;    pktfirst = 0;
436    obtfirst = 0;    obtfirst = 0;
437      ppktfirst = 0;
438      pobtfirst = 0;
439    //    //
440    TTree *T = 0;    TTree *T = 0;
441    T = (TTree*)file->Get("Physics");    T = (TTree*)file->Get("Physics");
# Line 266  Int_t PamelaDBOperations::SetUpperLimits Line 449  Int_t PamelaDBOperations::SetUpperLimits
449    ph = eh->GetPscuHeader();    ph = eh->GetPscuHeader();
450    pktfirst = ph->GetCounter();    pktfirst = ph->GetCounter();
451    obtfirst = ph->GetOrbitalTime();      obtfirst = ph->GetOrbitalTime();  
452      ppktfirst = pktfirst;
453      pobtfirst = obtfirst;
454    //    //
455    //   code = eh->GetCounter();    code = eh->GetCounter();
456    //   UInt_t en = 0;    UInt_t en = 0;
457    //   for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){    for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
458    //     en = code->Get(GetPacketType(*Iter));      en = code->Get(GetPacketType(*Iter));
459    //     if ( en ) printf(" Packet type is %s, entries: %i \n",*Iter,en);      if ( !strcmp("CalibCalPed",*Iter) || !strcmp("CalibTrk1",*Iter) || !strcmp("CalibTrk2",*Iter) || !strcmp("CalibS4",*Iter) ){
460    //};          if ( IsDebug() ) printf(" We have a calibration before the first physic packet: packet type is %s, entries: %i \n",*Iter,en);
461          //
462          TTree *TC = 0;
463          TC = (TTree*)file->Get("CalibCalPed");
464          if ( !TC || TC->IsZombie() ) throw -16;
465          EventHeader *ehc = 0;
466          PscuHeader *phc = 0;
467          TC->SetBranchAddress("Header", &ehc);
468          TC->GetEntry(0);
469          phc = ehc->GetPscuHeader();
470          pktfirst = phc->GetCounter();
471          obtfirst = phc->GetOrbitalTime();  
472          //
473        };
474      };  
475    //    //
476    T->GetEntry(nevent-1);    T->GetEntry(nevent-1);
477    ph = eh->GetPscuHeader();    ph = eh->GetPscuHeader();
# Line 283  Int_t PamelaDBOperations::SetUpperLimits Line 482  Int_t PamelaDBOperations::SetUpperLimits
482    upperobt = OBT(obtlast);    upperobt = OBT(obtlast);
483    upperentry = nevent-1;    upperentry = nevent-1;
484    //    //
485    if ( IsDebug() ) printf(" First entries are: OBT %llu pkt_num %i \n",obtfirst,pktfirst);    if ( IsDebug() ) printf(" First entries are: OBT %u pkt_num %u \n",obtfirst,pktfirst);
486    //    //
487    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);
488    //    //
489    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(32);
490    //    //
491    if ( !nevent ) return(2);    if ( !nevent ) return(64);
492    //    //
493    if ( nevent < 2 ) return(4);    if ( nevent < 2 ) return(128);
494      if ( nevent < jump ) jump = 1;
495      //  if ( nevent < jump ) jump = int(nevent/10);
496      //  if ( !jump ) jump = 1;
497    //    //
498    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 ){
499        //
500        if ( IsDebug() ) printf(" starting jump %i \n",jump);
501        if ( PEDANTIC ) throw -66;
502      // go back      // go back
503      zomp = nevent - 2;      zomp = nevent - 2;
504      //      //
# Line 315  Int_t PamelaDBOperations::SetUpperLimits Line 520  Int_t PamelaDBOperations::SetUpperLimits
520          upperpkt2 = PKT(ph->GetCounter());          upperpkt2 = PKT(ph->GetCounter());
521          upperobt2 = OBT(ph->GetOrbitalTime());          upperobt2 = OBT(ph->GetOrbitalTime());
522          //          //
523          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) ){
524              if ( IsDebug() ) printf(" .-. upperpkt2 %lld upperobt2 %lld \n",upperpkt2,upperobt2);  
525              if ( IsDebug() ) printf(" .-. upperpkt %lld t_pktlast %lld upperobt %lld t_obtlast %lld \n",upperpkt,t_pktlast,upperobt,t_obtlast);    
526              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);    
527              throw -13;    
528            };
529          //          //
530          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 ){
531            zomp = i + jump + 1;            zomp = i + jump + 1;
532            if ( zomp > nevent-2 ) zomp = nevent - 2;            if ( zomp > nevent-2 ) zomp = nevent - 2;
533            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 %u upperobt %lld obtlast %u last entry is %i \n",jump,zomp,upperpkt,pktlast,upperobt,obtlast,i);
534            break;            break;
535          };          };
536          //          //
# Line 355  Int_t PamelaDBOperations::SetUpperLimits Line 565  Int_t PamelaDBOperations::SetUpperLimits
565    //    //
566    rhev = rh->GetEntries();    rhev = rh->GetEntries();
567    rtev = rt->GetEntries();    rtev = rt->GetEntries();
568    UInt_t sobtt = 0;    Long64_t sobtt = 0LL;
569    UInt_t sobth = 0;    Long64_t sobth = 0LL;
570    UInt_t spktt = 0;    Long64_t spktt = 0LL;
571    UInt_t spkth = 0;    Long64_t spkth = 0LL;
572    UInt_t pktt = 0;    Long64_t pktt = 0LL;
573    ULong64_t obtt = 0;    Long64_t obtt = 0LL;
574    UInt_t pkth = 0;    Long64_t pkth = 0LL;
575    ULong64_t obth = 0;    Long64_t obth = 0LL;
   //  
   T->GetEntry(upperentry);  
   code = eh->GetCounter();  
   Int_t lasttrail = code->Get(pctp->RunTrailer);  
   Int_t lasthead = code->Get(pctp->RunHeader);  
   if ( lasttrail < rtev ){  
     rt->GetEntry(lasttrail);  
     pht = eht->GetPscuHeader();  
     pktt = PKT(pht->GetCounter());  
     obtt = OBT(pht->GetOrbitalTime());  
   };  
   //  
   if ( lasthead < rhev ){  
     rh->GetEntry(lasthead);  
     phh = ehh->GetPscuHeader();  
     pkth = PKT(phh->GetCounter());  
     obth = OBT(phh->GetOrbitalTime());  
   };  
   //  
   if ( IsDebug() ) printf(" rhev before %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);  
   if ( pkth > upperpkt && obth > upperobt ){  
     if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %i upperp %i oh %llu uppero %llu \n",pkth,upperpkt,obth,upperobt);  
     upperpkt = pkth;  
     upperobt = obth;  
     rhev = lasthead+1;  
   } else {  
     rhev = lasthead;  
   };  
   if ( IsDebug() ) printf(" rhev after %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);  
   //  
   if ( IsDebug() ) printf(" rtev beforev %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);  
   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);  
   //  goto kikko;  
   //  
   //  
   // Check if runtrailer/runheader are within lower limits  
   //  
576    //    //
577    pkth = 0;    if ( rhev || rtev ){
578    obth = 0;  
579    spkth = 0;      T->GetEntry(upperentry);
580    sobth = 0;      code = eh->GetCounter();
581    for (Int_t k=0; k<rhev; k++){      Int_t lasttrail = code->Get(pctp->RunTrailer);
582      if ( k > 0 ){      Int_t lasthead = code->Get(pctp->RunHeader);
583        spkth = pkth;      if ( lasttrail < rtev ){
584        sobth = obth;        rt->GetEntry(lasttrail);
585      };        pht = eht->GetPscuHeader();
586      rh->GetEntry(k);        pktt = PKT(pht->GetCounter());
587      phh = ehh->GetPscuHeader();        obtt = OBT(pht->GetOrbitalTime());
588      pkth = PKT(phh->GetCounter());      };
589      obth = OBT(phh->GetOrbitalTime());      //
590      //      if ( lasthead < rhev ){
591  //    if ( IsDebug() ) printf(" k %i rhev before %i ph %u upperp %u oh %u uppero %u \n",k,rhev,pkth,spkth,obth,sobth);        rh->GetEntry(lasthead);
592      //        phh = ehh->GetPscuHeader();
593      if ( pkth < spkth && obth < sobth ){        pkth = PKT(phh->GetCounter());
594        if ( IsDebug() ) printf(" RH PROBLEMS determining the event repetition at the end of the file lasthead %i  \n",rhev);        obth = OBT(phh->GetOrbitalTime());
595        //      };
596        rhev = k-1;      //
597        rh->GetEntry(rhev);      if ( IsDebug() ) printf(" rhev before %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
598        pkth = spkth;      if ( pkth > upperpkt && obth > upperobt ){
599        obth = sobth;        if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %lld upperp %lld oh %lld uppero %lld \n",pkth,upperpkt,obth,upperobt);
600        //        upperpkt = pkth;
601        UInt_t evbefh = 0;        upperobt = obth;
602        code = ehh->GetCounter();        rhev = lasthead+1;
603        evbefh = code->Get(pctp->Physics);          } else {
604        if ( evbefh >= 0 ){        rhev = lasthead;
605          T->GetEntry(evbefh);      };
606          ph = eh->GetPscuHeader();      if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
607          t_pktlast = PKT(ph->GetCounter());      //
608          t_obtlast = OBT(ph->GetOrbitalTime());      if ( IsDebug() ) printf(" rtev beforev %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
609          if ( t_pktlast <= spkth && t_obtlast <= sobth ){ // jump      if ( pktt > upperpkt && obtt > upperobt ){
610            upperpkt = pkth;        if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %lld upperp %lld ot %lld uppero %lld \n",pktt,upperpkt,obtt,upperobt);
611            upperobt = obth;        upperpkt = pktt;
612            upperentry = evbefh-1;        upperobt = obtt;
613          } else {        rtev = lasttrail+1;
614            while ( t_pktlast > spkth && t_obtlast > sobth && evbefh < nevent ){      } else {
615              evbefh++;          rtev = lasttrail;
616              T->GetEntry(evbefh);      };
617              ph = eh->GetPscuHeader();      if ( IsDebug() ) printf(" rtev after %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
618              t_pktlast = PKT(ph->GetCounter());      //  goto kikko;
619              t_obtlast = OBT(ph->GetOrbitalTime());      //
620            };      //
621            T->GetEntry(evbefh-1);      // Check if runtrailer/runheader are within lower limits
622        //
623        //
624        pkth = 0LL;
625        obth = 0LL;
626        spkth = 0LL;
627        sobth = 0LL;
628        for (Int_t k=0; k<rhev; k++){
629          if ( k > 0 ){
630            spkth = pkth;
631            sobth = obth;
632          };
633          rh->GetEntry(k);
634          phh = ehh->GetPscuHeader();
635          pkth = PKT(phh->GetCounter());
636          obth = OBT(phh->GetOrbitalTime());
637          //
638          //    if ( IsDebug() ) printf(" k %i rhev before %i ph %u upperp %u oh %u uppero %u \n",k,rhev,pkth,spkth,obth,sobth);
639          //
640          if ( pkth < spkth && obth < sobth ){
641            if ( PEDANTIC ) throw -66;
642            if ( IsDebug() ) printf(" RH PROBLEMS determining the event repetition at the end of the file lasthead %i  \n",rhev);
643            //
644            rhev = k-1;
645            rh->GetEntry(rhev);
646            pkth = spkth;
647            obth = sobth;
648            //
649            UInt_t evbefh = 0;
650            code = ehh->GetCounter();
651            evbefh = code->Get(pctp->Physics);    
652            if ( evbefh >= 0 ){
653              T->GetEntry(evbefh);
654            ph = eh->GetPscuHeader();            ph = eh->GetPscuHeader();
655            upperpkt = PKT(ph->GetCounter());            t_pktlast = PKT(ph->GetCounter());
656            upperobt = OBT(ph->GetOrbitalTime());            t_obtlast = OBT(ph->GetOrbitalTime());
657            upperentry = evbefh-1;            if ( t_pktlast <= spkth && t_obtlast <= sobth ){ // jump
658          };                  upperpkt = pkth;
659                upperobt = obth;
660                upperentry = evbefh-1;
661              } else {
662                while ( t_pktlast > spkth && t_obtlast > sobth && evbefh < nevent ){
663                  evbefh++;
664                  T->GetEntry(evbefh);
665                  ph = eh->GetPscuHeader();
666                  t_pktlast = PKT(ph->GetCounter());
667                  t_obtlast = OBT(ph->GetOrbitalTime());
668                };
669                T->GetEntry(evbefh-1);
670                ph = eh->GetPscuHeader();
671                upperpkt = PKT(ph->GetCounter());
672                upperobt = OBT(ph->GetOrbitalTime());
673                upperentry = evbefh-1;
674              };    
675            };
676            if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
677            goto kikko0;
678        };        };
       if ( IsDebug() ) printf(" rhev after %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);  
       goto kikko0;  
     };  
   };  
  kikko0:  
   //  
   //  
   //  
   pktt = 0;  
   obtt = 0;  
   spktt = 0;  
   sobtt = 0;  
   for (Int_t k=0; k<rtev; k++){  
     if ( k > 0 ){  
       spktt = pktt;  
       sobtt = obtt;  
679      };      };
680      rt->GetEntry(k);    kikko0:
     pht = eht->GetPscuHeader();  
     pktt = PKT(pht->GetCounter());  
     obtt = OBT(pht->GetOrbitalTime());  
681      //      //
 //    if ( IsDebug() ) printf(" k %i rtev beforev %i  pt %i upperp %i ot %llu uppero %llu \n",k,rtev,pktt,spktt,obtt,sobtt);  
682      //      //
683      if ( pktt < spktt && obtt < sobtt ){      //
684        if ( IsDebug() ) printf(" RT PROBLEMS determining the event repetition at the end of the file lasttrail %i \n",rtev);      pktt = 0LL;
685        obtt = 0LL;
686        spktt = 0LL;
687        sobtt = 0LL;
688        for (Int_t k=0; k<rtev; k++){
689          if ( k > 0 ){
690            spktt = pktt;
691            sobtt = obtt;
692          };
693          rt->GetEntry(k);
694          pht = eht->GetPscuHeader();
695          pktt = PKT(pht->GetCounter());
696          obtt = OBT(pht->GetOrbitalTime());
697        //        //
698        rtev = k-1;        //    if ( IsDebug() ) printf(" k %i rtev beforev %i  pt %i upperp %i ot %llu uppero %llu \n",k,rtev,pktt,spktt,obtt,sobtt);
       rt->GetEntry(rtev);  
       pktt = spktt;  
       obtt = sobtt;  
       if ( IsDebug() ) printf(" lasttrail %i pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);  
699        //        //
700        UInt_t evbeft = 0;        if ( pktt < spktt && obtt < sobtt ){
701        code = eht->GetCounter();          if ( PEDANTIC ) throw -66;
702        evbeft = code->Get(pctp->Physics);              if ( IsDebug() ) printf(" RT PROBLEMS determining the event repetition at the end of the file lasttrail %i \n",rtev);
703        if ( evbeft >= 0 ){          //
704          T->GetEntry(evbeft);          rtev = k-1;
705          ph = eh->GetPscuHeader();          rt->GetEntry(rtev);
706          t_pktlast = PKT(ph->GetCounter());          pktt = spktt;
707          t_obtlast = OBT(ph->GetOrbitalTime());          obtt = sobtt;
708          if ( t_pktlast <= spktt && t_obtlast <= sobtt ){ // jump          if ( IsDebug() ) printf(" lasttrail %i pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
709            upperpkt = pktt;          //
710            upperobt = obtt;          UInt_t evbeft = 0;
711            upperentry = evbeft-1;          code = eht->GetCounter();
712          } else {          evbeft = code->Get(pctp->Physics);    
713            while ( t_pktlast > spktt && t_obtlast > sobtt && evbeft < nevent ){          if ( evbeft >= 0 ){
714              evbeft++;              T->GetEntry(evbeft);
715              T->GetEntry(evbeft);            ph = eh->GetPscuHeader();
716              t_pktlast = PKT(ph->GetCounter());
717              t_obtlast = OBT(ph->GetOrbitalTime());
718              if ( t_pktlast <= spktt && t_obtlast <= sobtt ){ // jump
719                upperpkt = pktt;
720                upperobt = obtt;
721                upperentry = evbeft-1;
722              } else {
723                while ( t_pktlast > spktt && t_obtlast > sobtt && evbeft < nevent ){
724                  evbeft++;
725                  T->GetEntry(evbeft);
726                  ph = eh->GetPscuHeader();
727                  t_pktlast = PKT(ph->GetCounter());
728                  t_obtlast = OBT(ph->GetOrbitalTime());
729                };
730                T->GetEntry(evbeft-1);
731              ph = eh->GetPscuHeader();              ph = eh->GetPscuHeader();
732              t_pktlast = PKT(ph->GetCounter());              upperpkt = PKT(ph->GetCounter());
733              t_obtlast = OBT(ph->GetOrbitalTime());              upperobt = OBT(ph->GetOrbitalTime());
734                upperentry = evbeft-1;
735            };            };
           T->GetEntry(evbeft-1);  
           ph = eh->GetPscuHeader();  
           upperpkt = PKT(ph->GetCounter());  
           upperobt = OBT(ph->GetOrbitalTime());  
           upperentry = evbeft-1;  
736          };          };
737            if ( IsDebug() ) printf(" rtev after %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
738            goto kikko;
739            //      break;
740            //
741        };        };
742        if ( IsDebug() ) printf(" rtev after %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);        //  
743        goto kikko;      };
744        //      break;      //
745        //    kikko:
746        //
747        T->GetEntry(upperentry);
748        code = eh->GetCounter();
749        lasttrail = code->Get(pctp->RunTrailer);
750        lasthead = code->Get(pctp->RunHeader);
751        if ( lasttrail < rtev ){
752          rt->GetEntry(lasttrail);
753          pht = eht->GetPscuHeader();
754          pktt = PKT(pht->GetCounter());
755          obtt = OBT(pht->GetOrbitalTime());
756        };
757        //
758        if ( lasthead < rhev ){
759          rh->GetEntry(lasthead);
760          phh = ehh->GetPscuHeader();
761          pkth = PKT(phh->GetCounter());
762          obth = OBT(phh->GetOrbitalTime());
763        };
764        //
765        if ( IsDebug() ) printf(" rhev before %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
766        if ( pkth > upperpkt && obth > upperobt ){
767          if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %lld upperp %lld oh %lld uppero %lld \n",pkth,upperpkt,obth,upperobt);
768          upperpkt = pkth;
769          upperobt = obth;
770          rhev = lasthead+1;
771        } else {
772          rhev = lasthead;
773        };
774        if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
775        //
776        if ( IsDebug() ) printf(" rtev beforev %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
777        if ( pktt > upperpkt && obtt > upperobt ){
778          if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %lld upperp %lld ot %lld uppero %lld \n",pktt,upperpkt,obtt,upperobt);
779          upperpkt = pktt;
780          upperobt = obtt;
781          rtev = lasttrail+1;
782        } else {
783          rtev = lasttrail;
784      };      };
785      //        if ( IsDebug() ) printf(" rtev after %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
786        //
787    };    };
788    //    //
789   kikko:    if ( IsDebug() ) printf(" Upper limits are: OBT %lld pkt_num %lld upper entry %i \n",upperobt,upperpkt,upperentry);
790    //    //
791    T->GetEntry(upperentry);    return(0);
792    code = eh->GetCounter();  }
793    lasttrail = code->Get(pctp->RunTrailer);  
794    lasthead = code->Get(pctp->RunHeader);  /**
795    if ( lasttrail < rtev ){   *
796      rt->GetEntry(lasttrail);   * Trick to have unique RUN ID numbers even when runs are deleted and mysql deamon restarted.
797      pht = eht->GetPscuHeader();   * Entries in the _RUNID_GEN table are never deleted.
798      pktt = PKT(pht->GetCounter());   *
799      obtt = OBT(pht->GetOrbitalTime());   **/
800    };  UInt_t PamelaDBOperations::AssignRunID(){
801    //    //
802    if ( lasthead < rhev ){    TSQLResult *result = 0;
803      rh->GetEntry(lasthead);    TSQLRow *row = 0;
804      phh = ehh->GetPscuHeader();    UInt_t runid = 0;
     pkth = PKT(phh->GetCounter());  
     obth = OBT(phh->GetOrbitalTime());  
   };  
805    //    //
806    if ( IsDebug() ) printf(" rhev before %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);    stringstream   oss;
807    if ( pkth > upperpkt && obth > upperobt ){    //  
808      if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %i upperp %i oh %llu uppero %llu \n",pkth,upperpkt,obth,upperobt);    oss.str("");
809      upperpkt = pkth;    oss << "INSERT INTO _RUNID_GEN VALUES (NULL);";
810      upperobt = obth;    result = conn->Query(oss.str().c_str());
811      rhev = lasthead+1;    if ( !result ) throw -10;
812    } else {    oss.str("");
813      rhev = lasthead;    oss << "SELECT ID FROM _RUNID_GEN ORDER BY ID DESC LIMIT 1;";
814    };    result = conn->Query(oss.str().c_str());
815    if ( IsDebug() ) printf(" rhev after %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);    if ( !result ) throw -10;
816    //    //
817    if ( IsDebug() ) printf(" rtev beforev %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);    row = result->Next();
   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);  
818    //    //
819    if ( IsDebug() ) printf(" Upper limits are: OBT %llu pkt_num %i upper entry %i \n",upperobt,upperpkt,upperentry);    if ( !row ) throw -28;
820    //    //
821    return(0);    runid = (UInt_t)atoll(row->GetField(0));
822  }    //
823      return(runid);
824    };
825    
826  //  //
827  // GETTERS  // GETTERS
# Line 672  void PamelaDBOperations::CheckConnection Line 920  void PamelaDBOperations::CheckConnection
920    if( !conn ) throw -1;    if( !conn ) throw -1;
921    bool connect = conn->IsConnected();    bool connect = conn->IsConnected();
922    if( !connect ) throw -1;    if( !connect ) throw -1;
923      //
924      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());
925      //
926      if ( !dworbit && strcmp(this->GetRootName().Data(),"") ) throw -27;
927      //
928      // set DB timezone to UTC
929      //
930      stringstream oss;
931      //  
932      oss.str("");
933      oss << "SET time_zone='+0:00';";
934      TSQLResult *result = 0;
935      result = conn->Query(oss.str().c_str());
936      if ( !result ) throw -10;
937      oss.str("");
938      oss << "SET wait_timeout=173000;";
939      conn->Query(oss.str().c_str());
940      //
941  };  };
942    
943  /**  /**
944   * Return the correct packet number if we went back to zero   * Return the correct packet number if we went back to zero
945   */   */
946  UInt_t PamelaDBOperations::PKT(UInt_t pkt_num){    Long64_t PamelaDBOperations::PKT(UInt_t pkt_num){  
947    //    //
948    //  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));
949    //    //
950    if ( pkt_num < (pktfirst/2) && pktfirst > (16777214/2)  ) return((pkt_num+16777215));    if ( pkt_num < (ppktfirst/2) && ppktfirst > (16777214/2)  ){
951        if ( IsDebug() ) printf(" rise up pktnum %lld \n",(Long64_t)pkt_num+16777215LL);
952        return((Long64_t)pkt_num+16777215LL);
953      };
954    //    //
955    if ( pkt_num > pktfirst*2 && pkt_num > (16777214/2) ){    if ( pkt_num > ((Long64_t)ppktfirst*2) && pkt_num > (16777214/2) ){
956      if ( (pkt_num-16777215) < 0 ){      if ( IsDebug() ) printf(" rise down pktnum %lld \n",(Long64_t)pkt_num-16777215LL);
957        return((16777215-pkt_num));      return((Long64_t)pkt_num-16777215LL);
     } else {  
       return((pkt_num-16777215));  
     };  
958    };    };
959    //    //
960    return(pkt_num);    if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)pkt_num);
961      return((Long64_t)pkt_num);
962    //    //
963  };  };
964    
965  /**  /**
966   * Return the correct On Board Time if we went back to zero   * Return the correct On Board Time if we went back to zero
967   */   */
968  ULong64_t PamelaDBOperations::OBT(UInt_t obt){    Long64_t PamelaDBOperations::OBT(UInt_t obt){  
969    //    //
970    if ( obt < (obtfirst/2) && obtfirst > (numeric_limits<UInt_t>::max()/2) ) return((ULong64_t)(obt+numeric_limits<UInt_t>::max()));    if ( IsDebug() ) printf(" obt conversion: obt is %u obtfirst is %u  (numeric_limits<UInt_t>::max()/2) is %u  \n",obt,pobtfirst,(UInt_t)(numeric_limits<UInt_t>::max()/2));
971    //    //
972    if ( obt > (obtfirst*2) && obt > (numeric_limits<UInt_t>::max()/2) ){    if ( obt < (pobtfirst/2) && pobtfirst > (numeric_limits<UInt_t>::max()/2) ){
973      if ( (obt-numeric_limits<UInt_t>::max()) < 0  ){      if ( IsDebug() ) printf(" rise up obt %lld \n",(Long64_t)(obt+numeric_limits<UInt_t>::max()));
974        return((ULong64_t)(numeric_limits<UInt_t>::max()-obt));      return((Long64_t)(obt+numeric_limits<UInt_t>::max()));
975      } else {    };
976        return((ULong64_t)(obt-numeric_limits<UInt_t>::max()));    //
977      };    if ( obt > ((Long64_t)pobtfirst*2) && obt > (numeric_limits<UInt_t>::max()/2) ){
978        if ( IsDebug() ) printf(" pobtfirst*2 %lld \n",((Long64_t)pobtfirst*2));
979        if ( IsDebug() ) printf(" rise down pktnum %lld \n", (Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());
980        return((Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());
981    };    };
982    //    //
983    return((ULong64_t)obt);    if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)obt);
984      return((Long64_t)obt);
985  };  };
986    
987  /**  /**
# Line 825  Int_t PamelaDBOperations::insertPamelaRa Line 1096  Int_t PamelaDBOperations::insertPamelaRa
1096    if ( idr ) return(1);    if ( idr ) return(1);
1097    //    //
1098    oss.str("");    oss.str("");
1099    oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"    if ( STATIC ){
1100        << this->GetRawPath().Data() << "', '" << this->GetRawFile().Data() << "')";      oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"
1101            << this->GetRawPath().Data() << "', '" << this->GetRawFile().Data() << "')";
1102      } else {
1103        oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('$PAM_RAW', '" << this->GetRawFile().Data() << "')";
1104      };
1105    if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;    if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
1106    //    //
1107    idr =  this->SetID_RAW();    idr =  this->SetID_RAW();
# Line 845  Int_t PamelaDBOperations::insertPamelaGL Line 1120  Int_t PamelaDBOperations::insertPamelaGL
1120    TSQLResult *result = 0;    TSQLResult *result = 0;
1121    TSQLRow *row = 0;    TSQLRow *row = 0;
1122    UInt_t t0 = 0;    UInt_t t0 = 0;
1123      Int_t signal = 0;
1124      UInt_t idresof = 0;
1125      //
1126      signal = this->SetUpperLimits();
1127    //    //
1128    stringstream   oss;    stringstream   oss;
1129    //      //  
1130    if ( this->GetID_RAW() == 0 )  throw -11;    if ( this->GetID_RAW() == 0 )  throw -11;
1131    //    //
1132    oss.str("");    oss.str("");
1133    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),ID FROM GL_RESURS_OFFSET WHERE SPECIAL_FILE='"
1134        << id << " AND TO_ID_RAW >= "        << this->GetRawFile().Data() << "';";
       << id << ";";  
1135    if ( IsDebug() ) printf(" %s \n",oss.str().c_str());    if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
1136    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1137    if ( !result ) throw -10;    if ( !result ) throw -10;
1138    row = result->Next();    row = result->Next();
   if ( !row ) throw -10;  
1139    //    //
1140    t0 = (UInt_t)TDatime(row->GetField(0)).Convert();    if ( !row ){
1141        oss.str("");
1142        oss << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE),ID FROM GL_RESURS_OFFSET WHERE FROM_ORBIT< "
1143            << dworbit << " order by FROM_ORBIT desc limit 1;";
1144        if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
1145        result = conn->Query(oss.str().c_str());
1146        if ( !result ) throw -10;
1147        row = result->Next();
1148        if ( !row ) throw -10;
1149      };
1150      //
1151      idresof = (UInt_t)atoll(row->GetField(6));
1152      //
1153      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);
1154      t0 = (UInt_t)tu.GetSec();
1155      if ( IsDebug() ) printf(" t0 is %u ti is %s %s %s %s %s %s %s\n",t0,row->GetField(0),row->GetField(1),row->GetField(2),row->GetField(3),row->GetField(4),row->GetField(5),row->GetField(6));
1156      //
1157    /*    /*
1158     * Verify that the TIMESYNC have been not already processed     * Verify that the TIMESYNC have been not already processed
1159     */     */
# Line 875  Int_t PamelaDBOperations::insertPamelaGL Line 1168  Int_t PamelaDBOperations::insertPamelaGL
1168    if (result == NULL) throw -10;    if (result == NULL) throw -10;
1169    row = result->Next();    row = result->Next();
1170    if ((row != NULL) && ((UInt_t)atoll(row->GetField(0)) > 0)){    if ((row != NULL) && ((UInt_t)atoll(row->GetField(0)) > 0)){
1171        if ( IsDebug() ) printf(" found a timesync t0 is %u \n",t0);
1172      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;
1173        //
1174        tsync = (UInt_t)atoll(row->GetField(2));
1175        obt0 = (UInt_t)atoll(row->GetField(1));
1176        //
1177        if ( PEDANTIC ) throw -67;
1178      return(1);      return(1);
1179    };    };
1180    //    //
1181    TTree *T = 0;    TTree *T = 0;
   Int_t signal = 0;  
1182    //    //
1183    UInt_t nevent = 0;    UInt_t nevent = 0;
1184    UInt_t recEntries = 0;    UInt_t recEntries = 0;
# Line 932  Int_t PamelaDBOperations::insertPamelaGL Line 1230  Int_t PamelaDBOperations::insertPamelaGL
1230          //          //
1231          TYPE = 55;//224;          TYPE = 55;//224;
1232          //          //
1233            if ( IsDebug() ) printf("mcmd tsync %i tsync %u obt %u \n",i,TSYNC,OBT);
1234            //
1235          if ( TSYNC && OBT ){          if ( TSYNC && OBT ){
1236            existsts = true;            existsts = true;
1237            goto eout;            goto eout;
# Line 954  Int_t PamelaDBOperations::insertPamelaGL Line 1254  Int_t PamelaDBOperations::insertPamelaGL
1254      //      //
1255      rt->SetBranchAddress("RunTrailer", &runt);      rt->SetBranchAddress("RunTrailer", &runt);
1256      //      //
1257      if ( rhev > 0 ){      Int_t nrhev = rh->GetEntries();
1258        rh->GetEntry(0);      Int_t nrtev = rt->GetEntries();
1259        //      if ( IsDebug() ) printf(" ou nevent %i rhev %i rtev %i \n",nevent,nrhev,nrtev);
1260        TSYNC = runh->LAST_TIME_SYNC_INFO;      //
1261        OBT = runh->OBT_TIME_SYNC * 1000;      if ( nrhev > 0 ){
1262        //        for (Int_t i=0; i<nrhev; i++){
1263        TYPE = 20;          //
1264        //          rh->GetEntry(i);
1265        if ( TSYNC && OBT ){          //
1266          existsts = true;          TSYNC = runh->LAST_TIME_SYNC_INFO;
1267          goto eout;          OBT = runh->OBT_TIME_SYNC * 1000;
1268            //
1269            TYPE = 20;
1270            //
1271            if ( IsDebug() ) printf("runheader %i tsync %u obt %u \n",i,TSYNC,OBT);
1272            //
1273            if ( TSYNC && OBT ){
1274              existsts = true;
1275              goto eout;
1276            };
1277        };        };
1278        //        //
1279      };      };
1280      if ( rtev > 0 ){      if ( nrtev > 0 ){
1281        //        //
1282        if ( IsDebug() ) printf(" No runheader \n");        if ( IsDebug() ) printf(" No runheader \n");
1283        signal = 6;        signal = 6;
1284        //        //
1285        rt->GetEntry(0);        for (Int_t i=0; i<nrtev; i++){
1286        //          //
1287        TSYNC = runt->LAST_TYME_SYNC_INFO;          rt->GetEntry(i);
1288        OBT = runt->OBT_TYME_SYNC * 1000;          //
1289        //          TSYNC = runt->LAST_TYME_SYNC_INFO;
1290        TYPE = 21;          OBT = runt->OBT_TYME_SYNC * 1000;
1291        //          //
1292        if ( TSYNC && OBT ){          TYPE = 21;
1293          existsts = true;          //
1294          goto eout;          if ( IsDebug() ) printf("runtrailer %i tsync %u obt %u \n",i,TSYNC,OBT);
1295            //
1296            if ( TSYNC && OBT ){
1297              existsts = true;
1298              goto eout;
1299            };
1300        };        };
1301        //        //
1302      } else {      } else {
# Line 1030  Int_t PamelaDBOperations::insertPamelaGL Line 1344  Int_t PamelaDBOperations::insertPamelaGL
1344    //    //
1345    if ( !existsts && obt0 ){ // insert timesync by hand    if ( !existsts && obt0 ){ // insert timesync by hand
1346      //      //
1347        if ( PEDANTIC ) throw -68;
1348      if ( IsDebug() ) printf(" No incl mcmd \n");      if ( IsDebug() ) printf(" No incl mcmd \n");
1349      signal = 30;      signal = 30;
1350      //      //
# Line 1045  Int_t PamelaDBOperations::insertPamelaGL Line 1360  Int_t PamelaDBOperations::insertPamelaGL
1360    if ( !existsts ) throw -3;    if ( !existsts ) throw -3;
1361    //    //
1362    oss.str("");    oss.str("");
1363    oss << "INSERT INTO GL_TIMESYNC (ID_RAW,TYPE,OBT0,TIMESYNC) VALUES ('"    oss << "INSERT INTO GL_TIMESYNC (ID_RAW,TYPE,OBT0,TIMESYNC,ID_RESURS_OFFSET) VALUES ('"
1364        << this->GetID_RAW() << "','"//224'"        << this->GetID_RAW() << "','"//224'"
1365        << dec << (UInt_t)TYPE << "','"        << dec << (UInt_t)TYPE << "','"
1366        << dec << (UInt_t)OBT << "','"        << dec << (UInt_t)OBT << "','"
1367        << dec << (UInt_t)TSYNC << "');";        << dec << (UInt_t)TSYNC << "','"
1368          << dec << (UInt_t)idresof << "');";
1369    conn->Query(oss.str().c_str());    conn->Query(oss.str().c_str());
1370    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());
1371      if ( conn->GetErrorCode() ){
1372        printf(" OK, you got an error because the database structure you are using is not up to date\n Using backward compability code, hence you can continue safetly \n");
1373        oss.str("");
1374        oss << "INSERT INTO GL_TIMESYNC (ID_RAW,TYPE,OBT0,TIMESYNC) VALUES ('"
1375            << this->GetID_RAW() << "','"//224'"
1376            << dec << (UInt_t)TYPE << "','"
1377            << dec << (UInt_t)OBT << "','"
1378            << dec << (UInt_t)TSYNC << "');";
1379        conn->Query(oss.str().c_str());
1380        if ( IsDebug() ) printf(" Query the GL_TIMESYNC table to fill it:\n %s \n",oss.str().c_str());
1381      };
1382      //
1383      if ( IsDebug() ) printf(" found a timesync t0 is %u \n",t0);
1384    //    //
1385    toffset = (UInt_t)TSYNC - (UInt_t)(this->OBT(OBT)/1000) + t0;    toffset = (UInt_t)TSYNC - (UInt_t)(this->OBT(OBT)/1000) + t0;
1386    //    //
1387      tsync = TSYNC;
1388      obt0 = OBT;
1389      //
1390    delete result;    delete result;
1391    return(signal);    return(signal);
1392  }  }
# Line 1070  Int_t PamelaDBOperations::insertPamelaRo Line 1402  Int_t PamelaDBOperations::insertPamelaRo
1402    UInt_t idtimesync = 0;    UInt_t idtimesync = 0;
1403    //    //
1404    oss.str("");    oss.str("");
1405    oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "    if ( STATIC ){
1406        << " LEFT JOIN GL_ROOT "      oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1407        << " ON GL_RAW.ID = GL_ROOT.ID_RAW "          << " LEFT JOIN GL_ROOT "
1408        << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "          << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1409        << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";          << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "
1410            << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1411      } else {
1412        oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1413            << " LEFT JOIN GL_ROOT "
1414            << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1415            << " WHERE GL_RAW.PATH = '$PAM_RAW' AND "
1416            << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1417      };
1418    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1419    //    //
1420    if ( !result ) throw -12;    if ( !result ) throw -12;
# Line 1101  Int_t PamelaDBOperations::insertPamelaRo Line 1441  Int_t PamelaDBOperations::insertPamelaRo
1441    idtimesync = (UInt_t)atoll(row->GetField(0));    idtimesync = (UInt_t)atoll(row->GetField(0));
1442    //    //
1443    oss.str("");    oss.str("");
1444    oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"    if ( STATIC ){
1445        << this->GetID_RAW() << "', '" << idtimesync << "', '" << this->GetRootPath().Data() << "', '" << this->GetRootFile().Data() << "')";      oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
1446            << this->GetID_RAW() << "', '" << idtimesync << "', '" << this->GetRootPath().Data() << "', '" << this->GetRootFile().Data() << "')";
1447      } else {
1448        oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
1449            << this->GetID_RAW() << "', '" << idtimesync << "', '$PAM_L0', '" << this->GetRootFile().Data() << "')";
1450      };
1451    //    //
1452    if (conn->Query(oss.str().c_str()) == 0) throw -4;    if (conn->Query(oss.str().c_str()) == 0) throw -4;
1453    //    //
# Line 1129  Int_t PamelaDBOperations::assignBOOT_NUM Line 1474  Int_t PamelaDBOperations::assignBOOT_NUM
1474    TSQLResult *result = 0;    TSQLResult *result = 0;
1475    TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
1476    oss.str("");    oss.str("");
1477    oss << "SELECT ID, BOOT_NUMBER FROM GL_RAW WHERE "    if ( STATIC ){
1478        << " PATH = '" << this->GetRawPath().Data() << "' AND "      oss << "SELECT ID, BOOT_NUMBER FROM GL_RAW WHERE "
1479        << " NAME = '" << this->GetRawFile().Data() << "' ";          << " PATH = '" << this->GetRawPath().Data() << "' AND "
1480            << " NAME = '" << this->GetRawFile().Data() << "' ";
1481      } else {
1482        oss << "SELECT ID, BOOT_NUMBER FROM GL_RAW WHERE "
1483            << " PATH = '$PAM_RAW' AND "
1484            << " NAME = '" << this->GetRawFile().Data() << "' ";
1485      };
1486    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1487    //    //
1488    if ( !result ) throw -4;;    if ( !result ) throw -4;;
# Line 1154  Int_t PamelaDBOperations::assignBOOT_NUM Line 1505  Int_t PamelaDBOperations::assignBOOT_NUM
1505    VarDumpEvent  *vde = 0;    VarDumpEvent  *vde = 0;
1506    VarDumpRecord *vdr = 0;    VarDumpRecord *vdr = 0;
1507    //    //
1508      Bool_t found = false;
1509    trDumpEv->SetBranchAddress("VarDump", &vde);    trDumpEv->SetBranchAddress("VarDump", &vde);
1510    if ( trDumpEv->GetEntries() > 0 ){    if ( trDumpEv->GetEntries() > 0 ){
1511      Bool_t found = false;      found = false;
1512      for ( Int_t i = 0; i < trDumpEv->GetEntries(); i++){      for ( Int_t i = 0; i < trDumpEv->GetEntries(); i++){
1513        trDumpEv->GetEntry(i);        trDumpEv->GetEntry(i);
1514        vde->Records->GetEntries();        //      vde->Records->GetEntries();
1515        if ( vde->Records->GetEntries()>0 ){        if ( vde->Records->GetEntries()>5 ){
1516          found = true;          found = true;
1517          goto fill;          goto fill;
1518        };        };
# Line 1173  Int_t PamelaDBOperations::assignBOOT_NUM Line 1525  Int_t PamelaDBOperations::assignBOOT_NUM
1525        this->SetBOOTnumber((Int_t)vdr->VAR_VALUE);        this->SetBOOTnumber((Int_t)vdr->VAR_VALUE);
1526        //        //
1527      } else {      } else {
1528        if ( !this->GetBOOTnumber() ) return(4);        if ( !this->GetBOOTnumber() && !this->AutoBoot()) return(4);
1529        };
1530      } else {
1531        if ( !this->GetBOOTnumber() && !this->AutoBoot()) return(2);
1532      };
1533      //
1534      UInt_t bn = 0;
1535      Bool_t afound = false;
1536      if ( !found && this->AutoBoot()){
1537        afound = true;
1538        //
1539        // Search for other files with similar timesync
1540        //
1541        if ( IsDebug() ) printf(" tsync %u obt0 %u \n",tsync,obt0);
1542        UInt_t upperts = tsync-(obt0/1000)+5;
1543        UInt_t lowerts = tsync-(obt0/1000)-5;
1544        oss.str("");
1545        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)<"
1546            << upperts
1547            << " AND TIMESYNC-(OBT0/1000)>"
1548            << lowerts
1549            << " AND GL_RAW.BOOT_NUMBER>0 GROUP BY GL_TIMESYNC.OBT0;";
1550        result = conn->Query(oss.str().c_str());
1551        if ( IsDebug() ) printf(" Query the GL_TIMESYNC table to find boot number:\n %s \n",oss.str().c_str());
1552        //
1553        if ( !result ) throw -4;;
1554        found = true;
1555        if ( result->GetRowCount()<3 ){
1556          if ( IsDebug() ) printf(" AGH! no results!\n");
1557          found = false;
1558        } else {
1559          row = result->Next();      
1560          bn = (UInt_t)atoll(row->GetField(0));
1561          for ( Int_t r=1; r<result->GetRowCount() ;r++){
1562            if ( !row ) throw -4;
1563            if ( IsDebug() ) printf(" BOOT number is %s \n",row->GetField(0));
1564            if ( bn != (UInt_t)atoll(row->GetField(0)) ){
1565              if ( IsDebug() ) printf(" AGH! bn = %u here instead %u \n",bn,(UInt_t)atoll(row->GetField(0)));
1566              found = false;
1567            };
1568            row = result->Next();
1569          };
1570      };      };
1571      };
1572      //
1573      Int_t sgn = 0;
1574      //
1575      if ( !found && !BOOTNO ){
1576        throw -29;
1577    } else {    } else {
1578      if ( !this->GetBOOTnumber() ) return(2);      if ( afound ){
1579          this->SetBOOTnumber(bn);
1580          sgn = 8;
1581        };
1582    };    };
1583    //    //
1584    oss.str("");    oss.str("");
# Line 1186  Int_t PamelaDBOperations::assignBOOT_NUM Line 1588  Int_t PamelaDBOperations::assignBOOT_NUM
1588    conn->Query(oss.str().c_str());          conn->Query(oss.str().c_str());      
1589    //    //
1590    delete result;    delete result;
1591    return(0);    return(sgn);
1592  };  };
1593    
1594  /**  /**
# Line 1199  Int_t PamelaDBOperations::insertPamelaRU Line 1601  Int_t PamelaDBOperations::insertPamelaRU
1601    stringstream oss;    stringstream oss;
1602    oss.str("");    oss.str("");
1603    //    //
1604    signal = this->SetUpperLimits();    //  signal = this->SetUpperLimits();
1605    //    //
1606    // loop on runheader and runtrailer events    // loop on runheader and runtrailer events
1607    //    //
# Line 1217  Int_t PamelaDBOperations::insertPamelaRU Line 1619  Int_t PamelaDBOperations::insertPamelaRU
1619    rt->SetBranchAddress("RunTrailer", &runt);    rt->SetBranchAddress("RunTrailer", &runt);
1620    rt->SetBranchAddress("Header", &eht);    rt->SetBranchAddress("Header", &eht);
1621    //    //
1622      TTree *T = (TTree*)file->Get("Physics");
1623      if ( !T || T->IsZombie() ) throw -16;
1624      EventHeader *eh = 0;
1625      T->SetBranchAddress("Header", &eh);
1626      //
1627      if ( !(rh->GetEntries()) && !(rt->GetEntries()) && !(T->GetEntries()) ) return(16);
1628      //
1629    UInt_t obtt = 0;    UInt_t obtt = 0;
1630    UInt_t obth = 0;    UInt_t obth = 0;
1631    UInt_t pktt = 0;    UInt_t pktt = 0;
# Line 1250  Int_t PamelaDBOperations::insertPamelaRU Line 1659  Int_t PamelaDBOperations::insertPamelaRU
1659        //        //
1660        if ( !ptt &&  !(ptht+1) ){        if ( !ptt &&  !(ptht+1) ){
1661          //          //
1662          if ( IsDebug() ) printf(" Piece of run at the beginning of the file %i %i %i \n",ptht,pth,ptt);          if ( IsDebug() ) printf(" Piece of run at the beginning of the file %u %u %u \n",ptht,pth,ptt);
1663          //          //
1664          this->HandleRunFragments(true,false,0,(evbeft-1));          this->HandleRunFragments(true,false,0,(evbeft-1));
1665          //          //
1666          //          //
1667        } else if ( pth == ptht ){        } else if ( pth == ptht ){
1668          //          //
1669          if ( IsDebug() ) printf(" Missing header %i %i %i\n",ptht,pth,ptt);          if ( IsDebug() ) printf(" Missing header %u %u %u\n",ptht,pth,ptt);
1670          //          //
1671          if ( (ptt-1) < 0 ) throw -15; // should never arrive here!          if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
1672          rt->GetEntry(ptt-1);          rt->GetEntry(ptt-1);
# Line 1266  Int_t PamelaDBOperations::insertPamelaRU Line 1675  Int_t PamelaDBOperations::insertPamelaRU
1675          rt->GetEntry(ptt);          rt->GetEntry(ptt);
1676          pht = eht->GetPscuHeader();          pht = eht->GetPscuHeader();
1677          //          //
1678          if ( IsDebug() ) printf(" Try to find the beginning of a run which has only the runtrailer   %i %i %i \n",ptht,pth,ptt);          if ( IsDebug() ) printf(" Try to find the beginning of a run which has only the runtrailer   %u %u %u \n",ptht,pth,ptt);
1679          if ( IsDebug() ) printf(" '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''  %i %i %i \n",pkth,obth,obtt);          if ( IsDebug() ) printf(" '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''  %u %u %u \n",pkth,obth,obtt);
1680          //          //
1681          this->HandleMissingHoT(true,false,evbefh,evbeft-1);          this->HandleMissingHoT(true,false,evbefh,evbeft-1);
1682          //          //
1683        } else {        } else {
1684          //          //
1685          if ( IsDebug() ) printf(" Could be a good run, we have a runheader followed by a runtrailer %i %i %i\n",ptht,pth,ptt);          if ( IsDebug() ) printf(" Could be a good run, we have a runheader followed by a runtrailer %u %u %u\n",ptht,pth,ptt);
1686          //          //
1687          rh->GetEntry(ptht);          rh->GetEntry(ptht);
1688          phh = ehh->GetPscuHeader();          phh = ehh->GetPscuHeader();
# Line 1281  Int_t PamelaDBOperations::insertPamelaRU Line 1690  Int_t PamelaDBOperations::insertPamelaRU
1690          obth = phh->GetOrbitalTime();          obth = phh->GetOrbitalTime();
1691          cod = ehh->GetCounter();          cod = ehh->GetCounter();
1692          evbefh = cod->Get(pctp->Physics);          evbefh = cod->Get(pctp->Physics);
1693          if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' %i %i %i \n",pkth,obth,obtt);          if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' %u %u %u \n",pkth,obth,obtt);
1694          //          //
1695          // handle this run          // handle this run
1696          //          //
# Line 1291  Int_t PamelaDBOperations::insertPamelaRU Line 1700  Int_t PamelaDBOperations::insertPamelaRU
1700          //          //
1701          if ( PKT(pkth)>PKT(pktfirst) && OBT(obth)>OBT(obtfirst) && !ptt ){          if ( PKT(pkth)>PKT(pktfirst) && OBT(obth)>OBT(obtfirst) && !ptt ){
1702            //            //
1703            if ( IsDebug() ) printf(" Piece of run at the beginning of the file WITH NO RUNTRAILER \n");            if ( IsDebug() ) printf(" Piece of run at the beginning of the file WITH NO RUNTRAILER evbefh = %u \n",evbefh);        
           //  
           this->HandleRunFragments(true,true,0,(evbefh-1));  
1704            //            //
1705              if ( evbefh == 0 ) {
1706                //
1707                signal = 8;
1708                if ( IsDebug() ) printf(" Not supported yet: run with no events, no runtrailer, no runheader \n");
1709                //
1710              } else {
1711                //
1712                this->HandleRunFragments(true,true,0,(evbefh-1));
1713                //
1714              };
1715          };          };
1716          //          //
1717          //          //
1718          if ( (ptht - pth) > 1 ){          if ( (ptht - pth) > 1 ){
1719            //            //
1720            if ( IsDebug() ) printf(" Missing runtrailers! \n");            if ( IsDebug() ) printf(" Missing runtrailers! \n");
1721            if ( IsDebug() ) printf(" Attention there is a jump in the runheader counter %i %i %i \n",ptht,pth,ptt);            if ( IsDebug() ) printf(" Attention there is a jump in the runheader counter %u %u %u \n",ptht,pth,ptt);
1722            // is not the consecutive header            // is not the consecutive header
1723            while ( pth != ptht ){                      while ( pth != ptht ){          
1724              //              //
# Line 1322  Int_t PamelaDBOperations::insertPamelaRU Line 1739  Int_t PamelaDBOperations::insertPamelaRU
1739              obth = phh->GetOrbitalTime();              obth = phh->GetOrbitalTime();
1740              evbefh = cod->Get(pctp->Physics);              evbefh = cod->Get(pctp->Physics);
1741              //              //
1742              if ( IsDebug() ) printf(" Try to find the end of a run which has only the runheader   %i %i %i \n",ptht,pth,ptt);              if ( IsDebug() ) printf(" Try to find the end of a run which has only the runheader   %u %u %u \n",ptht,pth,ptt);
1743              if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' %i %i %i \n",pkth,obth,obtt);              if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' %u %u %u \n",pkth,obth,obtt);
1744              //              //
1745              this->HandleMissingHoT(false,true,evbefh,evbeft-1);              this->HandleMissingHoT(false,true,evbefh,evbeft-1);
1746              //              //
# Line 1332  Int_t PamelaDBOperations::insertPamelaRU Line 1749  Int_t PamelaDBOperations::insertPamelaRU
1749          } else if ( !(ptht - pth) ){          } else if ( !(ptht - pth) ){
1750            //            //
1751            if ( IsDebug() ) printf(" Missing runheader! \n");            if ( IsDebug() ) printf(" Missing runheader! \n");
1752            if ( IsDebug() ) printf(" Attention! the runheader counter did not changed %i %i %i \n",ptht,pth,ptt);            if ( IsDebug() ) printf(" Attention! the runheader counter did not changed %u %u %u \n",ptht,pth,ptt);
1753            if ( IsDebug() ) printf(" The run should have already been handled by HandleRun() \n");            if ( IsDebug() ) printf(" The run should have already been handled by HandleRun() \n");
1754            //            //
1755          } else {          } else {
# Line 1353  Int_t PamelaDBOperations::insertPamelaRU Line 1770  Int_t PamelaDBOperations::insertPamelaRU
1770            obth = phh->GetOrbitalTime();            obth = phh->GetOrbitalTime();
1771            cod = ehh->GetCounter();            cod = ehh->GetCounter();
1772            evbefh = cod->Get(pctp->Physics);            evbefh = cod->Get(pctp->Physics);
1773            if ( IsDebug() ) printf(" Piece of run at the end of file %i %i %i \n",pkth,obth,obtt);            if ( IsDebug() ) printf(" Piece of run at the end of file %u %u %u \n",pkth,obth,obtt);
1774            if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''' %i %i %i \n",ptht,pth,ptt);            if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''' %u %u %u \n",ptht,pth,ptt);
1775            if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''' %i \n",rhev);            if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''' %u \n",rhev);
1776            //            //
1777            this->HandleRunFragments(false,true,evbefh,upperentry);            this->HandleRunFragments(false,true,evbefh,upperentry);
1778          } else {          } else {
# Line 1403  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1820  Bool_t PamelaDBOperations::IsRunAlreadyI
1820    //                                  ( runhead_time <= _our_runhead_time &&  runtrail_time >= _our_runtrail_time) &&    //                                  ( runhead_time <= _our_runhead_time &&  runtrail_time >= _our_runtrail_time) &&
1821    //                                  ( runhead_obt <= _our_runheadobt || runhead_pkt <= _our_runheadpkt ) &&    //                                  ( runhead_obt <= _our_runheadobt || runhead_pkt <= _our_runheadpkt ) &&
1822    //                                  ( runtrail_obt <= _our_runtrailobt || runtrail_pkt <= _our_runtrailpkt ) )    //                                  ( runtrail_obt <= _our_runtrailobt || runtrail_pkt <= _our_runtrailpkt ) )
1823      //                                  ||
1824      //                                  ( runhead_time = _our_runhead_time &&  runtrail_time = _our_runtrail_time && nevents > 100 )
1825      //                                  )
1826      //                                  ||
1827      //                                  ( runhead_time = _our_runhead_time &&  runtrail_time > _our_runtrail_time && nevents > 100 )
1828      //                                  )
1829      //                                  ||
1830      //                                  ( runhead_time < _our_runhead_time &&  runtrail_time = _our_runtrail_time && nevents > 100 )
1831    //                                  )    //                                  )
1832    //    //
1833    oss << " SELECT ID,NEVENTS,TRK_CALIB_USED,PKT_COUNTER FROM GL_RUN WHERE "    oss << " SELECT ID,NEVENTS,TRK_CALIB_USED,PKT_COUNTER FROM GL_RUN WHERE "
# Line 1418  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1843  Bool_t PamelaDBOperations::IsRunAlreadyI
1843        << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "        << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
1844        << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("        << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
1845        << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "        << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
1846        << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";        << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") OR "
1847          << " (RUNHEADER_TIME=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "                //  these two lines in a certain way disable the patch below...
1848          << " RUNTRAILER_TIME=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND NEVENTS>100) OR"    //
1849          << " (RUNHEADER_TIME=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "                //
1850          << " RUNTRAILER_TIME>" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND NEVENTS>100) OR"    //
1851          << " (RUNHEADER_TIME<" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "                //
1852          << " RUNTRAILER_TIME=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND NEVENTS>100)"    //
1853          << " ));";
1854    //    //
1855    if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());    if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
1856    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
# Line 1440  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1872  Bool_t PamelaDBOperations::IsRunAlreadyI
1872      //      //
1873      // the run has already been inserted      // the run has already been inserted
1874      //      //
1875      //    return(true);  //<<<<<<<<<<<<<<<<<<<<<<<< patch follows, uncomment here      if ( signal && IsDebug() ) printf(" The run has already been inserted \n");    
1876        return(true);  //<<<<<<<<<<<<<<<<<<<<<<<< patch follows, uncomment here
1877      //      //
1878      // PATCH!      // PATCH!
1879      // we keep the processing run if (in order of growing importance) 1) we have the runtrailer while the old run doesn't have it 2) we have the runheader      // we keep the processing run if (in order of growing importance) 1) we have the runtrailer while the old run doesn't have it 2) we have the runheader
# Line 1449  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1882  Bool_t PamelaDBOperations::IsRunAlreadyI
1882      if ( glrun->GetNEVENTS() > (UInt_t)atoll(row->GetField(1)) ){      if ( glrun->GetNEVENTS() > (UInt_t)atoll(row->GetField(1)) ){
1883        //        //
1884        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");
1885        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1886        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1887        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) <<";";
1888        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1889    //       conn->Query(oss.str().c_str());
1890        if ( signal ) signal = false;        if ( signal ) signal = false;
1891        goto gonext;              goto gonext;      
1892        //        //
# Line 1466  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1900  Bool_t PamelaDBOperations::IsRunAlreadyI
1900        //        //
1901        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");
1902        //        //
1903        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1904        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1905        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) <<";";
1906        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1907    //       conn->Query(oss.str().c_str());
1908        //        //
1909        if ( signal ) signal = false;        if ( signal ) signal = false;
1910        goto gonext;        goto gonext;
# Line 1483  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1918  Bool_t PamelaDBOperations::IsRunAlreadyI
1918        //        //
1919        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");
1920        //        //
1921        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1922        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1923        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) <<";";
1924        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1925    //       conn->Query(oss.str().c_str());
1926        if ( signal ) signal = false;        if ( signal ) signal = false;
1927        //        //
1928      };      };
# Line 1501  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1937  Bool_t PamelaDBOperations::IsRunAlreadyI
1937    delete result;    delete result;
1938    //    //
1939    if ( signal && IsDebug() ) printf(" The run has already been inserted \n");        if ( signal && IsDebug() ) printf(" The run has already been inserted \n");    
1940      if ( !signal && IsDebug() ) printf(" The run existed and was deleted, fill the DB \n");
1941    return(signal);    return(signal);
1942  };  };
1943    
# Line 1522  void PamelaDBOperations::HandleRun(){   Line 1959  void PamelaDBOperations::HandleRun(){  
1959      //      //
1960      this->FillClass();      this->FillClass();
1961      //      //
1962      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);      if ( !IsRunAlreadyInserted() ){
1963          glrun->SetID(this->AssignRunID());
1964          glrun->SetID_RUN_FRAG(0);
1965          glrun->Fill_GL_RUN(conn);
1966        };
1967    } else {    } else {
1968      //      //
1969      if ( IsDebug() ) printf(" oh no! the distance between runheader and runtrailer seems wrong: check %llu pktt %llu \n",chkpkt,pktt);      if ( IsDebug() ) printf(" oh no! the distance between runheader and runtrailer seems wrong: check %llu pktt %llu \n",chkpkt,pktt);
# Line 1545  void PamelaDBOperations::HandleRunFragme Line 1986  void PamelaDBOperations::HandleRunFragme
1986    UInt_t rhfirstev = firstev;    UInt_t rhfirstev = firstev;
1987    UInt_t rtlastev = lastev;    UInt_t rtlastev = lastev;
1988    Bool_t found = false;    Bool_t found = false;
1989      Bool_t foundinrun = false;
1990    //    //
1991    TSQLResult *result = 0;    TSQLResult *result = 0;
1992    TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
# Line 1571  void PamelaDBOperations::HandleRunFragme Line 2013  void PamelaDBOperations::HandleRunFragme
2013    //    //
2014    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");
2015    //    //
2016      // First of all insert the run in the fragment table...
2017      //
2018      oss.str("");
2019      oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
2020          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
2021          << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
2022          << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
2023          << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
2024          << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2025          << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
2026          << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
2027          << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2028          << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
2029          << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
2030          << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2031          << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
2032          << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
2033      //
2034      if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
2035      result = conn->Query(oss.str().c_str());
2036      //
2037      if ( !result ) throw -4;
2038      //
2039      row = result->Next();
2040      //
2041      if ( !row ){
2042        //
2043        // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
2044        //
2045        if ( IsDebug() ) printf(" The run is new \n");
2046        if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
2047        //
2048        glrun->SetID(this->AssignRunID());
2049        glrun->SetID_RUN_FRAG(0);
2050        glrun->Fill_GL_RUN_FRAGMENTS(conn);
2051        //
2052      } else {
2053        if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
2054        if ( PEDANTIC ) throw -69;
2055        return;
2056      };
2057      //
2058      //
2059    // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?    // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
2060    //        //    
2061    if ( mishead && rhfirstev == firstev ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is    if ( mishead && rhfirstev == firstev ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
# Line 1579  void PamelaDBOperations::HandleRunFragme Line 2064  void PamelaDBOperations::HandleRunFragme
2064      oss.str("");      oss.str("");
2065      oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "      oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "
2066          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2067          << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME()          << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2068            << " ID != " << glrun->ID
2069          << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!          << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
2070      //      //
2071      if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());      if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());
# Line 1589  void PamelaDBOperations::HandleRunFragme Line 2075  void PamelaDBOperations::HandleRunFragme
2075      //      //
2076      row = result->Next();      row = result->Next();
2077      //      //
2078        if ( !row && NoFrag() ){
2079          //
2080          oss.str("");
2081          oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
2082              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2083              << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2084              << " ID != " << glrun->ID
2085              << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
2086          //
2087          if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
2088          result = conn->Query(oss.str().c_str());
2089          //
2090          if ( !result ) throw -4;
2091          //
2092          foundinrun = true;
2093          //
2094          row = result->Next();
2095          //
2096        };
2097        //
2098      if ( !row ){      if ( !row ){
2099        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2100        found = false;        found = false;
# Line 1663  void PamelaDBOperations::HandleRunFragme Line 2169  void PamelaDBOperations::HandleRunFragme
2169        //        //
2170        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 ");
2171        //        //
2172          if ( foundinrun ){
2173            glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2174            glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2175          };
2176          //
2177        GL_RUN *glrun1 = new GL_RUN();        GL_RUN *glrun1 = new GL_RUN();
2178        //        //
2179        UInt_t idfrag = (UInt_t)atoll(row->GetField(0));        //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
2180        //        //
2181        oss.str("");        oss.str("");
2182        oss << " ID="<<row->GetField(0)<<";";        oss << " ID="<<row->GetField(0)<<";";
# Line 1678  void PamelaDBOperations::HandleRunFragme Line 2189  void PamelaDBOperations::HandleRunFragme
2189        ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());        ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
2190        UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());        UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
2191        ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());        ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
2192        if ( IsDebug() ) printf(" Check overlapping events: %i %i %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);        if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2193        TTree *T= 0;        TTree *T= 0;
2194        T = (TTree*)file->Get("Physics");        T = (TTree*)file->Get("Physics");
2195        if ( !T || T->IsZombie() ) throw -16;        if ( !T || T->IsZombie() ) throw -16;
# Line 1691  void PamelaDBOperations::HandleRunFragme Line 2202  void PamelaDBOperations::HandleRunFragme
2202          bpkt = PKT(ph->GetCounter());          bpkt = PKT(ph->GetCounter());
2203          bobt = OBT(ph->GetOrbitalTime());                bobt = OBT(ph->GetOrbitalTime());      
2204          firstev++;          firstev++;
2205            if ( PEDANTIC ) throw -71;
2206        };        };
2207        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: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2208        //        //
       glrun1->SetID(0);  
2209        glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());        glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
2210        glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());        glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
2211        glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());        glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
# Line 1703  void PamelaDBOperations::HandleRunFragme Line 2214  void PamelaDBOperations::HandleRunFragme
2214        //        //
2215        glrun->SetEV_FROM(firstev);        glrun->SetEV_FROM(firstev);
2216        glrun->SetNEVENTS(lastev-firstev+1);        glrun->SetNEVENTS(lastev-firstev+1);
2217          //
2218        glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());        glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
2219        glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());        glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
2220        glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());        glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
# Line 1722  void PamelaDBOperations::HandleRunFragme Line 2234  void PamelaDBOperations::HandleRunFragme
2234        //        //
2235        if ( !IsRunAlreadyInserted() ){        if ( !IsRunAlreadyInserted() ){
2236          //          //
2237            //      glrun->SetID(this->AssignRunID());
2238            glrun->SetID_RUN_FRAG(glrun1->GetID());
2239          glrun->Fill_GL_RUN(conn);          glrun->Fill_GL_RUN(conn);
2240          //          //
2241          // 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);  
2242          //          //
2243            glrun1->SetID_RUN_FRAG(glrun->GetID());
2244          glrun1->Fill_GL_RUN(conn);          glrun1->Fill_GL_RUN(conn);
2245          //          //
         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;  
         //  
2246        };        };
       //  
       delete glrun1;  
       //  
2247        // delete old entry in fragment table        // delete old entry in fragment table
2248        //        //
2249        oss.str("");        glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2250          glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2251        //        //
2252        oss << " DELETE FROM GL_RUN_FRAGMENTS WHERE ID = " << idfrag << ";";        delete glrun1;
2253        //        //
       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;  
2254        //        //
2255        return;        return;
2256        //        //
# Line 1791  void PamelaDBOperations::HandleRunFragme Line 2259  void PamelaDBOperations::HandleRunFragme
2259    };    };
2260    //    //
2261    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
2262                                             // 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
2263      //      //
2264      oss.str("");      oss.str("");
2265      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 "
2266          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2267          << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME()          << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2268            << " ID != " << glrun->ID
2269          << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";          << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2270      //      //
2271      if ( IsDebug() ) printf(" look for runtrailer in the fragments table: query is \n %s \n",oss.str().c_str());      if ( IsDebug() ) printf(" look for runtrailer in the fragments table: query is \n %s \n",oss.str().c_str());
# Line 1806  void PamelaDBOperations::HandleRunFragme Line 2275  void PamelaDBOperations::HandleRunFragme
2275      //      //
2276      row = result->Next();      row = result->Next();
2277      //      //
2278        if ( !row && NoFrag() ){
2279          //
2280          oss.str("");
2281          oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN WHERE "
2282              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2283              << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2284              << " ID != " << glrun->ID
2285              << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2286          //
2287          if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
2288          result = conn->Query(oss.str().c_str());
2289          //
2290          if ( !result ) throw -4;
2291          //
2292          foundinrun = true;
2293          row = result->Next();
2294          //
2295        };
2296        //
2297      if ( !row ){      if ( !row ){
2298        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2299        found = false;        found = false;
# Line 1879  void PamelaDBOperations::HandleRunFragme Line 2367  void PamelaDBOperations::HandleRunFragme
2367        //        //
2368        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 ");
2369        //        //
2370          if ( foundinrun ){
2371            glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2372            glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2373          };
2374          //
2375        GL_RUN *glrun1 = new GL_RUN();        GL_RUN *glrun1 = new GL_RUN();
2376        //        //
2377        UInt_t idfrag = (UInt_t)atoll(row->GetField(0));        //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
2378        //        //
2379        oss.str("");        oss.str("");
2380        oss << " ID="<<row->GetField(0)<<";";        oss << " ID="<<row->GetField(0)<<";";
# Line 1894  void PamelaDBOperations::HandleRunFragme Line 2387  void PamelaDBOperations::HandleRunFragme
2387        ULong64_t aobt = OBT(glrun->GetRUNTRAILER_OBT());        ULong64_t aobt = OBT(glrun->GetRUNTRAILER_OBT());
2388        UInt_t bpkt = PKT(glrun1->GetRUNHEADER_PKT());        UInt_t bpkt = PKT(glrun1->GetRUNHEADER_PKT());
2389        ULong64_t bobt = OBT(glrun1->GetRUNHEADER_OBT());        ULong64_t bobt = OBT(glrun1->GetRUNHEADER_OBT());
2390        if ( IsDebug() ) printf(" Check overlapping events: %i %i %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);        if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
2391        TTree *T= 0;        TTree *T= 0;
2392        T = (TTree*)file->Get("Physics");        T = (TTree*)file->Get("Physics");
2393        if ( !T || T->IsZombie() ) throw -16;        if ( !T || T->IsZombie() ) throw -16;
# Line 1907  void PamelaDBOperations::HandleRunFragme Line 2400  void PamelaDBOperations::HandleRunFragme
2400          apkt = PKT(ph->GetCounter());          apkt = PKT(ph->GetCounter());
2401          aobt = OBT(ph->GetOrbitalTime());                aobt = OBT(ph->GetOrbitalTime());      
2402          lastev--;          lastev--;
2403            if ( PEDANTIC ) throw -72;
2404        };        };
2405        if ( IsDebug() ) printf(" Check overlapping events done: %i %i %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);        if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
2406        //        //
2407        glrun->SetEV_TO(lastev);        glrun->SetEV_TO(lastev);
2408        glrun->SetNEVENTS(lastev-firstev+1);        glrun->SetNEVENTS(lastev-firstev+1);
# Line 1918  void PamelaDBOperations::HandleRunFragme Line 2412  void PamelaDBOperations::HandleRunFragme
2412        glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());        glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());
2413        glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());        glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());
2414        //        //
       glrun1->SetID(0);  
2415        glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());        glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());
2416        glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());        glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());
2417        glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());        glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());
# Line 1938  void PamelaDBOperations::HandleRunFragme Line 2431  void PamelaDBOperations::HandleRunFragme
2431        //        //
2432        if ( !IsRunAlreadyInserted() ){        if ( !IsRunAlreadyInserted() ){
2433          //          //
2434          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();  
2435          //          //
2436          UInt_t idrun0 = 0;          glrun->SetID_RUN_FRAG(glrun1->GetID());
2437          if ( !row ){          glrun->Fill_GL_RUN(conn);
           throw -10;  
         } else {  
           idrun0 = (UInt_t)atoll(row->GetField(0));  
         };  
2438          //          //
2439          glrun1->SetID_RUN_FRAG(idrun0);          // set id number
2440          //          //
2441            glrun1->SetID_RUN_FRAG(glrun->GetID());
2442          glrun1->Fill_GL_RUN(conn);          glrun1->Fill_GL_RUN(conn);
2443          //          //
         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;  
         //  
2444        };        };
2445        //        //
2446        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 << ";";  
2447        //        //
2448        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");
2449        result =  conn->Query(oss.str().c_str());        glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
       if ( !result ) throw -4;  
2450        //        //
2451          delete glrun1;
2452        //        //
2453        return;        return;
2454        //        //
# Line 2036  void PamelaDBOperations::HandleRunFragme Line 2485  void PamelaDBOperations::HandleRunFragme
2485      //      //
2486      row = result->Next();      row = result->Next();
2487      //      //
2488      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 {  
2489        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");
2490          if ( PEDANTIC ) throw -70;
2491        } else {
2492          if ( NoFrag() ){
2493            glrun->SetID_RUN_FRAG(glrun->GetID());
2494            glrun->Fill_GL_RUN(conn);      
2495            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2496          };    
2497      };      };
2498    };    };
2499    //    //
# Line 2100  void PamelaDBOperations::HandleMissingHo Line 2519  void PamelaDBOperations::HandleMissingHo
2519      //      //
2520      this->FillClass(mishead,mistrail,firstev,lastev);      this->FillClass(mishead,mistrail,firstev,lastev);
2521      //      //
2522      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);          if ( !IsRunAlreadyInserted() ){
2523          glrun->SetID(this->AssignRunID());
2524          glrun->SetID_RUN_FRAG(0);
2525          glrun->Fill_GL_RUN(conn);    
2526        };
2527      //      //
2528    };    };
2529    //    //
# Line 2267  Bool_t PamelaDBOperations::IsRunConsiste Line 2690  Bool_t PamelaDBOperations::IsRunConsiste
2690            //                  //      
2691            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
2692            //            //
2693            if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                  if ( !IsRunAlreadyInserted() ){
2694                glrun->SetID(this->AssignRunID());
2695                glrun->SetID_RUN_FRAG(0);
2696                glrun->Fill_GL_RUN(conn);      
2697              };
2698            //            //
2699            firstevno = lastentry + 1;            firstevno = lastentry + 1;
2700            //            //
# Line 2343  void PamelaDBOperations::HandleSuspiciou Line 2770  void PamelaDBOperations::HandleSuspiciou
2770      if ( IsDebug() ) printf(" Checking but no events in the run! \n");      if ( IsDebug() ) printf(" Checking but no events in the run! \n");
2771      //      //
2772      this->FillClass();      this->FillClass();
2773      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);          if ( !IsRunAlreadyInserted() ){
2774          glrun->SetID(this->AssignRunID());
2775          glrun->SetID_RUN_FRAG(0);
2776          glrun->Fill_GL_RUN(conn);    
2777        };
2778      //      //
2779    } else {    } else {
2780      //      //
# Line 2371  void PamelaDBOperations::HandleSuspiciou Line 2802  void PamelaDBOperations::HandleSuspiciou
2802        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");
2803        //        //
2804        this->FillClass();        this->FillClass();
2805        if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                if ( !IsRunAlreadyInserted() ){
2806            glrun->SetID(this->AssignRunID());
2807            glrun->SetID_RUN_FRAG(0);
2808            glrun->Fill_GL_RUN(conn);        
2809          };
2810        //        //
2811      } else {      } else {
2812        //        //
# Line 2469  void PamelaDBOperations::HandleSuspiciou Line 2904  void PamelaDBOperations::HandleSuspiciou
2904            //                  //      
2905            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
2906            //            //
2907            if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                  if ( !IsRunAlreadyInserted() ){
2908                glrun->SetID(this->AssignRunID());
2909                glrun->SetID_RUN_FRAG(0);
2910                glrun->Fill_GL_RUN(conn);      
2911              };
2912            //            //
2913            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...
2914              //              //
# Line 2504  void PamelaDBOperations::HandleSuspiciou Line 2943  void PamelaDBOperations::HandleSuspiciou
2943              //                  //    
2944              this->SetCommonGLRUN(firstTime,lastTime);              this->SetCommonGLRUN(firstTime,lastTime);
2945              //              //
2946              if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                    if ( !IsRunAlreadyInserted() ){
2947                  glrun->SetID(this->AssignRunID());
2948                  glrun->SetID_RUN_FRAG(0);
2949                  glrun->Fill_GL_RUN(conn);      
2950                };
2951            };            };
2952            //            //
2953            firstevno = lastentry + 1;            firstevno = lastentry + 1;
# Line 2567  Int_t PamelaDBOperations::insertCALO_CAL Line 3010  Int_t PamelaDBOperations::insertCALO_CAL
3010          fromtime = this->GetAbsTime(ph->GetOrbitalTime());            fromtime = this->GetAbsTime(ph->GetOrbitalTime());  
3011          if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->OBT(obt) >= this->OBT(obtfirst) ){          if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->OBT(obt) >= this->OBT(obtfirst) ){
3012            //            //
3013            if ( IsDebug() ) printf(" Calo calibration for section %i at time %i obt %i pkt %i \n",section,fromtime,obt,pkt);            if ( IsDebug() ) printf(" Calo calibration for section %i at time %u obt %u pkt %u \n",section,fromtime,obt,pkt);
3014            //            //
3015            // check if the calibration has already been inserted            // check if the calibration has already been inserted
3016            //            //
# Line 2588  Int_t PamelaDBOperations::insertCALO_CAL Line 3031  Int_t PamelaDBOperations::insertCALO_CAL
3031            if ( row ){            if ( row ){
3032              //              //
3033              if ( IsDebug() ) printf(" Calo calibration already inserted in the DB\n");              if ( IsDebug() ) printf(" Calo calibration already inserted in the DB\n");
3034                if ( PEDANTIC ) throw -73;
3035              //              //
3036            } else {            } else {
3037              //              //
# Line 2611  Int_t PamelaDBOperations::insertCALO_CAL Line 3055  Int_t PamelaDBOperations::insertCALO_CAL
3055                // no calibrations in the db contain our calibration                // no calibrations in the db contain our calibration
3056                //                //
3057                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);
3058                if ( fromtime < 1150863400 ){                if ( fromtime < 1150871000 ){ //1150866904
3059                  if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);                  if ( IsDebug() ) printf(" First PAMELA flight calibration at time %u \n",fromtime);
3060                  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
3061                };                };
3062                //                //
# Line 2674  Int_t PamelaDBOperations::insertCALO_CAL Line 3118  Int_t PamelaDBOperations::insertCALO_CAL
3118            //            //
3119          } else {          } else {
3120            //            //
3121            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 %u obt %u pkt %u \n",section,fromtime,obt,pkt);
3122              if ( PEDANTIC ) throw -74;
3123            //            //
3124          };                };      
3125          //                //      
# Line 2685  Int_t PamelaDBOperations::insertCALO_CAL Line 3130  Int_t PamelaDBOperations::insertCALO_CAL
3130    return(0);    return(0);
3131  };  };
3132    
3133    
3134  /**  /**
3135   * Fill the GL_TRK_CALIB table   * Scan calorimeter calibrations packets, fill the GL_CALO_CALIB table
3136   */   */
3137  void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){  Int_t PamelaDBOperations::insertCALOPULSE_CALIB(){
3138    //    //
3139    TSQLResult *result = 0;    TSQLResult *result = 0;
3140    TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
# Line 2696  void PamelaDBOperations::HandleTRK_CALIB Line 3142  void PamelaDBOperations::HandleTRK_CALIB
3142    stringstream oss;    stringstream oss;
3143    oss.str("");    oss.str("");
3144    //    //
3145    UInt_t totime = 0;    oss << " DESCRIBE GL_CALOPULSE_CALIB;";
3146      if ( IsDebug() ) printf(" Check if the GL_CALOPULSE_CALIB table exists: query is \n %s \n",oss.str().c_str());
3147      result = conn->Query(oss.str().c_str());
3148    //    //
3149    if ( !pk1 && !pk2 ){    if ( conn->GetErrorCode() ){
3150      if ( IsDebug() ) printf(" Cannot handle trk calibration with both packet missing!\n");      if ( IsDebug() ) printf(" The GL_CALOPULSE_CALIB table does not exists! \n");
3151        throw -30;
3152    };    };
3153    //    //
3154    // check if the calibration has already been inserted    // CaloPulse1
   //  
   oss.str("");  
   oss << " SELECT ID FROM GL_TRK_CALIB WHERE "  
       << " BOOT_NUMBER = "<< this->GetBOOTnumber(); //  
   oss << " AND ( ( ";    
   if ( pk1 ){  
     oss << " OBT1 = "<< obt1 << " AND "  
         << " PKT1 = "<< pkt1  
         << " ) OR ( ";  
   } else {  
     oss << " PKT1 = "<< pkt2-1  
         << " ) OR ( ";    
   };        
   if ( pk2 ){  
     oss << " OBT2 = "<< obt2 << " AND "  
         << " PKT2 = "<< pkt2;  
   } else {  
     oss << " PKT2 = "<< pkt1+1;  
   };        
   oss << " ) );";    
   //  
   if ( IsDebug() ) printf(" Check if the trk calibration has already been inserted: query is \n %s \n",oss.str().c_str());  
   result = conn->Query(oss.str().c_str());  
3155    //    //
3156    if ( !result ) throw -4;    CalibCalPulse1Event *cp1 = 0;
3157      TTree *tr = 0;
3158      EventHeader *eh = 0;
3159      PscuHeader *ph = 0;
3160    //    //
3161    row = result->Next();    UInt_t nevents = 0;
3162      UInt_t fromtime = 0;
3163      UInt_t totime = 0;
3164      UInt_t obt = 0;
3165      UInt_t pkt = 0;
3166      //
3167      tr = (TTree*)file->Get("CalibCalPulse1");
3168      if ( !tr || tr->IsZombie() ) throw -31;
3169      //
3170      tr->SetBranchAddress("CalibCalPulse1", &cp1);
3171      tr->SetBranchAddress("Header", &eh);
3172      nevents = tr->GetEntries();
3173      //
3174      if ( nevents > 0 ){
3175        //
3176        for (UInt_t i=0; i < nevents; i++){
3177          tr->GetEntry(i);
3178          for (UInt_t section = 0; section < 4; section++){
3179            //
3180            if ( cp1->pstwerr[section] && cp1->unpackError == 0 ){
3181              valid = 1;
3182              if ( cp1->pperror[section] ) valid = 0;
3183              ph = eh->GetPscuHeader();
3184              obt = ph->GetOrbitalTime();  
3185              pkt = ph->GetCounter();  
3186              fromtime = this->GetAbsTime(ph->GetOrbitalTime());  
3187              if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->OBT(obt) >= this->OBT(obtfirst) ){
3188                //
3189                if ( IsDebug() ) printf(" Calo pulse1 calibration for section %i at time %u obt %u pkt %u \n",section,fromtime,obt,pkt);
3190                //
3191                // check if the calibration has already been inserted
3192                //
3193                oss.str("");
3194                oss << " SELECT ID FROM GL_CALOPULSE_CALIB WHERE "
3195                    << " SECTION = "<< section << " AND "
3196                    << " PULSE_AMPLITUDE = 0 AND "
3197                    << " BOOT_NUMBER = "<< this->GetBOOTnumber() << " AND "
3198                    << " OBT = "<< obt << " AND "
3199                    << " PKT = "<< pkt << ";";
3200                //
3201                if ( IsDebug() ) printf(" Check if the calo pulse1 calibration has already been inserted: query is \n %s \n",oss.str().c_str());
3202                result = conn->Query(oss.str().c_str());
3203                //
3204                if ( !result ) throw -4;
3205                //
3206                row = result->Next();
3207                //
3208                if ( row ){
3209                  //
3210                  if ( IsDebug() ) printf(" Calo pulse1 calibration already inserted in the DB\n");
3211                  if ( PEDANTIC ) throw -75;
3212                  //
3213                } else {
3214                  //
3215                  // we have to insert a new calibration, check where to place it
3216                  //
3217                  oss.str("");
3218                  oss << " SELECT ID,TO_TIME FROM GL_CALOPULSE_CALIB WHERE "
3219                      << " SECTION = "<< section << " AND "
3220                      << " PULSE_AMPLITUDE = 0 AND "
3221                      << " SECTION = "<< section << " AND "
3222                      << " FROM_TIME < "<< fromtime << " AND "
3223                      << " TO_TIME > "<< fromtime << ";";
3224                  //
3225                  if ( IsDebug() ) printf(" Check where to place the pulse1 calo calibration: query is \n %s \n",oss.str().c_str());
3226                  result = conn->Query(oss.str().c_str());
3227                  //
3228                  if ( !result ) throw -4;
3229                  //
3230                  row = result->Next();
3231                  //
3232                  if ( !row ){
3233                    //
3234                    // no calibrations in the db contain our calibration
3235                    //
3236                    if ( IsDebug() ) printf(" Pulse1 calibration with fromtime lower than others to be inserted in the DB for section %i \n",section);
3237                    if ( fromtime < 1150871000 ){ //1150866904
3238                      if ( IsDebug() ) printf(" First PAMELA flight calibration at time %u \n",fromtime);
3239                      fromtime = 0;// the first flight calibration was taken at about  1156429100 s, this line allow to analyze first runs in raw mode
3240                    };
3241                    //
3242                    oss.str("");
3243                    oss << " SELECT FROM_TIME FROM GL_CALOPULSE_CALIB WHERE "
3244                        << " PULSE_AMPLITUDE = 0 AND "
3245                        << " SECTION = "<< section << " AND "
3246                        << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
3247                    //
3248                    if ( IsDebug() ) printf(" Check the upper limit for pulse1 calibration: query is \n %s \n",oss.str().c_str());
3249                    result = conn->Query(oss.str().c_str());
3250                    //
3251                    if ( !result ) throw -4;
3252                    //
3253                    row = result->Next();
3254                    if ( !row ){
3255                      totime = numeric_limits<UInt_t>::max();
3256                    } else {
3257                      totime = (UInt_t)atoll(row->GetField(0));
3258                    };
3259                    //
3260                  } else {
3261                    //
3262                    // determine upper and lower limits and make space for the new calibration
3263                    //
3264                    totime = (UInt_t)atoll(row->GetField(1));
3265                    //
3266                    oss.str("");
3267                    oss << " UPDATE GL_CALOPULSE_CALIB SET "  
3268                        << " TO_TIME = "<< fromtime << " WHERE "  // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
3269                        << " ID = "<< row->GetField(0) << ";";
3270                    //
3271                    if ( IsDebug() ) printf(" Make space for the new pulse1 calibration: query is \n %s \n",oss.str().c_str());
3272                    result = conn->Query(oss.str().c_str());
3273                    //
3274                    if ( !result ) throw -4;
3275                    //
3276                  };
3277                  //
3278                  oss.str("");
3279                  oss << " INSERT INTO GL_CALOPULSE_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,SECTION,PULSED_STRIP,PULSE_AMPLITUDE,OBT,PKT,BOOT_NUMBER,VALIDATION) "
3280                      << " VALUES (NULL,' "
3281                      << idroot << "','"
3282                      << i << "','"
3283                      << fromtime << "','"
3284                      << totime << "','"
3285                      << section << "',NULL,'0','"
3286                      << obt << "','"
3287                      << pkt << "','"
3288                      << this->GetBOOTnumber() << "','"
3289                      << valid << "');";
3290                  //
3291                  if ( IsDebug() ) printf(" Insert the new pulse1 calibration: query is \n %s \n",oss.str().c_str());
3292                  //
3293                  result = conn->Query(oss.str().c_str());
3294                  //
3295                  if ( !result ) throw -4;
3296                  //
3297                };
3298                //
3299              } else {
3300                //
3301                if ( IsDebug() ) printf(" Repeated pulse1 calo calibration for section %i at time %u obt %u pkt %u \n",section,fromtime,obt,pkt);
3302                if ( PEDANTIC ) throw -76;
3303                //
3304              };      
3305              //      
3306            };
3307          };
3308        };
3309      };
3310      //
3311      // CaloPulse2
3312      //
3313      tr->Reset();
3314      CalibCalPulse2Event *cp2 = 0;
3315      tr = 0;
3316      //
3317      nevents = 0;
3318      fromtime = 0;
3319      totime = 0;
3320      obt = 0;
3321      pkt = 0;
3322      //
3323      tr = (TTree*)file->Get("CalibCalPulse2");
3324      if ( !tr || tr->IsZombie() ) throw -32;
3325      //
3326      tr->SetBranchAddress("CalibCalPulse2", &cp2);
3327      tr->SetBranchAddress("Header", &eh);
3328      nevents = tr->GetEntries();
3329      //
3330      if ( nevents > 0 ){
3331        //
3332        for (UInt_t i=0; i < nevents; i++){
3333          tr->GetEntry(i);
3334          for (UInt_t section = 0; section < 4; section++){
3335            //
3336            if ( cp2->pstwerr[section] && cp2->unpackError == 0 ){
3337              valid = 1;
3338              if ( cp2->pperror[section] ) valid = 0;
3339              ph = eh->GetPscuHeader();
3340              obt = ph->GetOrbitalTime();  
3341              pkt = ph->GetCounter();  
3342              fromtime = this->GetAbsTime(ph->GetOrbitalTime());  
3343              if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->OBT(obt) >= this->OBT(obtfirst) ){
3344                //
3345                if ( IsDebug() ) printf(" Calo pulse2 calibration for section %i at time %u obt %u pkt %u \n",section,fromtime,obt,pkt);
3346                //
3347                // check if the calibration has already been inserted
3348                //
3349                oss.str("");
3350                oss << " SELECT ID FROM GL_CALOPULSE_CALIB WHERE "
3351                    << " SECTION = "<< section << " AND "
3352                    << " PULSE_AMPLITUDE != 0 AND "
3353                    << " BOOT_NUMBER = "<< this->GetBOOTnumber() << " AND "
3354                    << " OBT = "<< obt << " AND "
3355                    << " PKT = "<< pkt << ";";
3356                //
3357                if ( IsDebug() ) printf(" Check if the calo pulse2 calibration has already been inserted: query is \n %s \n",oss.str().c_str());
3358                result = conn->Query(oss.str().c_str());
3359                //
3360                if ( !result ) throw -4;
3361                //
3362                row = result->Next();
3363                //
3364                if ( row ){
3365                  //
3366                  if ( IsDebug() ) printf(" Calo pulse2 calibration already inserted in the DB\n");
3367                  if ( PEDANTIC ) throw -77;
3368                  //
3369                } else {
3370                  //
3371                  // we have to insert a new calibration
3372                  //
3373                  //
3374                  // Determine the amplitude of the pulse
3375                  //
3376                  UInt_t pampli = 1;
3377                  UInt_t pstrip = 0;
3378                  UInt_t se = 0;
3379                  if ( section == 1 ) se = 2;
3380                  if ( section == 2 ) se = 3;
3381                  if ( section == 3 ) se = 1;
3382                  for (Int_t ii=0;ii<16;ii++){
3383                    if ( cp2->calpuls[se][0][ii] > 10000. ){
3384                      pampli = 2;
3385                      pstrip = ii;
3386                    };
3387                  };
3388                  if ( pampli == 1 ){
3389                    Bool_t found = false;
3390                    Float_t delta=0.;
3391                    UInt_t cstr = 0;
3392                    while ( !found && cstr < 16 ){
3393                      for (Int_t ii=0;ii<16;ii++){
3394                        delta = cp2->calpuls[se][0][ii] - cp2->calpuls[se][0][cstr];
3395                        if ( IsDebug() ) printf(" cstr is %u ii is %i delta is %f \n",cstr,ii,delta);
3396                        if ( delta > 500. ){
3397                          pampli = 1;
3398                          pstrip = ii;
3399                          found = true;
3400                          if ( IsDebug() ) printf(" FOUND cstr is %u ii is %i delta is %f \n",cstr,ii,delta);
3401                        };
3402                      };
3403                      cstr++;
3404                    };
3405                    if ( !found ) pstrip = 100;
3406                  };
3407                  if ( IsDebug() ) printf(" The amplitude of the pulser is %u (where 1 = low pulse, 2 = high pulse), pulsed strip is %u \n",pampli,pstrip);
3408                  //
3409                  // we have to insert a new calibration, check where to place it
3410                  //
3411                  oss.str("");
3412                  oss << " SELECT ID,TO_TIME FROM GL_CALOPULSE_CALIB WHERE "
3413                      << " SECTION = "<< section << " AND "
3414                      << " PULSE_AMPLITUDE = " << pampli << " AND "
3415                      << " SECTION = "<< section << " AND "
3416                      << " FROM_TIME < "<< fromtime << " AND "
3417                      << " TO_TIME > "<< fromtime << ";";
3418                  //
3419                  if ( IsDebug() ) printf(" Check where to place the pulse2 calo calibration: query is \n %s \n",oss.str().c_str());
3420                  result = conn->Query(oss.str().c_str());
3421                  //
3422                  if ( !result ) throw -4;
3423                  //
3424                  row = result->Next();
3425                  //
3426                  if ( !row ){
3427                    //
3428                    // no calibrations in the db contain our calibration
3429                    //
3430                    if ( IsDebug() ) printf(" Pulse2 calibration with fromtime lower than others to be inserted in the DB for section %i \n",section);
3431                    if ( fromtime < 1150871000 ){ //1150866904
3432                      if ( IsDebug() ) printf(" First PAMELA flight calibration at time %u \n",fromtime);
3433                      fromtime = 0;// the first flight calibration was taken at about  1156429100 s, this line allow to analyze first runs in raw mode
3434                    };
3435                    //
3436                    oss.str("");
3437                    oss << " SELECT FROM_TIME FROM GL_CALOPULSE_CALIB WHERE "
3438                        << " PULSE_AMPLITUDE = " << pampli << " AND "
3439                        << " SECTION = "<< section << " AND "
3440                        << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
3441                    //
3442                    if ( IsDebug() ) printf(" Check the upper limit for pulse2 calibration: query is \n %s \n",oss.str().c_str());
3443                    result = conn->Query(oss.str().c_str());
3444                    //
3445                    if ( !result ) throw -4;
3446                    //
3447                    row = result->Next();
3448                    if ( !row ){
3449                      totime = numeric_limits<UInt_t>::max();
3450                    } else {
3451                      totime = (UInt_t)atoll(row->GetField(0));
3452                    };
3453                    //
3454                  } else {
3455                    //
3456                    // determine upper and lower limits and make space for the new calibration
3457                    //
3458                    totime = (UInt_t)atoll(row->GetField(1));
3459                    //
3460                    oss.str("");
3461                    oss << " UPDATE GL_CALOPULSE_CALIB SET "  
3462                        << " TO_TIME = "<< fromtime << " WHERE "  // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
3463                        << " ID = "<< row->GetField(0) << ";";
3464                    //
3465                    if ( IsDebug() ) printf(" Make space for the new pulse2 calibration: query is \n %s \n",oss.str().c_str());
3466                    result = conn->Query(oss.str().c_str());
3467                    //
3468                    if ( !result ) throw -4;
3469                    //
3470                  };
3471                  //
3472                  // Fill the DB
3473                  //
3474                  oss.str("");
3475                  //              oss << " INSERT INTO GL_CALOPULSE_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,SECTION,OBT,PKT,BOOT_NUMBER,VALIDATION) "
3476                  oss << " INSERT INTO GL_CALOPULSE_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,SECTION,PULSED_STRIP,PULSE_AMPLITUDE,OBT,PKT,BOOT_NUMBER,VALIDATION) "
3477                      << " VALUES (NULL,' "
3478                      << idroot << "','"
3479                      << i << "','"
3480                      << fromtime << "','"
3481                      << totime << "','"
3482                      << section << "','"
3483                      << pstrip << "','"
3484                      << pampli << "','"
3485                      << obt << "','"
3486                      << pkt << "','"
3487                      << this->GetBOOTnumber() << "','"
3488                      << valid << "');";
3489                  //
3490                  if ( IsDebug() ) printf(" Insert the new pulse2 calibration: query is \n %s \n",oss.str().c_str());
3491                  //
3492                  result = conn->Query(oss.str().c_str());
3493                  //
3494                  if ( !result ) throw -4;
3495                  //
3496                };
3497                //
3498              } else {
3499                //
3500                if ( IsDebug() ) printf(" Repeated pulse2 calo calibration for section %i at time %u obt %u pkt %u \n",section,fromtime,obt,pkt);
3501                if ( PEDANTIC ) throw -78;
3502                //
3503              };      
3504              //      
3505            };
3506          };
3507        };
3508      };
3509      //
3510      return(0);
3511    };
3512    
3513    /**
3514     * Fill the GL_TRK_CALIB table
3515     */
3516    void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){
3517      //
3518      TSQLResult *result = 0;
3519      TSQLRow    *row    = 0;
3520      //
3521      stringstream oss;
3522      oss.str("");
3523      //
3524      UInt_t totime = 0;
3525      //
3526      if ( !pk1 && !pk2 ){
3527        if ( IsDebug() ) printf(" Cannot handle trk calibration with both packet missing!\n");
3528      };
3529      //
3530      // check if the calibration has already been inserted
3531      //
3532      oss.str("");
3533      oss << " SELECT ID FROM GL_TRK_CALIB WHERE "
3534          << " BOOT_NUMBER = "<< this->GetBOOTnumber(); //
3535      oss << " AND ( ( ";  
3536      if ( pk1 ){
3537        oss << " OBT1 = "<< obt1 << " AND "
3538            << " PKT1 = "<< pkt1
3539            << " ) OR ( ";
3540      } else {
3541        oss << " PKT1 = "<< pkt2-1
3542            << " ) OR ( ";  
3543      };      
3544      if ( pk2 ){
3545        oss << " OBT2 = "<< obt2 << " AND "
3546            << " PKT2 = "<< pkt2;
3547      } else {
3548        oss << " PKT2 = "<< pkt1+1;
3549      };      
3550      oss << " ) );";  
3551      //
3552      if ( IsDebug() ) printf(" Check if the trk calibration has already been inserted: query is \n %s \n",oss.str().c_str());
3553      result = conn->Query(oss.str().c_str());
3554      //
3555      if ( !result ) throw -4;
3556      //
3557      row = result->Next();
3558    //    //
3559    if ( row ){    if ( row ){
3560      //      //
3561      if ( IsDebug() ) printf(" Trk calibration already inserted in the DB\n");      if ( IsDebug() ) printf(" Trk calibration already inserted in the DB\n");
3562        if ( PEDANTIC ) throw -80;
3563      //      //
3564    } else {    } else {
3565      //      //
# Line 2756  void PamelaDBOperations::HandleTRK_CALIB Line 3582  void PamelaDBOperations::HandleTRK_CALIB
3582        // no calibrations in the db contain our calibration        // no calibrations in the db contain our calibration
3583        //        //
3584        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");
3585        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
3586        //        //
3587        oss.str("");        oss.str("");
3588        oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "        oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "
# Line 2885  Int_t PamelaDBOperations::insertTRK_CALI Line 3711  Int_t PamelaDBOperations::insertTRK_CALI
3711      pkt1 = ph1->GetCounter();        pkt1 = ph1->GetCounter();  
3712      fromtime = this->GetAbsTime(ph1->GetOrbitalTime());        fromtime = this->GetAbsTime(ph1->GetOrbitalTime());  
3713      //      //
3714      valid = 1;  //     valid = 1;
3715      //  //     //
3716      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
3717      //      //
3718      //      //
3719      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) ){
3720        //        //
3721        if ( IsDebug() ) printf(" Trk calibration1 at time %i obt %i pkt %i \n",fromtime,obt1,pkt1);        if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u \n",fromtime,obt1,pkt1);
3722          //      
3723          valid = ValidateTrkCalib( caltrk1, eh1 );
3724          if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;
3725        //        //
3726        // Do we have the second calibration packet?        // Do we have the second calibration packet?
3727        //        //
# Line 2909  Int_t PamelaDBOperations::insertTRK_CALI Line 3738  Int_t PamelaDBOperations::insertTRK_CALI
3738            obt2 = ph2->GetOrbitalTime();              obt2 = ph2->GetOrbitalTime();  
3739            pkt2 = ph2->GetCounter();              pkt2 = ph2->GetCounter();  
3740            //            //
3741            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
3742            //                  //      
3743          } else {          } else {
3744            //            //
# Line 2932  Int_t PamelaDBOperations::insertTRK_CALI Line 3761  Int_t PamelaDBOperations::insertTRK_CALI
3761          //          //
3762        };        };
3763        //        //
3764        if ( IsDebug() ) printf(" Found trk calibration2 at obt %i pkt %i t2 is %i \n",obt2,pkt2,t2);        if ( IsDebug() ) printf(" Found trk calibration2 at obt %u pkt %u t2 is %u \n",obt2,pkt2,t2);
3765        //        //
3766        // The calibration is good        // The calibration is good
3767        //        //
3768        if ( this->PKT(pkt2) == this->PKT(pkt1)+1 ){        if ( this->PKT(pkt2) == this->PKT(pkt1)+1 ){
3769          //          //
3770          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 %u pkt %u t2 is %u is good \n",obt2,pkt2,t2);
3771            //
3772            UInt_t valid2 = ValidateTrkCalib( caltrk2, eh2 );
3773            if ( IsDebug() ) cout << " pkt2 validation --> "<<valid2<<endl;
3774            valid = valid & valid2;
3775          //          //
3776          // Handle good calib          // Handle good calib
3777          //          //
# Line 2948  Int_t PamelaDBOperations::insertTRK_CALI Line 3781  Int_t PamelaDBOperations::insertTRK_CALI
3781          //          //
3782          if ( t2 != pret2+1 ){          if ( t2 != pret2+1 ){
3783            //            //
3784            if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %i pkt %i t2 is %i pret2 is %i \n",obt2,pkt2,t2,pret2);            if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %u pkt %u t2 is %u pret2 is %u \n",obt2,pkt2,t2,pret2);
3785            //            //
3786            while ( t2 > pret2+1 ){            while ( t2 > pret2+1 ){
3787              //              //
# Line 2977  Int_t PamelaDBOperations::insertTRK_CALI Line 3810  Int_t PamelaDBOperations::insertTRK_CALI
3810          //          //
3811          // Check for missing calibtrk2          // Check for missing calibtrk2
3812          //          //
3813          if ( IsDebug() ) printf(" Missing the trk calibration2! Next one at obt %i pkt %i t2 is %i\n",obt2,pkt2,t2);          if ( IsDebug() ) printf(" Missing the trk calibration2! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);
3814          t2 = pret2;          t2 = pret2;
3815          //          //
3816          // handle missing calib2          // handle missing calib2
# Line 2991  Int_t PamelaDBOperations::insertTRK_CALI Line 3824  Int_t PamelaDBOperations::insertTRK_CALI
3824        //        //
3825      } else {      } else {
3826        //        //
3827        if ( IsDebug() ) printf(" Repetead trk calibration1 at time %i obt %i pkt %i \n",fromtime,obt1,pkt1);        if ( IsDebug() ) printf(" Repetead trk calibration1 at time %u obt %u pkt %u \n",fromtime,obt1,pkt1);
3828          if ( PEDANTIC ) throw -79;
3829        //        //
3830      };      };
3831      //          //    
# Line 3016  Int_t PamelaDBOperations::insertTRK_CALI Line 3850  Int_t PamelaDBOperations::insertTRK_CALI
3850      valid = 0;      valid = 0;
3851      if ( this->PKT(pkt2) > this->PKT(pktfirst) || this->OBT(obt2) > this->OBT(obtfirst) ){      if ( this->PKT(pkt2) > this->PKT(pktfirst) || this->OBT(obt2) > this->OBT(obtfirst) ){
3852        //        //
3853        if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %i pkt %i t2 is %i\n",obt2,pkt2,t2);        if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);
3854        //        //
3855        this->HandleTRK_CALIB(false,true);        this->HandleTRK_CALIB(false,true);
3856        //        //
# Line 3070  Int_t PamelaDBOperations::insertS4_CALIB Line 3904  Int_t PamelaDBOperations::insertS4_CALIB
3904      fromtime = this->GetAbsTime(ph->GetOrbitalTime());        fromtime = this->GetAbsTime(ph->GetOrbitalTime());  
3905      if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->OBT(obt) >= this->OBT(obtfirst) ){      if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->OBT(obt) >= this->OBT(obtfirst) ){
3906        //        //
3907        if ( IsDebug() ) printf(" S4 calibration at time %i obt %i pkt %i \n",fromtime,obt,pkt);        if ( IsDebug() ) printf(" S4 calibration at time %u obt %u pkt %u \n",fromtime,obt,pkt);
3908        //        //
3909        // check if the calibration has already been inserted        // check if the calibration has already been inserted
3910        //        //
# Line 3090  Int_t PamelaDBOperations::insertS4_CALIB Line 3924  Int_t PamelaDBOperations::insertS4_CALIB
3924        if ( row ){        if ( row ){
3925          //          //
3926          if ( IsDebug() ) printf(" S4 calibration already inserted in the DB\n");          if ( IsDebug() ) printf(" S4 calibration already inserted in the DB\n");
3927            if ( PEDANTIC ) throw -81;
3928          //          //
3929        } else {        } else {
3930          //          //
# Line 3112  Int_t PamelaDBOperations::insertS4_CALIB Line 3947  Int_t PamelaDBOperations::insertS4_CALIB
3947            // no calibrations in the db contain our calibration            // no calibrations in the db contain our calibration
3948            //            //
3949            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");
3950            if ( fromtime < 1150863400 ){            if ( fromtime < 1150871000 ){  
3951              if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);              if ( IsDebug() ) printf(" First PAMELA flight calibration at time %u \n",fromtime);
3952              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
3953            };            };
3954            //            //
# Line 3172  Int_t PamelaDBOperations::insertS4_CALIB Line 4007  Int_t PamelaDBOperations::insertS4_CALIB
4007        //        //
4008      } else {      } else {
4009        //        //
4010        if ( IsDebug() ) printf(" Repetead S4 calibration at time %i obt %i pkt %i \n",fromtime,obt,pkt);        if ( IsDebug() ) printf(" Repeated S4 calibration at time %u obt %u pkt %u \n",fromtime,obt,pkt);
4011          if ( PEDANTIC ) throw -82;
4012        //        //
4013      };            };      
4014      //            //      
# Line 3185  Int_t PamelaDBOperations::insertS4_CALIB Line 4021  Int_t PamelaDBOperations::insertS4_CALIB
4021   * Scan the fragment table and move old fragments to the GL_RUN table   * Scan the fragment table and move old fragments to the GL_RUN table
4022   */   */
4023  Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(){  Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(){
4024      return(this->CleanGL_RUN_FRAGMENTS(""));
4025    };
4026    
4027    /**
4028     * Scan the fragment table and move old fragments to the GL_RUN table
4029     */
4030    Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(TString fcleanfile){
4031    //    //
4032    TSQLResult *result = 0;    TSQLResult *result = 0;
4033    TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
# Line 3192  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 4035  Int_t PamelaDBOperations::CleanGL_RUN_FR
4035    TSQLRow    *row2   = 0;    TSQLRow    *row2   = 0;
4036    //    //
4037    UInt_t moved = 0;    UInt_t moved = 0;
 //  UInt_t timelim = 0;  
 //  TDatime *time = new TDatime();  
4038    //    //
4039    stringstream oss;    stringstream oss;
4040    oss.str("");    oss.str("");
4041    //    //
4042    //    if ( !strcmp(fcleanfile.Data(),"") ){
4043    // check if there are entries older than "olderthan" seconds from now      //
4044    //      // check if there are entries older than "olderthan" seconds from now
4045    oss.str("");      //
4046    oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"      oss.str("");
4047        << " INSERT_TIME <= '" << clean_time->AsSQLString() << "';";      oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
4048    //          << " INSERT_TIME <= '" << clean_time->AsSQLString() << "';";
4049    if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS runs older than %s : query is \n %s \n",clean_time->AsSQLString(),oss.str().c_str());      //
4050    result = conn->Query(oss.str().c_str());      if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS runs older than %s : query is \n %s \n",clean_time->AsSQLString(),oss.str().c_str());
4051        result = conn->Query(oss.str().c_str());
4052        //
4053      } else {
4054        oss.str("");
4055        oss << " SELECT ID FROM GL_ROOT WHERE NAME='" << fcleanfile.Data() << "';";
4056        if ( IsDebug() ) printf(" Getting ID_ROOT_L0 query %s \n",oss.str().c_str());
4057        result = conn->Query(oss.str().c_str());
4058        //    
4059        if ( result ){
4060          //
4061          row = result->Next();
4062          //
4063          if ( row ){
4064            oss.str("");
4065            oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
4066                << " ID_ROOT_L0=" << row->GetField(0) << ";";
4067            //
4068            if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS for ROOT file query is \n %s \n",oss.str().c_str());
4069            result = conn->Query(oss.str().c_str());
4070            //    
4071          };
4072        } else {
4073          return(2);
4074        };
4075      };
4076    //    //
4077    if ( result ){    if ( result ){
4078      //      //
4079      row = result->Next();      row = result->Next();
4080      //      //
4081      if ( row ){      while ( row ){
4082        //        //
4083        oss.str("");        oss.str("");
4084        oss << " ID= "<< row->GetField(0);        oss << " ID= "<< row->GetField(0);
# Line 3247  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 4113  Int_t PamelaDBOperations::CleanGL_RUN_FR
4113          if ( IsDebug() ) printf(" The run is new \n");          if ( IsDebug() ) printf(" The run is new \n");
4114          if ( IsDebug() ) printf(" -> fill the DB \n");                if ( IsDebug() ) printf(" -> fill the DB \n");      
4115          //          //
4116          glrun->SetID(0);          //      glrun->SetID(this->AssignRunID()); we use the old run number!
4117            glrun->SetID_RUN_FRAG(glrun->GetID());
4118          glrun->Fill_GL_RUN(conn);            glrun->Fill_GL_RUN(conn);  
4119          //          //
4120          oss.str("");  //      oss.str("");
4121          oss << " SELECT ID FROM GL_RUN WHERE "  //      oss << " SELECT ID FROM GL_RUN WHERE "
4122              << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "  //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
4123              << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "  //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
4124              << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "  //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
4125              << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "  //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
4126              << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";  //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
4127          //  //      //
4128          if ( IsDebug() ) printf(" Look for the ID of the inserted run: query is \n %s \n",oss.str().c_str());  //      if ( IsDebug() ) printf(" Look for the ID of the inserted run: query is \n %s \n",oss.str().c_str());
4129          result2 = conn->Query(oss.str().c_str());  //      result2 = conn->Query(oss.str().c_str());
4130          //  //      //
4131          if ( !result2 ) throw -4;  //      if ( !result2 ) throw -4;
4132          //  //      //
4133          row2 = result2->Next();  //      row2 = result2->Next();
4134          //  //      //
4135          if ( !row2 ) throw -25;  //      if ( !row2 ) throw -25;
4136          //  //      //
4137          oss.str("");  //      oss.str("");
4138          oss << " UPDATE GL_RUN SET ID_RUN_FRAG = " << row2->GetField(0) << " WHERE ID = " << row2->GetField(0);  //      oss << " UPDATE GL_RUN SET ID_RUN_FRAG = " << row2->GetField(0) << " WHERE ID = " << row2->GetField(0);
4139          if ( IsDebug() ) printf(" Update the ID_RUN_FRAG of the inserted run: query is \n %s \n",oss.str().c_str());  //      if ( IsDebug() ) printf(" Update the ID_RUN_FRAG of the inserted run: query is \n %s \n",oss.str().c_str());
4140          result2 = conn->Query(oss.str().c_str());  //      result2 = conn->Query(oss.str().c_str());
4141          //  //      //
4142          if ( !result2 ) throw -4;  //      if ( !result2 ) throw -4;
4143          //          //
4144          moved++;          moved++;
4145          //          //
4146        } else {        } else {
4147          if ( IsDebug() ) printf(" The already exist in the GL_RUN table! \n");          if ( IsDebug() ) printf(" The already exist in the GL_RUN table! \n");
4148            if ( PEDANTIC ) throw -83;
4149        };        };
4150        if ( IsDebug() ) printf(" Delete run %s from the GL_RUN_FRAGMENTS table \n",row->GetField(0));              if ( IsDebug() ) printf(" Delete run %s from the GL_RUN_FRAGMENTS table \n",row->GetField(0));      
4151        //        //
4152        //        //
4153        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
4154        oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);  //      oss.str("");
4155        if ( IsDebug() ) printf(" Clean the GL_RUN_FRAGMENTS table: query is \n %s \n",oss.str().c_str());  //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);
4156        result2 = conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" Clean the GL_RUN_FRAGMENTS table: query is \n %s \n",oss.str().c_str());
4157        //  //       result2 = conn->Query(oss.str().c_str());
4158        if ( !result2 ) throw -4;  //      //
4159        //  //      if ( !result2 ) throw -4;
4160    //      //
4161          row = result->Next();
4162      };      };
4163    };    };
4164    if ( IsDebug() ) printf(" Moved %u runs\n",moved);    if ( IsDebug() ) printf(" Moved %u runs\n",moved);
# Line 3299  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 4169  Int_t PamelaDBOperations::CleanGL_RUN_FR
4169   * Check if runs are good, i.e. if the tracker calibration is correctly associated..   * Check if runs are good, i.e. if the tracker calibration is correctly associated..
4170   */   */
4171  Int_t PamelaDBOperations::ValidateRuns(){  Int_t PamelaDBOperations::ValidateRuns(){
4172      return(this->ValidateRuns(""));
4173    };
4174    
4175    /**
4176     * Check if runs are good, i.e. if the tracker calibration is correctly associated..
4177     */
4178    Int_t PamelaDBOperations::ValidateRuns(TString valfile){
4179    //    //
4180    TSQLResult *result = 0;    TSQLResult *result = 0;
4181    TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
4182    //    //
4183      UInt_t calibtime = 50;
4184      //
4185    stringstream oss;    stringstream oss;
4186    oss.str("");    oss.str("");
4187    //    //
# Line 3311  Int_t PamelaDBOperations::ValidateRuns() Line 4190  Int_t PamelaDBOperations::ValidateRuns()
4190    // =======================================================    // =======================================================
4191    UInt_t t_stop  = 0;    UInt_t t_stop  = 0;
4192    UInt_t t_start = 0;    UInt_t t_start = 0;
4193    // --------------------------------------------------------------    if ( !strcmp(valfile.Data(),"") ) {
4194    // 1) get the OBT of the last run inserted after clean-time limit      // --------------------------------------------------------------
4195    // --------------------------------------------------------------      // 1) get the OBT of the last run inserted after clean-time limit
4196    oss.str("");      // --------------------------------------------------------------
4197    oss << " SELECT * FROM GL_RUN  WHERE INSERT_TIME <= '" << clean_time->AsSQLString()      oss.str("");
4198            << "' ORDER BY RUNHEADER_TIME DESC LIMIT 1;";      oss << " SELECT * FROM GL_RUN  WHERE INSERT_TIME <= '" << clean_time->AsSQLString()
4199    if ( IsDebug() ) printf(" Get start validation-time: query is \n %s \n",oss.str().c_str());          << "' ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
4200    result = conn->Query(oss.str().c_str());      if ( IsDebug() ) printf(" Get start validation-time: query is \n %s \n",oss.str().c_str());
4201    if ( !result ) throw -4;      result = conn->Query(oss.str().c_str());
4202    if ( !result->GetRowCount() ) {      if ( !result ) throw -4;
4203            printf(" No runs to validate \n");      if ( !result->GetRowCount() ) {
4204            return(1);        printf(" No runs to validate \n");
4205    }else{        return(1);
4206          row = result->Next();      }else{
4207          t_start = (UInt_t)atoll(row->GetField(4));        row = result->Next();
4208    };          t_start = (UInt_t)atoll(row->GetField(4));
4209    // --------------------------------------------------------------      };  
4210    // 2) get the OBT of the last validated run      // --------------------------------------------------------------
4211    // --------------------------------------------------------------      // 2) get the OBT of the last validated run
4212    oss.str("");      // --------------------------------------------------------------
4213    oss << " SELECT * FROM GL_RUN  WHERE VALIDATION=1 AND RUNHEADER_TIME<="<< t_start      oss.str("");
4214        <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";      oss << " SELECT * FROM GL_RUN  WHERE VALIDATION=1 AND RUNHEADER_TIME<="<< t_start
4215    if ( IsDebug() ) printf(" Get stop validation-time: query is \n %s \n",oss.str().c_str());          <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
4216    result = conn->Query(oss.str().c_str());      if ( IsDebug() ) printf(" Get stop validation-time: query is \n %s \n",oss.str().c_str());
4217    if ( !result ) throw -4;      result = conn->Query(oss.str().c_str());
4218    if ( result->GetRowCount() ){      if ( !result ) throw -4;
4219            row = result->Next();      if ( result->GetRowCount() ){
4220            t_stop = (UInt_t)atoll(row->GetField(4));        row = result->Next();
4221    };        t_stop = (UInt_t)atoll(row->GetField(4));
4222    if ( IsDebug() ) printf("Validation interval: from time %i - to time %i \n\n",t_stop,t_start);      };
4223    // --------------------------------------------------------------      if ( IsDebug() ) printf("Validation interval: from time %u - to time %u \n\n",t_stop,t_start);
4224    // now retrieves runs to be validated      // --------------------------------------------------------------
4225    // --------------------------------------------------------------      // now retrieves runs to be validated
4226    oss.str("");      // --------------------------------------------------------------
4227    oss << " SELECT * FROM GL_RUN  WHERE  RUNHEADER_TIME <=" << t_start;      oss.str("");
4228    oss << " AND RUNHEADER_TIME >="<< t_stop;      oss << " SELECT * FROM GL_RUN  WHERE  RUNHEADER_TIME <=" << t_start;
4229    oss << " ORDER BY RUNHEADER_TIME DESC;";      oss << " AND RUNHEADER_TIME >="<< t_stop;
4230  //  if ( IsDebug() )      oss << " ORDER BY RUNHEADER_TIME DESC;";
4231    if ( IsDebug() )printf(" Check runs for validation: query is \n %s \n",oss.str().c_str());      if ( IsDebug() )printf(" Check runs for validation: query is \n %s \n",oss.str().c_str());
4232    result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
4233    if ( !result ) throw -4;    } else {
4234    if ( !result->GetRowCount() ) printf(" No runs to validate \n");      //
4235  //  printf("------------------------------------------------------------------------------- \n");      stringstream myquery;
4236          UInt_t myid = 0;
4237    Int_t nrow = 0;      myquery.str("");
4238    GL_RUN* this_run = new GL_RUN();      myquery << " SELECT ID FROM GL_ROOT where NAME='"<<valfile.Data() <<"';";
4239    GL_RUN* next_run = new GL_RUN();      //
4240    Int_t   nseq_max = 1000;      result = conn->Query(myquery.str().c_str());
4241  //  UInt_t* sequence = new UInt_t[100];      //
4242    vector<UInt_t> sequence(nseq_max);      row = result->Next();      
4243    Int_t   nseq = 0;      if( !row ){
4244    Bool_t CHECK = false;        if ( strcmp(valfile.Data(),GetRootName().Data()) ){
4245    Bool_t this_ONLINE = false;          if ( IsDebug() ) printf(" No file to be validated even if option \"-validate file\" was used!!\n");
4246    Bool_t next_ONLINE = false;          return(2);
4247    UInt_t t1=0,t2=0;        };
4248    // ---------------------------------------------------------------------------------        if ( IsDebug() ) printf(" No file to be validated (force mode)! \n");
4249    // - loop over runs, back in time,        return(0);
4250    // - select sequences of runs close in time (less than 60 s apart),      };
4251    //   which could be preceeded by a calibration      myid=(UInt_t)atoll(row->GetField(0));
4252    // - check if there might be a missing calibration      //
4253    // ---------------------------------------------------------------------------------      myquery.str("");
4254    while(1){      myquery << " SELECT MAX(RUNTRAILER_TIME),MIN(RUNHEADER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< myid <<";";
4255                  //
4256            row = result->Next();      result = conn->Query(myquery.str().c_str());
4257        //
4258        row = result->Next();      
4259        if( !row->GetField(0) || !row->GetField(1)){
4260          //
4261          if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
4262          //
4263          return(0);
4264          //
4265        } else {  
4266          //
4267          UInt_t runhtime = (UInt_t)atoll(row->GetField(0));
4268          UInt_t runttime = (UInt_t)atoll(row->GetField(1));
4269          UInt_t caltime = 0;
4270          //
4271          myquery.str("");
4272          myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
4273          myquery << " order by FROM_TIME asc limit 1;";
4274          //
4275          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4276          //
4277          //
4278          result = conn->Query(myquery.str().c_str());
4279          //
4280          row = result->Next();      
4281          if( !row ){
4282            caltime = runhtime;
4283          } else {
4284            caltime = (UInt_t)atoll(row->GetField(0));
4285          };
4286          //
4287          myquery.str("");
4288          myquery << " SELECT * from GL_RUN where RUNHEADER_TIME>="<< runttime <<" AND RUNHEADER_TIME<=" ;
4289          myquery << caltime << " order by RUNHEADER_TIME DESC";
4290          //
4291          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4292          //
4293          result = conn->Query(myquery.str().c_str());
4294          //
4295        };
4296      };
4297      //
4298      if ( !result ) throw -4;
4299      if ( !result->GetRowCount() && IsDebug() ) printf(" No runs to validate \n");
4300      //
4301      Int_t nrow = 0;
4302      GL_RUN* this_run = new GL_RUN();
4303      GL_RUN* next_run = new GL_RUN();
4304      Int_t   nseq_max = 1000;
4305    //  UInt_t* sequence = new UInt_t[100];
4306      vector<UInt_t> sequence(nseq_max);
4307      Int_t   nseq = 0;
4308      Bool_t CHECK = false;
4309      Bool_t this_ONLINE = false;
4310      Bool_t next_ONLINE = false;
4311      UInt_t t1=0,t2=0;
4312      // ---------------------------------------------------------------------------------
4313      // - loop over runs, back in time,
4314      // - select sequences of runs close in time (less than calibtime s apart),
4315      //   which could be preceeded by a calibration
4316      // - check if there might be a missing calibration
4317      // ---------------------------------------------------------------------------------
4318      while(1){
4319              
4320              row = result->Next();
4321            if( row == NULL ) break;            if( row == NULL ) break;
4322                        
4323            //------------            //------------
# Line 3408  Int_t PamelaDBOperations::ValidateRuns() Line 4351  Int_t PamelaDBOperations::ValidateRuns()
4351                                                        
4352                            if( this_run->ID == next_run->ID_RUN_FRAG ) interval = 0;     //=> run fragments                            if( this_run->ID == next_run->ID_RUN_FRAG ) interval = 0;     //=> run fragments
4353                                                        
4354                            if( interval >= 60 )CHECK = true;                     //more than 60 s => there might be a calibration                            if( interval >= calibtime )CHECK = true;                      //more than calibtime s => there might be a calibration
4355                                                        
4356                            if( !CHECK && this_run->VALIDATION ){                            if( !CHECK && this_run->VALIDATION ){
4357                                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);                                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
# Line 3448  Int_t PamelaDBOperations::ValidateRuns() Line 4391  Int_t PamelaDBOperations::ValidateRuns()
4391                    }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);                    }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);
4392            };            };
4393                        
4394            if ( IsDebug() ) printf("%i Run %i \n",nrow,this_run->ID);            if ( IsDebug() ) printf("%i Run %u \n",nrow,this_run->ID);
4395            nrow++;            nrow++;
4396                        
4397    };    };
# Line 3477  Bool_t PamelaDBOperations::MissingTRK_CA Line 4420  Bool_t PamelaDBOperations::MissingTRK_CA
4420          // which should be equal to the time between ascending-nodes.          // which should be equal to the time between ascending-nodes.
4421          //==============================================================          //==============================================================
4422          if ( t2 - trkcalib->FROM_TIME > 5700) {          if ( t2 - trkcalib->FROM_TIME > 5700) {
4423                  if ( IsDebug() )printf("Long time between calib and run start %i :-( ==> there might be a missing calib \n",t2 - trkcalib->FROM_TIME);                  if ( IsDebug() )printf("Long time between calib and run start %u :-( ==> there might be a missing calib \n",t2 - trkcalib->FROM_TIME);
4424          //==============================================================          //==============================================================
4425          // there might be a missing calibration, due to:          // there might be a missing calibration, due to:
4426          // - MM full          // - MM full
# Line 3498  Bool_t PamelaDBOperations::MissingTRK_CA Line 4441  Bool_t PamelaDBOperations::MissingTRK_CA
4441          // it is enough to say that there are no missing calibrations          // it is enough to say that there are no missing calibrations
4442          //==============================================================          //==============================================================
4443          // the long time interval bewteen runs might be due to download          // the long time interval bewteen runs might be due to download
4444          if ( IsDebug() )printf("Short time between calib and run start %i :-) ==> OK! \n",t2 - trkcalib->FROM_TIME);          if ( IsDebug() )printf("Short time between calib and run start %u :-) ==> OK! \n",t2 - trkcalib->FROM_TIME);
4445          return(false);          return(false);
4446                    
4447  };  };
# Line 3523  Int_t PamelaDBOperations::assignVALIDATI Line 4466  Int_t PamelaDBOperations::assignVALIDATI
4466    
4467    
4468    
4469    // Insert TLEs from file tlefilename in the table GL_TLE in the db
4470    // opened by conn, sorting them by date from older to newer, if each
4471    // TLE has not been alread inserted.
4472    Int_t PamelaDBOperations::populateTLE()//(TSQLServer *conn, char *tleFile)
4473    {
4474      fstream tlefile(tlefilename, ios::in);
4475    
4476      if ( !tlefile ) throw -7;
4477    
4478      vector<cTle*> ctles;
4479      vector<cTle*>::iterator iter;
4480      int present = 0;
4481    
4482      // Get three lines from tlefile, create a cTle object and put it
4483      // into ctles
4484      while(1) {
4485        cTle *tlef;
4486        string str1, str2, str3;
4487    
4488        getline(tlefile, str1);
4489        if(tlefile.eof()) break;
4490    
4491        getline(tlefile, str2);
4492        if(tlefile.eof()) break;
4493    
4494        getline(tlefile, str3);
4495        if(tlefile.eof()) break;
4496    
4497        // We now have three good lines for a cTle.
4498        tlef = new cTle(str1, str2, str3);
4499        ctles.push_back(tlef);
4500      }
4501    
4502      tlefile.close();
4503    
4504      // Sort by date
4505      sort(ctles.begin(), ctles.end(), compTLE);
4506    
4507      // Now we insert each TLE into the db
4508      for(iter = ctles.begin(); iter != ctles.end(); iter++) {
4509        cTle *tle = *iter;
4510    
4511        // Do nothing if it's already present in the db.  Just increase
4512        // the counter present.
4513        if (! isTlePresent(tle))
4514          {
4515            int status = insertTle(tle);
4516    
4517            // Insert query failed.  Return 1.
4518            if(status == EXIT_FAILURE) {
4519              
4520              if( IsDebug() ) {
4521                cerr << "Error: inserting TLE:" << endl
4522                     << tle->getName() << endl
4523                     << tle->getLine1() << endl
4524                     << tle->getLine2() << endl;
4525              }
4526    
4527              throw -4;
4528              return 1;
4529            }
4530    
4531          }
4532        else
4533          present++;
4534    
4535      }
4536    
4537      int inserted = ctles.size() - present;  // Number of inserted TLE.
4538      if ( IsDebug() )
4539        cout << "\nProcessed TLEs ranging from " << getTleDatetime(ctles[0]) << " to " << getTleDatetime(ctles[ctles.size()-1]) << "." << endl
4540             << inserted << " newly inserted TLEs out of " << ctles.size() << " processed." << endl;
4541    
4542      ctles.clear();
4543    
4544    
4545      // Return 2 if no new TLE has been inserted.  0 otherwise.
4546      if(! inserted ) return 2;
4547      return 0;
4548    }
4549    
4550    
4551    // Insert tle in the table GL_TLE using the connection conn.
4552    Int_t PamelaDBOperations::insertTle(cTle *tle)
4553    {
4554      stringstream oss;
4555      TSQLResult *result = 0;
4556    
4557      oss.str("");
4558      oss << " INSERT INTO GL_TLE (TLE1, TLE2, TLE3, FROM_TIME)"
4559          << " VALUES ( '"
4560          << tle->getName() << "', '"
4561          << tle->getLine1() << "', '"
4562          << tle->getLine2() << "', '"
4563          << getTleDatetime(tle) << "')";
4564    
4565      //  cout << oss.str().c_str() << endl;
4566      result = conn->Query(oss.str().c_str());
4567      if (result == NULL)
4568        return EXIT_FAILURE;
4569    
4570      return EXIT_SUCCESS;
4571    }
4572    
4573    
4574    // Return whether tle is already in the db connected by conn.
4575    bool PamelaDBOperations::isTlePresent(cTle *tle)
4576    {
4577      stringstream oss;
4578      TSQLResult *result = 0;
4579    
4580      oss.str("");
4581      oss << "SELECT * FROM GL_TLE WHERE FROM_TIME = '"
4582          << getTleDatetime(tle) << "'";
4583    
4584      result = conn->Query(oss.str().c_str());
4585      if (result == NULL) throw -4;
4586    
4587      if (result->GetRowCount())
4588        return true;
4589      else
4590        return false;
4591    }
4592    
4593    
4594    // Return whether the first TLE is dated early than the second
4595    bool compTLE (cTle *tle1, cTle *tle2)
4596    {
4597      return getTleJulian(tle1) < getTleJulian(tle2);
4598    }
4599    
4600    
4601    // Return the date of the tle using the format (year-2000)*1e3 +
4602    // julian day.  e.g. 6365 is the 31th Dec 2006.
4603    // It does *not* return a cJulian date.
4604    float getTleJulian(cTle *tle) {
4605      return tle->getField(cTle::FLD_EPOCHYEAR)*1e3 + tle->getField(cTle::FLD_EPOCHDAY);
4606    }
4607    
4608    
4609    // Return a string like YYYY-MM-DD hh:mm:ss, usable for mysql datetime
4610    // format.
4611    string getTleDatetime(cTle *tle)
4612    {
4613      int year, mon, day, hh, mm, ss;
4614      double dom; // day of month (is double!)
4615      stringstream date; // date in datetime format
4616    
4617      // create a cJulian from the date in tle
4618      cJulian jdate = cJulian( 2000 + (int) tle->getField(cTle::FLD_EPOCHYEAR), tle->getField(cTle::FLD_EPOCHDAY));
4619    
4620      // get year, month, day of month
4621      jdate.getComponent(&year, &mon, &dom);
4622    
4623      // build a datetime YYYY-MM-DD hh:mm:ss
4624      date.str("");
4625      day = (int) floor(dom);
4626      hh = (int) floor( (dom - day) * 24);
4627      mm = (int) floor( ((dom - day) * 24 - hh) * 60);
4628      ss = (int) floor( ((((dom - day) * 24 - hh) * 60 - mm) * 60));
4629      //  ms = (int) floor( (((((dom - day) * 24 - hh) * 60 - mm) * 60) - ss) * 1000);
4630    
4631      date << year << "-" << mon << "-" << day << " " << hh << ":" << mm << ":" << ss;
4632    
4633      return date.str();
4634    }
4635    
4636    /**
4637     * Remove a file from the DB, delete on cascade all entries related to that file
4638     * rearrange GL_RUN and GL_XXX_CALIB tables, turn off validation till the following
4639     * calibration
4640     **/
4641    Int_t PamelaDBOperations::removeFile(TString remfile){
4642      //
4643      // Determine ID_ROOT_L0 and ID_RAW
4644      //
4645      TSQLResult *pResult;
4646      TSQLRow *Row;
4647      stringstream myquery;
4648      //  
4649      myquery.str("");
4650      myquery << " SELECT ID, ID_RAW FROM GL_ROOT where NAME='"<<remfile.Data() <<"';";
4651      //
4652      pResult = conn->Query(myquery.str().c_str());
4653      //
4654      Row = pResult->Next();      
4655      if( !Row ){
4656        if ( strcmp(remfile.Data(),GetRootName().Data()) ){
4657          if ( IsDebug() ) printf(" No file to be removed even if option \"-remove file\" was used!!\n");
4658          return(1);
4659        };
4660        if ( IsDebug() ) printf(" No file to be removed (force mode)! \n");
4661        return(0);
4662      };
4663      //
4664      this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));
4665      this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));
4666      //
4667      this->ValidationOFF();
4668      //
4669      this->RemoveCALIBS();
4670      //
4671      this->RemoveRUNS();
4672      //
4673      this->RemoveFILES();
4674      //
4675      this->SetID_ROOT(0);
4676      this->SetID_RAW(0);
4677      //
4678      return(0);
4679    };
4680    
4681    /**
4682     *
4683     * Set validation bit to zero for runs following the removing file till
4684     * 1) a run with TRK_CALIB_USED=140
4685     * 2) a run with VALIDATION = 0
4686     * 3) the next calibration
4687     *
4688     **/
4689    void PamelaDBOperations::ValidationOFF(){
4690      TSQLResult *pResult;
4691      TSQLRow *Row;
4692      stringstream myquery;
4693      Int_t unv = 0;
4694      //select ID from GL_RUN where RUNHEADER_TIME>=1152671382 AND (VALIDATION=0 OR TRK_CALIB_USED=104) order by RUNHEADER_TIME asc limit 1;
4695      myquery.str("");
4696      myquery << " SELECT MAX(RUNTRAILER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
4697      //
4698      pResult = conn->Query(myquery.str().c_str());
4699      //
4700      Row = pResult->Next();      
4701      if( !Row->GetField(0) ){
4702        //
4703        if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
4704        //
4705      } else {  
4706        //
4707        UInt_t runhtime = (UInt_t)atoll(Row->GetField(0));
4708        UInt_t caltime = 0;
4709        //
4710        myquery.str("");
4711        myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
4712        myquery << " order by FROM_TIME asc limit 1;";
4713        //
4714        if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4715        //
4716        //
4717        delete pResult;
4718        pResult = conn->Query(myquery.str().c_str());
4719        //
4720        Row = pResult->Next();      
4721        if( !Row ){
4722          caltime = runhtime;
4723        } else {
4724          caltime = (UInt_t)atoll(Row->GetField(0));
4725        };
4726        //
4727        myquery.str("");
4728        myquery << " SELECT ID,RUNHEADER_TIME from GL_RUN where RUNHEADER_TIME>="<< runhtime <<" AND (VALIDATION=0 OR TRK_CALIB_USED=104 OR RUNHEADER_TIME>" ;
4729        myquery << caltime << ") order by RUNHEADER_TIME asc LIMIT 1";
4730        //
4731        if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4732        //
4733        pResult = conn->Query(myquery.str().c_str());
4734        //
4735        Row = pResult->Next();      
4736        if( !Row ){
4737          //
4738          if ( IsDebug() ) printf(" NO RUN NEED TO BE UNVALIDATED \n");
4739          //
4740        } else {
4741          myquery.str("");
4742          myquery << " SELECT ID from GL_RUN where RUNHEADER_TIME<"<< Row->GetField(1) <<" AND ";
4743          myquery << " RUNHEADER_TIME>=" <<runhtime;
4744          myquery << " order by RUNHEADER_TIME asc;";
4745          //
4746          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4747          //
4748          pResult = conn->Query(myquery.str().c_str());
4749          //
4750          Row = pResult->Next();  
4751          while ( Row ){
4752            //      
4753            unv++;
4754            this->assignVALIDATION((UInt_t)atoll(Row->GetField(0)), false);
4755            Row = pResult->Next();  
4756            //
4757          };
4758        };
4759      };
4760      if ( IsDebug() ) printf(" %u runs have been unvalidated \n",unv);
4761    };
4762    
4763    /**
4764     *
4765     * Rearrange GL_RUN table and remove runs
4766     *
4767     **/
4768    void PamelaDBOperations::RemoveRUNS(){
4769      TSQLResult *pResult;
4770      TSQLRow *Row;
4771      stringstream myquery;
4772      UInt_t drun = 0;
4773      GL_RUN *delrun = new GL_RUN();
4774      //
4775      myquery.str("");
4776      myquery << " SELECT ID FROM GL_RUN where ID_RUN_FRAG=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4777      //
4778      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4779      //
4780      pResult = conn->Query(myquery.str().c_str());
4781      //
4782      Row = pResult->Next();    
4783      //
4784      //
4785      if ( !Row ){
4786        if ( IsDebug() ) printf(" No run with ID_RUN_FRAG=0 belonged to this file \n");
4787      } else {
4788        if ( IsDebug() ) printf(" Deleting run from GL_RUN table \n");    
4789        while ( Row ){
4790          delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
4791          if ( IsDebug() ) printf(" del run %u \n",(UInt_t)atoll(Row->GetField(0)));
4792          drun++;
4793          Row = pResult->Next();    
4794        };
4795      };
4796      //
4797      //
4798      myquery.str("");
4799      myquery << " SELECT ID,ID_RUN_FRAG FROM GL_RUN where ID_RUN_FRAG!=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4800      //
4801      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4802      //
4803      pResult = conn->Query(myquery.str().c_str());
4804      //
4805      Row = pResult->Next();    
4806      //
4807      if ( !Row ){
4808        if ( IsDebug() ) printf(" No run with ID_RUN_FRAG!=0 belonged to this file \n");
4809      } else {
4810        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN table \n");    
4811        while ( Row ){
4812          if ( IsDebug() ) printf(" restore run %u \n",(UInt_t)atoll(Row->GetField(1)));
4813          delrun->RestoreRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN_FRAGMENTS");
4814          if ( IsDebug() ) printf(" del run %u \n",(UInt_t)atoll(Row->GetField(1)));
4815          delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN");
4816          if ( (UInt_t)atoll(Row->GetField(1)) != (UInt_t)atoll(Row->GetField(0)) ){
4817            if ( IsDebug() ) printf(" del run %u \n",(UInt_t)atoll(Row->GetField(0)));
4818            delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
4819          };
4820          drun++;
4821          Row = pResult->Next();    
4822        };
4823      };
4824      //
4825      if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN table \n",drun);    
4826      //
4827      //
4828      //
4829      drun = 0;
4830      //
4831      myquery.str("");
4832      myquery << " SELECT ID_TRASH FROM GL_RUN_TRASH where BELONGED_TO='GL_RUN_FRAGMENTS' AND ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4833      //
4834      pResult = conn->Query(myquery.str().c_str());
4835      //
4836      Row = pResult->Next();    
4837      //
4838      if ( !Row ){
4839        if ( IsDebug() ) printf(" No run from GL_RUN_FRAGMENTS table in the trash table for this file \n");
4840      } else {
4841        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_TRASH table \n");    
4842        while ( Row ){
4843          if ( IsDebug() ) printf(" del run idtrash %u \n",(UInt_t)atoll(Row->GetField(0)));
4844          myquery.str("");
4845          myquery << " DELETE FROM GL_RUN_TRASH where ID_TRASH=" << Row->GetField(0) <<";";      
4846          conn->Query(myquery.str().c_str());
4847          drun++;
4848          Row = pResult->Next();    
4849        };
4850      };
4851      //  
4852      if ( IsDebug() ) printf(" Deleted %u run(s) from GL_RUN_TRASH table \n",drun);    
4853      //
4854      //
4855      //
4856      drun = 0;
4857      //
4858      myquery.str("");
4859      myquery << " SELECT ID FROM GL_RUN_FRAGMENTS where ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4860      //
4861      pResult = conn->Query(myquery.str().c_str());
4862      //
4863      Row = pResult->Next();    
4864      //
4865      if ( !Row ){
4866        if ( IsDebug() ) printf(" No run in the GL_RUN_FRAGMENTS table for this file \n");
4867      } else {
4868        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_FRAGMENTS table \n");    
4869        while ( Row ){
4870          if ( IsDebug() ) printf(" del run %u \n",(UInt_t)atoll(Row->GetField(0)));
4871          myquery.str("");
4872          myquery << " DELETE FROM GL_RUN_FRAGMENTS where ID=" << Row->GetField(0) <<";";
4873          conn->Query(myquery.str().c_str());
4874          drun++;
4875          Row = pResult->Next();    
4876        };
4877      };
4878      //  
4879      if ( IsDebug() ) printf(" Deleted %u run(s) from GL_RUN_FRAGMENTS table \n",drun);    
4880      //
4881      //
4882      //
4883      delete delrun;
4884      //
4885    };
4886    
4887    
4888    /**
4889     *
4890     * Rearrange calibration tables
4891     *
4892     **/
4893    void PamelaDBOperations::RemoveFILES(){
4894      stringstream myquery;
4895      //
4896      myquery.str("");
4897      myquery << " DELETE FROM GL_RAW WHERE ID=" <<this->GetID_RAW() <<";";
4898      //
4899      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4900      //
4901      conn->Query(myquery.str().c_str());
4902      //
4903    };
4904    
4905    /**
4906     *
4907     * Rearrange calibration tables
4908     *
4909     **/
4910    void PamelaDBOperations::RemoveCALIBS(){
4911      TSQLResult *pResult;
4912      TSQLRow *Row;
4913      stringstream myquery;
4914      //  
4915      //
4916      // Calorimeter
4917      //
4918      for (Int_t section = 0; section < 4; section++){
4919        myquery.str("");
4920        myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_CALO_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<" AND ";
4921        myquery << " SECTION=" << section << ";";
4922        //
4923        pResult = conn->Query(myquery.str().c_str());
4924        //
4925        Row = pResult->Next();      
4926        if( !Row->GetField(0) || !Row->GetField(1) ){
4927          //
4928          if ( IsDebug() ) printf(" NO CALO CALIBRATION SECTION %i ASSOCIATED TO THIS FILE! \n",section);
4929          //
4930        } else {
4931          //
4932          myquery.str("");
4933          myquery << " UPDATE GL_CALO_CALIB SET TO_TIME=" << Row->GetField(1);
4934          myquery << " WHERE TO_TIME="<< Row->GetField(0) << " AND ";
4935          myquery << " SECTION=" << section << ";";
4936          //
4937          pResult = conn->Query(myquery.str().c_str());
4938          //
4939          if( !pResult ){
4940            //
4941            if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
4942            //
4943            throw -4;
4944            //
4945          };
4946          //
4947        };
4948      };
4949      Bool_t OLDDB = false;
4950      for (Int_t section = 0; section < 4; section++){
4951        myquery.str("");
4952        myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_CALOPULSE_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<" AND ";
4953        myquery << " SECTION=" << section << ";";
4954        //
4955        pResult = conn->Query(myquery.str().c_str());
4956        //
4957        if ( conn->GetErrorCode() ){
4958          printf(" Section %i : warning, old databse structure no GL_CALOPULSE_CALIB table!\n",section);
4959          OLDDB=true;
4960        } else {
4961          Row = pResult->Next();      
4962          if( !Row->GetField(0) || !Row->GetField(1) ){
4963            //
4964            if ( IsDebug() ) printf(" NO PULSE CALO CALIBRATION SECTION %i ASSOCIATED TO THIS FILE! \n",section);
4965            //
4966          } else {
4967            //
4968            myquery.str("");
4969            myquery << " UPDATE GL_CALOPULSE_CALIB SET TO_TIME=" << Row->GetField(1);
4970            myquery << " WHERE TO_TIME="<< Row->GetField(0) << " AND ";
4971            myquery << " SECTION=" << section << ";";
4972            //
4973            pResult = conn->Query(myquery.str().c_str());
4974            //
4975            if( !pResult ){
4976              //
4977              if ( IsDebug() ) printf(" ERROR DELETING CALO PULSE CALIBRATIONS \n");
4978              //
4979              throw -4;
4980              //
4981            };
4982            //
4983          };
4984        };
4985      };
4986      myquery.str("");
4987      myquery << " DELETE FROM GL_CALO_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT() << ";";
4988      //
4989      pResult = conn->Query(myquery.str().c_str());
4990      //
4991      if( !pResult ){
4992        //
4993        if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
4994        //
4995        throw -4;
4996        //
4997      };
4998      //
4999      myquery.str("");
5000      myquery << " DELETE FROM GL_CALOPULSE_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT() << ";";
5001      //
5002      pResult = conn->Query(myquery.str().c_str());
5003      if ( IsDebug() ) printf(" Delete from GL_CALOPULSE_CALIB query is %s \n",myquery.str().c_str());
5004      if ( !OLDDB ){
5005        //
5006        if( !pResult ){
5007          //
5008          if ( IsDebug() ) printf(" ERROR DELETING PULSE CALO CALIBRATIONS \n");
5009          //
5010          throw -4;
5011          //
5012        };
5013      };
5014      //
5015      // Tracker
5016      //
5017      myquery.str("");
5018      myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_TRK_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
5019      //
5020      pResult = conn->Query(myquery.str().c_str());
5021      //
5022      Row = pResult->Next();      
5023      if( !Row->GetField(0) || !Row->GetField(1) ){
5024        //
5025        if ( IsDebug() ) printf(" NO TRK CALIBRATION ASSOCIATED TO THIS FILE! \n");
5026        //
5027      } else {
5028        //
5029        myquery.str("");
5030        myquery << " UPDATE GL_TRK_CALIB SET TO_TIME=" << Row->GetField(1);
5031        myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
5032        //
5033        pResult = conn->Query(myquery.str().c_str());
5034        //
5035        if( !pResult ){
5036          //
5037          if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
5038          //
5039          throw -4;
5040          //
5041        };
5042        //
5043        myquery.str("");
5044        myquery << " DELETE FROM GL_TRK_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT() << ";";
5045        //
5046        pResult = conn->Query(myquery.str().c_str());
5047        //
5048        if( !pResult ){
5049          //
5050          if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
5051          //
5052          throw -4;
5053          //
5054        };
5055      };
5056      //
5057      //
5058      // S4
5059      //
5060      myquery.str("");
5061      myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_S4_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
5062      //
5063      pResult = conn->Query(myquery.str().c_str());
5064      //
5065      Row = pResult->Next();      
5066      if( !Row->GetField(0) || !Row->GetField(1) ){
5067        //
5068        if ( IsDebug() ) printf(" NO S4 CALIBRATION ASSOCIATED TO THIS FILE! \n");
5069        //
5070      } else {
5071        //
5072        myquery.str("");
5073        myquery << " UPDATE GL_S4_CALIB SET TO_TIME=" << Row->GetField(1);
5074        myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
5075        //
5076        pResult = conn->Query(myquery.str().c_str());
5077        //
5078        if( !pResult ){
5079          //
5080          if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
5081          //
5082          throw -4;
5083          //
5084        };
5085        //
5086        myquery.str("");
5087        myquery << " DELETE FROM GL_S4_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT() << ";";
5088        //
5089        pResult = conn->Query(myquery.str().c_str());
5090        //
5091        if( !pResult ){
5092          //
5093          if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
5094          //
5095          throw -4;
5096          //
5097        };
5098        //
5099      };
5100    };
5101    
5102    /**
5103     *
5104     * Rearrange calibration tables
5105     *
5106     **/
5107    UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh ){
5108    
5109        Int_t vorder[]={5,5,3,3,4,4,2,2,1,1,0,0};
5110        UInt_t timeaftercalib=120000; //2000;
5111    //  ----------
5112    //  Check CRCs
5113    //  ----------
5114        for(Int_t ipkt=0; ipkt<6; ipkt++){
5115            if( caltrk->crc_hcal[ipkt] )return 0; // :-(
5116            for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] )return 0; // :-(
5117        }
5118    //  -----------------------
5119    //  Check missing packets:
5120    //  -----------------------
5121    //    Readout order:
5122    //    ------------------
5123    //    DSP   packet board
5124    //    ------------------
5125    //    12    0      1
5126    //    10    1      1
5127    //     8    2      1
5128    //     4    3      1
5129    //     6    4      1
5130    //     2    5      1
5131    //    ------------------
5132    //    11    0      2
5133    //     9    1      2
5134    //     7    2      2
5135    //     3    3      2
5136    //     5    4      2
5137    //     1    5      2
5138    //    ------------------
5139    //  -------------------------------------------------
5140    //  Check if it is first or second calibration packet
5141    //  -------------------------------------------------
5142        UInt_t build=0;
5143        TString classname = caltrk->GetName();
5144        UInt_t base=0;
5145        UInt_t mask=0;
5146        if(classname.Contains("CalibTrk1Event")){
5147            base=12;
5148            mask=0x03F000;
5149        }
5150        if(classname.Contains("CalibTrk2Event")){
5151            base=18;
5152            mask=0xFC0000;
5153        }
5154    //  -------------------------------------------------
5155    //  Count number of packets and set build variable
5156    //  -------------------------------------------------
5157        Int_t  npkts=0;
5158        for(Int_t ipkt=0; ipkt<6; ipkt++){
5159            if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
5160                npkts++;
5161                build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );
5162            }
5163        }
5164    //    if( npkts==6 )return 1; // :-)
5165    
5166    //    cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime()<<endl;
5167    
5168    //  -----------------------------------------------
5169    //  If missing packets: check the acq configuration
5170    //  (some DSPs might be excluded from acquisition)
5171    //  -----------------------------------------------
5172    
5173    //  -----------------------------------------------
5174    //  retrieve the first run header after calib
5175    //  -----------------------------------------------
5176         PacketType *pctp;
5177         EventCounter *cod;
5178         cod = eh->GetCounter();
5179         Int_t irun = cod->Get(pctp->RunHeader);
5180         TTree *rh=(TTree*)file->Get("RunHeader");
5181         if ( !rh || rh->IsZombie() ) throw -17;
5182         if( rh->GetEntries() == irun ){
5183              if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (1)  -- cannot validate :-( "<<endl;
5184             return 0; // :-(
5185         }
5186    
5187         RunHeaderEvent *run  = 0;
5188         EventHeader    *hrun = 0;
5189         rh->SetBranchAddress("RunHeader", &run);
5190         rh->SetBranchAddress("Header", &hrun);
5191         rh->GetEntry(irun);
5192    //     cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime() << " Run " << hrun->GetPscuHeader()->GetOrbitalTime() <<endl;
5193    
5194         if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){
5195              if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (2) -- cannot validate :-( "<<endl;
5196             return 0; // :-(
5197         }
5198        
5199         if( !run->RM_ACQ_AFTER_CALIB ){
5200              if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) RM_ACQ_AFTER_CALIB=0    -- cannot validate :-( "<<endl;
5201             return 0; // :-(
5202         }
5203    
5204         UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());
5205         if( dtime > timeaftercalib ){
5206             if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;
5207             return 0; // :-(
5208         }
5209        
5210    
5211    
5212         if( (run->ACQ_BUILD_INFO & mask) != build ){
5213             if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) ACQ_BUILD_INFO= >>> "<<hex << (run->ACQ_BUILD_INFO&mask) << " != "<< build << dec<<endl;
5214             return 0; // :-(
5215         }
5216         return 1; // :-)
5217    
5218    }
5219    
5220    /**
5221     *
5222     * Check the DB (only for overlapping runs at the moment)
5223     *
5224     **/
5225    UInt_t PamelaDBOperations::Check(){
5226      //
5227      UInt_t test = 0;
5228      //
5229      UInt_t thisrht = 0;
5230      UInt_t thisrtt = 0;
5231      UInt_t thisid = 0;
5232      UInt_t prevrht = 0;
5233      UInt_t prevrtt = 0;
5234      UInt_t previd = 0;
5235      //
5236      UInt_t prevl0id = 0;
5237      UInt_t thisl0id = 0;
5238      //
5239      stringstream oss;
5240      TSQLResult *result = 0;
5241      TSQLRow    *row    = 0;
5242      TSQLResult *result2 = 0;
5243      TSQLRow    *row2    = 0;
5244      TSQLResult *result3 = 0;
5245      TSQLRow    *row3    = 0;
5246      oss.str("");
5247      oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME,NEVENTS FROM GL_RUN order by RUNHEADER_TIME asc;";
5248      //  oss << "SELECT ID,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN where ID>10170 and ID<10190 order by RUNHEADER_TIME asc;";
5249      result = conn->Query(oss.str().c_str());
5250      //
5251      if ( !result ) throw -4;;
5252      //
5253      row = result->Next();
5254      UInt_t nid = 0;
5255      //
5256      while ( row ){
5257        nid++;
5258        if ( !(nid%1000) && nid ) printf(" %iK run scanned \n",nid/1000);
5259        thisid = (UInt_t)atoll(row->GetField(0));
5260        thisl0id = (UInt_t)atoll(row->GetField(1));
5261        thisrht = (UInt_t)atoll(row->GetField(2));
5262        thisrtt = (UInt_t)atoll(row->GetField(3));
5263        //
5264        if ( (UInt_t)atoll(row->GetField(4)) > 1 ){
5265          //
5266          //
5267          //
5268          oss.str("");
5269          oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN WHERE ID!="
5270              << thisid << " AND ( RUNHEADER_TIME="
5271              << thisrht << " OR RUNTRAILER_TIME="
5272              << thisrtt << " ) AND NEVENTS!=0 AND NEVENTS!=1 order by RUNHEADER_TIME asc;";
5273          result3 = conn->Query(oss.str().c_str());
5274          if ( IsDebug() ) printf(" query is %s \n",oss.str().c_str());
5275          if ( result3 ){
5276            //
5277            oss.str("");
5278            oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN WHERE ID!="
5279                << thisid << " AND RUNHEADER_TIME="
5280                << thisrht << " AND RUNTRAILER_TIME!="
5281                << thisrtt << " AND NEVENTS!=0 AND NEVENTS!=1 order by RUNHEADER_TIME asc;";
5282            result3 = conn->Query(oss.str().c_str());
5283            if ( IsDebug() ) printf(" query is %s \n",oss.str().c_str());
5284            if ( result3 ){
5285              row3 = result3->Next();
5286              //
5287              while ( row3 ){
5288                //
5289                // 2 runs with same runheader
5290                //
5291                printf(" CHECK n.4 RUNs %u and %u HAVE SAME RUNHEADER \n",thisid,(UInt_t)atoll(row3->GetField(0)));  
5292                row3 = result3->Next();
5293              };
5294            };
5295            //
5296            oss.str("");
5297            oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN WHERE ID!="
5298                << thisid << " AND RUNHEADER_TIME!="
5299                << thisrht << " AND RUNTRAILER_TIME="
5300                << thisrtt << " AND NEVENTS!=0 AND NEVENTS!=1 order by RUNHEADER_TIME asc;";
5301            result3 = conn->Query(oss.str().c_str());
5302            if ( IsDebug() ) printf(" query is %s \n",oss.str().c_str());
5303            if ( result3 ){
5304              row3 = result3->Next();
5305              //
5306              while ( row3 ){
5307                //
5308                // 2 runs with same runtrailer
5309                //
5310                printf(" CHECK n.5 RUNs %u and %u HAVE SAME RUNTRAILER \n",thisid,(UInt_t)atoll(row3->GetField(0)));
5311                row3 = result3->Next();
5312              };
5313            };
5314            //
5315            oss.str("");
5316            oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN WHERE ID!="
5317                << thisid << " AND RUNHEADER_TIME="
5318                << thisrht << " AND RUNTRAILER_TIME="
5319                << thisrtt << " AND ID_RUN_FRAG!="
5320                << thisid << " order by RUNHEADER_TIME asc;";
5321            result3 = conn->Query(oss.str().c_str());
5322            if ( result3 ){
5323              row3 = result3->Next();
5324              //
5325              while ( row3 ){
5326                //
5327                // duplicated run
5328                //
5329                printf(" CHECK n.7 RUNs %u and %u HAVE SAME RUNTRAILER AND RUNHEADER (ARE THE SAME?) \n",thisid,(UInt_t)atoll(row3->GetField(0)));
5330                row3 = result3->Next();
5331              };
5332            };
5333          };
5334          //
5335          oss.str("");
5336          oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN WHERE ID!="
5337              << thisid << " AND RUNHEADER_TIME>"
5338              << thisrht << " AND RUNTRAILER_TIME<"
5339              << thisrtt << " order by RUNHEADER_TIME asc;";
5340          result3 = conn->Query(oss.str().c_str());
5341          if ( result3 ){
5342            row3 = result3->Next();
5343            //
5344            while ( row3 ){
5345              //
5346              // run contained in the checked one
5347              //
5348              printf(" CHECK n.6 RUN %u CONTAINS RUN %u  \n",thisid,(UInt_t)atoll(row3->GetField(0)));
5349              row3 = result3->Next();
5350            };
5351          };
5352          //
5353        };
5354        //
5355        //    if ( thisrht < prevrtt || thisrtt < prevrht || thisrht > thisrtt && !(!prevrht && !prevrtt &&!previd) ){
5356        //    if ( (thisrht < prevrtt || thisrtt < prevrht || thisrht > thisrtt) && (thisrht != prevrht) ){
5357        if ( (thisrht < prevrtt) && (thisrht != prevrht) ){
5358          if ( IsDebug() ) printf(" IDprev %u ID %u    prevrht %u prevrtt %u  thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
5359          printf(" CHECK n.1 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrht-prevrtt),previd,thisid);
5360          TString prevf = "";
5361          TString thisf = "";
5362          oss.str("");
5363          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
5364          result2 = conn->Query(oss.str().c_str());
5365          if ( !result2 ) throw -4;;
5366          row2 = result2->Next();
5367          prevf = (TString)row2->GetField(0);
5368          oss.str("");
5369          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
5370          result2 = conn->Query(oss.str().c_str());
5371          if ( !result2 ) throw -4;;
5372          row2 = result2->Next();
5373          thisf = (TString)row2->GetField(0);
5374          if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
5375          test = 1;
5376        };
5377        //
5378        if ( (thisrtt < prevrht) && (thisrht != prevrht) ){
5379          if ( IsDebug() ) printf(" IDprev %u ID %u    prevrht %u prevrtt %u  thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
5380          printf(" CHECK n.2 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrtt-prevrht),previd,thisid);
5381          TString prevf = "";
5382          TString thisf = "";
5383          oss.str("");
5384          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
5385          result2 = conn->Query(oss.str().c_str());
5386          if ( !result2 ) throw -4;
5387          row2 = result2->Next();
5388          prevf = (TString)row2->GetField(0);
5389          oss.str("");
5390          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
5391          result2 = conn->Query(oss.str().c_str());
5392          if ( !result2 ) throw -4;;
5393          row2 = result2->Next();
5394          thisf = (TString)row2->GetField(0);
5395          if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
5396          test = 1;
5397        };
5398        //
5399        if ( (thisrht > thisrtt) && (thisrht != prevrht) ){
5400          if ( IsDebug() ) printf(" IDprev %u ID %u    prevrht %u prevrtt %u  thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
5401          printf(" CHECK n.3 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrht-thisrtt),previd,thisid);
5402          TString prevf = "";
5403          TString thisf = "";
5404          oss.str("");
5405          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
5406          result2 = conn->Query(oss.str().c_str());
5407          if ( !result2 ) throw -4;;
5408          row2 = result2->Next();
5409          prevf = (TString)row2->GetField(0);
5410          oss.str("");
5411          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
5412          result2 = conn->Query(oss.str().c_str());
5413          if ( !result2 ) throw -4;;
5414          row2 = result2->Next();
5415          thisf = (TString)row2->GetField(0);
5416          if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
5417          test = 1;
5418        };
5419    
5420        //
5421        prevrht = thisrht;
5422        prevrtt = thisrtt;
5423        previd = thisid;
5424        prevl0id = thisl0id;
5425        row = result->Next();
5426      };
5427      //
5428      return(test);
5429      //
5430    };

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

  ViewVC Help
Powered by ViewVC 1.1.23