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

Diff of /chewbacca/YodaProfiler/src/PamelaDBOperations.cpp

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

revision 1.1 by mocchiut, Tue Sep 23 07:20:33 2008 UTC revision 1.16 by mocchiut, Fri Dec 12 10:49:54 2008 UTC
# Line 58  string getTleDatetime(cTle*); Line 58  string getTleDatetime(cTle*);
58   * @param debug        debug flag.   * @param debug        debug flag.
59   * @param tlefilename  ascii file with TLE 3 line elements.   * @param tlefilename  ascii file with TLE 3 line elements.
60   */   */
61  PamelaDBOperations::PamelaDBOperations(TString host, TString user, TString password, TString filerawname, TString filerootname, UInt_t boot, UInt_t tsync, UInt_t obt0, Bool_t debug, TString tlefilename, UInt_t dwinput, Bool_t staticp, Bool_t gpamela){  PamelaDBOperations::PamelaDBOperations(TString host, TString user, TString password, TString filerawname, TString filerootname, UInt_t boot, UInt_t tsync, UInt_t obt0, Bool_t debug, TString tlefilename, UInt_t dwinput, Bool_t staticp, Bool_t gpamela, Bool_t keepenv){
62    //    //
63    chewbacca = false;    chewbacca = false;
64    chminentry = 0;    chminentry = 0;
# Line 76  PamelaDBOperations::PamelaDBOperations(T Line 76  PamelaDBOperations::PamelaDBOperations(T
76      //      //
77    };    };
78    //    //
79      KEEPENV = false;
80      if ( keepenv ) KEEPENV=true;
81    STATIC=false;    STATIC=false;
82    if ( staticp ) STATIC=true;    if ( staticp ) STATIC=true;
83    //    //
# Line 99  PamelaDBOperations::PamelaDBOperations(T Line 101  PamelaDBOperations::PamelaDBOperations(T
101    if (INSERT_RAW) SetRawName(filerawname);    if (INSERT_RAW) SetRawName(filerawname);
102    //    //
103    INSERT_ROOT = !filerootname.IsNull();    INSERT_ROOT = !filerootname.IsNull();
104      if ( INSERT_ROOT ) this->SetRootName(filerootname);
105    this->SetOrbitNo(dwinput);    this->SetOrbitNo(dwinput);
106    //    //
107    this->SetID_RAW(0);    this->SetID_RAW(0);
# Line 138  void PamelaDBOperations::OpenL0File(TStr Line 141  void PamelaDBOperations::OpenL0File(TStr
141        TString chfile;        TString chfile;
142        UInt_t ridn = 0;        UInt_t ridn = 0;
143        qu.str("");        qu.str("");
144        qu << "SELECT ROOT_ID_N,PKT_NUMBER_INIT,PKT_NUMBER_FINAL,PKT_OBT_INIT,PKT_OBT_FINAL from ROOT_TABLE_MERGING where ID_N=" << chID << ";";        qu << "SELECT ROOT_ID_N,PKT_NUMBER_INIT,PKT_NUMBER_FINAL,PKT_OBT_INIT,PKT_OBT_FINAL,INSERTED_BY from ROOT_TABLE_MERGING where ID_N=" << chID << ";";
145        if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());        if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
146        result = conn->Query(qu.str().c_str());        result = conn->Query(qu.str().c_str());
147        if ( result ){        if ( result ){
# Line 149  void PamelaDBOperations::OpenL0File(TStr Line 152  void PamelaDBOperations::OpenL0File(TStr
152            chpktmax = (UInt_t)atoll(row->GetField(2));            chpktmax = (UInt_t)atoll(row->GetField(2));
153            chobtmin = (UInt_t)atoll(row->GetField(3));            chobtmin = (UInt_t)atoll(row->GetField(3));
154            chobtmax = (UInt_t)atoll(row->GetField(4));            chobtmax = (UInt_t)atoll(row->GetField(4));
155              chiby = (TString)(row->GetField(5));
156          } else {          } else {
157            throw -84;            throw -84;
158          };          };
# Line 163  void PamelaDBOperations::OpenL0File(TStr Line 167  void PamelaDBOperations::OpenL0File(TStr
167        if ( result2 ){        if ( result2 ){
168          row2 = result2->Next();          row2 = result2->Next();
169          if ( row2 ){          if ( row2 ){
170            chpath = (TString)gSystem->ExpandPathName(row2->GetField(0))+'/';            if ( KEEPENV ){
171                chpath = (TString)(row2->GetField(0))+'/';
172              } else {
173                chpath = (TString)gSystem->ExpandPathName(row2->GetField(0))+'/';
174              };
175            chfile = (TString)(row2->GetField(1));            chfile = (TString)(row2->GetField(1));
176            chobtts = (UInt_t)atoll(row2->GetField(2));            chobtts = (UInt_t)atoll(row2->GetField(2));
177            chlastts = (UInt_t)atoll(row2->GetField(3));            chlastts = (UInt_t)atoll(row2->GetField(3));
# Line 182  void PamelaDBOperations::OpenL0File(TStr Line 190  void PamelaDBOperations::OpenL0File(TStr
190          throw -85;          throw -85;
191        };        };
192        filerootname = chpath + chfile;// + ".root";        filerootname = chpath + chfile;// + ".root";
       if ( debug ) printf(" chewbacca: filename is %s \n",filerootname.Data());  
193      };      };
194      this->SetRootName(filerootname);      this->SetRootName(filerootname);
     file = TFile::Open(this->GetRootName().Data());  
   } else {  
     this->SetRootName("");  
195    };    };
196      if ( debug ) printf(" Filename is %s \n",filerootname.Data());
197      file = TFile::Open(this->GetRootName().Data());
198      //  } else {
199      //    this->SetRootName("");
200      //    this->SetRootName(filerootname);
201      //  };
202  }  }
203    
204  //  //
# Line 388  void PamelaDBOperations::SetOrbitNo(UInt Line 398  void PamelaDBOperations::SetOrbitNo(UInt
398      return;      return;
399    };    };
400    //    //
401    TString name = this->GetRootFile();    if ( !chewbacca ){
402    Int_t nlength = name.Length();      TString name = this->GetRootFile();
403    if ( nlength < 5 ) return;      Int_t nlength = name.Length();
404    TString dwo = 0;      if ( nlength < 5 ){
405    for (Int_t i = 0; i<5; i++){        if ( IsDebug() ) printf(" Agh problems determining the orbit number! name = %s \n",name.Data());
406      dwo.Append(name[i],1);        return;
407    };      };
408    if ( dwo.IsDigit() ){      TString dwo = 0;
409      dworbit = (UInt_t)dwo.Atoi();      for (Int_t i = 0; i<5; i++){
   } else {  
     dwo="";  
     for (Int_t i = 8; i<13; i++){  
410        dwo.Append(name[i],1);        dwo.Append(name[i],1);
411      };          };
412      if ( dwo.IsDigit() ) dworbit = (UInt_t)dwo.Atoi();      if ( dwo.IsDigit() ){
413          dworbit = (UInt_t)dwo.Atoi();
414        } else {
415          dwo="";
416          for (Int_t i = 8; i<13; i++){
417            dwo.Append(name[i],1);
418          };    
419          if ( dwo.IsDigit() ) dworbit = (UInt_t)dwo.Atoi();
420        };
421        if ( IsDebug() ) printf(" Downlink orbit is %i (dwo = %s) \n",dworbit,dwo.Data());
422    };    };
   if ( IsDebug() ) printf(" Downlink orbit is %i (dwo = %s) \n",dworbit,dwo.Data());  
423    return;    return;
424  };  };
425    
# Line 435  TString PamelaDBOperations::GetRawPath() Line 450  TString PamelaDBOperations::GetRawPath()
450    
451  TString PamelaDBOperations::GetRootPath(){  TString PamelaDBOperations::GetRootPath(){
452    if ( STATIC ){    if ( STATIC ){
453      return((TString)gSystem->DirName(filerootname.Data())+'/');      return((TString)gSystem->DirName(this->GetRootName().Data())+'/');
454    } else {    } else {    
455      return((TString)gSystem->ExpandPathName("$PAM_L0")+'/');      if ( KEEPENV ){
456          return((TString)gSystem->ExpandPathName(gSystem->DirName(filerootname.Data()))+'/');
457        } else {
458          return((TString)gSystem->ExpandPathName("$PAM_L0")+'/');
459        };
460    };    };
461  };  };
462    
# Line 490  void PamelaDBOperations::SetCommonGLRUN( Line 509  void PamelaDBOperations::SetCommonGLRUN(
509  };  };
510    
511  /**  /**
512     *
513     * Set the variables which belogns to physendrun tree
514     *
515     */
516    void PamelaDBOperations::SetPhysEndRunVariables(){
517      //
518      //
519      //
520      TTree *T = 0;
521      T = (TTree*)file->Get("PhysEndRun");
522      if ( !T || T->IsZombie() ) throw -90;
523      //
524      PhysEndRunEvent *pher= 0;
525      EventHeader *eh = 0;
526      T->SetBranchAddress("PhysEndRun", &pher);
527      T->SetBranchAddress("Header", &eh);
528      //
529      UInt_t phobt = 0;
530      UInt_t phpkt = 0;
531      //
532      glrun->SetPHYSENDRUN_MASK_S3S2S12(0);
533      glrun->SetPHYSENDRUN_MASK_S11CRC(0);
534      //
535      for (Int_t p=0; p<T->GetEntries(); p++){
536        //
537        T->GetEntry(p);
538        //
539        phobt = (UInt_t)eh->GetPscuHeader()->GetOrbitalTime();
540        phpkt = (UInt_t)eh->GetPscuHeader()->GetCounter();
541        //
542        if ( this->PKT(phpkt) >= this->PKT(glrun->GetRUNHEADER_PKT()) && this->PKT(phpkt) <= this->PKT(glrun->GetRUNTRAILER_PKT()) && this->OBT(phobt) >= this->OBT(glrun->GetRUNHEADER_OBT()) && this->OBT(phobt) <= this->OBT(glrun->GetRUNTRAILER_OBT())  ){
543          if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() || glrun->GetPHYSENDRUN_MASK_S11CRC() ){
544            if ( IsDebug() ) printf(" WARNING while looping in physendrun: found two PhysEndRun packet for the same RUN! \n");
545            if ( IsDebug() ) printf(" Actual values: %X %X New values %X %X \n ",glrun->GetPHYSENDRUN_MASK_S3S2S12(),glrun->GetPHYSENDRUN_MASK_S11CRC(),(UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S3S2S12,(UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S11CRC);
546            if ( PEDANTIC && IsDebug() ) printf(" ERROR while looping in physendrun: found two PhysEndRun packet for the same RUN!\n ");
547            if ( PEDANTIC ) throw -91;
548          } else {
549            glrun->SetPHYSENDRUN_MASK_S3S2S12((UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S3S2S12);
550            glrun->SetPHYSENDRUN_MASK_S11CRC((UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S11CRC);
551          };
552        };
553      };
554      //
555    };
556    
557    /**
558   * Patch, look for upper limits to avoid processing retransmitted data   * Patch, look for upper limits to avoid processing retransmitted data
559   */   */
560  Int_t PamelaDBOperations::SetUpperLimits(){  Int_t PamelaDBOperations::SetUpperLimits(){
# Line 603  Int_t PamelaDBOperations::SetUpperLimits Line 668  Int_t PamelaDBOperations::SetUpperLimits
668      UInt_t tjump = 50000;      UInt_t tjump = 50000;
669      //UInt_t tjump = 100;      //UInt_t tjump = 100;
670      while ( tjump > 0 ){      while ( tjump > 0 ){
671        pktlast = numeric_limits<UInt_t>::max();        //      pktlast = numeric_limits<UInt_t>::max();
672        while ( pktlast > chpktmax && (Int_t)(nevent-1-it) >= 0 ){        pktlast = chpktmax + 1;
673          while ( PKT(pktlast) > PKT(chpktmax) && (Int_t)(nevent-1-it) >= 0 ){
674          if ( (Int_t)(nevent-1-it) >= 0 ){          if ( (Int_t)(nevent-1-it) >= 0 ){
675            T->GetEntry(nevent-1-it);            T->GetEntry(nevent-1-it);
676            ph = eh->GetPscuHeader();            ph = eh->GetPscuHeader();
# Line 612  Int_t PamelaDBOperations::SetUpperLimits Line 678  Int_t PamelaDBOperations::SetUpperLimits
678          } else {          } else {
679            pktlast = chpktmax + 1;            pktlast = chpktmax + 1;
680          };          };
681          if ( (!(it%1000) || abs((int)pktlast - (int)chpktmax)<1000 ) && debug ) printf(" look for up %i %i %i nevent %u (nevent-1-it) %i \n",it,pktlast,chpktmax,nevent,(Int_t)(nevent-1-it));          if ( (!(it%1000) || abs((int)(PKT(pktlast) - PKT(chpktmax)))<1000 ) && debug ) printf(" look for up %i %i %i nevent %u (nevent-1-it) %i \n",it,pktlast,chpktmax,nevent,(Int_t)(nevent-1-it));
682          it += tjump;          it += tjump;
683        };        };
684        if ( tjump > 1 ) it -= 2*tjump;        if ( tjump > 1 ) it -= 2*tjump;
# Line 636  Int_t PamelaDBOperations::SetUpperLimits Line 702  Int_t PamelaDBOperations::SetUpperLimits
702      tjump = 50000;      tjump = 50000;
703      //tjump = 100;      //tjump = 100;
704      while ( tjump > 0 ){      while ( tjump > 0 ){
705        pktlast = 0;        //      pktlast = 0;
706        while ( pktlast < chpktmin && it < (Int_t)nevent ){        pktlast = chpktmin - 1;
707          if ( debug ) printf("LLlook for down %i %i %llu %llu \n",it,pktlast,PKT(pktlast),PKT(chpktmin));
708          while ( PKT(pktlast) < PKT(chpktmin) && it < (Int_t)nevent ){
709          if ( it < (Int_t)nevent ){          if ( it < (Int_t)nevent ){
710            T->GetEntry(it);            T->GetEntry(it);
711            ph = eh->GetPscuHeader();            ph = eh->GetPscuHeader();
# Line 739  Int_t PamelaDBOperations::SetUpperLimits Line 807  Int_t PamelaDBOperations::SetUpperLimits
807    };    };
808    //    //
809    if ( chewbacca && nevent < 1 ) {    if ( chewbacca && nevent < 1 ) {
810          pktfirst = chpktmin;      pktfirst = chpktmin;
811          upperpkt = PKT(chpktmax);      upperpkt = PKT(chpktmax);
812          pktlast = chpktmax;      pktlast = chpktmax;
813          obtfirst = chobtmin;      obtfirst = chobtmin;
814          obtlast = chobtmax;      obtlast = chobtmax;
815          upperobt = OBT(chobtmax);      upperobt = OBT(chobtmax);
816    };    };
817    //    //
818    if ( IsDebug() ) printf(" First entries are: OBT %u pkt_num %u entry %i\n",obtfirst,pktfirst,chminentry);    if ( IsDebug() ) printf(" First entries are: OBT %u pkt_num %u entry %i\n",obtfirst,pktfirst,chminentry);
# Line 752  Int_t PamelaDBOperations::SetUpperLimits Line 820  Int_t PamelaDBOperations::SetUpperLimits
820    if ( IsDebug() ) printf(" Last entries are: OBT %lld pkt_num %lld entry %i\n",upperobt,upperpkt,upperentry);    if ( IsDebug() ) printf(" Last entries are: OBT %lld pkt_num %lld entry %i\n",upperobt,upperpkt,upperentry);
821    //    //
822    if ( (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) > OBT(obtfirst)) || (PKT(pktlast) > PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) ){    if ( (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) > OBT(obtfirst)) || (PKT(pktlast) > PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) ){
823          if ( IsDebug() ) printf(" Inconsistent PKT/OBT sequence: \n     (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) > OBT(obtfirst)) %llu < %llu && %llu > %llu \n     OR \n     (PKT(pktlast) > PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) %llu > %llu && %llu < %llu \n",PKT(pktlast),PKT(pktfirst),OBT(obtlast),OBT(obtfirst),PKT(pktlast),PKT(pktfirst),OBT(obtlast),OBT(obtfirst));      if ( IsDebug() ) printf(" Inconsistent PKT/OBT sequence: \n     (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) > OBT(obtfirst)) %llu < %llu && %llu > %llu \n     OR \n     (PKT(pktlast) > PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) %llu > %llu && %llu < %llu \n",PKT(pktlast),PKT(pktfirst),OBT(obtlast),OBT(obtfirst),PKT(pktlast),PKT(pktfirst),OBT(obtlast),OBT(obtfirst));
824          if ( PEDANTIC ) throw -88;      if ( PEDANTIC ) throw -88;
825          return(32);      return(32);
826    };    };
827    //    //
828    if ( !nevent ) return(64);    if ( !nevent ) return(64);
# Line 1040  Int_t PamelaDBOperations::SetUpperLimits Line 1108  Int_t PamelaDBOperations::SetUpperLimits
1108          upperpkt = pkth;          upperpkt = pkth;
1109          upperobt = obth;          upperobt = obth;
1110          rhev = lasthead+1;          rhev = lasthead+1;
1111      } else {        } else {
1112          rhev = lasthead;          rhev = lasthead;
1113        };        };
1114        if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);        if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
# Line 1079  UInt_t PamelaDBOperations::AssignRunID() Line 1147  UInt_t PamelaDBOperations::AssignRunID()
1147    stringstream   oss;    stringstream   oss;
1148    //      //  
1149    oss.str("");    oss.str("");
1150    oss << "INSERT INTO _RUNID_GEN VALUES (NULL);";    if ( chewbacca ){// if chewbacca and tag=none then use chewbacca tag (chiby = chewbacca inserted by), if chewbacca and tag!=none then use tag, if not chewbacca use tag.
1151        if ( !strcmp(tag.Data(),"NONE") ){
1152          oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< chiby.Data() <<"');";
1153        } else {
1154          oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< tag.Data() <<"');";
1155        };
1156      } else {
1157        oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< tag.Data() <<"');";
1158      };
1159    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1160    if ( !result ) throw -10;    if ( !result ) throw -10;
1161    oss.str("");    oss.str("");
# Line 1227  void PamelaDBOperations::LockTables(){   Line 1303  void PamelaDBOperations::LockTables(){  
1303    stringstream oss;    stringstream oss;
1304    //      //  
1305    oss.str("");    oss.str("");
1306    oss << "lock table GL_RUN write, GL_ROOT write, GL_RAW write, GL_TIMESYNC write, GL_RESURS_OFFSET write, GL_PARAM write, GL_TLE write, GL_RUN_FRAGMENTS write, GL_RUN_TRASH write, GL_CALO_CALIB write, GL_CALOPULSE_CALIB write, GL_TRK_CALIB write, GL_S4_CALIB write, ROOT_TABLE_MERGING write, ROOT_TABLE write, _RUNID_GEN write;";    oss << "lock table GL_RUN write, GL_ROOT write, GL_RAW write, GL_TIMESYNC write, GL_RESURS_OFFSET write, GL_PARAM write, GL_TLE write, GL_RUN_FRAGMENTS write, GL_RUN_TRASH write, GL_CALO_CALIB write, GL_CALOPULSE_CALIB write, GL_TRK_CALIB write, GL_S4_CALIB write, ROOT_TABLE_MERGING write, ROOT_TABLE_BAD write, ROOT_TABLE write, _RUNID_GEN write;";
1307    TSQLResult *result = 0;    TSQLResult *result = 0;
1308    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1309    if ( !result ) throw -10;    if ( !result ) throw -10;
# Line 1260  void PamelaDBOperations::UnLockTables(){ Line 1336  void PamelaDBOperations::UnLockTables(){
1336   */   */
1337  Long64_t PamelaDBOperations::PKT(UInt_t pkt_num){    Long64_t PamelaDBOperations::PKT(UInt_t pkt_num){  
1338    //    //
1339  //  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));    //  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));
1340    //    //
1341    if ( pkt_num < (ppktfirst/2) && ppktfirst > (16777214/2)  ){    if ( pkt_num < (ppktfirst/2) && ppktfirst > (16777214/2)  ){
1342  //    if ( IsDebug() ) printf(" rise up pktnum %lld \n",(Long64_t)pkt_num+16777215LL);      //    if ( IsDebug() ) printf(" rise up pktnum %lld \n",(Long64_t)pkt_num+16777215LL);
1343      return((Long64_t)pkt_num+16777215LL);      return((Long64_t)pkt_num+16777215LL);
1344    };    };
1345    //    //
1346    if ( pkt_num > ((Long64_t)ppktfirst*2) && pkt_num > (16777214/2) ){    if ( pkt_num > ((Long64_t)ppktfirst*2) && pkt_num > (16777214/2) ){
1347  //    if ( IsDebug() ) printf(" rise down pktnum %lld \n",(Long64_t)pkt_num-16777215LL);      //    if ( IsDebug() ) printf(" rise down pktnum %lld \n",(Long64_t)pkt_num-16777215LL);
1348      return((Long64_t)pkt_num-16777215LL);      return((Long64_t)pkt_num-16777215LL);
1349    };    };
1350    //    //
1351  //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)pkt_num);    //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)pkt_num);
1352    return((Long64_t)pkt_num);    return((Long64_t)pkt_num);
1353    //    //
1354  };  };
# Line 1282  Long64_t PamelaDBOperations::PKT(UInt_t Line 1358  Long64_t PamelaDBOperations::PKT(UInt_t
1358   */   */
1359  Long64_t PamelaDBOperations::OBT(UInt_t obt){    Long64_t PamelaDBOperations::OBT(UInt_t obt){  
1360    //    //
1361  //  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));    //  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));
1362    //    //
1363    if ( obt < (pobtfirst/2) && pobtfirst > (numeric_limits<UInt_t>::max()/2) ){    if ( obt < ((Long64_t)pobtfirst/2) && pobtfirst > (numeric_limits<UInt_t>::max()/2) ){
1364  //    if ( IsDebug() ) printf(" rise up obt %lld \n",(Long64_t)obt+(Long64_t)numeric_limits<UInt_t>::max());      //    if ( IsDebug() ) printf(" rise up obt %lld \n",(Long64_t)obt+(Long64_t)numeric_limits<UInt_t>::max());
1365      return((Long64_t)obt+(Long64_t)numeric_limits<UInt_t>::max());      return((Long64_t)obt+(Long64_t)numeric_limits<UInt_t>::max());
1366    };    };
1367    //    //
1368    if ( obt > ((Long64_t)pobtfirst*2) && obt > (numeric_limits<UInt_t>::max()/2) ){    if ( obt > ((Long64_t)pobtfirst*2) && obt > (numeric_limits<UInt_t>::max()/2) ){
1369  //    if ( IsDebug() ) printf(" pobtfirst*2 %lld \n",((Long64_t)pobtfirst*2));      //    if ( IsDebug() ) printf(" pobtfirst*2 %lld \n",((Long64_t)pobtfirst*2));
1370  //    if ( IsDebug() ) printf(" rise down pktnum %lld \n", (Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());      //    if ( IsDebug() ) printf(" rise down pktnum %lld \n", (Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());
1371      return((Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());      return((Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());
1372    };    };
1373    //    //
1374  //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)obt);    //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)obt);
1375    return((Long64_t)obt);    return((Long64_t)obt);
1376  };  };
1377    
# Line 1331  void PamelaDBOperations::FillClass(Bool_ Line 1407  void PamelaDBOperations::FillClass(Bool_
1407    UInt_t lastPkt = 0;    UInt_t lastPkt = 0;
1408    UInt_t rhtime = 0;    UInt_t rhtime = 0;
1409    UInt_t rttime = 0;    UInt_t rttime = 0;
1410      //
1411      if ( IsDebug() ) printf(" A firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1412      //
1413    if ( !mishead ){    if ( !mishead ){
1414      codh = ehh->GetCounter();      codh = ehh->GetCounter();
1415      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1) ){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){      
1416          if ( IsDebug() ) printf(" B firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1417        firstev = 1;        firstev = 1;
1418        lastev = 0;        lastev = 0;
1419      } else {      } else {
# Line 1346  void PamelaDBOperations::FillClass(Bool_ Line 1426  void PamelaDBOperations::FillClass(Bool_
1426    };    };
1427    if ( !mistrail ){    if ( !mistrail ){
1428      codt = eht->GetCounter();      codt = eht->GetCounter();
1429      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1)){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1)){      
1430          if ( IsDebug() ) printf(" C firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1431        lastev = 0;        lastev = 0;
1432        firstev = lastev+1;        firstev = lastev+1;
1433      } else {      } else {
# Line 1363  void PamelaDBOperations::FillClass(Bool_ Line 1444  void PamelaDBOperations::FillClass(Bool_
1444    if ( mishead ) {    if ( mishead ) {
1445      glrun->Set_GL_RUNH0();      glrun->Set_GL_RUNH0();
1446      //      //
1447      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1) ){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){      
1448        firstObt = lastObt;        firstObt = lastObt;
1449        firstPkt = lastPkt;        firstPkt = lastPkt;
1450        rhtime = rttime;        rhtime = rttime;
# Line 1382  void PamelaDBOperations::FillClass(Bool_ Line 1463  void PamelaDBOperations::FillClass(Bool_
1463    if ( mistrail ){    if ( mistrail ){
1464      glrun->Set_GL_RUNT0();      glrun->Set_GL_RUNT0();
1465      //      //
1466      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1) ){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){      
1467        lastObt = firstObt;        lastObt = firstObt;
1468        lastPkt = firstPkt;        lastPkt = firstPkt;
1469        rttime = rhtime;        rttime = rhtime;
# Line 1405  void PamelaDBOperations::FillClass(Bool_ Line 1486  void PamelaDBOperations::FillClass(Bool_
1486    if ( IsDebug() ) printf(" firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);    if ( IsDebug() ) printf(" firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1487    //    //
1488    this->SetCommonGLRUN(rhtime,rttime);    this->SetCommonGLRUN(rhtime,rttime);
1489      this->SetPhysEndRunVariables();
1490    //    //
1491  };  };
1492    
# Line 1416  void PamelaDBOperations::FillClass(Bool_ Line 1498  void PamelaDBOperations::FillClass(Bool_
1498   * Insert a new row into GL_RAW table.   * Insert a new row into GL_RAW table.
1499   */   */
1500  Int_t PamelaDBOperations::insertPamelaRawFile(){  Int_t PamelaDBOperations::insertPamelaRawFile(){
1501    
1502        //
1503        Bool_t idr =  this->SetID_RAW();
1504        if ( idr ) return(1);
1505    
1506        GL_RAW glraw = GL_RAW();
1507        
1508        glraw.PATH = GetRawPath();
1509        glraw.NAME = GetRawFile();
1510        //    glraw.BOOT_NUMBER = 0;//???
1511        glraw.BOOT_NUMBER = this->GetBOOTnumber();
1512        
1513        if( insertPamelaRawFile(&glraw) )return(1);
1514        //
1515        idr =  this->SetID_RAW();
1516        if ( !idr ) throw -11;
1517        
1518        return(0);
1519    }
1520    /**
1521     * Insert a new row into GL_RAW table.
1522     */
1523    Int_t PamelaDBOperations::insertPamelaRawFile(GL_RAW *glraw){
1524    //    //
1525    stringstream oss;      if(!glraw)return(1);//?? ok I think
1526    //      //
1527    Bool_t idr =  this->SetID_RAW();      stringstream oss;
1528    if ( idr ) return(1);      //
1529    //      oss.str("");
1530    oss.str("");      if ( STATIC ){
1531    if ( STATIC ){          oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"
1532      oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"              << glraw->PATH << "', '" << glraw->NAME << "')";
1533          << this->GetRawPath().Data() << "', '" << this->GetRawFile().Data() << "')";      } else {
1534    } else {          oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('$PAM_RAW', '" << glraw->NAME << "')";
1535      oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('$PAM_RAW', '" << this->GetRawFile().Data() << "')";      };
1536    };      if ( debug ) cout <<oss.str().c_str() <<endl;
1537    if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;      if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
1538    //      //
1539    idr =  this->SetID_RAW();      oss.str("");
1540    if ( !idr ) throw -11;      oss << "SELECT ID FROM GL_RAW WHERE NAME=\""<<glraw->NAME<<"\";";
1541    //      if ( debug ) cout << oss.str().c_str()<<endl;
1542    return(0);      if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
1543        //
1544        TSQLResult *result = 0;
1545        TSQLRow    *row    = 0;
1546        result = conn->Query(oss.str().c_str());
1547        if ( result == NULL ) throw -4;
1548        row = result->Next();
1549        if ( !row ) return(1);
1550        glraw->ID = (UInt_t)atoll(row->GetField(0));
1551        if ( debug ) printf(" The ID of the RAW file is %u \n",glraw->ID);
1552        delete result;
1553        delete row;
1554        //
1555        return(0);
1556  }  }
1557    
1558    
# Line 1467  Int_t PamelaDBOperations::insertPamelaGL Line 1585  Int_t PamelaDBOperations::insertPamelaGL
1585      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
1586      if ( !result ) throw -10;      if ( !result ) throw -10;
1587      row = result->Next();      row = result->Next();
1588        if ( !row ) throw -92;
1589      idresof = (UInt_t)atoll(row->GetField(0));      idresof = (UInt_t)atoll(row->GetField(0));
1590      existsts = true;      existsts = true;
1591      goto eout;      goto eout;
# Line 1746  Int_t PamelaDBOperations::insertPamelaGL Line 1865  Int_t PamelaDBOperations::insertPamelaGL
1865   * The raw file indicates in the parameters should be already been stored in the database.   * The raw file indicates in the parameters should be already been stored in the database.
1866   */   */
1867  Int_t PamelaDBOperations::insertPamelaRootFile(){  Int_t PamelaDBOperations::insertPamelaRootFile(){
1868    stringstream oss;  
1869    TSQLResult *result = 0;      stringstream oss;
1870    TSQLRow    *row    = 0;      TSQLResult *result = 0;
1871    UInt_t idtimesync = 0;      TSQLRow    *row    = 0;
   //  
   //  
   if ( chewbacca ){  
     oss.str("");  
     oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" limit 1;";  
     if ( debug ) printf(" query is %s \n",oss.str().c_str());  
     result = conn->Query(oss.str().c_str());  
     //  
     if ( !result ) throw -3;  
1872      //      //
1873      row = result->Next();      // ----------------------
1874        // determine the timesync
1875        // ----------------------
1876        UInt_t idtimesync = 0;
1877      //      //
1878      if ( !row ) throw -3;      if ( chewbacca ){
1879      idtimesync = (UInt_t)atoll(row->GetField(0));          oss.str("");
1880    } else {          oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" limit 1;";
1881      oss.str("");          if ( debug ) printf(" %s \n",oss.str().c_str());
1882      if ( STATIC ){          result = conn->Query(oss.str().c_str());
1883        oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "          //
1884            << " LEFT JOIN GL_ROOT "          if ( !result ) throw -3;
1885            << " ON GL_RAW.ID = GL_ROOT.ID_RAW "          //
1886            << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "          row = result->Next();
1887            << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";          //
1888            if ( !row ) throw -3;
1889            idtimesync = (UInt_t)atoll(row->GetField(0));
1890      } else {      } else {
1891        oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "          oss.str("");
1892            << " LEFT JOIN GL_ROOT "          if ( STATIC ){
1893            << " ON GL_RAW.ID = GL_ROOT.ID_RAW "              oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1894            << " WHERE GL_RAW.PATH = '$PAM_RAW' AND "                  << " LEFT JOIN GL_ROOT "
1895            << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";                  << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1896                    << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "
1897                    << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1898            } else {
1899                oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1900                    << " LEFT JOIN GL_ROOT "
1901                    << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1902                    << " WHERE GL_RAW.PATH = '$PAM_RAW' AND "
1903                    << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1904            };
1905            result = conn->Query(oss.str().c_str());
1906            //
1907            if ( !result ) throw -12;
1908            //
1909            row = result->Next();
1910            //
1911            if ( !row ) throw -10;
1912            if ( row != NULL && (UInt_t)atoll(row->GetField(0))>0 ){
1913                idroot = (UInt_t)atoll(row->GetField(2));
1914                delete row;
1915                delete result;
1916                return(1);
1917            };
1918            //
1919            // determine which timesync has to be used
1920            //
1921            oss.str("");
1922            oss << "SELECT GL_TIMESYNC.ID FROM GL_TIMESYNC LEFT JOIN GL_RAW ON GL_RAW.ID = GL_TIMESYNC.ID_RAW ORDER BY GL_TIMESYNC.ID DESC LIMIT 1;";
1923            result = conn->Query(oss.str().c_str());
1924            //
1925            if ( !result ) throw -3;
1926            //
1927            row = result->Next();
1928            //
1929            if ( !row ) throw -3;
1930            idtimesync = (UInt_t)atoll(row->GetField(0));
1931      };      };
1932      result = conn->Query(oss.str().c_str());      
1933      //      delete row;
1934      if ( !result ) throw -12;      delete result;
1935      //  
1936      row = result->Next();      // ----------------------
1937      //      // insert root file
1938      if ( !row ) throw -10;      // ----------------------
1939      if ( row != NULL && (UInt_t)atoll(row->GetField(0))>0 ){  
1940        idroot = (UInt_t)atoll(row->GetField(2));      GL_ROOT glroot = GL_ROOT();
1941        return(1);      
1942        glroot.ID_RAW = GetID_RAW();
1943        glroot.ID_TIMESYNC = idtimesync;
1944        if ( STATIC ){
1945          glroot.PATH = GetRootPath();
1946        } else {
1947          if ( KEEPENV ){
1948            glroot.PATH = gSystem->DirName(filerootname.Data());
1949          } else {
1950            glroot.PATH = "$PAM_L0";
1951          };
1952      };      };
1953      //      glroot.NAME = GetRootFile();
1954      // determine which timesync has to be used  
1955      //      if ( insertPamelaRootFile(&glroot) )return 1;
1956      oss.str("");  
1957      oss << "SELECT GL_TIMESYNC.ID FROM GL_TIMESYNC LEFT JOIN GL_RAW ON GL_RAW.ID = GL_TIMESYNC.ID_RAW ORDER BY GL_TIMESYNC.ID DESC LIMIT 1;";      SetID_ROOT(glroot.ID);
1958      result = conn->Query(oss.str().c_str());      
1959      //  
1960      if ( !result ) throw -3;      return (0);
1961      //  }
1962      row = result->Next();  /**
1963      //   * Insert all the new rows into GL_ROOT.
1964      if ( !row ) throw -3;   * The raw file indicates in the parameters should be already been stored in the database.
1965      idtimesync = (UInt_t)atoll(row->GetField(0));   */
1966    };  Int_t PamelaDBOperations::insertPamelaRootFile(GL_ROOT *glroot){
1967      stringstream oss;
1968      TSQLResult *result = 0;
1969      TSQLRow    *row    = 0;
1970      //
1971    //    //
1972    oss.str("");    oss.str("");
1973    if ( STATIC ){    oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
1974      oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"        << glroot->ID_RAW << "', '" << glroot->ID_TIMESYNC << "', '" << glroot->PATH << "', '" << glroot->NAME << "')";
         << this->GetID_RAW() << "', '" << idtimesync << "', '" << this->GetRootPath().Data() << "', '" << this->GetRootFile().Data() << "')";  
   } else {  
     oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"  
         << this->GetID_RAW() << "', '" << idtimesync << "', '$PAM_L0', '" << this->GetRootFile().Data() << "')";  
   };  
1975    //    //
1976    if ( debug ) printf(" query is %s \n",oss.str().c_str());    if ( debug ) printf("%s \n",oss.str().c_str());
1977    if (conn->Query(oss.str().c_str()) == 0) throw -4;    if (conn->Query(oss.str().c_str()) == 0) throw -4;
1978    //    //
1979    delete result;    delete result;
1980    //    //
1981    oss.str("");    oss.str("");
1982    //  oss << "SELECT ID FROM GL_ROOT WHERE ID_RAW=" << this->GetID_RAW() << ";";    //  oss << "SELECT ID FROM GL_ROOT WHERE ID_RAW=" << this->GetID_RAW() << ";";
1983    if ( STATIC ){    oss << "SELECT ID FROM GL_ROOT WHERE PATH='" << glroot->PATH << "' and NAME='"<< glroot->NAME <<"';";
     oss << "SELECT ID FROM GL_ROOT WHERE PATH='" << this->GetRootPath().Data() << "' and NAME='"<< this->GetRootFile().Data() <<"';";  
   } else {  
     oss << "SELECT ID FROM GL_ROOT WHERE PATH='$PAM_L0' and NAME='"<< this->GetRootFile().Data() <<"';";  
   };  
1984    //    //
1985    if ( debug ) printf(" query is %s \n",oss.str().c_str());    if ( debug ) printf("%s \n",oss.str().c_str());
1986    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1987    if ( !result ) throw -12;    if ( !result ) throw -12;
1988    row = result->Next();    row = result->Next();
1989    if ( !row ) throw -3;    if ( !row ) throw -3;
1990    this->SetID_ROOT((UInt_t)atoll(row->GetField(0)));  
1991    if ( debug ) printf(" The ID of the ROOT file is %u \n",this->GetID_ROOT());    glroot->ID = (UInt_t)atoll(row->GetField(0));
1992    
1993      if ( debug ) printf(" The ID of the ROOT file is %u \n",glroot->ID);
1994    //    //
1995    delete result;    delete result;
1996    //    //
# Line 2061  Int_t PamelaDBOperations::insertPamelaRU Line 2218  Int_t PamelaDBOperations::insertPamelaRU
2218            cod = ehh->GetCounter();            cod = ehh->GetCounter();
2219            tcod = (UInt_t)cod->Get(pctp->Physics);            tcod = (UInt_t)cod->Get(pctp->Physics);
2220            evbefh = TMath::Max(chminentry,tcod);            evbefh = TMath::Max(chminentry,tcod);
2221  //        if ( (UInt_t)evbefh == upperentry ) evbefh = upperentry + 1;  // this does not work due to the Counter bug in chewbacca            //      if ( (UInt_t)evbefh == upperentry ) evbefh = upperentry + 1;  // this does not work due to the Counter bug in chewbacca
2222            if ( (UInt_t)evbefh == upperentry || !upperentry ) evbefh = upperentry + 1;            if ( (UInt_t)evbefh == upperentry || !upperentry ) evbefh = upperentry + 1;
2223  //            //
2224          if ( debug ) printf(" evbefh %i upperentry %u \n",evbefh,upperentry);            if ( debug ) printf(" evbefh %i upperentry %u \n",evbefh,upperentry);
2225            //            //
2226            this->HandleRunFragments(false,true,evbefh,upperentry);            this->HandleRunFragments(false,true,evbefh,upperentry);
2227            //            //
# Line 2091  Int_t PamelaDBOperations::insertPamelaRU Line 2248  Int_t PamelaDBOperations::insertPamelaRU
2248          ptht = cod->Get(pctp->RunHeader) - 1;          ptht = cod->Get(pctp->RunHeader) - 1;
2249          //      evbeft = cod->Get(pctp->Physics);          //      evbeft = cod->Get(pctp->Physics);
2250          tcod = (UInt_t)cod->Get(pctp->Physics);          tcod = (UInt_t)cod->Get(pctp->Physics);
2251          if ( !tcod ) tcod = 1;          //      if ( !tcod ) tcod = 1;    // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
2252          evbeft = TMath::Min(upperentry,(tcod-1));          evbeft = TMath::Min(upperentry,(tcod-1));
2253          if ( debug ) printf(" Loop in runtrailers, evbeft is %u upperentry %u cod->getetc %u \n",evbeft,upperentry,cod->Get(pctp->Physics));          if ( debug ) printf(" Loop in runtrailers, evbeft is %u upperentry %u cod->getetc %u \n",evbeft,upperentry,cod->Get(pctp->Physics));
2254          //          //
# Line 2130  Int_t PamelaDBOperations::insertPamelaRU Line 2287  Int_t PamelaDBOperations::insertPamelaRU
2287            obth = phh->GetOrbitalTime();            obth = phh->GetOrbitalTime();
2288            cod = ehh->GetCounter();            cod = ehh->GetCounter();
2289            tcod = (UInt_t)cod->Get(pctp->Physics);            tcod = (UInt_t)cod->Get(pctp->Physics);
2290            if ( !tcod ) tcod = 1;            //      if ( !tcod ) tcod = 1; // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
2291            evbefh = TMath::Max(chminentry,(tcod-1));            evbefh = TMath::Max(chminentry,(tcod-1));
2292            //            //
2293            if ( PKT(pkth) >= PKT(pktfirst) && PKT(pkth) <= upperpkt ){            if ( PKT(pkth) >= PKT(pktfirst) && PKT(pkth) <= upperpkt ){
# Line 2169  Int_t PamelaDBOperations::insertPamelaRU Line 2326  Int_t PamelaDBOperations::insertPamelaRU
2326                //                //
2327                this->HandleRunFragments(true,true,chminentry,(evbefh));                this->HandleRunFragments(true,true,chminentry,(evbefh));
2328                //                //
2329                  // what about pth=ptht-1
2330              };              };
2331            };            };
2332            //            //
# Line 2191  Int_t PamelaDBOperations::insertPamelaRU Line 2349  Int_t PamelaDBOperations::insertPamelaRU
2349                cod = ehh->GetCounter();                cod = ehh->GetCounter();
2350                //            evbeft = cod->Get(pctp->Physics);                //            evbeft = cod->Get(pctp->Physics);
2351                tcod = (UInt_t)cod->Get(pctp->Physics);                tcod = (UInt_t)cod->Get(pctp->Physics);
2352                if ( !tcod ) tcod = 1;                //              if ( !tcod ) tcod = 1; // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
2353                evbeft = TMath::Min(upperentry,(tcod-1));                evbeft = TMath::Min(upperentry,(tcod-1));
2354                rh->GetEntry(pth);                rh->GetEntry(pth);
2355                phh = ehh->GetPscuHeader();                phh = ehh->GetPscuHeader();
# Line 2231  Int_t PamelaDBOperations::insertPamelaRU Line 2389  Int_t PamelaDBOperations::insertPamelaRU
2389          //      if ( ptt+1 == rtev){            //      if ( ptt+1 == rtev){  
2390          if ( conptt+1 == nrtev ){            if ( conptt+1 == nrtev ){  
2391            //    if ( conptt+1 == (nrtev+nrtbef )){              //    if ( conptt+1 == (nrtev+nrtbef )){  
2392              if ( IsDebug() ) printf(" >>>>>>>>>>> %i %u %i %u \n",ptht,rhev,nrtev,conptt);
2393            ptht++;            ptht++;
2394            if ( ptht < rhev ){            if ( ptht < rhev ){
2395              rh->GetEntry(ptht);              rh->GetEntry(ptht);
2396                //pth++;
2397                //if ( pth < rhev ){
2398                //rh->GetEntry(pth);
2399              phh = ehh->GetPscuHeader();              phh = ehh->GetPscuHeader();
2400              pkth = phh->GetCounter();              pkth = phh->GetCounter();
2401              obth = phh->GetOrbitalTime();              obth = phh->GetOrbitalTime();
# Line 2257  Int_t PamelaDBOperations::insertPamelaRU Line 2419  Int_t PamelaDBOperations::insertPamelaRU
2419              if ( (UInt_t)evbeft < upperentry-1 && upperentry>0 ){              if ( (UInt_t)evbeft < upperentry-1 && upperentry>0 ){
2420                if ( IsDebug() ) printf(" Piece of run at the end of the file with NO RUNHEADER! evbeft %u upperentry-1 %u \n",(UInt_t)evbeft,upperentry-1);                if ( IsDebug() ) printf(" Piece of run at the end of the file with NO RUNHEADER! evbeft %u upperentry-1 %u \n",(UInt_t)evbeft,upperentry-1);
2421                //                //
2422                if ( (ptt-1) < 0 ) throw -15; // should never arrive here!                //              if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
2423                rt->GetEntry(ptt-1);                if ( (rtev-1) < 0 || ptt < 0 ) throw -15; // should never arrive here!
2424                  //              rt->GetEntry(ptt-1);
2425                  rt->GetEntry(rtev-1);
2426                cod = eht->GetCounter();                cod = eht->GetCounter();
2427                tcod = (UInt_t)cod->Get(pctp->Physics);                tcod = (UInt_t)cod->Get(pctp->Physics)+1;
2428                evbefh = TMath::Max(chminentry,tcod);                evbefh = TMath::Max(chminentry,tcod);
2429                //            evbefh = cod->Get(pctp->Physics);                //            evbefh = cod->Get(pctp->Physics);
2430                rt->GetEntry(ptt);                rt->GetEntry(ptt);
# Line 2367  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2531  Bool_t PamelaDBOperations::IsRunAlreadyI
2531        //        //
2532        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");
2533        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2534  //       oss.str("");        //       oss.str("");
2535  //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2536  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());              //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
2537  //       conn->Query(oss.str().c_str());        //       conn->Query(oss.str().c_str());
2538        if ( signal ) signal = false;        if ( signal ) signal = false;
2539        goto gonext;              goto gonext;      
2540        //        //
# Line 2385  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2549  Bool_t PamelaDBOperations::IsRunAlreadyI
2549        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");
2550        //        //
2551        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2552  //       oss.str("");        //       oss.str("");
2553  //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2554  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());              //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
2555  //       conn->Query(oss.str().c_str());        //       conn->Query(oss.str().c_str());
2556        //        //
2557        if ( signal ) signal = false;        if ( signal ) signal = false;
2558        goto gonext;        goto gonext;
# Line 2403  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2567  Bool_t PamelaDBOperations::IsRunAlreadyI
2567        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");
2568        //        //
2569        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2570  //       oss.str("");        //       oss.str("");
2571  //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2572  //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());              //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
2573  //       conn->Query(oss.str().c_str());        //       conn->Query(oss.str().c_str());
2574        if ( signal ) signal = false;        if ( signal ) signal = false;
2575        //        //
2576      };      };
# Line 2488  void PamelaDBOperations::HandleRunFragme Line 2652  void PamelaDBOperations::HandleRunFragme
2652      if ( IsDebug() ) printf("The run is not consistent, it contains non-physics packets! The run has been handled \n");      if ( IsDebug() ) printf("The run is not consistent, it contains non-physics packets! The run has been handled \n");
2653      //      //
2654    } else {    } else {
   //  
   // we have now the good first piece of a run, fill the glrun object  
   //  
   if ( rhfirstev != firstev && !mishead ) mishead = true;  
   if ( rtlastev != lastev && !mistrail ) mistrail = true;  
   //  
   this->FillClass(mishead,mistrail,firstev,lastev);  
   //  
   if ( IsDebug() ) printf("The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");  
   if ( IsDebug() ) printf(" C THIS RUN: RUNHEADER_OBT %u RUNTRAILER_OBT %u RUNHEADER_PKT %u RUNTRAILER_PKT %u \n", glrun->GetRUNHEADER_OBT(),glrun->GetRUNTRAILER_OBT(),glrun->GetRUNHEADER_PKT(),glrun->GetRUNTRAILER_PKT());  
   //  
   // First of all insert the run in the fragment table...  
   //  
   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 ){  
2655      //      //
2656      // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)      // we have now the good first piece of a run, fill the glrun object
2657      //      //
2658      if ( IsDebug() ) printf(" The run is new \n");      if ( firstev != (lastev+1) ){ // could be a problem sometimes (?)
2659      if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");        if ( rhfirstev != firstev && !mishead ) mishead = true;
2660          if ( rtlastev != lastev && !mistrail ) mistrail = true;
2661        };
2662      //      //
2663      glrun->SetID(this->AssignRunID());      if ( IsDebug() ) printf(" bhere firstev is %i lastev is %i \n",firstev,lastev);
2664      glrun->SetID_RUN_FRAG(0);      this->FillClass(mishead,mistrail,firstev,lastev);
2665      glrun->Fill_GL_RUN_FRAGMENTS(conn);      if ( IsDebug() ) printf(" chere firstev is %i lastev is %i \n",firstev,lastev);
2666      //      //
2667    } else {      if ( IsDebug() ) printf("The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
2668      if ( IsDebug() ) printf(" The run is already present in the fragment table \n");      if ( IsDebug() ) printf(" C THIS RUN: RUNHEADER_OBT %u RUNTRAILER_OBT %u RUNHEADER_PKT %u RUNTRAILER_PKT %u \n", glrun->GetRUNHEADER_OBT(),glrun->GetRUNTRAILER_OBT(),glrun->GetRUNHEADER_PKT(),glrun->GetRUNTRAILER_PKT());
2669      if ( PEDANTIC ) throw -69;      //
2670      return;      // First of all insert the run in the fragment table...
   };  
   //  
   if ( chewbacca && mishead && mistrail ) goto justcheck;  
   //  
   // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?  
   //      
   if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is  
                                            // missing it no way we can found a piece in the frag table  
2671      //      //
2672      oss.str("");      oss.str("");
2673      oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "      oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
2674          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
2675          << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "          << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
2676          << " ID != " << glrun->ID          << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
2677          << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!          << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
2678            << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2679            << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
2680            << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
2681            << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2682            << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
2683            << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
2684            << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2685            << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
2686            << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
2687      //      //
2688      if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());      if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
2689      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
2690      //      //
2691      if ( !result ) throw -4;      if ( !result ) throw -4;
2692      //      //
2693      row = result->Next();      row = result->Next();
2694      //      //
2695      if ( !row && NoFrag() ){      if ( !row ){
2696          //
2697          // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
2698          //
2699          if ( IsDebug() ) printf(" The run is new \n");
2700          if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
2701          //
2702          glrun->SetID(this->AssignRunID());
2703          glrun->SetID_RUN_FRAG(0);
2704          glrun->Fill_GL_RUN_FRAGMENTS(conn);
2705          //
2706        } else {
2707          if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
2708          if ( PEDANTIC ) throw -69;
2709          return;
2710        };
2711        //
2712        if ( chewbacca && mishead && mistrail ) goto justcheck;
2713        //
2714        // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
2715        //    
2716        if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
2717          // missing it no way we can found a piece in the frag table
2718        //        //
2719        oss.str("");        oss.str("");
2720        oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "        oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "
2721            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2722            << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "            << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2723            << " ID != " << glrun->ID            << " ID != " << glrun->ID
2724            << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!            << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
2725        //        //
2726        if ( IsDebug() ) printf(" look for runheader in the GL_RUN 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());
2727        result = conn->Query(oss.str().c_str());        result = conn->Query(oss.str().c_str());
2728        //        //
2729        if ( !result ) throw -4;        if ( !result ) throw -4;
2730        //        //
       foundinrun = true;  
       //  
2731        row = result->Next();        row = result->Next();
2732        //        //
2733      };        if ( !row && NoFrag() ){
     //  
     if ( !row ){  
       if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");  
       found = false;  
     } else {  
       //  
       found = false; // default value  
       //  
       if ( IsDebug() ) printf(" Found a possible candidate, checking if it is the good one... \n");  
       //  
       // if we have both runheader and runtrailer we can check with pkt_counter:  
       //  
       if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){  
         ULong64_t chkpkt = 0;    
         ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());  
         ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));  
2734          //          //
2735          chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;            oss.str("");
2736            oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
2737                << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2738                << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2739                << " ID != " << glrun->ID
2740                << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
2741          //          //
2742          if ( labs(chkpkt-pktt)<2 ){          if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
2743            //          result = conn->Query(oss.str().c_str());
           if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);  
           //  
           found = true;  
           //  
         } else {  
           //  
           if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);        
           //  
           found = false;  
           //  
         };  
       };  
       if ( !found && chewbacca ) goto justcheck;  
       if ( !found ){  
2744          //          //
2745          // if we arrive here we were not able to decide if the two pieces matches using only the pkt counter information, we must check times and obts          if ( !result ) throw -4;
2746          //          //
2747          ULong64_t chkpkt1 = 0;          foundinrun = true;
         ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());  
         ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));  
         chkpkt1 = labs(orunh1-dbrunt1);  
         //  
         ULong64_t chkpkt2 = 0;  
         ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());  
         ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));  
         chkpkt2 = labs(orunh2-dbrunt2);  
         //  
         ULong64_t chkpkt3 = 0;  
         ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());  
         ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));  
         chkpkt3 = labs(orunh3-dbrunt3);  
2748          //          //
2749          if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){          row = result->Next();
2750            //    if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){          //
2751          };
2752          //
2753          if ( !row ){
2754            if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2755            found = false;
2756          } else {
2757            //
2758            found = false; // default value
2759            //
2760            if ( IsDebug() ) printf(" A Found a possible candidate, checking if it is the good one... \n");
2761            //
2762            // if we have both runheader and runtrailer we can check with pkt_counter:
2763            //
2764            if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){
2765              ULong64_t chkpkt = 0;  
2766              ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
2767              ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
2768            //            //
2769            if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);            chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;  
2770            //            //
2771            found = true;            if ( labs(chkpkt-pktt)<2 ){
2772                //
2773                if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
2774                //
2775                found = true;
2776                if ( IsDebug() ) printf(" where firstev is %i lastev is %i \n",firstev,lastev);
2777                //
2778              } else {
2779                //
2780                if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);            
2781                //
2782                found = false;
2783                //
2784              };
2785            };
2786            if ( !found && chewbacca ) goto justcheck;
2787            if ( !found ){
2788            //            //
2789          } else {            // if we arrive here we were not able to decide if the two pieces matches using only the pkt counter information, we must check times and obts
2790            //            //
2791            if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);            ULong64_t chkpkt1 = 0;
2792              ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
2793              ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
2794              chkpkt1 = labs(orunh1-dbrunt1);
2795            //            //
2796            found = false;            ULong64_t chkpkt2 = 0;
2797              ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());
2798              ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
2799              chkpkt2 = labs(orunh2-dbrunt2);
2800              //
2801              ULong64_t chkpkt3 = 0;
2802              ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());
2803              ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
2804              chkpkt3 = labs(orunh3-dbrunt3);
2805            //            //
2806              if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
2807                //  if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){
2808                //
2809                if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
2810                //
2811                found = true;
2812                //
2813              } else {
2814                //
2815                if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
2816                //
2817                found = false;
2818                //
2819              };
2820          };          };
2821        };        };
     };  
     //  
     if ( found ){  
       //  
       // we have found the missing piece, glue the two together, merge the informations, fill the gl_run table (check first runs do not exists), delete entry in frag table  
       //  
       if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");  
       //  
       if ( foundinrun ){  
         glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");  
         glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");  
       };  
       //  
       GL_RUN *glrun1 = new GL_RUN();  
       //  
       //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));  
       //  
       oss.str("");  
       oss << " ID="<<row->GetField(0)<<";";  
2822        //        //
2823        glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos        if ( found ){
2824        //          //
2825        // merge infos          // we have found the missing piece, glue the two together, merge the informations, fill the gl_run table (check first runs do not exists), delete entry in frag table
2826        //          //
2827        UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());          if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
2828        ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());          //
2829        UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());          if ( foundinrun ){
2830        ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());            glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2831        if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);            glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2832        TTree *T= 0;          };
2833        T = (TTree*)file->Get("Physics");          //
2834        if ( !T || T->IsZombie() ) throw -16;          GL_RUN *glrun1 = new GL_RUN();
2835        EventHeader *eh = 0;          //
2836        PscuHeader *ph = 0;          //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
2837        T->SetBranchAddress("Header", &eh);          //
2838        while ( apkt > bpkt && aobt > bobt && firstev < lastev ){          oss.str("");
2839          T->GetEntry(firstev);          oss << " ID="<<row->GetField(0)<<";";
2840          ph = eh->GetPscuHeader();          //
2841          bpkt = PKT(ph->GetCounter());          glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos
2842          bobt = OBT(ph->GetOrbitalTime());                if ( IsDebug() ) printf(" there firstev is %i lastev is %i \n",firstev,lastev);
         firstev++;  
         if ( PEDANTIC ) throw -71;  
       };  
       if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);  
       //  
       glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());  
       glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());  
       glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());  
       glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());  
       glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());  
       //  
       glrun->SetEV_FROM(firstev);  
       glrun->SetNEVENTS(lastev-firstev+1);  
       //  
       glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());  
       glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());  
       glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());  
       glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());  
       glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());  
       glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());  
       glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());  
       glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());  
       glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());  
       glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());  
       glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());    
       glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());    
       glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());    
       glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());    
       glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());    
       glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());    
       //  
       if ( !IsRunAlreadyInserted() ){  
2843          //          //
2844          //      glrun->SetID(this->AssignRunID());          // merge infos
         glrun->SetID_RUN_FRAG(glrun1->GetID());  
         glrun->Fill_GL_RUN(conn);  
2845          //          //
2846          // set id number          UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());
2847            ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
2848            UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
2849            ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
2850            if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2851            TTree *T= 0;
2852            T = (TTree*)file->Get("Physics");
2853            if ( !T || T->IsZombie() ) throw -16;
2854            EventHeader *eh = 0;
2855            PscuHeader *ph = 0;
2856            T->SetBranchAddress("Header", &eh);
2857            while ( apkt > bpkt && aobt > bobt && firstev < lastev ){
2858              T->GetEntry(firstev);
2859              ph = eh->GetPscuHeader();
2860              bpkt = PKT(ph->GetCounter());
2861              bobt = OBT(ph->GetOrbitalTime());    
2862              firstev++;
2863              if ( PEDANTIC ) throw -71;
2864            };
2865            if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2866            //
2867            glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
2868            glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
2869            glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
2870            glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());
2871            glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());
2872            //
2873            if ( IsDebug() ) printf(" here firstev is %i lastev is %i \n",firstev,lastev);
2874            //
2875            glrun->SetEV_FROM(firstev);
2876            glrun->SetNEVENTS(lastev-firstev+1);
2877            //
2878            glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
2879            glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
2880            glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
2881            glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());
2882            glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());
2883            glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());
2884            glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());
2885            glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());
2886            glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());
2887            glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());
2888            glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());  
2889            glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());  
2890            glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());  
2891            glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());  
2892            glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());  
2893            glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());  
2894            //
2895            if ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
2896            if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
2897            //
2898            if ( !IsRunAlreadyInserted() ){
2899              //
2900              //    glrun->SetID(this->AssignRunID());
2901              glrun->SetID_RUN_FRAG(glrun1->GetID());
2902              glrun->Fill_GL_RUN(conn);
2903              //
2904              // set id number
2905              //
2906              glrun1->SetID_RUN_FRAG(glrun->GetID());
2907              glrun1->Fill_GL_RUN(conn);
2908              //
2909            };
2910            // delete old entry in fragment table
2911            //
2912            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2913            glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2914          //          //
2915          glrun1->SetID_RUN_FRAG(glrun->GetID());          delete glrun1;
2916          glrun1->Fill_GL_RUN(conn);          //
2917            //
2918            return;
2919          //          //
2920        };        };
       // delete old entry in fragment table  
       //  
       glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       //  
       delete glrun1;  
       //  
       //  
       return;  
2921        //        //
2922      };      };
2923      //      //
2924    };      if ( mistrail && ( rtlastev == lastev || chewbacca )) { // look for runtrailer (only when at the end of the file, if at the beginning and the runh is
2925    //        // missing it no way we can found a piece in the frag table
   if ( mistrail && ( rtlastev == lastev || chewbacca )) { // look for runtrailer (only when at the end of the file, if at the beginning and the runh is  
     // missing it no way we can found a piece in the frag table  
     //  
     oss.str("");  
     oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN_FRAGMENTS WHERE "  
         << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "  
         << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "  
         << " ID != " << glrun->ID  
         << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";  
     //  
     if ( IsDebug() ) printf(" look for runtrailer in the fragments table: 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 && NoFrag() ){  
2926        //        //
2927        oss.str("");        oss.str("");
2928        oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN WHERE "        oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN_FRAGMENTS WHERE "
2929            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2930            << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "            << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2931            << " ID != " << glrun->ID            << " ID != " << glrun->ID
2932            << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";            << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2933        //        //
2934        if ( IsDebug() ) printf(" look for runheader in the GL_RUN 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());
2935        result = conn->Query(oss.str().c_str());        result = conn->Query(oss.str().c_str());
2936        //        //
2937        if ( !result ) throw -4;        if ( !result ) throw -4;
2938        //        //
       foundinrun = true;  
2939        row = result->Next();        row = result->Next();
2940        //        //
2941      };        if ( !row && NoFrag() ){
2942      //          //
2943      if ( !row ){          oss.str("");
2944        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");          oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN WHERE "
2945        found = false;              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2946      } else {              << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2947        //              << " ID != " << glrun->ID
2948        found = false; // default value              << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2949        //          //
2950        if ( IsDebug() ) printf(" Found a possible candidate, checking if it is the good one... \n");          if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
2951        //          result = conn->Query(oss.str().c_str());
2952        // if we have both runheader and runtrailer we can check with pkt_counter:          //
2953            if ( !result ) throw -4;
2954            //
2955            foundinrun = true;
2956            row = result->Next();
2957            //
2958          };
2959        //        //
2960        if ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){        if ( !row ){
2961          ULong64_t chkpkt = 0;            if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2962          ULong64_t pktt = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));          found = false;
2963          ULong64_t pkth = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());        } else {
2964          //          //
2965          chkpkt = pkth + (ULong64_t)((UInt_t)atoll(row->GetField(1))) + 1ULL + 1ULL;            found = false; // default value
2966          //          //
2967          if ( labs(chkpkt-pktt)<2 ){          if ( IsDebug() ) printf(" B Found a possible candidate, checking if it is the good one... \n");
2968            //
2969            // if we have both runheader and runtrailer we can check with pkt_counter:
2970            //
2971            if ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){
2972              ULong64_t chkpkt = 0;  
2973              ULong64_t pktt = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
2974              ULong64_t pkth = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
2975            //            //
2976            if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);            chkpkt = pkth + (ULong64_t)((UInt_t)atoll(row->GetField(1))) + 1ULL + 1ULL;  
2977            //            //
2978            found = true;            if ( labs(chkpkt-pktt)<2 ){
2979                //
2980                if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
2981                //
2982                found = true;
2983                //
2984              } else {
2985                //
2986                if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);            
2987                //
2988                found = false;
2989                //
2990              };
2991            };
2992            if ( !found && chewbacca ) goto justcheck;
2993            if ( !found ){
2994            //            //
2995          } else {            // if we arrive here we were not able to decide if the two pieces matches using only the pkt counter information, we must check times and obts
2996            //            //
2997            if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);                  ULong64_t chkpkt1 = 0;
2998              ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
2999              ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
3000              chkpkt1 = labs(orunh1-dbrunt1);
3001            //            //
3002            found = false;            ULong64_t chkpkt2 = 0;
3003              ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNTRAILER_OBT());
3004              ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
3005              chkpkt2 = labs(orunh2-dbrunt2);
3006              //
3007              ULong64_t chkpkt3 = 0;
3008              ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNTRAILER_TIME());
3009              ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
3010              chkpkt3 = labs(orunh3-dbrunt3);
3011            //            //
3012              if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
3013                //
3014                if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
3015                //
3016                found = true;
3017                //
3018              } else {
3019                //
3020                if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
3021                //
3022                found = false;
3023                //
3024              };
3025          };          };
3026        };        };
3027        if ( !found && chewbacca ) goto justcheck;        //
3028        if ( !found ){        if ( found ){
3029            //
3030            // we have found the missing piece, glue the two together, merge the informations, fill the gl_run table (check first runs do not exists), delete entry in frag table
3031            //
3032            if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
3033          //          //
3034          // if we arrive here we were not able to decide if the two pieces matches using only the pkt counter information, we must check times and obts          if ( foundinrun ){
3035              glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3036              glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
3037            };
3038          //          //
3039          ULong64_t chkpkt1 = 0;          GL_RUN *glrun1 = new GL_RUN();
         ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());  
         ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));  
         chkpkt1 = labs(orunh1-dbrunt1);  
3040          //          //
3041          ULong64_t chkpkt2 = 0;          //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
         ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNTRAILER_OBT());  
         ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));  
         chkpkt2 = labs(orunh2-dbrunt2);  
3042          //          //
3043          ULong64_t chkpkt3 = 0;          oss.str("");
3044          ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNTRAILER_TIME());          oss << " ID="<<row->GetField(0)<<";";
         ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));  
         chkpkt3 = labs(orunh3-dbrunt3);  
3045          //          //
3046          if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){          glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runtrailer infos
3047            //          //
3048            if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);          // merge infos
3049            //          //
3050            found = true;          UInt_t apkt = PKT(glrun->GetRUNTRAILER_PKT());
3051            //          ULong64_t aobt = OBT(glrun->GetRUNTRAILER_OBT());
3052          } else {          UInt_t bpkt = PKT(glrun1->GetRUNHEADER_PKT());
3053            ULong64_t bobt = OBT(glrun1->GetRUNHEADER_OBT());
3054            if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
3055            TTree *T= 0;
3056            T = (TTree*)file->Get("Physics");
3057            if ( !T || T->IsZombie() ) throw -16;
3058            EventHeader *eh = 0;
3059            PscuHeader *ph = 0;
3060            T->SetBranchAddress("Header", &eh);
3061            while ( apkt > bpkt && aobt > bobt && lastev > 0 ){
3062              T->GetEntry(lastev);
3063              ph = eh->GetPscuHeader();
3064              apkt = PKT(ph->GetCounter());
3065              aobt = OBT(ph->GetOrbitalTime());    
3066              lastev--;
3067              if ( PEDANTIC ) throw -72;
3068            };
3069            if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
3070            //
3071            glrun->SetEV_TO(lastev);
3072            glrun->SetNEVENTS(lastev-firstev+1);
3073            glrun->SetPKT_COUNTER(glrun1->GetPKT_COUNTER());
3074            glrun->SetPKT_READY_COUNTER(glrun1->GetPKT_READY_COUNTER());
3075            glrun->SetRUNTRAILER_TIME(glrun1->GetRUNTRAILER_TIME());
3076            glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());
3077            glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());
3078            //
3079            glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());
3080            glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());
3081            glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());
3082            glrun1->SetCOMPILATIONTIMESTAMP(glrun->GetCOMPILATIONTIMESTAMP());
3083            glrun1->SetFAV_WRK_SCHEDULE(glrun->GetFAV_WRK_SCHEDULE());
3084            glrun1->SetEFF_WRK_SCHEDULE(glrun->GetEFF_WRK_SCHEDULE());
3085            glrun1->SetPRH_VAR_TRG_MODE_A(glrun->GetPRH_VAR_TRG_MODE_A());
3086            glrun1->SetPRH_VAR_TRG_MODE_B(glrun->GetPRH_VAR_TRG_MODE_B());
3087            glrun1->SetACQ_BUILD_INFO(glrun->GetACQ_BUILD_INFO());
3088            glrun1->SetACQ_VAR_INFO(glrun->GetACQ_VAR_INFO());
3089            glrun1->SetRM_ACQ_AFTER_CALIB(glrun->GetRM_ACQ_AFTER_CALIB());  
3090            glrun1->SetRM_ACQ_SETTING_MODE(glrun->GetRM_ACQ_SETTING_MODE());  
3091            glrun1->SetTRK_CALIB_USED(glrun->GetTRK_CALIB_USED());  
3092            glrun1->SetCAL_DSP_MASK(glrun->GetCAL_DSP_MASK());  
3093            glrun1->SetLAST_TIMESYNC(glrun->GetLAST_TIMESYNC());  
3094            glrun1->SetOBT_TIMESYNC(glrun->GetOBT_TIMESYNC());  
3095            //
3096            if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ) glrun1->SetPHYSENDRUN_MASK_S3S2S12(glrun->GetPHYSENDRUN_MASK_S3S2S12());
3097            if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) glrun1->SetPHYSENDRUN_MASK_S11CRC(glrun->GetPHYSENDRUN_MASK_S11CRC());
3098            //
3099            if ( !IsRunAlreadyInserted() ){
3100              //
3101              //    glrun->SetID(this->AssignRunID());
3102              //
3103              glrun->SetID_RUN_FRAG(glrun1->GetID());
3104              glrun->Fill_GL_RUN(conn);
3105            //            //
3106            if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);            // set id number
3107            //            //
3108            found = false;            glrun1->SetID_RUN_FRAG(glrun->GetID());
3109              glrun1->Fill_GL_RUN(conn);
3110            //            //
3111          };          };
3112            //
3113            // delete old entries in fragment table
3114            //
3115            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3116            glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3117            //
3118            delete glrun1;
3119            //
3120            return;
3121            //
3122        };        };
3123          //
3124      };      };
3125      //      //
3126      if ( found ){    justcheck:
3127        //      //
3128        // we have found the missing piece, glue the two together, merge the informations, fill the gl_run table (check first runs do not exists), delete entry in frag table      if ( !found ){      
       //  
       if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");  
       //  
       if ( foundinrun ){  
         glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");  
         glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");  
       };  
3129        //        //
3130        GL_RUN *glrun1 = new GL_RUN();        if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");
3131        //        //
3132        //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));        // not found, has this run already inserted in the GL_RUN or in the GL_RUN_FRAGMENTS table?
3133        //        //
3134        oss.str("");        oss.str("");
3135        oss << " ID="<<row->GetField(0)<<";";        oss << " SELECT ID FROM GL_RUN WHERE "
3136              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3137              << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3138              << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3139              << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3140              << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3141              << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3142              << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3143              << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3144              << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3145              << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3146              << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3147              << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3148              << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3149        //        //
3150        glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runtrailer infos        if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3151          result = conn->Query(oss.str().c_str());
3152        //        //
3153        // merge infos        if ( !result ) throw -4;
3154        //        //
3155        UInt_t apkt = PKT(glrun->GetRUNTRAILER_PKT());        row = result->Next();
       ULong64_t aobt = OBT(glrun->GetRUNTRAILER_OBT());  
       UInt_t bpkt = PKT(glrun1->GetRUNHEADER_PKT());  
       ULong64_t bobt = OBT(glrun1->GetRUNHEADER_OBT());  
       if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);  
       TTree *T= 0;  
       T = (TTree*)file->Get("Physics");  
       if ( !T || T->IsZombie() ) throw -16;  
       EventHeader *eh = 0;  
       PscuHeader *ph = 0;  
       T->SetBranchAddress("Header", &eh);  
       while ( apkt > bpkt && aobt > bobt && lastev > 0 ){  
         T->GetEntry(lastev);  
         ph = eh->GetPscuHeader();  
         apkt = PKT(ph->GetCounter());  
         aobt = OBT(ph->GetOrbitalTime());        
         lastev--;  
         if ( PEDANTIC ) throw -72;  
       };  
       if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);  
       //  
       glrun->SetEV_TO(lastev);  
       glrun->SetNEVENTS(lastev-firstev+1);  
       glrun->SetPKT_COUNTER(glrun1->GetPKT_COUNTER());  
       glrun->SetPKT_READY_COUNTER(glrun1->GetPKT_READY_COUNTER());  
       glrun->SetRUNTRAILER_TIME(glrun1->GetRUNTRAILER_TIME());  
       glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());  
       glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());  
       //  
       glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());  
       glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());  
       glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());  
       glrun1->SetCOMPILATIONTIMESTAMP(glrun->GetCOMPILATIONTIMESTAMP());  
       glrun1->SetFAV_WRK_SCHEDULE(glrun->GetFAV_WRK_SCHEDULE());  
       glrun1->SetEFF_WRK_SCHEDULE(glrun->GetEFF_WRK_SCHEDULE());  
       glrun1->SetPRH_VAR_TRG_MODE_A(glrun->GetPRH_VAR_TRG_MODE_A());  
       glrun1->SetPRH_VAR_TRG_MODE_B(glrun->GetPRH_VAR_TRG_MODE_B());  
       glrun1->SetACQ_BUILD_INFO(glrun->GetACQ_BUILD_INFO());  
       glrun1->SetACQ_VAR_INFO(glrun->GetACQ_VAR_INFO());  
       glrun1->SetRM_ACQ_AFTER_CALIB(glrun->GetRM_ACQ_AFTER_CALIB());    
       glrun1->SetRM_ACQ_SETTING_MODE(glrun->GetRM_ACQ_SETTING_MODE());    
       glrun1->SetTRK_CALIB_USED(glrun->GetTRK_CALIB_USED());    
       glrun1->SetCAL_DSP_MASK(glrun->GetCAL_DSP_MASK());    
       glrun1->SetLAST_TIMESYNC(glrun->GetLAST_TIMESYNC());    
       glrun1->SetOBT_TIMESYNC(glrun->GetOBT_TIMESYNC());    
3156        //        //
3157        if ( !IsRunAlreadyInserted() ){        if ( row ){
3158          //          if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");
3159          //      glrun->SetID(this->AssignRunID());          if ( PEDANTIC ) throw -70;
3160          //        } else {
3161          glrun->SetID_RUN_FRAG(glrun1->GetID());          if ( NoFrag() ){
3162          glrun->Fill_GL_RUN(conn);            glrun->SetID_RUN_FRAG(glrun->GetID());
3163          //            glrun->Fill_GL_RUN(conn);    
3164          // set id number            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3165          //          };    
         glrun1->SetID_RUN_FRAG(glrun->GetID());  
         glrun1->Fill_GL_RUN(conn);  
         //  
3166        };        };
       //  
       // delete old entries in fragment table  
       //  
       glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       //  
       delete glrun1;  
       //  
       return;  
       //  
     };  
     //  
   };  
   //  
  justcheck:  
   //  
   if ( !found ){        
     //  
     if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");  
     //  
     // not found, has this run already inserted in the GL_RUN or in the GL_RUN_FRAGMENTS table?  
     //  
     oss.str("");  
     oss << " SELECT ID FROM GL_RUN 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 ){  
       if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");  
       if ( PEDANTIC ) throw -70;  
     } else {  
       if ( NoFrag() ){  
         glrun->SetID_RUN_FRAG(glrun->GetID());  
         glrun->Fill_GL_RUN(conn);        
         glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       };      
3167      };      };
   };  
3168    }; // EEE    }; // EEE
3169    //    //
3170    return;    return;
# Line 3015  void PamelaDBOperations::HandleMissingHo Line 3193  void PamelaDBOperations::HandleMissingHo
3193        glrun->SetID(this->AssignRunID());        glrun->SetID(this->AssignRunID());
3194        glrun->SetID_RUN_FRAG(0);        glrun->SetID_RUN_FRAG(0);
3195        glrun->Fill_GL_RUN(conn);    // it'ok we arrive here only inside a file hence in the middle of the runs...        glrun->Fill_GL_RUN(conn);    // it'ok we arrive here only inside a file hence in the middle of the runs...
3196      };        };
3197      //      //
3198    };    };
3199    //    //
# Line 3059  Bool_t PamelaDBOperations::IsRunConsiste Line 3237  Bool_t PamelaDBOperations::IsRunConsiste
3237    if ( firstev == lastev+1 || lastev == firstev ) { // no events inside the run!    if ( firstev == lastev+1 || lastev == firstev ) { // no events inside the run!
3238      //if ( firstev <= lastev+1 ) { // no events inside the run!      //if ( firstev <= lastev+1 ) { // no events inside the run!
3239      if ( IsDebug() ) printf(" Checking but no events in the run! \n");      if ( IsDebug() ) printf(" Checking but no events in the run! \n");
3240        firstev = lastev+1; // this is necessary for files with no Physics entries, should have no influence on other files
3241      // return true is correct      // return true is correct
3242      return(true);      return(true);
3243      //      //
# Line 3068  Bool_t PamelaDBOperations::IsRunConsiste Line 3247  Bool_t PamelaDBOperations::IsRunConsiste
3247      code = eh->GetCounter();      code = eh->GetCounter();
3248      checkfirst = 0;      checkfirst = 0;
3249      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3250         if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
3251       };      };
3252      if ( IsDebug() ) printf(" Check first is %i firstev is %i\n",checkfirst,firstev);      if ( IsDebug() ) printf(" Check first is %i firstev is %i\n",checkfirst,firstev);
3253      //      //
3254      T->GetEntry(lastev);      T->GetEntry(lastev);
3255      code = eh->GetCounter();      code = eh->GetCounter();
3256      checklast = 0;      checklast = 0;
3257      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3258         if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
3259       };      };
3260      if ( IsDebug() ) printf(" Check last is %i lastev is %i\n",checklast,lastev);      if ( IsDebug() ) printf(" Check last is %i lastev is %i\n",checklast,lastev);
3261      //      //
3262      if ( checkfirst == checklast ){      if ( checkfirst == checklast ){
# Line 3088  Bool_t PamelaDBOperations::IsRunConsiste Line 3267  Bool_t PamelaDBOperations::IsRunConsiste
3267        //        //
3268      } else {      } else {
3269        //        //
3270        if ( IsDebug() ) printf(" There are no-phyics packets inside the run!\n");        if ( IsDebug() ) printf(" There are no-physics packets inside the run!\n");
3271        //        //
3272        // HERE WE MUST HANDLE THAT RUNS AND GO BACK        // HERE WE MUST HANDLE THAT RUNS AND GO BACK
3273        //        //
3274  //      if ( IsDebug() ) printf(" Never seen this case, try to handle it anyway, it was throw -95\n");        //      if ( IsDebug() ) printf(" Never seen this case, try to handle it anyway, it was throw -95\n");
3275        //        //
3276        Bool_t emptyruns = false;        Bool_t emptyruns = false;
3277        UInt_t check = 0;        UInt_t check = 0;
3278        UInt_t lastevtemp = lastev;        UInt_t lastevtemp = lastev;
3279        UInt_t firstevno = firstev;        UInt_t firstevno = firstev;
3280          UInt_t rhchko=0;
3281          UInt_t rhchk=0;
3282        //        //
3283        for (UInt_t i=firstev; i<=lastev; i++){        for (UInt_t i=firstev; i<=lastev; i++){
3284          //          //
# Line 3106  Bool_t PamelaDBOperations::IsRunConsiste Line 3287  Bool_t PamelaDBOperations::IsRunConsiste
3287          //          //
3288          check = 0;          check = 0;
3289          //          //
3290    
3291            // if we have a runheader set lastev then exit
3292            //
3293          for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){          for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3294            if ( strcmp(*Iter,"Physics") ) check += code->Get(GetPacketType(*Iter));            if ( strcmp(*Iter,"Physics") ) check += code->Get(GetPacketType(*Iter));
3295          };          };
3296            // check here if we have a runheader
3297            rhchko = rhchk;  
3298            rhchk = code->Get(GetPacketType("RunHeader"));    
3299          //          //
3300          if ( checkfirst < check || i == lastev ){          if ( checkfirst < check || i == lastev ){
3301            //            //
# Line 3184  Bool_t PamelaDBOperations::IsRunConsiste Line 3371  Bool_t PamelaDBOperations::IsRunConsiste
3371            };            };
3372            //                  //      
3373            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
3374              this->SetPhysEndRunVariables();
3375            //            //
3376            if ( chminentry == firstentry  ){ // EEE            if ( chminentry == firstentry  ){ // EEE
3377              if ( IsDebug() ) printf(" Inside isrunconsistent found a fragment of run at the beginning of the file, put it in the fragment table \n");              if ( IsDebug() ) printf(" Inside isrunconsistent found a fragment of run at the beginning of the file, put it in the fragment table \n");
3378  //              //
3379  //          this->HandleRunFragments(true,mistrail,firstentry,lastentry); // cannot call it here since it enters a loop which will destroy the already stored variables if we arrive here from HandleRunFragments              //      this->HandleRunFragments(true,mistrail,firstentry,lastentry); // cannot call it here since it enters a loop which will destroy the already stored variables if we arrive here from HandleRunFragments
3380  //              //
   
   
   
   
   
   
   
   
   
   
   
   
   
   mishead = true;  
   
   
   UInt_t rhfirstev = firstentry;  
 //  UInt_t rtlastev = lastentry;  
   Bool_t found = false;  
   Bool_t foundinrun = false;  
   //  
   TSQLResult *result = 0;  
   TSQLRow    *row    = 0;  
   //  
   stringstream oss;  
   oss.str("");  
   //  
   // we have now the good first piece of a run, fill the glrun object  
   //  
 //  if ( rhfirstev != firstev && !mishead ) mishead = true;  
 //  if ( rtlastev != lastev && !mistrail ) mistrail = true;  
   //  
 //  this->FillClass(mishead,mistrail,firstev,lastev);  
   //  
   if ( IsDebug() ) printf("zz The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");  
   if ( IsDebug() ) printf("zz C THIS RUN: RUNHEADER_OBT %u RUNTRAILER_OBT %u RUNHEADER_PKT %u RUNTRAILER_PKT %u \n", glrun->GetRUNHEADER_OBT(),glrun->GetRUNTRAILER_OBT(),glrun->GetRUNHEADER_PKT(),glrun->GetRUNTRAILER_PKT());  
   //  
   // First of all insert the run in the fragment table...  
   //  
   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->SetID(this->AssignRunID());  
     glrun->SetID_RUN_FRAG(0);  
     glrun->Fill_GL_RUN_FRAGMENTS(conn);  
     //  
   } else {  
     if ( IsDebug() ) printf(" The run is already present in the fragment table \n");  
     if ( PEDANTIC ) throw -69;  
 //    return;  
   };  
   //  
   if ( chewbacca && mishead && mistrail ) goto zjustcheck;  
   //  
   // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?  
   //  
   if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is  
                                            // missing it no way we can found a piece in the frag table  
     //  
     oss.str("");  
     oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "  
         << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "  
         << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "  
         << " ID != " << glrun->ID  
         << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!  
     //  
     if ( IsDebug() ) printf(" look for runheader in the fragments table: 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 && NoFrag() ){  
       //  
       oss.str("");  
       oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "  
           << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "  
           << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "  
           << " ID != " << glrun->ID  
           << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!  
       //  
       if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());  
       result = conn->Query(oss.str().c_str());  
       //  
       if ( !result ) throw -4;  
       //  
       foundinrun = true;  
       //  
       row = result->Next();  
       //  
     };  
     //  
     if ( !row ){  
       if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");  
       found = false;  
     } else {  
       //  
       found = false; // default value  
       //  
       if ( IsDebug() ) printf(" Found a possible candidate, checking if it is the good one... \n");  
       //  
       // if we have both runheader and runtrailer we can check with pkt_counter:  
       //  
       if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){  
         ULong64_t chkpkt = 0;  
         ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());  
         ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));  
         //  
         chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;  
         //  
         if ( labs(chkpkt-pktt)<2 ){  
           //  
           if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);  
           //  
           found = true;  
           //  
         } else {  
           //  
           if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);  
           //  
           found = false;  
           //  
         };  
       };  
       if ( !found && chewbacca ) goto zjustcheck;  
       if ( !found ){  
         //  
         // if we arrive here we were not able to decide if the two pieces matches using only the pkt counter information, we must check times and obts  
         //  
         ULong64_t chkpkt1 = 0;  
         ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());  
         ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));  
         chkpkt1 = labs(orunh1-dbrunt1);  
         //  
         ULong64_t chkpkt2 = 0;  
         ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());  
         ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));  
         chkpkt2 = labs(orunh2-dbrunt2);  
         //  
         ULong64_t chkpkt3 = 0;  
         ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());  
         ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));  
         chkpkt3 = labs(orunh3-dbrunt3);  
         //  
         if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){  
           //    if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){  
           //  
           if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);  
           //  
           found = true;  
           //  
         } else {  
           //  
           if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);  
           //  
           found = false;  
           //  
         };  
       };  
     };  
     //  
     if ( found ){  
       //  
       // we have found the missing piece, glue the two together, merge the informations, fill the gl_run table (check first runs do not exists), delete entry in frag table  
       //  
       if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");  
       //  
       if ( foundinrun ){  
         glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");  
         glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");  
       };  
       //  
       GL_RUN *glrun1 = new GL_RUN();  
       //  
       //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));  
       //  
       oss.str("");  
       oss << " ID="<<row->GetField(0)<<";";  
       //  
       glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos  
       //  
       // merge infos  
       //  
       UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());  
       ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());  
       UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());  
       ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());  
       if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);  
       TTree *T= 0;  
       T = (TTree*)file->Get("Physics");  
       if ( !T || T->IsZombie() ) throw -16;  
       EventHeader *eh = 0;  
       PscuHeader *ph = 0;  
       T->SetBranchAddress("Header", &eh);  
       while ( apkt > bpkt && aobt > bobt && firstev < lastev ){  
         T->GetEntry(firstev);  
         ph = eh->GetPscuHeader();  
         bpkt = PKT(ph->GetCounter());  
         bobt = OBT(ph->GetOrbitalTime());  
         firstev++;  
         if ( PEDANTIC ) throw -71;  
       };  
       if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);  
       //  
       glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());  
       glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());  
       glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());  
       glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());  
       glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());  
       //  
       glrun->SetEV_FROM(firstev);  
       glrun->SetNEVENTS(lastev-firstev+1);  
       //  
       glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());  
       glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());  
       glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());  
       glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());  
       glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());  
       glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());  
       glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());  
       glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());  
       glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());  
       glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());  
       glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());  
       glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());  
       glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());  
       glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());  
       glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());  
       glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());  
       //  
       if ( !IsRunAlreadyInserted() ){  
         //  
         //      glrun->SetID(this->AssignRunID());  
         glrun->SetID_RUN_FRAG(glrun1->GetID());  
         glrun->Fill_GL_RUN(conn);  
         //  
         // set id number  
         //  
         glrun1->SetID_RUN_FRAG(glrun->GetID());  
         glrun1->Fill_GL_RUN(conn);  
         //  
       };  
       // delete old entry in fragment table  
       //  
       glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       //  
       delete glrun1;  
       //  
       //  
 //      return;  
       //  
     };  
     //  
   };  
   //  
   //  
  zjustcheck:  
   //  
   if ( !found ){  
     //  
     if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");  
     //  
     // not found, has this run already inserted in the GL_RUN or in the GL_RUN_FRAGMENTS table?  
     //  
     oss.str("");  
     oss << " SELECT ID FROM GL_RUN 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 ){  
       if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");  
       if ( PEDANTIC ) throw -70;  
     } else {  
       if ( NoFrag() ){  
         glrun->SetID_RUN_FRAG(glrun->GetID());  
         glrun->Fill_GL_RUN(conn);  
         glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       };  
     };  
   }; // EEE  
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
3381    
3382                mishead = true;
3383    
3384    
3385                UInt_t rhfirstev = firstentry;
3386                //  UInt_t rtlastev = lastentry;
3387                Bool_t found = false;
3388                Bool_t foundinrun = false;
3389                //
3390                TSQLResult *result = 0;
3391                TSQLRow    *row    = 0;
3392                //
3393                stringstream oss;
3394                oss.str("");
3395                //
3396                // we have now the good first piece of a run, fill the glrun object
3397                //
3398                //  if ( rhfirstev != firstev && !mishead ) mishead = true;
3399                //  if ( rtlastev != lastev && !mistrail ) mistrail = true;
3400                //
3401                //  this->FillClass(mishead,mistrail,firstev,lastev);
3402                //
3403                if ( IsDebug() ) printf("zz The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
3404                if ( IsDebug() ) printf("zz C THIS RUN: RUNHEADER_OBT %u RUNTRAILER_OBT %u RUNHEADER_PKT %u RUNTRAILER_PKT %u \n", glrun->GetRUNHEADER_OBT(),glrun->GetRUNTRAILER_OBT(),glrun->GetRUNHEADER_PKT(),glrun->GetRUNTRAILER_PKT());
3405                //
3406                // First of all insert the run in the fragment table...
3407                //
3408                oss.str("");
3409                oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
3410                    << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3411                    << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3412                    << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3413                    << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3414                    << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3415                    << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3416                    << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3417                    << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3418                    << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3419                    << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3420                    << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3421                    << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3422                    << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3423                //
3424                if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3425                result = conn->Query(oss.str().c_str());
3426                //
3427                if ( !result ) throw -4;
3428                //
3429                row = result->Next();
3430                //
3431                if ( !row ){
3432                  //
3433                  // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
3434                  //
3435                  if ( IsDebug() ) printf(" The run is new \n");
3436                  if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
3437                  //
3438                  glrun->SetID(this->AssignRunID());
3439                  glrun->SetID_RUN_FRAG(0);
3440                  glrun->Fill_GL_RUN_FRAGMENTS(conn);
3441                  //
3442                } else {
3443                  if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
3444                  if ( PEDANTIC ) throw -69;
3445                  //    return;
3446                };
3447                //
3448                if ( chewbacca && mishead && mistrail ) goto zjustcheck;
3449                //
3450                // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
3451                //
3452                if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
3453                  // missing it no way we can found a piece in the frag table
3454                  //
3455                  oss.str("");
3456                  oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "
3457                      << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3458                      << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3459                      << " ID != " << glrun->ID
3460                      << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
3461                  //
3462                  if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());
3463                  result = conn->Query(oss.str().c_str());
3464                  //
3465                  if ( !result ) throw -4;
3466                  //
3467                  row = result->Next();
3468                  //
3469                  if ( !row && NoFrag() ){
3470                    //
3471                    oss.str("");
3472                    oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
3473                        << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3474                        << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3475                        << " ID != " << glrun->ID
3476                        << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
3477                    //
3478                    if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
3479                    result = conn->Query(oss.str().c_str());
3480                    //
3481                    if ( !result ) throw -4;
3482                    //
3483                    foundinrun = true;
3484                    //
3485                    row = result->Next();
3486                    //
3487                  };
3488                  //
3489                  if ( !row ){
3490                    if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
3491                    found = false;
3492                  } else {
3493                    //
3494                    found = false; // default value
3495                    //
3496                    if ( IsDebug() ) printf(" C Found a possible candidate, checking if it is the good one... \n");
3497                    //
3498                    // if we have both runheader and runtrailer we can check with pkt_counter:
3499                    //
3500                    if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){
3501                      ULong64_t chkpkt = 0;
3502                      ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
3503                      ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
3504                      //
3505                      chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;
3506                      //
3507                      if ( labs(chkpkt-pktt)<2 ){
3508                        //
3509                        if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
3510                        //
3511                        found = true;
3512                        //
3513                      } else {
3514                        //
3515                        if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);
3516                        //
3517                        found = false;
3518                        //
3519                      };
3520                    };
3521                    if ( !found && chewbacca ) goto zjustcheck;
3522                    if ( !found ){
3523                      //
3524                      // if we arrive here we were not able to decide if the two pieces matches using only the pkt counter information, we must check times and obts
3525                      //
3526                      ULong64_t chkpkt1 = 0;
3527                      ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
3528                      ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
3529                      chkpkt1 = labs(orunh1-dbrunt1);
3530                      //
3531                      ULong64_t chkpkt2 = 0;
3532                      ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());
3533                      ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
3534                      chkpkt2 = labs(orunh2-dbrunt2);
3535                      //
3536                      ULong64_t chkpkt3 = 0;
3537                      ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());
3538                      ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
3539                      chkpkt3 = labs(orunh3-dbrunt3);
3540                      //
3541                      if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
3542                        //    if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){
3543                        //
3544                        if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
3545                        //
3546                        found = true;
3547                        //
3548                      } else {
3549                        //
3550                        if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
3551                        //
3552                        found = false;
3553                        //
3554                      };
3555                    };
3556                  };
3557                  //
3558                  if ( found ){
3559                    //
3560                    // we have found the missing piece, glue the two together, merge the informations, fill the gl_run table (check first runs do not exists), delete entry in frag table
3561                    //
3562                    if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
3563                    //
3564                    if ( foundinrun ){
3565                      glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3566                      glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
3567                    };
3568                    //
3569                    GL_RUN *glrun1 = new GL_RUN();
3570                    //
3571                    //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
3572                    //
3573                    oss.str("");
3574                    oss << " ID="<<row->GetField(0)<<";";
3575                    //
3576                    glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos
3577                    //
3578                    // merge infos
3579                    //
3580                    UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());
3581                    ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
3582                    UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
3583                    ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
3584                    if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
3585                    TTree *T= 0;
3586                    T = (TTree*)file->Get("Physics");
3587                    if ( !T || T->IsZombie() ) throw -16;
3588                    EventHeader *eh = 0;
3589                    PscuHeader *ph = 0;
3590                    T->SetBranchAddress("Header", &eh);
3591                    while ( apkt > bpkt && aobt > bobt && firstev < lastev ){
3592                      T->GetEntry(firstev);
3593                      ph = eh->GetPscuHeader();
3594                      bpkt = PKT(ph->GetCounter());
3595                      bobt = OBT(ph->GetOrbitalTime());
3596                      firstev++;
3597                      if ( PEDANTIC ) throw -71;
3598                    };
3599                    if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
3600                    //
3601                    glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
3602                    glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
3603                    glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
3604                    glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());
3605                    glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());
3606                    //
3607                    glrun->SetEV_FROM(firstev);
3608                    glrun->SetNEVENTS(lastev-firstev+1);
3609                    //
3610                    glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
3611                    glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
3612                    glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
3613                    glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());
3614                    glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());
3615                    glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());
3616                    glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());
3617                    glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());
3618                    glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());
3619                    glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());
3620                    glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());
3621                    glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());
3622                    glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());
3623                    glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());
3624                    glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());
3625                    glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());
3626                    //
3627                    if ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
3628                    if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
3629                    //
3630                    if ( !IsRunAlreadyInserted() ){
3631                      //
3632                      //      glrun->SetID(this->AssignRunID());
3633                      glrun->SetID_RUN_FRAG(glrun1->GetID());
3634                      glrun->Fill_GL_RUN(conn);
3635                      //
3636                      // set id number
3637                      //
3638                      glrun1->SetID_RUN_FRAG(glrun->GetID());
3639                      glrun1->Fill_GL_RUN(conn);
3640                      //
3641                    };
3642                    // delete old entry in fragment table
3643                    //
3644                    glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3645                    glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3646                    //
3647                    delete glrun1;
3648                    //
3649                    //
3650                    //      return;
3651                    //
3652                  };
3653                  //
3654                };
3655                //
3656                //
3657              zjustcheck:
3658                //
3659                if ( !found ){
3660                  //
3661                  if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");
3662                  //
3663                  // not found, has this run already inserted in the GL_RUN or in the GL_RUN_FRAGMENTS table?
3664                  //
3665                  oss.str("");
3666                  oss << " SELECT ID FROM GL_RUN WHERE "
3667                      << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3668                      << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3669                      << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3670                      << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3671                      << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3672                      << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3673                      << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3674                      << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3675                      << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3676                      << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3677                      << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3678                      << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3679                      << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3680                  //
3681                  if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3682                  result = conn->Query(oss.str().c_str());
3683                  //
3684                  if ( !result ) throw -4;
3685                  //
3686                  row = result->Next();
3687                  //
3688                  if ( row ){
3689                    if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");
3690                    if ( PEDANTIC ) throw -70;
3691                  } else {
3692                    if ( NoFrag() ){
3693                      glrun->SetID_RUN_FRAG(glrun->GetID());
3694                      glrun->Fill_GL_RUN(conn);
3695                      glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3696                    };
3697                  };
3698                }; // EEE
3699    
3700    
3701            } else {            } else {
3702            if ( !IsRunAlreadyInserted() ){              if ( !IsRunAlreadyInserted() ){
3703              glrun->SetID(this->AssignRunID());                glrun->SetID(this->AssignRunID());
3704              glrun->SetID_RUN_FRAG(0);                glrun->SetID_RUN_FRAG(0);
3705              glrun->Fill_GL_RUN(conn);                glrun->Fill_GL_RUN(conn);
3706            };              };
3707            }; // EEE            }; // EEE
3708            //            //
3709            firstevno = lastentry + 1;            firstevno = lastentry + 1;
# Line 3564  Bool_t PamelaDBOperations::IsRunConsiste Line 3712  Bool_t PamelaDBOperations::IsRunConsiste
3712            //            //
3713          };          };
3714          //          //
3715            if ( i > firstev ){
3716              if ( rhchko != rhchk ){
3717                if ( IsDebug() ) printf("oh oh... we have a runheader! stop here and handle later the remaining piece\n");
3718                lastev = i;
3719                return(false);
3720              };
3721            };
3722            //
3723          if ( check == checklast && i != lastev ){          if ( check == checklast && i != lastev ){
3724            lastevtemp = i - 1;            lastevtemp = i - 1;
3725            i = lastev - 1;            i = lastev - 1;
# Line 3647  void PamelaDBOperations::HandleSuspiciou Line 3803  void PamelaDBOperations::HandleSuspiciou
3803      code = eh->GetCounter();      code = eh->GetCounter();
3804      checkfirst = 0;      checkfirst = 0;
3805      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3806         if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
3807         if ( !strcmp(*Iter,"RunHeader") ) nrunh1++;        if ( !strcmp(*Iter,"RunHeader") ) nrunh1++;
3808       };      };
3809      if ( IsDebug() ) printf(" Check first is %i \n",checkfirst);      if ( IsDebug() ) printf(" Check first is %i \n",checkfirst);
3810      //      //
3811      T->GetEntry(lastev);      T->GetEntry(lastev);
3812      code = eh->GetCounter();      code = eh->GetCounter();
3813      checklast = 0;      checklast = 0;
3814      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3815         if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
3816       };      };
3817      if ( IsDebug() ) printf(" Check last is %i \n",checklast);      if ( IsDebug() ) printf(" Check last is %i \n",checklast);
3818      //      //
3819      if ( checkfirst == checklast ){      if ( checkfirst == checklast ){
# Line 3769  void PamelaDBOperations::HandleSuspiciou Line 3925  void PamelaDBOperations::HandleSuspiciou
3925            };            };
3926            //                  //      
3927            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
3928              this->SetPhysEndRunVariables();
3929            //            //
3930            if ( !IsRunAlreadyInserted() ){            if ( !IsRunAlreadyInserted() ){
3931              glrun->SetID(this->AssignRunID());              glrun->SetID(this->AssignRunID());
# Line 3808  void PamelaDBOperations::HandleSuspiciou Line 3965  void PamelaDBOperations::HandleSuspiciou
3965              if ( IsDebug() ) printf(" We have the runtrailer \n");              if ( IsDebug() ) printf(" We have the runtrailer \n");
3966              //                  //    
3967              this->SetCommonGLRUN(firstTime,lastTime);              this->SetCommonGLRUN(firstTime,lastTime);
3968                this->SetPhysEndRunVariables();
3969              //              //
3970              if ( !IsRunAlreadyInserted() ){              if ( !IsRunAlreadyInserted() ){
3971                glrun->SetID(this->AssignRunID());                glrun->SetID(this->AssignRunID());
# Line 4382  Int_t PamelaDBOperations::insertCALOPULS Line 4540  Int_t PamelaDBOperations::insertCALOPULS
4540   * Fill the GL_TRK_CALIB table   * Fill the GL_TRK_CALIB table
4541   */   */
4542  void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){  void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){
4543    //      
4544    TSQLResult *result = 0;      GL_TRK_CALIB *glcal = new GL_TRK_CALIB();
   TSQLRow    *row    = 0;  
   //  
   stringstream oss;  
   oss.str("");  
   //  
   UInt_t totime = 0;  
   //  
   if ( !pk1 && !pk2 ){  
     if ( IsDebug() ) printf(" Cannot handle trk calibration with both packet missing!\n");  
     return;  
   };  
   //  
   // check if the calibration has already been inserted  
   //  
   oss.str("");  
   oss << " SELECT ID FROM GL_TRK_CALIB WHERE "  
       << " BOOT_NUMBER = "<< this->GetBOOTnumber(); //  
   oss << " AND ( ( ";    
   if ( pk1 ){  
     oss << " OBT1 = "<< obt1 << " AND "  
         << " PKT1 = "<< pkt1  
         << " ) OR ( ";  
   } else {  
     oss << " PKT1 = "<< pkt2-1  
         << " ) OR ( ";    
   };        
   if ( pk2 ){  
     oss << " OBT2 = "<< obt2 << " AND "  
         << " PKT2 = "<< pkt2;  
   } else {  
     oss << " PKT2 = "<< pkt1+1;  
   };        
   oss << " ) );";    
   //  
   if ( IsDebug() ) printf(" Check if the trk calibration has already been inserted: query is \n %s \n",oss.str().c_str());  
   result = conn->Query(oss.str().c_str());  
   //  
   if ( !result ) throw -4;  
   //  
   row = result->Next();  
   //  
   if ( row ){  
     //  
     if ( IsDebug() ) printf(" Trk calibration already inserted in the DB\n");  
     if ( PEDANTIC ) throw -80;  
4545      //      //
4546    } else {      glcal->ID         = 0;
4547        glcal->ID_ROOT_L0 = GetID_ROOT();
4548        glcal->EV_ROOT_CALIBTRK1 = t1;
4549        glcal->EV_ROOT_CALIBTRK2 = t2;
4550        glcal->FROM_TIME = fromtime;
4551        glcal->TO_TIME   = 0;
4552        glcal->OBT1      = obt1;
4553        glcal->OBT2      = obt2;
4554        glcal->PKT1      = pkt1;
4555        glcal->PKT2      = pkt2;
4556        glcal->BOOT_NUMBER = GetBOOTnumber();
4557        glcal->VALIDATION = valid;
4558      //      //
4559      // we have to insert a new calibration, check where to place it      HandleTRK_CALIB(glcal);
4560      //      //
4561      oss.str("");      delete glcal;
4562      oss << " SELECT ID,TO_TIME FROM GL_TRK_CALIB WHERE "  }
4563          << " FROM_TIME < "<< fromtime << " AND "  /**
4564          << " TO_TIME > "<< fromtime << ";";   * Fill the GL_TRK_CALIB table
4565     */
4566    void PamelaDBOperations::HandleTRK_CALIB(GL_TRK_CALIB *glcal){
4567    
4568        Bool_t pk1 = (glcal->OBT1>0&&glcal->PKT1>0);
4569        Bool_t pk2 = (glcal->OBT2>0&&glcal->PKT2>0);
4570        UInt_t boot_number = glcal->BOOT_NUMBER;
4571        UInt_t obt1 = glcal->OBT1;
4572        UInt_t obt2 = glcal->OBT2;
4573        UInt_t pkt1 = glcal->PKT1;
4574        UInt_t pkt2 = glcal->PKT2;
4575        UInt_t fromtime = glcal->FROM_TIME;
4576        UInt_t totime = 0;
4577        UInt_t idroot = glcal->ID_ROOT_L0;
4578        UInt_t t1 = glcal->EV_ROOT_CALIBTRK1;
4579        UInt_t t2 = glcal->EV_ROOT_CALIBTRK2;
4580        UInt_t valid = glcal->VALIDATION;
4581      //      //
4582      if ( IsDebug() ) printf(" Check where to place the trk calibration: query is \n %s \n",oss.str().c_str());      TSQLResult *result = 0;
4583      result = conn->Query(oss.str().c_str());      TSQLRow    *row    = 0;
4584      //      //
4585      if ( !result ) throw -4;      stringstream oss;
4586        oss.str("");
4587      //      //
     row = result->Next();  
4588      //      //
4589      if ( !row ){      if ( !pk1 && !pk2 ){
4590        //          if ( IsDebug() ) printf(" Cannot handle trk calibration with both packet missing!\n");
4591        // no calibrations in the db contain our calibration          return;
       //  
       if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB\n");  
       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  
       //  
       oss.str("");  
       oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "  
           << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";  
       //  
       if ( IsDebug() ) printf(" Check the upper limit for calibration: 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 ){  
         totime = numeric_limits<UInt_t>::max();  
       } else {  
         totime = (UInt_t)atoll(row->GetField(0));  
       };  
       //  
     } else {  
       //  
       // determine upper and lower limits and make space for the new calibration  
       //  
       totime = (UInt_t)atoll(row->GetField(1));  
       //  
       oss.str("");  
       oss << " UPDATE GL_TRK_CALIB SET "    
           << " TO_TIME = "<< fromtime << " WHERE "  // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[  
           << " ID = "<< row->GetField(0) << ";";  
       //  
       if ( IsDebug() ) printf(" Make space for the new trk calibration: query is \n %s \n",oss.str().c_str());  
       result = conn->Query(oss.str().c_str());  
       //  
       if ( !result ) throw -4;  
       //  
4592      };      };
4593      //      //
4594      oss.str("");      // check if the calibration has already been inserted
     oss << " INSERT INTO GL_TRK_CALIB (ID,ID_ROOT_L0,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,FROM_TIME,TO_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION) "  
         << " VALUES (NULL,' "  
         << idroot << "',";  
4595      //      //
4596      if ( !pk1 ){      oss.str("");
4597        oss << "NULL,";      oss << " SELECT ID FROM GL_TRK_CALIB WHERE "
4598            << " BOOT_NUMBER = "<< boot_number; //
4599        oss << " AND FROM_TIME="<<fromtime; /// NEWNEWNEW -- VA BENE ?!?!?!?!
4600        oss << " AND ( ( ";  
4601        if ( pk1 ){
4602            oss << " OBT1 = "<< obt1 << " AND "
4603                << " PKT1 = "<< pkt1
4604                << " ) OR ( ";
4605      } else {      } else {
4606        oss << "'"          oss << " PKT1 = "<< pkt2-1
4607            << t1 << "',";              << " ) OR ( ";  
4608      };      };      
4609      //      if ( pk2 ){
4610      if ( !pk2 ){          oss << " OBT2 = "<< obt2 << " AND "
4611        oss << "NULL,'";              << " PKT2 = "<< pkt2;
4612      } else {      } else {
4613        oss << "'"          oss << " PKT2 = "<< pkt1+1;
4614            << t2 << "','";      };      
4615      };      oss << " ) );";  
     //  
     oss << fromtime << "','"  
         << totime << "','"  
         << obt1 << "','"  
         << pkt1 << "','"  
         << obt2 << "','"  
         << pkt2 << "','"  
         << this->GetBOOTnumber() << "','"  
         << valid << "');";  
     //  
     if ( IsDebug() ) printf(" Insert the new trk calibration: query is \n %s \n",oss.str().c_str());  
4616      //      //
4617        if ( IsDebug() ) printf(" Check if the trk calibration has already been inserted: query is \n %s \n",oss.str().c_str());
4618      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
4619      //      //
4620      if ( !result ) throw -4;      if ( !result ) throw -4;
4621      //      //
4622    };      row = result->Next();
4623    //      //
4624        if ( row ){
4625            //
4626            if ( IsDebug() ) printf(" Trk calibration already inserted in the DB\n");
4627            if ( PEDANTIC ) throw -80;
4628            //
4629        } else {
4630            //
4631            // we have to insert a new calibration, check where to place it
4632            //
4633            oss.str("");
4634            oss << " SELECT ID,TO_TIME FROM GL_TRK_CALIB WHERE "
4635                << " FROM_TIME < "<< fromtime << " AND "
4636                << " TO_TIME > "<< fromtime << ";";
4637            //
4638            if ( IsDebug() ) printf(" Check where to place the trk calibration: query is \n %s \n",oss.str().c_str());
4639            result = conn->Query(oss.str().c_str());
4640            //
4641            if ( !result ) throw -4;
4642            //
4643            row = result->Next();
4644            //
4645            if ( !row ){
4646                //
4647                // no calibrations in the db contain our calibration
4648                //
4649                if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB\n");
4650                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
4651                //
4652                oss.str("");
4653                oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "
4654                    << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
4655                //
4656                if ( IsDebug() ) printf(" Check the upper limit for calibration: query is \n %s \n",oss.str().c_str());
4657                result = conn->Query(oss.str().c_str());
4658                //
4659                if ( !result ) throw -4;
4660                //
4661                row = result->Next();
4662                if ( !row ){
4663                    totime = numeric_limits<UInt_t>::max();
4664                } else {
4665                    totime = (UInt_t)atoll(row->GetField(0));
4666                };
4667                //
4668            } else {
4669                //
4670                // determine upper and lower limits and make space for the new calibration
4671                //
4672                totime = (UInt_t)atoll(row->GetField(1));
4673                //
4674                oss.str("");
4675                oss << " UPDATE GL_TRK_CALIB SET "  
4676                    << " TO_TIME = "<< fromtime << " WHERE "  // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
4677                    << " ID = "<< row->GetField(0) << ";";
4678                //
4679                if ( IsDebug() ) printf(" Make space for the new trk calibration: query is \n %s \n",oss.str().c_str());
4680                result = conn->Query(oss.str().c_str());
4681                //
4682                if ( !result ) throw -4;
4683                //
4684            };
4685            //
4686            oss.str("");
4687            oss << " INSERT INTO GL_TRK_CALIB (ID,ID_ROOT_L0,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,FROM_TIME,TO_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION) "
4688                << " VALUES (NULL,' "
4689                << idroot << "',";
4690            //
4691            if ( !pk1 ){
4692                oss << "NULL,";
4693            } else {
4694                oss << "'"
4695                    << t1 << "',";
4696            };
4697            //
4698            if ( !pk2 ){
4699                oss << "NULL,'";
4700            } else {
4701                oss << "'"
4702                    << t2 << "','";
4703            };
4704            //
4705            oss << fromtime << "','"
4706                << totime << "','"
4707                << obt1 << "','"
4708                << pkt1 << "','"
4709                << obt2 << "','"
4710                << pkt2 << "','"
4711                << boot_number << "','"
4712                << valid << "');";
4713            //
4714            if ( IsDebug() ) printf(" Insert the new trk calibration: query is \n %s \n",oss.str().c_str());
4715            //
4716            result = conn->Query(oss.str().c_str());
4717            //
4718            if ( !result ) throw -4;
4719            //
4720        };
4721        
4722        oss.str("");
4723        oss << " SELECT ID FROM GL_TRK_CALIB ORDER BY ID DESC LIMIT 1 ;";  
4724        if ( IsDebug() ) cout << oss.str().c_str() << endl;
4725        result = conn->Query(oss.str().c_str());
4726        if ( !result ) throw -4;;
4727        row = result->Next();
4728        if(row)glcal->ID = (UInt_t)atoll(row->GetField(0));
4729    
4730        //
4731  };  };
4732    
4733  /**  /**
4734   * Scan tracker calibrations packets, fill the GL_TRK_CALIB table   * Scan tracker calibrations packets, fill the GL_TRK_CALIB table
4735   */   */
4736  Int_t PamelaDBOperations::insertTRK_CALIB(){  Int_t PamelaDBOperations::insertTRK_CALIB(){
   //  
   CalibTrk1Event *caltrk1 = 0;  
   CalibTrk2Event *caltrk2 = 0;  
   TTree *tr1 = 0;  
   TTree *tr2 = 0;  
   EventHeader *eh1 = 0;  
   PscuHeader *ph1 = 0;  
   EventHeader *eh2 = 0;  
   PscuHeader *ph2 = 0;  
   //  
   PacketType *pctp=0;  
   EventCounter *codt2=0;  
   //  
   Int_t nevents1 = 0;  
   Int_t nevents2 = 0;  
   //  
   fromtime = 0;  
   //  
   obt1 = 0;  
   pkt1 = 0;  
   obt2 = 0;  
   pkt2 = 0;  
   //  
   tr1 = (TTree*)file->Get("CalibTrk1");  
   if ( !tr1 || tr1->IsZombie() ) throw -22;  
   tr2 = (TTree*)file->Get("CalibTrk2");  
   if ( !tr2 || tr2->IsZombie() ) throw -23;  
   //  
   tr1->SetBranchAddress("CalibTrk1", &caltrk1);  
   tr1->SetBranchAddress("Header", &eh1);  
   nevents1 = tr1->GetEntries();  
   tr2->SetBranchAddress("CalibTrk2", &caltrk2);  
   tr2->SetBranchAddress("Header", &eh2);  
   nevents2 = tr2->GetEntries();  
   //  
   if ( !nevents1 && !nevents2 ) return(1);  
   //  
   t2 = -1;  
   Int_t pret2 = 0;  
   Int_t t2t1cal = 0;  
   //  
   for (t1=0; t1 < nevents1; t1++){  
4737      //      //
4738      pret2 = t2;      CalibTrk1Event *caltrk1 = 0;
4739      tr1->GetEntry(t1);      CalibTrk2Event *caltrk2 = 0;
4740        TTree *tr1 = 0;
4741        TTree *tr2 = 0;
4742        EventHeader *eh1 = 0;
4743        PscuHeader *ph1 = 0;
4744        EventHeader *eh2 = 0;
4745        PscuHeader *ph2 = 0;
4746      //      //
4747      ph1 = eh1->GetPscuHeader();      PacketType *pctp=0;
4748      obt1 = ph1->GetOrbitalTime();        EventCounter *codt2=0;
     pkt1 = ph1->GetCounter();    
     fromtime = this->GetAbsTime(ph1->GetOrbitalTime());    
4749      //      //
4750  //     valid = 1;      Int_t nevents1 = 0;
4751  //     //      Int_t nevents2 = 0;
 //     if ( caltrk1->unpackError != 0 && caltrk1->good0 == 0 ) valid = 0;// CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT1  
4752      //      //
4753        fromtime = 0;
4754      //      //
4755      if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->PKT(pkt1) <= upperpkt && this->OBT(obt1) >= this->OBT(obtfirst) && this->OBT(obt1) <= upperobt ){      obt1 = 0;
4756        //    if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->OBT(obt1) >= this->OBT(obtfirst) ){      pkt1 = 0;
4757        //      obt2 = 0;
4758        if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u \n",fromtime,obt1,pkt1);      pkt2 = 0;
4759        //            //
4760        valid = ValidateTrkCalib( caltrk1, eh1 );      tr1 = (TTree*)file->Get("CalibTrk1");
4761        if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;      if ( !tr1 || tr1->IsZombie() ) throw -22;
4762        //      tr2 = (TTree*)file->Get("CalibTrk2");
4763        // Do we have the second calibration packet?      if ( !tr2 || tr2->IsZombie() ) throw -23;
4764        //      //
4765        while ( t2t1cal < t1+1 ){ // get the calibration packet2 that follows the packet1      tr1->SetBranchAddress("CalibTrk1", &caltrk1);
4766        tr1->SetBranchAddress("Header", &eh1);
4767        nevents1 = tr1->GetEntries();
4768        tr2->SetBranchAddress("CalibTrk2", &caltrk2);
4769        tr2->SetBranchAddress("Header", &eh2);
4770        nevents2 = tr2->GetEntries();
4771        //
4772        if ( !nevents1 && !nevents2 ) return(1);
4773        //
4774        t2 = -1;
4775        Int_t pret2 = 0;
4776        Int_t t2t1cal = 0;
4777        //
4778        bool MISSING_pkt1 = true;
4779        bool MISSING_pkt2 = true;
4780        int  ncalib = 0;
4781        bool try_to_recover = false;
4782        //
4783        for (t1=0; t1 < nevents1; t1++){//loop over packet1
4784            //
4785            pret2 = t2;
4786            tr1->GetEntry(t1);
4787          //          //
4788          t2++;          ph1 = eh1->GetPscuHeader();
4789            obt1 = ph1->GetOrbitalTime();  
4790            pkt1 = ph1->GetCounter();  
4791            fromtime = GetAbsTime(ph1->GetOrbitalTime());  
4792          //          //
4793          pret2 = t2 - 1; // EMILIANO          // chek if the packet number and obt are consistent with the other packets ???
4794          //          //
4795          if ( t2 < nevents2 ){          if ( PKT(pkt1) >= PKT(pktfirst) && PKT(pkt1) <= upperpkt && OBT(obt1) >= OBT(obtfirst) && OBT(obt1) <= upperobt ){
4796            tr2->GetEntry(t2);              //    if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->OBT(obt1) >= this->OBT(obtfirst) ){
4797            codt2 = eh2->GetCounter();              //
4798            t2t1cal = codt2->Get(pctp->CalibTrk1);              if ( IsDebug() ) printf("\n Trk calibration1 %u at time %u obt %u pkt %u \n",t1,fromtime,obt1,pkt1);
4799            //              //      
4800            ph2 = eh2->GetPscuHeader();              valid = ValidateTrkCalib( caltrk1, eh1 );
4801            obt2 = ph2->GetOrbitalTime();                if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;
4802            pkt2 = ph2->GetCounter();                //
4803            //              // Do we have the second calibration packet?
4804            if ( IsDebug() ) printf(" This is a trk calibration2 at obt %u pkt %u t2 is %u , t2t1cal is %u \n",obt2,pkt2,t2,t2t1cal);                    //
4805  //        if ( caltrk2->unpackError != 0 || caltrk2->good0 == 0 ) valid = 0; // CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT2              if ( IsDebug() ) cout << " Loop over calibration2 to search associated calibration: "<<endl;
4806            //                    while ( t2t1cal < t1+1 ){ // get the calibration packet2 that follows the packet1
4807                    //
4808                    t2++;
4809                    //
4810                    pret2 = t2 - 1; // EMILIANO
4811                    //
4812                    if ( t2 < nevents2 ){
4813                        tr2->GetEntry(t2);
4814                        codt2 = eh2->GetCounter();
4815                        t2t1cal = codt2->Get(pctp->CalibTrk1);
4816                        //
4817                        ph2 = eh2->GetPscuHeader();
4818                        obt2 = ph2->GetOrbitalTime();  
4819                        pkt2 = ph2->GetCounter();  
4820                        //
4821                        if ( IsDebug() ) printf(" >> trk calibration2 at obt %u pkt %u t2 is %u , t2t1cal is %u \n",obt2,pkt2,t2,t2t1cal);    
4822                        //    if ( caltrk2->unpackError != 0 || caltrk2->good0 == 0 ) valid = 0; // CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT2
4823                        //    
4824                    } else {
4825                        //
4826                        // running out of vector without finding the corresponding calibration, sig
4827                        //
4828                        if ( IsDebug() ) printf(" t2 >= nevents2 \n");
4829                        pret2 = t2;
4830                        obt2 = 0;
4831                        //    pkt2 = pkt1+2;
4832                        pkt2 = 0;
4833                        t2t1cal = t1+1;
4834                    };
4835                    //      if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) && (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){
4836    
4837                    // EMILIANO
4838                    //      if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) || (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){
4839                    //        //    if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){
4840                    //        if ( IsDebug() ) printf(" running out of vector without finding the corresponding calibration, sig \n");
4841                    //        //
4842                    //        // running out of vector without finding the corresponding calibration, sig
4843                    //        //
4844                    //        pret2 = t2;
4845                    //        obt2 = 0;
4846                    //        //      pkt2 = pkt1+2;
4847                    //        pkt2 = 0;
4848                    //        t2t1cal = t1+1;
4849                    //      };
4850    
4851    
4852                    //
4853                };
4854                //
4855                if ( IsDebug() ) printf(" Check if trk calibration2 is the right one \n");
4856                //
4857                // EMILIANO
4858                if ( ( PKT(pkt2) < PKT(pktfirst) || PKT(pkt2) > upperpkt) || (OBT(obt2) < OBT(obtfirst) || OBT(obt2) > upperobt) ){
4859                    //      if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){
4860                    if ( IsDebug() ) printf(" *WARNING*  The calibration found is outside the interval, sig \n");
4861                    //
4862                    // running out of vector without finding the corresponding calibration, sig
4863                    //
4864                    pret2 = t2;
4865                    obt2 = 0;
4866                    pkt2 = 0;
4867                };
4868                if ( PKT(pkt2) == PKT(pkt1)+1 ){
4869                    if ( IsDebug() ) cout << " ...OK"<<endl;
4870                    // =======================
4871                    // The calibration is good
4872                    // =======================
4873                    //
4874    //      if ( IsDebug() ) printf(" Found trk calibration2 at obt %u pkt %u t2 is %u \n",obt2,pkt2,t2);
4875    //      if ( IsDebug() ) printf(" Trk calibration2 at obt %u pkt %u t2 is %u is good \n",obt2,pkt2,t2);
4876    //        if ( IsDebug() ) printf("\n Trk calibration2 at time %u obt %u pkt %u \n",fromtime,obt2,pkt2);
4877                    if ( IsDebug() ) printf(" Trk calibration2 %u at time %u obt %u pkt %u \n",t2,fromtime,obt2,pkt2);
4878                    //
4879                    UInt_t valid2 = ValidateTrkCalib( caltrk2, eh2 );
4880                    if ( IsDebug() ) cout << " pkt2 validation --> "<<valid2<<endl;
4881    //      valid = valid & valid2;
4882                    valid = valid & valid2; //QUESTO VA CAMBIATO
4883                    //
4884                    // Handle good calib
4885                    //
4886                    MISSING_pkt1 = false;
4887                    MISSING_pkt2 = false;
4888    //              this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4889                    //
4890                    // Check for missing calibtrk1
4891                    //
4892                    if ( t2 != pret2+1 ){
4893                        //
4894                        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);
4895                        //
4896                        while ( t2 > pret2+1 ){
4897                            //
4898                            // handle missing calib1
4899                            //
4900                            pret2++;
4901                            //
4902                            obt1 = 0;
4903                            pkt1 = 0;
4904                            //
4905                            tr2->GetEntry(pret2);
4906                            ph2 = eh2->GetPscuHeader();
4907                            obt2 = ph2->GetOrbitalTime();  
4908                            pkt2 = ph2->GetCounter();  
4909                            //
4910                            fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
4911                            //
4912                            valid = 0;
4913                            MISSING_pkt1 = true;
4914                            MISSING_pkt2 = false;
4915    //                      this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4916                            //
4917                        };
4918                        //
4919                    };
4920                    //
4921                } else if ( this->PKT(pkt2) > this->PKT(pkt1)+1 ){
4922                    //
4923                    // Check for missing calibtrk2
4924                    //
4925                    if ( IsDebug() ) printf(" Missing the trk calibration2! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);
4926                    t2 = pret2;
4927                    //
4928                    // handle missing calib2
4929                    //
4930                    obt2 = 0;
4931                    pkt2 = 0;
4932                    valid = 0;
4933                    MISSING_pkt1 = false;
4934                    MISSING_pkt2 = true;
4935    //              this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4936                    //
4937                };
4938                //
4939    
4940                if( !(MISSING_pkt1&MISSING_pkt2) ){
4941                  this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4942                  ncalib++;
4943                  if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
4944                }
4945    
4946    
4947          } else {          } else {
4948            //            //
4949            // running out of vector without finding the corresponding calibration, sig              if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u OUTSIDE the considered time interval \n",fromtime,obt1,pkt1);
4950            //              //      if ( PEDANTIC ) throw -79;
4951            if ( IsDebug() ) printf(" t2 >= nevents2 \n");              //
           pret2 = t2;  
           obt2 = 0;  
           //      pkt2 = pkt1+2;  
           pkt2 = 0;  
           t2t1cal = t1+1;  
4952          };          };
4953          //      if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) && (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){          //    
4954    
4955          // EMILIANO      }; //end loop on pkt1
 //      if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) || (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){  
 //        //    if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){  
 //        if ( IsDebug() ) printf(" running out of vector without finding the corresponding calibration, sig \n");  
 //        //  
 //        // running out of vector without finding the corresponding calibration, sig  
 //        //  
 //        pret2 = t2;  
 //        obt2 = 0;  
 //        //      pkt2 = pkt1+2;  
 //        pkt2 = 0;  
 //        t2t1cal = t1+1;  
 //      };  
4956    
4957    
4958    
4959        //
4960        // we have one more calib pkt2 !
4961        //
4962        t2++;
4963        while ( t2 < nevents2 ){
4964          //          //
4965        };          // handle missing calib1
       //  
       if ( IsDebug() ) printf(" Check if trk calibration2 exists \n");  
       //  
       // EMILIANO  
       if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) || (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){  
         //      if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){  
         if ( IsDebug() ) printf(" The calibration found is outside the interval, sig \n");  
         //  
         // running out of vector without finding the corresponding calibration, sig  
         //  
         pret2 = t2;  
         obt2 = 0;  
         pkt2 = 0;  
       };  
       //  
       // The calibration is good  
       //  
       if ( this->PKT(pkt2) == this->PKT(pkt1)+1 ){  
         //  
         if ( IsDebug() ) printf(" Found trk calibration2 at obt %u pkt %u t2 is %u \n",obt2,pkt2,t2);  
         if ( IsDebug() ) printf(" The trk calibration2 at obt %u pkt %u t2 is %u is good \n",obt2,pkt2,t2);  
         //  
         UInt_t valid2 = ValidateTrkCalib( caltrk2, eh2 );  
         if ( IsDebug() ) cout << " pkt2 validation --> "<<valid2<<endl;  
         valid = valid & valid2;  
         //  
         // Handle good calib  
4966          //          //
4967          this->HandleTRK_CALIB(true,true);          if ( IsDebug() ) printf(" t2 is %u nevents2 is %u \n",t2,nevents2);
4968            obt1 = 0;
4969            pkt1 = 0;
4970          //          //
4971          // Check for missing calibtrk1          tr2->GetEntry(t2);
4972            ph2 = eh2->GetPscuHeader();
4973            obt2 = ph2->GetOrbitalTime();  
4974            pkt2 = ph2->GetCounter();  
4975          //          //
4976          if ( t2 != pret2+1 ){          fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
4977            //          valid = 0;
4978            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);          //  if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->PKT(pkt1) <= upperpkt && this->OBT(obt1) >= this->OBT(obtfirst) && this->OBT(obt1) <= upperobt ){
4979            //          // EMILIANO
4980            while ( t2 > pret2+1 ){          if ( this->PKT(pkt2) >= this->PKT(pktfirst) && this->PKT(pkt2 <= upperpkt) && this->OBT(obt2) >= this->OBT(obtfirst) && this->OBT(obt2) <= upperobt ){
4981              //              //    if ( this->PKT(pkt2) > this->PKT(pktfirst) || this->OBT(obt2) > this->OBT(obtfirst) ){
             // handle missing calib1  
             //  
             pret2++;  
             //  
             obt1 = 0;  
             pkt1 = 0;  
             //  
             tr2->GetEntry(pret2);  
             ph2 = eh2->GetPscuHeader();  
             obt2 = ph2->GetOrbitalTime();    
             pkt2 = ph2->GetCounter();    
4982              //              //
4983              fromtime = this->GetAbsTime(ph2->GetOrbitalTime());              if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);
4984              //              //
4985              valid = 0;              MISSING_pkt1 = true;
4986              this->HandleTRK_CALIB(false,true);              MISSING_pkt2 = false;
4987                this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4988                ncalib++;
4989                if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
4990              //              //
           };  
           //  
4991          };          };
4992          //          //
4993        } else if ( this->PKT(pkt2) > this->PKT(pkt1)+1 ){          t2++;
         //  
         // Check for missing calibtrk2  
         //  
         if ( IsDebug() ) printf(" Missing the trk calibration2! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);  
         t2 = pret2;  
4994          //          //
4995          // handle missing calib2      };
4996    
4997    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
4998    // -----------------------------------------------------------------
4999    // in case of corruption, check if the calibration can be recovered
5000    // from another chewbacca file
5001    // -----------------------------------------------------------------
5002    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
5003    
5004    //    cout <<" TRY TO RECOVER ?? "<<try_to_recover<<endl;
5005        
5006        if(chewbacca&&try_to_recover){
5007    
5008    
5009            if ( IsDebug() ) cout << endl << ">>>> TRY TO RECOVER TRACKER CALIBRATIONS <<<<"<<endl;
5010    
5011            TSQLResult *result = 0;
5012            TSQLRow    *row    = 0;
5013          //          //
5014          obt2 = 0;          stringstream oss;
5015          pkt2 = 0;          oss.str("");
         valid = 0;  
         this->HandleTRK_CALIB(true,false);        
5016          //          //
5017        };  
5018        //          ////////////////////////////////////////////////////////////////////////
5019      } else {          // retrieve the name of the current file:
5020        //          ////////////////////////////////////////////////////////////////////////        
5021        if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u OUTSIDE the considered time interval \n",fromtime,obt1,pkt1);          oss.str("");
5022        //      if ( PEDANTIC ) throw -79;          oss << "SELECT NAME FROM GL_ROOT where ID=" << GetID_ROOT() <<";";
5023        //          if ( IsDebug() ) cout << oss.str().c_str() << endl;
5024      };  
5025      //              result = conn->Query(oss.str().c_str());
5026    };          if ( !result ) throw -4;;
5027    //          row = result->Next();
5028    // we have one more calib pkt2 !          TString thisfilename = (TString)row->GetField(0);
5029    //          if ( IsDebug() ) cout << "Current file ==> "<<thisfilename<<endl;      
5030    t2++;  
5031    while ( t2 < nevents2 ){          ////////////////////////////////////////////////////////////////////////        
5032      //          // read all the calibrations inserted
5033      // handle missing calib1          ////////////////////////////////////////////////////////////////////////        
5034      //          oss.str("");
5035      if ( IsDebug() ) printf(" t2 is %u nevents2 is %u \n",t2,nevents2);          oss << " SELECT ";
5036      obt1 = 0;          oss << " ID,FROM_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,TO_TIME";
5037      pkt1 = 0;          oss << " FROM GL_TRK_CALIB ";
5038      //          oss << " ORDER BY ID DESC LIMIT "<<ncalib<<"; ";        
5039      tr2->GetEntry(t2);          if ( IsDebug() ) cout << oss.str().c_str() << endl;
5040      ph2 = eh2->GetPscuHeader();  
5041      obt2 = ph2->GetOrbitalTime();            result = conn->Query(oss.str().c_str());
5042      pkt2 = ph2->GetCounter();            if ( !result ) throw -4;;
5043      //          if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5044      fromtime = this->GetAbsTime(ph2->GetOrbitalTime());          
5045      valid = 0;          // -----------------------------------
5046  //  if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->PKT(pkt1) <= upperpkt && this->OBT(obt1) >= this->OBT(obtfirst) && this->OBT(obt1) <= upperobt ){          // loop over calibrations ...
5047   // EMILIANO          // -----------------------------------
5048      if ( this->PKT(pkt2) >= this->PKT(pktfirst) && this->PKT(pkt2 <= upperpkt) && this->OBT(obt2) >= this->OBT(obtfirst) && this->OBT(obt2) <= upperobt ){          UInt_t nn=0;
5049        //    if ( this->PKT(pkt2) > this->PKT(pktfirst) || this->OBT(obt2) > this->OBT(obtfirst) ){          do {
5050        //              row = result->Next();
5051        if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);              if(!row)break;
5052        //              
5053        this->HandleTRK_CALIB(false,true);              UInt_t id       = (UInt_t)atoll(row->GetField(0));
5054        //              UInt_t fromtime = (UInt_t)atoll(row->GetField(1));
5055      };              UInt_t obt1     = (UInt_t)atoll(row->GetField(2));
5056      //              UInt_t pkt1     = (UInt_t)atoll(row->GetField(3));
5057      t2++;              UInt_t obt2     = (UInt_t)atoll(row->GetField(4));
5058      //              UInt_t pkt2     = (UInt_t)atoll(row->GetField(5));
5059    };              UInt_t boot     = (UInt_t)atoll(row->GetField(6));
5060                UInt_t valid    = (UInt_t)atoll(row->GetField(7));
5061                bool MISSING_pkt1 = (row->GetFieldLength(8)==0);
5062                bool MISSING_pkt2 = (row->GetFieldLength(9)==0);
5063                UInt_t totime   = (UInt_t)atoll(row->GetField(10));
5064    
5065                // -------------------------------------
5066                // ...check if the entry is corrupted...
5067                // -------------------------------------
5068                cout <<"*** "<< MISSING_pkt1 << MISSING_pkt2 << valid <<endl;
5069                bool CORRUPTED = (MISSING_pkt1||MISSING_pkt2||!valid);
5070    
5071                if ( IsDebug() ) cout << "("<<nn<<")  ID = "<<id<<" from GL_TRK_CALIB  ==>  corrupted ? "<<CORRUPTED<<endl;
5072    
5073    //          if( !CORRUPTED  )continue; // nothing to do
5074    
5075                /////////////////////////////////////////////////////////  
5076                // if it is corrupted, ...look for ather chewbacca files
5077                // containing the same calibrations ...
5078                /////////////////////////////////////////////////////////
5079    
5080                bool this_MISSING_pkt1 = false;
5081                bool this_MISSING_pkt2 = false;
5082                int  this_t1=0;
5083                int  this_t2=0;;
5084                UInt_t this_valid = 0;
5085    
5086                TString path       = "";
5087                TString name       = "";
5088                TString raw        = "";
5089                UInt_t obt0        = 0;
5090                UInt_t timesync    = 0;
5091                UInt_t boot_number = 0;
5092                bool   FOUND       = false;
5093    
5094                if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
5095    
5096    //          for(int itable=0; itable<2; itable++){
5097                for(int itable=0; itable<1; itable++){
5098    
5099                    // ------------------------------------------------------
5100                    // loop over both ROOT_TABLE and ROOT_TABLE_BAD
5101                    // ------------------------------------------------------
5102    
5103                    TString table = "ROOT_TABLE";
5104                    if(itable==1)table = "ROOT_TABLE_BAD";
5105    
5106                    oss.str("");
5107                    oss << " SELECT ";
5108                    oss << " FOLDER_NAME,FILE_NAME,OBT_TIME_SYNC,LAST_TIME_SYNC_INFO,BOOT_NUMBER,INPUT_NAME ";
5109                    oss << " FROM "<<table;
5110                    oss << " WHERE 1 " << endl;
5111                    oss << " AND FILE_NAME != \""<< thisfilename<<"\"";
5112                    if( !MISSING_pkt1 ){
5113                        oss << " AND ";
5114                        oss << " PKT_NUMBER_INIT < "<<pkt1;
5115                        oss << " AND ";
5116                        oss << " PKT_NUMBER_FINAL > "<<pkt1;
5117                        oss << " AND ";
5118                        oss << " PKT_OBT_INIT < "<<obt1;
5119                        oss << " AND ";
5120                        oss << " PKT_OBT_FINAL > "<<obt1;
5121                    }else{
5122                        if(pkt2>1) pkt1 = pkt2-1;//serve dopo                  
5123                    }
5124                    if( !MISSING_pkt2 ){
5125                        oss << " AND ";
5126                        oss << " PKT_NUMBER_INIT < "<<pkt2;
5127                        oss << " AND ";
5128                        oss << " PKT_NUMBER_FINAL > "<<pkt2;
5129                        oss << " AND ";
5130                        oss << " PKT_OBT_INIT < "<<obt2;
5131                        oss << " AND ";
5132                        oss << " PKT_OBT_FINAL > "<<obt2;
5133                    }else{
5134                        if(pkt1>0) pkt2 = pkt1+1;//serve dopo
5135                    }
5136                    if( boot> 0 ){
5137                        oss << " AND ";
5138                        oss << " BOOT_NUMBER = "<<boot;
5139                    }else{
5140                    }
5141                    oss << " ORDER BY BAD_PKT_CALREAD ASC; ";
5142                
5143                    TSQLResult *result2 = 0;
5144                    TSQLRow    *row2    = 0;
5145    
5146                    if ( IsDebug() ) cout << oss.str().c_str() << endl;        
5147                    result2 = conn->Query(oss.str().c_str());
5148                    if ( !result2 ) throw -4;;
5149                    if ( IsDebug() ) cout <<"Rows: "<<result2->GetRowCount()<<endl;
5150    
5151                    // ------------------------------------------------------
5152                    // loop over files containing repetition (if any)
5153                    // ------------------------------------------------------
5154                    do {
5155                        row2 = result2->Next();
5156                        if(!row2)break;
5157                    
5158                        // ------------------------------------------------------
5159                        // ... a repetition is found ...
5160                        // ------------------------------------------------------
5161                        path       = (TString)row2->GetField(0);
5162                        name       = (TString)row2->GetField(1);
5163                        raw        = (TString)row2->GetField(5);
5164                        obt0        = (UInt_t)atoll(row2->GetField(2));
5165                        timesync    = (UInt_t)atoll(row2->GetField(3));
5166                        boot_number = (UInt_t)atoll(row2->GetField(4));
5167                    
5168                        if ( IsDebug() ) cout << "- - - - - - - - - - -" <<endl;
5169    //                  cout << path <<endl;
5170    //                  cout << "File    : " <<name <<endl;
5171    //                  cout << obt0 <<endl;
5172    //                  cout << timesync <<endl;
5173    //                  cout << "boot n. : "<<boot_number <<endl;
5174    //                  cout << raw <<endl;
5175    
5176                        // ------------------------------------------------------
5177                        // ... retrieve the calibration packets.
5178                        // ------------------------------------------------------
5179                        if ( IsDebug() ) printf(" file is %s/%s \n",((TString)gSystem->ExpandPathName(path.Data())).Data(),name.Data());
5180                        TFile *file = new TFile(((TString)gSystem->ExpandPathName(path.Data()))+"/"+name); // EM, path could be symbolic and we must expand it
5181                        if(!file)throw -100;
5182                        if(file->IsZombie())throw -100;
5183                        //
5184                        tr1 = (TTree*)file->Get("CalibTrk1");
5185                        if ( !tr1 || tr1->IsZombie() ) throw -22;
5186                        tr2 = (TTree*)file->Get("CalibTrk2");
5187                        if ( !tr2 || tr2->IsZombie() ) throw -23;
5188                        //
5189                        tr1->SetBranchAddress("CalibTrk1", &caltrk1);
5190                        tr1->SetBranchAddress("Header", &eh1);
5191                        nevents1 = tr1->GetEntries();
5192                        tr2->SetBranchAddress("CalibTrk2", &caltrk2);
5193                        tr2->SetBranchAddress("Header", &eh2);
5194                        nevents2 = tr2->GetEntries();
5195                        for(this_t1=0; this_t1<nevents1; this_t1++){
5196                            tr1->GetEntry(this_t1);
5197                            if(
5198                                (UInt_t)eh1->GetPscuHeader()->GetCounter() == pkt1 &&
5199                                true) break;
5200                            this_MISSING_pkt1 = true;
5201                        }
5202                        for(this_t2=0; this_t2<nevents2; this_t2++){
5203                            tr2->GetEntry(this_t2);
5204                            if(
5205                                (UInt_t)eh2->GetPscuHeader()->GetCounter() == pkt2 &&
5206                                true) break;
5207                            this_MISSING_pkt2 = true;
5208                        }
5209                        this_valid =
5210                            ValidateTrkCalib( caltrk1, eh1, file )
5211                            *
5212                            ValidateTrkCalib( caltrk2, eh2, file );
5213                                
5214                        // ---------------------------------------------------------------------
5215                        // accept the calibration if it is better than the previous:
5216                        //
5217                        // - if the new calibration is perfect (both valid packets)
5218                        // - if the new calibration has both the packets and the previous does not
5219                        // ---------------------------------------------------------------------
5220                        if(
5221                            ( !this_MISSING_pkt1&&!this_MISSING_pkt2&&this_valid )||
5222                            ( (MISSING_pkt1||MISSING_pkt2) && (!this_MISSING_pkt1&&!this_MISSING_pkt2) )||
5223                            false)FOUND=true;      
5224                
5225                        if(file)file->Close();
5226    
5227                        if(FOUND)break;
5228    
5229                    }while(1);//endl loop over root table entries
5230    
5231                    if(FOUND)break;
5232    
5233                }//end loop over tables
5234    
5235                if(FOUND){
5236    
5237                if ( IsDebug() ) cout << " >>> REPETITION FOUND :-) <<<" <<endl;
5238    
5239                    ////////////////////////////////////////////
5240                    // insert a new entry in GL_TRK_CALIB and
5241                    // modify the time-tag of the previous one
5242                    ////////////////////////////////////////////
5243    
5244                    // ---------------------------------------------------------------------
5245                    // step 1: insert a new raw file in GL_RAW
5246                    // ---------------------------------------------------------------------
5247                    //
5248                    // check if the raw file already exist
5249                    //
5250                    UInt_t id_raw = 0;   // EM GL_RAW is there only for backward compatibility so we do not need to fill it when in "chewbacca" mode
5251    //              oss.str("");
5252    //              oss << "SELECT ID FROM GL_RAW where NAME=\"" << gSystem->BaseName(raw.Data()) <<"\";";
5253    //              if ( IsDebug() ) cout << oss.str().c_str() << endl;
5254                    
5255    //              result = conn->Query(oss.str().c_str());
5256    //              if ( !result ) throw -4;;
5257    //              if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5258    //              if( result->GetRowCount() == 0){
5259    //                  if ( IsDebug() ) cout << " << Insert new RAW file >> "<<endl;
5260    //                  // - - - - - - - - - - -
5261    //                  // insert new raw file
5262    //                  // - - - - - - - - - - -
5263    //                  GL_RAW glraw = GL_RAW();    
5264    //                  glraw.PATH        = gSystem->DirName(raw.Data());
5265    //                  glraw.NAME        = gSystem->BaseName(raw.Data());
5266    //                  glraw.BOOT_NUMBER = boot_number;
5267    //                  //
5268    //                  insertPamelaRawFile( &glraw );
5269    //                  //              
5270    //                  id_raw = glraw.ID;              
5271    //              }else{
5272    //                  row = result->Next();
5273    //                  id_raw = (UInt_t)atoll(row->GetField(0));
5274    //              }
5275    //              if ( IsDebug() ) cout << "ID_RAW = "<<id_raw<<endl;
5276    
5277                    // ---------------------------------------------------------------------
5278                    // step 1(bis): retrieve the timesync id associated to the file
5279                    // (NB, uso lo stesso associato al file iniziale)
5280                    // ---------------------------------------------------------------------
5281                    UInt_t idtimesync = 0;
5282                    oss.str("");
5283                    oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" limit 1;";
5284                    if ( debug ) printf(" %s \n",oss.str().c_str());
5285                    result = conn->Query(oss.str().c_str());
5286                    if ( !result ) throw -3;
5287                    row = result->Next();
5288                    if ( !row ) throw -3;
5289                    idtimesync = (UInt_t)atoll(row->GetField(0));
5290                    if ( IsDebug() ) cout << "ID_TIMESYNC = "<<idtimesync<<endl;
5291                    
5292                    // ---------------------------------------------------------------------
5293                    // step 2: insert a new root file in GL_ROOT
5294                    // ---------------------------------------------------------------------
5295                    //
5296                    // check if the root file already exist
5297                    //
5298                    UInt_t id_root = 0;
5299                    oss.str("");
5300                    oss << "SELECT ID FROM GL_ROOT where NAME=\"" << gSystem->BaseName(name.Data()) <<"\";";
5301                    if ( IsDebug() ) cout << oss.str().c_str() << endl;
5302                    
5303                    result = conn->Query(oss.str().c_str());
5304                    if ( !result ) throw -4;;
5305                    if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5306                    if( result->GetRowCount() == 0){
5307                        if ( IsDebug() ) cout << " << Insert new ROOT file >> "<<endl;
5308                        // - - - - - - - - - - -
5309                        // insert new root file
5310                        // - - - - - - - - - - -
5311                        GL_ROOT glroot = GL_ROOT();            
5312                        glroot.ID_RAW      = id_raw;
5313                        glroot.ID_TIMESYNC = idtimesync;
5314                        //
5315                        // EM STATIC = the full expanded path must be put in the DB, KEEPENV = the path given as input (or found in ROOT_TABLE) must be used,
5316                        //             NOT STATIC NOT KEEPENV = $PAM_L0 must be used in the DB
5317                        //
5318                        if ( STATIC ){
5319                          glroot.PATH        = (TString)gSystem->ExpandPathName(path);
5320                        } else {
5321                          if ( KEEPENV ){
5322                            glroot.PATH      = path;
5323                          } else {
5324                            glroot.PATH      = "$PAM_L0";
5325                          };
5326                        };
5327                        //              glroot.PATH        = path;
5328                        glroot.NAME        = name;
5329                        //
5330                        insertPamelaRootFile( &glroot );
5331                        //              
5332                        id_root = glroot.ID;                    
5333                    }else{
5334                        row = result->Next();
5335                        if(row)id_root = (UInt_t)atoll(row->GetField(0));
5336                    }
5337                    if ( IsDebug() ) cout << "ID_ROOT = "<<id_root<<endl;
5338    
5339                    // ---------------------------------------------------------------------
5340                    // step 3: modify time-tag of corrupted GL_TRK_CALIB entry
5341                    // ---------------------------------------------------------------------
5342                    if ( IsDebug() ) cout << " << Modify time-tag of calibration ID="<<id<<" >> "<<endl;
5343                    oss.str("");
5344                    oss << " UPDATE GL_TRK_CALIB SET "  
5345                        << " TO_TIME=0 , FROM_TIME=0  WHERE "
5346                        << " ID = "<< id  << ";";
5347                    if ( IsDebug() ) cout << oss.str().c_str() << endl;
5348                    result = conn->Query(oss.str().c_str());
5349                    if ( !result ) throw -4;;
5350    
5351                    // ---------------------------------------------------------------------
5352                    // step 4: insert the new calibration:
5353                    // ---------------------------------------------------------------------
5354                    if ( IsDebug() ) cout << " << Insert new TRK calibration >> "<<endl;
5355                    //
5356                    GL_TRK_CALIB glcal = GL_TRK_CALIB();        
5357                    //
5358                    glcal.ID_ROOT_L0        = id_root;
5359                    glcal.EV_ROOT_CALIBTRK1 = this_t1;
5360                    glcal.EV_ROOT_CALIBTRK2 = this_t2;
5361                    glcal.FROM_TIME         = fromtime;
5362                    glcal.TO_TIME           = totime;
5363                    glcal.OBT1              = obt1;
5364                    glcal.OBT2              = obt2;
5365                    glcal.PKT1              = pkt1;
5366                    glcal.PKT2              = pkt1;
5367                    glcal.BOOT_NUMBER       = GetBOOTnumber();
5368                    glcal.VALIDATION        = this_valid;
5369                    //
5370                    HandleTRK_CALIB(&glcal);
5371                    if ( IsDebug() ) cout << "ID = "<<glcal.ID<<endl;
5372                    //
5373                    
5374                }
5375                if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
5376    
5377            }while(1);//end loop over calibrations
5378            
5379            
5380            if( result )delete result;
5381            if( row    )delete row;
5382            
5383            
5384    
5385            
5386    
5387    
5388        }
5389    
5390    
5391    //      // ------------------------------
5392    //      // try to recover the calibration
5393    //      // ------------------------------
5394    //      cout << "TRY TO RECOVER TRACKER CALIBRATION"<<endl;
5395    //      //
5396    //      ULong64_t time  = 0; //absolute time
5397    //      string    path[100]; //mettere un limite massimo
5398    //      int       nrows = 0;
5399    //      UInt_t    pkt   = 0;
5400    //      UInt_t    obt   = 0;
5401    //      char     *type  = "";
5402    //      EventHeader *eh   = new EventHeader();
5403    //      CalibTrk1Event *c = new CalibTrk1Event();
5404            
5405    //       //
5406    //       if(which_is_not_valid==1 || which_is_not_valid==3){
5407    //        //
5408    //        cout << "PKT1 --> missing or corrupted "<<endl;
5409    //        type = "CalibTrk1";
5410    //        pkt  = pkt1;
5411    //        obt  = obt1;
5412    //        time = this->GetAbsTime(obt1);
5413    //        if( pkt1 == 0 ){//missing
5414    //            time = this->GetAbsTime(obt2);
5415    //            pkt  = pkt2-1;          
5416    //        }
5417    //        //
5418    //       }else if (which_is_not_valid==2 || which_is_not_valid==3){
5419    //        //
5420    //        cout << "PKT2--> missing or corrupted "<<endl;
5421    //        type = "CalibTrk2 ";
5422    //        pkt  = pkt2;
5423    //        obt  = obt2;
5424    //        time = this->GetAbsTime(obt2);
5425    //        if( pkt2 == 0 ){//missing
5426    //            time = this->GetAbsTime(obt1);
5427    //            pkt  = pkt1+1;          
5428    //        }
5429    //        //
5430    //       }else{
5431    //        cout << "this should not happen!!! "<<endl;
5432    //        trow -666;
5433    //       }
5434          
5435    //       nrows = Query_ROOT_TABLE(time,conn,path);// get the list of file which might contain the packet
5436          
5437    
5438    //       for(int r=0; r<nrows; r++){ //loop over rows
5439    //        if(path)cout << r << " >>>> "<<(path+r)->c_str() << endl;
5440    //        /// verifica che il file non sia quello gia` aperto
5441    //       }
5442    
5443    //       ////////////////////////////////////////////////////////////////////////
5444    
5445    //       TSQLResult *result = 0;
5446    //       TSQLRow    *row    = 0;
5447    //       //
5448    //       stringstream oss;
5449    //       oss.str("");
5450    //       // ----------------------------------------
5451    //       // read the id of last calibration inserted
5452    //       // ----------------------------------------
5453    //       oss.str("");
5454    //       oss << " SELECT ";
5455    //       oss << " (ID,ID_ROOT_L0,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,FROM_TIME,TO_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION) ";
5456    //       oss << " ORDER BY ID DESC LIMIT 1; ";
5457          
5458    //       result = conn->Query(oss.str().c_str());
5459    //       row = result->Next();
5460    //       if( !row )throw -666;
5461    
5462    //       if( result )delete result;
5463    //       if( row    )delete row;
5464    
5465    //       UInt_t id = (UInt_t)atoll(row->GetField(0));
5466    
5467    //       // -------------------------------------
5468    //       // ...and modify it with new parameters
5469    //       // -------------------------------------
5470          
5471    
5472    //   }
5473    //    //
5474    return(0);    return(0);
5475  };  };
# Line 5061  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 5772  Int_t PamelaDBOperations::CleanGL_RUN_FR
5772                    << " RM_ACQ_SETTING_MODE=" << glrun->GetRM_ACQ_SETTING_MODE()<< " , "                      << " RM_ACQ_SETTING_MODE=" << glrun->GetRM_ACQ_SETTING_MODE()<< " , "  
5773                    << " TRK_CALIB_USED=" << glrun->GetTRK_CALIB_USED()<< " , "                      << " TRK_CALIB_USED=" << glrun->GetTRK_CALIB_USED()<< " , "  
5774                    << " CAL_DSP_MASK=" << glrun->GetCAL_DSP_MASK()<< " , "                      << " CAL_DSP_MASK=" << glrun->GetCAL_DSP_MASK()<< " , "  
5775                    << " LAST_TIMESYNC=" << glrun->GetLAST_TIMESYNC()<< " , "                      << " LAST_TIMESYNC=" << glrun->GetLAST_TIMESYNC()<< " , ";
5776                    << " OBT_TIMESYNC=" << glrun->GetOBT_TIMESYNC()                //
5777                    << " WHERE ID=" << myid[u] << ";";                if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
5778                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12() << " , ";
5779                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
5780                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC() << " , ";
5781                  //              
5782                  oss << " OBT_TIMESYNC=" << glrun->GetOBT_TIMESYNC();
5783                  oss << " WHERE ID=" << myid[u] << ";";
5784                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
5785              };              };
5786              //              //
# Line 5074  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 5791  Int_t PamelaDBOperations::CleanGL_RUN_FR
5791              for (UInt_t u=1; u <= nid ; u++){              for (UInt_t u=1; u <= nid ; u++){
5792                oss.str("");                oss.str("");
5793                oss << "UPDATE GL_RUN_FRAGMENTS SET "                oss << "UPDATE GL_RUN_FRAGMENTS SET "
5794                    << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , "                    << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , ";
5795                    << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "                //
5796                  if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
5797                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , ";
5798                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
5799                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , ";
5800                  //              
5801                  oss << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "
5802                    << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT()<< ";";                    << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT()<< ";";
5803                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
5804              };                  };    
# Line 5098  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 5821  Int_t PamelaDBOperations::CleanGL_RUN_FR
5821                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
5822                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "
5823                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< " , "                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< " , "
5824                    << " PKT_COUNTER=" << glrun->GetPKT_COUNTER()<< " , "                    << " PKT_COUNTER=" << glrun->GetPKT_COUNTER()<< " , ";
5825                    << " PKT_READY_COUNTER=" << glrun->GetPKT_READY_COUNTER()                //
5826                  if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
5827                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
5828                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) {
5829                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
5830                  //              
5831                  oss << " PKT_READY_COUNTER=" << glrun->GetPKT_READY_COUNTER()
5832                    << " WHERE ID=" << myid[u] << ";";                    << " WHERE ID=" << myid[u] << ";";
5833                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
5834              };              };
# Line 5112  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 5841  Int_t PamelaDBOperations::CleanGL_RUN_FR
5841                oss.str("");                oss.str("");
5842                oss << "UPDATE GL_RUN_FRAGMENTS SET "                oss << "UPDATE GL_RUN_FRAGMENTS SET "
5843                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
5844                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , ";
5845                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< ";";                //
5846                  if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
5847                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
5848                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ){
5849                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
5850                  //              
5851                  oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< ";";
5852                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
5853              };                  };    
5854            };            };
# Line 5272  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6007  Int_t PamelaDBOperations::CleanGL_RUN_FR
6007          glrun->SetID_RUN_FRAG(glrun->GetID());          glrun->SetID_RUN_FRAG(glrun->GetID());
6008          glrun->Fill_GL_RUN(conn);            glrun->Fill_GL_RUN(conn);  
6009          //          //
6010  //      oss.str("");          //      oss.str("");
6011  //      oss << " SELECT ID FROM GL_RUN WHERE "          //      oss << " SELECT ID FROM GL_RUN WHERE "
6012  //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "          //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
6013  //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "          //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
6014  //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "          //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
6015  //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "          //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
6016  //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";          //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
6017  //      //          //      //
6018  //      if ( IsDebug() ) printf(" Look for the ID of the inserted run: query is \n %s \n",oss.str().c_str());          //      if ( IsDebug() ) printf(" Look for the ID of the inserted run: query is \n %s \n",oss.str().c_str());
6019  //      result2 = conn->Query(oss.str().c_str());          //      result2 = conn->Query(oss.str().c_str());
6020  //      //          //      //
6021  //      if ( !result2 ) throw -4;          //      if ( !result2 ) throw -4;
6022  //      //          //      //
6023  //      row2 = result2->Next();          //      row2 = result2->Next();
6024  //      //          //      //
6025  //      if ( !row2 ) throw -25;          //      if ( !row2 ) throw -25;
6026  //      //          //      //
6027  //      oss.str("");          //      oss.str("");
6028  //      oss << " UPDATE GL_RUN SET ID_RUN_FRAG = " << row2->GetField(0) << " WHERE ID = " << row2->GetField(0);          //      oss << " UPDATE GL_RUN SET ID_RUN_FRAG = " << row2->GetField(0) << " WHERE ID = " << row2->GetField(0);
6029  //      if ( IsDebug() ) printf(" Update the ID_RUN_FRAG of the inserted run: query is \n %s \n",oss.str().c_str());          //      if ( IsDebug() ) printf(" Update the ID_RUN_FRAG of the inserted run: query is \n %s \n",oss.str().c_str());
6030  //      result2 = conn->Query(oss.str().c_str());          //      result2 = conn->Query(oss.str().c_str());
6031  //      //          //      //
6032  //      if ( !result2 ) throw -4;          //      if ( !result2 ) throw -4;
6033          //          //
6034          moved++;          moved++;
6035          //          //
# Line 5306  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6041  Int_t PamelaDBOperations::CleanGL_RUN_FR
6041        //        //
6042        //        //
6043        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
6044  //      oss.str("");        //      oss.str("");
6045  //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);        //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);
6046  //       if ( IsDebug() ) printf(" Clean the GL_RUN_FRAGMENTS table: query is \n %s \n",oss.str().c_str());        //       if ( IsDebug() ) printf(" Clean the GL_RUN_FRAGMENTS table: query is \n %s \n",oss.str().c_str());
6047  //       result2 = conn->Query(oss.str().c_str());        //       result2 = conn->Query(oss.str().c_str());
6048  //      //        //      //
6049  //      if ( !result2 ) throw -4;        //      if ( !result2 ) throw -4;
6050  //      //        //      //
6051        row = result->Next();        row = result->Next();
6052      };      };
6053    };    };
# Line 5366  Int_t PamelaDBOperations::ValidateRuns(T Line 6101  Int_t PamelaDBOperations::ValidateRuns(T
6101      // 2) get the OBT of the last validated run      // 2) get the OBT of the last validated run
6102      // --------------------------------------------------------------      // --------------------------------------------------------------
6103      oss.str("");      oss.str("");
6104      oss << " SELECT * FROM GL_RUN  WHERE VALIDATION=1 AND RUNHEADER_TIME<="<< t_start      //    oss << " SELECT * FROM GL_RUN  WHERE VALIDATION=1 AND RUNHEADER_TIME<="<< t_start
6105        oss << " SELECT * FROM GL_RUN  WHERE VALIDATION>0 AND RUNHEADER_TIME<="<< t_start
6106          <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";          <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
6107      if ( IsDebug() ) printf(" Get stop validation-time: query is \n %s \n",oss.str().c_str());      if ( IsDebug() ) printf(" Get stop validation-time: query is \n %s \n",oss.str().c_str());
6108      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
# Line 5457  Int_t PamelaDBOperations::ValidateRuns(T Line 6193  Int_t PamelaDBOperations::ValidateRuns(T
6193    GL_RUN* this_run = new GL_RUN();    GL_RUN* this_run = new GL_RUN();
6194    GL_RUN* next_run = new GL_RUN();    GL_RUN* next_run = new GL_RUN();
6195    Int_t   nseq_max = 1000;    Int_t   nseq_max = 1000;
6196  //  UInt_t* sequence = new UInt_t[100];    //  UInt_t* sequence = new UInt_t[100];
6197    vector<UInt_t> sequence(nseq_max);    vector<UInt_t> sequence(nseq_max);
6198    Int_t   nseq = 0;    Int_t   nseq = 0;
6199    Bool_t CHECK = false;    Bool_t CHECK = false;
# Line 5472  Int_t PamelaDBOperations::ValidateRuns(T Line 6208  Int_t PamelaDBOperations::ValidateRuns(T
6208    // ---------------------------------------------------------------------------------    // ---------------------------------------------------------------------------------
6209    while(1){    while(1){
6210                        
6211            row = result->Next();      row = result->Next();
6212            if( row == NULL ) break;      if( row == NULL ) break;
6213                        
6214            //------------      //------------
6215            //get run info      //get run info
6216            //------------      //------------
6217            this_run->Set_GL_RUN(row);      this_run->Set_GL_RUN(row);
6218                                        
6219            Bool_t this_BAD = false;      Bool_t this_BAD = false;
6220            if(this_run->GetTRK_CALIB_USED() == 1 || this_run->GetTRK_CALIB_USED() == 2) this_ONLINE = true;      if(this_run->GetTRK_CALIB_USED() == 1 || this_run->GetTRK_CALIB_USED() == 2) this_ONLINE = true;
6221            else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;      else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;
6222            else{      else{
6223  //                printf("Missing or corrupted header!! \n");        //                  printf("Missing or corrupted header!! \n");
6224                    this_ONLINE = false;        this_ONLINE = false;
6225                    this_BAD = true;        this_BAD = true;
6226            };      };
6227    
6228            //-----------------------------------      //-----------------------------------
6229            //compare with previous(next in time)      //compare with previous(next in time)
6230            //-----------------------------------      //-----------------------------------
6231            CHECK = false;      CHECK = false;
6232            UInt_t interval=0;      UInt_t interval=0;
6233                        
6234            if( nrow != 0){      if( nrow != 0){
6235                    
6236                                        
6237                    t1 = this_run->GetRUNTRAILER_TIME();        t1 = this_run->GetRUNTRAILER_TIME();
6238                    t2 = next_run->GetRUNHEADER_TIME();        t2 = next_run->GetRUNHEADER_TIME();
6239                    interval = (t2-t1);        interval = (t2-t1);
6240                                        
6241                    if(this_ONLINE && next_ONLINE){                               // this: ON-LINE + next: ON-LINE        if(this_ONLINE && next_ONLINE){                           // this: ON-LINE + next: ON-LINE
6242                                                        
6243                            if( this_run->ID == next_run->ID_RUN_FRAG ) interval = 0;     //=> run fragments          if( this_run->ID == next_run->ID_RUN_FRAG ) interval = 0;       //=> run fragments
6244                                                        
6245                            if( interval >= calibtime )CHECK = true;                      //more than calibtime s => there might be a calibration          if( interval >= calibtime )CHECK = true;                        //more than calibtime s => there might be a calibration
6246                                                        
6247                            if( !CHECK && this_run->VALIDATION ){          if( !CHECK && this_run->VALIDATION ){
6248                                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);            //      for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
6249                                    nseq=0;            for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],this_run->VALIDATION);
6250                            }            nseq=0;
6251            }
6252                                        
6253                    }else if( !this_ONLINE && next_ONLINE) {              // this: DEFAULT + next:ON-LINE        }else if( !this_ONLINE && next_ONLINE) {          // this: DEFAULT + next:ON-LINE
6254                                                        
6255                            CHECK = true;          CHECK = true;
6256    
6257                    }else if( !next_ONLINE ){                                             // this:ANY + next:DEFAULT        }else if( !next_ONLINE ){                                         // this:ANY + next:DEFAULT
6258                                                        
6259                            assignVALIDATION(next_run->ID,true);          assignVALIDATION(next_run->ID,true);
6260                            nseq=0;          nseq=0;
6261                    }        }
6262            }      }
6263    
6264            //----------------------------      //----------------------------
6265            //check run sequence for calib      //check run sequence for calib
6266            //----------------------------      //----------------------------
6267            if( CHECK ){      if( CHECK ){
6268                    // check if calibration exists        // check if calibration exists
6269                    if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);        if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);
6270                    Bool_t MISSING = MissingTRK_CALIB(t1,t2);        //      Bool_t MISSING = MissingTRK_CALIB(t1,t2);
6271                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],!MISSING);        UInt_t MISSING = MissingTRK_CALIB(t1,t2);
6272                    nseq=0;        UInt_t val = 0;
6273            };        if ( MISSING == 1 ) val = 0;
6274            //--------------        if ( MISSING == 0 ) val = 1;
6275            //store run info        if ( MISSING == 2 ) val = 2;
6276            //--------------        for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],val);
6277            *next_run   = *this_run;        nseq=0;
6278            next_ONLINE = this_ONLINE;      };
6279            if( !this_BAD ){      //--------------
6280                    if(nseq < nseq_max){      //store run info
6281                            sequence[nseq] = this_run->ID;      //--------------
6282                            nseq++;      *next_run   = *this_run;
6283                    }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);      next_ONLINE = this_ONLINE;
6284            };      if( !this_BAD ){
6285          if(nseq < nseq_max){
6286            sequence[nseq] = this_run->ID;
6287            nseq++;
6288          }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);
6289        };
6290                        
6291            if ( IsDebug() ) printf("%i Run %u \n",nrow,this_run->ID);      if ( IsDebug() ) printf("%i Run %u \n",nrow,this_run->ID);
6292            nrow++;      nrow++;
6293                        
6294    };    };
6295    delete this_run;    delete this_run;
# Line 5561  Int_t PamelaDBOperations::ValidateRuns(T Line 6303  Int_t PamelaDBOperations::ValidateRuns(T
6303   * @param t2 To absolute time   * @param t2 To absolute time
6304   * @return true if there might be a missing calibration   * @return true if there might be a missing calibration
6305   */   */
6306  Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){  //Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
6307    UInt_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
6308                    
6309          GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();    GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();
6310                    
6311          // get the closest VALIDATED calibration before the run start (t2)    // get the closest calibration before the run start (t2)
6312          if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true);      //>>> missing    //  if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true);        //>>> missing
6313      if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(1);       //>>> missing
6314                    
6315          if ( trkcalib->TO_TIME  < t2 ) return(true);                                    //>>> missing    //  if ( trkcalib->TO_TIME  < t2 ) return(true);                                      //>>> missing
6316      if ( trkcalib->TO_TIME  < t2 ) return(1);                                     //>>> missing
6317                    
6318          //==============================================================    //==============================================================
6319          // Check is done first on the basis of time between calibration,    // Check is done first on the basis of time between calibration,
6320          // which should be equal to the time between ascending-nodes.    // which should be equal to the time between ascending-nodes.
6321          //==============================================================    //==============================================================
6322          if ( t2 - trkcalib->FROM_TIME > 5700) {    if ( t2 - trkcalib->FROM_TIME > 5700) {
6323                  if ( IsDebug() )printf("Long time between calib and run start %u :-( ==> there might be a missing calib \n",t2 - trkcalib->FROM_TIME);      if ( IsDebug() )printf("Long time between calib and run start %u :-( ==> there might be a missing calib \n",t2 - trkcalib->FROM_TIME);
6324          //==============================================================      //==============================================================
6325          // there might be a missing calibration, due to:      // there might be a missing calibration, due to:
6326          // - MM full      // - MM full
6327          // - corrupted packets      // - corrupted packets
6328          // - loss of data      // - loss of data
6329          // There is an exception in case a download was done during ascending node      // There is an exception in case a download was done during ascending node
6330          //==============================================================      //==============================================================
6331                  Bool_t DOWNLOAD = false;      Bool_t DOWNLOAD = false;
6332                  // check if the calib was skipped becouse of download .... DA FARE!!      // check if the calib was skipped becouse of download .... DA FARE!!
6333                  if(DOWNLOAD)return(false);      //    if(DOWNLOAD)return(false);
6334        if(DOWNLOAD)return(0);
6335                                    
6336                  return(true);                                   //>>> missing      //    return(true);                                         //>>> missing
6337        return(1);                                  //>>> missing
6338                                    
6339          };    };
6340                    
6341          //==============================================================    //==============================================================
6342          // If the last calibration is close to the run less than this time,    // If the last calibration is close to the run less than this time,
6343          // it is enough to say that there are no missing calibrations    // it is enough to say that there are no missing calibrations
6344          //==============================================================    //==============================================================
6345          // the long time interval bewteen runs might be due to download    // the long time interval bewteen runs might be due to download
6346          if ( IsDebug() )printf("Short time between calib and run start %u :-) ==> OK! \n",t2 - trkcalib->FROM_TIME);    if ( IsDebug() )printf("Short time between calib and run start %u :-) ==> OK! \n",t2 - trkcalib->FROM_TIME);
6347          return(false);    if ( trkcalib->VALIDATION ) return(0);
6348      if ( IsDebug() )printf("Calibration is not validated... :-/ ==> OK but with VALIDATION=2! \n");
6349      return(2);
6350                    
6351  };  };
6352  /**  /**
# Line 5606  Bool_t PamelaDBOperations::MissingTRK_CA Line 6355  Bool_t PamelaDBOperations::MissingTRK_CA
6355   * @param validation true/false   * @param validation true/false
6356   */   */
6357  Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){  Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){
6358          TSQLResult *result = 0;    return(this->assignVALIDATION(idrun,(UInt_t)validation));
6359          stringstream oss;  }
6360          oss.str("");  
6361          oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";  Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, UInt_t validation){
6362          //    TSQLResult *result = 0;
6363  //      if ( IsDebug() )    stringstream oss;
6364  //      printf(" Set VALIDATION = %i for run %i \n",validation,idrun);    oss.str("");
6365          if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());    oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";
6366          result = conn->Query(oss.str().c_str());    //
6367          if ( !result ) throw -4;    //    if ( IsDebug() )
6368          return(0);    //    printf(" Set VALIDATION = %i for run %i \n",validation,idrun);
6369      if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());
6370      result = conn->Query(oss.str().c_str());
6371      if ( !result ) throw -4;
6372      return(0);
6373  }  }
6374    
6375    
# Line 5802  Int_t PamelaDBOperations::removeFile(TSt Line 6555  Int_t PamelaDBOperations::removeFile(TSt
6555    stringstream myquery;    stringstream myquery;
6556    //      //  
6557    myquery.str("");    myquery.str("");
6558    myquery << " SELECT ID, ID_RAW FROM GL_ROOT where NAME='"<<remfile.Data() <<"';";    myquery << " SELECT ID,ID_RAW,ID_TIMESYNC FROM GL_ROOT where NAME='"<<remfile.Data() <<"';";
6559    //    //
6560    pResult = conn->Query(myquery.str().c_str());    pResult = conn->Query(myquery.str().c_str());
6561    //    //
# Line 5818  Int_t PamelaDBOperations::removeFile(TSt Line 6571  Int_t PamelaDBOperations::removeFile(TSt
6571    //    //
6572    this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));    this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));
6573    this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));    this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));
6574      UInt_t idtsy=(UInt_t)atoll(Row->GetField(2));
6575    //    //
6576    this->ValidationOFF();    this->ValidationOFF();
6577    //    //
# Line 5825  Int_t PamelaDBOperations::removeFile(TSt Line 6579  Int_t PamelaDBOperations::removeFile(TSt
6579    //    //
6580    this->RemoveRUNS();    this->RemoveRUNS();
6581    //    //
6582    this->RemoveFILES();    this->RemoveFILES(idtsy);
6583    //    //
6584    this->SetID_ROOT(0);    this->SetID_ROOT(0);
6585    this->SetID_RAW(0);    this->SetID_RAW(0);
# Line 6045  void PamelaDBOperations::RemoveRUNS(){ Line 6799  void PamelaDBOperations::RemoveRUNS(){
6799   * Rearrange calibration tables   * Rearrange calibration tables
6800   *   *
6801   **/   **/
6802  void PamelaDBOperations::RemoveFILES(){  void PamelaDBOperations::RemoveFILES(UInt_t idtsy){
6803    stringstream myquery;    stringstream myquery;
6804    //    //
6805    myquery.str("");    myquery.str("");
# Line 6055  void PamelaDBOperations::RemoveFILES(){ Line 6809  void PamelaDBOperations::RemoveFILES(){
6809    //    //
6810    conn->Query(myquery.str().c_str());    conn->Query(myquery.str().c_str());
6811    //    //
6812      myquery.str("");
6813      myquery << " DELETE FROM GL_ROOT WHERE ID=" <<this->GetID_ROOT() <<";";
6814      //
6815      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
6816      //
6817      conn->Query(myquery.str().c_str());  //
6818      //
6819      if ( !chewbacca ){
6820        myquery.str("");
6821        myquery << " DELETE FROM GL_TIMESYNC WHERE ID=" << idtsy <<";";
6822        //
6823        if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
6824        //
6825        conn->Query(myquery.str().c_str());
6826      };
6827      //
6828  };  };
6829    
6830  /**  /**
# Line 6259  void PamelaDBOperations::RemoveCALIBS(){ Line 7029  void PamelaDBOperations::RemoveCALIBS(){
7029   * Rearrange calibration tables   * Rearrange calibration tables
7030   *   *
7031   **/   **/
7032  UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh ){  UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh , TFile *file){
7033    
7034        if(!caltrk) return 0;
7035    
7036        if ( IsDebug() ) cout << "ValidateTrkCalib:"<<endl;
7037    
7038        UInt_t validate = 1;
7039      Int_t vorder[]={5,5,3,3,4,4,2,2,1,1,0,0};      Int_t vorder[]={5,5,3,3,4,4,2,2,1,1,0,0};
7040      UInt_t timeaftercalib=120000; //2000;      UInt_t timeaftercalib=120000; //2000;
7041  //  ----------      TString classname = caltrk->GetName();
7042  //  Check CRCs  
7043  //  ----------  //  ----------------------------------
7044    //  Check CRCs and failed calibrations
7045    //  ----------------------------------
7046      for(Int_t ipkt=0; ipkt<6; ipkt++){      for(Int_t ipkt=0; ipkt<6; ipkt++){
7047          if( caltrk->crc_hcal[ipkt] )return 0; // :-(          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
7048          for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] )return 0; // :-(              if( caltrk->crc_hcal[ipkt] ){
7049    //              if(IsDebug())cout<<"(CRC Header)";
7050                    validate = 0;
7051                    if(IsDebug())cout <<endl<<" *** CRC *** (header DSPn "<<caltrk->DSPnumber[ipkt]<<")";
7052            
7053                }
7054                for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] ){
7055    //              if(IsDebug())cout<<"(CRC Pkt-"<<ilad<<")";
7056                    if(IsDebug())cout <<endl<<" *** CRC *** (data DSPn "<<caltrk->DSPnumber[ipkt]<<" ladder "<<ilad<<")";
7057                    validate = 0;
7058                }
7059                if( !(caltrk->ncalib_event[ipkt]==0 && caltrk->cal_flag[ipkt]==0) ){
7060                    if(IsDebug())cout <<endl<<" *** FAILURE ***     (data DSPn "<<caltrk->DSPnumber[ipkt]<<")";
7061                    validate = 0;
7062                }
7063            }else{
7064    //          validate=0;
7065                if(IsDebug())cout <<endl<<" *** DSPn *** ("<< caltrk->DSPnumber[ipkt] <<" @pkt "<<ipkt<<")";
7066            }
7067      }      }
7068    
7069  //  -----------------------  //  -----------------------
7070  //  Check missing packets:  //  Check missing packets:
7071  //  -----------------------  //  -----------------------
# Line 6295  UInt_t PamelaDBOperations::ValidateTrkCa Line 7091  UInt_t PamelaDBOperations::ValidateTrkCa
7091  //  Check if it is first or second calibration packet  //  Check if it is first or second calibration packet
7092  //  -------------------------------------------------  //  -------------------------------------------------
7093      UInt_t build=0;      UInt_t build=0;
     TString classname = caltrk->GetName();  
7094      UInt_t base=0;      UInt_t base=0;
7095      UInt_t mask=0;      UInt_t mask=0;
7096      if(classname.Contains("CalibTrk1Event")){      if(classname.Contains("CalibTrk1Event")){
# Line 6306  UInt_t PamelaDBOperations::ValidateTrkCa Line 7101  UInt_t PamelaDBOperations::ValidateTrkCa
7101          base=18;          base=18;
7102          mask=0xFC0000;          mask=0xFC0000;
7103      }      }
7104  //  -------------------------------------------------  //  ----------------------------------------------------
7105  //  Count number of packets and set build variable  //  Count number of valid packets and set build variable
7106  //  -------------------------------------------------  //  ----------------------------------------------------
7107        if(IsDebug())cout <<endl<< " DSP: ";
7108      Int_t  npkts=0;      Int_t  npkts=0;
7109      for(Int_t ipkt=0; ipkt<6; ipkt++){      for(Int_t ipkt=0; ipkt<6; ipkt++){
7110          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
7111                if(IsDebug())cout <<" "<<caltrk->DSPnumber[ipkt];
7112              npkts++;              npkts++;
7113              build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );              build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );
7114          }  //          cout << caltrk->DSPnumber[ipkt]
7115            };
7116      }      }
7117  //    if( npkts==6 )return 1; // :-)      if(IsDebug())cout << " ==> "<< hex << build << dec;
7118    //  ----------------------------------------------------
7119  //    cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime()<<endl;  //  If the number of valid packets is 6, ok exit...
7120    //  ----------------------------------------------------
7121  //  -----------------------------------------------      if( npkts==6 ){
7122  //  If missing packets: check the acq configuration          return validate; // exit
7123        }
7124    ////////////////////////////////////////////////////////
7125    //  ...otherwise there might be some missing packets
7126    //
7127    //  In this case check the acq configuration
7128  //  (some DSPs might be excluded from acquisition)  //  (some DSPs might be excluded from acquisition)
7129  //  -----------------------------------------------  ////////////////////////////////////////////////////////
7130    
7131        if(!eh || !file || (file&&file->IsZombie()) ){
7132            if ( IsDebug() )cout << " *** MISSING VIEW *** eh="<<eh<<" file="<<file<<" cannot validate"<<endl;
7133            return (0);
7134        }
7135        
7136  //  -----------------------------------------------  //  -----------------------------------------------
7137  //  retrieve the first run header after calib  //  retrieve the first run header after calib
7138  //  -----------------------------------------------  //  -----------------------------------------------
7139       PacketType *pctp;      
7140       EventCounter *cod;      PacketType *pctp;
7141       cod = eh->GetCounter();      EventCounter *cod;
7142       Int_t irun = cod->Get(pctp->RunHeader);      cod = eh->GetCounter();
7143       TTree *rh=(TTree*)file->Get("RunHeader");      Int_t irun = cod->Get(pctp->RunHeader);
7144       if ( !rh || rh->IsZombie() ) throw -17;      TTree *rh=(TTree*)file->Get("RunHeader");
7145       if( rh->GetEntries() == irun ){      if ( !rh || rh->IsZombie() ) throw -17;
7146            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (1)  -- cannot validate :-( "<<endl;      if( rh->GetEntries() <= irun ){
7147           return 0; // :-(          if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (1) -- cannot validate :-( "<<endl;
7148       }          return 0; // :-(
7149        }
7150       RunHeaderEvent *run  = 0;      RunHeaderEvent *run  = 0;
7151       EventHeader    *hrun = 0;      EventHeader    *hrun = 0;
7152       rh->SetBranchAddress("RunHeader", &run);      rh->SetBranchAddress("RunHeader", &run);
7153       rh->SetBranchAddress("Header", &hrun);      rh->SetBranchAddress("Header", &hrun);
7154       rh->GetEntry(irun);      rh->GetEntry(irun);    
7155  //     cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime() << " Run " << hrun->GetPscuHeader()->GetOrbitalTime() <<endl;      if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){
7156            if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (2) -- cannot validate :-( "<<endl;
7157       if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){          return 0; // :-(
7158            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (2) -- cannot validate :-( "<<endl;      }
7159           return 0; // :-(  
7160       }      UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());
7161            if( dtime > timeaftercalib ){
7162       if( !run->RM_ACQ_AFTER_CALIB ){          if ( IsDebug() ) cout << " *** MISSING-PKT *** run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;
7163            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) RM_ACQ_AFTER_CALIB=0    -- cannot validate :-( "<<endl;          return 0; // :-(
7164           return 0; // :-(      }
7165       }  
7166        if ( IsDebug() ) cout <<endl<< " ACQ_BUILD_INFO ==> "<<hex<<(run->ACQ_BUILD_INFO & mask)<<dec;
7167       UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());  
7168       if( dtime > timeaftercalib ){      if( (run->ACQ_BUILD_INFO & mask) != build ){
7169           if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;          validate=0; // :-(
7170           return 0; // :-(          cout <<endl<< " *** MISSING-PKT *** packet mismatch: ACQ_BUILD_INFO="<<hex<<(run->ACQ_BUILD_INFO&mask)<<" != "<<build<<dec;
7171       }      };
7172        
7173        return validate;
7174    
      if( (run->ACQ_BUILD_INFO & mask) != build ){  
          if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) ACQ_BUILD_INFO= >>> "<<hex << (run->ACQ_BUILD_INFO&mask) << " != "<< build << dec<<endl;  
          return 0; // :-(  
      }  
      return 1; // :-)  
7175    
7176  }  }
7177    
# Line 6378  UInt_t PamelaDBOperations::ValidateTrkCa Line 7181  UInt_t PamelaDBOperations::ValidateTrkCa
7181   *   *
7182   **/   **/
7183  UInt_t PamelaDBOperations::Check(){  UInt_t PamelaDBOperations::Check(){
7184          return(this->Check(0,0));    return(this->Check(0,0));
7185  }  }
7186    
7187  UInt_t PamelaDBOperations::Check(UInt_t from, UInt_t to){  UInt_t PamelaDBOperations::Check(UInt_t from, UInt_t to){
7188    //    //
7189          if ( IsDebug() ) printf(" from %u to %u \n",from,to);    if ( IsDebug() ) printf(" from %u to %u \n",from,to);
7190    //    //
7191    UInt_t test = 0;    UInt_t test = 0;
7192    //    //
# Line 6424  UInt_t PamelaDBOperations::Check(UInt_t Line 7227  UInt_t PamelaDBOperations::Check(UInt_t
7227      //      //
7228      if ( from > 0 && nid <= from ) goto ss;      if ( from > 0 && nid <= from ) goto ss;
7229      if ( to > 0 && nid >= to ) goto ss;      if ( to > 0 && nid >= to ) goto ss;
7230  //      //
7231      if ( (UInt_t)atoll(row->GetField(4)) > 1 ){      if ( (UInt_t)atoll(row->GetField(4)) > 1 ){
7232        //        //
7233        //        //
# Line 6455  UInt_t PamelaDBOperations::Check(UInt_t Line 7258  UInt_t PamelaDBOperations::Check(UInt_t
7258              printf(" CHECK n.4 RUNs %u and %u HAVE SAME RUNHEADER \n",thisid,(UInt_t)atoll(row3->GetField(0)));                printf(" CHECK n.4 RUNs %u and %u HAVE SAME RUNHEADER \n",thisid,(UInt_t)atoll(row3->GetField(0)));  
7259              row3 = result3->Next();              row3 = result3->Next();
7260            };            };
7261  //      delete result3;            //    delete result3;
7262    
7263          };          };
7264          //          //
# Line 6476  UInt_t PamelaDBOperations::Check(UInt_t Line 7279  UInt_t PamelaDBOperations::Check(UInt_t
7279              printf(" CHECK n.5 RUNs %u and %u HAVE SAME RUNTRAILER \n",thisid,(UInt_t)atoll(row3->GetField(0)));              printf(" CHECK n.5 RUNs %u and %u HAVE SAME RUNTRAILER \n",thisid,(UInt_t)atoll(row3->GetField(0)));
7280              row3 = result3->Next();              row3 = result3->Next();
7281            };            };
7282  //      delete result3;            //    delete result3;
7283          };          };
7284          //          //
7285          oss.str("");          oss.str("");
# Line 6496  UInt_t PamelaDBOperations::Check(UInt_t Line 7299  UInt_t PamelaDBOperations::Check(UInt_t
7299              printf(" CHECK n.7 RUNs %u and %u HAVE SAME RUNTRAILER AND RUNHEADER (ARE THE SAME?) \n",thisid,(UInt_t)atoll(row3->GetField(0)));              printf(" CHECK n.7 RUNs %u and %u HAVE SAME RUNTRAILER AND RUNHEADER (ARE THE SAME?) \n",thisid,(UInt_t)atoll(row3->GetField(0)));
7300              row3 = result3->Next();              row3 = result3->Next();
7301            };            };
7302   //     delete result3;            //    delete result3;
7303    
7304          };          };
7305        };        };
# Line 6517  UInt_t PamelaDBOperations::Check(UInt_t Line 7320  UInt_t PamelaDBOperations::Check(UInt_t
7320            printf(" CHECK n.6 RUN %u CONTAINS RUN %u  \n",thisid,(UInt_t)atoll(row3->GetField(0)));            printf(" CHECK n.6 RUN %u CONTAINS RUN %u  \n",thisid,(UInt_t)atoll(row3->GetField(0)));
7321            row3 = result3->Next();            row3 = result3->Next();
7322          };          };
7323  //      delete result3;          //      delete result3;
7324        };        };
7325        //        //
7326      };      };
# Line 6543  UInt_t PamelaDBOperations::Check(UInt_t Line 7346  UInt_t PamelaDBOperations::Check(UInt_t
7346        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
7347        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7348        test = 1;        test = 1;
7349  //      delete result2;        //        delete result2;
7350      };      };
7351      //      //
7352      if ( (thisrtt < prevrht) && (thisrht != prevrht) ){      if ( (thisrtt < prevrht) && (thisrht != prevrht) ){
# Line 6565  UInt_t PamelaDBOperations::Check(UInt_t Line 7368  UInt_t PamelaDBOperations::Check(UInt_t
7368        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
7369        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7370        test = 1;        test = 1;
7371  //      delete result2;        //        delete result2;
7372      };      };
7373      //      //
7374      if ( (thisrht > thisrtt) && (thisrht != prevrht) ){      if ( (thisrht > thisrtt) && (thisrht != prevrht) ){
# Line 6587  UInt_t PamelaDBOperations::Check(UInt_t Line 7390  UInt_t PamelaDBOperations::Check(UInt_t
7390        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
7391        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7392        test = 1;        test = 1;
7393  //      delete result2;        //        delete result2;
7394      };      };
7395  ss:    ss:
7396      //      //
7397      prevrht = thisrht;      prevrht = thisrht;
7398      prevrtt = thisrtt;      prevrtt = thisrtt;
7399      previd = thisid;      previd = thisid;
7400      prevl0id = thisl0id;      prevl0id = thisl0id;
7401      row = result->Next();      row = result->Next();
7402  //    if ( result2 ) delete result2;      //    if ( result2 ) delete result2;
7403  //    if ( result3 ) delete result3;      //    if ( result3 ) delete result3;
7404    };    };
7405    //    //
7406    return(test);    return(test);

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

  ViewVC Help
Powered by ViewVC 1.1.23