/[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.35 by mocchiut, Mon Apr 30 09:16:49 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 %u pkt_num %u \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(32);
408    //    //
409    if ( !nevent ) return(2);    if ( !nevent ) return(64);
410    //    //
411    if ( nevent < 2 ) return(4);    if ( nevent < 2 ) return(128);
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 %u 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 633  Int_t PamelaDBOperations::insertPamelaGL Line 1035  Int_t PamelaDBOperations::insertPamelaGL
1035    TSQLResult *result = 0;    TSQLResult *result = 0;
1036    TSQLRow *row = 0;    TSQLRow *row = 0;
1037    UInt_t t0 = 0;    UInt_t t0 = 0;
1038      Int_t signal = 0;
1039      //
1040      signal = this->SetUpperLimits();
1041    //    //
1042    stringstream   oss;    stringstream   oss;
1043    //      //  
1044    if ( this->GetID_RAW() == 0 )  throw -11;    if ( this->GetID_RAW() == 0 )  throw -11;
1045    //    //
1046    oss.str("");    oss.str("");
1047    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='"
1048        << id << " AND TO_ID_RAW >= "        << this->GetRawFile().Data() << "';";
       << id << ";";  
1049    if ( IsDebug() ) printf(" %s \n",oss.str().c_str());    if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
1050    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1051    if ( !result ) throw -10;    if ( !result ) throw -10;
1052    row = result->Next();    row = result->Next();
   if ( !row ) throw -10;  
1053    //    //
1054    t0 = (UInt_t)TDatime(row->GetField(0)).Convert();    if ( !row ){
1055        oss.str("");
1056        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< "
1057            << dworbit << " order by FROM_ORBIT desc limit 1;";
1058        if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
1059        result = conn->Query(oss.str().c_str());
1060        if ( !result ) throw -10;
1061        row = result->Next();
1062        if ( !row ) throw -10;
1063      };
1064      //
1065      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);
1066      t0 = (UInt_t)tu.GetSec();
1067      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));
1068      //
1069    /*    /*
1070     * Verify that the TIMESYNC have been not already processed     * Verify that the TIMESYNC have been not already processed
1071     */     */
# Line 663  Int_t PamelaDBOperations::insertPamelaGL Line 1080  Int_t PamelaDBOperations::insertPamelaGL
1080    if (result == NULL) throw -10;    if (result == NULL) throw -10;
1081    row = result->Next();    row = result->Next();
1082    if ((row != NULL) && ((UInt_t)atoll(row->GetField(0)) > 0)){    if ((row != NULL) && ((UInt_t)atoll(row->GetField(0)) > 0)){
1083        if ( IsDebug() ) printf(" found a timesync t0 is %u \n",t0);
1084      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;
1085        //
1086        tsync = (UInt_t)atoll(row->GetField(2));
1087        obt0 = (UInt_t)atoll(row->GetField(1));
1088        //
1089      return(1);      return(1);
1090    };    };
1091    //    //
# Line 719  Int_t PamelaDBOperations::insertPamelaGL Line 1141  Int_t PamelaDBOperations::insertPamelaGL
1141          //          //
1142          TYPE = 55;//224;          TYPE = 55;//224;
1143          //          //
1144            if ( IsDebug() ) printf("mcmd tsync %i tsync %u obt %u \n",i,TSYNC,OBT);
1145            //
1146          if ( TSYNC && OBT ){          if ( TSYNC && OBT ){
1147            existsts = true;            existsts = true;
1148            goto out;            goto eout;
1149          };          };
1150          //          //
1151        };        };
# Line 729  Int_t PamelaDBOperations::insertPamelaGL Line 1153  Int_t PamelaDBOperations::insertPamelaGL
1153    };    };
1154    if ( !existsts ) { // try with runheader and runtrailer    if ( !existsts ) { // try with runheader and runtrailer
1155      //      //
1156        if ( IsDebug() ) printf(" No ts mcmd \n");
1157        signal = 2;
1158        //
1159      TTree *rh=(TTree*)file->Get("RunHeader");      TTree *rh=(TTree*)file->Get("RunHeader");
1160      if ( !rh || rh->IsZombie() ) throw -17;      if ( !rh || rh->IsZombie() ) throw -17;
1161      TTree *rt=(TTree*)file->Get("RunTrailer");      TTree *rt=(TTree*)file->Get("RunTrailer");
# Line 738  Int_t PamelaDBOperations::insertPamelaGL Line 1165  Int_t PamelaDBOperations::insertPamelaGL
1165      //      //
1166      rt->SetBranchAddress("RunTrailer", &runt);      rt->SetBranchAddress("RunTrailer", &runt);
1167      //      //
1168      //    Int_t rhev = rh->GetEntries();      Int_t nrhev = rh->GetEntries();
1169      //    Int_t rtev = rt->GetEntries();      Int_t nrtev = rt->GetEntries();
1170        if ( IsDebug() ) printf(" ou nevent %i rhev %i rtev %i \n",nevent,nrhev,nrtev);
1171      //      //
1172      if ( rhev > 0 ){      if ( nrhev > 0 ){
1173        rh->GetEntry(0);        for (Int_t i=0; i<nrhev; i++){
1174        //          //
1175        TSYNC = runh->LAST_TIME_SYNC_INFO;          rh->GetEntry(i);
1176        OBT = runh->OBT_TIME_SYNC * 1000;          //
1177        //          TSYNC = runh->LAST_TIME_SYNC_INFO;
1178        TYPE = 20;          OBT = runh->OBT_TIME_SYNC * 1000;
1179        //          //
1180        if ( TSYNC && OBT ){          TYPE = 20;
1181          existsts = true;          //
1182          goto out;          if ( IsDebug() ) printf("runheader %i tsync %u obt %u \n",i,TSYNC,OBT);
1183            //
1184            if ( TSYNC && OBT ){
1185              existsts = true;
1186              goto eout;
1187            };
1188        };        };
1189        //        //
1190      };      };
1191      if ( rtev > 0 ){      if ( nrtev > 0 ){
       rt->GetEntry(0);  
1192        //        //
1193        TSYNC = runt->LAST_TYME_SYNC_INFO;        if ( IsDebug() ) printf(" No runheader \n");
1194        OBT = runt->OBT_TYME_SYNC * 1000;        signal = 6;
1195        //        //
1196        TYPE = 21;        for (Int_t i=0; i<nrtev; i++){
1197        //          //
1198        if ( TSYNC && OBT ){          rt->GetEntry(i);
1199          existsts = true;          //
1200          goto out;          TSYNC = runt->LAST_TYME_SYNC_INFO;
1201            OBT = runt->OBT_TYME_SYNC * 1000;
1202            //
1203            TYPE = 21;
1204            //
1205            if ( IsDebug() ) printf("runtrailer %i tsync %u obt %u \n",i,TSYNC,OBT);
1206            //
1207            if ( TSYNC && OBT ){
1208              existsts = true;
1209              goto eout;
1210            };
1211        };        };
1212        //        //
1213        } else {
1214          if ( IsDebug() ) printf(" No runheader \n");
1215      };      };
1216    };    };
1217    //    //
1218    if ( !existsts ){ // try with inclination mcmd    if ( !existsts ){ // try with inclination mcmd
1219        //
1220        if ( IsDebug() ) printf(" No runtrailer \n");
1221        signal = 14;
1222        //
1223      Double_t timesync = 0.;      Double_t timesync = 0.;
1224      for (UInt_t i=0; i<nevent;i++){      for (UInt_t i=0; i<nevent;i++){
1225        //        //
# Line 800  Int_t PamelaDBOperations::insertPamelaGL Line 1248  Int_t PamelaDBOperations::insertPamelaGL
1248        TYPE = 666;        TYPE = 666;
1249        if ( TSYNC && OBT ){        if ( TSYNC && OBT ){
1250          existsts = true;          existsts = true;
1251          goto out;          goto eout;
1252        };        };
1253      };      };
1254    };    };
1255    //    //
1256    if ( !existsts && obt0 ){ // insert timesync by hand    if ( !existsts && obt0 ){ // insert timesync by hand
1257        //
1258        if ( IsDebug() ) printf(" No incl mcmd \n");
1259        signal = 30;
1260        //
1261      OBT = obt0;      OBT = obt0;
1262      TSYNC = tsync;      TSYNC = tsync;
1263      TYPE = 999;      TYPE = 999;
1264      existsts = true;      existsts = true;
1265      goto out;      goto eout;
1266    };    };
1267    //    //
1268   out:   eout:
1269    //    //
1270    if ( !existsts ) throw -3;    if ( !existsts ) throw -3;
1271    //    //
# Line 826  Int_t PamelaDBOperations::insertPamelaGL Line 1278  Int_t PamelaDBOperations::insertPamelaGL
1278    conn->Query(oss.str().c_str());    conn->Query(oss.str().c_str());
1279    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());
1280    //    //
1281      if ( IsDebug() ) printf(" found a timesync t0 is %u \n",t0);
1282    toffset = (UInt_t)TSYNC - (UInt_t)(this->OBT(OBT)/1000) + t0;    toffset = (UInt_t)TSYNC - (UInt_t)(this->OBT(OBT)/1000) + t0;
1283    //    //
1284      tsync = TSYNC;
1285      obt0 = OBT;
1286      //
1287    delete result;    delete result;
1288    return(0);    return(signal);
1289  }  }
1290    
1291  /**  /**
# Line 843  Int_t PamelaDBOperations::insertPamelaRo Line 1299  Int_t PamelaDBOperations::insertPamelaRo
1299    UInt_t idtimesync = 0;    UInt_t idtimesync = 0;
1300    //    //
1301    oss.str("");    oss.str("");
1302    oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "    if ( STATIC ){
1303        << " LEFT JOIN GL_ROOT "      oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1304        << " ON GL_RAW.ID = GL_ROOT.ID_RAW "          << " LEFT JOIN GL_ROOT "
1305        << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "          << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1306        << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";          << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "
1307            << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1308      } else {
1309        oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1310            << " LEFT JOIN GL_ROOT "
1311            << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1312            << " WHERE GL_RAW.PATH = '$PAM_RAW' AND "
1313            << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1314      };
1315    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1316    //    //
1317    if ( !result ) throw -12;    if ( !result ) throw -12;
# Line 874  Int_t PamelaDBOperations::insertPamelaRo Line 1338  Int_t PamelaDBOperations::insertPamelaRo
1338    idtimesync = (UInt_t)atoll(row->GetField(0));    idtimesync = (UInt_t)atoll(row->GetField(0));
1339    //    //
1340    oss.str("");    oss.str("");
1341    oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"    if ( STATIC ){
1342        << this->GetID_RAW() << "', '" << idtimesync << "', '" << this->GetRootPath().Data() << "', '" << this->GetRootFile().Data() << "')";      oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
1343            << this->GetID_RAW() << "', '" << idtimesync << "', '" << this->GetRootPath().Data() << "', '" << this->GetRootFile().Data() << "')";
1344      } else {
1345        oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
1346            << this->GetID_RAW() << "', '" << idtimesync << "', '$PAM_L0', '" << this->GetRootFile().Data() << "')";
1347      };
1348    //    //
1349    if (conn->Query(oss.str().c_str()) == 0) throw -4;    if (conn->Query(oss.str().c_str()) == 0) throw -4;
1350    //    //
# Line 902  Int_t PamelaDBOperations::assignBOOT_NUM Line 1371  Int_t PamelaDBOperations::assignBOOT_NUM
1371    TSQLResult *result = 0;    TSQLResult *result = 0;
1372    TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
1373    oss.str("");    oss.str("");
1374    oss << "SELECT ID, BOOT_NUMBER FROM GL_RAW WHERE "    if ( STATIC ){
1375        << " PATH = '" << this->GetRawPath().Data() << "' AND "      oss << "SELECT ID, BOOT_NUMBER FROM GL_RAW WHERE "
1376        << " NAME = '" << this->GetRawFile().Data() << "' ";          << " PATH = '" << this->GetRawPath().Data() << "' AND "
1377            << " NAME = '" << this->GetRawFile().Data() << "' ";
1378      } else {
1379        oss << "SELECT ID, BOOT_NUMBER FROM GL_RAW WHERE "
1380            << " PATH = '$PAM_RAW' AND "
1381            << " NAME = '" << this->GetRawFile().Data() << "' ";
1382      };
1383    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1384    //    //
1385    if ( !result ) return(8);    if ( !result ) throw -4;;
1386    row = result->Next();    row = result->Next();
1387    if ( !row ) return(16);    if ( !row ) return(16);
1388    if ( row->GetField(1) ){    if ( row->GetField(1) ){
1389      this->SetBOOTnumber((UInt_t)atoll(row->GetField(1)));      this->SetBOOTnumber((UInt_t)atoll(row->GetField(1)));
1390      return(1);      return(1);
1391    };    };
1392    if ( !row->GetField(0) ) return(8);    if ( !row->GetField(0) ) throw -26;
1393    //    //
1394    UInt_t idRaw = (UInt_t)atoll(row->GetField(0));    UInt_t idRaw = (UInt_t)atoll(row->GetField(0));
1395    //    //
# Line 924  Int_t PamelaDBOperations::assignBOOT_NUM Line 1399  Int_t PamelaDBOperations::assignBOOT_NUM
1399    trDumpEv = (TTree*)file->Get("VarDump");    trDumpEv = (TTree*)file->Get("VarDump");
1400    if ( !trDumpEv || trDumpEv->IsZombie() ) throw -20;    if ( !trDumpEv || trDumpEv->IsZombie() ) throw -20;
1401    //    //
   if (trDumpEv == NULL) return(2);  
   //      
1402    VarDumpEvent  *vde = 0;    VarDumpEvent  *vde = 0;
1403    VarDumpRecord *vdr = 0;    VarDumpRecord *vdr = 0;
1404    //    //
1405      Bool_t found = false;
1406    trDumpEv->SetBranchAddress("VarDump", &vde);    trDumpEv->SetBranchAddress("VarDump", &vde);
1407    if (trDumpEv->GetEntries() > 0){    if ( trDumpEv->GetEntries() > 0 ){
1408      trDumpEv->GetEntry(0);      found = false;
1409      vde->Records->GetEntries();      for ( Int_t i = 0; i < trDumpEv->GetEntries(); i++){
1410      if ( !vde->Records->GetEntries() ){        trDumpEv->GetEntry(i);
1411        if ( !this->GetBOOTnumber() ) return(4);        //      vde->Records->GetEntries();
1412      } else {        if ( vde->Records->GetEntries()>5 ){
1413            found = true;
1414            goto fill;
1415          };
1416        };
1417      fill:
1418        if ( found ){
1419          //
1420        vdr = (VarDumpRecord*)vde->Records->At(6);        vdr = (VarDumpRecord*)vde->Records->At(6);
1421          //
1422        this->SetBOOTnumber((Int_t)vdr->VAR_VALUE);        this->SetBOOTnumber((Int_t)vdr->VAR_VALUE);
1423          //
1424        } else {
1425          if ( !this->GetBOOTnumber() && !this->AutoBoot()) return(4);
1426      };      };
1427    } else {    } else {
1428      if ( !this->GetBOOTnumber() ) return(2);      if ( !this->GetBOOTnumber() && !this->AutoBoot()) return(2);
1429    };    };
1430    //    //
1431    oss.str("");    UInt_t bn = 0;
1432    oss << " UPDATE GL_RAW "    Bool_t afound = false;
1433        << " SET GL_RAW.BOOT_NUMBER = '" << dec << this->GetBOOTnumber() << "'"    if ( !found && this->AutoBoot()){
1434        << " WHERE GL_RAW.ID = '" << idRaw << "'";      afound = true;
1435    conn->Query(oss.str().c_str());            //
1436    //      // Search for other files with similar timesync
1437    delete result;      //
1438    return(0);      if ( IsDebug() ) printf(" tsync %u obt0 %u \n",tsync,obt0);
1439  };      UInt_t upperts = tsync-(obt0/1000)+5;
1440        UInt_t lowerts = tsync-(obt0/1000)-5;
1441  /**      oss.str("");
1442   * Scan runtrailer packet, fill the GL_RUN table and      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)<"
1443   * check for missing and truncated runs          << upperts
1444   */          << " AND TIMESYNC-(OBT0/1000)>"
1445  Int_t PamelaDBOperations::insertPamelaRUN(){          << lowerts
1446            << " AND GL_RAW.BOOT_NUMBER>0 GROUP BY GL_TIMESYNC.OBT0;";
1447        result = conn->Query(oss.str().c_str());
1448        if ( IsDebug() ) printf(" Query the GL_TIMESYNC table to find boot number:\n %s \n",oss.str().c_str());
1449        //
1450        if ( !result ) throw -4;;
1451        found = true;
1452        if ( result->GetRowCount()<3 ){
1453          if ( IsDebug() ) printf(" AGH! no results!\n");
1454          found = false;
1455        } else {
1456          row = result->Next();      
1457          bn = (UInt_t)atoll(row->GetField(0));
1458          for ( Int_t r=1; r<result->GetRowCount() ;r++){
1459            if ( !row ) throw -4;
1460            if ( IsDebug() ) printf(" BOOT number is %s \n",row->GetField(0));
1461            if ( bn != (UInt_t)atoll(row->GetField(0)) ){
1462              if ( IsDebug() ) printf(" AGH! bn = %u here instead %u \n",bn,(UInt_t)atoll(row->GetField(0)));
1463              found = false;
1464            };
1465            row = result->Next();
1466          };
1467        };
1468      };
1469      //
1470      Int_t sgn = 0;
1471      //
1472      if ( !found && !BOOTNO ){
1473        throw -29;
1474      } else {
1475        if ( afound ){
1476          this->SetBOOTnumber(bn);
1477          sgn = 8;
1478        };
1479      };
1480      //
1481      oss.str("");
1482      oss << " UPDATE GL_RAW "
1483          << " SET GL_RAW.BOOT_NUMBER = '" << dec << this->GetBOOTnumber() << "'"
1484          << " WHERE GL_RAW.ID = '" << idRaw << "'";
1485      conn->Query(oss.str().c_str());      
1486      //
1487      delete result;
1488      return(sgn);
1489    };
1490    
1491    /**
1492     * Scan runtrailer packet, fill the GL_RUN table and
1493     * check for missing and truncated runs
1494     */
1495    Int_t PamelaDBOperations::insertPamelaRUN(){
1496    Int_t signal = 0;    Int_t signal = 0;
1497    //    //
1498    stringstream oss;    stringstream oss;
1499    oss.str("");    oss.str("");
1500    //    //
1501    signal = this->SetUpperLimits();    //  signal = this->SetUpperLimits();
1502    //    //
1503    // loop on runheader and runtrailer events    // loop on runheader and runtrailer events
1504    //    //
# Line 1014  Int_t PamelaDBOperations::insertPamelaRU Line 1549  Int_t PamelaDBOperations::insertPamelaRU
1549        //        //
1550        if ( !ptt &&  !(ptht+1) ){        if ( !ptt &&  !(ptht+1) ){
1551          //          //
1552          if ( IsDebug() ) printf(" Piece of run at the beginning of the file %i %i %i \n",ptht,pth,ptt);          if ( IsDebug() ) printf(" Piece of run at the beginning of the file %u %u %u \n",ptht,pth,ptt);
1553          //          //
1554          this->HandleRunFragments(true,false,0,(evbeft-1));          this->HandleRunFragments(true,false,0,(evbeft-1));
1555          //          //
1556          //          //
1557        } else if ( pth == ptht ){        } else if ( pth == ptht ){
1558          //          //
1559          if ( IsDebug() ) printf(" Missing header %i %i %i\n",ptht,pth,ptt);          if ( IsDebug() ) printf(" Missing header %u %u %u\n",ptht,pth,ptt);
1560          //          //
1561          if ( (ptt-1) < 0 ) throw -15;          if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
1562          rt->GetEntry(ptt-1);          rt->GetEntry(ptt-1);
1563          cod = eht->GetCounter();          cod = eht->GetCounter();
1564          evbefh = cod->Get(pctp->Physics);          evbefh = cod->Get(pctp->Physics);
1565          rt->GetEntry(ptt);          rt->GetEntry(ptt);
1566          pht = eht->GetPscuHeader();          pht = eht->GetPscuHeader();
1567          //          //
1568          if ( IsDebug() ) printf(" Try to find the beginning of a run which has only the runtrailer   %i %i %i \n",ptht,pth,ptt);          if ( IsDebug() ) printf(" Try to find the beginning of a run which has only the runtrailer   %u %u %u \n",ptht,pth,ptt);
1569          if ( IsDebug() ) printf(" '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''  %i %i %i \n",pkth,obth,obtt);          if ( IsDebug() ) printf(" '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''  %u %u %u \n",pkth,obth,obtt);
1570          //          //
1571          this->HandleMissingHoT(true,false,evbefh,evbeft-1);          this->HandleMissingHoT(true,false,evbefh,evbeft-1);
1572          //          //
1573        } else {        } else {
1574          //          //
1575          if ( IsDebug() ) printf(" Could be a good run, we have a runheader followed by a runtrailer %i %i %i\n",ptht,pth,ptt);          if ( IsDebug() ) printf(" Could be a good run, we have a runheader followed by a runtrailer %u %u %u\n",ptht,pth,ptt);
1576          //          //
1577          rh->GetEntry(ptht);          rh->GetEntry(ptht);
1578          phh = ehh->GetPscuHeader();          phh = ehh->GetPscuHeader();
# Line 1045  Int_t PamelaDBOperations::insertPamelaRU Line 1580  Int_t PamelaDBOperations::insertPamelaRU
1580          obth = phh->GetOrbitalTime();          obth = phh->GetOrbitalTime();
1581          cod = ehh->GetCounter();          cod = ehh->GetCounter();
1582          evbefh = cod->Get(pctp->Physics);          evbefh = cod->Get(pctp->Physics);
1583          if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' %i %i %i \n",pkth,obth,obtt);          if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' %u %u %u \n",pkth,obth,obtt);
1584          //          //
1585          // handle this run          // handle this run
1586          //          //
# Line 1065  Int_t PamelaDBOperations::insertPamelaRU Line 1600  Int_t PamelaDBOperations::insertPamelaRU
1600          if ( (ptht - pth) > 1 ){          if ( (ptht - pth) > 1 ){
1601            //            //
1602            if ( IsDebug() ) printf(" Missing runtrailers! \n");            if ( IsDebug() ) printf(" Missing runtrailers! \n");
1603            if ( IsDebug() ) printf(" Attention there is a jump in the runheader counter %i %i %i \n",ptht,pth,ptt);            if ( IsDebug() ) printf(" Attention there is a jump in the runheader counter %u %u %u \n",ptht,pth,ptt);
1604            // is not the consecutive header            // is not the consecutive header
1605            while ( pth != ptht ){                      while ( pth != ptht ){          
1606              //              //
# Line 1086  Int_t PamelaDBOperations::insertPamelaRU Line 1621  Int_t PamelaDBOperations::insertPamelaRU
1621              obth = phh->GetOrbitalTime();              obth = phh->GetOrbitalTime();
1622              evbefh = cod->Get(pctp->Physics);              evbefh = cod->Get(pctp->Physics);
1623              //              //
1624              if ( IsDebug() ) printf(" Try to find the end of a run which has only the runheader   %i %i %i \n",ptht,pth,ptt);              if ( IsDebug() ) printf(" Try to find the end of a run which has only the runheader   %u %u %u \n",ptht,pth,ptt);
1625              if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' %i %i %i \n",pkth,obth,obtt);              if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' %u %u %u \n",pkth,obth,obtt);
1626              //              //
1627              this->HandleMissingHoT(false,true,evbefh,evbeft-1);              this->HandleMissingHoT(false,true,evbefh,evbeft-1);
1628              //              //
# Line 1096  Int_t PamelaDBOperations::insertPamelaRU Line 1631  Int_t PamelaDBOperations::insertPamelaRU
1631          } else if ( !(ptht - pth) ){          } else if ( !(ptht - pth) ){
1632            //            //
1633            if ( IsDebug() ) printf(" Missing runheader! \n");            if ( IsDebug() ) printf(" Missing runheader! \n");
1634            if ( IsDebug() ) printf(" Attention! the runheader counter did not changed %i %i %i \n",ptht,pth,ptt);            if ( IsDebug() ) printf(" Attention! the runheader counter did not changed %u %u %u \n",ptht,pth,ptt);
1635            if ( IsDebug() ) printf(" The run should have already been handled by HandleRun() \n");            if ( IsDebug() ) printf(" The run should have already been handled by HandleRun() \n");
1636            //            //
1637          } else {          } else {
# Line 1117  Int_t PamelaDBOperations::insertPamelaRU Line 1652  Int_t PamelaDBOperations::insertPamelaRU
1652            obth = phh->GetOrbitalTime();            obth = phh->GetOrbitalTime();
1653            cod = ehh->GetCounter();            cod = ehh->GetCounter();
1654            evbefh = cod->Get(pctp->Physics);            evbefh = cod->Get(pctp->Physics);
1655            if ( IsDebug() ) printf(" Piece of run at the end of file %i %i %i \n",pkth,obth,obtt);            if ( IsDebug() ) printf(" Piece of run at the end of file %u %u %u \n",pkth,obth,obtt);
1656            if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''' %i %i %i \n",ptht,pth,ptt);            if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''' %u %u %u \n",ptht,pth,ptt);
1657            if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''' %i \n",rhev);            if ( IsDebug() ) printf(" ''''''''''''''''''''''''''''''' %u \n",rhev);
1658            //            //
1659            this->HandleRunFragments(false,true,evbefh,upperentry);            this->HandleRunFragments(false,true,evbefh,upperentry);
1660          } else {          } else {
# Line 1129  Int_t PamelaDBOperations::insertPamelaRU Line 1664  Int_t PamelaDBOperations::insertPamelaRU
1664            if ( (UInt_t)evbeft < upperentry-1 ){            if ( (UInt_t)evbeft < upperentry-1 ){
1665              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");
1666              //              //
1667              if ( (ptt-1) < 0 ) throw -15;              if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
1668              rt->GetEntry(ptt-1);              rt->GetEntry(ptt-1);
1669              cod = eht->GetCounter();              cod = eht->GetCounter();
1670              evbefh = cod->Get(pctp->Physics);              evbefh = cod->Get(pctp->Physics);
# Line 1213  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1748  Bool_t PamelaDBOperations::IsRunAlreadyI
1748      if ( glrun->GetNEVENTS() > (UInt_t)atoll(row->GetField(1)) ){      if ( glrun->GetNEVENTS() > (UInt_t)atoll(row->GetField(1)) ){
1749        //        //
1750        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");
1751        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1752        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1753        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) <<";";
1754        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1755    //       conn->Query(oss.str().c_str());
1756        if ( signal ) signal = false;        if ( signal ) signal = false;
1757        goto gonext;              goto gonext;      
1758        //        //
# Line 1230  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1766  Bool_t PamelaDBOperations::IsRunAlreadyI
1766        //        //
1767        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");
1768        //        //
1769        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1770        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1771        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) <<";";
1772        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1773    //       conn->Query(oss.str().c_str());
1774        //        //
1775        if ( signal ) signal = false;        if ( signal ) signal = false;
1776        goto gonext;        goto gonext;
# Line 1247  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1784  Bool_t PamelaDBOperations::IsRunAlreadyI
1784        //        //
1785        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");
1786        //        //
1787        oss.str("");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
1788        oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";  //       oss.str("");
1789        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) <<";";
1790        conn->Query(oss.str().c_str());  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
1791    //       conn->Query(oss.str().c_str());
1792        if ( signal ) signal = false;        if ( signal ) signal = false;
1793        //        //
1794      };      };
# Line 1265  Bool_t PamelaDBOperations::IsRunAlreadyI Line 1803  Bool_t PamelaDBOperations::IsRunAlreadyI
1803    delete result;    delete result;
1804    //    //
1805    if ( signal && IsDebug() ) printf(" The run has already been inserted \n");        if ( signal && IsDebug() ) printf(" The run has already been inserted \n");    
1806      if ( !signal && IsDebug() ) printf(" The run existed and was deleted, fill the DB \n");
1807    return(signal);    return(signal);
1808  };  };
1809    
# Line 1286  void PamelaDBOperations::HandleRun(){   Line 1825  void PamelaDBOperations::HandleRun(){  
1825      //      //
1826      this->FillClass();      this->FillClass();
1827      //      //
1828      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);      if ( !IsRunAlreadyInserted() ){
1829          glrun->SetID(this->AssignRunID());
1830          glrun->SetID_RUN_FRAG(0);
1831          glrun->Fill_GL_RUN(conn);
1832        };
1833    } else {    } else {
1834      //      //
1835      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 1852  void PamelaDBOperations::HandleRunFragme
1852    UInt_t rhfirstev = firstev;    UInt_t rhfirstev = firstev;
1853    UInt_t rtlastev = lastev;    UInt_t rtlastev = lastev;
1854    Bool_t found = false;    Bool_t found = false;
1855      Bool_t foundinrun = false;
1856    //    //
1857    TSQLResult *result = 0;    TSQLResult *result = 0;
1858    TSQLRow    *row    = 0;    TSQLRow    *row    = 0;
# Line 1335  void PamelaDBOperations::HandleRunFragme Line 1879  void PamelaDBOperations::HandleRunFragme
1879    //    //
1880    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");
1881    //    //
1882      // First of all insert the run in the fragment table...
1883      //
1884      oss.str("");
1885      oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
1886          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
1887          << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
1888          << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
1889          << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
1890          << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
1891          << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
1892          << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
1893          << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1894          << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
1895          << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
1896          << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
1897          << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
1898          << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
1899      //
1900      if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
1901      result = conn->Query(oss.str().c_str());
1902      //
1903      if ( !result ) throw -4;
1904      //
1905      row = result->Next();
1906      //
1907      if ( !row ){
1908        //
1909        // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
1910        //
1911        if ( IsDebug() ) printf(" The run is new \n");
1912        if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
1913        //
1914        glrun->SetID(this->AssignRunID());
1915        glrun->SetID_RUN_FRAG(0);
1916        glrun->Fill_GL_RUN_FRAGMENTS(conn);
1917        //
1918      } else {
1919        if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
1920        return;
1921      };
1922      //
1923      //
1924    // 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?
1925    //        //    
1926    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 1929  void PamelaDBOperations::HandleRunFragme
1929      oss.str("");      oss.str("");
1930      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 "
1931          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
1932          << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME()          << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1933            << " ID != " << glrun->ID
1934          << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!          << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
1935      //      //
1936      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 1940  void PamelaDBOperations::HandleRunFragme
1940      //      //
1941      row = result->Next();      row = result->Next();
1942      //      //
1943        if ( !row && NoFrag() ){
1944          //
1945          oss.str("");
1946          oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
1947              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
1948              << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
1949              << " ID != " << glrun->ID
1950              << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
1951          //
1952          if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
1953          result = conn->Query(oss.str().c_str());
1954          //
1955          if ( !result ) throw -4;
1956          //
1957          foundinrun = true;
1958          //
1959          row = result->Next();
1960          //
1961        };
1962        //
1963      if ( !row ){      if ( !row ){
1964        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
1965        found = false;        found = false;
# Line 1427  void PamelaDBOperations::HandleRunFragme Line 2034  void PamelaDBOperations::HandleRunFragme
2034        //        //
2035        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 ");
2036        //        //
2037          if ( foundinrun ){
2038            glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2039            glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2040          };
2041          //
2042        GL_RUN *glrun1 = new GL_RUN();        GL_RUN *glrun1 = new GL_RUN();
2043        //        //
2044        UInt_t idfrag = (UInt_t)atoll(row->GetField(0));        //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
2045        //        //
2046        oss.str("");        oss.str("");
2047        oss << " ID="<<row->GetField(0)<<";";        oss << " ID="<<row->GetField(0)<<";";
# Line 1442  void PamelaDBOperations::HandleRunFragme Line 2054  void PamelaDBOperations::HandleRunFragme
2054        ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());        ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
2055        UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());        UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
2056        ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());        ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
2057        if ( IsDebug() ) printf(" Check overlapping events: %i %i %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);        if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2058        TTree *T= 0;        TTree *T= 0;
2059        T = (TTree*)file->Get("Physics");        T = (TTree*)file->Get("Physics");
2060        if ( !T || T->IsZombie() ) throw -16;        if ( !T || T->IsZombie() ) throw -16;
# Line 1456  void PamelaDBOperations::HandleRunFragme Line 2068  void PamelaDBOperations::HandleRunFragme
2068          bobt = OBT(ph->GetOrbitalTime());                bobt = OBT(ph->GetOrbitalTime());      
2069          firstev++;          firstev++;
2070        };        };
2071        if ( IsDebug() ) printf(" Check overlapping events done: %i %i %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);        if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2072        //        //
       glrun1->SetID(0);  
2073        glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());        glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
2074        glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());        glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
2075        glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());        glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
# Line 1467  void PamelaDBOperations::HandleRunFragme Line 2078  void PamelaDBOperations::HandleRunFragme
2078        //        //
2079        glrun->SetEV_FROM(firstev);        glrun->SetEV_FROM(firstev);
2080        glrun->SetNEVENTS(lastev-firstev+1);        glrun->SetNEVENTS(lastev-firstev+1);
2081          //
2082        glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());        glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
2083        glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());        glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
2084        glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());        glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
# Line 1486  void PamelaDBOperations::HandleRunFragme Line 2098  void PamelaDBOperations::HandleRunFragme
2098        //        //
2099        if ( !IsRunAlreadyInserted() ){        if ( !IsRunAlreadyInserted() ){
2100          //          //
2101            //      glrun->SetID(this->AssignRunID());
2102            glrun->SetID_RUN_FRAG(glrun1->GetID());
2103          glrun->Fill_GL_RUN(conn);          glrun->Fill_GL_RUN(conn);
2104          //          //
2105          // 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);  
2106          //          //
2107            glrun1->SetID_RUN_FRAG(glrun->GetID());
2108          glrun1->Fill_GL_RUN(conn);          glrun1->Fill_GL_RUN(conn);
2109          //          //
         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;  
         //  
2110        };        };
       //  
       delete glrun1;  
       //  
2111        // delete old entry in fragment table        // delete old entry in fragment table
2112        //        //
2113        oss.str("");        glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2114          glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2115        //        //
2116        oss << " DELETE FROM GL_RUN_FRAGMENTS WHERE ID = " << idfrag << ";";        delete glrun1;
2117        //        //
       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;  
2118        //        //
2119        return;        return;
2120        //        //
# Line 1555  void PamelaDBOperations::HandleRunFragme Line 2123  void PamelaDBOperations::HandleRunFragme
2123    };    };
2124    //    //
2125    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
2126                                             // 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
2127      //      //
2128      oss.str("");      oss.str("");
2129      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 "
2130          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2131          << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME()          << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2132            << " ID != " << glrun->ID
2133          << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";          << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2134      //      //
2135      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 2139  void PamelaDBOperations::HandleRunFragme
2139      //      //
2140      row = result->Next();      row = result->Next();
2141      //      //
2142        if ( !row && NoFrag() ){
2143          //
2144          oss.str("");
2145          oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN WHERE "
2146              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2147              << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2148              << " ID != " << glrun->ID
2149              << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2150          //
2151          if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
2152          result = conn->Query(oss.str().c_str());
2153          //
2154          if ( !result ) throw -4;
2155          //
2156          foundinrun = true;
2157          row = result->Next();
2158          //
2159        };
2160        //
2161      if ( !row ){      if ( !row ){
2162        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2163        found = false;        found = false;
# Line 1643  void PamelaDBOperations::HandleRunFragme Line 2231  void PamelaDBOperations::HandleRunFragme
2231        //        //
2232        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 ");
2233        //        //
2234          if ( foundinrun ){
2235            glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2236            glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2237          };
2238          //
2239        GL_RUN *glrun1 = new GL_RUN();        GL_RUN *glrun1 = new GL_RUN();
2240        //        //
2241        UInt_t idfrag = (UInt_t)atoll(row->GetField(0));        //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
2242        //        //
2243        oss.str("");        oss.str("");
2244        oss << " ID="<<row->GetField(0)<<";";        oss << " ID="<<row->GetField(0)<<";";
# Line 1658  void PamelaDBOperations::HandleRunFragme Line 2251  void PamelaDBOperations::HandleRunFragme
2251        ULong64_t aobt = OBT(glrun->GetRUNTRAILER_OBT());        ULong64_t aobt = OBT(glrun->GetRUNTRAILER_OBT());
2252        UInt_t bpkt = PKT(glrun1->GetRUNHEADER_PKT());        UInt_t bpkt = PKT(glrun1->GetRUNHEADER_PKT());
2253        ULong64_t bobt = OBT(glrun1->GetRUNHEADER_OBT());        ULong64_t bobt = OBT(glrun1->GetRUNHEADER_OBT());
2254        if ( IsDebug() ) printf(" Check overlapping events: %i %i %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);        if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
2255        TTree *T= 0;        TTree *T= 0;
2256        T = (TTree*)file->Get("Physics");        T = (TTree*)file->Get("Physics");
2257        if ( !T || T->IsZombie() ) throw -16;        if ( !T || T->IsZombie() ) throw -16;
# Line 1672  void PamelaDBOperations::HandleRunFragme Line 2265  void PamelaDBOperations::HandleRunFragme
2265          aobt = OBT(ph->GetOrbitalTime());                aobt = OBT(ph->GetOrbitalTime());      
2266          lastev--;          lastev--;
2267        };        };
2268        if ( IsDebug() ) printf(" Check overlapping events done: %i %i %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);        if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
2269        //        //
2270        glrun->SetEV_TO(lastev);        glrun->SetEV_TO(lastev);
2271        glrun->SetNEVENTS(lastev-firstev+1);        glrun->SetNEVENTS(lastev-firstev+1);
# Line 1682  void PamelaDBOperations::HandleRunFragme Line 2275  void PamelaDBOperations::HandleRunFragme
2275        glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());        glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());
2276        glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());        glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());
2277        //        //
       glrun1->SetID(0);  
2278        glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());        glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());
2279        glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());        glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());
2280        glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());        glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());
# Line 1702  void PamelaDBOperations::HandleRunFragme Line 2294  void PamelaDBOperations::HandleRunFragme
2294        //        //
2295        if ( !IsRunAlreadyInserted() ){        if ( !IsRunAlreadyInserted() ){
2296          //          //
2297          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();  
2298          //          //
2299          UInt_t idrun0 = 0;          glrun->SetID_RUN_FRAG(glrun1->GetID());
2300          if ( !row ){          glrun->Fill_GL_RUN(conn);
           throw -10;  
         } else {  
           idrun0 = (UInt_t)atoll(row->GetField(0));  
         };  
2301          //          //
2302          glrun1->SetID_RUN_FRAG(idrun0);          // set id number
2303          //          //
2304            glrun1->SetID_RUN_FRAG(glrun->GetID());
2305          glrun1->Fill_GL_RUN(conn);          glrun1->Fill_GL_RUN(conn);
2306          //          //
         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;  
         //  
2307        };        };
2308        //        //
2309        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 << ";";  
2310        //        //
2311        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");
2312        result =  conn->Query(oss.str().c_str());        glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
       if ( !result ) throw -4;  
2313        //        //
2314          delete glrun1;
2315        //        //
2316        return;        return;
2317        //        //
# Line 1800  void PamelaDBOperations::HandleRunFragme Line 2348  void PamelaDBOperations::HandleRunFragme
2348      //      //
2349      row = result->Next();      row = result->Next();
2350      //      //
2351      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 {  
2352        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");
2353        } else {
2354          if ( NoFrag() ){
2355            glrun->SetID_RUN_FRAG(glrun->GetID());
2356            glrun->Fill_GL_RUN(conn);      
2357            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2358          };    
2359      };      };
2360    };    };
2361    //    //
# Line 1864  void PamelaDBOperations::HandleMissingHo Line 2381  void PamelaDBOperations::HandleMissingHo
2381      //      //
2382      this->FillClass(mishead,mistrail,firstev,lastev);      this->FillClass(mishead,mistrail,firstev,lastev);
2383      //      //
2384      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);          if ( !IsRunAlreadyInserted() ){
2385          glrun->SetID(this->AssignRunID());
2386          glrun->SetID_RUN_FRAG(0);
2387          glrun->Fill_GL_RUN(conn);    
2388        };
2389      //      //
2390    };    };
2391    //    //
# Line 2031  Bool_t PamelaDBOperations::IsRunConsiste Line 2552  Bool_t PamelaDBOperations::IsRunConsiste
2552            //                  //      
2553            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
2554            //            //
2555            if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                  if ( !IsRunAlreadyInserted() ){
2556                glrun->SetID(this->AssignRunID());
2557                glrun->SetID_RUN_FRAG(0);
2558                glrun->Fill_GL_RUN(conn);      
2559              };
2560            //            //
2561            firstevno = lastentry + 1;            firstevno = lastentry + 1;
2562            //            //
# Line 2106  void PamelaDBOperations::HandleSuspiciou Line 2631  void PamelaDBOperations::HandleSuspiciou
2631    if ( firstev == lastev+1 ) { // no events inside the run!    if ( firstev == lastev+1 ) { // no events inside the run!
2632      if ( IsDebug() ) printf(" Checking but no events in the run! \n");      if ( IsDebug() ) printf(" Checking but no events in the run! \n");
2633      //      //
     //    if ( IsDebug() ) printf(" -> fill the DB \n");  
     //  
2634      this->FillClass();      this->FillClass();
2635      if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);          if ( !IsRunAlreadyInserted() ){
2636          glrun->SetID(this->AssignRunID());
2637          glrun->SetID_RUN_FRAG(0);
2638          glrun->Fill_GL_RUN(conn);    
2639        };
2640      //      //
2641    } else {    } else {
2642      //      //
# Line 2137  void PamelaDBOperations::HandleSuspiciou Line 2664  void PamelaDBOperations::HandleSuspiciou
2664        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");
2665        //        //
2666        this->FillClass();        this->FillClass();
2667        if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                if ( !IsRunAlreadyInserted() ){
2668            glrun->SetID(this->AssignRunID());
2669            glrun->SetID_RUN_FRAG(0);
2670            glrun->Fill_GL_RUN(conn);        
2671          };
2672        //        //
2673      } else {      } else {
2674        //        //
# Line 2235  void PamelaDBOperations::HandleSuspiciou Line 2766  void PamelaDBOperations::HandleSuspiciou
2766            //                  //      
2767            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
2768            //            //
2769            if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                  if ( !IsRunAlreadyInserted() ){
2770                glrun->SetID(this->AssignRunID());
2771                glrun->SetID_RUN_FRAG(0);
2772                glrun->Fill_GL_RUN(conn);      
2773              };
2774            //            //
2775            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...
2776              //              //
# Line 2270  void PamelaDBOperations::HandleSuspiciou Line 2805  void PamelaDBOperations::HandleSuspiciou
2805              //                  //    
2806              this->SetCommonGLRUN(firstTime,lastTime);              this->SetCommonGLRUN(firstTime,lastTime);
2807              //              //
2808              if ( !IsRunAlreadyInserted() ) glrun->Fill_GL_RUN(conn);                    if ( !IsRunAlreadyInserted() ){
2809                  glrun->SetID(this->AssignRunID());
2810                  glrun->SetID_RUN_FRAG(0);
2811                  glrun->Fill_GL_RUN(conn);      
2812                };
2813            };            };
2814            //            //
2815            firstevno = lastentry + 1;            firstevno = lastentry + 1;
# Line 2318  Int_t PamelaDBOperations::insertCALO_CAL Line 2857  Int_t PamelaDBOperations::insertCALO_CAL
2857    tr->SetBranchAddress("Header", &eh);    tr->SetBranchAddress("Header", &eh);
2858    nevents = tr->GetEntries();    nevents = tr->GetEntries();
2859    //    //
2860    if ( !nevents ) return(0);    if ( !nevents ) return(1);
2861    //    //
2862    for (UInt_t i=0; i < nevents; i++){    for (UInt_t i=0; i < nevents; i++){
2863      tr->GetEntry(i);      tr->GetEntry(i);
# Line 2333  Int_t PamelaDBOperations::insertCALO_CAL Line 2872  Int_t PamelaDBOperations::insertCALO_CAL
2872          fromtime = this->GetAbsTime(ph->GetOrbitalTime());            fromtime = this->GetAbsTime(ph->GetOrbitalTime());  
2873          if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->OBT(obt) >= this->OBT(obtfirst) ){          if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->OBT(obt) >= this->OBT(obtfirst) ){
2874            //            //
2875            if ( IsDebug() ) printf(" Calo calibration for section %i at time %i obt %i pkt %i \n",section,fromtime,obt,pkt);            if ( IsDebug() ) printf(" Calo calibration for section %i at time %u obt %u pkt %u \n",section,fromtime,obt,pkt);
2876            //            //
2877            // check if the calibration has already been inserted            // check if the calibration has already been inserted
2878            //            //
# Line 2377  Int_t PamelaDBOperations::insertCALO_CAL Line 2916  Int_t PamelaDBOperations::insertCALO_CAL
2916                // no calibrations in the db contain our calibration                // no calibrations in the db contain our calibration
2917                //                //
2918                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);
2919                if ( fromtime < 1150863400 ){                if ( fromtime < 1150871000 ){ //1150866904
2920                  if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);                  if ( IsDebug() ) printf(" First PAMELA flight calibration at time %u \n",fromtime);
2921                  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
2922                };                };
2923                //                //
# Line 2440  Int_t PamelaDBOperations::insertCALO_CAL Line 2979  Int_t PamelaDBOperations::insertCALO_CAL
2979            //            //
2980          } else {          } else {
2981            //            //
2982            if ( IsDebug() ) printf(" Repetead calo calibration for section %i at time %i obt %i pkt %i \n",section,fromtime,obt,pkt);            if ( IsDebug() ) printf(" Repeated calo calibration for section %i at time %u obt %u pkt %u \n",section,fromtime,obt,pkt);
2983            //            //
2984          };                };      
2985          //                //      
# Line 2522  void PamelaDBOperations::HandleTRK_CALIB Line 3061  void PamelaDBOperations::HandleTRK_CALIB
3061        // no calibrations in the db contain our calibration        // no calibrations in the db contain our calibration
3062        //        //
3063        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");
3064        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
3065        //        //
3066        oss.str("");        oss.str("");
3067        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 3174  Int_t PamelaDBOperations::insertTRK_CALI
3174    tr2->SetBranchAddress("Header", &eh2);    tr2->SetBranchAddress("Header", &eh2);
3175    nevents2 = tr2->GetEntries();    nevents2 = tr2->GetEntries();
3176    //    //
3177    if ( !nevents1 && !nevents2 ) return(0);    if ( !nevents1 && !nevents2 ) return(1);
3178    //    //
3179    t2 = -1;    t2 = -1;
3180    Int_t pret2 = 0;    Int_t pret2 = 0;
# Line 2651  Int_t PamelaDBOperations::insertTRK_CALI Line 3190  Int_t PamelaDBOperations::insertTRK_CALI
3190      pkt1 = ph1->GetCounter();        pkt1 = ph1->GetCounter();  
3191      fromtime = this->GetAbsTime(ph1->GetOrbitalTime());        fromtime = this->GetAbsTime(ph1->GetOrbitalTime());  
3192      //      //
3193      valid = 1;  //     valid = 1;
3194      //  //     //
3195      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
3196      //      //
3197      //      //
3198      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) ){
3199        //        //
3200        if ( IsDebug() ) printf(" Trk calibration1 at time %i obt %i pkt %i \n",fromtime,obt1,pkt1);        if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u \n",fromtime,obt1,pkt1);
3201          //      
3202          valid = ValidateTrkCalib( caltrk1, eh1 );
3203          if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;
3204        //        //
3205        // Do we have the second calibration packet?        // Do we have the second calibration packet?
3206        //        //
# Line 2675  Int_t PamelaDBOperations::insertTRK_CALI Line 3217  Int_t PamelaDBOperations::insertTRK_CALI
3217            obt2 = ph2->GetOrbitalTime();              obt2 = ph2->GetOrbitalTime();  
3218            pkt2 = ph2->GetCounter();              pkt2 = ph2->GetCounter();  
3219            //            //
3220            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
3221            //                  //      
3222          } else {          } else {
3223            //            //
# Line 2698  Int_t PamelaDBOperations::insertTRK_CALI Line 3240  Int_t PamelaDBOperations::insertTRK_CALI
3240          //          //
3241        };        };
3242        //        //
3243        if ( IsDebug() ) printf(" Found trk calibration2 at obt %i pkt %i t2 is %i \n",obt2,pkt2,t2);        if ( IsDebug() ) printf(" Found trk calibration2 at obt %u pkt %u t2 is %u \n",obt2,pkt2,t2);
3244        //        //
3245        // The calibration is good        // The calibration is good
3246        //        //
3247        if ( this->PKT(pkt2) == this->PKT(pkt1)+1 ){        if ( this->PKT(pkt2) == this->PKT(pkt1)+1 ){
3248          //          //
3249          if ( IsDebug() ) printf(" The trk calibration2 at obt %i pkt %i t2 is %i is good \n",obt2,pkt2,t2);          if ( IsDebug() ) printf(" The trk calibration2 at obt %u pkt %u t2 is %u is good \n",obt2,pkt2,t2);
3250            //
3251            UInt_t valid2 = ValidateTrkCalib( caltrk2, eh2 );
3252            if ( IsDebug() ) cout << " pkt2 validation --> "<<valid2<<endl;
3253            valid = valid & valid2;
3254          //          //
3255          // Handle good calib          // Handle good calib
3256          //          //
# Line 2714  Int_t PamelaDBOperations::insertTRK_CALI Line 3260  Int_t PamelaDBOperations::insertTRK_CALI
3260          //          //
3261          if ( t2 != pret2+1 ){          if ( t2 != pret2+1 ){
3262            //            //
3263            if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %i pkt %i t2 is %i pret2 is %i \n",obt2,pkt2,t2,pret2);            if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %u pkt %u t2 is %u pret2 is %u \n",obt2,pkt2,t2,pret2);
3264            //            //
3265            while ( t2 > pret2+1 ){            while ( t2 > pret2+1 ){
3266              //              //
# Line 2743  Int_t PamelaDBOperations::insertTRK_CALI Line 3289  Int_t PamelaDBOperations::insertTRK_CALI
3289          //          //
3290          // Check for missing calibtrk2          // Check for missing calibtrk2
3291          //          //
3292          if ( IsDebug() ) printf(" Missing the trk calibration2! Next one at obt %i pkt %i t2 is %i\n",obt2,pkt2,t2);          if ( IsDebug() ) printf(" Missing the trk calibration2! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);
3293          t2 = pret2;          t2 = pret2;
3294          //          //
3295          // handle missing calib2          // handle missing calib2
# Line 2757  Int_t PamelaDBOperations::insertTRK_CALI Line 3303  Int_t PamelaDBOperations::insertTRK_CALI
3303        //        //
3304      } else {      } else {
3305        //        //
3306        if ( IsDebug() ) printf(" Repetead trk calibration1 at time %i obt %i pkt %i \n",fromtime,obt1,pkt1);        if ( IsDebug() ) printf(" Repetead trk calibration1 at time %u obt %u pkt %u \n",fromtime,obt1,pkt1);
3307        //        //
3308      };      };
3309      //          //    
# Line 2782  Int_t PamelaDBOperations::insertTRK_CALI Line 3328  Int_t PamelaDBOperations::insertTRK_CALI
3328      valid = 0;      valid = 0;
3329      if ( this->PKT(pkt2) > this->PKT(pktfirst) || this->OBT(obt2) > this->OBT(obtfirst) ){      if ( this->PKT(pkt2) > this->PKT(pktfirst) || this->OBT(obt2) > this->OBT(obtfirst) ){
3330        //        //
3331        if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %i pkt %i t2 is %i\n",obt2,pkt2,t2);        if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);
3332        //        //
3333        this->HandleTRK_CALIB(false,true);        this->HandleTRK_CALIB(false,true);
3334        //        //
# Line 2807  Int_t PamelaDBOperations::insertS4_CALIB Line 3353  Int_t PamelaDBOperations::insertS4_CALIB
3353    stringstream oss;    stringstream oss;
3354    oss.str("");    oss.str("");
3355    //    //
   CalibS4Event *calibS4    = new  CalibS4Event();  
3356    TTree *tr = 0;    TTree *tr = 0;
3357    EventHeader *eh = 0;    EventHeader *eh = 0;
3358    PscuHeader *ph = 0;    PscuHeader *ph = 0;
# Line 2821  Int_t PamelaDBOperations::insertS4_CALIB Line 3366  Int_t PamelaDBOperations::insertS4_CALIB
3366    tr = (TTree*)file->Get("CalibS4");    tr = (TTree*)file->Get("CalibS4");
3367    if ( !tr || tr->IsZombie() ) throw -24;    if ( !tr || tr->IsZombie() ) throw -24;
3368    //    //
   tr->SetBranchAddress("CalibS4", &calibS4);  
3369    tr->SetBranchAddress("Header", &eh);    tr->SetBranchAddress("Header", &eh);
3370    //    //
3371    nevents = tr->GetEntries();    nevents = tr->GetEntries();
3372    //    //
3373    if ( !nevents ) return(0);    if ( !nevents ) return(1);
3374    //    //
3375    for (UInt_t i = 0; i < nevents; i++){    for (UInt_t i = 0; i < nevents; i++){
3376      //      //
3377      tr->GetEntry(i);      tr->GetEntry(i);
     TArrayD params = S4_paramfit(calibS4);  
3378      //      //
3379      ph = eh->GetPscuHeader();      ph = eh->GetPscuHeader();
3380      obt = ph->GetOrbitalTime();        obt = ph->GetOrbitalTime();  
# Line 2839  Int_t PamelaDBOperations::insertS4_CALIB Line 3382  Int_t PamelaDBOperations::insertS4_CALIB
3382      fromtime = this->GetAbsTime(ph->GetOrbitalTime());        fromtime = this->GetAbsTime(ph->GetOrbitalTime());  
3383      if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->OBT(obt) >= this->OBT(obtfirst) ){      if ( this->PKT(pkt) >= this->PKT(pktfirst) && this->OBT(obt) >= this->OBT(obtfirst) ){
3384        //        //
3385        if ( IsDebug() ) printf(" S4 calibration at time %i obt %i pkt %i \n",fromtime,obt,pkt);        if ( IsDebug() ) printf(" S4 calibration at time %u obt %u pkt %u \n",fromtime,obt,pkt);
3386        //        //
3387        // check if the calibration has already been inserted        // check if the calibration has already been inserted
3388        //        //
# Line 2881  Int_t PamelaDBOperations::insertS4_CALIB Line 3424  Int_t PamelaDBOperations::insertS4_CALIB
3424            // no calibrations in the db contain our calibration            // no calibrations in the db contain our calibration
3425            //            //
3426            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");
3427            if ( fromtime < 1150863400 ){            if ( fromtime < 1150871000 ){  
3428              if ( IsDebug() ) printf(" First PAMELA flight calibration at time %i \n",fromtime);              if ( IsDebug() ) printf(" First PAMELA flight calibration at time %u \n",fromtime);
3429              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
3430            };            };
3431            //            //
# Line 2921  Int_t PamelaDBOperations::insertS4_CALIB Line 3464  Int_t PamelaDBOperations::insertS4_CALIB
3464          };          };
3465          //          //
3466          oss.str("");          oss.str("");
3467          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) "
3468              << " VALUES (NULL,' "              << " VALUES (NULL,' "
3469              << idroot << "','"              << idroot << "','"
3470              << i << "','"              << i << "','"
3471              << fromtime << "','"              << fromtime << "','"
3472              << totime << "','"              << totime << "','"
             << dec << params.At(0) << "','"  
             << dec << params.At(1) << "','"        
3473              << obt << "','"              << obt << "','"
3474              << pkt << "','"              << pkt << "','"
3475              << this->GetBOOTnumber() << "','"              << this->GetBOOTnumber() << "');";
             << valid << "');";  
3476          //          //
3477          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());
3478          //          //
# Line 2944  Int_t PamelaDBOperations::insertS4_CALIB Line 3484  Int_t PamelaDBOperations::insertS4_CALIB
3484        //        //
3485      } else {      } else {
3486        //        //
3487        if ( IsDebug() ) printf(" Repetead S4 calibration at time %i obt %i pkt %i \n",fromtime,obt,pkt);        if ( IsDebug() ) printf(" Repeated S4 calibration at time %u obt %u pkt %u \n",fromtime,obt,pkt);
3488        //        //
3489      };            };      
3490      //            //      
# Line 2953  Int_t PamelaDBOperations::insertS4_CALIB Line 3493  Int_t PamelaDBOperations::insertS4_CALIB
3493    return(0);    return(0);
3494  };  };
3495    
3496    /**
3497  /*   * Scan the fragment table and move old fragments to the GL_RUN table
  * Fit function Received from Valeria Malvezzi 06/02/2006  
3498   */   */
3499  Double_t fitf(Double_t *x, Double_t *par){    Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(){
3500    Double_t fitval =(par[0]*x[0])+par[1];    return(this->CleanGL_RUN_FRAGMENTS(""));
3501    return fitval;  };
 }  
3502    
3503  /*  /**
3504   * 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
3505   */   */
3506  TArrayD PamelaDBOperations::S4_paramfit(pamela::CalibS4Event *S4CalibEvent){        Int_t PamelaDBOperations::CleanGL_RUN_FRAGMENTS(TString fcleanfile){
3507      //
3508    //----------- variable initialization -------------------------------------------------    TSQLResult *result = 0;
3509      TSQLRow    *row    = 0;
3510    Double_t mip[3]={1, 30, 300};    TSQLResult *result2 = 0;
3511    Double_t adc[3] = {0.,0.,0.};    TSQLRow    *row2   = 0;
3512        //
3513    TArrayD parametri(2);    UInt_t moved = 0;
3514      //
3515    valid = 1;    stringstream oss;
3516      oss.str("");
3517    //------------ Fit calibrations and find parameters to calibrate data ------------------    //
3518    pamela::S4::S4Event  *s4Record;    if ( !strcmp(fcleanfile.Data(),"") ){
3519        //
3520    for (Int_t j = 0; j < 4; j++){      // check if there are entries older than "olderthan" seconds from now
3521      for (Int_t i = 0; i < 128; i++){      //
3522        s4Record = (pamela::S4::S4Event*)S4CalibEvent->Records->At((j*128 + i));      oss.str("");
3523        switch (j) {      oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
3524        case 0 :{          << " INSERT_TIME <= '" << clean_time->AsSQLString() << "';";
3525          adc[0]=adc[0]+((s4Record->S4_DATA)-32);      //
3526          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());
3527        };      result = conn->Query(oss.str().c_str());
3528        case 1 :{      //
3529          adc[1]=adc[1]+((s4Record->S4_DATA)-32);    } else {
3530          break;      oss.str("");
3531        };      oss << " SELECT ID FROM GL_ROOT WHERE NAME='" << fcleanfile.Data() << "';";
3532        case 3 :{      if ( IsDebug() ) printf(" Getting ID_ROOT_L0 query %s \n",oss.str().c_str());
3533          adc[2]=adc[2]+((s4Record->S4_DATA)-32);      result = conn->Query(oss.str().c_str());
3534          break;      //    
3535        };      if ( result ){
3536          //
3537          row = result->Next();
3538          //
3539          if ( row ){
3540            oss.str("");
3541            oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE"
3542                << " ID_ROOT_L0=" << row->GetField(0) << ";";
3543            //
3544            if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS for ROOT file query is \n %s \n",oss.str().c_str());
3545            result = conn->Query(oss.str().c_str());
3546            //    
3547        };        };
3548        } else {
3549          return(2);
3550      };      };
3551    };    };
3552        //
3553    adc[0]=adc[0]/128;    if ( result ){
3554    adc[1]=adc[1]/128;      //
3555    adc[2]=adc[2]/128;      row = result->Next();
3556          //
3557    TGraph *fitpar = new TGraph (3, adc, mip);      while ( row ){
3558    TF1 *func = new TF1("fitf", fitf, -0., 1000., 2); // definizione della funzione, 2 = num. parametri        //
3559            oss.str("");
3560    func->SetParameters(0.3,1.);        //inizializzazione dei parametri a 1        oss << " ID= "<< row->GetField(0);
3561    func->SetParNames("m","q");      //definisce il nome dei parametri        //
3562    fitpar->Fit(func,"qr");          //fitta fitpar con la funzione func nel range definito nella funzione        glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);  
3563    //fitpar->Fit(func,"r");          //fitta fitpar con la funzione func nel range definito nella funzione        //
3564              oss.str("");
3565    parametri[0] = func -> GetParameter(0);        oss << " SELECT ID,NEVENTS,TRK_CALIB_USED,PKT_COUNTER FROM GL_RUN WHERE "
3566    parametri[1] = func -> GetParameter(1);            << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND ("
3567              << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3568    if ( parametri[0] < 0. || parametri[0] > 0.5 || parametri[1] < 0.8 || parametri[1] > 1. ) valid = 0;            << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3569              << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3570    if ( IsDebug() ) printf(" par1 = %g par2 = %g\n",parametri[0],parametri[1]);            << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3571              << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3572    return parametri;            << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3573              << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3574              << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3575              << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3576              << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3577              << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3578              << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3579          //
3580          if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3581          result2 = conn->Query(oss.str().c_str());
3582          //
3583          if ( !result2 ) throw -4;
3584          //
3585          row2 = result2->Next();
3586          //
3587          if ( !row2 ){
3588            //
3589            if ( IsDebug() ) printf(" The run is new \n");
3590            if ( IsDebug() ) printf(" -> fill the DB \n");      
3591            //
3592            //      glrun->SetID(this->AssignRunID()); we use the old run number!
3593            glrun->SetID_RUN_FRAG(glrun->GetID());
3594            glrun->Fill_GL_RUN(conn);  
3595            //
3596    //      oss.str("");
3597    //      oss << " SELECT ID FROM GL_RUN WHERE "
3598    //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
3599    //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
3600    //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
3601    //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
3602    //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
3603    //      //
3604    //      if ( IsDebug() ) printf(" Look for the ID of the inserted run: query is \n %s \n",oss.str().c_str());
3605    //      result2 = conn->Query(oss.str().c_str());
3606    //      //
3607    //      if ( !result2 ) throw -4;
3608    //      //
3609    //      row2 = result2->Next();
3610    //      //
3611    //      if ( !row2 ) throw -25;
3612    //      //
3613    //      oss.str("");
3614    //      oss << " UPDATE GL_RUN SET ID_RUN_FRAG = " << row2->GetField(0) << " WHERE ID = " << row2->GetField(0);
3615    //      if ( IsDebug() ) printf(" Update the ID_RUN_FRAG of the inserted run: query is \n %s \n",oss.str().c_str());
3616    //      result2 = conn->Query(oss.str().c_str());
3617    //      //
3618    //      if ( !result2 ) throw -4;
3619            //
3620            moved++;
3621            //
3622          } else {
3623            if ( IsDebug() ) printf(" The already exist in the GL_RUN table! \n");
3624          };
3625          if ( IsDebug() ) printf(" Delete run %s from the GL_RUN_FRAGMENTS table \n",row->GetField(0));      
3626          //
3627          //
3628          glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3629    //      oss.str("");
3630    //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);
3631    //       if ( IsDebug() ) printf(" Clean the GL_RUN_FRAGMENTS table: query is \n %s \n",oss.str().c_str());
3632    //       result2 = conn->Query(oss.str().c_str());
3633    //      //
3634    //      if ( !result2 ) throw -4;
3635    //      //
3636          row = result->Next();
3637        };
3638      };
3639      if ( IsDebug() ) printf(" Moved %u runs\n",moved);
3640      return(0);
3641    };
3642    
3643    /**
3644     * Check if runs are good, i.e. if the tracker calibration is correctly associated..
3645     */
3646    Int_t PamelaDBOperations::ValidateRuns(){
3647      return(this->ValidateRuns(""));
3648    };
3649    
3650    /**
3651     * Check if runs are good, i.e. if the tracker calibration is correctly associated..
3652     */
3653    Int_t PamelaDBOperations::ValidateRuns(TString valfile){
3654      //
3655      TSQLResult *result = 0;
3656      TSQLRow    *row    = 0;
3657      //
3658      UInt_t calibtime = 50;
3659      //
3660      stringstream oss;
3661      oss.str("");
3662      //
3663      // =======================================================
3664      // validate runs by checking missing calibrations
3665      // =======================================================
3666      UInt_t t_stop  = 0;
3667      UInt_t t_start = 0;
3668      if ( !strcmp(valfile.Data(),"") ) {
3669        // --------------------------------------------------------------
3670        // 1) get the OBT of the last run inserted after clean-time limit
3671        // --------------------------------------------------------------
3672        oss.str("");
3673        oss << " SELECT * FROM GL_RUN  WHERE INSERT_TIME <= '" << clean_time->AsSQLString()
3674            << "' ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
3675        if ( IsDebug() ) printf(" Get start validation-time: query is \n %s \n",oss.str().c_str());
3676        result = conn->Query(oss.str().c_str());
3677        if ( !result ) throw -4;
3678        if ( !result->GetRowCount() ) {
3679          printf(" No runs to validate \n");
3680          return(1);
3681        }else{
3682          row = result->Next();
3683          t_start = (UInt_t)atoll(row->GetField(4));
3684        };  
3685        // --------------------------------------------------------------
3686        // 2) get the OBT of the last validated run
3687        // --------------------------------------------------------------
3688        oss.str("");
3689        oss << " SELECT * FROM GL_RUN  WHERE VALIDATION=1 AND RUNHEADER_TIME<="<< t_start
3690            <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
3691        if ( IsDebug() ) printf(" Get stop validation-time: query is \n %s \n",oss.str().c_str());
3692        result = conn->Query(oss.str().c_str());
3693        if ( !result ) throw -4;
3694        if ( result->GetRowCount() ){
3695          row = result->Next();
3696          t_stop = (UInt_t)atoll(row->GetField(4));
3697        };
3698        if ( IsDebug() ) printf("Validation interval: from time %u - to time %u \n\n",t_stop,t_start);
3699        // --------------------------------------------------------------
3700        // now retrieves runs to be validated
3701        // --------------------------------------------------------------
3702        oss.str("");
3703        oss << " SELECT * FROM GL_RUN  WHERE  RUNHEADER_TIME <=" << t_start;
3704        oss << " AND RUNHEADER_TIME >="<< t_stop;
3705        oss << " ORDER BY RUNHEADER_TIME DESC;";
3706        if ( IsDebug() )printf(" Check runs for validation: query is \n %s \n",oss.str().c_str());
3707        result = conn->Query(oss.str().c_str());
3708      } else {
3709        //
3710        stringstream myquery;
3711        UInt_t myid = 0;
3712        myquery.str("");
3713        myquery << " SELECT ID FROM GL_ROOT where NAME='"<<valfile.Data() <<"';";
3714        //
3715        result = conn->Query(myquery.str().c_str());
3716        //
3717        row = result->Next();      
3718        if( !row ){
3719          if ( strcmp(valfile.Data(),GetRootName().Data()) ){
3720            if ( IsDebug() ) printf(" No file to be validated even if option \"-validate file\" was used!!\n");
3721            return(2);
3722          };
3723          if ( IsDebug() ) printf(" No file to be validated (force mode)! \n");
3724          return(0);
3725        };
3726        myid=(UInt_t)atoll(row->GetField(0));
3727        //
3728        myquery.str("");
3729        myquery << " SELECT MAX(RUNTRAILER_TIME),MIN(RUNHEADER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< myid <<";";
3730        //
3731        result = conn->Query(myquery.str().c_str());
3732        //
3733        row = result->Next();      
3734        if( !row->GetField(0) || !row->GetField(1)){
3735          //
3736          if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
3737          //
3738          return(0);
3739          //
3740        } else {  
3741          //
3742          UInt_t runhtime = (UInt_t)atoll(row->GetField(0));
3743          UInt_t runttime = (UInt_t)atoll(row->GetField(1));
3744          UInt_t caltime = 0;
3745          //
3746          myquery.str("");
3747          myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
3748          myquery << " order by FROM_TIME asc limit 1;";
3749          //
3750          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
3751          //
3752          //
3753          result = conn->Query(myquery.str().c_str());
3754          //
3755          row = result->Next();      
3756          if( !row ){
3757            caltime = runhtime;
3758          } else {
3759            caltime = (UInt_t)atoll(row->GetField(0));
3760          };
3761          //
3762          myquery.str("");
3763          myquery << " SELECT * from GL_RUN where RUNHEADER_TIME>="<< runttime <<" AND RUNHEADER_TIME<=" ;
3764          myquery << caltime << " order by RUNHEADER_TIME DESC";
3765          //
3766          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
3767          //
3768          result = conn->Query(myquery.str().c_str());
3769          //
3770        };
3771      };
3772      //
3773      if ( !result ) throw -4;
3774      if ( !result->GetRowCount() && IsDebug() ) printf(" No runs to validate \n");
3775      //
3776      Int_t nrow = 0;
3777      GL_RUN* this_run = new GL_RUN();
3778      GL_RUN* next_run = new GL_RUN();
3779      Int_t   nseq_max = 1000;
3780    //  UInt_t* sequence = new UInt_t[100];
3781      vector<UInt_t> sequence(nseq_max);
3782      Int_t   nseq = 0;
3783      Bool_t CHECK = false;
3784      Bool_t this_ONLINE = false;
3785      Bool_t next_ONLINE = false;
3786      UInt_t t1=0,t2=0;
3787      // ---------------------------------------------------------------------------------
3788      // - loop over runs, back in time,
3789      // - select sequences of runs close in time (less than calibtime s apart),
3790      //   which could be preceeded by a calibration
3791      // - check if there might be a missing calibration
3792      // ---------------------------------------------------------------------------------
3793      while(1){
3794              
3795              row = result->Next();
3796              if( row == NULL ) break;
3797              
3798              //------------
3799              //get run info
3800              //------------
3801              this_run->Set_GL_RUN(row);
3802                      
3803              Bool_t this_BAD = false;
3804              if(this_run->GetTRK_CALIB_USED() == 1 || this_run->GetTRK_CALIB_USED() == 2) this_ONLINE = true;
3805              else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;
3806              else{
3807    //                printf("Missing or corrupted header!! \n");
3808                      this_ONLINE = false;
3809                      this_BAD = true;
3810              };
3811    
3812              //-----------------------------------
3813              //compare with previous(next in time)
3814              //-----------------------------------
3815              CHECK = false;
3816              UInt_t interval=0;
3817              
3818              if( nrow != 0){
3819            
3820                      
3821                      t1 = this_run->GetRUNTRAILER_TIME();
3822                      t2 = next_run->GetRUNHEADER_TIME();
3823                      interval = (t2-t1);
3824                      
3825                      if(this_ONLINE && next_ONLINE){                               // this: ON-LINE + next: ON-LINE
3826                              
3827                              if( this_run->ID == next_run->ID_RUN_FRAG ) interval = 0;     //=> run fragments
3828                              
3829                              if( interval >= calibtime )CHECK = true;                      //more than calibtime s => there might be a calibration
3830                              
3831                              if( !CHECK && this_run->VALIDATION ){
3832                                      for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
3833                                      nseq=0;
3834                              }
3835                      
3836                      }else if( !this_ONLINE && next_ONLINE) {              // this: DEFAULT + next:ON-LINE
3837                              
3838                              CHECK = true;
3839    
3840                      }else if( !next_ONLINE ){                                             // this:ANY + next:DEFAULT
3841                              
3842                              assignVALIDATION(next_run->ID,true);
3843                              nseq=0;
3844                      }
3845              }
3846    
3847              //----------------------------
3848              //check run sequence for calib
3849              //----------------------------
3850              if( CHECK ){
3851                      // check if calibration exists
3852                      if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);
3853                      Bool_t MISSING = MissingTRK_CALIB(t1,t2);
3854                      for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],!MISSING);
3855                      nseq=0;
3856              };
3857              //--------------
3858              //store run info
3859              //--------------
3860              *next_run   = *this_run;
3861              next_ONLINE = this_ONLINE;
3862              if( !this_BAD ){
3863                      if(nseq < nseq_max){
3864                              sequence[nseq] = this_run->ID;
3865                              nseq++;
3866                      }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);
3867              };
3868              
3869              if ( IsDebug() ) printf("%i Run %u \n",nrow,this_run->ID);
3870              nrow++;
3871              
3872      };
3873      delete this_run;
3874      delete next_run;
3875      //
3876      return(0);
3877    };
3878    /**
3879     * Check if there might be a missing tracker calibration in a given time interval
3880     * @param t1 From absolute time
3881     * @param t2 To absolute time
3882     * @return true if there might be a missing calibration
3883     */
3884    Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
3885            
3886            GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();
3887            
3888            // get the closest VALIDATED calibration before the run start (t2)
3889            if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true);      //>>> missing
3890            
3891            if ( trkcalib->TO_TIME  < t2 ) return(true);                                    //>>> missing
3892            
3893            //==============================================================
3894            // Check is done first on the basis of time between calibration,
3895            // which should be equal to the time between ascending-nodes.
3896            //==============================================================
3897            if ( t2 - trkcalib->FROM_TIME > 5700) {
3898                    if ( IsDebug() )printf("Long time between calib and run start %u :-( ==> there might be a missing calib \n",t2 - trkcalib->FROM_TIME);
3899            //==============================================================
3900            // there might be a missing calibration, due to:
3901            // - MM full
3902            // - corrupted packets
3903            // - loss of data
3904            // There is an exception in case a download was done during ascending node
3905            //==============================================================
3906                    Bool_t DOWNLOAD = false;
3907                    // check if the calib was skipped becouse of download .... DA FARE!!
3908                    if(DOWNLOAD)return(false);
3909                    
3910                    return(true);                                   //>>> missing
3911                    
3912            };
3913            
3914            //==============================================================
3915            // If the last calibration is close to the run less than this time,
3916            // it is enough to say that there are no missing calibrations
3917            //==============================================================
3918            // the long time interval bewteen runs might be due to download
3919            if ( IsDebug() )printf("Short time between calib and run start %u :-) ==> OK! \n",t2 - trkcalib->FROM_TIME);
3920            return(false);
3921            
3922    };
3923    /**
3924     * Assign VALIDATION value to a GL_RUN entry
3925     * @param idrun Run ID
3926     * @param validation true/false
3927     */
3928    Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){
3929            TSQLResult *result = 0;
3930            stringstream oss;
3931            oss.str("");
3932            oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";
3933            //
3934    //      if ( IsDebug() )
3935    //      printf(" Set VALIDATION = %i for run %i \n",validation,idrun);
3936            if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());
3937            result = conn->Query(oss.str().c_str());
3938            if ( !result ) throw -4;
3939            return(0);
3940    }
3941    
3942    
3943    
3944    // Insert TLEs from file tlefilename in the table GL_TLE in the db
3945    // opened by conn, sorting them by date from older to newer, if each
3946    // TLE has not been alread inserted.
3947    Int_t PamelaDBOperations::populateTLE()//(TSQLServer *conn, char *tleFile)
3948    {
3949      fstream tlefile(tlefilename, ios::in);
3950    
3951      if ( !tlefile ) throw -7;
3952    
3953      vector<cTle*> ctles;
3954      vector<cTle*>::iterator iter;
3955      int present = 0;
3956    
3957      // Get three lines from tlefile, create a cTle object and put it
3958      // into ctles
3959      while(1) {
3960        cTle *tlef;
3961        string str1, str2, str3;
3962    
3963        getline(tlefile, str1);
3964        if(tlefile.eof()) break;
3965    
3966        getline(tlefile, str2);
3967        if(tlefile.eof()) break;
3968    
3969        getline(tlefile, str3);
3970        if(tlefile.eof()) break;
3971    
3972        // We now have three good lines for a cTle.
3973        tlef = new cTle(str1, str2, str3);
3974        ctles.push_back(tlef);
3975      }
3976    
3977      tlefile.close();
3978    
3979      // Sort by date
3980      sort(ctles.begin(), ctles.end(), compTLE);
3981    
3982      // Now we insert each TLE into the db
3983      for(iter = ctles.begin(); iter != ctles.end(); iter++) {
3984        cTle *tle = *iter;
3985    
3986        // Do nothing if it's already present in the db.  Just increase
3987        // the counter present.
3988        if (! isTlePresent(tle))
3989          {
3990            int status = insertTle(tle);
3991    
3992            // Insert query failed.  Return 1.
3993            if(status == EXIT_FAILURE) {
3994              
3995              if( IsDebug() ) {
3996                cerr << "Error: inserting TLE:" << endl
3997                     << tle->getName() << endl
3998                     << tle->getLine1() << endl
3999                     << tle->getLine2() << endl;
4000              }
4001    
4002              throw -4;
4003              return 1;
4004            }
4005    
4006          }
4007        else
4008          present++;
4009    
4010      }
4011    
4012      int inserted = ctles.size() - present;  // Number of inserted TLE.
4013      if ( IsDebug() )
4014        cout << "\nProcessed TLEs ranging from " << getTleDatetime(ctles[0]) << " to " << getTleDatetime(ctles[ctles.size()-1]) << "." << endl
4015             << inserted << " newly inserted TLEs out of " << ctles.size() << " processed." << endl;
4016    
4017      ctles.clear();
4018    
4019    
4020      // Return 2 if no new TLE has been inserted.  0 otherwise.
4021      if(! inserted ) return 2;
4022      return 0;
4023    }
4024    
4025    
4026    // Insert tle in the table GL_TLE using the connection conn.
4027    Int_t PamelaDBOperations::insertTle(cTle *tle)
4028    {
4029      stringstream oss;
4030      TSQLResult *result = 0;
4031    
4032      oss.str("");
4033      oss << " INSERT INTO GL_TLE (TLE1, TLE2, TLE3, FROM_TIME)"
4034          << " VALUES ( '"
4035          << tle->getName() << "', '"
4036          << tle->getLine1() << "', '"
4037          << tle->getLine2() << "', '"
4038          << getTleDatetime(tle) << "')";
4039    
4040      //  cout << oss.str().c_str() << endl;
4041      result = conn->Query(oss.str().c_str());
4042      if (result == NULL)
4043        return EXIT_FAILURE;
4044    
4045      return EXIT_SUCCESS;
4046    }
4047    
4048    
4049    // Return whether tle is already in the db connected by conn.
4050    bool PamelaDBOperations::isTlePresent(cTle *tle)
4051    {
4052      stringstream oss;
4053      TSQLResult *result = 0;
4054    
4055      oss.str("");
4056      oss << "SELECT * FROM GL_TLE WHERE FROM_TIME = '"
4057          << getTleDatetime(tle) << "'";
4058    
4059      result = conn->Query(oss.str().c_str());
4060      if (result == NULL) throw -4;
4061    
4062      if (result->GetRowCount())
4063        return true;
4064      else
4065        return false;
4066    }
4067    
4068    
4069    // Return whether the first TLE is dated early than the second
4070    bool compTLE (cTle *tle1, cTle *tle2)
4071    {
4072      return getTleJulian(tle1) < getTleJulian(tle2);
4073    }
4074    
4075    
4076    // Return the date of the tle using the format (year-2000)*1e3 +
4077    // julian day.  e.g. 6365 is the 31th Dec 2006.
4078    // It does *not* return a cJulian date.
4079    float getTleJulian(cTle *tle) {
4080      return tle->getField(cTle::FLD_EPOCHYEAR)*1e3 + tle->getField(cTle::FLD_EPOCHDAY);
4081    }
4082    
4083    
4084    // Return a string like YYYY-MM-DD hh:mm:ss, usable for mysql datetime
4085    // format.
4086    string getTleDatetime(cTle *tle)
4087    {
4088      int year, mon, day, hh, mm, ss;
4089      double dom; // day of month (is double!)
4090      stringstream date; // date in datetime format
4091    
4092      // create a cJulian from the date in tle
4093      cJulian jdate = cJulian( 2000 + (int) tle->getField(cTle::FLD_EPOCHYEAR), tle->getField(cTle::FLD_EPOCHDAY));
4094    
4095      // get year, month, day of month
4096      jdate.getComponent(&year, &mon, &dom);
4097    
4098      // build a datetime YYYY-MM-DD hh:mm:ss
4099      date.str("");
4100      day = (int) floor(dom);
4101      hh = (int) floor( (dom - day) * 24);
4102      mm = (int) floor( ((dom - day) * 24 - hh) * 60);
4103      ss = (int) floor( ((((dom - day) * 24 - hh) * 60 - mm) * 60));
4104      //  ms = (int) floor( (((((dom - day) * 24 - hh) * 60 - mm) * 60) - ss) * 1000);
4105    
4106      date << year << "-" << mon << "-" << day << " " << hh << ":" << mm << ":" << ss;
4107    
4108      return date.str();
4109    }
4110    
4111    /**
4112     * Remove a file from the DB, delete on cascade all entries related to that file
4113     * rearrange GL_RUN and GL_XXX_CALIB tables, turn off validation till the following
4114     * calibration
4115     **/
4116    Int_t PamelaDBOperations::removeFile(TString remfile){
4117      //
4118      // Determine ID_ROOT_L0 and ID_RAW
4119      //
4120      TSQLResult *pResult;
4121      TSQLRow *Row;
4122      stringstream myquery;
4123      //  
4124      myquery.str("");
4125      myquery << " SELECT ID, ID_RAW FROM GL_ROOT where NAME='"<<remfile.Data() <<"';";
4126      //
4127      pResult = conn->Query(myquery.str().c_str());
4128      //
4129      Row = pResult->Next();      
4130      if( !Row ){
4131        if ( strcmp(remfile.Data(),GetRootName().Data()) ){
4132          if ( IsDebug() ) printf(" No file to be removed even if option \"-remove file\" was used!!\n");
4133          return(1);
4134        };
4135        if ( IsDebug() ) printf(" No file to be removed (force mode)! \n");
4136        return(0);
4137      };
4138      //
4139      this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));
4140      this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));
4141      //
4142      this->ValidationOFF();
4143      //
4144      this->RemoveCALIBS();
4145      //
4146      this->RemoveRUNS();
4147      //
4148      this->RemoveFILES();
4149      //
4150      this->SetID_ROOT(0);
4151      this->SetID_RAW(0);
4152      //
4153      return(0);
4154    };
4155    
4156    /**
4157     *
4158     * Set validation bit to zero for runs following the removing file till
4159     * 1) a run with TRK_CALIB_USED=140
4160     * 2) a run with VALIDATION = 0
4161     * 3) the next calibration
4162     *
4163     **/
4164    void PamelaDBOperations::ValidationOFF(){
4165      TSQLResult *pResult;
4166      TSQLRow *Row;
4167      stringstream myquery;
4168      Int_t unv = 0;
4169      //select ID from GL_RUN where RUNHEADER_TIME>=1152671382 AND (VALIDATION=0 OR TRK_CALIB_USED=104) order by RUNHEADER_TIME asc limit 1;
4170      myquery.str("");
4171      myquery << " SELECT MAX(RUNTRAILER_TIME) FROM GL_RUN WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
4172      //
4173      pResult = conn->Query(myquery.str().c_str());
4174      //
4175      Row = pResult->Next();      
4176      if( !Row->GetField(0) ){
4177        //
4178        if ( IsDebug() ) printf(" NO RUN ASSOCIATED TO THIS FILE! \n");
4179        //
4180      } else {  
4181        //
4182        UInt_t runhtime = (UInt_t)atoll(Row->GetField(0));
4183        UInt_t caltime = 0;
4184        //
4185        myquery.str("");
4186        myquery << " SELECT FROM_TIME FROM GL_TRK_CALIB where FROM_TIME>" <<runhtime;
4187        myquery << " order by FROM_TIME asc limit 1;";
4188        //
4189        if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4190        //
4191        //
4192        delete pResult;
4193        pResult = conn->Query(myquery.str().c_str());
4194        //
4195        Row = pResult->Next();      
4196        if( !Row ){
4197          caltime = runhtime;
4198        } else {
4199          caltime = (UInt_t)atoll(Row->GetField(0));
4200        };
4201        //
4202        myquery.str("");
4203        myquery << " SELECT ID,RUNHEADER_TIME from GL_RUN where RUNHEADER_TIME>="<< runhtime <<" AND (VALIDATION=0 OR TRK_CALIB_USED=104 OR RUNHEADER_TIME>" ;
4204        myquery << caltime << ") order by RUNHEADER_TIME asc LIMIT 1";
4205        //
4206        if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4207        //
4208        pResult = conn->Query(myquery.str().c_str());
4209        //
4210        Row = pResult->Next();      
4211        if( !Row ){
4212          //
4213          if ( IsDebug() ) printf(" NO RUN NEED TO BE UNVALIDATED \n");
4214          //
4215        } else {
4216          myquery.str("");
4217          myquery << " SELECT ID from GL_RUN where RUNHEADER_TIME<"<< Row->GetField(1) <<" AND ";
4218          myquery << " RUNHEADER_TIME>=" <<runhtime;
4219          myquery << " order by RUNHEADER_TIME asc;";
4220          //
4221          if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4222          //
4223          pResult = conn->Query(myquery.str().c_str());
4224          //
4225          Row = pResult->Next();  
4226          while ( Row ){
4227            //      
4228            unv++;
4229            this->assignVALIDATION((UInt_t)atoll(Row->GetField(0)), false);
4230            Row = pResult->Next();  
4231            //
4232          };
4233        };
4234      };
4235      if ( IsDebug() ) printf(" %u runs have been unvalidated \n",unv);
4236    };
4237    
4238    /**
4239     *
4240     * Rearrange GL_RUN table and remove runs
4241     *
4242     **/
4243    void PamelaDBOperations::RemoveRUNS(){
4244      TSQLResult *pResult;
4245      TSQLRow *Row;
4246      stringstream myquery;
4247      UInt_t drun = 0;
4248      GL_RUN *delrun = new GL_RUN();
4249      //
4250      myquery.str("");
4251      myquery << " SELECT ID FROM GL_RUN where ID_RUN_FRAG=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4252      //
4253      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4254      //
4255      pResult = conn->Query(myquery.str().c_str());
4256      //
4257      Row = pResult->Next();    
4258      //
4259      //
4260      if ( !Row ){
4261        if ( IsDebug() ) printf(" No run with ID_RUN_FRAG=0 belonged to this file \n");
4262      } else {
4263        if ( IsDebug() ) printf(" Deleting run from GL_RUN table \n");    
4264        while ( Row ){
4265          delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
4266          if ( IsDebug() ) printf(" del run %u \n",(UInt_t)atoll(Row->GetField(0)));
4267          drun++;
4268          Row = pResult->Next();    
4269        };
4270      };
4271      //
4272      //
4273      myquery.str("");
4274      myquery << " SELECT ID,ID_RUN_FRAG FROM GL_RUN where ID_RUN_FRAG!=0 and ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4275      //
4276      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4277      //
4278      pResult = conn->Query(myquery.str().c_str());
4279      //
4280      Row = pResult->Next();    
4281      //
4282      if ( !Row ){
4283        if ( IsDebug() ) printf(" No run with ID_RUN_FRAG!=0 belonged to this file \n");
4284      } else {
4285        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN table \n");    
4286        while ( Row ){
4287          if ( IsDebug() ) printf(" restore run %u \n",(UInt_t)atoll(Row->GetField(1)));
4288          delrun->RestoreRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN_FRAGMENTS");
4289          if ( IsDebug() ) printf(" del run %u \n",(UInt_t)atoll(Row->GetField(1)));
4290          delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(1)),"GL_RUN");
4291          if ( (UInt_t)atoll(Row->GetField(1)) != (UInt_t)atoll(Row->GetField(0)) ){
4292            if ( IsDebug() ) printf(" del run %u \n",(UInt_t)atoll(Row->GetField(0)));
4293            delrun->DeleteRun(conn,(UInt_t)atoll(Row->GetField(0)),"GL_RUN");
4294          };
4295          drun++;
4296          Row = pResult->Next();    
4297        };
4298      };
4299      //
4300      if ( IsDebug() ) printf(" Deleted %i run(s) from GL_RUN table \n",drun);    
4301      //
4302      //
4303      //
4304      drun = 0;
4305      //
4306      myquery.str("");
4307      myquery << " SELECT ID_TRASH FROM GL_RUN_TRASH where BELONGED_TO='GL_RUN_FRAGMENTS' AND ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4308      //
4309      pResult = conn->Query(myquery.str().c_str());
4310      //
4311      Row = pResult->Next();    
4312      //
4313      if ( !Row ){
4314        if ( IsDebug() ) printf(" No run from GL_RUN_FRAGMENTS table in the trash table for this file \n");
4315      } else {
4316        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_TRASH table \n");    
4317        while ( Row ){
4318          if ( IsDebug() ) printf(" del run idtrash %u \n",(UInt_t)atoll(Row->GetField(0)));
4319          myquery.str("");
4320          myquery << " DELETE FROM GL_RUN_TRASH where ID_TRASH=" << Row->GetField(0) <<";";      
4321          conn->Query(myquery.str().c_str());
4322          drun++;
4323          Row = pResult->Next();    
4324        };
4325      };
4326      //  
4327      if ( IsDebug() ) printf(" Deleted %u run(s) from GL_RUN_TRASH table \n",drun);    
4328      //
4329      //
4330      //
4331      drun = 0;
4332      //
4333      myquery.str("");
4334      myquery << " SELECT ID FROM GL_RUN_FRAGMENTS where ID_ROOT_L0=" <<this->GetID_ROOT() <<";";
4335      //
4336      pResult = conn->Query(myquery.str().c_str());
4337      //
4338      Row = pResult->Next();    
4339      //
4340      if ( !Row ){
4341        if ( IsDebug() ) printf(" No run in the GL_RUN_FRAGMENTS table for this file \n");
4342      } else {
4343        if ( IsDebug() ) printf(" Deleting run fragments from GL_RUN_FRAGMENTS table \n");    
4344        while ( Row ){
4345          if ( IsDebug() ) printf(" del run %u \n",(UInt_t)atoll(Row->GetField(0)));
4346          myquery.str("");
4347          myquery << " DELETE FROM GL_RUN_FRAGMENTS where ID=" << Row->GetField(0) <<";";
4348          conn->Query(myquery.str().c_str());
4349          drun++;
4350          Row = pResult->Next();    
4351        };
4352      };
4353      //  
4354      if ( IsDebug() ) printf(" Deleted %u run(s) from GL_RUN_FRAGMENTS table \n",drun);    
4355      //
4356      //
4357      //
4358      delete delrun;
4359      //
4360    };
4361    
4362    
4363    /**
4364     *
4365     * Rearrange calibration tables
4366     *
4367     **/
4368    void PamelaDBOperations::RemoveFILES(){
4369      stringstream myquery;
4370      //
4371      myquery.str("");
4372      myquery << " DELETE FROM GL_RAW WHERE ID=" <<this->GetID_RAW() <<";";
4373      //
4374      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
4375      //
4376      conn->Query(myquery.str().c_str());
4377      //
4378    };
4379    
4380    /**
4381     *
4382     * Rearrange calibration tables
4383     *
4384     **/
4385    void PamelaDBOperations::RemoveCALIBS(){
4386      TSQLResult *pResult;
4387      TSQLRow *Row;
4388      stringstream myquery;
4389      //  
4390      //
4391      // Calorimeter
4392      //
4393      for (Int_t section = 0; section < 4; section++){
4394        myquery.str("");
4395        myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_CALO_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<" AND ";
4396        myquery << " SECTION=" << section << ";";
4397        //
4398        pResult = conn->Query(myquery.str().c_str());
4399        //
4400        Row = pResult->Next();      
4401        if( !Row->GetField(0) || !Row->GetField(1) ){
4402          //
4403          if ( IsDebug() ) printf(" NO CALO CALIBRATION SECTION %i ASSOCIATED TO THIS FILE! \n",section);
4404          //
4405        } else {
4406          //
4407          myquery.str("");
4408          myquery << " UPDATE GL_CALO_CALIB SET TO_TIME=" << Row->GetField(1);
4409          myquery << " WHERE TO_TIME="<< Row->GetField(0) << " AND ";
4410          myquery << " SECTION=" << section << ";";
4411          //
4412          pResult = conn->Query(myquery.str().c_str());
4413          //
4414          if( !pResult ){
4415            //
4416            if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
4417            //
4418            throw -4;
4419            //
4420          };
4421          //
4422        };
4423      };
4424      myquery.str("");
4425      myquery << " DELETE FROM GL_CALO_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4426      //
4427      pResult = conn->Query(myquery.str().c_str());
4428      //
4429      if( !pResult ){
4430        //
4431        if ( IsDebug() ) printf(" ERROR DELETING CALO CALIBRATIONS \n");
4432        //
4433        throw -4;
4434        //
4435      };
4436      //
4437      // Tracker
4438      //
4439      myquery.str("");
4440      myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_TRK_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
4441      //
4442      pResult = conn->Query(myquery.str().c_str());
4443      //
4444      Row = pResult->Next();      
4445      if( !Row->GetField(0) || !Row->GetField(1) ){
4446        //
4447        if ( IsDebug() ) printf(" NO TRK CALIBRATION ASSOCIATED TO THIS FILE! \n");
4448        //
4449      } else {
4450        //
4451        myquery.str("");
4452        myquery << " UPDATE GL_TRK_CALIB SET TO_TIME=" << Row->GetField(1);
4453        myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
4454        //
4455        pResult = conn->Query(myquery.str().c_str());
4456        //
4457        if( !pResult ){
4458          //
4459          if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
4460          //
4461          throw -4;
4462          //
4463        };
4464        //
4465        myquery.str("");
4466        myquery << " DELETE FROM GL_TRK_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4467        //
4468        pResult = conn->Query(myquery.str().c_str());
4469        //
4470        if( !pResult ){
4471          //
4472          if ( IsDebug() ) printf(" ERROR DELETING TRK CALIBRATIONS \n");
4473          //
4474          throw -4;
4475          //
4476        };
4477      };
4478      //
4479      //
4480      // S4
4481      //
4482      myquery.str("");
4483      myquery << " SELECT MIN(FROM_TIME),MAX(TO_TIME) FROM GL_S4_CALIB WHERE ID_ROOT_L0="<< this->GetID_ROOT() <<";";
4484      //
4485      pResult = conn->Query(myquery.str().c_str());
4486      //
4487      Row = pResult->Next();      
4488      if( !Row->GetField(0) || !Row->GetField(1) ){
4489        //
4490        if ( IsDebug() ) printf(" NO S4 CALIBRATION ASSOCIATED TO THIS FILE! \n");
4491        //
4492      } else {
4493        //
4494        myquery.str("");
4495        myquery << " UPDATE GL_S4_CALIB SET TO_TIME=" << Row->GetField(1);
4496        myquery << " WHERE TO_TIME="<< Row->GetField(0) << ";";
4497        //
4498        pResult = conn->Query(myquery.str().c_str());
4499        //
4500        if( !pResult ){
4501          //
4502          if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
4503          //
4504          throw -4;
4505          //
4506        };
4507        //
4508        myquery.str("");
4509        myquery << " DELETE FROM GL_S4_CALIB WHERE ID_ROOT_L0=" << this->GetID_ROOT();
4510        //
4511        pResult = conn->Query(myquery.str().c_str());
4512        //
4513        if( !pResult ){
4514          //
4515          if ( IsDebug() ) printf(" ERROR DELETING S4 CALIBRATIONS \n");
4516          //
4517          throw -4;
4518          //
4519        };
4520        //
4521      };
4522    };
4523    
4524    /**
4525     *
4526     * Rearrange calibration tables
4527     *
4528     **/
4529    UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh ){
4530    
4531        Int_t vorder[]={5,5,3,3,4,4,2,2,1,1,0,0};
4532        UInt_t timeaftercalib=120000; //2000;
4533    //  ----------
4534    //  Check CRCs
4535    //  ----------
4536        for(Int_t ipkt=0; ipkt<6; ipkt++){
4537            if( caltrk->crc_hcal[ipkt] )return 0; // :-(
4538            for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] )return 0; // :-(
4539        }
4540    //  -----------------------
4541    //  Check missing packets:
4542    //  -----------------------
4543    //    Readout order:
4544    //    ------------------
4545    //    DSP   packet board
4546    //    ------------------
4547    //    12    0      1
4548    //    10    1      1
4549    //     8    2      1
4550    //     4    3      1
4551    //     6    4      1
4552    //     2    5      1
4553    //    ------------------
4554    //    11    0      2
4555    //     9    1      2
4556    //     7    2      2
4557    //     3    3      2
4558    //     5    4      2
4559    //     1    5      2
4560    //    ------------------
4561    //  -------------------------------------------------
4562    //  Check if it is first or second calibration packet
4563    //  -------------------------------------------------
4564        UInt_t build=0;
4565        TString classname = caltrk->GetName();
4566        UInt_t base=0;
4567        UInt_t mask=0;
4568        if(classname.Contains("CalibTrk1Event")){
4569            base=12;
4570            mask=0x03F000;
4571        }
4572        if(classname.Contains("CalibTrk2Event")){
4573            base=18;
4574            mask=0xFC0000;
4575        }
4576    //  -------------------------------------------------
4577    //  Count number of packets and set build variable
4578    //  -------------------------------------------------
4579        Int_t  npkts=0;
4580        for(Int_t ipkt=0; ipkt<6; ipkt++){
4581            if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
4582                npkts++;
4583                build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );
4584            }
4585        }
4586    //    if( npkts==6 )return 1; // :-)
4587    
4588    //    cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime()<<endl;
4589    
4590    //  -----------------------------------------------
4591    //  If missing packets: check the acq configuration
4592    //  (some DSPs might be excluded from acquisition)
4593    //  -----------------------------------------------
4594    
4595    //  -----------------------------------------------
4596    //  retrieve the first run header after calib
4597    //  -----------------------------------------------
4598         PacketType *pctp;
4599         EventCounter *cod;
4600         cod = eh->GetCounter();
4601         Int_t irun = cod->Get(pctp->RunHeader);
4602         TTree *rh=(TTree*)file->Get("RunHeader");
4603         if ( !rh || rh->IsZombie() ) throw -17;
4604         if( rh->GetEntries() == irun ){
4605              if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (1)  -- cannot validate :-( "<<endl;
4606             return 0; // :-(
4607         }
4608    
4609         RunHeaderEvent *run  = 0;
4610         EventHeader    *hrun = 0;
4611         rh->SetBranchAddress("RunHeader", &run);
4612         rh->SetBranchAddress("Header", &hrun);
4613         rh->GetEntry(irun);
4614    //     cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime() << " Run " << hrun->GetPscuHeader()->GetOrbitalTime() <<endl;
4615    
4616         if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){
4617              if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (2) -- cannot validate :-( "<<endl;
4618             return 0; // :-(
4619         }
4620        
4621         if( !run->RM_ACQ_AFTER_CALIB ){
4622              if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) RM_ACQ_AFTER_CALIB=0    -- cannot validate :-( "<<endl;
4623             return 0; // :-(
4624         }
4625    
4626         UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());
4627         if( dtime > timeaftercalib ){
4628             if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;
4629             return 0; // :-(
4630         }
4631        
4632    
4633    
4634         if( (run->ACQ_BUILD_INFO & mask) != build ){
4635             if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) ACQ_BUILD_INFO= >>> "<<hex << (run->ACQ_BUILD_INFO&mask) << " != "<< build << dec<<endl;
4636             return 0; // :-(
4637         }
4638         return 1; // :-)
4639    
4640    }
4641    
4642    /**
4643     *
4644     * Check the DB (only for overlapping runs at the moment)
4645     *
4646     **/
4647    UInt_t PamelaDBOperations::Check(){
4648      //
4649      UInt_t test = 0;
4650      //
4651      UInt_t thisrht = 0;
4652      UInt_t thisrtt = 0;
4653      UInt_t thisid = 0;
4654      UInt_t prevrht = 0;
4655      UInt_t prevrtt = 0;
4656      UInt_t previd = 0;
4657      //
4658      UInt_t prevl0id = 0;
4659      UInt_t thisl0id = 0;
4660      //
4661      stringstream oss;
4662      TSQLResult *result = 0;
4663      TSQLRow    *row    = 0;
4664      TSQLResult *result2 = 0;
4665      TSQLRow    *row2    = 0;
4666      oss.str("");
4667      oss << "SELECT ID,ID_ROOT_L0,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN order by RUNHEADER_TIME asc;";
4668      //  oss << "SELECT ID,RUNHEADER_TIME,RUNTRAILER_TIME FROM GL_RUN where ID>10170 and ID<10190 order by RUNHEADER_TIME asc;";
4669      result = conn->Query(oss.str().c_str());
4670      //
4671      if ( !result ) throw -4;;
4672      //
4673      row = result->Next();
4674      //
4675      while ( row ){
4676        thisid = (UInt_t)atoll(row->GetField(0));
4677        thisl0id = (UInt_t)atoll(row->GetField(1));
4678        thisrht = (UInt_t)atoll(row->GetField(2));
4679        thisrtt = (UInt_t)atoll(row->GetField(3));
4680        //
4681        //    if ( thisrht < prevrtt || thisrtt < prevrht || thisrht > thisrtt && !(!prevrht && !prevrtt &&!previd) ){
4682        //    if ( (thisrht < prevrtt || thisrtt < prevrht || thisrht > thisrtt) && (thisrht != prevrht) ){
4683        if ( (thisrht < prevrtt) && (thisrht != prevrht) ){
4684          if ( IsDebug() ) printf(" IDprev %u ID %u    prevrht %u prevrtt %u  thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
4685          printf(" CHECK n.1 TIME SCREW of %u s AROUND RUNs %u and %u \n",(thisrht-prevrtt),previd,thisid);
4686          TString prevf = "";
4687          TString thisf = "";
4688          oss.str("");
4689          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
4690          result2 = conn->Query(oss.str().c_str());
4691          if ( !result2 ) throw -4;;
4692          row2 = result2->Next();
4693          prevf = (TString)row2->GetField(0);
4694          oss.str("");
4695          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
4696          result2 = conn->Query(oss.str().c_str());
4697          if ( !result2 ) throw -4;;
4698          row2 = result2->Next();
4699          thisf = (TString)row2->GetField(0);
4700          if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
4701          test = 1;
4702        };
4703        //
4704        if ( (thisrtt < prevrht) && (thisrht != prevrht) ){
4705          if ( IsDebug() ) printf(" IDprev %u ID %u    prevrht %u prevrtt %u  thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
4706          printf(" CHECK n.2 TIME SCREW of %u s AROUND RUNs %u and %u \n",(thisrtt-prevrht),previd,thisid);
4707          TString prevf = "";
4708          TString thisf = "";
4709          oss.str("");
4710          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
4711          result2 = conn->Query(oss.str().c_str());
4712          if ( !result2 ) throw -4;;
4713          row2 = result2->Next();
4714          prevf = (TString)row2->GetField(0);
4715          oss.str("");
4716          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
4717          result2 = conn->Query(oss.str().c_str());
4718          if ( !result2 ) throw -4;;
4719          row2 = result2->Next();
4720          thisf = (TString)row2->GetField(0);
4721          if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
4722          test = 1;
4723        };
4724        //
4725        if ( (thisrht > thisrtt) && (thisrht != prevrht) ){
4726          if ( IsDebug() ) printf(" IDprev %u ID %u    prevrht %u prevrtt %u  thisrht %u thisrtt %u \n",previd,thisid,prevrht,prevrtt,thisrht,thisrtt);
4727          printf(" CHECK n.3 TIME SCREW of %u s AROUND RUNs %u and %u \n",(thisrht-thisrtt),previd,thisid);
4728          TString prevf = "";
4729          TString thisf = "";
4730          oss.str("");
4731          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)prevl0id <<";";
4732          result2 = conn->Query(oss.str().c_str());
4733          if ( !result2 ) throw -4;;
4734          row2 = result2->Next();
4735          prevf = (TString)row2->GetField(0);
4736          oss.str("");
4737          oss << "SELECT NAME FROM GL_ROOT where ID=" << (UInt_t)thisl0id <<";";
4738          result2 = conn->Query(oss.str().c_str());
4739          if ( !result2 ) throw -4;;
4740          row2 = result2->Next();
4741          thisf = (TString)row2->GetField(0);
4742          if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
4743          test = 1;
4744        };
4745    
4746        //
4747        prevrht = thisrht;
4748        prevrtt = thisrtt;
4749        previd = thisid;
4750        prevl0id = thisl0id;
4751        row = result->Next();
4752      };
4753      //
4754      return(test);
4755      //
4756  };  };

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

  ViewVC Help
Powered by ViewVC 1.1.23