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

Diff of /YodaProfiler/src/PamelaDBOperations.cpp

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

revision 1.1 by mocchiut, Wed Aug 30 11:18:13 2006 UTC revision 1.33 by mocchiut, Mon Apr 30 08:31:28 2007 UTC
# Line 8  Line 8 
8  #include <list>  #include <list>
9  #include <errno.h>  #include <errno.h>
10  //  //
11    #include <TFile.h>
12    #include <TSystem.h>
13  #include <TSQLResult.h>  #include <TSQLResult.h>
 #include <TRFIOFile.h>  
14  #include <TSQLRow.h>  #include <TSQLRow.h>
15  #include <TTree.h>  #include <TTree.h>
16  #include <TGraph.h>  #include <TGraph.h>
17  #include <TDatime.h>  #include <TTimeStamp.h>
18  #include <TF1.h>  #include <TF1.h>
19  //  //
20  #include <EventHeader.h>  #include <EventHeader.h>
# Line 29  Line 30 
30  #include <varDump/VarDumpEvent.h>  #include <varDump/VarDumpEvent.h>
31  #include <varDump/VarDumpRecord.h>  #include <varDump/VarDumpRecord.h>
32  #include <physics/S4/S4Event.h>  #include <physics/S4/S4Event.h>
   
33  //  //
34    #include <sgp4.h>
35    
36  #include <PamelaDBOperations.h>  #include <PamelaDBOperations.h>
37  //  //
38  using namespace std;  using namespace std;
39  using namespace pamela;  using namespace pamela;
40  //using namespace yngn::util;  
41    // Some function to work with cTle stuff.
42    bool compTLE(cTle* tle1, cTle *tle2);
43    float getTleJulian(cTle *);
44    string getTleDatetime(cTle*);
45    
46  /**  /**
47   * Constructor.   * Constructor.
# Line 48  using namespace pamela; Line 54  using namespace pamela;
54   * @param obt0         file obt0.   * @param obt0         file obt0.
55   * @param tsync        file timesync.   * @param tsync        file timesync.
56   * @param debug        debug flag.   * @param debug        debug flag.
57     * @param tlefilename  ascii file with TLE 3 line elements.
58   */   */
59  PamelaDBOperations::PamelaDBOperations(TString host, TString user, TString password, TString filerawname, TString filerootname, UInt_t boot, UInt_t tsync, UInt_t obt0, Bool_t debug){  PamelaDBOperations::PamelaDBOperations(TString host, TString user, TString password, TString filerawname, TString filerootname, UInt_t boot, UInt_t tsync, UInt_t obt0, Bool_t debug, TString tlefilename, UInt_t dwinput, Bool_t staticp){
60    //    //
61      STATIC=false;
62      if ( staticp ) STATIC=true;
63    //    //
64    SetConnection(host,user,password);    SetConnection(host,user,password);
65    //    //
# Line 63  PamelaDBOperations::PamelaDBOperations(T Line 72  PamelaDBOperations::PamelaDBOperations(T
72    SetTsync(tsync);    SetTsync(tsync);
73    SetObt0(obt0);    SetObt0(obt0);
74    //    //
75      SetTLEPath(tlefilename);
76      //
77    //    //
78    SetRootName(filerootname);    INSERT_RAW =!filerawname.IsNull();
79    SetRawName(filerawname);    if(INSERT_RAW)SetRawName(filerawname);
80    //    //
81    this->OpenFile();    INSERT_ROOT = !filerootname.IsNull();
82      if( INSERT_ROOT ){
83        this->SetRootName(filerootname);
84        this->SetOrbitNo(dwinput);
85        file = TFile::Open(this->GetRootName().Data());
86      } else {
87        this->SetRootName("");
88      };
89    //    //
90    this->SetID_RAW(0);    this->SetID_RAW(0);
91    this->SetID_ROOT(0);    this->SetID_ROOT(0);
92    
93      VALIDATE = false;
94      
95    //    //
96  };  };
97    
# Line 79  PamelaDBOperations::PamelaDBOperations(T Line 100  PamelaDBOperations::PamelaDBOperations(T
100   */   */
101  void PamelaDBOperations::Close(){  void PamelaDBOperations::Close(){
102    if( conn && conn->IsConnected() ) conn->Close();    if( conn && conn->IsConnected() ) conn->Close();
103      delete clean_time;
104    delete glrun;    delete glrun;
105    delete this;    delete this;
106  };  };
# Line 87  void PamelaDBOperations::Close(){ Line 109  void PamelaDBOperations::Close(){
109  // SETTERS  // SETTERS
110  //  //
111    
112    //
113    // must be out of the constructor in order to FORCE the validation of the latest runs in case you run the validation together with the latest file
114    //
115    void PamelaDBOperations::CheckValidate(Long64_t olderthan){
116      clean_time = new TDatime();
117      //
118      if(olderthan >= 0){
119        VALIDATE = true;
120        UInt_t timelim = 0;
121        timelim =  (UInt_t)clean_time->Convert(true) - olderthan;
122        clean_time->Set(timelim,false);
123      };
124    };
125    
126  /**  /**
127   * Open the DB connection   * Open the DB connection
128   * @param host         hostname for the SQL connection.   * @param host         hostname for the SQL connection.
# Line 94  void PamelaDBOperations::Close(){ Line 130  void PamelaDBOperations::Close(){
130   * @param password     password for the SQL connection.   * @param password     password for the SQL connection.
131   */   */
132  void PamelaDBOperations::SetConnection(TString host, TString user, TString password){  void PamelaDBOperations::SetConnection(TString host, TString user, TString password){
133      if ( IsDebug() ) printf(" Connecting using host = %s user = %s password = %s \n",host.Data(),user.Data(),password.Data());
134    conn = TSQLServer::Connect(host.Data(),user.Data(),password.Data());    conn = TSQLServer::Connect(host.Data(),user.Data(),password.Data());
135  };  };
136    
# Line 122  void PamelaDBOperations::SetDebugFlag(Bo Line 159  void PamelaDBOperations::SetDebugFlag(Bo
159  };  };
160    
161  /**  /**
162     * Set the autoboot flag
163     *
164     */
165    void PamelaDBOperations::SetAutoBoot(Bool_t dbg){
166      AUTOBOOT = dbg;
167    };
168    
169    /**
170     * Set the nofrag flag
171     *
172     */
173    void PamelaDBOperations::SetNoFrag(Bool_t nf){
174      NOFRAG = nf;
175    };
176    
177    /**
178   * Store the BOOT number of the RAW file.   * Store the BOOT number of the RAW file.
179   * @param boot    BOOT number of the RAW file   * @param boot    BOOT number of the RAW file
180   */   */
# Line 162  void PamelaDBOperations::SetRootName(TSt Line 215  void PamelaDBOperations::SetRootName(TSt
215  };  };
216    
217  /**  /**
218     * Store the downlink orbit number from filename.
219     */
220    void PamelaDBOperations::SetOrbitNo(UInt_t dwinput){
221      dworbit = 0;
222      //
223      if ( dwinput ){
224        dworbit = dwinput;
225        if ( IsDebug() ) printf(" Downlink orbit given by hand: %i  \n",dworbit);
226        return;
227      };
228      //
229      TString name = this->GetRootFile();
230      Int_t nlength = name.Length();
231      if ( nlength < 5 ) return;
232      TString dwo = 0;
233      for (Int_t i = 0; i<5; i++){
234        dwo.Append(name[i],1);
235      };
236      if ( dwo.IsDigit() ){
237        dworbit = (UInt_t)dwo.Atoi();
238      } else {
239        dwo="";
240        for (Int_t i = 8; i<13; i++){
241          dwo.Append(name[i],1);
242        };    
243        if ( dwo.IsDigit() ) dworbit = (UInt_t)dwo.Atoi();
244      };
245      if ( IsDebug() ) printf(" Downlink orbit is %i (dwo = %s) \n",dworbit,dwo.Data());
246      return;
247    };
248    
249    
250    
251    /**
252   * Store the NOBOOT flag.   * Store the NOBOOT flag.
253   * @param noboot    true/false.   * @param noboot    true/false.
254   */   */
# Line 170  void PamelaDBOperations::SetNOBOOT(Bool_ Line 257  void PamelaDBOperations::SetNOBOOT(Bool_
257  };  };
258    
259  /**  /**
260     * Store path to the TLE file.
261     */
262    void PamelaDBOperations::SetTLEPath(TString str){
263      tlefilename = str;
264    };
265    
266    TString PamelaDBOperations::GetRawPath(){
267      if ( STATIC ){
268        return((TString)gSystem->DirName(filerawname.Data())+'/');
269      } else {
270        return((TString)gSystem->ExpandPathName("$PAM_RAW")+'/');
271      };
272    };
273    
274    TString PamelaDBOperations::GetRootPath(){
275      if ( STATIC ){
276        return((TString)gSystem->DirName(filerootname.Data())+'/');
277      } else {
278        return((TString)gSystem->ExpandPathName("$PAM_L0")+'/');
279      };
280    };
281    
282    /**
283     * Store the olderthan variable
284     * @param olderthan
285     */
286    // void PamelaDBOperations::SetOlderThan(Long64_t oldthan){
287    //   olderthan = oldthan;
288    // };
289    
290    /**
291   * Retrieve the ID_RAW, if exists, returns NULL if does not exist.   * Retrieve the ID_RAW, if exists, returns NULL if does not exist.
292   */   */
293  Bool_t PamelaDBOperations::SetID_RAW(){  Bool_t PamelaDBOperations::SetID_RAW(){
# Line 177  Bool_t PamelaDBOperations::SetID_RAW(){ Line 295  Bool_t PamelaDBOperations::SetID_RAW(){
295    TSQLResult *result = 0;    TSQLResult *result = 0;
296    TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
297    oss.str("");    oss.str("");
298    oss << "SELECT ID FROM GL_RAW WHERE "    if ( STATIC ){
299        << " PATH = '" << this->GetRawPath().Data() << "' AND "      oss << "SELECT ID FROM GL_RAW WHERE "
300        << " NAME = '" << this->GetRawFile().Data() << "' ";          << " PATH = '" << this->GetRawPath().Data() << "' AND "
301            << " NAME = '" << this->GetRawFile().Data() << "' ";  
302      } else {
303        oss << "SELECT ID FROM GL_RAW WHERE "
304            << " PATH = '$PAM_RAW' AND "
305            << " NAME = '" << this->GetRawFile().Data() << "' ";  
306      }
307    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
308    if (result == NULL) throw -4;    if ( result == NULL ) throw -4;
309    row = result->Next();    row = result->Next();
310    if (row == NULL) return false;    if ( !row ) return(false);
311    delete result;    delete result;
312    id = (UInt_t)atoll(row->GetField(0));    id = (UInt_t)atoll(row->GetField(0));
313    return(true);    return(true);
# Line 210  Int_t PamelaDBOperations::SetUpperLimits Line 334  Int_t PamelaDBOperations::SetUpperLimits
334    UInt_t nevent = 0;    UInt_t nevent = 0;
335    UInt_t pktlast = 0;    UInt_t pktlast = 0;
336    UInt_t obtlast = 0;    UInt_t obtlast = 0;
337    UInt_t t_pktlast = 0;    Long64_t t_pktlast = 0LL;
338    UInt_t t_obtlast = 0;    //  UInt_t t_obtlast = 0;
339    UInt_t upperpkt2 = 0;    Long64_t t_obtlast = 0LL;
340    ULong64_t upperobt2 = 0;    Long64_t upperpkt2 = 0LL;
341      Long64_t upperobt2 = 0LL;
342    UInt_t zomp = 0;    UInt_t zomp = 0;
343    UInt_t jump = 50000; // was 5000    UInt_t jump = 50000; // was 5000
344      EventCounter *code=0;
345      //
346      Long64_t deltapkt = 5000LL;
347      Long64_t deltaobt = 50000LL;
348      //
349      pcksList packetsNames;
350      pcksList::iterator Iter;
351      getPacketsNames(packetsNames);
352    //    //
353    pktfirst = 0;    pktfirst = 0;
354    obtfirst = 0;    obtfirst = 0;
355      ppktfirst = 0;
356      pobtfirst = 0;
357    //    //
358    TTree *T = 0;    TTree *T = 0;
359    T = (TTree*)file->Get("Physics");    T = (TTree*)file->Get("Physics");
# Line 232  Int_t PamelaDBOperations::SetUpperLimits Line 367  Int_t PamelaDBOperations::SetUpperLimits
367    ph = eh->GetPscuHeader();    ph = eh->GetPscuHeader();
368    pktfirst = ph->GetCounter();    pktfirst = ph->GetCounter();
369    obtfirst = ph->GetOrbitalTime();      obtfirst = ph->GetOrbitalTime();  
370      ppktfirst = pktfirst;
371      pobtfirst = obtfirst;
372      //
373      code = eh->GetCounter();
374      UInt_t en = 0;
375      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
376        en = code->Get(GetPacketType(*Iter));
377        if ( !strcmp("CalibCalPed",*Iter) || !strcmp("CalibTrk1",*Iter) || !strcmp("CalibTrk2",*Iter) || !strcmp("CalibS4",*Iter) ){
378          if ( IsDebug() ) printf(" We have a calibration before the first physic packet: packet type is %s, entries: %i \n",*Iter,en);
379          //
380          TTree *TC = 0;
381          TC = (TTree*)file->Get("CalibCalPed");
382          if ( !TC || TC->IsZombie() ) throw -16;
383          EventHeader *ehc = 0;
384          PscuHeader *phc = 0;
385          TC->SetBranchAddress("Header", &ehc);
386          TC->GetEntry(0);
387          phc = ehc->GetPscuHeader();
388          pktfirst = phc->GetCounter();
389          obtfirst = phc->GetOrbitalTime();  
390          //
391        };
392      };  
393    //    //
394    T->GetEntry(nevent-1);    T->GetEntry(nevent-1);
395    ph = eh->GetPscuHeader();    ph = eh->GetPscuHeader();
# Line 242  Int_t PamelaDBOperations::SetUpperLimits Line 400  Int_t PamelaDBOperations::SetUpperLimits
400    upperobt = OBT(obtlast);    upperobt = OBT(obtlast);
401    upperentry = nevent-1;    upperentry = nevent-1;
402    //    //
403    if ( IsDebug() ) printf(" First entries are: OBT %llu pkt_num %i \n",obtfirst,pktfirst);    if ( IsDebug() ) printf(" First entries are: OBT %i pkt_num %i \n",obtfirst,pktfirst);
404    //    //
405    if ( IsDebug() ) printf(" Last entries are: OBT %llu pkt_num %i entry %i\n",upperobt,upperpkt,upperentry);    if ( IsDebug() ) printf(" Last entries are: OBT %lld pkt_num %lld entry %i\n",upperobt,upperpkt,upperentry);
406    //    //
407    if ( (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) > OBT(obtfirst)) || (PKT(pktlast) > PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) ) return(1);    if ( (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) > OBT(obtfirst)) || (PKT(pktlast) > PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) ) return(1);
408    //    //
409    if ( !nevent ) return(2);    if ( !nevent ) return(2);
410    //    //
411    if ( nevent < 2 ) return(4);    if ( nevent < 2 ) return(4);
412      if ( nevent < jump ) jump = 1;
413      //  if ( nevent < jump ) jump = int(nevent/10);
414      //  if ( !jump ) jump = 1;
415    //    //
416    if ( PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst) ){    if ( (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) || (labs(PKT(pktlast)-PKT(pktfirst))<deltapkt && labs(OBT(obtlast)-OBT(obtfirst))<deltaobt) && nevent > deltapkt ){
417        //
418        if ( IsDebug() ) printf(" starting jump %i \n",jump);
419      // go back      // go back
420      zomp = nevent - 2;      zomp = nevent - 2;
421      //      //
# Line 274  Int_t PamelaDBOperations::SetUpperLimits Line 437  Int_t PamelaDBOperations::SetUpperLimits
437          upperpkt2 = PKT(ph->GetCounter());          upperpkt2 = PKT(ph->GetCounter());
438          upperobt2 = OBT(ph->GetOrbitalTime());          upperobt2 = OBT(ph->GetOrbitalTime());
439          //          //
440          if ( (t_pktlast < upperpkt && t_obtlast > upperobt) || (t_pktlast < upperpkt2 && t_obtlast > upperobt2) ) throw -13;              if ( (t_pktlast < upperpkt && t_obtlast > upperobt) || (t_pktlast < upperpkt2 && t_obtlast > upperobt2) ){
441              if ( IsDebug() ) printf(" .-. upperpkt2 %lld upperobt2 %lld \n",upperpkt2,upperobt2);  
442              if ( IsDebug() ) printf(" .-. upperpkt %lld t_pktlast %lld upperobt %lld t_obtlast %lld \n",upperpkt,t_pktlast,upperobt,t_obtlast);    
443              if ( IsDebug() ) printf(" .-. jump %i zomp %i upperpkt %lld pktlast %u upperobt %lld obtlast %u last entry is %i \n",jump,zomp,upperpkt,pktlast,upperobt,obtlast,i);    
444              throw -13;    
445            };
446          //          //
447          if ( t_pktlast < upperpkt && t_obtlast < upperobt && t_pktlast < upperpkt2 && t_obtlast < upperobt2 ){          if ( t_pktlast < upperpkt && t_obtlast < upperobt && t_pktlast < upperpkt2 && t_obtlast < upperobt2 ){
448            zomp = i + jump + 1;            zomp = i + jump + 1;
449            if ( zomp > nevent-2 ) zomp = nevent - 2;            if ( zomp > nevent-2 ) zomp = nevent - 2;
450            if ( IsDebug() ) printf(" .-. jump %i zomp %i upperpkt %i pktlast %i upperobt %llu obtlast %u last entry is %i \n",jump,zomp,upperpkt,pktlast,upperobt,obtlast,i);            if ( IsDebug() ) printf(" .-. jump %i zomp %i upperpkt %lld pktlast %i upperobt %lld obtlast %u last entry is %i \n",jump,zomp,upperpkt,pktlast,upperobt,obtlast,i);
451            break;            break;
452          };          };
453          //          //
# Line 301  Int_t PamelaDBOperations::SetUpperLimits Line 469  Int_t PamelaDBOperations::SetUpperLimits
469    // check if last runtrailer is within limits, if not extend limits (one should check for all packets but we need only runtrailer)    // check if last runtrailer is within limits, if not extend limits (one should check for all packets but we need only runtrailer)
470    //    //
471    PacketType *pctp=0;    PacketType *pctp=0;
   EventCounter *code=0;  
   T->GetEntry(upperentry);  
   code = eh->GetCounter();  
   Int_t lasttrail = code->Get(pctp->RunTrailer);  
   Int_t lasthead = code->Get(pctp->RunHeader);  
472    TTree *rh=(TTree*)file->Get("RunHeader");    TTree *rh=(TTree*)file->Get("RunHeader");
473    if ( !rh || rh->IsZombie() ) throw -17;    if ( !rh || rh->IsZombie() ) throw -17;
474    TTree *rt=(TTree*)file->Get("RunTrailer");    TTree *rt=(TTree*)file->Get("RunTrailer");
# Line 319  Int_t PamelaDBOperations::SetUpperLimits Line 482  Int_t PamelaDBOperations::SetUpperLimits
482    //    //
483    rhev = rh->GetEntries();    rhev = rh->GetEntries();
484    rtev = rt->GetEntries();    rtev = rt->GetEntries();
485    UInt_t pktt = 0;    Long64_t sobtt = 0LL;
486    ULong64_t obtt = 0;    Long64_t sobth = 0LL;
487    UInt_t pkth = 0;    Long64_t spktt = 0LL;
488    ULong64_t obth = 0;    Long64_t spkth = 0LL;
489      Long64_t pktt = 0LL;
490      Long64_t obtt = 0LL;
491      Long64_t pkth = 0LL;
492      Long64_t obth = 0LL;
493    //    //
494    if ( lasttrail < rtev ){    if ( rhev || rtev ){
495      rt->GetEntry(lasttrail);  
496      pht = eht->GetPscuHeader();      T->GetEntry(upperentry);
497      pktt = PKT(pht->GetCounter());      code = eh->GetCounter();
498      obtt = OBT(pht->GetOrbitalTime());      Int_t lasttrail = code->Get(pctp->RunTrailer);
499        Int_t lasthead = code->Get(pctp->RunHeader);
500        if ( lasttrail < rtev ){
501          rt->GetEntry(lasttrail);
502          pht = eht->GetPscuHeader();
503          pktt = PKT(pht->GetCounter());
504          obtt = OBT(pht->GetOrbitalTime());
505        };
506        //
507        if ( lasthead < rhev ){
508          rh->GetEntry(lasthead);
509          phh = ehh->GetPscuHeader();
510          pkth = PKT(phh->GetCounter());
511          obth = OBT(phh->GetOrbitalTime());
512        };
513        //
514        if ( IsDebug() ) printf(" rhev before %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
515        if ( pkth > upperpkt && obth > upperobt ){
516          if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %lld upperp %lld oh %lld uppero %lld \n",pkth,upperpkt,obth,upperobt);
517          upperpkt = pkth;
518          upperobt = obth;
519          rhev = lasthead+1;
520        } else {
521          rhev = lasthead;
522        };
523        if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
524        //
525        if ( IsDebug() ) printf(" rtev beforev %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
526        if ( pktt > upperpkt && obtt > upperobt ){
527          if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %lld upperp %lld ot %lld uppero %lld \n",pktt,upperpkt,obtt,upperobt);
528          upperpkt = pktt;
529          upperobt = obtt;
530          rtev = lasttrail+1;
531        } else {
532          rtev = lasttrail;
533        };
534        if ( IsDebug() ) printf(" rtev after %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
535        //  goto kikko;
536        //
537        //
538        // Check if runtrailer/runheader are within lower limits
539        //
540        //
541        pkth = 0LL;
542        obth = 0LL;
543        spkth = 0LL;
544        sobth = 0LL;
545        for (Int_t k=0; k<rhev; k++){
546          if ( k > 0 ){
547            spkth = pkth;
548            sobth = obth;
549          };
550          rh->GetEntry(k);
551          phh = ehh->GetPscuHeader();
552          pkth = PKT(phh->GetCounter());
553          obth = OBT(phh->GetOrbitalTime());
554          //
555          //    if ( IsDebug() ) printf(" k %i rhev before %i ph %u upperp %u oh %u uppero %u \n",k,rhev,pkth,spkth,obth,sobth);
556          //
557          if ( pkth < spkth && obth < sobth ){
558            if ( IsDebug() ) printf(" RH PROBLEMS determining the event repetition at the end of the file lasthead %i  \n",rhev);
559            //
560            rhev = k-1;
561            rh->GetEntry(rhev);
562            pkth = spkth;
563            obth = sobth;
564            //
565            UInt_t evbefh = 0;
566            code = ehh->GetCounter();
567            evbefh = code->Get(pctp->Physics);    
568            if ( evbefh >= 0 ){
569              T->GetEntry(evbefh);
570              ph = eh->GetPscuHeader();
571              t_pktlast = PKT(ph->GetCounter());
572              t_obtlast = OBT(ph->GetOrbitalTime());
573              if ( t_pktlast <= spkth && t_obtlast <= sobth ){ // jump
574                upperpkt = pkth;
575                upperobt = obth;
576                upperentry = evbefh-1;
577              } else {
578                while ( t_pktlast > spkth && t_obtlast > sobth && evbefh < nevent ){
579                  evbefh++;
580                  T->GetEntry(evbefh);
581                  ph = eh->GetPscuHeader();
582                  t_pktlast = PKT(ph->GetCounter());
583                  t_obtlast = OBT(ph->GetOrbitalTime());
584                };
585                T->GetEntry(evbefh-1);
586                ph = eh->GetPscuHeader();
587                upperpkt = PKT(ph->GetCounter());
588                upperobt = OBT(ph->GetOrbitalTime());
589                upperentry = evbefh-1;
590              };    
591            };
592            if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
593            goto kikko0;
594          };
595        };
596      kikko0:
597        //
598        //
599        //
600        pktt = 0LL;
601        obtt = 0LL;
602        spktt = 0LL;
603        sobtt = 0LL;
604        for (Int_t k=0; k<rtev; k++){
605          if ( k > 0 ){
606            spktt = pktt;
607            sobtt = obtt;
608          };
609          rt->GetEntry(k);
610          pht = eht->GetPscuHeader();
611          pktt = PKT(pht->GetCounter());
612          obtt = OBT(pht->GetOrbitalTime());
613          //
614          //    if ( IsDebug() ) printf(" k %i rtev beforev %i  pt %i upperp %i ot %llu uppero %llu \n",k,rtev,pktt,spktt,obtt,sobtt);
615          //
616          if ( pktt < spktt && obtt < sobtt ){
617            if ( IsDebug() ) printf(" RT PROBLEMS determining the event repetition at the end of the file lasttrail %i \n",rtev);
618            //
619            rtev = k-1;
620            rt->GetEntry(rtev);
621            pktt = spktt;
622            obtt = sobtt;
623            if ( IsDebug() ) printf(" lasttrail %i pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
624            //
625            UInt_t evbeft = 0;
626            code = eht->GetCounter();
627            evbeft = code->Get(pctp->Physics);    
628            if ( evbeft >= 0 ){
629              T->GetEntry(evbeft);
630              ph = eh->GetPscuHeader();
631              t_pktlast = PKT(ph->GetCounter());
632              t_obtlast = OBT(ph->GetOrbitalTime());
633              if ( t_pktlast <= spktt && t_obtlast <= sobtt ){ // jump
634                upperpkt = pktt;
635                upperobt = obtt;
636                upperentry = evbeft-1;
637              } else {
638                while ( t_pktlast > spktt && t_obtlast > sobtt && evbeft < nevent ){
639                  evbeft++;
640                  T->GetEntry(evbeft);
641                  ph = eh->GetPscuHeader();
642                  t_pktlast = PKT(ph->GetCounter());
643                  t_obtlast = OBT(ph->GetOrbitalTime());
644                };
645                T->GetEntry(evbeft-1);
646                ph = eh->GetPscuHeader();
647                upperpkt = PKT(ph->GetCounter());
648                upperobt = OBT(ph->GetOrbitalTime());
649                upperentry = evbeft-1;
650              };
651            };
652            if ( IsDebug() ) printf(" rtev after %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
653            goto kikko;
654            //      break;
655            //
656          };
657          //  
658        };
659        //
660      kikko:
661        //
662        T->GetEntry(upperentry);
663        code = eh->GetCounter();
664        lasttrail = code->Get(pctp->RunTrailer);
665        lasthead = code->Get(pctp->RunHeader);
666        if ( lasttrail < rtev ){
667          rt->GetEntry(lasttrail);
668          pht = eht->GetPscuHeader();
669          pktt = PKT(pht->GetCounter());
670          obtt = OBT(pht->GetOrbitalTime());
671        };
672        //
673        if ( lasthead < rhev ){
674          rh->GetEntry(lasthead);
675          phh = ehh->GetPscuHeader();
676          pkth = PKT(phh->GetCounter());
677          obth = OBT(phh->GetOrbitalTime());
678        };
679        //
680        if ( IsDebug() ) printf(" rhev before %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
681        if ( pkth > upperpkt && obth > upperobt ){
682          if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %lld upperp %lld oh %lld uppero %lld \n",pkth,upperpkt,obth,upperobt);
683          upperpkt = pkth;
684          upperobt = obth;
685          rhev = lasthead+1;
686        } else {
687          rhev = lasthead;
688        };
689        if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
690        //
691        if ( IsDebug() ) printf(" rtev beforev %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
692        if ( pktt > upperpkt && obtt > upperobt ){
693          if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %lld upperp %lld ot %lld uppero %lld \n",pktt,upperpkt,obtt,upperobt);
694          upperpkt = pktt;
695          upperobt = obtt;
696          rtev = lasttrail+1;
697        } else {
698          rtev = lasttrail;
699        };
700        if ( IsDebug() ) printf(" rtev after %i  pt %lld upperp %lld ot %lld uppero %lld \n",rtev,pktt,upperpkt,obtt,upperobt);
701        //
702    };    };
703    //    //
704    if ( IsDebug() ) printf(" rtev beforev %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);    if ( IsDebug() ) printf(" Upper limits are: OBT %lld pkt_num %lld upper entry %i \n",upperobt,upperpkt,upperentry);
   if ( pktt > upperpkt && obtt > upperobt ){  
     if ( IsDebug() ) printf(" Upper limits extended to include last trailer: pt %i upperp %i ot %llu uppero %llu \n",pktt,upperpkt,obtt,upperobt);  
     upperpkt = pktt;  
     upperobt = obtt;  
     rtev = lasttrail+1;  
   } else {  
     rtev = lasttrail;  
   };  
   if ( IsDebug() ) printf(" rtev after %i  pt %i upperp %i ot %llu uppero %llu \n",rtev,pktt,upperpkt,obtt,upperobt);  
705    //    //
706    if ( lasthead < rhev ){    return(0);
707      rh->GetEntry(lasthead);  }
708      phh = ehh->GetPscuHeader();  
709      pkth = PKT(pht->GetCounter());  /**
710      obth = OBT(pht->GetOrbitalTime());   *
711    };   * Trick to have unique RUN ID numbers even when runs are deleted and mysql deamon restarted.
712     * Entries in the _RUNID_GEN table are never deleted.
713     *
714     **/
715    UInt_t PamelaDBOperations::AssignRunID(){
716    //    //
717    if ( IsDebug() ) printf(" rhev before %i ph %i upperp %i oh %llu uppero %llu \n",rhev,pkth,upperpkt,obth,upperobt);    TSQLResult *result = 0;
718    if ( pkth > upperpkt && obth > upperobt ){    TSQLRow *row = 0;
719      if ( IsDebug() ) printf(" Upper limits extended to include last header: ph %i upperp %i oh %llu uppero %llu \n",pkth,upperpkt,obth,upperobt);    UInt_t runid = 0;
     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);  
720    //    //
721    if ( IsDebug() ) printf(" Upper limits are: OBT %llu pkt_num %i upper entry %i \n",upperobt,upperpkt,upperentry);    stringstream   oss;
722      //  
723      oss.str("");
724      oss << "INSERT INTO _RUNID_GEN VALUES (NULL);";
725      result = conn->Query(oss.str().c_str());
726      if ( !result ) throw -10;
727      oss.str("");
728      oss << "SELECT ID FROM _RUNID_GEN ORDER BY ID DESC LIMIT 1;";
729      result = conn->Query(oss.str().c_str());
730      if ( !result ) throw -10;
731    //    //
732    return(0);    row = result->Next();
733  }    //
734      if ( !row ) throw -28;
735      //
736      runid = (UInt_t)atoll(row->GetField(0));
737      //
738      return(runid);
739    };
740    
741  //  //
742  // GETTERS  // GETTERS
# Line 440  const PacketType* PamelaDBOperations::Ge Line 813  const PacketType* PamelaDBOperations::Ge
813  // PRIVATE FUNCTIONS  // PRIVATE FUNCTIONS
814  //  //
815    
816  /**  // /**
817   * Open the ROOT filename for reading  // * Open the ROOT filename for reading
818   */  // */
819  void PamelaDBOperations::OpenFile(){  // void PamelaDBOperations::OpenFile(){
820    file = TFile::Open(this->GetRootName().Data());  //   file = TFile::Open(this->GetRootName().Data());
821    //   //
822    
823    void PamelaDBOperations::CheckFile(){  
824      if ( !file ) throw -12;
825  };  };
826    
827    
828  /**  /**
829   * Check if LEVEL0 file and DB connection have really be opened   * Check if LEVEL0 file and DB connection have really be opened
830   */   */
831  void PamelaDBOperations::CheckFile(){    void PamelaDBOperations::CheckConnection(){  
   //  
   if ( !file ) throw -12;  
832    //    //
833    // check connection    // check connection
834    //    //
835    if( !conn ) throw -1;        if( !conn ) throw -1;
836    bool connect = conn->IsConnected();    bool connect = conn->IsConnected();
837    if( !connect ) throw -1;        if( !connect ) throw -1;
838      //
839      if ( IsDebug() ) printf("\n DB INFORMATIONS:\n SQL: %s Version: %s Host %s Port %i \n\n",conn->GetDBMS(),conn->ServerInfo(),conn->GetHost(),conn->GetPort());
840      //
841      if ( !dworbit && strcmp(this->GetRootName().Data(),"") ) throw -27;
842      //
843      // set DB timezone to UTC
844      //
845      stringstream oss;
846      //  
847      oss.str("");
848      oss << "SET time_zone='+0:00';";
849      TSQLResult *result = 0;
850      result = conn->Query(oss.str().c_str());
851      if ( !result ) throw -10;
852      oss.str("");
853      oss << "SET wait_timeout=173000;";
854      conn->Query(oss.str().c_str());
855      //
856  };  };
857    
858  /**  /**
859   * Return the correct packet number if we went back to zero   * Return the correct packet number if we went back to zero
860   */   */
861  UInt_t PamelaDBOperations::PKT(UInt_t pkt_num){    Long64_t PamelaDBOperations::PKT(UInt_t pkt_num){  
862    //    //
863    //  if ( IsDebug() ) printf(" pkt conversion: pkt_num is %u pktfirst is %u (pktfirst - (UInt_t)(16777212/2)) is %u  \n",pkt_num,pktfirst,(pktfirst - (UInt_t)(16777212/2)));    if ( IsDebug() ) printf(" pkt conversion: pkt_num is %u pktfirst is %u  (UInt_t)(16777214/2)) is %u  \n",pkt_num,ppktfirst,(UInt_t)(16777214/2));
864    //    //
865    if ( pkt_num < (pktfirst/2) && pktfirst > (16777214/2)  ) return((pkt_num+16777215));    if ( pkt_num < (ppktfirst/2) && ppktfirst > (16777214/2)  ){
866        if ( IsDebug() ) printf(" rise up pktnum %lld \n",(Long64_t)pkt_num+16777215LL);
867        return((Long64_t)pkt_num+16777215LL);
868      };
869    //    //
870    if ( pkt_num > pktfirst*2 && pkt_num > (16777214/2) ){    if ( pkt_num > ((Long64_t)ppktfirst*2) && pkt_num > (16777214/2) ){
871      if ( (pkt_num-16777215) < 0 ){      if ( IsDebug() ) printf(" rise down pktnum %lld \n",(Long64_t)pkt_num-16777215LL);
872        return((16777215-pkt_num));      return((Long64_t)pkt_num-16777215LL);
     } else {  
       return((pkt_num-16777215));  
     };  
873    };    };
874    //    //
875    return(pkt_num);    if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)pkt_num);
876      return((Long64_t)pkt_num);
877    //    //
878  };  };
879    
880  /**  /**
881   * Return the correct On Board Time if we went back to zero   * Return the correct On Board Time if we went back to zero
882   */   */
883  ULong64_t PamelaDBOperations::OBT(UInt_t obt){    Long64_t PamelaDBOperations::OBT(UInt_t obt){  
884    //    //
885    if ( obt < (obtfirst/2) && obtfirst > (numeric_limits<UInt_t>::max()/2) ) return((ULong64_t)(obt+numeric_limits<UInt_t>::max()));    if ( IsDebug() ) printf(" obt conversion: 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));
886    //    //
887    if ( obt > (obtfirst*2) && obt > (numeric_limits<UInt_t>::max()/2) ){    if ( obt < (pobtfirst/2) && pobtfirst > (numeric_limits<UInt_t>::max()/2) ){
888      if ( (obt-numeric_limits<UInt_t>::max()) < 0  ){      if ( IsDebug() ) printf(" rise up obt %lld \n",(Long64_t)(obt+numeric_limits<UInt_t>::max()));
889        return((ULong64_t)(numeric_limits<UInt_t>::max()-obt));      return((Long64_t)(obt+numeric_limits<UInt_t>::max()));
890      } else {    };
891        return((ULong64_t)(obt-numeric_limits<UInt_t>::max()));    //
892      };    if ( obt > ((Long64_t)pobtfirst*2) && obt > (numeric_limits<UInt_t>::max()/2) ){
893        if ( IsDebug() ) printf(" pobtfirst*2 %lld \n",((Long64_t)pobtfirst*2));
894        if ( IsDebug() ) printf(" rise down pktnum %lld \n", (Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());
895        return((Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());
896    };    };
897    //    //
898    return((ULong64_t)obt);    if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)obt);
899      return((Long64_t)obt);
900  };  };
901    
902  /**  /**
# Line 550  void PamelaDBOperations::FillClass(Bool_ Line 948  void PamelaDBOperations::FillClass(Bool_
948      lastPkt = glrun->GetRUNTRAILER_PKT();      lastPkt = glrun->GetRUNTRAILER_PKT();
949    };    };
950    //    //
951    if ( mishead && mistrail && lastev+1 == firstev ) throw -14; // run with no events, no runtrailer, no runheader... unsupported    if ( mishead && mistrail && lastev+1 == firstev ) throw -14; // run with no events, no runtrailer, no runheader... unsupported should never arrive here
952    //    //
953    if ( mishead ) {    if ( mishead ) {
954      glrun->Set_GL_RUNH0();      glrun->Set_GL_RUNH0();
# Line 613  Int_t PamelaDBOperations::insertPamelaRa Line 1011  Int_t PamelaDBOperations::insertPamelaRa
1011    if ( idr ) return(1);    if ( idr ) return(1);
1012    //    //
1013    oss.str("");    oss.str("");
1014    oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"    if ( STATIC ){
1015        << this->GetRawPath().Data() << "', '" << this->GetRawFile().Data() << "')";      oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"
1016            << this->GetRawPath().Data() << "', '" << this->GetRawFile().Data() << "')";
1017      } else {
1018        oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('$PAM_RAW', '" << this->GetRawFile().Data() << "')";
1019      };
1020    if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;    if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
1021    //    //
1022    idr =  this->SetID_RAW();    idr =  this->SetID_RAW();
# Line 639  Int_t PamelaDBOperations::insertPamelaGL Line 1041  Int_t PamelaDBOperations::insertPamelaGL
1041    if ( this->GetID_RAW() == 0 )  throw -11;    if ( this->GetID_RAW() == 0 )  throw -11;
1042    //    //
1043    oss.str("");    oss.str("");
1044    oss << "SELECT OFFSET_DATE FROM GL_RESURS_OFFSET WHERE FROM_ID_RAW<= "    oss << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE) FROM GL_RESURS_OFFSET WHERE SPECIAL_FILE='"
1045        << id << " AND TO_ID_RAW >= "        << this->GetRawFile().Data() << "';";
       << id << ";";  
1046    if ( IsDebug() ) printf(" %s \n",oss.str().c_str());    if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
1047    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1048    if ( !result ) throw -10;    if ( !result ) throw -10;
1049    row = result->Next();    row = result->Next();
   if ( !row ) throw -10;  
1050    //    //
1051    t0 = (UInt_t)TDatime(row->GetField(0)).Convert();    if ( !row ){
1052        oss.str("");
1053        oss << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE) FROM GL_RESURS_OFFSET WHERE FROM_ORBIT< "
1054            << dworbit << " order by FROM_ORBIT desc limit 1;";
1055        if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
1056        result = conn->Query(oss.str().c_str());
1057        if ( !result ) throw -10;
1058        row = result->Next();
1059        if ( !row ) throw -10;
1060      };
1061      //
1062      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);
1063      t0 = (UInt_t)tu.GetSec();
1064      if ( IsDebug() ) printf(" t0 is %u ti is %s %s %s %s %s %s\n",t0,row->GetField(0),row->GetField(1),row->GetField(2),row->GetField(3),row->GetField(4),row->GetField(5));
1065      //
1066    /*    /*
1067     * Verify that the TIMESYNC have been not already processed     * Verify that the TIMESYNC have been not already processed
1068     */     */
# Line 663  Int_t PamelaDBOperations::insertPamelaGL Line 1077  Int_t PamelaDBOperations::insertPamelaGL
1077    if (result == NULL) throw -10;    if (result == NULL) throw -10;
1078    row = result->Next();    row = result->Next();
1079    if ((row != NULL) && ((UInt_t)atoll(row->GetField(0)) > 0)){    if ((row != NULL) && ((UInt_t)atoll(row->GetField(0)) > 0)){
1080        if ( IsDebug() ) printf(" found a timesync t0 is %u \n",t0);
1081      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;
1082        //
1083        tsync = (UInt_t)atoll(row->GetField(2));
1084        obt0 = (UInt_t)atoll(row->GetField(1));
1085        //
1086      return(1);      return(1);
1087    };    };
1088    //    //
1089    TTree *T = 0;    TTree *T = 0;
1090      Int_t signal = 0;
1091    //    //
1092    UInt_t nevent = 0;    UInt_t nevent = 0;
1093    UInt_t recEntries = 0;    UInt_t recEntries = 0;
# Line 719  Int_t PamelaDBOperations::insertPamelaGL Line 1139  Int_t PamelaDBOperations::insertPamelaGL
1139          //          //
1140          TYPE = 55;//224;          TYPE = 55;//224;
1141          //          //
1142            if ( IsDebug() ) printf("mcmd tsync %i tsync %u obt %u \n",i,TSYNC,OBT);
1143            //
1144          if ( TSYNC && OBT ){          if ( TSYNC && OBT ){
1145            existsts = true;            existsts = true;
1146            goto out;            goto eout;
1147          };          };
1148          //          //
1149        };        };
# Line 729  Int_t PamelaDBOperations::insertPamelaGL Line 1151  Int_t PamelaDBOperations::insertPamelaGL
1151    };    };
1152    if ( !existsts ) { // try with runheader and runtrailer    if ( !existsts ) { // try with runheader and runtrailer
1153      //      //
1154        if ( IsDebug() ) printf(" No ts mcmd \n");
1155        signal = 2;
1156        //
1157      TTree *rh=(TTree*)file->Get("RunHeader");      TTree *rh=(TTree*)file->Get("RunHeader");
1158      if ( !rh || rh->IsZombie() ) throw -17;      if ( !rh || rh->IsZombie() ) throw -17;
1159      TTree *rt=(TTree*)file->Get("RunTrailer");      TTree *rt=(TTree*)file->Get("RunTrailer");
# Line 738  Int_t PamelaDBOperations::insertPamelaGL Line 1163  Int_t PamelaDBOperations::insertPamelaGL
1163      //      //
1164      rt->SetBranchAddress("RunTrailer", &runt);      rt->SetBranchAddress("RunTrailer", &runt);
1165      //      //
1166      //    Int_t rhev = rh->GetEntries();      Int_t nrhev = rh->GetEntries();
1167      //    Int_t rtev = rt->GetEntries();      Int_t nrtev = rt->GetEntries();
1168        if ( IsDebug() ) printf(" ou nevent %i rhev %i rtev %i \n",nevent,nrhev,nrtev);
1169      //      //
1170      if ( rhev > 0 ){      if ( nrhev > 0 ){
1171        rh->GetEntry(0);        for (Int_t i=0; i<nrhev; i++){
1172        //          //
1173        TSYNC = runh->LAST_TIME_SYNC_INFO;          rh->GetEntry(i);
1174        OBT = runh->OBT_TIME_SYNC * 1000;          //
1175        //          TSYNC = runh->LAST_TIME_SYNC_INFO;
1176        TYPE = 20;          OBT = runh->OBT_TIME_SYNC * 1000;
1177        //          //
1178        if ( TSYNC && OBT ){          TYPE = 20;
1179          existsts = true;          //
1180          goto out;          if ( IsDebug() ) printf("runheader %i tsync %u obt %u \n",i,TSYNC,OBT);
1181            //
1182            if ( TSYNC && OBT ){
1183              existsts = true;
1184              goto eout;
1185            };
1186        };        };
1187        //        //
1188      };      };
1189      if ( rtev > 0 ){      if ( nrtev > 0 ){
       rt->GetEntry(0);  
1190        //        //
1191        TSYNC = runt->LAST_TYME_SYNC_INFO;        if ( IsDebug() ) printf(" No runheader \n");
1192        OBT = runt->OBT_TYME_SYNC * 1000;        signal = 6;
1193        //        //
1194        TYPE = 21;        for (Int_t i=0; i<nrtev; i++){
1195        //          //
1196        if ( TSYNC && OBT ){          rt->GetEntry(i);
1197          existsts = true;          //
1198          goto out;          TSYNC = runt->LAST_TYME_SYNC_INFO;
1199            OBT = runt->OBT_TYME_SYNC * 1000;
1200            //
1201            TYPE = 21;
1202            //
1203            if ( IsDebug() ) printf("runtrailer %i tsync %u obt %u \n",i,TSYNC,OBT);
1204            //
1205            if ( TSYNC && OBT ){
1206              existsts = true;
1207              goto eout;
1208            };
1209        };        };
1210        //        //
1211        } else {
1212          if ( IsDebug() ) printf(" No runheader \n");
1213      };      };
1214    };    };
1215    //    //
1216    if ( !existsts ){ // try with inclination mcmd    if ( !existsts ){ // try with inclination mcmd
1217        //
1218        if ( IsDebug() ) printf(" No runtrailer \n");
1219        signal = 14;
1220        //
1221      Double_t timesync = 0.;      Double_t timesync = 0.;
1222      for (UInt_t i=0; i<nevent;i++){      for (UInt_t i=0; i<nevent;i++){
1223        //        //
# Line 800  Int_t PamelaDBOperations::insertPamelaGL Line 1246  Int_t PamelaDBOperations::insertPamelaGL
1246        TYPE = 666;        TYPE = 666;
1247        if ( TSYNC && OBT ){        if ( TSYNC && OBT ){
1248          existsts = true;          existsts = true;
1249          goto out;          goto eout;
1250        };        };
1251      };      };
1252    };    };
1253    //    //
1254    if ( !existsts && obt0 ){ // insert timesync by hand    if ( !existsts && obt0 ){ // insert timesync by hand
1255        //
1256        if ( IsDebug() ) printf(" No incl mcmd \n");
1257        signal = 30;
1258        //
1259      OBT = obt0;      OBT = obt0;
1260      TSYNC = tsync;      TSYNC = tsync;
1261      TYPE = 999;      TYPE = 999;
1262      existsts = true;      existsts = true;
1263      goto out;      goto eout;
1264    };    };
1265    //    //
1266   out:   eout:
1267    //    //
1268    if ( !existsts ) throw -3;    if ( !existsts ) throw -3;
1269    //    //
# Line 826  Int_t PamelaDBOperations::insertPamelaGL Line 1276  Int_t PamelaDBOperations::insertPamelaGL
1276    conn->Query(oss.str().c_str());    conn->Query(oss.str().c_str());
1277    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());
1278    //    //
1279      if ( IsDebug() ) printf(" found a timesync t0 is %u \n",t0);
1280    toffset = (UInt_t)TSYNC - (UInt_t)(this->OBT(OBT)/1000) + t0;    toffset = (UInt_t)TSYNC - (UInt_t)(this->OBT(OBT)/1000) + t0;
1281    //    //
1282      tsync = TSYNC;
1283      obt0 = OBT;
1284      //
1285    delete result;    delete result;
1286    return(0);    return(signal);
1287  }  }
1288    
1289  /**  /**
# Line 843  Int_t PamelaDBOperations::insertPamelaRo Line 1297  Int_t PamelaDBOperations::insertPamelaRo
1297    UInt_t idtimesync = 0;    UInt_t idtimesync = 0;
1298    //    //
1299    oss.str("");    oss.str("");
1300    oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "    if ( STATIC ){
1301        << " LEFT JOIN GL_ROOT "      oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1302        << " ON GL_RAW.ID = GL_ROOT.ID_RAW "          << " LEFT JOIN GL_ROOT "
1303        << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "          << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1304        << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";          << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "
1305            << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1306      } else {
1307        oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1308            << " LEFT JOIN GL_ROOT "
1309            << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1310            << " WHERE GL_RAW.PATH = '$PAM_RAW' AND "
1311            << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1312      };
1313    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1314    //    //
1315    if ( !result ) throw -12;    if ( !result ) throw -12;
# Line 874  Int_t PamelaDBOperations::insertPamelaRo Line 1336  Int_t PamelaDBOperations::insertPamelaRo
1336    idtimesync = (UInt_t)atoll(row->GetField(0));    idtimesync = (UInt_t)atoll(row->GetField(0));
1337    //    //
1338    oss.str("");    oss.str("");
1339    oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"    if ( STATIC ){
1340        << this->GetID_RAW() << "', '" << idtimesync << "', '" << this->GetRootPath().Data() << "', '" << this->GetRootFile().Data() << "')";      oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
1341            << this->GetID_RAW() << "', '" << idtimesync << "', '" << this->GetRootPath().Data() << "', '" << this->GetRootFile().Data() << "')";
1342      } else {
1343        oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
1344            << this->GetID_RAW() << "', '" << idtimesync << "', '$PAM_L0', '" << this->GetRootFile().Data() << "')";
1345      };
1346    //    //
1347    if (conn->Query(oss.str().c_str()) == 0) throw -4;    if (conn->Query(oss.str().c_str()) == 0) throw -4;
1348    //    //
# Line 902  Int_t PamelaDBOperations::assignBOOT_NUM Line 1369  Int_t PamelaDBOperations::assignBOOT_NUM
1369    TSQLResult *result = 0;    TSQLResult *result = 0;
1370    TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
1371    oss.str("");    oss.str("");
1372    oss << "SELECT ID, BOOT_NUMBER FROM GL_RAW WHERE "    if ( STATIC ){
1373        << " PATH = '" << this->GetRawPath().Data() << "' AND "      oss << "SELECT ID, BOOT_NUMBER FROM GL_RAW WHERE "
1374        << " NAME = '" << this->GetRawFile().Data() << "' ";          << " PATH = '" << this->GetRawPath().Data() << "' AND "
1375            << " NAME = '" << this->GetRawFile().Data() << "' ";
1376      } else {
1377        oss << "SELECT ID, BOOT_NUMBER FROM GL_RAW WHERE "
1378            << " PATH = '$PAM_RAW' AND "
1379            << " NAME = '" << this->GetRawFile().Data() << "' ";
1380      };
1381    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1382    //    //
1383    if ( !result ) return(8);    if ( !result ) throw -4;;
1384    row = result->Next();    row = result->Next();
1385    if ( !row ) return(16);    if ( !row ) return(16);
1386    if ( row->GetField(1) ){    if ( row->GetField(1) ){
1387      this->SetBOOTnumber((UInt_t)atoll(row->GetField(1)));      this->SetBOOTnumber((UInt_t)atoll(row->GetField(1)));
1388      return(1);      return(1);
1389    };    };
1390    if ( !row->GetField(0) ) return(8);    if ( !row->GetField(0) ) throw -26;
1391    //    //
1392    UInt_t idRaw = (UInt_t)atoll(row->GetField(0));    UInt_t idRaw = (UInt_t)atoll(row->GetField(0));
1393    //    //
# Line 924  Int_t PamelaDBOperations::assignBOOT_NUM Line 1397  Int_t PamelaDBOperations::assignBOOT_NUM
1397    trDumpEv = (TTree*)file->Get("VarDump");    trDumpEv = (TTree*)file->Get("VarDump");
1398    if ( !trDumpEv || trDumpEv->IsZombie() ) throw -20;    if ( !trDumpEv || trDumpEv->IsZombie() ) throw -20;
1399    //    //
   if (trDumpEv == NULL) return(2);  
   //      
1400    VarDumpEvent  *vde = 0;    VarDumpEvent  *vde = 0;
1401    VarDumpRecord *vdr = 0;    VarDumpRecord *vdr = 0;
1402    //    //
1403      Bool_t found = false;
1404    trDumpEv->SetBranchAddress("VarDump", &vde);    trDumpEv->SetBranchAddress("VarDump", &vde);
1405    if (trDumpEv->GetEntries() > 0){    if ( trDumpEv->GetEntries() > 0 ){
1406      trDumpEv->GetEntry(0);      found = false;
1407      vde->Records->GetEntries();      for ( Int_t i = 0; i < trDumpEv->GetEntries(); i++){
1408      if ( !vde->Records->GetEntries() ){        trDumpEv->GetEntry(i);
1409        if ( !this->GetBOOTnumber() ) return(4);        //      vde->Records->GetEntries();
1410      } else {        if ( vde->Records->GetEntries()>5 ){
1411            found = true;
1412            goto fill;
1413          };
1414        };
1415      fill:
1416        if ( found ){
1417          //
1418        vdr = (VarDumpRecord*)vde->Records->At(6);        vdr = (VarDumpRecord*)vde->Records->At(6);
1419          //
1420        this->SetBOOTnumber((Int_t)vdr->VAR_VALUE);        this->SetBOOTnumber((Int_t)vdr->VAR_VALUE);
1421          //
1422        } else {
1423          if ( !this->GetBOOTnumber() && !this->AutoBoot()) return(4);
1424        };
1425      } else {
1426        if ( !this->GetBOOTnumber() && !this->AutoBoot()) return(2);
1427      };
1428      //
1429      UInt_t bn = 0;
1430      Bool_t afound = false;
1431      if ( !found && this->AutoBoot()){
1432        afound = true;
1433        //
1434        // Search for other files with similar timesync
1435        //
1436        if ( IsDebug() ) printf(" tsync %u obt0 %u \n",tsync,obt0);
1437        UInt_t upperts = tsync-(obt0/1000)+5;
1438        UInt_t lowerts = tsync-(obt0/1000)-5;
1439        oss.str("");
1440        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)<"
1441            << upperts
1442            << " AND TIMESYNC-(OBT0/1000)>"
1443            << lowerts
1444            << " AND GL_RAW.BOOT_NUMBER>0 GROUP BY GL_TIMESYNC.OBT0;";
1445        result = conn->Query(oss.str().c_str());
1446        if ( IsDebug() ) printf(" Query the GL_TIMESYNC table to find boot number:\n %s \n",oss.str().c_str());
1447        //
1448        if ( !result ) throw -4;;
1449        found = true;
1450        if ( result->GetRowCount()<3 ){
1451          if ( IsDebug() ) printf(" AGH! no results!\n");
1452          found = false;
1453        } else {
1454          row = result->Next();      
1455          bn = (UInt_t)atoll(row->GetField(0));
1456          for ( Int_t r=1; r<result->GetRowCount() ;r++){
1457            if ( !row ) throw -4;
1458            if ( IsDebug() ) printf(" BOOT number is %s \n",row->GetField(0));
1459            if ( bn != (UInt_t)atoll(row->GetField(0)) ){
1460              if ( IsDebug() ) printf(" AGH! bn = %u here instead %u \n",bn,(UInt_t)atoll(row->GetField(0)));
1461              found = false;
1462            };
1463            row = result->Next();
1464          };
1465      };      };
1466      };
1467      //
1468      Int_t sgn = 0;
1469      //
1470      if ( !found && !BOOTNO ){
1471        throw -29;
1472    } else {    } else {
1473      if ( !this->GetBOOTnumber() ) return(2);      if ( afound ){
1474          this->SetBOOTnumber(bn);
1475          sgn = 8;
1476        };
1477    };    };
1478    //    //
1479    oss.str("");    oss.str("");
# Line 950  Int_t PamelaDBOperations::assignBOOT_NUM Line 1483  Int_t PamelaDBOperations::assignBOOT_NUM
1483    conn->Query(oss.str().c_str());          conn->Query(oss.str().c_str());      
1484    //    //
1485    delete result;    delete result;
1486    return(0);    return(sgn);
1487  };  };
1488    
1489  /**  /**
# Line 1023  Int_t PamelaDBOperations::insertPamelaRU Line 1556  Int_t PamelaDBOperations::insertPamelaRU
1556          //          //
1557          if ( IsDebug() ) printf(" Missing header %i %i %i\n",ptht,pth,ptt);          if ( IsDebug() ) printf(" Missing header %i %i %i\n",ptht,pth,ptt);
1558          //          //
1559          if ( (ptt-1) < 0 ) throw -15;          if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
1560          rt->GetEntry(ptt-1);          rt->GetEntry(ptt-1);
1561          cod = eht->GetCounter();          cod = eht->GetCounter();
1562          evbefh = cod->Get(pctp->Physics);          evbefh = cod->Get(pctp->Physics);
# Line 1129  Int_t PamelaDBOperations::insertPamelaRU Line 1662  Int_t PamelaDBOperations::insertPamelaRU
1662            if ( (UInt_t)evbeft < upperentry-1 ){            if ( (UInt_t)evbeft < upperentry-1 ){
1663              if ( IsDebug() ) printf(" Piece of run at the end of the file with NO RUNHEADER!\n");              if ( IsDebug() ) printf(" Piece of run at the end of the file with NO RUNHEADER!\n");
1664              //              //
1665              if ( (ptt-1) < 0 ) throw -15;              if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
1666              rt->GetEntry(ptt-1);              rt->GetEntry(ptt-1);
1667              cod = eht->GetCounter();              cod = eht->GetCounter();
1668              evbefh = cod->Get(pctp->Physics);              evbefh = cod->Get(pctp->Physics);
# Line 1213  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1746  Bool_t PamelaDBOperations::IsRunAlreadyI
1746      if ( glrun->GetNEVENTS() > (UInt_t)atoll(row->GetField(1)) ){      if ( glrun->GetNEVENTS() > (UInt_t)atoll(row->GetField(1)) ){
1747        //        //
1748        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");
1749        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1750        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1751        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) <<";";
1752        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1753    //       conn->Query(oss.str().c_str());
1754        if ( signal ) signal = false;        if ( signal ) signal = false;
1755        goto gonext;              goto gonext;      
1756        //        //
# Line 1230  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1764  Bool_t PamelaDBOperations::IsRunAlreadyI
1764        //        //
1765        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");
1766        //        //
1767        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1768        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1769        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) <<";";
1770        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1771    //       conn->Query(oss.str().c_str());
1772        //        //
1773        if ( signal ) signal = false;        if ( signal ) signal = false;
1774        goto gonext;        goto gonext;
# Line 1247  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1782  Bool_t PamelaDBOperations::IsRunAlreadyI
1782        //        //
1783        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");
1784        //        //
1785        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1786        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1787        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) <<";";
1788        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1789    //       conn->Query(oss.str().c_str());
1790        if ( signal ) signal = false;        if ( signal ) signal = false;
1791        //        //
1792      };      };
# Line 1265  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1801  Bool_t PamelaDBOperations::IsRunAlreadyI
1801    delete result;    delete result;
1802    //    //
1803    if ( signal && IsDebug() ) printf(" The run has already been inserted \n");        if ( signal && IsDebug() ) printf(" The run has already been inserted \n");    
1804      if ( !signal && IsDebug() ) printf(" The run existed and was deleted, fill the DB \n");
1805    return(signal);    return(signal);
1806  };  };
1807    
# Line 1286  void PamelaDBOperations::HandleRun(){   Line 1823  void PamelaDBOperations::HandleRun(){  
1823      //      //
1824      this->FillClass();      this->FillClass();
1825      //      //
1826      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);      if ( !IsRunAlreadyInserted() ){
1827          glrun->SetID(this->AssignRunID());
1828          glrun->SetID_RUN_FRAG(0);
1829          glrun->Fill_GL_RUN(conn);
1830        };
1831    } else {    } else {
1832      //      //
1833      if ( IsDebug() ) printf(" oh no! the distance between runheader and runtrailer seems wrong: check %llu pktt %llu \n",chkpkt,pktt);      if ( IsDebug() ) printf(" oh no! the distance between runheader and runtrailer seems wrong: check %llu pktt %llu \n",chkpkt,pktt);
# Line 1309  void PamelaDBOperations::HandleRunFragme Line 1850  void PamelaDBOperations::HandleRunFragme
1850    UInt_t rhfirstev = firstev;    UInt_t rhfirstev = firstev;
1851    UInt_t rtlastev = lastev;    UInt_t rtlastev = lastev;
1852    Bool_t found = false;    Bool_t found = false;
1853      Bool_t foundinrun = false;
1854    //    //
1855    TSQLResult *result = 0;    TSQLResult *result = 0;
1856    TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
# Line 1335  void PamelaDBOperations::HandleRunFragme Line 1877  void PamelaDBOperations::HandleRunFragme
1877    //    //
1878    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");
1879    //    //
1880      // First of all insert the run in the fragment table...
1881      //
1882      oss.str("");
1883      oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
1884          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
1885          << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
1886          << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
1887          << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
1888          << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
1889          << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
1890          << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
1891          << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1892          << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
1893          << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
1894          << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
1895          << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
1896          << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
1897      //
1898      if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
1899      result = conn->Query(oss.str().c_str());
1900      //
1901      if ( !result ) throw -4;
1902      //
1903      row = result->Next();
1904      //
1905      if ( !row ){
1906        //
1907        // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
1908        //
1909        if ( IsDebug() ) printf(" The run is new \n");
1910        if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
1911        //
1912        glrun->SetID(this->AssignRunID());
1913        glrun->SetID_RUN_FRAG(0);
1914        glrun->Fill_GL_RUN_FRAGMENTS(conn);
1915        //
1916      } else {
1917        if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
1918        return;
1919      };
1920      //
1921      //
1922    // 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?
1923    //        //    
1924    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 1343  void PamelaDBOperations::HandleRunFragme Line 1927  void PamelaDBOperations::HandleRunFragme
1927      oss.str("");      oss.str("");
1928      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 "
1929          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
1930          << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME()          << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1931            << " ID != " << glrun->ID
1932          << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!          << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
1933      //      //
1934      if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());      if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());
# Line 1353  void PamelaDBOperations::HandleRunFragme Line 1938  void PamelaDBOperations::HandleRunFragme
1938      //      //
1939      row = result->Next();      row = result->Next();
1940      //      //
1941        if ( !row && NoFrag() ){
1942          //
1943          oss.str("");
1944          oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
1945              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
1946              << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1947              << " ID != " << glrun->ID
1948              << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
1949          //
1950          if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
1951          result = conn->Query(oss.str().c_str());
1952          //
1953          if ( !result ) throw -4;
1954          //
1955          foundinrun = true;
1956          //
1957          row = result->Next();
1958          //
1959        };
1960        //
1961      if ( !row ){      if ( !row ){
1962        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
1963        found = false;        found = false;
# Line 1427  void PamelaDBOperations::HandleRunFragme Line 2032  void PamelaDBOperations::HandleRunFragme
2032        //        //
2033        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 ");
2034        //        //
2035          if ( foundinrun ){
2036            glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2037            glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2038          };
2039          //
2040        GL_RUN *glrun1 = new GL_RUN();        GL_RUN *glrun1 = new GL_RUN();
2041        //        //
2042        UInt_t idfrag = (UInt_t)atoll(row->GetField(0));        //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
2043        //        //
2044        oss.str("");        oss.str("");
2045        oss << " ID="<<row->GetField(0)<<";";        oss << " ID="<<row->GetField(0)<<";";
# Line 1458  void PamelaDBOperations::HandleRunFragme Line 2068  void PamelaDBOperations::HandleRunFragme
2068        };        };
2069        if ( IsDebug() ) printf(" Check overlapping events done: %i %i %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);        if ( IsDebug() ) printf(" Check overlapping events done: %i %i %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2070        //        //
       glrun1->SetID(0);  
2071        glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());        glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
2072        glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());        glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
2073        glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());        glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
# Line 1467  void PamelaDBOperations::HandleRunFragme Line 2076  void PamelaDBOperations::HandleRunFragme
2076        //        //
2077        glrun->SetEV_FROM(firstev);        glrun->SetEV_FROM(firstev);
2078        glrun->SetNEVENTS(lastev-firstev+1);        glrun->SetNEVENTS(lastev-firstev+1);
2079          //
2080        glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());        glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
2081        glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());        glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
2082        glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());        glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
# Line 1486  void PamelaDBOperations::HandleRunFragme Line 2096  void PamelaDBOperations::HandleRunFragme
2096        //        //
2097        if ( !IsRunAlreadyInserted() ){        if ( !IsRunAlreadyInserted() ){
2098          //          //
2099            //      glrun->SetID(this->AssignRunID());
2100            glrun->SetID_RUN_FRAG(glrun1->GetID());
2101          glrun->Fill_GL_RUN(conn);          glrun->Fill_GL_RUN(conn);
2102          //          //
2103          // 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);  
2104          //          //
2105            glrun1->SetID_RUN_FRAG(glrun->GetID());
2106          glrun1->Fill_GL_RUN(conn);          glrun1->Fill_GL_RUN(conn);
2107          //          //
         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;  
         //  
2108        };        };
       //  
       delete glrun1;  
       //  
2109        // delete old entry in fragment table        // delete old entry in fragment table
2110        //        //
2111        oss.str("");        glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2112          glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2113        //        //
2114        oss << " DELETE FROM GL_RUN_FRAGMENTS WHERE ID = " << idfrag << ";";        delete glrun1;
2115        //        //
       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;  
2116        //        //
2117        return;        return;
2118        //        //
# Line 1555  void PamelaDBOperations::HandleRunFragme Line 2121  void PamelaDBOperations::HandleRunFragme
2121    };    };
2122    //    //
2123    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
2124                                             // 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
2125      //      //
2126      oss.str("");      oss.str("");
2127      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 "
2128          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2129          << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME()          << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2130            << " ID != " << glrun->ID
2131          << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";          << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2132      //      //
2133      if ( IsDebug() ) printf(" look for runtrailer in the fragments table: query is \n %s \n",oss.str().c_str());      if ( IsDebug() ) printf(" look for runtrailer in the fragments table: query is \n %s \n",oss.str().c_str());
# Line 1570  void PamelaDBOperations::HandleRunFragme Line 2137  void PamelaDBOperations::HandleRunFragme
2137      //      //
2138      row = result->Next();      row = result->Next();
2139      //      //
2140        if ( !row && NoFrag() ){
2141          //
2142          oss.str("");
2143          oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN WHERE "
2144              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2145              << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2146              << " ID != " << glrun->ID
2147              << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2148          //
2149          if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
2150          result = conn->Query(oss.str().c_str());
2151          //
2152          if ( !result ) throw -4;
2153          //
2154          foundinrun = true;
2155          row = result->Next();
2156          //
2157        };
2158        //
2159      if ( !row ){      if ( !row ){
2160        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2161        found = false;        found = false;
# Line 1643  void PamelaDBOperations::HandleRunFragme Line 2229  void PamelaDBOperations::HandleRunFragme
2229        //        //
2230        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 ");
2231        //        //
2232          if ( foundinrun ){
2233            glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2234            glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2235          };
2236          //
2237        GL_RUN *glrun1 = new GL_RUN();        GL_RUN *glrun1 = new GL_RUN();
2238        //        //
2239        UInt_t idfrag = (UInt_t)atoll(row->GetField(0));        //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
2240        //        //
2241        oss.str("");        oss.str("");
2242        oss << " ID="<<row->GetField(0)<<";";        oss << " ID="<<row->GetField(0)<<";";
# Line 1682  void PamelaDBOperations::HandleRunFragme Line 2273  void PamelaDBOperations::HandleRunFragme
2273        glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());        glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());
2274        glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());        glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());
2275        //        //
       glrun1->SetID(0);  
2276        glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());        glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());
2277        glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());        glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());
2278        glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());        glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());
# Line 1702  void PamelaDBOperations::HandleRunFragme Line 2292  void PamelaDBOperations::HandleRunFragme
2292        //        //
2293        if ( !IsRunAlreadyInserted() ){        if ( !IsRunAlreadyInserted() ){
2294          //          //
2295          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();  
2296          //          //
2297          UInt_t idrun0 = 0;          glrun->SetID_RUN_FRAG(glrun1->GetID());
2298          if ( !row ){          glrun->Fill_GL_RUN(conn);
           throw -10;  
         } else {  
           idrun0 = (UInt_t)atoll(row->GetField(0));  
         };  
2299          //          //
2300          glrun1->SetID_RUN_FRAG(idrun0);          // set id number
2301          //          //
2302            glrun1->SetID_RUN_FRAG(glrun->GetID());
2303          glrun1->Fill_GL_RUN(conn);          glrun1->Fill_GL_RUN(conn);
2304          //          //
         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;  
         //  
2305        };        };
2306        //        //
2307        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 << ";";  
2308        //        //
2309        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");
2310        result =  conn->Query(oss.str().c_str());        glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
       if ( !result ) throw -4;  
2311        //        //
2312          delete glrun1;
2313        //        //
2314        return;        return;
2315        //        //
# Line 1800  void PamelaDBOperations::HandleRunFragme Line 2346  void PamelaDBOperations::HandleRunFragme
2346      //      //
2347      row = result->Next();      row = result->Next();
2348      //      //
2349      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 {  
2350        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");
2351        } else {
2352          if ( NoFrag() ){
2353            glrun->SetID_RUN_FRAG(glrun->GetID());
2354            glrun->Fill_GL_RUN(conn);      
2355            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2356          };    
2357      };      };
2358    };    };
2359    //    //
# Line 1864  void PamelaDBOperations::HandleMissingHo Line 2379  void PamelaDBOperations::HandleMissingHo
2379      //      //
2380      this->FillClass(mishead,mistrail,firstev,lastev);      this->FillClass(mishead,mistrail,firstev,lastev);
2381      //      //
2382      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);          if ( !IsRunAlreadyInserted() ){
2383          glrun->SetID(this->AssignRunID());
2384          glrun->SetID_RUN_FRAG(0);
2385          glrun->Fill_GL_RUN(conn);    
2386        };
2387      //      //
2388    };    };
2389    //    //
# Line 2031  Bool_t PamelaDBOperations::IsRunConsiste Line 2550  Bool_t PamelaDBOperations::IsRunConsiste
2550            //                  //      
2551            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
2552            //            //
2553            if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                  if ( !IsRunAlreadyInserted() ){
2554                glrun->SetID(this->AssignRunID());
2555                glrun->SetID_RUN_FRAG(0);
2556                glrun->Fill_GL_RUN(conn);      
2557              };
2558            //            //
2559            firstevno = lastentry + 1;            firstevno = lastentry + 1;
2560            //            //
# Line 2106  void PamelaDBOperations::HandleSuspiciou Line 2629  void PamelaDBOperations::HandleSuspiciou
2629    if ( firstev == lastev+1 ) { // no events inside the run!    if ( firstev == lastev+1 ) { // no events inside the run!
2630      if ( IsDebug() ) printf(" Checking but no events in the run! \n");      if ( IsDebug() ) printf(" Checking but no events in the run! \n");
2631      //      //
     //    if ( IsDebug() ) printf(" -> fill the DB \n");  
     //  
2632      this->FillClass();      this->FillClass();
2633      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);          if ( !IsRunAlreadyInserted() ){
2634          glrun->SetID(this->AssignRunID());
2635          glrun->SetID_RUN_FRAG(0);
2636          glrun->Fill_GL_RUN(conn);    
2637        };
2638      //      //
2639    } else {    } else {
2640      //      //
# Line 2137  void PamelaDBOperations::HandleSuspiciou Line 2662  void PamelaDBOperations::HandleSuspiciou
2662        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");
2663        //        //
2664        this->FillClass();        this->FillClass();
2665        if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                if ( !IsRunAlreadyInserted() ){
2666            glrun->SetID(this->AssignRunID());
2667            glrun->SetID_RUN_FRAG(0);
2668            glrun->Fill_GL_RUN(conn);        
2669          };
2670        //        //
2671      } else {      } else {
2672        //        //
# Line 2235  void PamelaDBOperations::HandleSuspiciou Line 2764  void PamelaDBOperations::HandleSuspiciou
2764            //                  //      
2765            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
2766            //            //
2767            if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                  if ( !IsRunAlreadyInserted() ){
2768                glrun->SetID(this->AssignRunID());
2769                glrun->SetID_RUN_FRAG(0);
2770                glrun->Fill_GL_RUN(conn);      
2771              };
2772            //            //
2773            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...
2774              //              //
# Line 2270  void PamelaDBOperations::HandleSuspiciou Line 2803  void PamelaDBOperations::HandleSuspiciou
2803              //                  //    
2804              this->SetCommonGLRUN(firstTime,lastTime);              this->SetCommonGLRUN(firstTime,lastTime);
2805              //              //
2806              if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                    if ( !IsRunAlreadyInserted() ){
2807                  glrun->SetID(this->AssignRunID());
2808                  glrun->SetID_RUN_FRAG(0);
2809                  glrun->Fill_GL_RUN(conn);      
2810                };
2811            };            };
2812            //            //
2813            firstevno = lastentry + 1;            firstevno = lastentry + 1;
# Line 2318  Int_t PamelaDBOperations::insertCALO_CAL Line 2855  Int_t PamelaDBOperations::insertCALO_CAL
2855    tr->SetBranchAddress("Header", &eh);    tr->SetBranchAddress("Header", &eh);
2856    nevents = tr->GetEntries();    nevents = tr->GetEntries();
2857    //    //
2858    if ( !nevents ) return(0);    if ( !nevents ) return(1);
2859    //    //
2860    for (UInt_t i=0; i < nevents; i++){    for (UInt_t i=0; i < nevents; i++){
2861      tr->GetEntry(i);      tr->GetEntry(i);
# Line 2377  Int_t PamelaDBOperations::insertCALO_CAL Line 2914  Int_t PamelaDBOperations::insertCALO_CAL
2914                // no calibrations in the db contain our calibration                // no calibrations in the db contain our calibration
2915                //                //
2916                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);
2917                if ( fromtime < 1150863400 ){                if ( fromtime < 1150871000 ){ //1150866904
2918                  if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);                  if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);
2919                  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
2920                };                };
# Line 2440  Int_t PamelaDBOperations::insertCALO_CAL Line 2977  Int_t PamelaDBOperations::insertCALO_CAL
2977            //            //
2978          } else {          } else {
2979            //            //
2980            if ( IsDebug() ) printf(" Repetead calo calibration for section %i at time %i obt %i pkt %i \n",section,fromtime,obt,pkt);            if ( IsDebug() ) printf(" Repeated calo calibration for section %i at time %i obt %i pkt %i \n",section,fromtime,obt,pkt);
2981            //            //
2982          };                };      
2983          //                //      
# Line 2522  void PamelaDBOperations::HandleTRK_CALIB Line 3059  void PamelaDBOperations::HandleTRK_CALIB
3059        // no calibrations in the db contain our calibration        // no calibrations in the db contain our calibration
3060        //        //
3061        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");
3062        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
3063        //        //
3064        oss.str("");        oss.str("");
3065        oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "        oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "
# Line 2635  Int_t PamelaDBOperations::insertTRK_CALI Line 3172  Int_t PamelaDBOperations::insertTRK_CALI
3172    tr2->SetBranchAddress("Header", &eh2);    tr2->SetBranchAddress("Header", &eh2);
3173    nevents2 = tr2->GetEntries();    nevents2 = tr2->GetEntries();
3174    //    //
3175    if ( !nevents1 && !nevents2 ) return(0);    if ( !nevents1 && !nevents2 ) return(1);
3176    //    //
3177    t2 = -1;    t2 = -1;
3178    Int_t pret2 = 0;    Int_t pret2 = 0;
# Line 2651  Int_t PamelaDBOperations::insertTRK_CALI Line 3188  Int_t PamelaDBOperations::insertTRK_CALI
3188      pkt1 = ph1->GetCounter();        pkt1 = ph1->GetCounter();  
3189      fromtime = this->GetAbsTime(ph1->GetOrbitalTime());        fromtime = this->GetAbsTime(ph1->GetOrbitalTime());  
3190      //      //
3191      valid = 1;  //     valid = 1;
3192      //  //     //
3193      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
3194      //      //
3195      //      //
3196      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) ){
3197        //        //
3198        if ( IsDebug() ) printf(" Trk calibration1 at time %i obt %i pkt %i \n",fromtime,obt1,pkt1);        if ( IsDebug() ) printf(" Trk calibration1 at time %i obt %i pkt %i \n",fromtime,obt1,pkt1);
3199          //      
3200          valid = ValidateTrkCalib( caltrk1, eh1 );
3201          if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;
3202        //        //
3203        // Do we have the second calibration packet?        // Do we have the second calibration packet?
3204        //        //
# Line 2675  Int_t PamelaDBOperations::insertTRK_CALI Line 3215  Int_t PamelaDBOperations::insertTRK_CALI
3215            obt2 = ph2->GetOrbitalTime();              obt2 = ph2->GetOrbitalTime();  
3216            pkt2 = ph2->GetCounter();              pkt2 = ph2->GetCounter();  
3217            //            //
3218            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
3219            //                  //      
3220          } else {          } else {
3221            //            //
# Line 2706  Int_t PamelaDBOperations::insertTRK_CALI Line 3246  Int_t PamelaDBOperations::insertTRK_CALI
3246          //          //
3247          if ( IsDebug() ) printf(" The trk calibration2 at obt %i pkt %i t2 is %i is good \n",obt2,pkt2,t2);          if ( IsDebug() ) printf(" The trk calibration2 at obt %i pkt %i t2 is %i is good \n",obt2,pkt2,t2);
3248          //          //
3249            UInt_t valid2 = ValidateTrkCalib( caltrk2, eh2 );
3250            if ( IsDebug() ) cout << " pkt2 validation --> "<<valid2<<endl;
3251            valid = valid & valid2;
3252            //
3253          // Handle good calib          // Handle good calib
3254          //          //
3255          this->HandleTRK_CALIB(true,true);          this->HandleTRK_CALIB(true,true);
# Line 2807  Int_t PamelaDBOperations::insertS4_CALIB Line 3351  Int_t PamelaDBOperations::insertS4_CALIB
3351    stringstream oss;    stringstream oss;
3352    oss.str("");    oss.str("");
3353    //    //
   CalibS4Event *calibS4    = new  CalibS4Event();  
3354    TTree *tr = 0;    TTree *tr = 0;
3355    EventHeader *eh = 0;    EventHeader *eh = 0;
3356    PscuHeader *ph = 0;    PscuHeader *ph = 0;
# Line 2821  Int_t PamelaDBOperations::insertS4_CALIB Line 3364  Int_t PamelaDBOperations::insertS4_CALIB
3364    tr = (TTree*)file->Get("CalibS4");    tr = (TTree*)file->Get("CalibS4");
3365    if ( !tr || tr->IsZombie() ) throw -24;    if ( !tr || tr->IsZombie() ) throw -24;
3366    //    //
   tr->SetBranchAddress("CalibS4", &calibS4);  
3367    tr->SetBranchAddress("Header", &eh);    tr->SetBranchAddress("Header", &eh);
3368    //    //
3369    nevents = tr->GetEntries();    nevents = tr->GetEntries();
3370    //    //
3371    if ( !nevents ) return(0);    if ( !nevents ) return(1);
3372    //    //
3373    for (UInt_t i = 0; i < nevents; i++){    for (UInt_t i = 0; i < nevents; i++){
3374      //      //
3375      tr->GetEntry(i);      tr->GetEntry(i);
     TArrayD params = S4_paramfit(calibS4);  
3376      //      //
3377      ph = eh->GetPscuHeader();      ph = eh->GetPscuHeader();
3378      obt = ph->GetOrbitalTime();        obt = ph->GetOrbitalTime();  
# Line 2881  Int_t PamelaDBOperations::insertS4_CALIB Line 3422  Int_t PamelaDBOperations::insertS4_CALIB
3422            // no calibrations in the db contain our calibration            // no calibrations in the db contain our calibration
3423            //            //
3424            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");
3425            if ( fromtime < 1150863400 ){            if ( fromtime < 1150871000 ){  
3426              if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);              if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);
3427              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
3428            };            };
# Line 2921  Int_t PamelaDBOperations::insertS4_CALIB Line 3462  Int_t PamelaDBOperations::insertS4_CALIB
3462          };          };
3463          //          //
3464          oss.str("");          oss.str("");
3465          oss << " INSERT INTO GL_S4_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,PARAM_FIT0,PARAM_FIT1,OBT,PKT,BOOT_NUMBER,VALIDATION) "          oss << " INSERT INTO GL_S4_CALIB (ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME,OBT,PKT,BOOT_NUMBER) "
3466              << " VALUES (NULL,' "              << " VALUES (NULL,' "
3467              << idroot << "','"              << idroot << "','"
3468              << i << "','"              << i << "','"
3469              << fromtime << "','"              << fromtime << "','"
3470              << totime << "','"              << totime << "','"
             << dec << params.At(0) << "','"  
             << dec << params.At(1) << "','"        
3471              << obt << "','"              << obt << "','"
3472              << pkt << "','"              << pkt << "','"
3473              << this->GetBOOTnumber() << "','"              << this->GetBOOTnumber() << "');";
             << valid << "');";  
3474          //          //
3475          if ( IsDebug() ) printf(" Insert the new calibration: query is \n %s \n",oss.str().c_str());          if ( IsDebug() ) printf(" Insert the new calibration: query is \n %s \n",oss.str().c_str());
3476          //          //
# Line 2953  Int_t PamelaDBOperations::insertS4_CALIB Line 3491  Int_t PamelaDBOperations::insertS4_CALIB
3491    return(0);    return(0);
3492  };  };
3493    
3494    /**
3495  /*   * Scan the fragment table and move old fragments to the GL_RUN table
  * Fit function Received from Valeria Malvezzi 06/02/2006  
3496   */   */
3497  Double_t fitf(Double_t *x, Double_t *par){    Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(){
3498    Double_t fitval =(par[0]*x[0])+par[1];    return(this->CleanGL_RUN_FRAGMENTS(""));
3499    return fitval;  };
 }  
3500    
3501  /*  /**
3502   * Fit the S4 calibration with a straight line - Received from Valeria Malvezzi 06/02/2006   * Scan the fragment table and move old fragments to the GL_RUN table
3503   */   */
3504  TArrayD PamelaDBOperations::S4_paramfit(pamela::CalibS4Event *S4CalibEvent){        Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(TString fcleanfile){
3505      //
3506    //----------- variable initialization -------------------------------------------------    TSQLResult *result = 0;
3507      TSQLRow    *row    = 0;
3508    Double_t mip[3]={1, 30, 300};    TSQLResult *result2 = 0;
3509    Double_t adc[3] = {0.,0.,0.};    TSQLRow    *row2   = 0;
3510        //
3511    TArrayD parametri(2);    UInt_t moved = 0;
3512      //
3513    valid = 1;    stringstream oss;
3514      oss.str("");
3515    //------------ Fit calibrations and find parameters to calibrate data ------------------    //
3516    pamela::S4::S4Event  *s4Record;    if ( !strcmp(fcleanfile.Data(),"") ){
3517        //
3518    for (Int_t j = 0; j < 4; j++){      // check if there are entries older than "olderthan" seconds from now
3519      for (Int_t i = 0; i < 128; i++){      //
3520        s4Record = (pamela::S4::S4Event*)S4CalibEvent->Records->At((j*128 + i));      oss.str("");
3521        switch (j) {      oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
3522        case 0 :{          << " INSERT_TIME <= '" << clean_time->AsSQLString() << "';";
3523          adc[0]=adc[0]+((s4Record->S4_DATA)-32);      //
3524          break;      if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS runs older than %s : query is \n %s \n",clean_time->AsSQLString(),oss.str().c_str());
3525        };      result = conn->Query(oss.str().c_str());
3526        case 1 :{      //
3527          adc[1]=adc[1]+((s4Record->S4_DATA)-32);    } else {
3528          break;      oss.str("");
3529        };      oss << " SELECT ID FROM GL_ROOT WHERE NAME='" << fcleanfile.Data() << "';";
3530        case 3 :{      if ( IsDebug() ) printf(" Getting ID_ROOT_L0 query %s \n",oss.str().c_str());
3531          adc[2]=adc[2]+((s4Record->S4_DATA)-32);      result = conn->Query(oss.str().c_str());
3532          break;      //    
3533        if ( result ){
3534          //
3535          row = result->Next();
3536          //
3537          if ( row ){
3538            oss.str("");
3539            oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
3540                << " ID_ROOT_L0=" << row->GetField(0) << ";";
3541            //
3542            if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS for ROOT file query is \n %s \n",oss.str().c_str());
3543            result = conn->Query(oss.str().c_str());
3544            //    
3545        };        };
3546        } else {
3547          return(2);
3548        };
3549      };
3550      //
3551      if ( result ){
3552        //
3553        row = result->Next();
3554        //
3555        while ( row ){
3556          //
3557          oss.str("");
3558          oss << " ID= "<< row->GetField(0);
3559          //
3560          glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);  
3561          //
3562          oss.str("");
3563          oss << " SELECT ID,NEVENTS,TRK_CALIB_USED,PKT_COUNTER FROM GL_RUN WHERE "
3564              << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND ("
3565              << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3566              << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3567              << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3568              << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3569              << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3570              << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3571              << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3572              << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3573              << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3574              << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3575              << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3576              << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3577          //
3578          if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3579          result2 = conn->Query(oss.str().c_str());
3580          //
3581          if ( !result2 ) throw -4;
3582          //
3583          row2 = result2->Next();
3584          //
3585          if ( !row2 ){
3586            //
3587            if ( IsDebug() ) printf(" The run is new \n");
3588            if ( IsDebug() ) printf(" -> fill the DB \n");      
3589            //
3590            //      glrun->SetID(this->AssignRunID()); we use the old run number!
3591            glrun->SetID_RUN_FRAG(glrun->GetID());
3592            glrun->Fill_GL_RUN(conn);  
3593            //
3594    //      oss.str("");
3595    //      oss << " SELECT ID FROM GL_RUN WHERE "
3596    //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
3597    //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
3598    //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
3599    //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
3600    //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
3601    //      //
3602    //      if ( IsDebug() ) printf(" Look for the ID of the inserted run: query is \n %s \n",oss.str().c_str());
3603    //      result2 = conn->Query(oss.str().c_str());
3604    //      //
3605    //      if ( !result2 ) throw -4;
3606    //      //
3607    //      row2 = result2->Next();
3608    //      //
3609    //      if ( !row2 ) throw -25;
3610    //      //
3611    //      oss.str("");
3612    //      oss << " UPDATE GL_RUN SET ID_RUN_FRAG = " << row2->GetField(0) << " WHERE ID = " << row2->GetField(0);
3613    //      if ( IsDebug() ) printf(" Update the ID_RUN_FRAG of the inserted run: query is \n %s \n",oss.str().c_str());
3614    //      result2 = conn->Query(oss.str().c_str());
3615    //      //
3616    //      if ( !result2 ) throw -4;
3617            //
3618            moved++;
3619            //
3620          } else {
3621            if ( IsDebug() ) printf(" The already exist in the GL_RUN table! \n");
3622        };        };
3623          if ( IsDebug() ) printf(" Delete run %s from the GL_RUN_FRAGMENTS table \n",row->GetField(0));      
3624          //
3625          //
3626          glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3627    //      oss.str("");
3628    //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);
3629    //       if ( IsDebug() ) printf(" Clean the GL_RUN_FRAGMENTS table: query is \n %s \n",oss.str().c_str());
3630    //       result2 = conn->Query(oss.str().c_str());
3631    //      //
3632    //      if ( !result2 ) throw -4;
3633    //      //
3634          row = result->Next();
3635      };      };
3636    };    };
3637        if ( IsDebug() ) printf(" Moved %u runs\n",moved);
3638    adc[0]=adc[0]/128;    return(0);
3639    adc[1]=adc[1]/128;  };
   adc[2]=adc[2]/128;  
     
   TGraph *fitpar = new TGraph (3, adc, mip);  
   TF1 *func = new TF1("fitf", fitf, -0., 1000., 2); // definizione della funzione, 2 = num. parametri  
     
   func->SetParameters(0.3,1.);        //inizializzazione dei parametri a 1  
   func->SetParNames("m","q");      //definisce il nome dei parametri  
   fitpar->Fit(func,"qr");          //fitta fitpar con la funzione func nel range definito nella funzione  
   //fitpar->Fit(func,"r");          //fitta fitpar con la funzione func nel range definito nella funzione  
       
   parametri[0] = func -> GetParameter(0);  
   parametri[1] = func -> GetParameter(1);  
   
   if ( parametri[0] < 0. || parametri[0] > 0.5 || parametri[1] < 0.8 || parametri[1] > 1. ) valid = 0;  
3640    
3641    if ( IsDebug() ) printf(" par1 = %g par2 = %g\n",parametri[0],parametri[1]);  /**
3642     * Check if runs are good, i.e. if the tracker calibration is correctly associated..
3643    return parametri;   */
3644    Int_t PamelaDBOperations::ValidateRuns(){
3645      return(this->ValidateRuns(""));
3646    };
3647    
3648    /**
3649     * Check if runs are good, i.e. if the tracker calibration is correctly associated..
3650     */
3651    Int_t PamelaDBOperations::ValidateRuns(TString valfile){
3652      //
3653      TSQLResult *result = 0;
3654      TSQLRow    *row    = 0;
3655      //
3656      UInt_t calibtime = 50;
3657      //
3658      stringstream oss;
3659      oss.str("");
3660      //
3661      // =======================================================
3662      // validate runs by checking missing calibrations
3663      // =======================================================
3664      UInt_t t_stop  = 0;
3665      UInt_t t_start = 0;
3666      if ( !strcmp(valfile.Data(),"") ) {
3667        // --------------------------------------------------------------
3668        // 1) get the OBT of the last run inserted after clean-time limit
3669        // --------------------------------------------------------------
3670        oss.str("");
3671        oss << " SELECT * FROM GL_RUN  WHERE INSERT_TIME <= '" << clean_time->AsSQLString()
3672            << "' ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
3673        if ( IsDebug() ) printf(" Get start validation-time: query is \n %s \n",oss.str().c_str());
3674        result = conn->Query(oss.str().c_str());
3675        if ( !result ) throw -4;
3676        if ( !result->GetRowCount() ) {
3677          printf(" No runs to validate \n");
3678          return(1);
3679        }else{
3680          row = result->Next();
3681          t_start = (UInt_t)atoll(row->GetField(4));
3682        };  
3683        // --------------------------------------------------------------
3684        // 2) get the OBT of the last validated run
3685        // --------------------------------------------------------------
3686        oss.str("");
3687        oss << " SELECT * FROM GL_RUN  WHERE VALIDATION=1 AND RUNHEADER_TIME<="<< t_start
3688            <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
3689        if ( IsDebug() ) printf(" Get stop validation-time: query is \n %s \n",oss.str().c_str());
3690        result = conn->Query(oss.str().c_str());
3691        if ( !result ) throw -4;
3692        if ( result->GetRowCount() ){
3693          row = result->Next();
3694          t_stop = (UInt_t)atoll(row->GetField(4));
3695        };
3696        if ( IsDebug() ) printf("Validation interval: from time %i - to time %i \n\n",t_stop,t_start);
3697        // --------------------------------------------------------------
3698        // now retrieves runs to be validated
3699        // --------------------------------------------------------------
3700        oss.str("");
3701        oss << " SELECT * FROM GL_RUN  WHERE  RUNHEADER_TIME <=" << t_start;
3702        oss << " AND RUNHEADER_TIME >="<< t_stop;
3703        oss << " ORDER BY RUNHEADER_TIME DESC;";
3704        if ( IsDebug() )printf(" Check runs for validation: query is \n %s \n",oss.str().c_str());
3705        result = conn->Query(oss.str().c_str());
3706      } else {
3707        //
3708        stringstream myquery;
3709        UInt_t myid = 0;
3710        myquery.str("");
3711        myquery << " SELECT ID FROM GL_ROOT where NAME='"<<valfile.Data() <<"';";
3712        //
3713        result = conn->Query(myquery.str().c_str());
3714        //
3715        row = result->Next();      
3716        if( !row ){
3717          if ( strcmp(valfile.Data(),GetRootName().Data()) ){
3718            if ( IsDebug() ) printf(" No file to be validated even if option \"-validate file\" was used!!\n");
3719            return(2);
3720          };
3721          if ( IsDebug() ) printf(" No file to be validated (force mode)! \n");
3722          return(0);
3723        };
3724        myid=(UInt_t)atoll(row->GetField(0));
3725        //
3726        myquery.str("");
3727        myquery << " SELECT MAX(RUNTRAILER_TIME),MIN(RUNHEADER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< myid <<";";
3728        //
3729        result = conn->Query(myquery.str().c_str());
3730        //
3731        row = result->Next();      
3732        if( !row->GetField(0) || !row->GetField(1)){
3733          //
3734          if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
3735          //
3736          return(0);
3737          //
3738        } else {  
3739          //
3740          UInt_t runhtime = (UInt_t)atoll(row->GetField(0));
3741          UInt_t runttime = (UInt_t)atoll(row->GetField(1));
3742          UInt_t caltime = 0;
3743          //
3744          myquery.str("");
3745          myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
3746          myquery << " order by FROM_TIME asc limit 1;";
3747          //
3748          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
3749          //
3750          //
3751          result = conn->Query(myquery.str().c_str());
3752          //
3753          row = result->Next();      
3754          if( !row ){
3755            caltime = runhtime;
3756          } else {
3757            caltime = (UInt_t)atoll(row->GetField(0));
3758          };
3759          //
3760          myquery.str("");
3761          myquery << " SELECT * from GL_RUN where RUNHEADER_TIME>="<< runttime <<" AND RUNHEADER_TIME<=" ;
3762          myquery << caltime << " order by RUNHEADER_TIME DESC";
3763          //
3764          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
3765          //
3766          result = conn->Query(myquery.str().c_str());
3767          //
3768        };
3769      };
3770      //
3771      if ( !result ) throw -4;
3772      if ( !result->GetRowCount() && IsDebug() ) printf(" No runs to validate \n");
3773      //
3774      Int_t nrow = 0;
3775      GL_RUN* this_run = new GL_RUN();
3776      GL_RUN* next_run = new GL_RUN();
3777      Int_t   nseq_max = 1000;
3778    //  UInt_t* sequence = new UInt_t[100];
3779      vector<UInt_t> sequence(nseq_max);
3780      Int_t   nseq = 0;
3781      Bool_t CHECK = false;
3782      Bool_t this_ONLINE = false;
3783      Bool_t next_ONLINE = false;
3784      UInt_t t1=0,t2=0;
3785      // ---------------------------------------------------------------------------------
3786      // - loop over runs, back in time,
3787      // - select sequences of runs close in time (less than calibtime s apart),
3788      //   which could be preceeded by a calibration
3789      // - check if there might be a missing calibration
3790      // ---------------------------------------------------------------------------------
3791      while(1){
3792              
3793              row = result->Next();
3794              if( row == NULL ) break;
3795              
3796              //------------
3797              //get run info
3798              //------------
3799              this_run->Set_GL_RUN(row);
3800                      
3801              Bool_t this_BAD = false;
3802              if(this_run->GetTRK_CALIB_USED() == 1 || this_run->GetTRK_CALIB_USED() == 2) this_ONLINE = true;
3803              else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;
3804              else{
3805    //                printf("Missing or corrupted header!! \n");
3806                      this_ONLINE = false;
3807                      this_BAD = true;
3808              };
3809    
3810              //-----------------------------------
3811              //compare with previous(next in time)
3812              //-----------------------------------
3813              CHECK = false;
3814              UInt_t interval=0;
3815              
3816              if( nrow != 0){
3817            
3818                      
3819                      t1 = this_run->GetRUNTRAILER_TIME();
3820                      t2 = next_run->GetRUNHEADER_TIME();
3821                      interval = (t2-t1);
3822                      
3823                      if(this_ONLINE && next_ONLINE){                               // this: ON-LINE + next: ON-LINE
3824                              
3825                              if( this_run->ID == next_run->ID_RUN_FRAG ) interval = 0;     //=> run fragments
3826                              
3827                              if( interval >= calibtime )CHECK = true;                      //more than calibtime s => there might be a calibration
3828                              
3829                              if( !CHECK && this_run->VALIDATION ){
3830                                      for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
3831                                      nseq=0;
3832                              }
3833                      
3834                      }else if( !this_ONLINE && next_ONLINE) {              // this: DEFAULT + next:ON-LINE
3835                              
3836                              CHECK = true;
3837    
3838                      }else if( !next_ONLINE ){                                             // this:ANY + next:DEFAULT
3839                              
3840                              assignVALIDATION(next_run->ID,true);
3841                              nseq=0;
3842                      }
3843              }
3844    
3845              //----------------------------
3846              //check run sequence for calib
3847              //----------------------------
3848              if( CHECK ){
3849                      // check if calibration exists
3850                      if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);
3851                      Bool_t MISSING = MissingTRK_CALIB(t1,t2);
3852                      for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],!MISSING);
3853                      nseq=0;
3854              };
3855              //--------------
3856              //store run info
3857              //--------------
3858              *next_run   = *this_run;
3859              next_ONLINE = this_ONLINE;
3860              if( !this_BAD ){
3861                      if(nseq < nseq_max){
3862                              sequence[nseq] = this_run->ID;
3863                              nseq++;
3864                      }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);
3865              };
3866              
3867              if ( IsDebug() ) printf("%i Run %i \n",nrow,this_run->ID);
3868              nrow++;
3869              
3870      };
3871      delete this_run;
3872      delete next_run;
3873      //
3874      return(0);
3875    };
3876    /**
3877     * Check if there might be a missing tracker calibration in a given time interval
3878     * @param t1 From absolute time
3879     * @param t2 To absolute time
3880     * @return true if there might be a missing calibration
3881     */
3882    Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
3883            
3884            GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();
3885            
3886            // get the closest VALIDATED calibration before the run start (t2)
3887            if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true);      //>>> missing
3888            
3889            if ( trkcalib->TO_TIME  < t2 ) return(true);                                    //>>> missing
3890            
3891            //==============================================================
3892            // Check is done first on the basis of time between calibration,
3893            // which should be equal to the time between ascending-nodes.
3894            //==============================================================
3895            if ( t2 - trkcalib->FROM_TIME > 5700) {
3896                    if ( IsDebug() )printf("Long time between calib and run start %i :-( ==> there might be a missing calib \n",t2 - trkcalib->FROM_TIME);
3897            //==============================================================
3898            // there might be a missing calibration, due to:
3899            // - MM full
3900            // - corrupted packets
3901            // - loss of data
3902            // There is an exception in case a download was done during ascending node
3903            //==============================================================
3904                    Bool_t DOWNLOAD = false;
3905                    // check if the calib was skipped becouse of download .... DA FARE!!
3906                    if(DOWNLOAD)return(false);
3907                    
3908                    return(true);                                   //>>> missing
3909                    
3910            };
3911            
3912            //==============================================================
3913            // If the last calibration is close to the run less than this time,
3914            // it is enough to say that there are no missing calibrations
3915            //==============================================================
3916            // the long time interval bewteen runs might be due to download
3917            if ( IsDebug() )printf("Short time between calib and run start %i :-) ==> OK! \n",t2 - trkcalib->FROM_TIME);
3918            return(false);
3919            
3920    };
3921    /**
3922     * Assign VALIDATION value to a GL_RUN entry
3923     * @param idrun Run ID
3924     * @param validation true/false
3925     */
3926    Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){
3927            TSQLResult *result = 0;
3928            stringstream oss;
3929            oss.str("");
3930            oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";
3931            //
3932    //      if ( IsDebug() )
3933    //      printf(" Set VALIDATION = %i for run %i \n",validation,idrun);
3934            if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());
3935            result = conn->Query(oss.str().c_str());
3936            if ( !result ) throw -4;
3937            return(0);
3938    }
3939    
3940    
3941    
3942    // Insert TLEs from file tlefilename in the table GL_TLE in the db
3943    // opened by conn, sorting them by date from older to newer, if each
3944    // TLE has not been alread inserted.
3945    Int_t PamelaDBOperations::populateTLE()//(TSQLServer *conn, char *tleFile)
3946    {
3947      fstream tlefile(tlefilename, ios::in);
3948    
3949      if ( !tlefile ) throw -7;
3950    
3951      vector<cTle*> ctles;
3952      vector<cTle*>::iterator iter;
3953      int present = 0;
3954    
3955      // Get three lines from tlefile, create a cTle object and put it
3956      // into ctles
3957      while(1) {
3958        cTle *tlef;
3959        string str1, str2, str3;
3960    
3961        getline(tlefile, str1);
3962        if(tlefile.eof()) break;
3963    
3964        getline(tlefile, str2);
3965        if(tlefile.eof()) break;
3966    
3967        getline(tlefile, str3);
3968        if(tlefile.eof()) break;
3969    
3970        // We now have three good lines for a cTle.
3971        tlef = new cTle(str1, str2, str3);
3972        ctles.push_back(tlef);
3973      }
3974    
3975      tlefile.close();
3976    
3977      // Sort by date
3978      sort(ctles.begin(), ctles.end(), compTLE);
3979    
3980      // Now we insert each TLE into the db
3981      for(iter = ctles.begin(); iter != ctles.end(); iter++) {
3982        cTle *tle = *iter;
3983    
3984        // Do nothing if it's already present in the db.  Just increase
3985        // the counter present.
3986        if (! isTlePresent(tle))
3987          {
3988            int status = insertTle(tle);
3989    
3990            // Insert query failed.  Return 1.
3991            if(status == EXIT_FAILURE) {
3992              
3993              if( IsDebug() ) {
3994                cerr << "Error: inserting TLE:" << endl
3995                     << tle->getName() << endl
3996                     << tle->getLine1() << endl
3997                     << tle->getLine2() << endl;
3998              }
3999    
4000              throw -4;
4001              return 1;
4002            }
4003    
4004          }
4005        else
4006          present++;
4007    
4008      }
4009    
4010      int inserted = ctles.size() - present;  // Number of inserted TLE.
4011      if ( IsDebug() )
4012        cout << "\nProcessed TLEs ranging from " << getTleDatetime(ctles[0]) << " to " << getTleDatetime(ctles[ctles.size()-1]) << "." << endl
4013             << inserted << " newly inserted TLEs out of " << ctles.size() << " processed." << endl;
4014    
4015      ctles.clear();
4016    
4017    
4018      // Return 2 if no new TLE has been inserted.  0 otherwise.
4019      if(! inserted ) return 2;
4020      return 0;
4021    }
4022    
4023    
4024    // Insert tle in the table GL_TLE using the connection conn.
4025    Int_t PamelaDBOperations::insertTle(cTle *tle)
4026    {
4027      stringstream oss;
4028      TSQLResult *result = 0;
4029    
4030      oss.str("");
4031      oss << " INSERT INTO GL_TLE (TLE1, TLE2, TLE3, FROM_TIME)"
4032          << " VALUES ( '"
4033          << tle->getName() << "', '"
4034          << tle->getLine1() << "', '"
4035          << tle->getLine2() << "', '"
4036          << getTleDatetime(tle) << "')";
4037    
4038      //  cout << oss.str().c_str() << endl;
4039      result = conn->Query(oss.str().c_str());
4040      if (result == NULL)
4041        return EXIT_FAILURE;
4042    
4043      return EXIT_SUCCESS;
4044    }
4045    
4046    
4047    // Return whether tle is already in the db connected by conn.
4048    bool PamelaDBOperations::isTlePresent(cTle *tle)
4049    {
4050      stringstream oss;
4051      TSQLResult *result = 0;
4052    
4053      oss.str("");
4054      oss << "SELECT * FROM GL_TLE WHERE FROM_TIME = '"
4055          << getTleDatetime(tle) << "'";
4056    
4057      result = conn->Query(oss.str().c_str());
4058      if (result == NULL) throw -4;
4059    
4060      if (result->GetRowCount())
4061        return true;
4062      else
4063        return false;
4064    }
4065    
4066    
4067    // Return whether the first TLE is dated early than the second
4068    bool compTLE (cTle *tle1, cTle *tle2)
4069    {
4070      return getTleJulian(tle1) < getTleJulian(tle2);
4071    }
4072    
4073    
4074    // Return the date of the tle using the format (year-2000)*1e3 +
4075    // julian day.  e.g. 6365 is the 31th Dec 2006.
4076    // It does *not* return a cJulian date.
4077    float getTleJulian(cTle *tle) {
4078      return tle->getField(cTle::FLD_EPOCHYEAR)*1e3 + tle->getField(cTle::FLD_EPOCHDAY);
4079    }
4080    
4081    
4082    // Return a string like YYYY-MM-DD hh:mm:ss, usable for mysql datetime
4083    // format.
4084    string getTleDatetime(cTle *tle)
4085    {
4086      int year, mon, day, hh, mm, ss;
4087      double dom; // day of month (is double!)
4088      stringstream date; // date in datetime format
4089    
4090      // create a cJulian from the date in tle
4091      cJulian jdate = cJulian( 2000 + (int) tle->getField(cTle::FLD_EPOCHYEAR), tle->getField(cTle::FLD_EPOCHDAY));
4092    
4093      // get year, month, day of month
4094      jdate.getComponent(&year, &mon, &dom);
4095    
4096      // build a datetime YYYY-MM-DD hh:mm:ss
4097      date.str("");
4098      day = (int) floor(dom);
4099      hh = (int) floor( (dom - day) * 24);
4100      mm = (int) floor( ((dom - day) * 24 - hh) * 60);
4101      ss = (int) floor( ((((dom - day) * 24 - hh) * 60 - mm) * 60));
4102      //  ms = (int) floor( (((((dom - day) * 24 - hh) * 60 - mm) * 60) - ss) * 1000);
4103    
4104      date << year << "-" << mon << "-" << day << " " << hh << ":" << mm << ":" << ss;
4105    
4106      return date.str();
4107    }
4108    
4109    /**
4110     * Remove a file from the DB, delete on cascade all entries related to that file
4111     * rearrange GL_RUN and GL_XXX_CALIB tables, turn off validation till the following
4112     * calibration
4113     **/
4114    Int_t PamelaDBOperations::removeFile(TString remfile){
4115      //
4116      // Determine ID_ROOT_L0 and ID_RAW
4117      //
4118      TSQLResult *pResult;
4119      TSQLRow *Row;
4120      stringstream myquery;
4121      //  
4122      myquery.str("");
4123      myquery << " SELECT ID, ID_RAW FROM GL_ROOT where NAME='"<<remfile.Data() <<"';";
4124      //
4125      pResult = conn->Query(myquery.str().c_str());
4126      //
4127      Row = pResult->Next();      
4128      if( !Row ){
4129        if ( strcmp(remfile.Data(),GetRootName().Data()) ){
4130          if ( IsDebug() ) printf(" No file to be removed even if option \"-remove file\" was used!!\n");
4131          return(1);
4132        };
4133        if ( IsDebug() ) printf(" No file to be removed (force mode)! \n");
4134        return(0);
4135      };
4136      //
4137      this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));
4138      this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));
4139      //
4140      this->ValidationOFF();
4141      //
4142      this->RemoveCALIBS();
4143      //
4144      this->RemoveRUNS();
4145      //
4146      this->RemoveFILES();
4147      //
4148      this->SetID_ROOT(0);
4149      this->SetID_RAW(0);
4150      //
4151      return(0);
4152    };
4153    
4154    /**
4155     *
4156     * Set validation bit to zero for runs following the removing file till
4157     * 1) a run with TRK_CALIB_USED=140
4158     * 2) a run with VALIDATION = 0
4159     * 3) the next calibration
4160     *
4161     **/
4162    void PamelaDBOperations::ValidationOFF(){
4163      TSQLResult *pResult;
4164      TSQLRow *Row;
4165      stringstream myquery;
4166      Int_t unv = 0;
4167      //select ID from GL_RUN where RUNHEADER_TIME>=1152671382 AND (VALIDATION=0 OR TRK_CALIB_USED=104) order by RUNHEADER_TIME asc limit 1;
4168      myquery.str("");
4169      myquery << " SELECT MAX(RUNTRAILER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
4170      //
4171      pResult = conn->Query(myquery.str().c_str());
4172      //
4173      Row = pResult->Next();      
4174      if( !Row->GetField(0) ){
4175        //
4176        if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
4177        //
4178      } else {  
4179        //
4180        UInt_t runhtime = (UInt_t)atoll(Row->GetField(0));
4181        UInt_t caltime = 0;
4182        //
4183        myquery.str("");
4184        myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
4185        myquery << " order by FROM_TIME asc limit 1;";
4186        //
4187        if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4188        //
4189        //
4190        delete pResult;
4191        pResult = conn->Query(myquery.str().c_str());
4192        //
4193        Row = pResult->Next();      
4194        if( !Row ){
4195          caltime = runhtime;
4196        } else {
4197          caltime = (UInt_t)atoll(Row->GetField(0));
4198        };
4199        //
4200        myquery.str("");
4201        myquery << " SELECT ID,RUNHEADER_TIME from GL_RUN where RUNHEADER_TIME>="<< runhtime <<" AND (VALIDATION=0 OR TRK_CALIB_USED=104 OR RUNHEADER_TIME>" ;
4202        myquery << caltime << ") order by RUNHEADER_TIME asc LIMIT 1";
4203        //
4204        if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4205        //
4206        pResult = conn->Query(myquery.str().c_str());
4207        //
4208        Row = pResult->Next();      
4209        if( !Row ){
4210          //
4211          if ( IsDebug() ) printf(" NO RUN NEED TO BE UNVALIDATED \n");
4212          //
4213        } else {
4214          myquery.str("");
4215          myquery << " SELECT ID from GL_RUN where RUNHEADER_TIME<"<< Row->GetField(1) <<" AND ";
4216          myquery << " RUNHEADER_TIME>=" <<runhtime;
4217          myquery << " order by RUNHEADER_TIME asc;";
4218          //
4219          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4220          //
4221          pResult = conn->Query(myquery.str().c_str());
4222          //
4223          Row = pResult->Next();  
4224          while ( Row ){
4225            //      
4226            unv++;
4227            this->assignVALIDATION((UInt_t)atoll(Row->GetField(0)), false);
4228            Row = pResult->Next();  
4229            //
4230          };
4231        };
4232      };
4233      if ( IsDebug() ) printf(" %i runs have been unvalidated \n",unv);
4234    };
4235    
4236    /**
4237     *
4238     * Rearrange GL_RUN table and remove runs
4239     *
4240     **/
4241    void PamelaDBOperations::RemoveRUNS(){
4242      TSQLResult *pResult;
4243      TSQLRow *Row;
4244      stringstream myquery;
4245      UInt_t drun = 0;
4246      GL_RUN *delrun = new GL_RUN();
4247      //
4248      myquery.str("");
4249      myquery << " SELECT ID FROM GL_RUN where ID_RUN_FRAG=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4250      //
4251      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4252      //
4253      pResult = conn->Query(myquery.str().c_str());
4254      //
4255      Row = pResult->Next();    
4256      //
4257      //
4258      if ( !Row ){
4259        if ( IsDebug() ) printf(" No run with ID_RUN_FRAG=0 belonged to this file \n");
4260      } else {
4261        if ( IsDebug() ) printf(" Deleting run from GL_RUN table \n");    
4262        while ( Row ){
4263          delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
4264          if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(0)));
4265          drun++;
4266          Row = pResult->Next();    
4267        };
4268      };
4269      //
4270      //
4271      myquery.str("");
4272      myquery << " SELECT ID,ID_RUN_FRAG FROM GL_RUN where ID_RUN_FRAG!=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4273      //
4274      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4275      //
4276      pResult = conn->Query(myquery.str().c_str());
4277      //
4278      Row = pResult->Next();    
4279      //
4280      if ( !Row ){
4281        if ( IsDebug() ) printf(" No run with ID_RUN_FRAG!=0 belonged to this file \n");
4282      } else {
4283        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN table \n");    
4284        while ( Row ){
4285          if ( IsDebug() ) printf(" restore run %i \n",(UInt_t)atoll(Row->GetField(1)));
4286          delrun->RestoreRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN_FRAGMENTS");
4287          if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(1)));
4288          delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN");
4289          if ( (UInt_t)atoll(Row->GetField(1)) != (UInt_t)atoll(Row->GetField(0)) ){
4290            if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(0)));
4291            delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
4292          };
4293          drun++;
4294          Row = pResult->Next();    
4295        };
4296      };
4297      //
4298      if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN table \n",drun);    
4299      //
4300      //
4301      //
4302      drun = 0;
4303      //
4304      myquery.str("");
4305      myquery << " SELECT ID_TRASH FROM GL_RUN_TRASH where BELONGED_TO='GL_RUN_FRAGMENTS' AND ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4306      //
4307      pResult = conn->Query(myquery.str().c_str());
4308      //
4309      Row = pResult->Next();    
4310      //
4311      if ( !Row ){
4312        if ( IsDebug() ) printf(" No run from GL_RUN_FRAGMENTS table in the trash table for this file \n");
4313      } else {
4314        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_TRASH table \n");    
4315        while ( Row ){
4316          if ( IsDebug() ) printf(" del run idtrash %i \n",(UInt_t)atoll(Row->GetField(0)));
4317          myquery.str("");
4318          myquery << " DELETE FROM GL_RUN_TRASH where ID_TRASH=" << Row->GetField(0) <<";";      
4319          conn->Query(myquery.str().c_str());
4320          drun++;
4321          Row = pResult->Next();    
4322        };
4323      };
4324      //  
4325      if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN_TRASH table \n",drun);    
4326      //
4327      //
4328      //
4329      drun = 0;
4330      //
4331      myquery.str("");
4332      myquery << " SELECT ID FROM GL_RUN_FRAGMENTS where ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4333      //
4334      pResult = conn->Query(myquery.str().c_str());
4335      //
4336      Row = pResult->Next();    
4337      //
4338      if ( !Row ){
4339        if ( IsDebug() ) printf(" No run in the GL_RUN_FRAGMENTS table for this file \n");
4340      } else {
4341        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_FRAGMENTS table \n");    
4342        while ( Row ){
4343          if ( IsDebug() ) printf(" del run %i \n",(UInt_t)atoll(Row->GetField(0)));
4344          myquery.str("");
4345          myquery << " DELETE FROM GL_RUN_FRAGMENTS where ID=" << Row->GetField(0) <<";";
4346          conn->Query(myquery.str().c_str());
4347          drun++;
4348          Row = pResult->Next();    
4349        };
4350      };
4351      //  
4352      if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN_FRAGMENTS table \n",drun);    
4353      //
4354      //
4355      //
4356      delete delrun;
4357      //
4358    };
4359    
4360    
4361    /**
4362     *
4363     * Rearrange calibration tables
4364     *
4365     **/
4366    void PamelaDBOperations::RemoveFILES(){
4367      stringstream myquery;
4368      //
4369      myquery.str("");
4370      myquery << " DELETE FROM GL_RAW WHERE ID=" <<this->GetID_RAW() <<";";
4371      //
4372      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4373      //
4374      conn->Query(myquery.str().c_str());
4375      //
4376    };
4377    
4378    /**
4379     *
4380     * Rearrange calibration tables
4381     *
4382     **/
4383    void PamelaDBOperations::RemoveCALIBS(){
4384      TSQLResult *pResult;
4385      TSQLRow *Row;
4386      stringstream myquery;
4387      //  
4388      //
4389      // Calorimeter
4390      //
4391      for (Int_t section = 0; section < 4; section++){
4392        myquery.str("");
4393        myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_CALO_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<" AND ";
4394        myquery << " SECTION=" << section << ";";
4395        //
4396        pResult = conn->Query(myquery.str().c_str());
4397        //
4398        Row = pResult->Next();      
4399        if( !Row->GetField(0) || !Row->GetField(1) ){
4400          //
4401          if ( IsDebug() ) printf(" NO CALO CALIBRATION SECTION %i ASSOCIATED TO THIS FILE! \n",section);
4402          //
4403        } else {
4404          //
4405          myquery.str("");
4406          myquery << " UPDATE GL_CALO_CALIB SET TO_TIME=" << Row->GetField(1);
4407          myquery << " WHERE TO_TIME="<< Row->GetField(0) << " AND ";
4408          myquery << " SECTION=" << section << ";";
4409          //
4410          pResult = conn->Query(myquery.str().c_str());
4411          //
4412          if( !pResult ){
4413            //
4414            if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
4415            //
4416            throw -4;
4417            //
4418          };
4419          //
4420        };
4421      };
4422      myquery.str("");
4423      myquery << " DELETE FROM GL_CALO_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4424      //
4425      pResult = conn->Query(myquery.str().c_str());
4426      //
4427      if( !pResult ){
4428        //
4429        if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
4430        //
4431        throw -4;
4432        //
4433      };
4434      //
4435      // Tracker
4436      //
4437      myquery.str("");
4438      myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_TRK_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
4439      //
4440      pResult = conn->Query(myquery.str().c_str());
4441      //
4442      Row = pResult->Next();      
4443      if( !Row->GetField(0) || !Row->GetField(1) ){
4444        //
4445        if ( IsDebug() ) printf(" NO TRK CALIBRATION ASSOCIATED TO THIS FILE! \n");
4446        //
4447      } else {
4448        //
4449        myquery.str("");
4450        myquery << " UPDATE GL_TRK_CALIB SET TO_TIME=" << Row->GetField(1);
4451        myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
4452        //
4453        pResult = conn->Query(myquery.str().c_str());
4454        //
4455        if( !pResult ){
4456          //
4457          if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
4458          //
4459          throw -4;
4460          //
4461        };
4462        //
4463        myquery.str("");
4464        myquery << " DELETE FROM GL_TRK_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4465        //
4466        pResult = conn->Query(myquery.str().c_str());
4467        //
4468        if( !pResult ){
4469          //
4470          if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
4471          //
4472          throw -4;
4473          //
4474        };
4475      };
4476      //
4477      //
4478      // S4
4479      //
4480      myquery.str("");
4481      myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_S4_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
4482      //
4483      pResult = conn->Query(myquery.str().c_str());
4484      //
4485      Row = pResult->Next();      
4486      if( !Row->GetField(0) || !Row->GetField(1) ){
4487        //
4488        if ( IsDebug() ) printf(" NO S4 CALIBRATION ASSOCIATED TO THIS FILE! \n");
4489        //
4490      } else {
4491        //
4492        myquery.str("");
4493        myquery << " UPDATE GL_S4_CALIB SET TO_TIME=" << Row->GetField(1);
4494        myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
4495        //
4496        pResult = conn->Query(myquery.str().c_str());
4497        //
4498        if( !pResult ){
4499          //
4500          if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
4501          //
4502          throw -4;
4503          //
4504        };
4505        //
4506        myquery.str("");
4507        myquery << " DELETE FROM GL_S4_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4508        //
4509        pResult = conn->Query(myquery.str().c_str());
4510        //
4511        if( !pResult ){
4512          //
4513          if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
4514          //
4515          throw -4;
4516          //
4517        };
4518        //
4519      };
4520    };
4521    
4522    /**
4523     *
4524     * Rearrange calibration tables
4525     *
4526     **/
4527    UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh ){
4528    
4529        Int_t vorder[]={5,5,3,3,4,4,2,2,1,1,0,0};
4530        UInt_t timeaftercalib=120000; //2000;
4531    //  ----------
4532    //  Check CRCs
4533    //  ----------
4534        for(Int_t ipkt=0; ipkt<6; ipkt++){
4535            if( caltrk->crc_hcal[ipkt] )return 0; // :-(
4536            for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] )return 0; // :-(
4537        }
4538    //  -----------------------
4539    //  Check missing packets:
4540    //  -----------------------
4541    //    Readout order:
4542    //    ------------------
4543    //    DSP   packet board
4544    //    ------------------
4545    //    12    0      1
4546    //    10    1      1
4547    //     8    2      1
4548    //     4    3      1
4549    //     6    4      1
4550    //     2    5      1
4551    //    ------------------
4552    //    11    0      2
4553    //     9    1      2
4554    //     7    2      2
4555    //     3    3      2
4556    //     5    4      2
4557    //     1    5      2
4558    //    ------------------
4559    //  -------------------------------------------------
4560    //  Check if it is first or second calibration packet
4561    //  -------------------------------------------------
4562        UInt_t build=0;
4563        TString classname = caltrk->GetName();
4564        UInt_t base=0;
4565        UInt_t mask=0;
4566        if(classname.Contains("CalibTrk1Event")){
4567            base=12;
4568            mask=0x03F000;
4569        }
4570        if(classname.Contains("CalibTrk2Event")){
4571            base=18;
4572            mask=0xFC0000;
4573        }
4574    //  -------------------------------------------------
4575    //  Count number of packets and set build variable
4576    //  -------------------------------------------------
4577        Int_t  npkts=0;
4578        for(Int_t ipkt=0; ipkt<6; ipkt++){
4579            if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
4580                npkts++;
4581                build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );
4582            }
4583        }
4584    //    if( npkts==6 )return 1; // :-)
4585    
4586    //    cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime()<<endl;
4587    
4588    //  -----------------------------------------------
4589    //  If missing packets: check the acq configuration
4590    //  (some DSPs might be excluded from acquisition)
4591    //  -----------------------------------------------
4592    
4593    //  -----------------------------------------------
4594    //  retrieve the first run header after calib
4595    //  -----------------------------------------------
4596         PacketType *pctp;
4597         EventCounter *cod;
4598         cod = eh->GetCounter();
4599         Int_t irun = cod->Get(pctp->RunHeader);
4600         TTree *rh=(TTree*)file->Get("RunHeader");
4601         if ( !rh || rh->IsZombie() ) throw -17;
4602         if( rh->GetEntries() == irun ){
4603              if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (1)  -- cannot validate :-( "<<endl;
4604             return 0; // :-(
4605         }
4606    
4607         RunHeaderEvent *run  = 0;
4608         EventHeader    *hrun = 0;
4609         rh->SetBranchAddress("RunHeader", &run);
4610         rh->SetBranchAddress("Header", &hrun);
4611         rh->GetEntry(irun);
4612    //     cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime() << " Run " << hrun->GetPscuHeader()->GetOrbitalTime() <<endl;
4613    
4614         if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){
4615              if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (2) -- cannot validate :-( "<<endl;
4616             return 0; // :-(
4617         }
4618        
4619         if( !run->RM_ACQ_AFTER_CALIB ){
4620              if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) RM_ACQ_AFTER_CALIB=0    -- cannot validate :-( "<<endl;
4621             return 0; // :-(
4622         }
4623    
4624         UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());
4625         if( dtime > timeaftercalib ){
4626             if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;
4627             return 0; // :-(
4628         }
4629        
4630    
4631    
4632         if( (run->ACQ_BUILD_INFO & mask) != build ){
4633             if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) ACQ_BUILD_INFO= >>> "<<hex << (run->ACQ_BUILD_INFO&mask) << " != "<< build << dec<<endl;
4634             return 0; // :-(
4635         }
4636         return 1; // :-)
4637    
4638    }
4639    
4640    /**
4641     *
4642     * Check the DB (only for overlapping runs at the moment)
4643     *
4644     **/
4645    UInt_t PamelaDBOperations::Check(){
4646      //
4647      UInt_t test = 0;
4648      //
4649      UInt_t thisrht = 0;
4650      UInt_t thisrtt = 0;
4651      UInt_t thisid = 0;
4652      UInt_t prevrht = 0;
4653      UInt_t prevrtt = 0;
4654      UInt_t previd = 0;
4655      //
4656      UInt_t prevl0id = 0;
4657      UInt_t thisl0id = 0;
4658      //
4659      stringstream oss;
4660      TSQLResult *result = 0;
4661      TSQLRow    *row    = 0;
4662      TSQLResult *result2 = 0;
4663      TSQLRow    *row2    = 0;
4664      oss.str("");
4665      oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN order by RUNHEADER_TIME asc;";
4666      //  oss << "SELECT ID,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN where ID>10170 and ID<10190 order by RUNHEADER_TIME asc;";
4667      result = conn->Query(oss.str().c_str());
4668      //
4669      if ( !result ) throw -4;;
4670      //
4671      row = result->Next();
4672      //
4673      while ( row ){
4674        thisid = (UInt_t)atoll(row->GetField(0));
4675        thisl0id = (UInt_t)atoll(row->GetField(1));
4676        thisrht = (UInt_t)atoll(row->GetField(2));
4677        thisrtt = (UInt_t)atoll(row->GetField(3));
4678        //
4679        //    if ( thisrht < prevrtt || thisrtt < prevrht || thisrht > thisrtt && !(!prevrht && !prevrtt &&!previd) ){
4680        //    if ( (thisrht < prevrtt || thisrtt < prevrht || thisrht > thisrtt) && (thisrht != prevrht) ){
4681        if ( (thisrht < prevrtt) && (thisrht != prevrht) ){
4682          if ( IsDebug() ) printf(" IDprev %u ID %u    prevrht %u prevrtt %u  thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
4683          printf(" CHECK n.1 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrht-prevrtt),previd,thisid);
4684          TString prevf = "";
4685          TString thisf = "";
4686          oss.str("");
4687          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
4688          result2 = conn->Query(oss.str().c_str());
4689          if ( !result2 ) throw -4;;
4690          row2 = result2->Next();
4691          prevf = (TString)row2->GetField(0);
4692          oss.str("");
4693          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
4694          result2 = conn->Query(oss.str().c_str());
4695          if ( !result2 ) throw -4;;
4696          row2 = result2->Next();
4697          thisf = (TString)row2->GetField(0);
4698          if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
4699          test = 1;
4700        };
4701        //
4702        if ( (thisrtt < prevrht) && (thisrht != prevrht) ){
4703          if ( IsDebug() ) printf(" IDprev %u ID %u    prevrht %u prevrtt %u  thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
4704          printf(" CHECK n.2 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrtt-prevrht),previd,thisid);
4705          TString prevf = "";
4706          TString thisf = "";
4707          oss.str("");
4708          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
4709          result2 = conn->Query(oss.str().c_str());
4710          if ( !result2 ) throw -4;;
4711          row2 = result2->Next();
4712          prevf = (TString)row2->GetField(0);
4713          oss.str("");
4714          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
4715          result2 = conn->Query(oss.str().c_str());
4716          if ( !result2 ) throw -4;;
4717          row2 = result2->Next();
4718          thisf = (TString)row2->GetField(0);
4719          if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
4720          test = 1;
4721        };
4722        //
4723        if ( (thisrht > thisrtt) && (thisrht != prevrht) ){
4724          if ( IsDebug() ) printf(" IDprev %u ID %u    prevrht %u prevrtt %u  thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
4725          printf(" CHECK n.3 TIME SCREW of %i s AROUND RUNs %u and %u \n",(thisrht-thisrtt),previd,thisid);
4726          TString prevf = "";
4727          TString thisf = "";
4728          oss.str("");
4729          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
4730          result2 = conn->Query(oss.str().c_str());
4731          if ( !result2 ) throw -4;;
4732          row2 = result2->Next();
4733          prevf = (TString)row2->GetField(0);
4734          oss.str("");
4735          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
4736          result2 = conn->Query(oss.str().c_str());
4737          if ( !result2 ) throw -4;;
4738          row2 = result2->Next();
4739          thisf = (TString)row2->GetField(0);
4740          if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
4741          test = 1;
4742        };
4743    
4744        //
4745        prevrht = thisrht;
4746        prevrtt = thisrtt;
4747        previd = thisid;
4748        prevl0id = thisl0id;
4749        row = result->Next();
4750      };
4751      //
4752      return(test);
4753      //
4754  };  };

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

  ViewVC Help
Powered by ViewVC 1.1.23