/[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.14 by mocchiut, Wed Dec 3 19:57:52 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 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 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 2258  Int_t PamelaDBOperations::insertPamelaRU Line 2420  Int_t PamelaDBOperations::insertPamelaRU
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);                //              rt->GetEntry(ptt-1);
2424                  rt->GetEntry(rtev-1);
2425                cod = eht->GetCounter();                cod = eht->GetCounter();
2426                tcod = (UInt_t)cod->Get(pctp->Physics);                tcod = (UInt_t)cod->Get(pctp->Physics)+1;
2427                evbefh = TMath::Max(chminentry,tcod);                evbefh = TMath::Max(chminentry,tcod);
2428                //            evbefh = cod->Get(pctp->Physics);                //            evbefh = cod->Get(pctp->Physics);
2429                rt->GetEntry(ptt);                rt->GetEntry(ptt);
# Line 2367  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2530  Bool_t PamelaDBOperations::IsRunAlreadyI
2530        //        //
2531        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");
2532        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2533  //       oss.str("");        //       oss.str("");
2534  //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2535  //       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());      
2536  //       conn->Query(oss.str().c_str());        //       conn->Query(oss.str().c_str());
2537        if ( signal ) signal = false;        if ( signal ) signal = false;
2538        goto gonext;              goto gonext;      
2539        //        //
# Line 2385  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2548  Bool_t PamelaDBOperations::IsRunAlreadyI
2548        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");
2549        //        //
2550        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2551  //       oss.str("");        //       oss.str("");
2552  //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2553  //       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());      
2554  //       conn->Query(oss.str().c_str());        //       conn->Query(oss.str().c_str());
2555        //        //
2556        if ( signal ) signal = false;        if ( signal ) signal = false;
2557        goto gonext;        goto gonext;
# Line 2403  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2566  Bool_t PamelaDBOperations::IsRunAlreadyI
2566        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");
2567        //        //
2568        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2569  //       oss.str("");        //       oss.str("");
2570  //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2571  //       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());      
2572  //       conn->Query(oss.str().c_str());        //       conn->Query(oss.str().c_str());
2573        if ( signal ) signal = false;        if ( signal ) signal = false;
2574        //        //
2575      };      };
# Line 2488  void PamelaDBOperations::HandleRunFragme Line 2651  void PamelaDBOperations::HandleRunFragme
2651      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");
2652      //      //
2653    } 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 ){  
2654      //      //
2655      // 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
2656      //      //
2657      if ( IsDebug() ) printf(" The run is new \n");      if ( rhfirstev != firstev && !mishead ) mishead = true;
2658      if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");      if ( rtlastev != lastev && !mistrail ) mistrail = true;
2659      //      //
2660      glrun->SetID(this->AssignRunID());      this->FillClass(mishead,mistrail,firstev,lastev);
     glrun->SetID_RUN_FRAG(0);  
     glrun->Fill_GL_RUN_FRAGMENTS(conn);  
2661      //      //
2662    } else {      if ( IsDebug() ) printf("The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
2663      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());
2664      if ( PEDANTIC ) throw -69;      //
2665      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  
2666      //      //
2667      oss.str("");      oss.str("");
2668      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 "
2669          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
2670          << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "          << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
2671          << " ID != " << glrun->ID          << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
2672          << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!          << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
2673            << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2674            << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
2675            << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
2676            << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2677            << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
2678            << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
2679            << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2680            << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
2681            << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
2682      //      //
2683      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());
2684      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
2685      //      //
2686      if ( !result ) throw -4;      if ( !result ) throw -4;
2687      //      //
2688      row = result->Next();      row = result->Next();
2689      //      //
2690      if ( !row && NoFrag() ){      if ( !row ){
2691          //
2692          // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
2693          //
2694          if ( IsDebug() ) printf(" The run is new \n");
2695          if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
2696          //
2697          glrun->SetID(this->AssignRunID());
2698          glrun->SetID_RUN_FRAG(0);
2699          glrun->Fill_GL_RUN_FRAGMENTS(conn);
2700          //
2701        } else {
2702          if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
2703          if ( PEDANTIC ) throw -69;
2704          return;
2705        };
2706        //
2707        if ( chewbacca && mishead && mistrail ) goto justcheck;
2708        //
2709        // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
2710        //    
2711        if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
2712          // missing it no way we can found a piece in the frag table
2713        //        //
2714        oss.str("");        oss.str("");
2715        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 "
2716            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2717            << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "            << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2718            << " ID != " << glrun->ID            << " ID != " << glrun->ID
2719            << " 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!!
2720        //        //
2721        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());
2722        result = conn->Query(oss.str().c_str());        result = conn->Query(oss.str().c_str());
2723        //        //
2724        if ( !result ) throw -4;        if ( !result ) throw -4;
2725        //        //
       foundinrun = true;  
       //  
2726        row = result->Next();        row = result->Next();
2727        //        //
2728      };        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)));  
2729          //          //
2730          chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;            oss.str("");
2731            oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
2732                << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2733                << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2734                << " ID != " << glrun->ID
2735                << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
2736          //          //
2737          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());
2738            //          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 ){  
2739          //          //
2740          // 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;
2741          //          //
2742          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);  
2743          //          //
2744          if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){          row = result->Next();
2745            //    if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){          //
2746          };
2747          //
2748          if ( !row ){
2749            if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2750            found = false;
2751          } else {
2752            //
2753            found = false; // default value
2754            //
2755            if ( IsDebug() ) printf(" Found a possible candidate, checking if it is the good one... \n");
2756            //
2757            // if we have both runheader and runtrailer we can check with pkt_counter:
2758            //
2759            if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){
2760              ULong64_t chkpkt = 0;  
2761              ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
2762              ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
2763            //            //
2764            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;  
2765            //            //
2766            found = true;            if ( labs(chkpkt-pktt)<2 ){
2767                //
2768                if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
2769                //
2770                found = true;
2771                //
2772              } else {
2773                //
2774                if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);            
2775                //
2776                found = false;
2777                //
2778              };
2779            };
2780            if ( !found && chewbacca ) goto justcheck;
2781            if ( !found ){
2782            //            //
2783          } 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
2784            //            //
2785            if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);            ULong64_t chkpkt1 = 0;
2786              ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
2787              ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
2788              chkpkt1 = labs(orunh1-dbrunt1);
2789            //            //
2790            found = false;            ULong64_t chkpkt2 = 0;
2791              ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());
2792              ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
2793              chkpkt2 = labs(orunh2-dbrunt2);
2794              //
2795              ULong64_t chkpkt3 = 0;
2796              ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());
2797              ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
2798              chkpkt3 = labs(orunh3-dbrunt3);
2799            //            //
2800              if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
2801                //  if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){
2802                //
2803                if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
2804                //
2805                found = true;
2806                //
2807              } else {
2808                //
2809                if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
2810                //
2811                found = false;
2812                //
2813              };
2814          };          };
2815        };        };
     };  
     //  
     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)<<";";  
2816        //        //
2817        glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos        if ( found ){
2818        //          //
2819        // 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
2820        //          //
2821        UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());          if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
2822        ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());          //
2823        UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());          if ( foundinrun ){
2824        ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());            glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2825        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");
2826        TTree *T= 0;          };
2827        T = (TTree*)file->Get("Physics");          //
2828        if ( !T || T->IsZombie() ) throw -16;          GL_RUN *glrun1 = new GL_RUN();
2829        EventHeader *eh = 0;          //
2830        PscuHeader *ph = 0;          //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
2831        T->SetBranchAddress("Header", &eh);          //
2832        while ( apkt > bpkt && aobt > bobt && firstev < lastev ){          oss.str("");
2833          T->GetEntry(firstev);          oss << " ID="<<row->GetField(0)<<";";
2834          ph = eh->GetPscuHeader();          //
2835          bpkt = PKT(ph->GetCounter());          glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos
         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() ){  
2836          //          //
2837          //      glrun->SetID(this->AssignRunID());          // merge infos
         glrun->SetID_RUN_FRAG(glrun1->GetID());  
         glrun->Fill_GL_RUN(conn);  
2838          //          //
2839          // set id number          UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());
2840            ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
2841            UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
2842            ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
2843            if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2844            TTree *T= 0;
2845            T = (TTree*)file->Get("Physics");
2846            if ( !T || T->IsZombie() ) throw -16;
2847            EventHeader *eh = 0;
2848            PscuHeader *ph = 0;
2849            T->SetBranchAddress("Header", &eh);
2850            while ( apkt > bpkt && aobt > bobt && firstev < lastev ){
2851              T->GetEntry(firstev);
2852              ph = eh->GetPscuHeader();
2853              bpkt = PKT(ph->GetCounter());
2854              bobt = OBT(ph->GetOrbitalTime());    
2855              firstev++;
2856              if ( PEDANTIC ) throw -71;
2857            };
2858            if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2859            //
2860            glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
2861            glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
2862            glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
2863            glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());
2864            glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());
2865            //
2866            glrun->SetEV_FROM(firstev);
2867            glrun->SetNEVENTS(lastev-firstev+1);
2868            //
2869            glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
2870            glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
2871            glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
2872            glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());
2873            glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());
2874            glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());
2875            glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());
2876            glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());
2877            glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());
2878            glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());
2879            glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());  
2880            glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());  
2881            glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());  
2882            glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());  
2883            glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());  
2884            glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());  
2885            //
2886            if ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
2887            if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
2888            //
2889            if ( !IsRunAlreadyInserted() ){
2890              //
2891              //    glrun->SetID(this->AssignRunID());
2892              glrun->SetID_RUN_FRAG(glrun1->GetID());
2893              glrun->Fill_GL_RUN(conn);
2894              //
2895              // set id number
2896              //
2897              glrun1->SetID_RUN_FRAG(glrun->GetID());
2898              glrun1->Fill_GL_RUN(conn);
2899              //
2900            };
2901            // delete old entry in fragment table
2902            //
2903            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2904            glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2905          //          //
2906          glrun1->SetID_RUN_FRAG(glrun->GetID());          delete glrun1;
2907          glrun1->Fill_GL_RUN(conn);          //
2908            //
2909            return;
2910          //          //
2911        };        };
       // delete old entry in fragment table  
       //  
       glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       //  
       delete glrun1;  
       //  
       //  
       return;  
2912        //        //
2913      };      };
2914      //      //
2915    };      if ( mistrail && ( rtlastev == lastev || chewbacca )) { // look for runtrailer (only when at the end of the file, if at the beginning and the runh is
2916    //        // 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() ){  
2917        //        //
2918        oss.str("");        oss.str("");
2919        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 "
2920            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2921            << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "            << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2922            << " ID != " << glrun->ID            << " ID != " << glrun->ID
2923            << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";            << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2924        //        //
2925        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());
2926        result = conn->Query(oss.str().c_str());        result = conn->Query(oss.str().c_str());
2927        //        //
2928        if ( !result ) throw -4;        if ( !result ) throw -4;
2929        //        //
       foundinrun = true;  
2930        row = result->Next();        row = result->Next();
2931        //        //
2932      };        if ( !row && NoFrag() ){
2933      //          //
2934      if ( !row ){          oss.str("");
2935        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 "
2936        found = false;              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2937      } else {              << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2938        //              << " ID != " << glrun->ID
2939        found = false; // default value              << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2940        //          //
2941        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());
2942        //          result = conn->Query(oss.str().c_str());
2943        // if we have both runheader and runtrailer we can check with pkt_counter:          //
2944            if ( !result ) throw -4;
2945            //
2946            foundinrun = true;
2947            row = result->Next();
2948            //
2949          };
2950        //        //
2951        if ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){        if ( !row ){
2952          ULong64_t chkpkt = 0;            if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2953          ULong64_t pktt = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));          found = false;
2954          ULong64_t pkth = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());        } else {
2955          //          //
2956          chkpkt = pkth + (ULong64_t)((UInt_t)atoll(row->GetField(1))) + 1ULL + 1ULL;            found = false; // default value
2957          //          //
2958          if ( labs(chkpkt-pktt)<2 ){          if ( IsDebug() ) printf(" Found a possible candidate, checking if it is the good one... \n");
2959            //
2960            // if we have both runheader and runtrailer we can check with pkt_counter:
2961            //
2962            if ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){
2963              ULong64_t chkpkt = 0;  
2964              ULong64_t pktt = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
2965              ULong64_t pkth = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
2966            //            //
2967            if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);            chkpkt = pkth + (ULong64_t)((UInt_t)atoll(row->GetField(1))) + 1ULL + 1ULL;  
2968            //            //
2969            found = true;            if ( labs(chkpkt-pktt)<2 ){
2970                //
2971                if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
2972                //
2973                found = true;
2974                //
2975              } else {
2976                //
2977                if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);            
2978                //
2979                found = false;
2980                //
2981              };
2982            };
2983            if ( !found && chewbacca ) goto justcheck;
2984            if ( !found ){
2985            //            //
2986          } 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
2987            //            //
2988            if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);                  ULong64_t chkpkt1 = 0;
2989              ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
2990              ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
2991              chkpkt1 = labs(orunh1-dbrunt1);
2992            //            //
2993            found = false;            ULong64_t chkpkt2 = 0;
2994              ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNTRAILER_OBT());
2995              ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
2996              chkpkt2 = labs(orunh2-dbrunt2);
2997              //
2998              ULong64_t chkpkt3 = 0;
2999              ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNTRAILER_TIME());
3000              ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
3001              chkpkt3 = labs(orunh3-dbrunt3);
3002            //            //
3003              if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
3004                //
3005                if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
3006                //
3007                found = true;
3008                //
3009              } else {
3010                //
3011                if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
3012                //
3013                found = false;
3014                //
3015              };
3016          };          };
3017        };        };
3018        if ( !found && chewbacca ) goto justcheck;        //
3019        if ( !found ){        if ( found ){
3020            //
3021            // 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
3022            //
3023            if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
3024          //          //
3025          // 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 ){
3026              glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3027              glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
3028            };
3029          //          //
3030          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);  
3031          //          //
3032          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);  
3033          //          //
3034          ULong64_t chkpkt3 = 0;          oss.str("");
3035          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);  
3036          //          //
3037          if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){          glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runtrailer infos
3038            //          //
3039            if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);          // merge infos
3040            //          //
3041            found = true;          UInt_t apkt = PKT(glrun->GetRUNTRAILER_PKT());
3042            //          ULong64_t aobt = OBT(glrun->GetRUNTRAILER_OBT());
3043          } else {          UInt_t bpkt = PKT(glrun1->GetRUNHEADER_PKT());
3044            ULong64_t bobt = OBT(glrun1->GetRUNHEADER_OBT());
3045            if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
3046            TTree *T= 0;
3047            T = (TTree*)file->Get("Physics");
3048            if ( !T || T->IsZombie() ) throw -16;
3049            EventHeader *eh = 0;
3050            PscuHeader *ph = 0;
3051            T->SetBranchAddress("Header", &eh);
3052            while ( apkt > bpkt && aobt > bobt && lastev > 0 ){
3053              T->GetEntry(lastev);
3054              ph = eh->GetPscuHeader();
3055              apkt = PKT(ph->GetCounter());
3056              aobt = OBT(ph->GetOrbitalTime());    
3057              lastev--;
3058              if ( PEDANTIC ) throw -72;
3059            };
3060            if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
3061            //
3062            glrun->SetEV_TO(lastev);
3063            glrun->SetNEVENTS(lastev-firstev+1);
3064            glrun->SetPKT_COUNTER(glrun1->GetPKT_COUNTER());
3065            glrun->SetPKT_READY_COUNTER(glrun1->GetPKT_READY_COUNTER());
3066            glrun->SetRUNTRAILER_TIME(glrun1->GetRUNTRAILER_TIME());
3067            glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());
3068            glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());
3069            //
3070            glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());
3071            glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());
3072            glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());
3073            glrun1->SetCOMPILATIONTIMESTAMP(glrun->GetCOMPILATIONTIMESTAMP());
3074            glrun1->SetFAV_WRK_SCHEDULE(glrun->GetFAV_WRK_SCHEDULE());
3075            glrun1->SetEFF_WRK_SCHEDULE(glrun->GetEFF_WRK_SCHEDULE());
3076            glrun1->SetPRH_VAR_TRG_MODE_A(glrun->GetPRH_VAR_TRG_MODE_A());
3077            glrun1->SetPRH_VAR_TRG_MODE_B(glrun->GetPRH_VAR_TRG_MODE_B());
3078            glrun1->SetACQ_BUILD_INFO(glrun->GetACQ_BUILD_INFO());
3079            glrun1->SetACQ_VAR_INFO(glrun->GetACQ_VAR_INFO());
3080            glrun1->SetRM_ACQ_AFTER_CALIB(glrun->GetRM_ACQ_AFTER_CALIB());  
3081            glrun1->SetRM_ACQ_SETTING_MODE(glrun->GetRM_ACQ_SETTING_MODE());  
3082            glrun1->SetTRK_CALIB_USED(glrun->GetTRK_CALIB_USED());  
3083            glrun1->SetCAL_DSP_MASK(glrun->GetCAL_DSP_MASK());  
3084            glrun1->SetLAST_TIMESYNC(glrun->GetLAST_TIMESYNC());  
3085            glrun1->SetOBT_TIMESYNC(glrun->GetOBT_TIMESYNC());  
3086            //
3087            if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ) glrun1->SetPHYSENDRUN_MASK_S3S2S12(glrun->GetPHYSENDRUN_MASK_S3S2S12());
3088            if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) glrun1->SetPHYSENDRUN_MASK_S11CRC(glrun->GetPHYSENDRUN_MASK_S11CRC());
3089            //
3090            if ( !IsRunAlreadyInserted() ){
3091              //
3092              //    glrun->SetID(this->AssignRunID());
3093              //
3094              glrun->SetID_RUN_FRAG(glrun1->GetID());
3095              glrun->Fill_GL_RUN(conn);
3096            //            //
3097            if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);            // set id number
3098            //            //
3099            found = false;            glrun1->SetID_RUN_FRAG(glrun->GetID());
3100              glrun1->Fill_GL_RUN(conn);
3101            //            //
3102          };          };
3103            //
3104            // delete old entries in fragment table
3105            //
3106            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3107            glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3108            //
3109            delete glrun1;
3110            //
3111            return;
3112            //
3113        };        };
3114          //
3115      };      };
3116      //      //
3117      if ( found ){    justcheck:
3118        //      //
3119        // 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");  
       };  
3120        //        //
3121        GL_RUN *glrun1 = new GL_RUN();        if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");
3122        //        //
3123        //      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?
3124        //        //
3125        oss.str("");        oss.str("");
3126        oss << " ID="<<row->GetField(0)<<";";        oss << " SELECT ID FROM GL_RUN WHERE "
3127              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3128              << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3129              << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3130              << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3131              << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3132              << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3133              << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3134              << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3135              << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3136              << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3137              << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3138              << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3139              << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3140        //        //
3141        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());
3142          result = conn->Query(oss.str().c_str());
3143        //        //
3144        // merge infos        if ( !result ) throw -4;
3145        //        //
3146        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());    
3147        //        //
3148        if ( !IsRunAlreadyInserted() ){        if ( row ){
3149          //          if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");
3150          //      glrun->SetID(this->AssignRunID());          if ( PEDANTIC ) throw -70;
3151          //        } else {
3152          glrun->SetID_RUN_FRAG(glrun1->GetID());          if ( NoFrag() ){
3153          glrun->Fill_GL_RUN(conn);            glrun->SetID_RUN_FRAG(glrun->GetID());
3154          //            glrun->Fill_GL_RUN(conn);    
3155          // set id number            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3156          //          };    
         glrun1->SetID_RUN_FRAG(glrun->GetID());  
         glrun1->Fill_GL_RUN(conn);  
         //  
3157        };        };
       //  
       // delete old entries in fragment table  
       //  
       glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       //  
       delete glrun1;  
       //  
       return;  
       //  
3158      };      };
     //  
   };  
   //  
  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");  
       };      
     };  
   };  
3159    }; // EEE    }; // EEE
3160    //    //
3161    return;    return;
# Line 3068  Bool_t PamelaDBOperations::IsRunConsiste Line 3237  Bool_t PamelaDBOperations::IsRunConsiste
3237      code = eh->GetCounter();      code = eh->GetCounter();
3238      checkfirst = 0;      checkfirst = 0;
3239      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3240         if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
3241       };      };
3242      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);
3243      //      //
3244      T->GetEntry(lastev);      T->GetEntry(lastev);
3245      code = eh->GetCounter();      code = eh->GetCounter();
3246      checklast = 0;      checklast = 0;
3247      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3248         if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
3249       };      };
3250      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);
3251      //      //
3252      if ( checkfirst == checklast ){      if ( checkfirst == checklast ){
# Line 3088  Bool_t PamelaDBOperations::IsRunConsiste Line 3257  Bool_t PamelaDBOperations::IsRunConsiste
3257        //        //
3258      } else {      } else {
3259        //        //
3260        if ( IsDebug() ) printf(" There are no-phyics packets inside the run!\n");        if ( IsDebug() ) printf(" There are no-physics packets inside the run!\n");
3261        //        //
3262        // HERE WE MUST HANDLE THAT RUNS AND GO BACK        // HERE WE MUST HANDLE THAT RUNS AND GO BACK
3263        //        //
3264  //      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");
3265        //        //
3266        Bool_t emptyruns = false;        Bool_t emptyruns = false;
3267        UInt_t check = 0;        UInt_t check = 0;
3268        UInt_t lastevtemp = lastev;        UInt_t lastevtemp = lastev;
3269        UInt_t firstevno = firstev;        UInt_t firstevno = firstev;
3270          UInt_t rhchko=0;
3271          UInt_t rhchk=0;
3272        //        //
3273        for (UInt_t i=firstev; i<=lastev; i++){        for (UInt_t i=firstev; i<=lastev; i++){
3274          //          //
# Line 3106  Bool_t PamelaDBOperations::IsRunConsiste Line 3277  Bool_t PamelaDBOperations::IsRunConsiste
3277          //          //
3278          check = 0;          check = 0;
3279          //          //
3280    
3281            // if we have a runheader set lastev then exit
3282            //
3283          for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){          for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3284            if ( strcmp(*Iter,"Physics") ) check += code->Get(GetPacketType(*Iter));            if ( strcmp(*Iter,"Physics") ) check += code->Get(GetPacketType(*Iter));
3285          };          };
3286            // check here if we have a runheader
3287            rhchko = rhchk;  
3288            rhchk = code->Get(GetPacketType("RunHeader"));    
3289          //          //
3290          if ( checkfirst < check || i == lastev ){          if ( checkfirst < check || i == lastev ){
3291            //            //
# Line 3184  Bool_t PamelaDBOperations::IsRunConsiste Line 3361  Bool_t PamelaDBOperations::IsRunConsiste
3361            };            };
3362            //                  //      
3363            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
3364              this->SetPhysEndRunVariables();
3365            //            //
3366            if ( chminentry == firstentry  ){ // EEE            if ( chminentry == firstentry  ){ // EEE
3367              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");
3368  //              //
3369  //          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
3370  //              //
   
   
   
   
   
   
   
   
   
   
   
   
   
   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  
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
3371    
3372                mishead = true;
3373    
3374    
3375                UInt_t rhfirstev = firstentry;
3376                //  UInt_t rtlastev = lastentry;
3377                Bool_t found = false;
3378                Bool_t foundinrun = false;
3379                //
3380                TSQLResult *result = 0;
3381                TSQLRow    *row    = 0;
3382                //
3383                stringstream oss;
3384                oss.str("");
3385                //
3386                // we have now the good first piece of a run, fill the glrun object
3387                //
3388                //  if ( rhfirstev != firstev && !mishead ) mishead = true;
3389                //  if ( rtlastev != lastev && !mistrail ) mistrail = true;
3390                //
3391                //  this->FillClass(mishead,mistrail,firstev,lastev);
3392                //
3393                if ( IsDebug() ) printf("zz The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
3394                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());
3395                //
3396                // First of all insert the run in the fragment table...
3397                //
3398                oss.str("");
3399                oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
3400                    << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3401                    << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3402                    << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3403                    << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3404                    << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3405                    << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3406                    << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3407                    << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3408                    << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3409                    << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3410                    << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3411                    << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3412                    << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3413                //
3414                if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3415                result = conn->Query(oss.str().c_str());
3416                //
3417                if ( !result ) throw -4;
3418                //
3419                row = result->Next();
3420                //
3421                if ( !row ){
3422                  //
3423                  // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
3424                  //
3425                  if ( IsDebug() ) printf(" The run is new \n");
3426                  if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
3427                  //
3428                  glrun->SetID(this->AssignRunID());
3429                  glrun->SetID_RUN_FRAG(0);
3430                  glrun->Fill_GL_RUN_FRAGMENTS(conn);
3431                  //
3432                } else {
3433                  if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
3434                  if ( PEDANTIC ) throw -69;
3435                  //    return;
3436                };
3437                //
3438                if ( chewbacca && mishead && mistrail ) goto zjustcheck;
3439                //
3440                // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
3441                //
3442                if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
3443                  // missing it no way we can found a piece in the frag table
3444                  //
3445                  oss.str("");
3446                  oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "
3447                      << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3448                      << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3449                      << " ID != " << glrun->ID
3450                      << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
3451                  //
3452                  if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());
3453                  result = conn->Query(oss.str().c_str());
3454                  //
3455                  if ( !result ) throw -4;
3456                  //
3457                  row = result->Next();
3458                  //
3459                  if ( !row && NoFrag() ){
3460                    //
3461                    oss.str("");
3462                    oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
3463                        << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3464                        << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3465                        << " ID != " << glrun->ID
3466                        << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
3467                    //
3468                    if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
3469                    result = conn->Query(oss.str().c_str());
3470                    //
3471                    if ( !result ) throw -4;
3472                    //
3473                    foundinrun = true;
3474                    //
3475                    row = result->Next();
3476                    //
3477                  };
3478                  //
3479                  if ( !row ){
3480                    if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
3481                    found = false;
3482                  } else {
3483                    //
3484                    found = false; // default value
3485                    //
3486                    if ( IsDebug() ) printf(" Found a possible candidate, checking if it is the good one... \n");
3487                    //
3488                    // if we have both runheader and runtrailer we can check with pkt_counter:
3489                    //
3490                    if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){
3491                      ULong64_t chkpkt = 0;
3492                      ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
3493                      ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
3494                      //
3495                      chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;
3496                      //
3497                      if ( labs(chkpkt-pktt)<2 ){
3498                        //
3499                        if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
3500                        //
3501                        found = true;
3502                        //
3503                      } else {
3504                        //
3505                        if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);
3506                        //
3507                        found = false;
3508                        //
3509                      };
3510                    };
3511                    if ( !found && chewbacca ) goto zjustcheck;
3512                    if ( !found ){
3513                      //
3514                      // 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
3515                      //
3516                      ULong64_t chkpkt1 = 0;
3517                      ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
3518                      ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
3519                      chkpkt1 = labs(orunh1-dbrunt1);
3520                      //
3521                      ULong64_t chkpkt2 = 0;
3522                      ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());
3523                      ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
3524                      chkpkt2 = labs(orunh2-dbrunt2);
3525                      //
3526                      ULong64_t chkpkt3 = 0;
3527                      ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());
3528                      ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
3529                      chkpkt3 = labs(orunh3-dbrunt3);
3530                      //
3531                      if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
3532                        //    if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){
3533                        //
3534                        if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
3535                        //
3536                        found = true;
3537                        //
3538                      } else {
3539                        //
3540                        if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
3541                        //
3542                        found = false;
3543                        //
3544                      };
3545                    };
3546                  };
3547                  //
3548                  if ( found ){
3549                    //
3550                    // 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
3551                    //
3552                    if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
3553                    //
3554                    if ( foundinrun ){
3555                      glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3556                      glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
3557                    };
3558                    //
3559                    GL_RUN *glrun1 = new GL_RUN();
3560                    //
3561                    //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
3562                    //
3563                    oss.str("");
3564                    oss << " ID="<<row->GetField(0)<<";";
3565                    //
3566                    glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos
3567                    //
3568                    // merge infos
3569                    //
3570                    UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());
3571                    ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
3572                    UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
3573                    ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
3574                    if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
3575                    TTree *T= 0;
3576                    T = (TTree*)file->Get("Physics");
3577                    if ( !T || T->IsZombie() ) throw -16;
3578                    EventHeader *eh = 0;
3579                    PscuHeader *ph = 0;
3580                    T->SetBranchAddress("Header", &eh);
3581                    while ( apkt > bpkt && aobt > bobt && firstev < lastev ){
3582                      T->GetEntry(firstev);
3583                      ph = eh->GetPscuHeader();
3584                      bpkt = PKT(ph->GetCounter());
3585                      bobt = OBT(ph->GetOrbitalTime());
3586                      firstev++;
3587                      if ( PEDANTIC ) throw -71;
3588                    };
3589                    if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
3590                    //
3591                    glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
3592                    glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
3593                    glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
3594                    glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());
3595                    glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());
3596                    //
3597                    glrun->SetEV_FROM(firstev);
3598                    glrun->SetNEVENTS(lastev-firstev+1);
3599                    //
3600                    glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
3601                    glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
3602                    glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
3603                    glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());
3604                    glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());
3605                    glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());
3606                    glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());
3607                    glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());
3608                    glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());
3609                    glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());
3610                    glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());
3611                    glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());
3612                    glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());
3613                    glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());
3614                    glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());
3615                    glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());
3616                    //
3617                    if ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
3618                    if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
3619                    //
3620                    if ( !IsRunAlreadyInserted() ){
3621                      //
3622                      //      glrun->SetID(this->AssignRunID());
3623                      glrun->SetID_RUN_FRAG(glrun1->GetID());
3624                      glrun->Fill_GL_RUN(conn);
3625                      //
3626                      // set id number
3627                      //
3628                      glrun1->SetID_RUN_FRAG(glrun->GetID());
3629                      glrun1->Fill_GL_RUN(conn);
3630                      //
3631                    };
3632                    // delete old entry in fragment table
3633                    //
3634                    glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3635                    glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3636                    //
3637                    delete glrun1;
3638                    //
3639                    //
3640                    //      return;
3641                    //
3642                  };
3643                  //
3644                };
3645                //
3646                //
3647              zjustcheck:
3648                //
3649                if ( !found ){
3650                  //
3651                  if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");
3652                  //
3653                  // not found, has this run already inserted in the GL_RUN or in the GL_RUN_FRAGMENTS table?
3654                  //
3655                  oss.str("");
3656                  oss << " SELECT ID FROM GL_RUN WHERE "
3657                      << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3658                      << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3659                      << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3660                      << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3661                      << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3662                      << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3663                      << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3664                      << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3665                      << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3666                      << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3667                      << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3668                      << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3669                      << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3670                  //
3671                  if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3672                  result = conn->Query(oss.str().c_str());
3673                  //
3674                  if ( !result ) throw -4;
3675                  //
3676                  row = result->Next();
3677                  //
3678                  if ( row ){
3679                    if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");
3680                    if ( PEDANTIC ) throw -70;
3681                  } else {
3682                    if ( NoFrag() ){
3683                      glrun->SetID_RUN_FRAG(glrun->GetID());
3684                      glrun->Fill_GL_RUN(conn);
3685                      glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3686                    };
3687                  };
3688                }; // EEE
3689    
3690    
3691            } else {            } else {
3692            if ( !IsRunAlreadyInserted() ){              if ( !IsRunAlreadyInserted() ){
3693              glrun->SetID(this->AssignRunID());                glrun->SetID(this->AssignRunID());
3694              glrun->SetID_RUN_FRAG(0);                glrun->SetID_RUN_FRAG(0);
3695              glrun->Fill_GL_RUN(conn);                glrun->Fill_GL_RUN(conn);
3696            };              };
3697            }; // EEE            }; // EEE
3698            //            //
3699            firstevno = lastentry + 1;            firstevno = lastentry + 1;
# Line 3564  Bool_t PamelaDBOperations::IsRunConsiste Line 3702  Bool_t PamelaDBOperations::IsRunConsiste
3702            //            //
3703          };          };
3704          //          //
3705            if ( i > firstev ){
3706              if ( rhchko != rhchk ){
3707                if ( IsDebug() ) printf("oh oh... we have a runheader! stop here and handle later the remaining piece\n");
3708                lastev = i;
3709                return(false);
3710              };
3711            };
3712            //
3713          if ( check == checklast && i != lastev ){          if ( check == checklast && i != lastev ){
3714            lastevtemp = i - 1;            lastevtemp = i - 1;
3715            i = lastev - 1;            i = lastev - 1;
# Line 3647  void PamelaDBOperations::HandleSuspiciou Line 3793  void PamelaDBOperations::HandleSuspiciou
3793      code = eh->GetCounter();      code = eh->GetCounter();
3794      checkfirst = 0;      checkfirst = 0;
3795      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3796         if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
3797         if ( !strcmp(*Iter,"RunHeader") ) nrunh1++;        if ( !strcmp(*Iter,"RunHeader") ) nrunh1++;
3798       };      };
3799      if ( IsDebug() ) printf(" Check first is %i \n",checkfirst);      if ( IsDebug() ) printf(" Check first is %i \n",checkfirst);
3800      //      //
3801      T->GetEntry(lastev);      T->GetEntry(lastev);
3802      code = eh->GetCounter();      code = eh->GetCounter();
3803      checklast = 0;      checklast = 0;
3804      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3805         if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
3806       };      };
3807      if ( IsDebug() ) printf(" Check last is %i \n",checklast);      if ( IsDebug() ) printf(" Check last is %i \n",checklast);
3808      //      //
3809      if ( checkfirst == checklast ){      if ( checkfirst == checklast ){
# Line 3769  void PamelaDBOperations::HandleSuspiciou Line 3915  void PamelaDBOperations::HandleSuspiciou
3915            };            };
3916            //                  //      
3917            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
3918              this->SetPhysEndRunVariables();
3919            //            //
3920            if ( !IsRunAlreadyInserted() ){            if ( !IsRunAlreadyInserted() ){
3921              glrun->SetID(this->AssignRunID());              glrun->SetID(this->AssignRunID());
# Line 3808  void PamelaDBOperations::HandleSuspiciou Line 3955  void PamelaDBOperations::HandleSuspiciou
3955              if ( IsDebug() ) printf(" We have the runtrailer \n");              if ( IsDebug() ) printf(" We have the runtrailer \n");
3956              //                  //    
3957              this->SetCommonGLRUN(firstTime,lastTime);              this->SetCommonGLRUN(firstTime,lastTime);
3958                this->SetPhysEndRunVariables();
3959              //              //
3960              if ( !IsRunAlreadyInserted() ){              if ( !IsRunAlreadyInserted() ){
3961                glrun->SetID(this->AssignRunID());                glrun->SetID(this->AssignRunID());
# Line 4382  Int_t PamelaDBOperations::insertCALOPULS Line 4530  Int_t PamelaDBOperations::insertCALOPULS
4530   * Fill the GL_TRK_CALIB table   * Fill the GL_TRK_CALIB table
4531   */   */
4532  void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){  void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){
4533    //      
4534    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;  
4535      //      //
4536    } else {      glcal->ID         = 0;
4537        glcal->ID_ROOT_L0 = GetID_ROOT();
4538        glcal->EV_ROOT_CALIBTRK1 = t1;
4539        glcal->EV_ROOT_CALIBTRK2 = t2;
4540        glcal->FROM_TIME = fromtime;
4541        glcal->TO_TIME   = 0;
4542        glcal->OBT1      = obt1;
4543        glcal->OBT2      = obt2;
4544        glcal->PKT1      = pkt1;
4545        glcal->PKT2      = pkt2;
4546        glcal->BOOT_NUMBER = GetBOOTnumber();
4547        glcal->VALIDATION = valid;
4548      //      //
4549      // we have to insert a new calibration, check where to place it      HandleTRK_CALIB(glcal);
4550      //      //
4551      oss.str("");      delete glcal;
4552      oss << " SELECT ID,TO_TIME FROM GL_TRK_CALIB WHERE "  }
4553          << " FROM_TIME < "<< fromtime << " AND "  /**
4554          << " TO_TIME > "<< fromtime << ";";   * Fill the GL_TRK_CALIB table
4555     */
4556    void PamelaDBOperations::HandleTRK_CALIB(GL_TRK_CALIB *glcal){
4557    
4558        Bool_t pk1 = (glcal->OBT1>0&&glcal->PKT1>0);
4559        Bool_t pk2 = (glcal->OBT2>0&&glcal->PKT2>0);
4560        UInt_t boot_number = glcal->BOOT_NUMBER;
4561        UInt_t obt1 = glcal->OBT1;
4562        UInt_t obt2 = glcal->OBT2;
4563        UInt_t pkt1 = glcal->PKT1;
4564        UInt_t pkt2 = glcal->PKT2;
4565        UInt_t fromtime = glcal->FROM_TIME;
4566        UInt_t totime = 0;
4567        UInt_t idroot = glcal->ID_ROOT_L0;
4568        UInt_t t1 = glcal->EV_ROOT_CALIBTRK1;
4569        UInt_t t2 = glcal->EV_ROOT_CALIBTRK2;
4570        UInt_t valid = glcal->VALIDATION;
4571      //      //
4572      if ( IsDebug() ) printf(" Check where to place the trk calibration: query is \n %s \n",oss.str().c_str());      TSQLResult *result = 0;
4573      result = conn->Query(oss.str().c_str());      TSQLRow    *row    = 0;
4574      //      //
4575      if ( !result ) throw -4;      stringstream oss;
4576        oss.str("");
4577      //      //
     row = result->Next();  
4578      //      //
4579      if ( !row ){      if ( !pk1 && !pk2 ){
4580        //          if ( IsDebug() ) printf(" Cannot handle trk calibration with both packet missing!\n");
4581        // 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;  
       //  
4582      };      };
4583      //      //
4584      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 << "',";  
4585      //      //
4586      if ( !pk1 ){      oss.str("");
4587        oss << "NULL,";      oss << " SELECT ID FROM GL_TRK_CALIB WHERE "
4588            << " BOOT_NUMBER = "<< boot_number; //
4589        oss << " AND FROM_TIME="<<fromtime; /// NEWNEWNEW -- VA BENE ?!?!?!?!
4590        oss << " AND ( ( ";  
4591        if ( pk1 ){
4592            oss << " OBT1 = "<< obt1 << " AND "
4593                << " PKT1 = "<< pkt1
4594                << " ) OR ( ";
4595      } else {      } else {
4596        oss << "'"          oss << " PKT1 = "<< pkt2-1
4597            << t1 << "',";              << " ) OR ( ";  
4598      };      };      
4599      //      if ( pk2 ){
4600      if ( !pk2 ){          oss << " OBT2 = "<< obt2 << " AND "
4601        oss << "NULL,'";              << " PKT2 = "<< pkt2;
4602      } else {      } else {
4603        oss << "'"          oss << " PKT2 = "<< pkt1+1;
4604            << t2 << "','";      };      
4605      };      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());  
4606      //      //
4607        if ( IsDebug() ) printf(" Check if the trk calibration has already been inserted: query is \n %s \n",oss.str().c_str());
4608      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
4609      //      //
4610      if ( !result ) throw -4;      if ( !result ) throw -4;
4611      //      //
4612    };      row = result->Next();
4613    //      //
4614        if ( row ){
4615            //
4616            if ( IsDebug() ) printf(" Trk calibration already inserted in the DB\n");
4617            if ( PEDANTIC ) throw -80;
4618            //
4619        } else {
4620            //
4621            // we have to insert a new calibration, check where to place it
4622            //
4623            oss.str("");
4624            oss << " SELECT ID,TO_TIME FROM GL_TRK_CALIB WHERE "
4625                << " FROM_TIME < "<< fromtime << " AND "
4626                << " TO_TIME > "<< fromtime << ";";
4627            //
4628            if ( IsDebug() ) printf(" Check where to place the trk calibration: query is \n %s \n",oss.str().c_str());
4629            result = conn->Query(oss.str().c_str());
4630            //
4631            if ( !result ) throw -4;
4632            //
4633            row = result->Next();
4634            //
4635            if ( !row ){
4636                //
4637                // no calibrations in the db contain our calibration
4638                //
4639                if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB\n");
4640                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
4641                //
4642                oss.str("");
4643                oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "
4644                    << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
4645                //
4646                if ( IsDebug() ) printf(" Check the upper limit for calibration: query is \n %s \n",oss.str().c_str());
4647                result = conn->Query(oss.str().c_str());
4648                //
4649                if ( !result ) throw -4;
4650                //
4651                row = result->Next();
4652                if ( !row ){
4653                    totime = numeric_limits<UInt_t>::max();
4654                } else {
4655                    totime = (UInt_t)atoll(row->GetField(0));
4656                };
4657                //
4658            } else {
4659                //
4660                // determine upper and lower limits and make space for the new calibration
4661                //
4662                totime = (UInt_t)atoll(row->GetField(1));
4663                //
4664                oss.str("");
4665                oss << " UPDATE GL_TRK_CALIB SET "  
4666                    << " TO_TIME = "<< fromtime << " WHERE "  // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
4667                    << " ID = "<< row->GetField(0) << ";";
4668                //
4669                if ( IsDebug() ) printf(" Make space for the new trk calibration: query is \n %s \n",oss.str().c_str());
4670                result = conn->Query(oss.str().c_str());
4671                //
4672                if ( !result ) throw -4;
4673                //
4674            };
4675            //
4676            oss.str("");
4677            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) "
4678                << " VALUES (NULL,' "
4679                << idroot << "',";
4680            //
4681            if ( !pk1 ){
4682                oss << "NULL,";
4683            } else {
4684                oss << "'"
4685                    << t1 << "',";
4686            };
4687            //
4688            if ( !pk2 ){
4689                oss << "NULL,'";
4690            } else {
4691                oss << "'"
4692                    << t2 << "','";
4693            };
4694            //
4695            oss << fromtime << "','"
4696                << totime << "','"
4697                << obt1 << "','"
4698                << pkt1 << "','"
4699                << obt2 << "','"
4700                << pkt2 << "','"
4701                << boot_number << "','"
4702                << valid << "');";
4703            //
4704            if ( IsDebug() ) printf(" Insert the new trk calibration: query is \n %s \n",oss.str().c_str());
4705            //
4706            result = conn->Query(oss.str().c_str());
4707            //
4708            if ( !result ) throw -4;
4709            //
4710        };
4711        
4712        oss.str("");
4713        oss << " SELECT ID FROM GL_TRK_CALIB ORDER BY ID DESC LIMIT 1 ;";  
4714        if ( IsDebug() ) cout << oss.str().c_str() << endl;
4715        result = conn->Query(oss.str().c_str());
4716        if ( !result ) throw -4;;
4717        row = result->Next();
4718        if(row)glcal->ID = (UInt_t)atoll(row->GetField(0));
4719    
4720        //
4721  };  };
4722    
4723  /**  /**
4724   * Scan tracker calibrations packets, fill the GL_TRK_CALIB table   * Scan tracker calibrations packets, fill the GL_TRK_CALIB table
4725   */   */
4726  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++){  
4727      //      //
4728      pret2 = t2;      CalibTrk1Event *caltrk1 = 0;
4729      tr1->GetEntry(t1);      CalibTrk2Event *caltrk2 = 0;
4730        TTree *tr1 = 0;
4731        TTree *tr2 = 0;
4732        EventHeader *eh1 = 0;
4733        PscuHeader *ph1 = 0;
4734        EventHeader *eh2 = 0;
4735        PscuHeader *ph2 = 0;
4736      //      //
4737      ph1 = eh1->GetPscuHeader();      PacketType *pctp=0;
4738      obt1 = ph1->GetOrbitalTime();        EventCounter *codt2=0;
     pkt1 = ph1->GetCounter();    
     fromtime = this->GetAbsTime(ph1->GetOrbitalTime());    
4739      //      //
4740  //     valid = 1;      Int_t nevents1 = 0;
4741  //     //      Int_t nevents2 = 0;
 //     if ( caltrk1->unpackError != 0 && caltrk1->good0 == 0 ) valid = 0;// CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT1  
4742      //      //
4743        fromtime = 0;
4744      //      //
4745      if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->PKT(pkt1) <= upperpkt && this->OBT(obt1) >= this->OBT(obtfirst) && this->OBT(obt1) <= upperobt ){      obt1 = 0;
4746        //    if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->OBT(obt1) >= this->OBT(obtfirst) ){      pkt1 = 0;
4747        //      obt2 = 0;
4748        if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u \n",fromtime,obt1,pkt1);      pkt2 = 0;
4749        //            //
4750        valid = ValidateTrkCalib( caltrk1, eh1 );      tr1 = (TTree*)file->Get("CalibTrk1");
4751        if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;      if ( !tr1 || tr1->IsZombie() ) throw -22;
4752        //      tr2 = (TTree*)file->Get("CalibTrk2");
4753        // Do we have the second calibration packet?      if ( !tr2 || tr2->IsZombie() ) throw -23;
4754        //      //
4755        while ( t2t1cal < t1+1 ){ // get the calibration packet2 that follows the packet1      tr1->SetBranchAddress("CalibTrk1", &caltrk1);
4756        tr1->SetBranchAddress("Header", &eh1);
4757        nevents1 = tr1->GetEntries();
4758        tr2->SetBranchAddress("CalibTrk2", &caltrk2);
4759        tr2->SetBranchAddress("Header", &eh2);
4760        nevents2 = tr2->GetEntries();
4761        //
4762        if ( !nevents1 && !nevents2 ) return(1);
4763        //
4764        t2 = -1;
4765        Int_t pret2 = 0;
4766        Int_t t2t1cal = 0;
4767        //
4768        bool MISSING_pkt1 = true;
4769        bool MISSING_pkt2 = true;
4770        int  ncalib = 0;
4771        bool try_to_recover = false;
4772        //
4773        for (t1=0; t1 < nevents1; t1++){//loop over packet1
4774            //
4775            pret2 = t2;
4776            tr1->GetEntry(t1);
4777          //          //
4778          t2++;          ph1 = eh1->GetPscuHeader();
4779            obt1 = ph1->GetOrbitalTime();  
4780            pkt1 = ph1->GetCounter();  
4781            fromtime = GetAbsTime(ph1->GetOrbitalTime());  
4782          //          //
4783          pret2 = t2 - 1; // EMILIANO          // chek if the packet number and obt are consistent with the other packets ???
4784          //          //
4785          if ( t2 < nevents2 ){          if ( PKT(pkt1) >= PKT(pktfirst) && PKT(pkt1) <= upperpkt && OBT(obt1) >= OBT(obtfirst) && OBT(obt1) <= upperobt ){
4786            tr2->GetEntry(t2);              //    if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->OBT(obt1) >= this->OBT(obtfirst) ){
4787            codt2 = eh2->GetCounter();              //
4788            t2t1cal = codt2->Get(pctp->CalibTrk1);              if ( IsDebug() ) printf("\n Trk calibration1 %u at time %u obt %u pkt %u \n",t1,fromtime,obt1,pkt1);
4789            //              //      
4790            ph2 = eh2->GetPscuHeader();              valid = ValidateTrkCalib( caltrk1, eh1 );
4791            obt2 = ph2->GetOrbitalTime();                if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;
4792            pkt2 = ph2->GetCounter();                //
4793            //              // Do we have the second calibration packet?
4794            if ( IsDebug() ) printf(" This is a trk calibration2 at obt %u pkt %u t2 is %u , t2t1cal is %u \n",obt2,pkt2,t2,t2t1cal);                    //
4795  //        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;
4796            //                    while ( t2t1cal < t1+1 ){ // get the calibration packet2 that follows the packet1
4797                    //
4798                    t2++;
4799                    //
4800                    pret2 = t2 - 1; // EMILIANO
4801                    //
4802                    if ( t2 < nevents2 ){
4803                        tr2->GetEntry(t2);
4804                        codt2 = eh2->GetCounter();
4805                        t2t1cal = codt2->Get(pctp->CalibTrk1);
4806                        //
4807                        ph2 = eh2->GetPscuHeader();
4808                        obt2 = ph2->GetOrbitalTime();  
4809                        pkt2 = ph2->GetCounter();  
4810                        //
4811                        if ( IsDebug() ) printf(" >> trk calibration2 at obt %u pkt %u t2 is %u , t2t1cal is %u \n",obt2,pkt2,t2,t2t1cal);    
4812                        //    if ( caltrk2->unpackError != 0 || caltrk2->good0 == 0 ) valid = 0; // CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT2
4813                        //    
4814                    } else {
4815                        //
4816                        // running out of vector without finding the corresponding calibration, sig
4817                        //
4818                        if ( IsDebug() ) printf(" t2 >= nevents2 \n");
4819                        pret2 = t2;
4820                        obt2 = 0;
4821                        //    pkt2 = pkt1+2;
4822                        pkt2 = 0;
4823                        t2t1cal = t1+1;
4824                    };
4825                    //      if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) && (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){
4826    
4827                    // EMILIANO
4828                    //      if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) || (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){
4829                    //        //    if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){
4830                    //        if ( IsDebug() ) printf(" running out of vector without finding the corresponding calibration, sig \n");
4831                    //        //
4832                    //        // running out of vector without finding the corresponding calibration, sig
4833                    //        //
4834                    //        pret2 = t2;
4835                    //        obt2 = 0;
4836                    //        //      pkt2 = pkt1+2;
4837                    //        pkt2 = 0;
4838                    //        t2t1cal = t1+1;
4839                    //      };
4840    
4841    
4842                    //
4843                };
4844                //
4845                if ( IsDebug() ) printf(" Check if trk calibration2 is the right one \n");
4846                //
4847                // EMILIANO
4848                if ( ( PKT(pkt2) < PKT(pktfirst) || PKT(pkt2) > upperpkt) || (OBT(obt2) < OBT(obtfirst) || OBT(obt2) > upperobt) ){
4849                    //      if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){
4850                    if ( IsDebug() ) printf(" *WARNING*  The calibration found is outside the interval, sig \n");
4851                    //
4852                    // running out of vector without finding the corresponding calibration, sig
4853                    //
4854                    pret2 = t2;
4855                    obt2 = 0;
4856                    pkt2 = 0;
4857                };
4858                if ( PKT(pkt2) == PKT(pkt1)+1 ){
4859                    if ( IsDebug() ) cout << " ...OK"<<endl;
4860                    // =======================
4861                    // The calibration is good
4862                    // =======================
4863                    //
4864    //      if ( IsDebug() ) printf(" Found trk calibration2 at obt %u pkt %u t2 is %u \n",obt2,pkt2,t2);
4865    //      if ( IsDebug() ) printf(" Trk calibration2 at obt %u pkt %u t2 is %u is good \n",obt2,pkt2,t2);
4866    //        if ( IsDebug() ) printf("\n Trk calibration2 at time %u obt %u pkt %u \n",fromtime,obt2,pkt2);
4867                    if ( IsDebug() ) printf(" Trk calibration2 %u at time %u obt %u pkt %u \n",t2,fromtime,obt2,pkt2);
4868                    //
4869                    UInt_t valid2 = ValidateTrkCalib( caltrk2, eh2 );
4870                    if ( IsDebug() ) cout << " pkt2 validation --> "<<valid2<<endl;
4871    //      valid = valid & valid2;
4872                    valid = valid & valid2; //QUESTO VA CAMBIATO
4873                    //
4874                    // Handle good calib
4875                    //
4876                    MISSING_pkt1 = false;
4877                    MISSING_pkt2 = false;
4878    //              this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4879                    //
4880                    // Check for missing calibtrk1
4881                    //
4882                    if ( t2 != pret2+1 ){
4883                        //
4884                        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);
4885                        //
4886                        while ( t2 > pret2+1 ){
4887                            //
4888                            // handle missing calib1
4889                            //
4890                            pret2++;
4891                            //
4892                            obt1 = 0;
4893                            pkt1 = 0;
4894                            //
4895                            tr2->GetEntry(pret2);
4896                            ph2 = eh2->GetPscuHeader();
4897                            obt2 = ph2->GetOrbitalTime();  
4898                            pkt2 = ph2->GetCounter();  
4899                            //
4900                            fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
4901                            //
4902                            valid = 0;
4903                            MISSING_pkt1 = true;
4904                            MISSING_pkt2 = false;
4905    //                      this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4906                            //
4907                        };
4908                        //
4909                    };
4910                    //
4911                } else if ( this->PKT(pkt2) > this->PKT(pkt1)+1 ){
4912                    //
4913                    // Check for missing calibtrk2
4914                    //
4915                    if ( IsDebug() ) printf(" Missing the trk calibration2! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);
4916                    t2 = pret2;
4917                    //
4918                    // handle missing calib2
4919                    //
4920                    obt2 = 0;
4921                    pkt2 = 0;
4922                    valid = 0;
4923                    MISSING_pkt1 = false;
4924                    MISSING_pkt2 = true;
4925    //              this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4926                    //
4927                };
4928                //
4929    
4930                if( !(MISSING_pkt1&MISSING_pkt2) ){
4931                  this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4932                  ncalib++;
4933                  if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
4934                }
4935    
4936    
4937          } else {          } else {
4938            //            //
4939            // 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);
4940            //              //      if ( PEDANTIC ) throw -79;
4941            if ( IsDebug() ) printf(" t2 >= nevents2 \n");              //
           pret2 = t2;  
           obt2 = 0;  
           //      pkt2 = pkt1+2;  
           pkt2 = 0;  
           t2t1cal = t1+1;  
4942          };          };
4943          //      if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) && (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){          //    
4944    
4945          // 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;  
 //      };  
4946    
4947    
4948    
4949        //
4950        // we have one more calib pkt2 !
4951        //
4952        t2++;
4953        while ( t2 < nevents2 ){
4954          //          //
4955        };          // 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  
4956          //          //
4957          this->HandleTRK_CALIB(true,true);          if ( IsDebug() ) printf(" t2 is %u nevents2 is %u \n",t2,nevents2);
4958            obt1 = 0;
4959            pkt1 = 0;
4960          //          //
4961          // Check for missing calibtrk1          tr2->GetEntry(t2);
4962            ph2 = eh2->GetPscuHeader();
4963            obt2 = ph2->GetOrbitalTime();  
4964            pkt2 = ph2->GetCounter();  
4965          //          //
4966          if ( t2 != pret2+1 ){          fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
4967            //          valid = 0;
4968            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 ){
4969            //          // EMILIANO
4970            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 ){
4971              //              //    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();    
4972              //              //
4973              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);
4974              //              //
4975              valid = 0;              MISSING_pkt1 = true;
4976              this->HandleTRK_CALIB(false,true);              MISSING_pkt2 = false;
4977                this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4978                ncalib++;
4979                if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
4980              //              //
           };  
           //  
4981          };          };
4982          //          //
4983        } 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;  
4984          //          //
4985          // handle missing calib2      };
4986    
4987    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
4988    // -----------------------------------------------------------------
4989    // in case of corruption, check if the calibration can be recovered
4990    // from another chewbacca file
4991    // -----------------------------------------------------------------
4992    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
4993    
4994    //    cout <<" TRY TO RECOVER ?? "<<try_to_recover<<endl;
4995        
4996        if(chewbacca&&try_to_recover){
4997    
4998    
4999            if ( IsDebug() ) cout << endl << ">>>> TRY TO RECOVER TRACKER CALIBRATIONS <<<<"<<endl;
5000    
5001            TSQLResult *result = 0;
5002            TSQLRow    *row    = 0;
5003          //          //
5004          obt2 = 0;          stringstream oss;
5005          pkt2 = 0;          oss.str("");
         valid = 0;  
         this->HandleTRK_CALIB(true,false);        
5006          //          //
5007        };  
5008        //          ////////////////////////////////////////////////////////////////////////
5009      } else {          // retrieve the name of the current file:
5010        //          ////////////////////////////////////////////////////////////////////////        
5011        if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u OUTSIDE the considered time interval \n",fromtime,obt1,pkt1);          oss.str("");
5012        //      if ( PEDANTIC ) throw -79;          oss << "SELECT NAME FROM GL_ROOT where ID=" << GetID_ROOT() <<";";
5013        //          if ( IsDebug() ) cout << oss.str().c_str() << endl;
5014      };  
5015      //              result = conn->Query(oss.str().c_str());
5016    };          if ( !result ) throw -4;;
5017    //          row = result->Next();
5018    // we have one more calib pkt2 !          TString thisfilename = (TString)row->GetField(0);
5019    //          if ( IsDebug() ) cout << "Current file ==> "<<thisfilename<<endl;      
5020    t2++;  
5021    while ( t2 < nevents2 ){          ////////////////////////////////////////////////////////////////////////        
5022      //          // read all the calibrations inserted
5023      // handle missing calib1          ////////////////////////////////////////////////////////////////////////        
5024      //          oss.str("");
5025      if ( IsDebug() ) printf(" t2 is %u nevents2 is %u \n",t2,nevents2);          oss << " SELECT ";
5026      obt1 = 0;          oss << " ID,FROM_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,TO_TIME";
5027      pkt1 = 0;          oss << " FROM GL_TRK_CALIB ";
5028      //          oss << " ORDER BY ID DESC LIMIT "<<ncalib<<"; ";        
5029      tr2->GetEntry(t2);          if ( IsDebug() ) cout << oss.str().c_str() << endl;
5030      ph2 = eh2->GetPscuHeader();  
5031      obt2 = ph2->GetOrbitalTime();            result = conn->Query(oss.str().c_str());
5032      pkt2 = ph2->GetCounter();            if ( !result ) throw -4;;
5033      //          if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5034      fromtime = this->GetAbsTime(ph2->GetOrbitalTime());          
5035      valid = 0;          // -----------------------------------
5036  //  if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->PKT(pkt1) <= upperpkt && this->OBT(obt1) >= this->OBT(obtfirst) && this->OBT(obt1) <= upperobt ){          // loop over calibrations ...
5037   // EMILIANO          // -----------------------------------
5038      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;
5039        //    if ( this->PKT(pkt2) > this->PKT(pktfirst) || this->OBT(obt2) > this->OBT(obtfirst) ){          do {
5040        //              row = result->Next();
5041        if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);              if(!row)break;
5042        //              
5043        this->HandleTRK_CALIB(false,true);              UInt_t id       = (UInt_t)atoll(row->GetField(0));
5044        //              UInt_t fromtime = (UInt_t)atoll(row->GetField(1));
5045      };              UInt_t obt1     = (UInt_t)atoll(row->GetField(2));
5046      //              UInt_t pkt1     = (UInt_t)atoll(row->GetField(3));
5047      t2++;              UInt_t obt2     = (UInt_t)atoll(row->GetField(4));
5048      //              UInt_t pkt2     = (UInt_t)atoll(row->GetField(5));
5049    };              UInt_t boot     = (UInt_t)atoll(row->GetField(6));
5050                UInt_t valid    = (UInt_t)atoll(row->GetField(7));
5051                bool MISSING_pkt1 = (row->GetFieldLength(8)==0);
5052                bool MISSING_pkt2 = (row->GetFieldLength(9)==0);
5053                UInt_t totime   = (UInt_t)atoll(row->GetField(10));
5054    
5055                // -------------------------------------
5056                // ...check if the entry is corrupted...
5057                // -------------------------------------
5058                cout <<"*** "<< MISSING_pkt1 << MISSING_pkt2 << valid <<endl;
5059                bool CORRUPTED = (MISSING_pkt1||MISSING_pkt2||!valid);
5060    
5061                if ( IsDebug() ) cout << "("<<nn<<")  ID = "<<id<<" from GL_TRK_CALIB  ==>  corrupted ? "<<CORRUPTED<<endl;
5062    
5063    //          if( !CORRUPTED  )continue; // nothing to do
5064    
5065                /////////////////////////////////////////////////////////  
5066                // if it is corrupted, ...look for ather chewbacca files
5067                // containing the same calibrations ...
5068                /////////////////////////////////////////////////////////
5069    
5070                bool this_MISSING_pkt1 = false;
5071                bool this_MISSING_pkt2 = false;
5072                int  this_t1=0;
5073                int  this_t2=0;;
5074                UInt_t this_valid = 0;
5075    
5076                TString path       = "";
5077                TString name       = "";
5078                TString raw        = "";
5079                UInt_t obt0        = 0;
5080                UInt_t timesync    = 0;
5081                UInt_t boot_number = 0;
5082                bool   FOUND       = false;
5083    
5084                if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
5085    
5086    //          for(int itable=0; itable<2; itable++){
5087                for(int itable=0; itable<1; itable++){
5088    
5089                    // ------------------------------------------------------
5090                    // loop over both ROOT_TABLE and ROOT_TABLE_BAD
5091                    // ------------------------------------------------------
5092    
5093                    TString table = "ROOT_TABLE";
5094                    if(itable==1)table = "ROOT_TABLE_BAD";
5095    
5096                    oss.str("");
5097                    oss << " SELECT ";
5098                    oss << " FOLDER_NAME,FILE_NAME,OBT_TIME_SYNC,LAST_TIME_SYNC_INFO,BOOT_NUMBER,INPUT_NAME ";
5099                    oss << " FROM "<<table;
5100                    oss << " WHERE 1 " << endl;
5101                    oss << " AND FILE_NAME != \""<< thisfilename<<"\"";
5102                    if( !MISSING_pkt1 ){
5103                        oss << " AND ";
5104                        oss << " PKT_NUMBER_INIT < "<<pkt1;
5105                        oss << " AND ";
5106                        oss << " PKT_NUMBER_FINAL > "<<pkt1;
5107                        oss << " AND ";
5108                        oss << " PKT_OBT_INIT < "<<obt1;
5109                        oss << " AND ";
5110                        oss << " PKT_OBT_FINAL > "<<obt1;
5111                    }else{
5112                        if(pkt2>1) pkt1 = pkt2-1;//serve dopo                  
5113                    }
5114                    if( !MISSING_pkt2 ){
5115                        oss << " AND ";
5116                        oss << " PKT_NUMBER_INIT < "<<pkt2;
5117                        oss << " AND ";
5118                        oss << " PKT_NUMBER_FINAL > "<<pkt2;
5119                        oss << " AND ";
5120                        oss << " PKT_OBT_INIT < "<<obt2;
5121                        oss << " AND ";
5122                        oss << " PKT_OBT_FINAL > "<<obt2;
5123                    }else{
5124                        if(pkt1>0) pkt2 = pkt1+1;//serve dopo
5125                    }
5126                    if( boot> 0 ){
5127                        oss << " AND ";
5128                        oss << " BOOT_NUMBER = "<<boot;
5129                    }else{
5130                    }
5131                    oss << " ORDER BY BAD_PKT_CALREAD ASC; ";
5132                
5133                    TSQLResult *result2 = 0;
5134                    TSQLRow    *row2    = 0;
5135    
5136                    if ( IsDebug() ) cout << oss.str().c_str() << endl;        
5137                    result2 = conn->Query(oss.str().c_str());
5138                    if ( !result2 ) throw -4;;
5139                    if ( IsDebug() ) cout <<"Rows: "<<result2->GetRowCount()<<endl;
5140    
5141                    // ------------------------------------------------------
5142                    // loop over files containing repetition (if any)
5143                    // ------------------------------------------------------
5144                    do {
5145                        row2 = result2->Next();
5146                        if(!row2)break;
5147                    
5148                        // ------------------------------------------------------
5149                        // ... a repetition is found ...
5150                        // ------------------------------------------------------
5151                        path       = (TString)row2->GetField(0);
5152                        name       = (TString)row2->GetField(1);
5153                        raw        = (TString)row2->GetField(5);
5154                        obt0        = (UInt_t)atoll(row2->GetField(2));
5155                        timesync    = (UInt_t)atoll(row2->GetField(3));
5156                        boot_number = (UInt_t)atoll(row2->GetField(4));
5157                    
5158                        if ( IsDebug() ) cout << "- - - - - - - - - - -" <<endl;
5159    //                  cout << path <<endl;
5160    //                  cout << "File    : " <<name <<endl;
5161    //                  cout << obt0 <<endl;
5162    //                  cout << timesync <<endl;
5163    //                  cout << "boot n. : "<<boot_number <<endl;
5164    //                  cout << raw <<endl;
5165    
5166                        // ------------------------------------------------------
5167                        // ... retrieve the calibration packets.
5168                        // ------------------------------------------------------
5169                        if ( IsDebug() ) printf(" file is %s/%s \n",((TString)gSystem->ExpandPathName(path.Data())).Data(),name.Data());
5170                        TFile *file = new TFile(((TString)gSystem->ExpandPathName(path.Data()))+"/"+name); // EM, path could be symbolic and we must expand it
5171                        if(!file)throw -100;
5172                        if(file->IsZombie())throw -100;
5173                        //
5174                        tr1 = (TTree*)file->Get("CalibTrk1");
5175                        if ( !tr1 || tr1->IsZombie() ) throw -22;
5176                        tr2 = (TTree*)file->Get("CalibTrk2");
5177                        if ( !tr2 || tr2->IsZombie() ) throw -23;
5178                        //
5179                        tr1->SetBranchAddress("CalibTrk1", &caltrk1);
5180                        tr1->SetBranchAddress("Header", &eh1);
5181                        nevents1 = tr1->GetEntries();
5182                        tr2->SetBranchAddress("CalibTrk2", &caltrk2);
5183                        tr2->SetBranchAddress("Header", &eh2);
5184                        nevents2 = tr2->GetEntries();
5185                        for(this_t1=0; this_t1<nevents1; this_t1++){
5186                            tr1->GetEntry(this_t1);
5187                            if(
5188                                (UInt_t)eh1->GetPscuHeader()->GetCounter() == pkt1 &&
5189                                true) break;
5190                            this_MISSING_pkt1 = true;
5191                        }
5192                        for(this_t2=0; this_t2<nevents2; this_t2++){
5193                            tr2->GetEntry(this_t2);
5194                            if(
5195                                (UInt_t)eh2->GetPscuHeader()->GetCounter() == pkt2 &&
5196                                true) break;
5197                            this_MISSING_pkt2 = true;
5198                        }
5199                        this_valid =
5200                            ValidateTrkCalib( caltrk1, eh1, file )
5201                            *
5202                            ValidateTrkCalib( caltrk2, eh2, file );
5203                                
5204                        // ---------------------------------------------------------------------
5205                        // accept the calibration if it is better than the previous:
5206                        //
5207                        // - if the new calibration is perfect (both valid packets)
5208                        // - if the new calibration has both the packets and the previous does not
5209                        // ---------------------------------------------------------------------
5210                        if(
5211                            ( !this_MISSING_pkt1&&!this_MISSING_pkt2&&this_valid )||
5212                            ( (MISSING_pkt1||MISSING_pkt2) && (!this_MISSING_pkt1&&!this_MISSING_pkt2) )||
5213                            false)FOUND=true;      
5214                
5215                        if(file)file->Close();
5216    
5217                        if(FOUND)break;
5218    
5219                    }while(1);//endl loop over root table entries
5220    
5221                    if(FOUND)break;
5222    
5223                }//end loop over tables
5224    
5225                if(FOUND){
5226    
5227                if ( IsDebug() ) cout << " >>> REPETITION FOUND :-) <<<" <<endl;
5228    
5229                    ////////////////////////////////////////////
5230                    // insert a new entry in GL_TRK_CALIB and
5231                    // modify the time-tag of the previous one
5232                    ////////////////////////////////////////////
5233    
5234                    // ---------------------------------------------------------------------
5235                    // step 1: insert a new raw file in GL_RAW
5236                    // ---------------------------------------------------------------------
5237                    //
5238                    // check if the raw file already exist
5239                    //
5240                    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
5241    //              oss.str("");
5242    //              oss << "SELECT ID FROM GL_RAW where NAME=\"" << gSystem->BaseName(raw.Data()) <<"\";";
5243    //              if ( IsDebug() ) cout << oss.str().c_str() << endl;
5244                    
5245    //              result = conn->Query(oss.str().c_str());
5246    //              if ( !result ) throw -4;;
5247    //              if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5248    //              if( result->GetRowCount() == 0){
5249    //                  if ( IsDebug() ) cout << " << Insert new RAW file >> "<<endl;
5250    //                  // - - - - - - - - - - -
5251    //                  // insert new raw file
5252    //                  // - - - - - - - - - - -
5253    //                  GL_RAW glraw = GL_RAW();    
5254    //                  glraw.PATH        = gSystem->DirName(raw.Data());
5255    //                  glraw.NAME        = gSystem->BaseName(raw.Data());
5256    //                  glraw.BOOT_NUMBER = boot_number;
5257    //                  //
5258    //                  insertPamelaRawFile( &glraw );
5259    //                  //              
5260    //                  id_raw = glraw.ID;              
5261    //              }else{
5262    //                  row = result->Next();
5263    //                  id_raw = (UInt_t)atoll(row->GetField(0));
5264    //              }
5265    //              if ( IsDebug() ) cout << "ID_RAW = "<<id_raw<<endl;
5266    
5267                    // ---------------------------------------------------------------------
5268                    // step 1(bis): retrieve the timesync id associated to the file
5269                    // (NB, uso lo stesso associato al file iniziale)
5270                    // ---------------------------------------------------------------------
5271                    UInt_t idtimesync = 0;
5272                    oss.str("");
5273                    oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" limit 1;";
5274                    if ( debug ) printf(" %s \n",oss.str().c_str());
5275                    result = conn->Query(oss.str().c_str());
5276                    if ( !result ) throw -3;
5277                    row = result->Next();
5278                    if ( !row ) throw -3;
5279                    idtimesync = (UInt_t)atoll(row->GetField(0));
5280                    if ( IsDebug() ) cout << "ID_TIMESYNC = "<<idtimesync<<endl;
5281                    
5282                    // ---------------------------------------------------------------------
5283                    // step 2: insert a new root file in GL_ROOT
5284                    // ---------------------------------------------------------------------
5285                    //
5286                    // check if the root file already exist
5287                    //
5288                    UInt_t id_root = 0;
5289                    oss.str("");
5290                    oss << "SELECT ID FROM GL_ROOT where NAME=\"" << gSystem->BaseName(name.Data()) <<"\";";
5291                    if ( IsDebug() ) cout << oss.str().c_str() << endl;
5292                    
5293                    result = conn->Query(oss.str().c_str());
5294                    if ( !result ) throw -4;;
5295                    if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5296                    if( result->GetRowCount() == 0){
5297                        if ( IsDebug() ) cout << " << Insert new ROOT file >> "<<endl;
5298                        // - - - - - - - - - - -
5299                        // insert new root file
5300                        // - - - - - - - - - - -
5301                        GL_ROOT glroot = GL_ROOT();            
5302                        glroot.ID_RAW      = id_raw;
5303                        glroot.ID_TIMESYNC = idtimesync;
5304                        //
5305                        // 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,
5306                        //             NOT STATIC NOT KEEPENV = $PAM_L0 must be used in the DB
5307                        //
5308                        if ( STATIC ){
5309                          glroot.PATH        = (TString)gSystem->ExpandPathName(path);
5310                        } else {
5311                          if ( KEEPENV ){
5312                            glroot.PATH      = path;
5313                          } else {
5314                            glroot.PATH      = "$PAM_L0";
5315                          };
5316                        };
5317                        //              glroot.PATH        = path;
5318                        glroot.NAME        = name;
5319                        //
5320                        insertPamelaRootFile( &glroot );
5321                        //              
5322                        id_root = glroot.ID;                    
5323                    }else{
5324                        row = result->Next();
5325                        if(row)id_root = (UInt_t)atoll(row->GetField(0));
5326                    }
5327                    if ( IsDebug() ) cout << "ID_ROOT = "<<id_root<<endl;
5328    
5329                    // ---------------------------------------------------------------------
5330                    // step 3: modify time-tag of corrupted GL_TRK_CALIB entry
5331                    // ---------------------------------------------------------------------
5332                    if ( IsDebug() ) cout << " << Modify time-tag of calibration ID="<<id<<" >> "<<endl;
5333                    oss.str("");
5334                    oss << " UPDATE GL_TRK_CALIB SET "  
5335                        << " TO_TIME=0 , FROM_TIME=0  WHERE "
5336                        << " ID = "<< id  << ";";
5337                    if ( IsDebug() ) cout << oss.str().c_str() << endl;
5338                    result = conn->Query(oss.str().c_str());
5339                    if ( !result ) throw -4;;
5340    
5341                    // ---------------------------------------------------------------------
5342                    // step 4: insert the new calibration:
5343                    // ---------------------------------------------------------------------
5344                    if ( IsDebug() ) cout << " << Insert new TRK calibration >> "<<endl;
5345                    //
5346                    GL_TRK_CALIB glcal = GL_TRK_CALIB();        
5347                    //
5348                    glcal.ID_ROOT_L0        = id_root;
5349                    glcal.EV_ROOT_CALIBTRK1 = this_t1;
5350                    glcal.EV_ROOT_CALIBTRK2 = this_t2;
5351                    glcal.FROM_TIME         = fromtime;
5352                    glcal.TO_TIME           = totime;
5353                    glcal.OBT1              = obt1;
5354                    glcal.OBT2              = obt2;
5355                    glcal.PKT1              = pkt1;
5356                    glcal.PKT2              = pkt1;
5357                    glcal.BOOT_NUMBER       = GetBOOTnumber();
5358                    glcal.VALIDATION        = this_valid;
5359                    //
5360                    HandleTRK_CALIB(&glcal);
5361                    if ( IsDebug() ) cout << "ID = "<<glcal.ID<<endl;
5362                    //
5363                    
5364                }
5365                if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
5366    
5367            }while(1);//end loop over calibrations
5368            
5369            
5370            if( result )delete result;
5371            if( row    )delete row;
5372            
5373            
5374    
5375            
5376    
5377    
5378        }
5379    
5380    
5381    //      // ------------------------------
5382    //      // try to recover the calibration
5383    //      // ------------------------------
5384    //      cout << "TRY TO RECOVER TRACKER CALIBRATION"<<endl;
5385    //      //
5386    //      ULong64_t time  = 0; //absolute time
5387    //      string    path[100]; //mettere un limite massimo
5388    //      int       nrows = 0;
5389    //      UInt_t    pkt   = 0;
5390    //      UInt_t    obt   = 0;
5391    //      char     *type  = "";
5392    //      EventHeader *eh   = new EventHeader();
5393    //      CalibTrk1Event *c = new CalibTrk1Event();
5394            
5395    //       //
5396    //       if(which_is_not_valid==1 || which_is_not_valid==3){
5397    //        //
5398    //        cout << "PKT1 --> missing or corrupted "<<endl;
5399    //        type = "CalibTrk1";
5400    //        pkt  = pkt1;
5401    //        obt  = obt1;
5402    //        time = this->GetAbsTime(obt1);
5403    //        if( pkt1 == 0 ){//missing
5404    //            time = this->GetAbsTime(obt2);
5405    //            pkt  = pkt2-1;          
5406    //        }
5407    //        //
5408    //       }else if (which_is_not_valid==2 || which_is_not_valid==3){
5409    //        //
5410    //        cout << "PKT2--> missing or corrupted "<<endl;
5411    //        type = "CalibTrk2 ";
5412    //        pkt  = pkt2;
5413    //        obt  = obt2;
5414    //        time = this->GetAbsTime(obt2);
5415    //        if( pkt2 == 0 ){//missing
5416    //            time = this->GetAbsTime(obt1);
5417    //            pkt  = pkt1+1;          
5418    //        }
5419    //        //
5420    //       }else{
5421    //        cout << "this should not happen!!! "<<endl;
5422    //        trow -666;
5423    //       }
5424          
5425    //       nrows = Query_ROOT_TABLE(time,conn,path);// get the list of file which might contain the packet
5426          
5427    
5428    //       for(int r=0; r<nrows; r++){ //loop over rows
5429    //        if(path)cout << r << " >>>> "<<(path+r)->c_str() << endl;
5430    //        /// verifica che il file non sia quello gia` aperto
5431    //       }
5432    
5433    //       ////////////////////////////////////////////////////////////////////////
5434    
5435    //       TSQLResult *result = 0;
5436    //       TSQLRow    *row    = 0;
5437    //       //
5438    //       stringstream oss;
5439    //       oss.str("");
5440    //       // ----------------------------------------
5441    //       // read the id of last calibration inserted
5442    //       // ----------------------------------------
5443    //       oss.str("");
5444    //       oss << " SELECT ";
5445    //       oss << " (ID,ID_ROOT_L0,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,FROM_TIME,TO_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION) ";
5446    //       oss << " ORDER BY ID DESC LIMIT 1; ";
5447          
5448    //       result = conn->Query(oss.str().c_str());
5449    //       row = result->Next();
5450    //       if( !row )throw -666;
5451    
5452    //       if( result )delete result;
5453    //       if( row    )delete row;
5454    
5455    //       UInt_t id = (UInt_t)atoll(row->GetField(0));
5456    
5457    //       // -------------------------------------
5458    //       // ...and modify it with new parameters
5459    //       // -------------------------------------
5460          
5461    
5462    //   }
5463    //    //
5464    return(0);    return(0);
5465  };  };
# Line 5061  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 5762  Int_t PamelaDBOperations::CleanGL_RUN_FR
5762                    << " RM_ACQ_SETTING_MODE=" << glrun->GetRM_ACQ_SETTING_MODE()<< " , "                      << " RM_ACQ_SETTING_MODE=" << glrun->GetRM_ACQ_SETTING_MODE()<< " , "  
5763                    << " TRK_CALIB_USED=" << glrun->GetTRK_CALIB_USED()<< " , "                      << " TRK_CALIB_USED=" << glrun->GetTRK_CALIB_USED()<< " , "  
5764                    << " CAL_DSP_MASK=" << glrun->GetCAL_DSP_MASK()<< " , "                      << " CAL_DSP_MASK=" << glrun->GetCAL_DSP_MASK()<< " , "  
5765                    << " LAST_TIMESYNC=" << glrun->GetLAST_TIMESYNC()<< " , "                      << " LAST_TIMESYNC=" << glrun->GetLAST_TIMESYNC()<< " , ";
5766                    << " OBT_TIMESYNC=" << glrun->GetOBT_TIMESYNC()                //
5767                    << " WHERE ID=" << myid[u] << ";";                if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
5768                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12() << " , ";
5769                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
5770                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC() << " , ";
5771                  //              
5772                  oss << " OBT_TIMESYNC=" << glrun->GetOBT_TIMESYNC();
5773                  oss << " WHERE ID=" << myid[u] << ";";
5774                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
5775              };              };
5776              //              //
# Line 5074  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 5781  Int_t PamelaDBOperations::CleanGL_RUN_FR
5781              for (UInt_t u=1; u <= nid ; u++){              for (UInt_t u=1; u <= nid ; u++){
5782                oss.str("");                oss.str("");
5783                oss << "UPDATE GL_RUN_FRAGMENTS SET "                oss << "UPDATE GL_RUN_FRAGMENTS SET "
5784                    << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , "                    << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , ";
5785                    << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "                //
5786                  if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
5787                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , ";
5788                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
5789                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , ";
5790                  //              
5791                  oss << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "
5792                    << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT()<< ";";                    << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT()<< ";";
5793                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
5794              };                  };    
# Line 5098  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 5811  Int_t PamelaDBOperations::CleanGL_RUN_FR
5811                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
5812                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "
5813                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< " , "                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< " , "
5814                    << " PKT_COUNTER=" << glrun->GetPKT_COUNTER()<< " , "                    << " PKT_COUNTER=" << glrun->GetPKT_COUNTER()<< " , ";
5815                    << " PKT_READY_COUNTER=" << glrun->GetPKT_READY_COUNTER()                //
5816                  if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
5817                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
5818                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) {
5819                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
5820                  //              
5821                  oss << " PKT_READY_COUNTER=" << glrun->GetPKT_READY_COUNTER()
5822                    << " WHERE ID=" << myid[u] << ";";                    << " WHERE ID=" << myid[u] << ";";
5823                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
5824              };              };
# Line 5112  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 5831  Int_t PamelaDBOperations::CleanGL_RUN_FR
5831                oss.str("");                oss.str("");
5832                oss << "UPDATE GL_RUN_FRAGMENTS SET "                oss << "UPDATE GL_RUN_FRAGMENTS SET "
5833                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
5834                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , ";
5835                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< ";";                //
5836                  if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
5837                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
5838                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ){
5839                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
5840                  //              
5841                  oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< ";";
5842                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
5843              };                  };    
5844            };            };
# Line 5272  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 5997  Int_t PamelaDBOperations::CleanGL_RUN_FR
5997          glrun->SetID_RUN_FRAG(glrun->GetID());          glrun->SetID_RUN_FRAG(glrun->GetID());
5998          glrun->Fill_GL_RUN(conn);            glrun->Fill_GL_RUN(conn);  
5999          //          //
6000  //      oss.str("");          //      oss.str("");
6001  //      oss << " SELECT ID FROM GL_RUN WHERE "          //      oss << " SELECT ID FROM GL_RUN WHERE "
6002  //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "          //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
6003  //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "          //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
6004  //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "          //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
6005  //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "          //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
6006  //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";          //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
6007  //      //          //      //
6008  //      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());
6009  //      result2 = conn->Query(oss.str().c_str());          //      result2 = conn->Query(oss.str().c_str());
6010  //      //          //      //
6011  //      if ( !result2 ) throw -4;          //      if ( !result2 ) throw -4;
6012  //      //          //      //
6013  //      row2 = result2->Next();          //      row2 = result2->Next();
6014  //      //          //      //
6015  //      if ( !row2 ) throw -25;          //      if ( !row2 ) throw -25;
6016  //      //          //      //
6017  //      oss.str("");          //      oss.str("");
6018  //      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);
6019  //      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());
6020  //      result2 = conn->Query(oss.str().c_str());          //      result2 = conn->Query(oss.str().c_str());
6021  //      //          //      //
6022  //      if ( !result2 ) throw -4;          //      if ( !result2 ) throw -4;
6023          //          //
6024          moved++;          moved++;
6025          //          //
# Line 5306  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6031  Int_t PamelaDBOperations::CleanGL_RUN_FR
6031        //        //
6032        //        //
6033        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
6034  //      oss.str("");        //      oss.str("");
6035  //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);        //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);
6036  //       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());
6037  //       result2 = conn->Query(oss.str().c_str());        //       result2 = conn->Query(oss.str().c_str());
6038  //      //        //      //
6039  //      if ( !result2 ) throw -4;        //      if ( !result2 ) throw -4;
6040  //      //        //      //
6041        row = result->Next();        row = result->Next();
6042      };      };
6043    };    };
# Line 5366  Int_t PamelaDBOperations::ValidateRuns(T Line 6091  Int_t PamelaDBOperations::ValidateRuns(T
6091      // 2) get the OBT of the last validated run      // 2) get the OBT of the last validated run
6092      // --------------------------------------------------------------      // --------------------------------------------------------------
6093      oss.str("");      oss.str("");
6094      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
6095        oss << " SELECT * FROM GL_RUN  WHERE VALIDATION>0 AND RUNHEADER_TIME<="<< t_start
6096          <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";          <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
6097      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());
6098      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
# Line 5457  Int_t PamelaDBOperations::ValidateRuns(T Line 6183  Int_t PamelaDBOperations::ValidateRuns(T
6183    GL_RUN* this_run = new GL_RUN();    GL_RUN* this_run = new GL_RUN();
6184    GL_RUN* next_run = new GL_RUN();    GL_RUN* next_run = new GL_RUN();
6185    Int_t   nseq_max = 1000;    Int_t   nseq_max = 1000;
6186  //  UInt_t* sequence = new UInt_t[100];    //  UInt_t* sequence = new UInt_t[100];
6187    vector<UInt_t> sequence(nseq_max);    vector<UInt_t> sequence(nseq_max);
6188    Int_t   nseq = 0;    Int_t   nseq = 0;
6189    Bool_t CHECK = false;    Bool_t CHECK = false;
# Line 5472  Int_t PamelaDBOperations::ValidateRuns(T Line 6198  Int_t PamelaDBOperations::ValidateRuns(T
6198    // ---------------------------------------------------------------------------------    // ---------------------------------------------------------------------------------
6199    while(1){    while(1){
6200                        
6201            row = result->Next();      row = result->Next();
6202            if( row == NULL ) break;      if( row == NULL ) break;
6203                        
6204            //------------      //------------
6205            //get run info      //get run info
6206            //------------      //------------
6207            this_run->Set_GL_RUN(row);      this_run->Set_GL_RUN(row);
6208                                        
6209            Bool_t this_BAD = false;      Bool_t this_BAD = false;
6210            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;
6211            else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;      else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;
6212            else{      else{
6213  //                printf("Missing or corrupted header!! \n");        //                  printf("Missing or corrupted header!! \n");
6214                    this_ONLINE = false;        this_ONLINE = false;
6215                    this_BAD = true;        this_BAD = true;
6216            };      };
6217    
6218            //-----------------------------------      //-----------------------------------
6219            //compare with previous(next in time)      //compare with previous(next in time)
6220            //-----------------------------------      //-----------------------------------
6221            CHECK = false;      CHECK = false;
6222            UInt_t interval=0;      UInt_t interval=0;
6223                        
6224            if( nrow != 0){      if( nrow != 0){
6225                    
6226                                        
6227                    t1 = this_run->GetRUNTRAILER_TIME();        t1 = this_run->GetRUNTRAILER_TIME();
6228                    t2 = next_run->GetRUNHEADER_TIME();        t2 = next_run->GetRUNHEADER_TIME();
6229                    interval = (t2-t1);        interval = (t2-t1);
6230                                        
6231                    if(this_ONLINE && next_ONLINE){                               // this: ON-LINE + next: ON-LINE        if(this_ONLINE && next_ONLINE){                           // this: ON-LINE + next: ON-LINE
6232                                                        
6233                            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
6234                                                        
6235                            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
6236                                                        
6237                            if( !CHECK && this_run->VALIDATION ){          if( !CHECK && this_run->VALIDATION ){
6238                                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);            //      for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
6239                                    nseq=0;            for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],this_run->VALIDATION);
6240                            }            nseq=0;
6241            }
6242                                        
6243                    }else if( !this_ONLINE && next_ONLINE) {              // this: DEFAULT + next:ON-LINE        }else if( !this_ONLINE && next_ONLINE) {          // this: DEFAULT + next:ON-LINE
6244                                                        
6245                            CHECK = true;          CHECK = true;
6246    
6247                    }else if( !next_ONLINE ){                                             // this:ANY + next:DEFAULT        }else if( !next_ONLINE ){                                         // this:ANY + next:DEFAULT
6248                                                        
6249                            assignVALIDATION(next_run->ID,true);          assignVALIDATION(next_run->ID,true);
6250                            nseq=0;          nseq=0;
6251                    }        }
6252            }      }
6253    
6254            //----------------------------      //----------------------------
6255            //check run sequence for calib      //check run sequence for calib
6256            //----------------------------      //----------------------------
6257            if( CHECK ){      if( CHECK ){
6258                    // check if calibration exists        // check if calibration exists
6259                    if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);        if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);
6260                    Bool_t MISSING = MissingTRK_CALIB(t1,t2);        //      Bool_t MISSING = MissingTRK_CALIB(t1,t2);
6261                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],!MISSING);        UInt_t MISSING = MissingTRK_CALIB(t1,t2);
6262                    nseq=0;        UInt_t val = 0;
6263            };        if ( MISSING == 1 ) val = 0;
6264            //--------------        if ( MISSING == 0 ) val = 1;
6265            //store run info        if ( MISSING == 2 ) val = 2;
6266            //--------------        for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],val);
6267            *next_run   = *this_run;        nseq=0;
6268            next_ONLINE = this_ONLINE;      };
6269            if( !this_BAD ){      //--------------
6270                    if(nseq < nseq_max){      //store run info
6271                            sequence[nseq] = this_run->ID;      //--------------
6272                            nseq++;      *next_run   = *this_run;
6273                    }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);      next_ONLINE = this_ONLINE;
6274            };      if( !this_BAD ){
6275          if(nseq < nseq_max){
6276            sequence[nseq] = this_run->ID;
6277            nseq++;
6278          }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);
6279        };
6280                        
6281            if ( IsDebug() ) printf("%i Run %u \n",nrow,this_run->ID);      if ( IsDebug() ) printf("%i Run %u \n",nrow,this_run->ID);
6282            nrow++;      nrow++;
6283                        
6284    };    };
6285    delete this_run;    delete this_run;
# Line 5561  Int_t PamelaDBOperations::ValidateRuns(T Line 6293  Int_t PamelaDBOperations::ValidateRuns(T
6293   * @param t2 To absolute time   * @param t2 To absolute time
6294   * @return true if there might be a missing calibration   * @return true if there might be a missing calibration
6295   */   */
6296  Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){  //Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
6297    UInt_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
6298                    
6299          GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();    GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();
6300                    
6301          // get the closest VALIDATED calibration before the run start (t2)    // get the closest calibration before the run start (t2)
6302          if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true);      //>>> missing    //  if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true);        //>>> missing
6303      if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(1);       //>>> missing
6304                    
6305          if ( trkcalib->TO_TIME  < t2 ) return(true);                                    //>>> missing    //  if ( trkcalib->TO_TIME  < t2 ) return(true);                                      //>>> missing
6306      if ( trkcalib->TO_TIME  < t2 ) return(1);                                     //>>> missing
6307                    
6308          //==============================================================    //==============================================================
6309          // Check is done first on the basis of time between calibration,    // Check is done first on the basis of time between calibration,
6310          // which should be equal to the time between ascending-nodes.    // which should be equal to the time between ascending-nodes.
6311          //==============================================================    //==============================================================
6312          if ( t2 - trkcalib->FROM_TIME > 5700) {    if ( t2 - trkcalib->FROM_TIME > 5700) {
6313                  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);
6314          //==============================================================      //==============================================================
6315          // there might be a missing calibration, due to:      // there might be a missing calibration, due to:
6316          // - MM full      // - MM full
6317          // - corrupted packets      // - corrupted packets
6318          // - loss of data      // - loss of data
6319          // 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
6320          //==============================================================      //==============================================================
6321                  Bool_t DOWNLOAD = false;      Bool_t DOWNLOAD = false;
6322                  // check if the calib was skipped becouse of download .... DA FARE!!      // check if the calib was skipped becouse of download .... DA FARE!!
6323                  if(DOWNLOAD)return(false);      //    if(DOWNLOAD)return(false);
6324        if(DOWNLOAD)return(0);
6325                                    
6326                  return(true);                                   //>>> missing      //    return(true);                                         //>>> missing
6327        return(1);                                  //>>> missing
6328                                    
6329          };    };
6330                    
6331          //==============================================================    //==============================================================
6332          // 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,
6333          // it is enough to say that there are no missing calibrations    // it is enough to say that there are no missing calibrations
6334          //==============================================================    //==============================================================
6335          // the long time interval bewteen runs might be due to download    // the long time interval bewteen runs might be due to download
6336          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);
6337          return(false);    if ( trkcalib->VALIDATION ) return(0);
6338      if ( IsDebug() )printf("Calibration is not validated... :-/ ==> OK but with VALIDATION=2! \n");
6339      return(2);
6340                    
6341  };  };
6342  /**  /**
# Line 5606  Bool_t PamelaDBOperations::MissingTRK_CA Line 6345  Bool_t PamelaDBOperations::MissingTRK_CA
6345   * @param validation true/false   * @param validation true/false
6346   */   */
6347  Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){  Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){
6348          TSQLResult *result = 0;    return(this->assignVALIDATION(idrun,(UInt_t)validation));
6349          stringstream oss;  }
6350          oss.str("");  
6351          oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";  Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, UInt_t validation){
6352          //    TSQLResult *result = 0;
6353  //      if ( IsDebug() )    stringstream oss;
6354  //      printf(" Set VALIDATION = %i for run %i \n",validation,idrun);    oss.str("");
6355          if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());    oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";
6356          result = conn->Query(oss.str().c_str());    //
6357          if ( !result ) throw -4;    //    if ( IsDebug() )
6358          return(0);    //    printf(" Set VALIDATION = %i for run %i \n",validation,idrun);
6359      if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());
6360      result = conn->Query(oss.str().c_str());
6361      if ( !result ) throw -4;
6362      return(0);
6363  }  }
6364    
6365    
# Line 5802  Int_t PamelaDBOperations::removeFile(TSt Line 6545  Int_t PamelaDBOperations::removeFile(TSt
6545    stringstream myquery;    stringstream myquery;
6546    //      //  
6547    myquery.str("");    myquery.str("");
6548    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() <<"';";
6549    //    //
6550    pResult = conn->Query(myquery.str().c_str());    pResult = conn->Query(myquery.str().c_str());
6551    //    //
# Line 5818  Int_t PamelaDBOperations::removeFile(TSt Line 6561  Int_t PamelaDBOperations::removeFile(TSt
6561    //    //
6562    this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));    this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));
6563    this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));    this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));
6564      UInt_t idtsy=(UInt_t)atoll(Row->GetField(2));
6565    //    //
6566    this->ValidationOFF();    this->ValidationOFF();
6567    //    //
# Line 5825  Int_t PamelaDBOperations::removeFile(TSt Line 6569  Int_t PamelaDBOperations::removeFile(TSt
6569    //    //
6570    this->RemoveRUNS();    this->RemoveRUNS();
6571    //    //
6572    this->RemoveFILES();    this->RemoveFILES(idtsy);
6573    //    //
6574    this->SetID_ROOT(0);    this->SetID_ROOT(0);
6575    this->SetID_RAW(0);    this->SetID_RAW(0);
# Line 6045  void PamelaDBOperations::RemoveRUNS(){ Line 6789  void PamelaDBOperations::RemoveRUNS(){
6789   * Rearrange calibration tables   * Rearrange calibration tables
6790   *   *
6791   **/   **/
6792  void PamelaDBOperations::RemoveFILES(){  void PamelaDBOperations::RemoveFILES(UInt_t idtsy){
6793    stringstream myquery;    stringstream myquery;
6794    //    //
6795    myquery.str("");    myquery.str("");
# Line 6055  void PamelaDBOperations::RemoveFILES(){ Line 6799  void PamelaDBOperations::RemoveFILES(){
6799    //    //
6800    conn->Query(myquery.str().c_str());    conn->Query(myquery.str().c_str());
6801    //    //
6802      myquery.str("");
6803      myquery << " DELETE FROM GL_ROOT WHERE ID=" <<this->GetID_ROOT() <<";";
6804      //
6805      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
6806      //
6807      conn->Query(myquery.str().c_str());  //
6808      //
6809      if ( !chewbacca ){
6810        myquery.str("");
6811        myquery << " DELETE FROM GL_TIMESYNC WHERE ID=" << idtsy <<";";
6812        //
6813        if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
6814        //
6815        conn->Query(myquery.str().c_str());
6816      };
6817      //
6818  };  };
6819    
6820  /**  /**
# Line 6259  void PamelaDBOperations::RemoveCALIBS(){ Line 7019  void PamelaDBOperations::RemoveCALIBS(){
7019   * Rearrange calibration tables   * Rearrange calibration tables
7020   *   *
7021   **/   **/
7022  UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh ){  UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh , TFile *file){
7023    
7024        if(!caltrk) return 0;
7025    
7026        if ( IsDebug() ) cout << "ValidateTrkCalib:"<<endl;
7027    
7028        UInt_t validate = 1;
7029      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};
7030      UInt_t timeaftercalib=120000; //2000;      UInt_t timeaftercalib=120000; //2000;
7031  //  ----------      TString classname = caltrk->GetName();
7032  //  Check CRCs  
7033  //  ----------  //  ----------------------------------
7034    //  Check CRCs and failed calibrations
7035    //  ----------------------------------
7036      for(Int_t ipkt=0; ipkt<6; ipkt++){      for(Int_t ipkt=0; ipkt<6; ipkt++){
7037          if( caltrk->crc_hcal[ipkt] )return 0; // :-(          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
7038          for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] )return 0; // :-(              if( caltrk->crc_hcal[ipkt] ){
7039    //              if(IsDebug())cout<<"(CRC Header)";
7040                    validate = 0;
7041                    if(IsDebug())cout <<endl<<" *** CRC *** (header DSPn "<<caltrk->DSPnumber[ipkt]<<")";
7042            
7043                }
7044                for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] ){
7045    //              if(IsDebug())cout<<"(CRC Pkt-"<<ilad<<")";
7046                    if(IsDebug())cout <<endl<<" *** CRC *** (data DSPn "<<caltrk->DSPnumber[ipkt]<<" ladder "<<ilad<<")";
7047                    validate = 0;
7048                }
7049                if( !(caltrk->ncalib_event[ipkt]==0 && caltrk->cal_flag[ipkt]==0) ){
7050                    if(IsDebug())cout <<endl<<" *** FAILURE ***     (data DSPn "<<caltrk->DSPnumber[ipkt]<<")";
7051                    validate = 0;
7052                }
7053            }else{
7054    //          validate=0;
7055                if(IsDebug())cout <<endl<<" *** DSPn *** ("<< caltrk->DSPnumber[ipkt] <<" @pkt "<<ipkt<<")";
7056            }
7057      }      }
7058    
7059  //  -----------------------  //  -----------------------
7060  //  Check missing packets:  //  Check missing packets:
7061  //  -----------------------  //  -----------------------
# Line 6295  UInt_t PamelaDBOperations::ValidateTrkCa Line 7081  UInt_t PamelaDBOperations::ValidateTrkCa
7081  //  Check if it is first or second calibration packet  //  Check if it is first or second calibration packet
7082  //  -------------------------------------------------  //  -------------------------------------------------
7083      UInt_t build=0;      UInt_t build=0;
     TString classname = caltrk->GetName();  
7084      UInt_t base=0;      UInt_t base=0;
7085      UInt_t mask=0;      UInt_t mask=0;
7086      if(classname.Contains("CalibTrk1Event")){      if(classname.Contains("CalibTrk1Event")){
# Line 6306  UInt_t PamelaDBOperations::ValidateTrkCa Line 7091  UInt_t PamelaDBOperations::ValidateTrkCa
7091          base=18;          base=18;
7092          mask=0xFC0000;          mask=0xFC0000;
7093      }      }
7094  //  -------------------------------------------------  //  ----------------------------------------------------
7095  //  Count number of packets and set build variable  //  Count number of valid packets and set build variable
7096  //  -------------------------------------------------  //  ----------------------------------------------------
7097        if(IsDebug())cout <<endl<< " DSP: ";
7098      Int_t  npkts=0;      Int_t  npkts=0;
7099      for(Int_t ipkt=0; ipkt<6; ipkt++){      for(Int_t ipkt=0; ipkt<6; ipkt++){
7100          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
7101                if(IsDebug())cout <<" "<<caltrk->DSPnumber[ipkt];
7102              npkts++;              npkts++;
7103              build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );              build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );
7104          }  //          cout << caltrk->DSPnumber[ipkt]
7105            };
7106      }      }
7107  //    if( npkts==6 )return 1; // :-)      if(IsDebug())cout << " ==> "<< hex << build << dec;
7108    //  ----------------------------------------------------
7109  //    cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime()<<endl;  //  If the number of valid packets is 6, ok exit...
7110    //  ----------------------------------------------------
7111  //  -----------------------------------------------      if( npkts==6 ){
7112  //  If missing packets: check the acq configuration          return validate; // exit
7113        }
7114    ////////////////////////////////////////////////////////
7115    //  ...otherwise there might be some missing packets
7116    //
7117    //  In this case check the acq configuration
7118  //  (some DSPs might be excluded from acquisition)  //  (some DSPs might be excluded from acquisition)
7119  //  -----------------------------------------------  ////////////////////////////////////////////////////////
7120    
7121        if(!eh || !file || (file&&file->IsZombie()) ){
7122            if ( IsDebug() )cout << " *** MISSING VIEW *** eh="<<eh<<" file="<<file<<" cannot validate"<<endl;
7123            return (0);
7124        }
7125        
7126  //  -----------------------------------------------  //  -----------------------------------------------
7127  //  retrieve the first run header after calib  //  retrieve the first run header after calib
7128  //  -----------------------------------------------  //  -----------------------------------------------
7129       PacketType *pctp;      
7130       EventCounter *cod;      PacketType *pctp;
7131       cod = eh->GetCounter();      EventCounter *cod;
7132       Int_t irun = cod->Get(pctp->RunHeader);      cod = eh->GetCounter();
7133       TTree *rh=(TTree*)file->Get("RunHeader");      Int_t irun = cod->Get(pctp->RunHeader);
7134       if ( !rh || rh->IsZombie() ) throw -17;      TTree *rh=(TTree*)file->Get("RunHeader");
7135       if( rh->GetEntries() == irun ){      if ( !rh || rh->IsZombie() ) throw -17;
7136            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (1)  -- cannot validate :-( "<<endl;      if( rh->GetEntries() <= irun ){
7137           return 0; // :-(          if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (1) -- cannot validate :-( "<<endl;
7138       }          return 0; // :-(
7139        }
7140       RunHeaderEvent *run  = 0;      RunHeaderEvent *run  = 0;
7141       EventHeader    *hrun = 0;      EventHeader    *hrun = 0;
7142       rh->SetBranchAddress("RunHeader", &run);      rh->SetBranchAddress("RunHeader", &run);
7143       rh->SetBranchAddress("Header", &hrun);      rh->SetBranchAddress("Header", &hrun);
7144       rh->GetEntry(irun);      rh->GetEntry(irun);    
7145  //     cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime() << " Run " << hrun->GetPscuHeader()->GetOrbitalTime() <<endl;      if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){
7146            if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (2) -- cannot validate :-( "<<endl;
7147       if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){          return 0; // :-(
7148            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (2) -- cannot validate :-( "<<endl;      }
7149           return 0; // :-(  
7150       }      UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());
7151            if( dtime > timeaftercalib ){
7152       if( !run->RM_ACQ_AFTER_CALIB ){          if ( IsDebug() ) cout << " *** MISSING-PKT *** run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;
7153            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) RM_ACQ_AFTER_CALIB=0    -- cannot validate :-( "<<endl;          return 0; // :-(
7154           return 0; // :-(      }
7155       }  
7156        if ( IsDebug() ) cout <<endl<< " ACQ_BUILD_INFO ==> "<<hex<<(run->ACQ_BUILD_INFO & mask)<<dec;
7157       UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());  
7158       if( dtime > timeaftercalib ){      if( (run->ACQ_BUILD_INFO & mask) != build ){
7159           if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;          validate=0; // :-(
7160           return 0; // :-(          cout <<endl<< " *** MISSING-PKT *** packet mismatch: ACQ_BUILD_INFO="<<hex<<(run->ACQ_BUILD_INFO&mask)<<" != "<<build<<dec;
7161       }      };
7162        
7163        return validate;
7164    
      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; // :-)  
7165    
7166  }  }
7167    
# Line 6378  UInt_t PamelaDBOperations::ValidateTrkCa Line 7171  UInt_t PamelaDBOperations::ValidateTrkCa
7171   *   *
7172   **/   **/
7173  UInt_t PamelaDBOperations::Check(){  UInt_t PamelaDBOperations::Check(){
7174          return(this->Check(0,0));    return(this->Check(0,0));
7175  }  }
7176    
7177  UInt_t PamelaDBOperations::Check(UInt_t from, UInt_t to){  UInt_t PamelaDBOperations::Check(UInt_t from, UInt_t to){
7178    //    //
7179          if ( IsDebug() ) printf(" from %u to %u \n",from,to);    if ( IsDebug() ) printf(" from %u to %u \n",from,to);
7180    //    //
7181    UInt_t test = 0;    UInt_t test = 0;
7182    //    //
# Line 6424  UInt_t PamelaDBOperations::Check(UInt_t Line 7217  UInt_t PamelaDBOperations::Check(UInt_t
7217      //      //
7218      if ( from > 0 && nid <= from ) goto ss;      if ( from > 0 && nid <= from ) goto ss;
7219      if ( to > 0 && nid >= to ) goto ss;      if ( to > 0 && nid >= to ) goto ss;
7220  //      //
7221      if ( (UInt_t)atoll(row->GetField(4)) > 1 ){      if ( (UInt_t)atoll(row->GetField(4)) > 1 ){
7222        //        //
7223        //        //
# Line 6455  UInt_t PamelaDBOperations::Check(UInt_t Line 7248  UInt_t PamelaDBOperations::Check(UInt_t
7248              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)));  
7249              row3 = result3->Next();              row3 = result3->Next();
7250            };            };
7251  //      delete result3;            //    delete result3;
7252    
7253          };          };
7254          //          //
# Line 6476  UInt_t PamelaDBOperations::Check(UInt_t Line 7269  UInt_t PamelaDBOperations::Check(UInt_t
7269              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)));
7270              row3 = result3->Next();              row3 = result3->Next();
7271            };            };
7272  //      delete result3;            //    delete result3;
7273          };          };
7274          //          //
7275          oss.str("");          oss.str("");
# Line 6496  UInt_t PamelaDBOperations::Check(UInt_t Line 7289  UInt_t PamelaDBOperations::Check(UInt_t
7289              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)));
7290              row3 = result3->Next();              row3 = result3->Next();
7291            };            };
7292   //     delete result3;            //    delete result3;
7293    
7294          };          };
7295        };        };
# Line 6517  UInt_t PamelaDBOperations::Check(UInt_t Line 7310  UInt_t PamelaDBOperations::Check(UInt_t
7310            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)));
7311            row3 = result3->Next();            row3 = result3->Next();
7312          };          };
7313  //      delete result3;          //      delete result3;
7314        };        };
7315        //        //
7316      };      };
# Line 6543  UInt_t PamelaDBOperations::Check(UInt_t Line 7336  UInt_t PamelaDBOperations::Check(UInt_t
7336        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
7337        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7338        test = 1;        test = 1;
7339  //      delete result2;        //        delete result2;
7340      };      };
7341      //      //
7342      if ( (thisrtt < prevrht) && (thisrht != prevrht) ){      if ( (thisrtt < prevrht) && (thisrht != prevrht) ){
# Line 6565  UInt_t PamelaDBOperations::Check(UInt_t Line 7358  UInt_t PamelaDBOperations::Check(UInt_t
7358        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
7359        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7360        test = 1;        test = 1;
7361  //      delete result2;        //        delete result2;
7362      };      };
7363      //      //
7364      if ( (thisrht > thisrtt) && (thisrht != prevrht) ){      if ( (thisrht > thisrtt) && (thisrht != prevrht) ){
# Line 6587  UInt_t PamelaDBOperations::Check(UInt_t Line 7380  UInt_t PamelaDBOperations::Check(UInt_t
7380        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
7381        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7382        test = 1;        test = 1;
7383  //      delete result2;        //        delete result2;
7384      };      };
7385  ss:    ss:
7386      //      //
7387      prevrht = thisrht;      prevrht = thisrht;
7388      prevrtt = thisrtt;      prevrtt = thisrtt;
7389      previd = thisid;      previd = thisid;
7390      prevl0id = thisl0id;      prevl0id = thisl0id;
7391      row = result->Next();      row = result->Next();
7392  //    if ( result2 ) delete result2;      //    if ( result2 ) delete result2;
7393  //    if ( result3 ) delete result3;      //    if ( result3 ) delete result3;
7394    };    };
7395    //    //
7396    return(test);    return(test);

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

  ViewVC Help
Powered by ViewVC 1.1.23