/[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.6 by mocchiut, Tue Nov 4 10:48:38 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 138  void PamelaDBOperations::OpenL0File(TStr Line 140  void PamelaDBOperations::OpenL0File(TStr
140        TString chfile;        TString chfile;
141        UInt_t ridn = 0;        UInt_t ridn = 0;
142        qu.str("");        qu.str("");
143        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 << ";";
144        if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());        if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
145        result = conn->Query(qu.str().c_str());        result = conn->Query(qu.str().c_str());
146        if ( result ){        if ( result ){
# Line 149  void PamelaDBOperations::OpenL0File(TStr Line 151  void PamelaDBOperations::OpenL0File(TStr
151            chpktmax = (UInt_t)atoll(row->GetField(2));            chpktmax = (UInt_t)atoll(row->GetField(2));
152            chobtmin = (UInt_t)atoll(row->GetField(3));            chobtmin = (UInt_t)atoll(row->GetField(3));
153            chobtmax = (UInt_t)atoll(row->GetField(4));            chobtmax = (UInt_t)atoll(row->GetField(4));
154              chiby = (TString)(row->GetField(5));
155          } else {          } else {
156            throw -84;            throw -84;
157          };          };
# Line 163  void PamelaDBOperations::OpenL0File(TStr Line 166  void PamelaDBOperations::OpenL0File(TStr
166        if ( result2 ){        if ( result2 ){
167          row2 = result2->Next();          row2 = result2->Next();
168          if ( row2 ){          if ( row2 ){
169            chpath = (TString)gSystem->ExpandPathName(row2->GetField(0))+'/';            if ( KEEPENV ){
170                chpath = (TString)(row2->GetField(0))+'/';
171              } else {
172                chpath = (TString)gSystem->ExpandPathName(row2->GetField(0))+'/';
173              };
174            chfile = (TString)(row2->GetField(1));            chfile = (TString)(row2->GetField(1));
175            chobtts = (UInt_t)atoll(row2->GetField(2));            chobtts = (UInt_t)atoll(row2->GetField(2));
176            chlastts = (UInt_t)atoll(row2->GetField(3));            chlastts = (UInt_t)atoll(row2->GetField(3));
# Line 435  TString PamelaDBOperations::GetRawPath() Line 442  TString PamelaDBOperations::GetRawPath()
442    
443  TString PamelaDBOperations::GetRootPath(){  TString PamelaDBOperations::GetRootPath(){
444    if ( STATIC ){    if ( STATIC ){
445      return((TString)gSystem->DirName(filerootname.Data())+'/');      return((TString)gSystem->DirName(this->GetRootName().Data())+'/');
446    } else {    } else {    
447      return((TString)gSystem->ExpandPathName("$PAM_L0")+'/');      if ( KEEPENV ){
448          return((TString)gSystem->ExpandPathName(gSystem->DirName(filerootname.Data()))+'/');
449        } else {
450          return((TString)gSystem->ExpandPathName("$PAM_L0")+'/');
451        };
452    };    };
453  };  };
454    
# Line 490  void PamelaDBOperations::SetCommonGLRUN( Line 501  void PamelaDBOperations::SetCommonGLRUN(
501  };  };
502    
503  /**  /**
504     *
505     * Set the variables which belogns to physendrun tree
506     *
507     */
508    void PamelaDBOperations::SetPhysEndRunVariables(){
509      //
510      //
511      //
512      TTree *T = 0;
513      T = (TTree*)file->Get("PhysEndRun");
514      if ( !T || T->IsZombie() ) throw -90;
515      //
516      PhysEndRunEvent *pher= 0;
517      EventHeader *eh = 0;
518      T->SetBranchAddress("PhysEndRun", &pher);
519      T->SetBranchAddress("Header", &eh);
520      //
521      UInt_t phobt = 0;
522      UInt_t phpkt = 0;
523      //
524      glrun->SetPHYSENDRUN_MASK_S3S2S12(0);
525      glrun->SetPHYSENDRUN_MASK_S11CRC(0);
526      //
527      for (Int_t p=0; p<T->GetEntries(); p++){
528        //
529        T->GetEntry(p);
530        //
531        phobt = (UInt_t)eh->GetPscuHeader()->GetOrbitalTime();
532        phpkt = (UInt_t)eh->GetPscuHeader()->GetCounter();
533        //
534        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())  ){
535          if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() || glrun->GetPHYSENDRUN_MASK_S11CRC() ){
536            if ( IsDebug() ) printf(" WARNING while looping in physendrun: found two PhysEndRun packet for the same RUN! \n");
537            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);
538            if ( PEDANTIC && IsDebug() ) printf(" ERROR while looping in physendrun: found two PhysEndRun packet for the same RUN!\n ");
539            if ( PEDANTIC ) throw -91;
540          } else {
541            glrun->SetPHYSENDRUN_MASK_S3S2S12((UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S3S2S12);
542            glrun->SetPHYSENDRUN_MASK_S11CRC((UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S11CRC);
543          };
544        };
545      };
546      //
547    };
548    
549    /**
550   * Patch, look for upper limits to avoid processing retransmitted data   * Patch, look for upper limits to avoid processing retransmitted data
551   */   */
552  Int_t PamelaDBOperations::SetUpperLimits(){  Int_t PamelaDBOperations::SetUpperLimits(){
# Line 739  Int_t PamelaDBOperations::SetUpperLimits Line 796  Int_t PamelaDBOperations::SetUpperLimits
796    };    };
797    //    //
798    if ( chewbacca && nevent < 1 ) {    if ( chewbacca && nevent < 1 ) {
799          pktfirst = chpktmin;      pktfirst = chpktmin;
800          upperpkt = PKT(chpktmax);      upperpkt = PKT(chpktmax);
801          pktlast = chpktmax;      pktlast = chpktmax;
802          obtfirst = chobtmin;      obtfirst = chobtmin;
803          obtlast = chobtmax;      obtlast = chobtmax;
804          upperobt = OBT(chobtmax);      upperobt = OBT(chobtmax);
805    };    };
806    //    //
807    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 809  Int_t PamelaDBOperations::SetUpperLimits
809    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);
810    //    //
811    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)) ){
812          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));
813          if ( PEDANTIC ) throw -88;      if ( PEDANTIC ) throw -88;
814          return(32);      return(32);
815    };    };
816    //    //
817    if ( !nevent ) return(64);    if ( !nevent ) return(64);
# Line 1040  Int_t PamelaDBOperations::SetUpperLimits Line 1097  Int_t PamelaDBOperations::SetUpperLimits
1097          upperpkt = pkth;          upperpkt = pkth;
1098          upperobt = obth;          upperobt = obth;
1099          rhev = lasthead+1;          rhev = lasthead+1;
1100      } else {        } else {
1101          rhev = lasthead;          rhev = lasthead;
1102        };        };
1103        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 1136  UInt_t PamelaDBOperations::AssignRunID()
1136    stringstream   oss;    stringstream   oss;
1137    //      //  
1138    oss.str("");    oss.str("");
1139    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.
1140        if ( !strcmp(tag.Data(),"NONE") ){
1141          oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< chiby.Data() <<"');";
1142        } else {
1143          oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< tag.Data() <<"');";
1144        };
1145      } else {
1146        oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< tag.Data() <<"');";
1147      };
1148    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1149    if ( !result ) throw -10;    if ( !result ) throw -10;
1150    oss.str("");    oss.str("");
# Line 1227  void PamelaDBOperations::LockTables(){   Line 1292  void PamelaDBOperations::LockTables(){  
1292    stringstream oss;    stringstream oss;
1293    //      //  
1294    oss.str("");    oss.str("");
1295    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;";
1296    TSQLResult *result = 0;    TSQLResult *result = 0;
1297    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1298    if ( !result ) throw -10;    if ( !result ) throw -10;
# Line 1260  void PamelaDBOperations::UnLockTables(){ Line 1325  void PamelaDBOperations::UnLockTables(){
1325   */   */
1326  Long64_t PamelaDBOperations::PKT(UInt_t pkt_num){    Long64_t PamelaDBOperations::PKT(UInt_t pkt_num){  
1327    //    //
1328  //  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));
1329    //    //
1330    if ( pkt_num < (ppktfirst/2) && ppktfirst > (16777214/2)  ){    if ( pkt_num < (ppktfirst/2) && ppktfirst > (16777214/2)  ){
1331  //    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);
1332      return((Long64_t)pkt_num+16777215LL);      return((Long64_t)pkt_num+16777215LL);
1333    };    };
1334    //    //
1335    if ( pkt_num > ((Long64_t)ppktfirst*2) && pkt_num > (16777214/2) ){    if ( pkt_num > ((Long64_t)ppktfirst*2) && pkt_num > (16777214/2) ){
1336  //    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);
1337      return((Long64_t)pkt_num-16777215LL);      return((Long64_t)pkt_num-16777215LL);
1338    };    };
1339    //    //
1340  //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)pkt_num);    //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)pkt_num);
1341    return((Long64_t)pkt_num);    return((Long64_t)pkt_num);
1342    //    //
1343  };  };
# Line 1282  Long64_t PamelaDBOperations::PKT(UInt_t Line 1347  Long64_t PamelaDBOperations::PKT(UInt_t
1347   */   */
1348  Long64_t PamelaDBOperations::OBT(UInt_t obt){    Long64_t PamelaDBOperations::OBT(UInt_t obt){  
1349    //    //
1350  //  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));
1351    //    //
1352    if ( obt < (pobtfirst/2) && pobtfirst > (numeric_limits<UInt_t>::max()/2) ){    if ( obt < (pobtfirst/2) && pobtfirst > (numeric_limits<UInt_t>::max()/2) ){
1353  //    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());
1354      return((Long64_t)obt+(Long64_t)numeric_limits<UInt_t>::max());      return((Long64_t)obt+(Long64_t)numeric_limits<UInt_t>::max());
1355    };    };
1356    //    //
1357    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) ){
1358  //    if ( IsDebug() ) printf(" pobtfirst*2 %lld \n",((Long64_t)pobtfirst*2));      //    if ( IsDebug() ) printf(" pobtfirst*2 %lld \n",((Long64_t)pobtfirst*2));
1359  //    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());
1360      return((Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());      return((Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());
1361    };    };
1362    //    //
1363  //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)obt);    //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)obt);
1364    return((Long64_t)obt);    return((Long64_t)obt);
1365  };  };
1366    
# Line 1331  void PamelaDBOperations::FillClass(Bool_ Line 1396  void PamelaDBOperations::FillClass(Bool_
1396    UInt_t lastPkt = 0;    UInt_t lastPkt = 0;
1397    UInt_t rhtime = 0;    UInt_t rhtime = 0;
1398    UInt_t rttime = 0;    UInt_t rttime = 0;
1399      //
1400      if ( IsDebug() ) printf(" A firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1401      //
1402    if ( !mishead ){    if ( !mishead ){
1403      codh = ehh->GetCounter();      codh = ehh->GetCounter();
1404      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1) ){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){      
1405          if ( IsDebug() ) printf(" B firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1406        firstev = 1;        firstev = 1;
1407        lastev = 0;        lastev = 0;
1408      } else {      } else {
# Line 1346  void PamelaDBOperations::FillClass(Bool_ Line 1415  void PamelaDBOperations::FillClass(Bool_
1415    };    };
1416    if ( !mistrail ){    if ( !mistrail ){
1417      codt = eht->GetCounter();      codt = eht->GetCounter();
1418      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1)){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1)){      
1419          if ( IsDebug() ) printf(" C firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1420        lastev = 0;        lastev = 0;
1421        firstev = lastev+1;        firstev = lastev+1;
1422      } else {      } else {
# Line 1363  void PamelaDBOperations::FillClass(Bool_ Line 1433  void PamelaDBOperations::FillClass(Bool_
1433    if ( mishead ) {    if ( mishead ) {
1434      glrun->Set_GL_RUNH0();      glrun->Set_GL_RUNH0();
1435      //      //
1436      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1) ){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){      
1437        firstObt = lastObt;        firstObt = lastObt;
1438        firstPkt = lastPkt;        firstPkt = lastPkt;
1439        rhtime = rttime;        rhtime = rttime;
# Line 1382  void PamelaDBOperations::FillClass(Bool_ Line 1452  void PamelaDBOperations::FillClass(Bool_
1452    if ( mistrail ){    if ( mistrail ){
1453      glrun->Set_GL_RUNT0();      glrun->Set_GL_RUNT0();
1454      //      //
1455      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1) ){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){      
1456        lastObt = firstObt;        lastObt = firstObt;
1457        lastPkt = firstPkt;        lastPkt = firstPkt;
1458        rttime = rhtime;        rttime = rhtime;
# Line 1405  void PamelaDBOperations::FillClass(Bool_ Line 1475  void PamelaDBOperations::FillClass(Bool_
1475    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);
1476    //    //
1477    this->SetCommonGLRUN(rhtime,rttime);    this->SetCommonGLRUN(rhtime,rttime);
1478      this->SetPhysEndRunVariables();
1479    //    //
1480  };  };
1481    
# Line 1416  void PamelaDBOperations::FillClass(Bool_ Line 1487  void PamelaDBOperations::FillClass(Bool_
1487   * Insert a new row into GL_RAW table.   * Insert a new row into GL_RAW table.
1488   */   */
1489  Int_t PamelaDBOperations::insertPamelaRawFile(){  Int_t PamelaDBOperations::insertPamelaRawFile(){
1490    
1491        //
1492        Bool_t idr =  this->SetID_RAW();
1493        if ( idr ) return(1);
1494    
1495        GL_RAW glraw = GL_RAW();
1496        
1497        glraw.PATH = GetRawPath();
1498        glraw.NAME = GetRawFile();
1499        //    glraw.BOOT_NUMBER = 0;//???
1500        glraw.BOOT_NUMBER = this->GetBOOTnumber();
1501        
1502        if( insertPamelaRawFile(&glraw) )return(1);
1503        //
1504        idr =  this->SetID_RAW();
1505        if ( !idr ) throw -11;
1506        
1507        return(0);
1508    }
1509    /**
1510     * Insert a new row into GL_RAW table.
1511     */
1512    Int_t PamelaDBOperations::insertPamelaRawFile(GL_RAW *glraw){
1513    //    //
1514    stringstream oss;      if(!glraw)return(1);//?? ok I think
1515    //      //
1516    Bool_t idr =  this->SetID_RAW();      stringstream oss;
1517    if ( idr ) return(1);      //
1518    //      oss.str("");
1519    oss.str("");      if ( STATIC ){
1520    if ( STATIC ){          oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"
1521      oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"              << glraw->PATH << "', '" << glraw->NAME << "')";
1522          << this->GetRawPath().Data() << "', '" << this->GetRawFile().Data() << "')";      } else {
1523    } else {          oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('$PAM_RAW', '" << glraw->NAME << "')";
1524      oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('$PAM_RAW', '" << this->GetRawFile().Data() << "')";      };
1525    };      if ( debug ) cout <<oss.str().c_str() <<endl;
1526    if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;      if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
1527    //      //
1528    idr =  this->SetID_RAW();      oss.str("");
1529    if ( !idr ) throw -11;      oss << "SELECT ID FROM GL_RAW WHERE NAME=\""<<glraw->NAME<<"\";";
1530    //      if ( debug ) cout << oss.str().c_str()<<endl;
1531    return(0);      if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
1532        //
1533        TSQLResult *result = 0;
1534        TSQLRow    *row    = 0;
1535        result = conn->Query(oss.str().c_str());
1536        if ( result == NULL ) throw -4;
1537        row = result->Next();
1538        if ( !row ) return(1);
1539        glraw->ID = (UInt_t)atoll(row->GetField(0));
1540        if ( debug ) printf(" The ID of the RAW file is %u \n",glraw->ID);
1541        delete result;
1542        delete row;
1543        //
1544        return(0);
1545  }  }
1546    
1547    
# Line 1746  Int_t PamelaDBOperations::insertPamelaGL Line 1853  Int_t PamelaDBOperations::insertPamelaGL
1853   * 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.
1854   */   */
1855  Int_t PamelaDBOperations::insertPamelaRootFile(){  Int_t PamelaDBOperations::insertPamelaRootFile(){
1856    stringstream oss;  
1857    TSQLResult *result = 0;      stringstream oss;
1858    TSQLRow    *row    = 0;      TSQLResult *result = 0;
1859    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;  
1860      //      //
1861      row = result->Next();      // ----------------------
1862        // determine the timesync
1863        // ----------------------
1864        UInt_t idtimesync = 0;
1865      //      //
1866      if ( !row ) throw -3;      if ( chewbacca ){
1867      idtimesync = (UInt_t)atoll(row->GetField(0));          oss.str("");
1868    } else {          oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" limit 1;";
1869      oss.str("");          if ( debug ) printf(" %s \n",oss.str().c_str());
1870      if ( STATIC ){          result = conn->Query(oss.str().c_str());
1871        oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "          //
1872            << " LEFT JOIN GL_ROOT "          if ( !result ) throw -3;
1873            << " ON GL_RAW.ID = GL_ROOT.ID_RAW "          //
1874            << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "          row = result->Next();
1875            << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";          //
1876            if ( !row ) throw -3;
1877            idtimesync = (UInt_t)atoll(row->GetField(0));
1878      } else {      } else {
1879        oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "          oss.str("");
1880            << " LEFT JOIN GL_ROOT "          if ( STATIC ){
1881            << " ON GL_RAW.ID = GL_ROOT.ID_RAW "              oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1882            << " WHERE GL_RAW.PATH = '$PAM_RAW' AND "                  << " LEFT JOIN GL_ROOT "
1883            << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";                  << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1884                    << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "
1885                    << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1886            } else {
1887                oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1888                    << " LEFT JOIN GL_ROOT "
1889                    << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1890                    << " WHERE GL_RAW.PATH = '$PAM_RAW' AND "
1891                    << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1892            };
1893            result = conn->Query(oss.str().c_str());
1894            //
1895            if ( !result ) throw -12;
1896            //
1897            row = result->Next();
1898            //
1899            if ( !row ) throw -10;
1900            if ( row != NULL && (UInt_t)atoll(row->GetField(0))>0 ){
1901                idroot = (UInt_t)atoll(row->GetField(2));
1902                delete row;
1903                delete result;
1904                return(1);
1905            };
1906            //
1907            // determine which timesync has to be used
1908            //
1909            oss.str("");
1910            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;";
1911            result = conn->Query(oss.str().c_str());
1912            //
1913            if ( !result ) throw -3;
1914            //
1915            row = result->Next();
1916            //
1917            if ( !row ) throw -3;
1918            idtimesync = (UInt_t)atoll(row->GetField(0));
1919      };      };
1920      result = conn->Query(oss.str().c_str());      
1921      //      delete row;
1922      if ( !result ) throw -12;      delete result;
1923      //  
1924      row = result->Next();      // ----------------------
1925      //      // insert root file
1926      if ( !row ) throw -10;      // ----------------------
1927      if ( row != NULL && (UInt_t)atoll(row->GetField(0))>0 ){  
1928        idroot = (UInt_t)atoll(row->GetField(2));      GL_ROOT glroot = GL_ROOT();
1929        return(1);      
1930        glroot.ID_RAW = GetID_RAW();
1931        glroot.ID_TIMESYNC = idtimesync;
1932        if ( STATIC ){
1933          glroot.PATH = GetRootPath();
1934        } else {
1935          if ( KEEPENV ){
1936            glroot.PATH = gSystem->DirName(filerootname.Data());
1937          } else {
1938            glroot.PATH = "$PAM_L0";
1939          };
1940      };      };
1941      //      glroot.NAME = GetRootFile();
1942      // determine which timesync has to be used  
1943      //      if ( insertPamelaRootFile(&glroot) )return 1;
1944      oss.str("");  
1945      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);
1946      result = conn->Query(oss.str().c_str());      
1947      //  
1948      if ( !result ) throw -3;      return (0);
1949      //  }
1950      row = result->Next();  /**
1951      //   * Insert all the new rows into GL_ROOT.
1952      if ( !row ) throw -3;   * The raw file indicates in the parameters should be already been stored in the database.
1953      idtimesync = (UInt_t)atoll(row->GetField(0));   */
1954    };  Int_t PamelaDBOperations::insertPamelaRootFile(GL_ROOT *glroot){
1955      stringstream oss;
1956      TSQLResult *result = 0;
1957      TSQLRow    *row    = 0;
1958      //
1959    //    //
1960    oss.str("");    oss.str("");
1961    if ( STATIC ){    oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
1962      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() << "')";  
   };  
1963    //    //
1964    if ( debug ) printf(" query is %s \n",oss.str().c_str());    if ( debug ) printf("%s \n",oss.str().c_str());
1965    if (conn->Query(oss.str().c_str()) == 0) throw -4;    if (conn->Query(oss.str().c_str()) == 0) throw -4;
1966    //    //
1967    delete result;    delete result;
1968    //    //
1969    oss.str("");    oss.str("");
1970    //  oss << "SELECT ID FROM GL_ROOT WHERE ID_RAW=" << this->GetID_RAW() << ";";    //  oss << "SELECT ID FROM GL_ROOT WHERE ID_RAW=" << this->GetID_RAW() << ";";
1971    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() <<"';";  
   };  
1972    //    //
1973    if ( debug ) printf(" query is %s \n",oss.str().c_str());    if ( debug ) printf("%s \n",oss.str().c_str());
1974    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1975    if ( !result ) throw -12;    if ( !result ) throw -12;
1976    row = result->Next();    row = result->Next();
1977    if ( !row ) throw -3;    if ( !row ) throw -3;
1978    this->SetID_ROOT((UInt_t)atoll(row->GetField(0)));  
1979    if ( debug ) printf(" The ID of the ROOT file is %u \n",this->GetID_ROOT());    glroot->ID = (UInt_t)atoll(row->GetField(0));
1980    
1981      if ( debug ) printf(" The ID of the ROOT file is %u \n",glroot->ID);
1982    //    //
1983    delete result;    delete result;
1984    //    //
# Line 2061  Int_t PamelaDBOperations::insertPamelaRU Line 2206  Int_t PamelaDBOperations::insertPamelaRU
2206            cod = ehh->GetCounter();            cod = ehh->GetCounter();
2207            tcod = (UInt_t)cod->Get(pctp->Physics);            tcod = (UInt_t)cod->Get(pctp->Physics);
2208            evbefh = TMath::Max(chminentry,tcod);            evbefh = TMath::Max(chminentry,tcod);
2209  //        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
2210            if ( (UInt_t)evbefh == upperentry || !upperentry ) evbefh = upperentry + 1;            if ( (UInt_t)evbefh == upperentry || !upperentry ) evbefh = upperentry + 1;
2211  //            //
2212          if ( debug ) printf(" evbefh %i upperentry %u \n",evbefh,upperentry);            if ( debug ) printf(" evbefh %i upperentry %u \n",evbefh,upperentry);
2213            //            //
2214            this->HandleRunFragments(false,true,evbefh,upperentry);            this->HandleRunFragments(false,true,evbefh,upperentry);
2215            //            //
# Line 2367  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2512  Bool_t PamelaDBOperations::IsRunAlreadyI
2512        //        //
2513        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");
2514        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2515  //       oss.str("");        //       oss.str("");
2516  //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2517  //       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());      
2518  //       conn->Query(oss.str().c_str());        //       conn->Query(oss.str().c_str());
2519        if ( signal ) signal = false;        if ( signal ) signal = false;
2520        goto gonext;              goto gonext;      
2521        //        //
# Line 2385  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2530  Bool_t PamelaDBOperations::IsRunAlreadyI
2530        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");
2531        //        //
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        //        //
2538        if ( signal ) signal = false;        if ( signal ) signal = false;
2539        goto gonext;        goto gonext;
# Line 2403  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2548  Bool_t PamelaDBOperations::IsRunAlreadyI
2548        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");
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        if ( signal ) signal = false;        if ( signal ) signal = false;
2556        //        //
2557      };      };
# Line 2488  void PamelaDBOperations::HandleRunFragme Line 2633  void PamelaDBOperations::HandleRunFragme
2633      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");
2634      //      //
2635    } 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 ){  
2636      //      //
2637      // 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
2638      //      //
2639      if ( IsDebug() ) printf(" The run is new \n");      if ( rhfirstev != firstev && !mishead ) mishead = true;
2640      if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");      if ( rtlastev != lastev && !mistrail ) mistrail = true;
2641      //      //
2642      glrun->SetID(this->AssignRunID());      this->FillClass(mishead,mistrail,firstev,lastev);
     glrun->SetID_RUN_FRAG(0);  
     glrun->Fill_GL_RUN_FRAGMENTS(conn);  
2643      //      //
2644    } else {      if ( IsDebug() ) printf("The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
2645      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());
2646      if ( PEDANTIC ) throw -69;      //
2647      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  
2648      //      //
2649      oss.str("");      oss.str("");
2650      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 "
2651          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
2652          << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "          << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
2653          << " ID != " << glrun->ID          << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
2654          << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!          << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
2655            << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2656            << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
2657            << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
2658            << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2659            << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
2660            << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
2661            << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2662            << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
2663            << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
2664      //      //
2665      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());
2666      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
2667      //      //
2668      if ( !result ) throw -4;      if ( !result ) throw -4;
2669      //      //
2670      row = result->Next();      row = result->Next();
2671      //      //
2672      if ( !row && NoFrag() ){      if ( !row ){
2673          //
2674          // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
2675          //
2676          if ( IsDebug() ) printf(" The run is new \n");
2677          if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
2678          //
2679          glrun->SetID(this->AssignRunID());
2680          glrun->SetID_RUN_FRAG(0);
2681          glrun->Fill_GL_RUN_FRAGMENTS(conn);
2682          //
2683        } else {
2684          if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
2685          if ( PEDANTIC ) throw -69;
2686          return;
2687        };
2688        //
2689        if ( chewbacca && mishead && mistrail ) goto justcheck;
2690        //
2691        // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
2692        //    
2693        if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
2694          // missing it no way we can found a piece in the frag table
2695        //        //
2696        oss.str("");        oss.str("");
2697        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 "
2698            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2699            << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "            << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2700            << " ID != " << glrun->ID            << " ID != " << glrun->ID
2701            << " 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!!
2702        //        //
2703        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());
2704        result = conn->Query(oss.str().c_str());        result = conn->Query(oss.str().c_str());
2705        //        //
2706        if ( !result ) throw -4;        if ( !result ) throw -4;
2707        //        //
       foundinrun = true;  
       //  
2708        row = result->Next();        row = result->Next();
2709        //        //
2710      };        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)));  
2711          //          //
2712          chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;            oss.str("");
2713            oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
2714                << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2715                << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2716                << " ID != " << glrun->ID
2717                << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
2718            //
2719            if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
2720            result = conn->Query(oss.str().c_str());
2721            //
2722            if ( !result ) throw -4;
2723            //
2724            foundinrun = true;
2725            //
2726            row = result->Next();
2727          //          //
         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;  
           //  
         };  
2728        };        };
2729        if ( !found && chewbacca ) goto justcheck;        //
2730        if ( !found ){        if ( !row ){
2731            if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2732            found = false;
2733          } else {
2734          //          //
2735          // 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          found = false; // default value
2736          //          //
2737          ULong64_t chkpkt1 = 0;          if ( IsDebug() ) printf(" Found a possible candidate, checking if it is the good one... \n");
         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);  
2738          //          //
2739          if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){          // if we have both runheader and runtrailer we can check with pkt_counter:
2740            //    if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){          //
2741            //          if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){
2742            if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);            ULong64_t chkpkt = 0;  
2743              ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
2744              ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
2745            //            //
2746            found = true;            chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;  
2747            //            //
2748          } else {            if ( labs(chkpkt-pktt)<2 ){
2749                //
2750                if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
2751                //
2752                found = true;
2753                //
2754              } else {
2755                //
2756                if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);            
2757                //
2758                found = false;
2759                //
2760              };
2761            };
2762            if ( !found && chewbacca ) goto justcheck;
2763            if ( !found ){
2764            //            //
2765            if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);            // 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
2766            //            //
2767            found = false;            ULong64_t chkpkt1 = 0;
2768              ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
2769              ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
2770              chkpkt1 = labs(orunh1-dbrunt1);
2771            //            //
2772              ULong64_t chkpkt2 = 0;
2773              ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());
2774              ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
2775              chkpkt2 = labs(orunh2-dbrunt2);
2776              //
2777              ULong64_t chkpkt3 = 0;
2778              ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());
2779              ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
2780              chkpkt3 = labs(orunh3-dbrunt3);
2781              //
2782              if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
2783                //  if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){
2784                //
2785                if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
2786                //
2787                found = true;
2788                //
2789              } else {
2790                //
2791                if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
2792                //
2793                found = false;
2794                //
2795              };
2796          };          };
2797        };        };
     };  
     //  
     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");  
       };  
2798        //        //
2799        GL_RUN *glrun1 = new GL_RUN();        if ( found ){
2800        //          //
2801        //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));          // 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
2802        //          //
2803        oss.str("");          if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
2804        oss << " ID="<<row->GetField(0)<<";";          //
2805        //          if ( foundinrun ){
2806        glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos            glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2807        //            glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2808        // merge infos          };
2809        //          //
2810        UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());          GL_RUN *glrun1 = new GL_RUN();
2811        ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());          //
2812        UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());          //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
2813        ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());          //
2814        if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);          oss.str("");
2815        TTree *T= 0;          oss << " ID="<<row->GetField(0)<<";";
2816        T = (TTree*)file->Get("Physics");          //
2817        if ( !T || T->IsZombie() ) throw -16;          glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos
2818        EventHeader *eh = 0;          //
2819        PscuHeader *ph = 0;          // merge infos
2820        T->SetBranchAddress("Header", &eh);          //
2821        while ( apkt > bpkt && aobt > bobt && firstev < lastev ){          UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());
2822          T->GetEntry(firstev);          ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
2823          ph = eh->GetPscuHeader();          UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
2824          bpkt = PKT(ph->GetCounter());          ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
2825          bobt = OBT(ph->GetOrbitalTime());                if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2826          firstev++;          TTree *T= 0;
2827          if ( PEDANTIC ) throw -71;          T = (TTree*)file->Get("Physics");
2828        };          if ( !T || T->IsZombie() ) throw -16;
2829        if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);          EventHeader *eh = 0;
2830        //          PscuHeader *ph = 0;
2831        glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());          T->SetBranchAddress("Header", &eh);
2832        glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());          while ( apkt > bpkt && aobt > bobt && firstev < lastev ){
2833        glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());            T->GetEntry(firstev);
2834        glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());            ph = eh->GetPscuHeader();
2835        glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());            bpkt = PKT(ph->GetCounter());
2836        //            bobt = OBT(ph->GetOrbitalTime());    
2837        glrun->SetEV_FROM(firstev);            firstev++;
2838        glrun->SetNEVENTS(lastev-firstev+1);            if ( PEDANTIC ) throw -71;
2839        //          };
2840        glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());          if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2841        glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());          //
2842        glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());          glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
2843        glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());          glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
2844        glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());          glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
2845        glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());          glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());
2846        glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());          glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());
2847        glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());          //
2848        glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());          glrun->SetEV_FROM(firstev);
2849        glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());          glrun->SetNEVENTS(lastev-firstev+1);
2850        glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());            //
2851        glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());            glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
2852        glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());            glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
2853        glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());            glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
2854        glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());            glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());
2855        glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());            glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());
2856        //          glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());
2857        if ( !IsRunAlreadyInserted() ){          glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());
2858            glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());
2859            glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());
2860            glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());
2861            glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());  
2862            glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());  
2863            glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());  
2864            glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());  
2865            glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());  
2866            glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());  
2867            //
2868            if ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
2869            if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
2870            //
2871            if ( !IsRunAlreadyInserted() ){
2872              //
2873              //    glrun->SetID(this->AssignRunID());
2874              glrun->SetID_RUN_FRAG(glrun1->GetID());
2875              glrun->Fill_GL_RUN(conn);
2876              //
2877              // set id number
2878              //
2879              glrun1->SetID_RUN_FRAG(glrun->GetID());
2880              glrun1->Fill_GL_RUN(conn);
2881              //
2882            };
2883            // delete old entry in fragment table
2884            //
2885            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2886            glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2887          //          //
2888          //      glrun->SetID(this->AssignRunID());          delete glrun1;
         glrun->SetID_RUN_FRAG(glrun1->GetID());  
         glrun->Fill_GL_RUN(conn);  
2889          //          //
         // set id number  
2890          //          //
2891          glrun1->SetID_RUN_FRAG(glrun->GetID());          return;
         glrun1->Fill_GL_RUN(conn);  
2892          //          //
2893        };        };
       // delete old entry in fragment table  
       //  
       glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       //  
       delete glrun1;  
       //  
       //  
       return;  
2894        //        //
2895      };      };
2896      //      //
2897    };      if ( mistrail && ( rtlastev == lastev || chewbacca )) { // look for runtrailer (only when at the end of the file, if at the beginning and the runh is
2898    //        // 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() ){  
2899        //        //
2900        oss.str("");        oss.str("");
2901        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 "
2902            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2903            << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "            << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2904            << " ID != " << glrun->ID            << " ID != " << glrun->ID
2905            << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";            << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2906        //        //
2907        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());
2908        result = conn->Query(oss.str().c_str());        result = conn->Query(oss.str().c_str());
2909        //        //
2910        if ( !result ) throw -4;        if ( !result ) throw -4;
2911        //        //
       foundinrun = true;  
2912        row = result->Next();        row = result->Next();
2913        //        //
2914      };        if ( !row && NoFrag() ){
2915      //          //
2916      if ( !row ){          oss.str("");
2917        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 "
2918        found = false;              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2919      } else {              << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2920        //              << " ID != " << glrun->ID
2921        found = false; // default value              << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2922        //          //
2923        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());
2924        //          result = conn->Query(oss.str().c_str());
2925        // if we have both runheader and runtrailer we can check with pkt_counter:          //
2926            if ( !result ) throw -4;
2927            //
2928            foundinrun = true;
2929            row = result->Next();
2930            //
2931          };
2932        //        //
2933        if ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){        if ( !row ){
2934          ULong64_t chkpkt = 0;            if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2935          ULong64_t pktt = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));          found = false;
2936          ULong64_t pkth = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());        } else {
2937            //
2938            found = false; // default value
2939            //
2940            if ( IsDebug() ) printf(" Found a possible candidate, checking if it is the good one... \n");
2941          //          //
2942          chkpkt = pkth + (ULong64_t)((UInt_t)atoll(row->GetField(1))) + 1ULL + 1ULL;            // if we have both runheader and runtrailer we can check with pkt_counter:
2943          //          //
2944          if ( labs(chkpkt-pktt)<2 ){          if ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){
2945              ULong64_t chkpkt = 0;  
2946              ULong64_t pktt = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
2947              ULong64_t pkth = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
2948            //            //
2949            if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);            chkpkt = pkth + (ULong64_t)((UInt_t)atoll(row->GetField(1))) + 1ULL + 1ULL;  
2950            //            //
2951            found = true;            if ( labs(chkpkt-pktt)<2 ){
2952                //
2953                if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
2954                //
2955                found = true;
2956                //
2957              } else {
2958                //
2959                if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);            
2960                //
2961                found = false;
2962                //
2963              };
2964            };
2965            if ( !found && chewbacca ) goto justcheck;
2966            if ( !found ){
2967            //            //
2968          } 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
2969            //            //
2970            if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);                  ULong64_t chkpkt1 = 0;
2971              ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
2972              ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
2973              chkpkt1 = labs(orunh1-dbrunt1);
2974            //            //
2975            found = false;            ULong64_t chkpkt2 = 0;
2976              ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNTRAILER_OBT());
2977              ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
2978              chkpkt2 = labs(orunh2-dbrunt2);
2979            //            //
2980              ULong64_t chkpkt3 = 0;
2981              ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNTRAILER_TIME());
2982              ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
2983              chkpkt3 = labs(orunh3-dbrunt3);
2984              //
2985              if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
2986                //
2987                if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
2988                //
2989                found = true;
2990                //
2991              } else {
2992                //
2993                if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
2994                //
2995                found = false;
2996                //
2997              };
2998          };          };
2999        };        };
3000        if ( !found && chewbacca ) goto justcheck;        //
3001        if ( !found ){        if ( found ){
3002            //
3003            // 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
3004            //
3005            if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
3006            //
3007            if ( foundinrun ){
3008              glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3009              glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
3010            };
3011          //          //
3012          // 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          GL_RUN *glrun1 = new GL_RUN();
3013          //          //
3014          ULong64_t chkpkt1 = 0;          //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
         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);  
3015          //          //
3016          ULong64_t chkpkt2 = 0;          oss.str("");
3017          ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNTRAILER_OBT());          oss << " ID="<<row->GetField(0)<<";";
         ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));  
         chkpkt2 = labs(orunh2-dbrunt2);  
3018          //          //
3019          ULong64_t chkpkt3 = 0;          glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runtrailer infos
         ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNTRAILER_TIME());  
         ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));  
         chkpkt3 = labs(orunh3-dbrunt3);  
3020          //          //
3021          if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){          // merge infos
3022            //          //
3023            if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);          UInt_t apkt = PKT(glrun->GetRUNTRAILER_PKT());
3024            //          ULong64_t aobt = OBT(glrun->GetRUNTRAILER_OBT());
3025            found = true;          UInt_t bpkt = PKT(glrun1->GetRUNHEADER_PKT());
3026            //          ULong64_t bobt = OBT(glrun1->GetRUNHEADER_OBT());
3027          } else {          if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
3028            TTree *T= 0;
3029            T = (TTree*)file->Get("Physics");
3030            if ( !T || T->IsZombie() ) throw -16;
3031            EventHeader *eh = 0;
3032            PscuHeader *ph = 0;
3033            T->SetBranchAddress("Header", &eh);
3034            while ( apkt > bpkt && aobt > bobt && lastev > 0 ){
3035              T->GetEntry(lastev);
3036              ph = eh->GetPscuHeader();
3037              apkt = PKT(ph->GetCounter());
3038              aobt = OBT(ph->GetOrbitalTime());    
3039              lastev--;
3040              if ( PEDANTIC ) throw -72;
3041            };
3042            if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
3043            //
3044            glrun->SetEV_TO(lastev);
3045            glrun->SetNEVENTS(lastev-firstev+1);
3046            glrun->SetPKT_COUNTER(glrun1->GetPKT_COUNTER());
3047            glrun->SetPKT_READY_COUNTER(glrun1->GetPKT_READY_COUNTER());
3048            glrun->SetRUNTRAILER_TIME(glrun1->GetRUNTRAILER_TIME());
3049            glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());
3050            glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());
3051            //
3052            glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());
3053            glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());
3054            glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());
3055            glrun1->SetCOMPILATIONTIMESTAMP(glrun->GetCOMPILATIONTIMESTAMP());
3056            glrun1->SetFAV_WRK_SCHEDULE(glrun->GetFAV_WRK_SCHEDULE());
3057            glrun1->SetEFF_WRK_SCHEDULE(glrun->GetEFF_WRK_SCHEDULE());
3058            glrun1->SetPRH_VAR_TRG_MODE_A(glrun->GetPRH_VAR_TRG_MODE_A());
3059            glrun1->SetPRH_VAR_TRG_MODE_B(glrun->GetPRH_VAR_TRG_MODE_B());
3060            glrun1->SetACQ_BUILD_INFO(glrun->GetACQ_BUILD_INFO());
3061            glrun1->SetACQ_VAR_INFO(glrun->GetACQ_VAR_INFO());
3062            glrun1->SetRM_ACQ_AFTER_CALIB(glrun->GetRM_ACQ_AFTER_CALIB());  
3063            glrun1->SetRM_ACQ_SETTING_MODE(glrun->GetRM_ACQ_SETTING_MODE());  
3064            glrun1->SetTRK_CALIB_USED(glrun->GetTRK_CALIB_USED());  
3065            glrun1->SetCAL_DSP_MASK(glrun->GetCAL_DSP_MASK());  
3066            glrun1->SetLAST_TIMESYNC(glrun->GetLAST_TIMESYNC());  
3067            glrun1->SetOBT_TIMESYNC(glrun->GetOBT_TIMESYNC());  
3068            //
3069            if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ) glrun1->SetPHYSENDRUN_MASK_S3S2S12(glrun->GetPHYSENDRUN_MASK_S3S2S12());
3070            if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) glrun1->SetPHYSENDRUN_MASK_S11CRC(glrun->GetPHYSENDRUN_MASK_S11CRC());
3071            //
3072            if ( !IsRunAlreadyInserted() ){
3073              //
3074              //    glrun->SetID(this->AssignRunID());
3075              //
3076              glrun->SetID_RUN_FRAG(glrun1->GetID());
3077              glrun->Fill_GL_RUN(conn);
3078            //            //
3079            if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);            // set id number
3080            //            //
3081            found = false;            glrun1->SetID_RUN_FRAG(glrun->GetID());
3082              glrun1->Fill_GL_RUN(conn);
3083            //            //
3084          };          };
3085            //
3086            // delete old entries in fragment table
3087            //
3088            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3089            glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3090            //
3091            delete glrun1;
3092            //
3093            return;
3094            //
3095        };        };
3096          //
3097      };      };
3098      //      //
3099      if ( found ){    justcheck:
3100        //      //
3101        // 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");  
       };  
3102        //        //
3103        GL_RUN *glrun1 = new GL_RUN();        if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");
3104        //        //
3105        //      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?
3106        //        //
3107        oss.str("");        oss.str("");
3108        oss << " ID="<<row->GetField(0)<<";";        oss << " SELECT ID FROM GL_RUN WHERE "
3109              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3110              << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3111              << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3112              << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3113              << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3114              << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3115              << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3116              << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3117              << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3118              << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3119              << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3120              << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3121              << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3122        //        //
3123        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());
3124          result = conn->Query(oss.str().c_str());
3125        //        //
3126        // merge infos        if ( !result ) throw -4;
3127        //        //
3128        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());    
3129        //        //
3130        if ( !IsRunAlreadyInserted() ){        if ( row ){
3131          //          if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");
3132          //      glrun->SetID(this->AssignRunID());          if ( PEDANTIC ) throw -70;
3133          //        } else {
3134          glrun->SetID_RUN_FRAG(glrun1->GetID());          if ( NoFrag() ){
3135          glrun->Fill_GL_RUN(conn);            glrun->SetID_RUN_FRAG(glrun->GetID());
3136          //            glrun->Fill_GL_RUN(conn);    
3137          // set id number            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3138          //          };    
         glrun1->SetID_RUN_FRAG(glrun->GetID());  
         glrun1->Fill_GL_RUN(conn);  
         //  
3139        };        };
       //  
       // delete old entries in fragment table  
       //  
       glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       //  
       delete glrun1;  
       //  
       return;  
       //  
     };  
     //  
   };  
   //  
  justcheck:  
   //  
   if ( !found ){        
     //  
     if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");  
     //  
     // not found, has this run already inserted in the GL_RUN or in the GL_RUN_FRAGMENTS table?  
     //  
     oss.str("");  
     oss << " SELECT ID FROM GL_RUN WHERE "  
         << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("  
         << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "  
         << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("  
         << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "  
         << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("  
         << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "  
         << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "  
         << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "  
         << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("  
         << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "  
         << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("  
         << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "  
         << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";  
     //  
     if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());  
     result = conn->Query(oss.str().c_str());  
     //  
     if ( !result ) throw -4;  
     //  
     row = result->Next();  
     //  
     if ( row ){  
       if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");  
       if ( PEDANTIC ) throw -70;  
     } else {  
       if ( NoFrag() ){  
         glrun->SetID_RUN_FRAG(glrun->GetID());  
         glrun->Fill_GL_RUN(conn);        
         glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       };      
3140      };      };
   };  
3141    }; // EEE    }; // EEE
3142    //    //
3143    return;    return;
# Line 3068  Bool_t PamelaDBOperations::IsRunConsiste Line 3219  Bool_t PamelaDBOperations::IsRunConsiste
3219      code = eh->GetCounter();      code = eh->GetCounter();
3220      checkfirst = 0;      checkfirst = 0;
3221      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3222         if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
3223       };      };
3224      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);
3225      //      //
3226      T->GetEntry(lastev);      T->GetEntry(lastev);
3227      code = eh->GetCounter();      code = eh->GetCounter();
3228      checklast = 0;      checklast = 0;
3229      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3230         if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
3231       };      };
3232      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);
3233      //      //
3234      if ( checkfirst == checklast ){      if ( checkfirst == checklast ){
# Line 3092  Bool_t PamelaDBOperations::IsRunConsiste Line 3243  Bool_t PamelaDBOperations::IsRunConsiste
3243        //        //
3244        // HERE WE MUST HANDLE THAT RUNS AND GO BACK        // HERE WE MUST HANDLE THAT RUNS AND GO BACK
3245        //        //
3246  //      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");
3247        //        //
3248        Bool_t emptyruns = false;        Bool_t emptyruns = false;
3249        UInt_t check = 0;        UInt_t check = 0;
# Line 3184  Bool_t PamelaDBOperations::IsRunConsiste Line 3335  Bool_t PamelaDBOperations::IsRunConsiste
3335            };            };
3336            //                  //      
3337            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
3338              this->SetPhysEndRunVariables();
3339            //            //
3340            if ( chminentry == firstentry  ){ // EEE            if ( chminentry == firstentry  ){ // EEE
3341              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");
3342  //              //
3343  //          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
3344  //              //
   
   
   
   
   
   
   
   
   
   
   
   
   
   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  
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
3345    
3346                mishead = true;
3347    
3348    
3349                UInt_t rhfirstev = firstentry;
3350                //  UInt_t rtlastev = lastentry;
3351                Bool_t found = false;
3352                Bool_t foundinrun = false;
3353                //
3354                TSQLResult *result = 0;
3355                TSQLRow    *row    = 0;
3356                //
3357                stringstream oss;
3358                oss.str("");
3359                //
3360                // we have now the good first piece of a run, fill the glrun object
3361                //
3362                //  if ( rhfirstev != firstev && !mishead ) mishead = true;
3363                //  if ( rtlastev != lastev && !mistrail ) mistrail = true;
3364                //
3365                //  this->FillClass(mishead,mistrail,firstev,lastev);
3366                //
3367                if ( IsDebug() ) printf("zz The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
3368                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());
3369                //
3370                // First of all insert the run in the fragment table...
3371                //
3372                oss.str("");
3373                oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
3374                    << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3375                    << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3376                    << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3377                    << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3378                    << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3379                    << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3380                    << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3381                    << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3382                    << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3383                    << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3384                    << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3385                    << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3386                    << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3387                //
3388                if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3389                result = conn->Query(oss.str().c_str());
3390                //
3391                if ( !result ) throw -4;
3392                //
3393                row = result->Next();
3394                //
3395                if ( !row ){
3396                  //
3397                  // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
3398                  //
3399                  if ( IsDebug() ) printf(" The run is new \n");
3400                  if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
3401                  //
3402                  glrun->SetID(this->AssignRunID());
3403                  glrun->SetID_RUN_FRAG(0);
3404                  glrun->Fill_GL_RUN_FRAGMENTS(conn);
3405                  //
3406                } else {
3407                  if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
3408                  if ( PEDANTIC ) throw -69;
3409                  //    return;
3410                };
3411                //
3412                if ( chewbacca && mishead && mistrail ) goto zjustcheck;
3413                //
3414                // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
3415                //
3416                if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
3417                  // missing it no way we can found a piece in the frag table
3418                  //
3419                  oss.str("");
3420                  oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "
3421                      << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3422                      << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3423                      << " ID != " << glrun->ID
3424                      << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
3425                  //
3426                  if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());
3427                  result = conn->Query(oss.str().c_str());
3428                  //
3429                  if ( !result ) throw -4;
3430                  //
3431                  row = result->Next();
3432                  //
3433                  if ( !row && NoFrag() ){
3434                    //
3435                    oss.str("");
3436                    oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
3437                        << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3438                        << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3439                        << " ID != " << glrun->ID
3440                        << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
3441                    //
3442                    if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
3443                    result = conn->Query(oss.str().c_str());
3444                    //
3445                    if ( !result ) throw -4;
3446                    //
3447                    foundinrun = true;
3448                    //
3449                    row = result->Next();
3450                    //
3451                  };
3452                  //
3453                  if ( !row ){
3454                    if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
3455                    found = false;
3456                  } else {
3457                    //
3458                    found = false; // default value
3459                    //
3460                    if ( IsDebug() ) printf(" Found a possible candidate, checking if it is the good one... \n");
3461                    //
3462                    // if we have both runheader and runtrailer we can check with pkt_counter:
3463                    //
3464                    if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){
3465                      ULong64_t chkpkt = 0;
3466                      ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
3467                      ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
3468                      //
3469                      chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;
3470                      //
3471                      if ( labs(chkpkt-pktt)<2 ){
3472                        //
3473                        if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
3474                        //
3475                        found = true;
3476                        //
3477                      } else {
3478                        //
3479                        if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);
3480                        //
3481                        found = false;
3482                        //
3483                      };
3484                    };
3485                    if ( !found && chewbacca ) goto zjustcheck;
3486                    if ( !found ){
3487                      //
3488                      // 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
3489                      //
3490                      ULong64_t chkpkt1 = 0;
3491                      ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
3492                      ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
3493                      chkpkt1 = labs(orunh1-dbrunt1);
3494                      //
3495                      ULong64_t chkpkt2 = 0;
3496                      ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());
3497                      ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
3498                      chkpkt2 = labs(orunh2-dbrunt2);
3499                      //
3500                      ULong64_t chkpkt3 = 0;
3501                      ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());
3502                      ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
3503                      chkpkt3 = labs(orunh3-dbrunt3);
3504                      //
3505                      if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
3506                        //    if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){
3507                        //
3508                        if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
3509                        //
3510                        found = true;
3511                        //
3512                      } else {
3513                        //
3514                        if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
3515                        //
3516                        found = false;
3517                        //
3518                      };
3519                    };
3520                  };
3521                  //
3522                  if ( found ){
3523                    //
3524                    // 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
3525                    //
3526                    if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
3527                    //
3528                    if ( foundinrun ){
3529                      glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3530                      glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
3531                    };
3532                    //
3533                    GL_RUN *glrun1 = new GL_RUN();
3534                    //
3535                    //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
3536                    //
3537                    oss.str("");
3538                    oss << " ID="<<row->GetField(0)<<";";
3539                    //
3540                    glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos
3541                    //
3542                    // merge infos
3543                    //
3544                    UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());
3545                    ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
3546                    UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
3547                    ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
3548                    if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
3549                    TTree *T= 0;
3550                    T = (TTree*)file->Get("Physics");
3551                    if ( !T || T->IsZombie() ) throw -16;
3552                    EventHeader *eh = 0;
3553                    PscuHeader *ph = 0;
3554                    T->SetBranchAddress("Header", &eh);
3555                    while ( apkt > bpkt && aobt > bobt && firstev < lastev ){
3556                      T->GetEntry(firstev);
3557                      ph = eh->GetPscuHeader();
3558                      bpkt = PKT(ph->GetCounter());
3559                      bobt = OBT(ph->GetOrbitalTime());
3560                      firstev++;
3561                      if ( PEDANTIC ) throw -71;
3562                    };
3563                    if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
3564                    //
3565                    glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
3566                    glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
3567                    glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
3568                    glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());
3569                    glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());
3570                    //
3571                    glrun->SetEV_FROM(firstev);
3572                    glrun->SetNEVENTS(lastev-firstev+1);
3573                    //
3574                    glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
3575                    glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
3576                    glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
3577                    glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());
3578                    glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());
3579                    glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());
3580                    glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());
3581                    glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());
3582                    glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());
3583                    glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());
3584                    glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());
3585                    glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());
3586                    glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());
3587                    glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());
3588                    glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());
3589                    glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());
3590                    //
3591                    if ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
3592                    if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
3593                    //
3594                    if ( !IsRunAlreadyInserted() ){
3595                      //
3596                      //      glrun->SetID(this->AssignRunID());
3597                      glrun->SetID_RUN_FRAG(glrun1->GetID());
3598                      glrun->Fill_GL_RUN(conn);
3599                      //
3600                      // set id number
3601                      //
3602                      glrun1->SetID_RUN_FRAG(glrun->GetID());
3603                      glrun1->Fill_GL_RUN(conn);
3604                      //
3605                    };
3606                    // delete old entry in fragment table
3607                    //
3608                    glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3609                    glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3610                    //
3611                    delete glrun1;
3612                    //
3613                    //
3614                    //      return;
3615                    //
3616                  };
3617                  //
3618                };
3619                //
3620                //
3621              zjustcheck:
3622                //
3623                if ( !found ){
3624                  //
3625                  if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");
3626                  //
3627                  // not found, has this run already inserted in the GL_RUN or in the GL_RUN_FRAGMENTS table?
3628                  //
3629                  oss.str("");
3630                  oss << " SELECT ID FROM GL_RUN WHERE "
3631                      << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3632                      << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3633                      << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3634                      << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3635                      << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3636                      << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3637                      << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3638                      << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3639                      << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3640                      << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3641                      << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3642                      << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3643                      << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3644                  //
3645                  if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3646                  result = conn->Query(oss.str().c_str());
3647                  //
3648                  if ( !result ) throw -4;
3649                  //
3650                  row = result->Next();
3651                  //
3652                  if ( row ){
3653                    if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");
3654                    if ( PEDANTIC ) throw -70;
3655                  } else {
3656                    if ( NoFrag() ){
3657                      glrun->SetID_RUN_FRAG(glrun->GetID());
3658                      glrun->Fill_GL_RUN(conn);
3659                      glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3660                    };
3661                  };
3662                }; // EEE
3663    
3664    
3665            } else {            } else {
3666            if ( !IsRunAlreadyInserted() ){              if ( !IsRunAlreadyInserted() ){
3667              glrun->SetID(this->AssignRunID());                glrun->SetID(this->AssignRunID());
3668              glrun->SetID_RUN_FRAG(0);                glrun->SetID_RUN_FRAG(0);
3669              glrun->Fill_GL_RUN(conn);                glrun->Fill_GL_RUN(conn);
3670            };              };
3671            }; // EEE            }; // EEE
3672            //            //
3673            firstevno = lastentry + 1;            firstevno = lastentry + 1;
# Line 3647  void PamelaDBOperations::HandleSuspiciou Line 3759  void PamelaDBOperations::HandleSuspiciou
3759      code = eh->GetCounter();      code = eh->GetCounter();
3760      checkfirst = 0;      checkfirst = 0;
3761      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3762         if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
3763         if ( !strcmp(*Iter,"RunHeader") ) nrunh1++;        if ( !strcmp(*Iter,"RunHeader") ) nrunh1++;
3764       };      };
3765      if ( IsDebug() ) printf(" Check first is %i \n",checkfirst);      if ( IsDebug() ) printf(" Check first is %i \n",checkfirst);
3766      //      //
3767      T->GetEntry(lastev);      T->GetEntry(lastev);
3768      code = eh->GetCounter();      code = eh->GetCounter();
3769      checklast = 0;      checklast = 0;
3770      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3771         if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
3772       };      };
3773      if ( IsDebug() ) printf(" Check last is %i \n",checklast);      if ( IsDebug() ) printf(" Check last is %i \n",checklast);
3774      //      //
3775      if ( checkfirst == checklast ){      if ( checkfirst == checklast ){
# Line 3769  void PamelaDBOperations::HandleSuspiciou Line 3881  void PamelaDBOperations::HandleSuspiciou
3881            };            };
3882            //                  //      
3883            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
3884              this->SetPhysEndRunVariables();
3885            //            //
3886            if ( !IsRunAlreadyInserted() ){            if ( !IsRunAlreadyInserted() ){
3887              glrun->SetID(this->AssignRunID());              glrun->SetID(this->AssignRunID());
# Line 3808  void PamelaDBOperations::HandleSuspiciou Line 3921  void PamelaDBOperations::HandleSuspiciou
3921              if ( IsDebug() ) printf(" We have the runtrailer \n");              if ( IsDebug() ) printf(" We have the runtrailer \n");
3922              //                  //    
3923              this->SetCommonGLRUN(firstTime,lastTime);              this->SetCommonGLRUN(firstTime,lastTime);
3924                this->SetPhysEndRunVariables();
3925              //              //
3926              if ( !IsRunAlreadyInserted() ){              if ( !IsRunAlreadyInserted() ){
3927                glrun->SetID(this->AssignRunID());                glrun->SetID(this->AssignRunID());
# Line 4382  Int_t PamelaDBOperations::insertCALOPULS Line 4496  Int_t PamelaDBOperations::insertCALOPULS
4496   * Fill the GL_TRK_CALIB table   * Fill the GL_TRK_CALIB table
4497   */   */
4498  void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){  void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){
4499    //      
4500    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 ){  
4501      //      //
4502      if ( IsDebug() ) printf(" Trk calibration already inserted in the DB\n");      glcal->ID         = 0;
4503      if ( PEDANTIC ) throw -80;      glcal->ID_ROOT_L0 = GetID_ROOT();
4504        glcal->EV_ROOT_CALIBTRK1 = t1;
4505        glcal->EV_ROOT_CALIBTRK2 = t2;
4506        glcal->FROM_TIME = fromtime;
4507        glcal->TO_TIME   = 0;
4508        glcal->OBT1      = obt1;
4509        glcal->OBT2      = obt2;
4510        glcal->PKT1      = pkt1;
4511        glcal->PKT2      = pkt2;
4512        glcal->BOOT_NUMBER = GetBOOTnumber();
4513        glcal->VALIDATION = valid;
4514      //      //
4515    } else {      HandleTRK_CALIB(glcal);
     //  
     // we have to insert a new calibration, check where to place it  
4516      //      //
4517      oss.str("");      delete glcal;
4518      oss << " SELECT ID,TO_TIME FROM GL_TRK_CALIB WHERE "  }
4519          << " FROM_TIME < "<< fromtime << " AND "  /**
4520          << " TO_TIME > "<< fromtime << ";";   * Fill the GL_TRK_CALIB table
4521     */
4522    void PamelaDBOperations::HandleTRK_CALIB(GL_TRK_CALIB *glcal){
4523    
4524        Bool_t pk1 = (glcal->OBT1>0&&glcal->PKT1>0);
4525        Bool_t pk2 = (glcal->OBT2>0&&glcal->PKT2>0);
4526        UInt_t boot_number = glcal->BOOT_NUMBER;
4527        UInt_t obt1 = glcal->OBT1;
4528        UInt_t obt2 = glcal->OBT2;
4529        UInt_t pkt1 = glcal->PKT1;
4530        UInt_t pkt2 = glcal->PKT2;
4531        UInt_t fromtime = glcal->FROM_TIME;
4532        UInt_t totime = 0;
4533        UInt_t idroot = glcal->ID_ROOT_L0;
4534        UInt_t t1 = glcal->EV_ROOT_CALIBTRK1;
4535        UInt_t t2 = glcal->EV_ROOT_CALIBTRK2;
4536        UInt_t valid = glcal->VALIDATION;
4537      //      //
4538      if ( IsDebug() ) printf(" Check where to place the trk calibration: query is \n %s \n",oss.str().c_str());      TSQLResult *result = 0;
4539      result = conn->Query(oss.str().c_str());      TSQLRow    *row    = 0;
4540      //      //
4541      if ( !result ) throw -4;      stringstream oss;
4542        oss.str("");
4543      //      //
     row = result->Next();  
4544      //      //
4545      if ( !row ){      if ( !pk1 && !pk2 ){
4546        //          if ( IsDebug() ) printf(" Cannot handle trk calibration with both packet missing!\n");
4547        // 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;  
       //  
4548      };      };
4549      //      //
4550      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 << "',";  
4551      //      //
4552      if ( !pk1 ){      oss.str("");
4553        oss << "NULL,";      oss << " SELECT ID FROM GL_TRK_CALIB WHERE "
4554            << " BOOT_NUMBER = "<< boot_number; //
4555        oss << " AND FROM_TIME="<<fromtime; /// NEWNEWNEW -- VA BENE ?!?!?!?!
4556        oss << " AND ( ( ";  
4557        if ( pk1 ){
4558            oss << " OBT1 = "<< obt1 << " AND "
4559                << " PKT1 = "<< pkt1
4560                << " ) OR ( ";
4561      } else {      } else {
4562        oss << "'"          oss << " PKT1 = "<< pkt2-1
4563            << t1 << "',";              << " ) OR ( ";  
4564      };      };      
4565      //      if ( pk2 ){
4566      if ( !pk2 ){          oss << " OBT2 = "<< obt2 << " AND "
4567        oss << "NULL,'";              << " PKT2 = "<< pkt2;
4568      } else {      } else {
4569        oss << "'"          oss << " PKT2 = "<< pkt1+1;
4570            << t2 << "','";      };      
4571      };      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());  
4572      //      //
4573        if ( IsDebug() ) printf(" Check if the trk calibration has already been inserted: query is \n %s \n",oss.str().c_str());
4574      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
4575      //      //
4576      if ( !result ) throw -4;      if ( !result ) throw -4;
4577      //      //
4578    };      row = result->Next();
4579    //      //
4580        if ( row ){
4581            //
4582            if ( IsDebug() ) printf(" Trk calibration already inserted in the DB\n");
4583            if ( PEDANTIC ) throw -80;
4584            //
4585        } else {
4586            //
4587            // we have to insert a new calibration, check where to place it
4588            //
4589            oss.str("");
4590            oss << " SELECT ID,TO_TIME FROM GL_TRK_CALIB WHERE "
4591                << " FROM_TIME < "<< fromtime << " AND "
4592                << " TO_TIME > "<< fromtime << ";";
4593            //
4594            if ( IsDebug() ) printf(" Check where to place the trk calibration: query is \n %s \n",oss.str().c_str());
4595            result = conn->Query(oss.str().c_str());
4596            //
4597            if ( !result ) throw -4;
4598            //
4599            row = result->Next();
4600            //
4601            if ( !row ){
4602                //
4603                // no calibrations in the db contain our calibration
4604                //
4605                if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB\n");
4606                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
4607                //
4608                oss.str("");
4609                oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "
4610                    << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
4611                //
4612                if ( IsDebug() ) printf(" Check the upper limit for calibration: query is \n %s \n",oss.str().c_str());
4613                result = conn->Query(oss.str().c_str());
4614                //
4615                if ( !result ) throw -4;
4616                //
4617                row = result->Next();
4618                if ( !row ){
4619                    totime = numeric_limits<UInt_t>::max();
4620                } else {
4621                    totime = (UInt_t)atoll(row->GetField(0));
4622                };
4623                //
4624            } else {
4625                //
4626                // determine upper and lower limits and make space for the new calibration
4627                //
4628                totime = (UInt_t)atoll(row->GetField(1));
4629                //
4630                oss.str("");
4631                oss << " UPDATE GL_TRK_CALIB SET "  
4632                    << " TO_TIME = "<< fromtime << " WHERE "  // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
4633                    << " ID = "<< row->GetField(0) << ";";
4634                //
4635                if ( IsDebug() ) printf(" Make space for the new trk calibration: query is \n %s \n",oss.str().c_str());
4636                result = conn->Query(oss.str().c_str());
4637                //
4638                if ( !result ) throw -4;
4639                //
4640            };
4641            //
4642            oss.str("");
4643            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) "
4644                << " VALUES (NULL,' "
4645                << idroot << "',";
4646            //
4647            if ( !pk1 ){
4648                oss << "NULL,";
4649            } else {
4650                oss << "'"
4651                    << t1 << "',";
4652            };
4653            //
4654            if ( !pk2 ){
4655                oss << "NULL,'";
4656            } else {
4657                oss << "'"
4658                    << t2 << "','";
4659            };
4660            //
4661            oss << fromtime << "','"
4662                << totime << "','"
4663                << obt1 << "','"
4664                << pkt1 << "','"
4665                << obt2 << "','"
4666                << pkt2 << "','"
4667                << boot_number << "','"
4668                << valid << "');";
4669            //
4670            if ( IsDebug() ) printf(" Insert the new trk calibration: query is \n %s \n",oss.str().c_str());
4671            //
4672            result = conn->Query(oss.str().c_str());
4673            //
4674            if ( !result ) throw -4;
4675            //
4676        };
4677        
4678        oss.str("");
4679        oss << " SELECT ID FROM GL_TRK_CALIB ORDER BY ID DESC LIMIT 1 ;";  
4680        if ( IsDebug() ) cout << oss.str().c_str() << endl;
4681        result = conn->Query(oss.str().c_str());
4682        if ( !result ) throw -4;;
4683        row = result->Next();
4684        if(row)glcal->ID = (UInt_t)atoll(row->GetField(0));
4685    
4686        //
4687  };  };
4688    
4689  /**  /**
4690   * Scan tracker calibrations packets, fill the GL_TRK_CALIB table   * Scan tracker calibrations packets, fill the GL_TRK_CALIB table
4691   */   */
4692  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++){  
4693      //      //
4694      pret2 = t2;      CalibTrk1Event *caltrk1 = 0;
4695      tr1->GetEntry(t1);      CalibTrk2Event *caltrk2 = 0;
4696        TTree *tr1 = 0;
4697        TTree *tr2 = 0;
4698        EventHeader *eh1 = 0;
4699        PscuHeader *ph1 = 0;
4700        EventHeader *eh2 = 0;
4701        PscuHeader *ph2 = 0;
4702      //      //
4703      ph1 = eh1->GetPscuHeader();      PacketType *pctp=0;
4704      obt1 = ph1->GetOrbitalTime();        EventCounter *codt2=0;
     pkt1 = ph1->GetCounter();    
     fromtime = this->GetAbsTime(ph1->GetOrbitalTime());    
4705      //      //
4706  //     valid = 1;      Int_t nevents1 = 0;
4707  //     //      Int_t nevents2 = 0;
 //     if ( caltrk1->unpackError != 0 && caltrk1->good0 == 0 ) valid = 0;// CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT1  
4708      //      //
4709        fromtime = 0;
4710      //      //
4711      if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->PKT(pkt1) <= upperpkt && this->OBT(obt1) >= this->OBT(obtfirst) && this->OBT(obt1) <= upperobt ){      obt1 = 0;
4712        //    if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->OBT(obt1) >= this->OBT(obtfirst) ){      pkt1 = 0;
4713        //      obt2 = 0;
4714        if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u \n",fromtime,obt1,pkt1);      pkt2 = 0;
4715        //            //
4716        valid = ValidateTrkCalib( caltrk1, eh1 );      tr1 = (TTree*)file->Get("CalibTrk1");
4717        if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;      if ( !tr1 || tr1->IsZombie() ) throw -22;
4718        //      tr2 = (TTree*)file->Get("CalibTrk2");
4719        // Do we have the second calibration packet?      if ( !tr2 || tr2->IsZombie() ) throw -23;
4720        //      //
4721        while ( t2t1cal < t1+1 ){ // get the calibration packet2 that follows the packet1      tr1->SetBranchAddress("CalibTrk1", &caltrk1);
4722          //      tr1->SetBranchAddress("Header", &eh1);
4723          t2++;      nevents1 = tr1->GetEntries();
4724          //      tr2->SetBranchAddress("CalibTrk2", &caltrk2);
4725          pret2 = t2 - 1; // EMILIANO      tr2->SetBranchAddress("Header", &eh2);
4726          //      nevents2 = tr2->GetEntries();
4727          if ( t2 < nevents2 ){      //
4728            tr2->GetEntry(t2);      if ( !nevents1 && !nevents2 ) return(1);
4729            codt2 = eh2->GetCounter();      //
4730            t2t1cal = codt2->Get(pctp->CalibTrk1);      t2 = -1;
4731            //      Int_t pret2 = 0;
4732            ph2 = eh2->GetPscuHeader();      Int_t t2t1cal = 0;
4733            obt2 = ph2->GetOrbitalTime();        //
4734            pkt2 = ph2->GetCounter();        bool MISSING_pkt1 = true;
4735            //      bool MISSING_pkt2 = true;
4736            if ( IsDebug() ) printf(" This is a trk calibration2 at obt %u pkt %u t2 is %u , t2t1cal is %u \n",obt2,pkt2,t2,t2t1cal);            int  ncalib = 0;
4737  //        if ( caltrk2->unpackError != 0 || caltrk2->good0 == 0 ) valid = 0; // CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT2      bool try_to_recover = false;
4738            //            //
4739          } else {      for (t1=0; t1 < nevents1; t1++){//loop over packet1
           //  
           // running out of vector without finding the corresponding calibration, sig  
           //  
           if ( IsDebug() ) printf(" t2 >= nevents2 \n");  
           pret2 = t2;  
           obt2 = 0;  
           //      pkt2 = pkt1+2;  
           pkt2 = 0;  
           t2t1cal = t1+1;  
         };  
         //      if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) && (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){  
   
         // 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(" 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;  
 //      };  
   
   
         //  
       };  
       //  
       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  
4740          //          //
4741          pret2 = t2;          pret2 = t2;
4742          obt2 = 0;          tr1->GetEntry(t1);
         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);  
4743          //          //
4744          UInt_t valid2 = ValidateTrkCalib( caltrk2, eh2 );          ph1 = eh1->GetPscuHeader();
4745          if ( IsDebug() ) cout << " pkt2 validation --> "<<valid2<<endl;          obt1 = ph1->GetOrbitalTime();  
4746          valid = valid & valid2;          pkt1 = ph1->GetCounter();  
4747            fromtime = GetAbsTime(ph1->GetOrbitalTime());  
4748          //          //
4749          // Handle good calib          // chek if the packet number and obt are consistent with the other packets ???
4750          //          //
4751          this->HandleTRK_CALIB(true,true);          if ( PKT(pkt1) >= PKT(pktfirst) && PKT(pkt1) <= upperpkt && OBT(obt1) >= OBT(obtfirst) && OBT(obt1) <= upperobt ){
4752          //              //    if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->OBT(obt1) >= this->OBT(obtfirst) ){
         // Check for missing calibtrk1  
         //  
         if ( t2 != pret2+1 ){  
           //  
           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);  
           //  
           while ( t2 > pret2+1 ){  
4753              //              //
4754              // handle missing calib1              if ( IsDebug() ) printf("\n Trk calibration1 %u at time %u obt %u pkt %u \n",t1,fromtime,obt1,pkt1);
4755                //      
4756                valid = ValidateTrkCalib( caltrk1, eh1 );
4757                if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;
4758              //              //
4759              pret2++;              // Do we have the second calibration packet?
4760                //
4761                if ( IsDebug() ) cout << " Loop over calibration2 to search associated calibration: "<<endl;
4762                while ( t2t1cal < t1+1 ){ // get the calibration packet2 that follows the packet1
4763                    //
4764                    t2++;
4765                    //
4766                    pret2 = t2 - 1; // EMILIANO
4767                    //
4768                    if ( t2 < nevents2 ){
4769                        tr2->GetEntry(t2);
4770                        codt2 = eh2->GetCounter();
4771                        t2t1cal = codt2->Get(pctp->CalibTrk1);
4772                        //
4773                        ph2 = eh2->GetPscuHeader();
4774                        obt2 = ph2->GetOrbitalTime();  
4775                        pkt2 = ph2->GetCounter();  
4776                        //
4777                        if ( IsDebug() ) printf(" >> trk calibration2 at obt %u pkt %u t2 is %u , t2t1cal is %u \n",obt2,pkt2,t2,t2t1cal);    
4778                        //    if ( caltrk2->unpackError != 0 || caltrk2->good0 == 0 ) valid = 0; // CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT2
4779                        //    
4780                    } else {
4781                        //
4782                        // running out of vector without finding the corresponding calibration, sig
4783                        //
4784                        if ( IsDebug() ) printf(" t2 >= nevents2 \n");
4785                        pret2 = t2;
4786                        obt2 = 0;
4787                        //    pkt2 = pkt1+2;
4788                        pkt2 = 0;
4789                        t2t1cal = t1+1;
4790                    };
4791                    //      if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) && (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){
4792    
4793                    // EMILIANO
4794                    //      if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) || (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){
4795                    //        //    if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){
4796                    //        if ( IsDebug() ) printf(" running out of vector without finding the corresponding calibration, sig \n");
4797                    //        //
4798                    //        // running out of vector without finding the corresponding calibration, sig
4799                    //        //
4800                    //        pret2 = t2;
4801                    //        obt2 = 0;
4802                    //        //      pkt2 = pkt1+2;
4803                    //        pkt2 = 0;
4804                    //        t2t1cal = t1+1;
4805                    //      };
4806    
4807    
4808                    //
4809                };
4810              //              //
4811              obt1 = 0;              if ( IsDebug() ) printf(" Check if trk calibration2 is the right one \n");
             pkt1 = 0;  
4812              //              //
4813              tr2->GetEntry(pret2);              // EMILIANO
4814              ph2 = eh2->GetPscuHeader();              if ( ( PKT(pkt2) < PKT(pktfirst) || PKT(pkt2) > upperpkt) || (OBT(obt2) < OBT(obtfirst) || OBT(obt2) > upperobt) ){
4815              obt2 = ph2->GetOrbitalTime();                    //      if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){
4816              pkt2 = ph2->GetCounter();                    if ( IsDebug() ) printf(" *WARNING*  The calibration found is outside the interval, sig \n");
4817                    //
4818                    // running out of vector without finding the corresponding calibration, sig
4819                    //
4820                    pret2 = t2;
4821                    obt2 = 0;
4822                    pkt2 = 0;
4823                };
4824                if ( PKT(pkt2) == PKT(pkt1)+1 ){
4825                    if ( IsDebug() ) cout << " ...OK"<<endl;
4826                    // =======================
4827                    // The calibration is good
4828                    // =======================
4829                    //
4830    //      if ( IsDebug() ) printf(" Found trk calibration2 at obt %u pkt %u t2 is %u \n",obt2,pkt2,t2);
4831    //      if ( IsDebug() ) printf(" Trk calibration2 at obt %u pkt %u t2 is %u is good \n",obt2,pkt2,t2);
4832    //        if ( IsDebug() ) printf("\n Trk calibration2 at time %u obt %u pkt %u \n",fromtime,obt2,pkt2);
4833                    if ( IsDebug() ) printf(" Trk calibration2 %u at time %u obt %u pkt %u \n",t2,fromtime,obt2,pkt2);
4834                    //
4835                    UInt_t valid2 = ValidateTrkCalib( caltrk2, eh2 );
4836                    if ( IsDebug() ) cout << " pkt2 validation --> "<<valid2<<endl;
4837    //      valid = valid & valid2;
4838                    valid = valid & valid2; //QUESTO VA CAMBIATO
4839                    //
4840                    // Handle good calib
4841                    //
4842                    MISSING_pkt1 = false;
4843                    MISSING_pkt2 = false;
4844    //              this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4845                    //
4846                    // Check for missing calibtrk1
4847                    //
4848                    if ( t2 != pret2+1 ){
4849                        //
4850                        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);
4851                        //
4852                        while ( t2 > pret2+1 ){
4853                            //
4854                            // handle missing calib1
4855                            //
4856                            pret2++;
4857                            //
4858                            obt1 = 0;
4859                            pkt1 = 0;
4860                            //
4861                            tr2->GetEntry(pret2);
4862                            ph2 = eh2->GetPscuHeader();
4863                            obt2 = ph2->GetOrbitalTime();  
4864                            pkt2 = ph2->GetCounter();  
4865                            //
4866                            fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
4867                            //
4868                            valid = 0;
4869                            MISSING_pkt1 = true;
4870                            MISSING_pkt2 = false;
4871    //                      this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4872                            //
4873                        };
4874                        //
4875                    };
4876                    //
4877                } else if ( this->PKT(pkt2) > this->PKT(pkt1)+1 ){
4878                    //
4879                    // Check for missing calibtrk2
4880                    //
4881                    if ( IsDebug() ) printf(" Missing the trk calibration2! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);
4882                    t2 = pret2;
4883                    //
4884                    // handle missing calib2
4885                    //
4886                    obt2 = 0;
4887                    pkt2 = 0;
4888                    valid = 0;
4889                    MISSING_pkt1 = false;
4890                    MISSING_pkt2 = true;
4891    //              this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4892                    //
4893                };
4894              //              //
4895              fromtime = this->GetAbsTime(ph2->GetOrbitalTime());          } else {
4896              //              //
4897              valid = 0;              if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u OUTSIDE the considered time interval \n",fromtime,obt1,pkt1);
4898              this->HandleTRK_CALIB(false,true);              //      if ( PEDANTIC ) throw -79;
4899              //              //
           };  
           //  
4900          };          };
4901            //    
4902    
4903            if( !(MISSING_pkt1&MISSING_pkt2) ){
4904                this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4905                ncalib++;
4906                if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
4907            }
4908    
4909        }; //end loop on pkt1
4910    
4911    
4912    
4913        //
4914        // we have one more calib pkt2 !
4915        //
4916        t2++;
4917        while ( t2 < nevents2 ){
4918          //          //
4919        } else if ( this->PKT(pkt2) > this->PKT(pkt1)+1 ){          // handle missing calib1
         //  
         // Check for missing calibtrk2  
4920          //          //
4921          if ( IsDebug() ) printf(" Missing the trk calibration2! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);          if ( IsDebug() ) printf(" t2 is %u nevents2 is %u \n",t2,nevents2);
4922          t2 = pret2;          obt1 = 0;
4923            pkt1 = 0;
4924          //          //
4925          // handle missing calib2          tr2->GetEntry(t2);
4926            ph2 = eh2->GetPscuHeader();
4927            obt2 = ph2->GetOrbitalTime();  
4928            pkt2 = ph2->GetCounter();  
4929          //          //
4930          obt2 = 0;          fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
         pkt2 = 0;  
4931          valid = 0;          valid = 0;
4932          this->HandleTRK_CALIB(true,false);                //  if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->PKT(pkt1) <= upperpkt && this->OBT(obt1) >= this->OBT(obtfirst) && this->OBT(obt1) <= upperobt ){
4933            // EMILIANO
4934            if ( this->PKT(pkt2) >= this->PKT(pktfirst) && this->PKT(pkt2 <= upperpkt) && this->OBT(obt2) >= this->OBT(obtfirst) && this->OBT(obt2) <= upperobt ){
4935                //    if ( this->PKT(pkt2) > this->PKT(pktfirst) || this->OBT(obt2) > this->OBT(obtfirst) ){
4936                //
4937                if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);
4938                //
4939                MISSING_pkt1 = true;
4940                MISSING_pkt2 = false;
4941                this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4942                ncalib++;
4943                if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
4944                //
4945            };
4946            //
4947            t2++;
4948          //          //
       };  
       //  
     } else {  
       //  
       if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u OUTSIDE the considered time interval \n",fromtime,obt1,pkt1);  
       //      if ( PEDANTIC ) throw -79;  
       //  
     };  
     //      
   };  
   //  
   // we have one more calib pkt2 !  
   //  
   t2++;  
   while ( t2 < nevents2 ){  
     //  
     // handle missing calib1  
     //  
     if ( IsDebug() ) printf(" t2 is %u nevents2 is %u \n",t2,nevents2);  
     obt1 = 0;  
     pkt1 = 0;  
     //  
     tr2->GetEntry(t2);  
     ph2 = eh2->GetPscuHeader();  
     obt2 = ph2->GetOrbitalTime();    
     pkt2 = ph2->GetCounter();    
     //  
     fromtime = this->GetAbsTime(ph2->GetOrbitalTime());  
     valid = 0;  
 //  if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->PKT(pkt1) <= upperpkt && this->OBT(obt1) >= this->OBT(obtfirst) && this->OBT(obt1) <= upperobt ){  
  // 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(" Missing the trk calibration1! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);  
       //  
       this->HandleTRK_CALIB(false,true);  
       //  
4949      };      };
4950      //  
4951      t2++;  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
4952      //  // -----------------------------------------------------------------
4953    };  // in case of corruption, check if the calibration can be recovered
4954    // from another chewbacca file
4955    // -----------------------------------------------------------------
4956    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
4957    
4958    //    cout <<" TRY TO RECOVER ?? "<<try_to_recover<<endl;
4959        
4960        if(chewbacca&&try_to_recover){
4961    
4962    
4963            if ( IsDebug() ) cout << endl << ">>>> TRY TO RECOVER TRACKER CALIBRATIONS <<<<"<<endl;
4964    
4965            TSQLResult *result = 0;
4966            TSQLRow    *row    = 0;
4967            //
4968            stringstream oss;
4969            oss.str("");
4970            //
4971    
4972            ////////////////////////////////////////////////////////////////////////
4973            // retrieve the name of the current file:
4974            ////////////////////////////////////////////////////////////////////////        
4975            oss.str("");
4976            oss << "SELECT NAME FROM GL_ROOT where ID=" << GetID_ROOT() <<";";
4977            if ( IsDebug() ) cout << oss.str().c_str() << endl;
4978    
4979            result = conn->Query(oss.str().c_str());
4980            if ( !result ) throw -4;;
4981            row = result->Next();
4982            TString thisfilename = (TString)row->GetField(0);
4983            if ( IsDebug() ) cout << "Current file ==> "<<thisfilename<<endl;      
4984    
4985            ////////////////////////////////////////////////////////////////////////        
4986            // read all the calibrations inserted
4987            ////////////////////////////////////////////////////////////////////////        
4988            oss.str("");
4989            oss << " SELECT ";
4990            oss << " ID,FROM_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,TO_TIME";
4991            oss << " FROM GL_TRK_CALIB ";
4992            oss << " ORDER BY ID DESC LIMIT "<<ncalib<<"; ";        
4993            if ( IsDebug() ) cout << oss.str().c_str() << endl;
4994    
4995            result = conn->Query(oss.str().c_str());
4996            if ( !result ) throw -4;;
4997            if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
4998            
4999            // -----------------------------------
5000            // loop over calibrations ...
5001            // -----------------------------------
5002            UInt_t nn=0;
5003            do {
5004                row = result->Next();
5005                if(!row)break;
5006                
5007                UInt_t id       = (UInt_t)atoll(row->GetField(0));
5008                UInt_t fromtime = (UInt_t)atoll(row->GetField(1));
5009                UInt_t obt1     = (UInt_t)atoll(row->GetField(2));
5010                UInt_t pkt1     = (UInt_t)atoll(row->GetField(3));
5011                UInt_t obt2     = (UInt_t)atoll(row->GetField(4));
5012                UInt_t pkt2     = (UInt_t)atoll(row->GetField(5));
5013                UInt_t boot     = (UInt_t)atoll(row->GetField(6));
5014                UInt_t valid    = (UInt_t)atoll(row->GetField(7));
5015                bool MISSING_pkt1 = (row->GetFieldLength(8)==0);
5016                bool MISSING_pkt2 = (row->GetFieldLength(9)==0);
5017                UInt_t totime   = (UInt_t)atoll(row->GetField(10));
5018    
5019                // -------------------------------------
5020                // ...check if the entry is corrupted...
5021                // -------------------------------------
5022                cout <<"*** "<< MISSING_pkt1 << MISSING_pkt2 << valid <<endl;
5023                bool CORRUPTED = (MISSING_pkt1||MISSING_pkt2||!valid);
5024    
5025                if ( IsDebug() ) cout << "("<<nn<<")  ID = "<<id<<" from GL_TRK_CALIB  ==>  corrupted ? "<<CORRUPTED<<endl;
5026    
5027    //          if( !CORRUPTED  )continue; // nothing to do
5028    
5029                /////////////////////////////////////////////////////////  
5030                // if it is corrupted, ...look for ather chewbacca files
5031                // containing the same calibrations ...
5032                /////////////////////////////////////////////////////////
5033    
5034                bool this_MISSING_pkt1 = false;
5035                bool this_MISSING_pkt2 = false;
5036                int  this_t1=0;
5037                int  this_t2=0;;
5038                UInt_t this_valid = 0;
5039    
5040                TString path       = "";
5041                TString name       = "";
5042                TString raw        = "";
5043                UInt_t obt0        = 0;
5044                UInt_t timesync    = 0;
5045                UInt_t boot_number = 0;
5046                bool   FOUND       = false;
5047    
5048                if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
5049    
5050    //          for(int itable=0; itable<2; itable++){
5051                for(int itable=0; itable<1; itable++){
5052    
5053                    // ------------------------------------------------------
5054                    // loop over both ROOT_TABLE and ROOT_TABLE_BAD
5055                    // ------------------------------------------------------
5056    
5057                    TString table = "ROOT_TABLE";
5058                    if(itable==1)table = "ROOT_TABLE_BAD";
5059    
5060                    oss.str("");
5061                    oss << " SELECT ";
5062                    oss << " FOLDER_NAME,FILE_NAME,OBT_TIME_SYNC,LAST_TIME_SYNC_INFO,BOOT_NUMBER,INPUT_NAME ";
5063                    oss << " FROM "<<table;
5064                    oss << " WHERE 1 " << endl;
5065                    oss << " AND FILE_NAME != \""<< thisfilename<<"\"";
5066                    if( !MISSING_pkt1 ){
5067                        oss << " AND ";
5068                        oss << " PKT_NUMBER_INIT < "<<pkt1;
5069                        oss << " AND ";
5070                        oss << " PKT_NUMBER_FINAL > "<<pkt1;
5071                        oss << " AND ";
5072                        oss << " PKT_OBT_INIT < "<<obt1;
5073                        oss << " AND ";
5074                        oss << " PKT_OBT_FINAL > "<<obt1;
5075                    }else{
5076                        if(pkt2>1) pkt1 = pkt2-1;//serve dopo                  
5077                    }
5078                    if( !MISSING_pkt2 ){
5079                        oss << " AND ";
5080                        oss << " PKT_NUMBER_INIT < "<<pkt2;
5081                        oss << " AND ";
5082                        oss << " PKT_NUMBER_FINAL > "<<pkt2;
5083                        oss << " AND ";
5084                        oss << " PKT_OBT_INIT < "<<obt2;
5085                        oss << " AND ";
5086                        oss << " PKT_OBT_FINAL > "<<obt2;
5087                    }else{
5088                        if(pkt1>0) pkt2 = pkt1+1;//serve dopo
5089                    }
5090                    if( boot> 0 ){
5091                        oss << " AND ";
5092                        oss << " BOOT_NUMBER = "<<boot;
5093                    }else{
5094                    }
5095                    oss << " ORDER BY BAD_PKT_CALREAD ASC; ";
5096                
5097                    TSQLResult *result2 = 0;
5098                    TSQLRow    *row2    = 0;
5099    
5100                    if ( IsDebug() ) cout << oss.str().c_str() << endl;        
5101                    result2 = conn->Query(oss.str().c_str());
5102                    if ( !result2 ) throw -4;;
5103                    if ( IsDebug() ) cout <<"Rows: "<<result2->GetRowCount()<<endl;
5104    
5105                    // ------------------------------------------------------
5106                    // loop over files containing repetition (if any)
5107                    // ------------------------------------------------------
5108                    do {
5109                        row2 = result2->Next();
5110                        if(!row2)break;
5111                    
5112                        // ------------------------------------------------------
5113                        // ... a repetition is found ...
5114                        // ------------------------------------------------------
5115                        path       = (TString)row2->GetField(0);
5116                        name       = (TString)row2->GetField(1);
5117                        raw        = (TString)row2->GetField(5);
5118                        obt0        = (UInt_t)atoll(row2->GetField(2));
5119                        timesync    = (UInt_t)atoll(row2->GetField(3));
5120                        boot_number = (UInt_t)atoll(row2->GetField(4));
5121                    
5122                        if ( IsDebug() ) cout << "- - - - - - - - - - -" <<endl;
5123    //                  cout << path <<endl;
5124    //                  cout << "File    : " <<name <<endl;
5125    //                  cout << obt0 <<endl;
5126    //                  cout << timesync <<endl;
5127    //                  cout << "boot n. : "<<boot_number <<endl;
5128    //                  cout << raw <<endl;
5129    
5130                        // ------------------------------------------------------
5131                        // ... retrieve the calibration packets.
5132                        // ------------------------------------------------------
5133                        TFile *file = new TFile((TString)gSystem->ExpandPathName(path)+"/"+name); // EM, path could be symbolic and we must expand it
5134                        if(!file)throw -100;
5135                        if(file->IsZombie())throw -100;
5136                        //
5137                        tr1 = (TTree*)file->Get("CalibTrk1");
5138                        if ( !tr1 || tr1->IsZombie() ) throw -22;
5139                        tr2 = (TTree*)file->Get("CalibTrk2");
5140                        if ( !tr2 || tr2->IsZombie() ) throw -23;
5141                        //
5142                        tr1->SetBranchAddress("CalibTrk1", &caltrk1);
5143                        tr1->SetBranchAddress("Header", &eh1);
5144                        nevents1 = tr1->GetEntries();
5145                        tr2->SetBranchAddress("CalibTrk2", &caltrk2);
5146                        tr2->SetBranchAddress("Header", &eh2);
5147                        nevents2 = tr2->GetEntries();
5148                        for(this_t1=0; this_t1<nevents1; this_t1++){
5149                            tr1->GetEntry(this_t1);
5150                            if(
5151                                (UInt_t)eh1->GetPscuHeader()->GetCounter() == pkt1 &&
5152                                true) break;
5153                            this_MISSING_pkt1 = true;
5154                        }
5155                        for(this_t2=0; this_t2<nevents2; this_t2++){
5156                            tr2->GetEntry(this_t2);
5157                            if(
5158                                (UInt_t)eh2->GetPscuHeader()->GetCounter() == pkt2 &&
5159                                true) break;
5160                            this_MISSING_pkt2 = true;
5161                        }
5162                        this_valid =
5163                            ValidateTrkCalib( caltrk1, eh1, file )
5164                            *
5165                            ValidateTrkCalib( caltrk2, eh2, file );
5166                                
5167                        // ---------------------------------------------------------------------
5168                        // accept the calibration if it is better than the previous:
5169                        //
5170                        // - if the new calibration is perfect (both valid packets)
5171                        // - if the new calibration has both the packets and the previous does not
5172                        // ---------------------------------------------------------------------
5173                        if(
5174                            ( !this_MISSING_pkt1&&!this_MISSING_pkt2&&this_valid )||
5175                            ( (MISSING_pkt1||MISSING_pkt2) && (!this_MISSING_pkt1&&!this_MISSING_pkt2) )||
5176                            false)FOUND=true;      
5177                
5178                        if(file)file->Close();
5179    
5180                        if(FOUND)break;
5181    
5182                    }while(1);//endl loop over root table entries
5183    
5184                    if(FOUND)break;
5185    
5186                }//end loop over tables
5187    
5188                if(FOUND){
5189    
5190                if ( IsDebug() ) cout << " >>> REPETITION FOUND :-) <<<" <<endl;
5191    
5192                    ////////////////////////////////////////////
5193                    // insert a new entry in GL_TRK_CALIB and
5194                    // modify the time-tag of the previous one
5195                    ////////////////////////////////////////////
5196    
5197                    // ---------------------------------------------------------------------
5198                    // step 1: insert a new raw file in GL_RAW
5199                    // ---------------------------------------------------------------------
5200                    //
5201                    // check if the raw file already exist
5202                    //
5203                    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
5204    //              oss.str("");
5205    //              oss << "SELECT ID FROM GL_RAW where NAME=\"" << gSystem->BaseName(raw.Data()) <<"\";";
5206    //              if ( IsDebug() ) cout << oss.str().c_str() << endl;
5207                    
5208    //              result = conn->Query(oss.str().c_str());
5209    //              if ( !result ) throw -4;;
5210    //              if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5211    //              if( result->GetRowCount() == 0){
5212    //                  if ( IsDebug() ) cout << " << Insert new RAW file >> "<<endl;
5213    //                  // - - - - - - - - - - -
5214    //                  // insert new raw file
5215    //                  // - - - - - - - - - - -
5216    //                  GL_RAW glraw = GL_RAW();    
5217    //                  glraw.PATH        = gSystem->DirName(raw.Data());
5218    //                  glraw.NAME        = gSystem->BaseName(raw.Data());
5219    //                  glraw.BOOT_NUMBER = boot_number;
5220    //                  //
5221    //                  insertPamelaRawFile( &glraw );
5222    //                  //              
5223    //                  id_raw = glraw.ID;              
5224    //              }else{
5225    //                  row = result->Next();
5226    //                  id_raw = (UInt_t)atoll(row->GetField(0));
5227    //              }
5228    //              if ( IsDebug() ) cout << "ID_RAW = "<<id_raw<<endl;
5229    
5230                    // ---------------------------------------------------------------------
5231                    // step 1(bis): retrieve the timesync id associated to the file
5232                    // (NB, uso lo stesso associato al file iniziale)
5233                    // ---------------------------------------------------------------------
5234                    UInt_t idtimesync = 0;
5235                    oss.str("");
5236                    oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" limit 1;";
5237                    if ( debug ) printf(" %s \n",oss.str().c_str());
5238                    result = conn->Query(oss.str().c_str());
5239                    if ( !result ) throw -3;
5240                    row = result->Next();
5241                    if ( !row ) throw -3;
5242                    idtimesync = (UInt_t)atoll(row->GetField(0));
5243                    if ( IsDebug() ) cout << "ID_TIMESYNC = "<<idtimesync<<endl;
5244                    
5245                    // ---------------------------------------------------------------------
5246                    // step 2: insert a new root file in GL_ROOT
5247                    // ---------------------------------------------------------------------
5248                    //
5249                    // check if the root file already exist
5250                    //
5251                    UInt_t id_root = 0;
5252                    oss.str("");
5253                    oss << "SELECT ID FROM GL_ROOT where NAME=\"" << gSystem->BaseName(name.Data()) <<"\";";
5254                    if ( IsDebug() ) cout << oss.str().c_str() << endl;
5255                    
5256                    result = conn->Query(oss.str().c_str());
5257                    if ( !result ) throw -4;;
5258                    if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5259                    if( result->GetRowCount() == 0){
5260                        if ( IsDebug() ) cout << " << Insert new ROOT file >> "<<endl;
5261                        // - - - - - - - - - - -
5262                        // insert new root file
5263                        // - - - - - - - - - - -
5264                        GL_ROOT glroot = GL_ROOT();            
5265                        glroot.ID_RAW      = id_raw;
5266                        glroot.ID_TIMESYNC = idtimesync;
5267                        //
5268                        // 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,
5269                        //             NOT STATIC NOT KEEPENV = $PAM_L0 must be used in the DB
5270                        //
5271                        if ( STATIC ){
5272                          glroot.PATH        = (TString)gSystem->ExpandPathName(path);
5273                        } else {
5274                          if ( KEEPENV ){
5275                            glroot.PATH      = path;
5276                          } else {
5277                            glroot.PATH      = "$PAM_L0";
5278                          };
5279                        };
5280                        //              glroot.PATH        = path;
5281                        glroot.NAME        = name;
5282                        //
5283                        insertPamelaRootFile( &glroot );
5284                        //              
5285                        id_root = glroot.ID;                    
5286                    }else{
5287                        row = result->Next();
5288                        if(row)id_root = (UInt_t)atoll(row->GetField(0));
5289                    }
5290                    if ( IsDebug() ) cout << "ID_ROOT = "<<id_root<<endl;
5291    
5292                    // ---------------------------------------------------------------------
5293                    // step 3: modify time-tag of corrupted GL_TRK_CALIB entry
5294                    // ---------------------------------------------------------------------
5295                    if ( IsDebug() ) cout << " << Modify time-tag of calibration ID="<<id<<" >> "<<endl;
5296                    oss.str("");
5297                    oss << " UPDATE GL_TRK_CALIB SET "  
5298                        << " TO_TIME=0 , FROM_TIME=0  WHERE "
5299                        << " ID = "<< id  << ";";
5300                    if ( IsDebug() ) cout << oss.str().c_str() << endl;
5301                    result = conn->Query(oss.str().c_str());
5302                    if ( !result ) throw -4;;
5303    
5304                    // ---------------------------------------------------------------------
5305                    // step 4: insert the new calibration:
5306                    // ---------------------------------------------------------------------
5307                    if ( IsDebug() ) cout << " << Insert new TRK calibration >> "<<endl;
5308                    //
5309                    GL_TRK_CALIB glcal = GL_TRK_CALIB();        
5310                    //
5311                    glcal.ID_ROOT_L0        = id_root;
5312                    glcal.EV_ROOT_CALIBTRK1 = this_t1;
5313                    glcal.EV_ROOT_CALIBTRK2 = this_t2;
5314                    glcal.FROM_TIME         = fromtime;
5315                    glcal.TO_TIME           = totime;
5316                    glcal.OBT1              = obt1;
5317                    glcal.OBT2              = obt2;
5318                    glcal.PKT1              = pkt1;
5319                    glcal.PKT2              = pkt1;
5320                    glcal.BOOT_NUMBER       = GetBOOTnumber();
5321                    glcal.VALIDATION        = this_valid;
5322                    //
5323                    HandleTRK_CALIB(&glcal);
5324                    if ( IsDebug() ) cout << "ID = "<<glcal.ID<<endl;
5325                    //
5326                    
5327                }
5328                if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
5329    
5330            }while(1);//end loop over calibrations
5331            
5332            
5333            if( result )delete result;
5334            if( row    )delete row;
5335            
5336            
5337    
5338            
5339    
5340    
5341        }
5342    
5343    
5344    //      // ------------------------------
5345    //      // try to recover the calibration
5346    //      // ------------------------------
5347    //      cout << "TRY TO RECOVER TRACKER CALIBRATION"<<endl;
5348    //      //
5349    //      ULong64_t time  = 0; //absolute time
5350    //      string    path[100]; //mettere un limite massimo
5351    //      int       nrows = 0;
5352    //      UInt_t    pkt   = 0;
5353    //      UInt_t    obt   = 0;
5354    //      char     *type  = "";
5355    //      EventHeader *eh   = new EventHeader();
5356    //      CalibTrk1Event *c = new CalibTrk1Event();
5357            
5358    //       //
5359    //       if(which_is_not_valid==1 || which_is_not_valid==3){
5360    //        //
5361    //        cout << "PKT1 --> missing or corrupted "<<endl;
5362    //        type = "CalibTrk1";
5363    //        pkt  = pkt1;
5364    //        obt  = obt1;
5365    //        time = this->GetAbsTime(obt1);
5366    //        if( pkt1 == 0 ){//missing
5367    //            time = this->GetAbsTime(obt2);
5368    //            pkt  = pkt2-1;          
5369    //        }
5370    //        //
5371    //       }else if (which_is_not_valid==2 || which_is_not_valid==3){
5372    //        //
5373    //        cout << "PKT2--> missing or corrupted "<<endl;
5374    //        type = "CalibTrk2 ";
5375    //        pkt  = pkt2;
5376    //        obt  = obt2;
5377    //        time = this->GetAbsTime(obt2);
5378    //        if( pkt2 == 0 ){//missing
5379    //            time = this->GetAbsTime(obt1);
5380    //            pkt  = pkt1+1;          
5381    //        }
5382    //        //
5383    //       }else{
5384    //        cout << "this should not happen!!! "<<endl;
5385    //        trow -666;
5386    //       }
5387          
5388    //       nrows = Query_ROOT_TABLE(time,conn,path);// get the list of file which might contain the packet
5389          
5390    
5391    //       for(int r=0; r<nrows; r++){ //loop over rows
5392    //        if(path)cout << r << " >>>> "<<(path+r)->c_str() << endl;
5393    //        /// verifica che il file non sia quello gia` aperto
5394    //       }
5395    
5396    //       ////////////////////////////////////////////////////////////////////////
5397    
5398    //       TSQLResult *result = 0;
5399    //       TSQLRow    *row    = 0;
5400    //       //
5401    //       stringstream oss;
5402    //       oss.str("");
5403    //       // ----------------------------------------
5404    //       // read the id of last calibration inserted
5405    //       // ----------------------------------------
5406    //       oss.str("");
5407    //       oss << " SELECT ";
5408    //       oss << " (ID,ID_ROOT_L0,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,FROM_TIME,TO_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION) ";
5409    //       oss << " ORDER BY ID DESC LIMIT 1; ";
5410          
5411    //       result = conn->Query(oss.str().c_str());
5412    //       row = result->Next();
5413    //       if( !row )throw -666;
5414    
5415    //       if( result )delete result;
5416    //       if( row    )delete row;
5417    
5418    //       UInt_t id = (UInt_t)atoll(row->GetField(0));
5419    
5420    //       // -------------------------------------
5421    //       // ...and modify it with new parameters
5422    //       // -------------------------------------
5423          
5424    
5425    //   }
5426    //    //
5427    return(0);    return(0);
5428  };  };
# Line 5061  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 5725  Int_t PamelaDBOperations::CleanGL_RUN_FR
5725                    << " RM_ACQ_SETTING_MODE=" << glrun->GetRM_ACQ_SETTING_MODE()<< " , "                      << " RM_ACQ_SETTING_MODE=" << glrun->GetRM_ACQ_SETTING_MODE()<< " , "  
5726                    << " TRK_CALIB_USED=" << glrun->GetTRK_CALIB_USED()<< " , "                      << " TRK_CALIB_USED=" << glrun->GetTRK_CALIB_USED()<< " , "  
5727                    << " CAL_DSP_MASK=" << glrun->GetCAL_DSP_MASK()<< " , "                      << " CAL_DSP_MASK=" << glrun->GetCAL_DSP_MASK()<< " , "  
5728                    << " LAST_TIMESYNC=" << glrun->GetLAST_TIMESYNC()<< " , "                      << " LAST_TIMESYNC=" << glrun->GetLAST_TIMESYNC()<< " , ";
5729                    << " OBT_TIMESYNC=" << glrun->GetOBT_TIMESYNC()                //
5730                    << " WHERE ID=" << myid[u] << ";";                if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
5731                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12() << " , ";
5732                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
5733                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC() << " , ";
5734                  //              
5735                  oss << " OBT_TIMESYNC=" << glrun->GetOBT_TIMESYNC();
5736                  oss << " WHERE ID=" << myid[u] << ";";
5737                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
5738              };              };
5739              //              //
# Line 5074  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 5744  Int_t PamelaDBOperations::CleanGL_RUN_FR
5744              for (UInt_t u=1; u <= nid ; u++){              for (UInt_t u=1; u <= nid ; u++){
5745                oss.str("");                oss.str("");
5746                oss << "UPDATE GL_RUN_FRAGMENTS SET "                oss << "UPDATE GL_RUN_FRAGMENTS SET "
5747                    << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , "                    << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , ";
5748                    << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "                //
5749                  if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
5750                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , ";
5751                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
5752                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , ";
5753                  //              
5754                  oss << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "
5755                    << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT()<< ";";                    << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT()<< ";";
5756                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
5757              };                  };    
# Line 5098  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 5774  Int_t PamelaDBOperations::CleanGL_RUN_FR
5774                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
5775                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "
5776                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< " , "                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< " , "
5777                    << " PKT_COUNTER=" << glrun->GetPKT_COUNTER()<< " , "                    << " PKT_COUNTER=" << glrun->GetPKT_COUNTER()<< " , ";
5778                    << " PKT_READY_COUNTER=" << glrun->GetPKT_READY_COUNTER()                //
5779                  if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
5780                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
5781                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) {
5782                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
5783                  //              
5784                  oss << " PKT_READY_COUNTER=" << glrun->GetPKT_READY_COUNTER()
5785                    << " WHERE ID=" << myid[u] << ";";                    << " WHERE ID=" << myid[u] << ";";
5786                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
5787              };              };
# Line 5112  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 5794  Int_t PamelaDBOperations::CleanGL_RUN_FR
5794                oss.str("");                oss.str("");
5795                oss << "UPDATE GL_RUN_FRAGMENTS SET "                oss << "UPDATE GL_RUN_FRAGMENTS SET "
5796                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
5797                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , ";
5798                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< ";";                //
5799                  if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
5800                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
5801                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ){
5802                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
5803                  //              
5804                  oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< ";";
5805                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
5806              };                  };    
5807            };            };
# Line 5272  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 5960  Int_t PamelaDBOperations::CleanGL_RUN_FR
5960          glrun->SetID_RUN_FRAG(glrun->GetID());          glrun->SetID_RUN_FRAG(glrun->GetID());
5961          glrun->Fill_GL_RUN(conn);            glrun->Fill_GL_RUN(conn);  
5962          //          //
5963  //      oss.str("");          //      oss.str("");
5964  //      oss << " SELECT ID FROM GL_RUN WHERE "          //      oss << " SELECT ID FROM GL_RUN WHERE "
5965  //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "          //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
5966  //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "          //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
5967  //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "          //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
5968  //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "          //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
5969  //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";          //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
5970  //      //          //      //
5971  //      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());
5972  //      result2 = conn->Query(oss.str().c_str());          //      result2 = conn->Query(oss.str().c_str());
5973  //      //          //      //
5974  //      if ( !result2 ) throw -4;          //      if ( !result2 ) throw -4;
5975  //      //          //      //
5976  //      row2 = result2->Next();          //      row2 = result2->Next();
5977  //      //          //      //
5978  //      if ( !row2 ) throw -25;          //      if ( !row2 ) throw -25;
5979  //      //          //      //
5980  //      oss.str("");          //      oss.str("");
5981  //      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);
5982  //      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());
5983  //      result2 = conn->Query(oss.str().c_str());          //      result2 = conn->Query(oss.str().c_str());
5984  //      //          //      //
5985  //      if ( !result2 ) throw -4;          //      if ( !result2 ) throw -4;
5986          //          //
5987          moved++;          moved++;
5988          //          //
# Line 5306  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 5994  Int_t PamelaDBOperations::CleanGL_RUN_FR
5994        //        //
5995        //        //
5996        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
5997  //      oss.str("");        //      oss.str("");
5998  //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);        //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);
5999  //       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());
6000  //       result2 = conn->Query(oss.str().c_str());        //       result2 = conn->Query(oss.str().c_str());
6001  //      //        //      //
6002  //      if ( !result2 ) throw -4;        //      if ( !result2 ) throw -4;
6003  //      //        //      //
6004        row = result->Next();        row = result->Next();
6005      };      };
6006    };    };
# Line 5457  Int_t PamelaDBOperations::ValidateRuns(T Line 6145  Int_t PamelaDBOperations::ValidateRuns(T
6145    GL_RUN* this_run = new GL_RUN();    GL_RUN* this_run = new GL_RUN();
6146    GL_RUN* next_run = new GL_RUN();    GL_RUN* next_run = new GL_RUN();
6147    Int_t   nseq_max = 1000;    Int_t   nseq_max = 1000;
6148  //  UInt_t* sequence = new UInt_t[100];    //  UInt_t* sequence = new UInt_t[100];
6149    vector<UInt_t> sequence(nseq_max);    vector<UInt_t> sequence(nseq_max);
6150    Int_t   nseq = 0;    Int_t   nseq = 0;
6151    Bool_t CHECK = false;    Bool_t CHECK = false;
# Line 5472  Int_t PamelaDBOperations::ValidateRuns(T Line 6160  Int_t PamelaDBOperations::ValidateRuns(T
6160    // ---------------------------------------------------------------------------------    // ---------------------------------------------------------------------------------
6161    while(1){    while(1){
6162                        
6163            row = result->Next();      row = result->Next();
6164            if( row == NULL ) break;      if( row == NULL ) break;
6165                        
6166            //------------      //------------
6167            //get run info      //get run info
6168            //------------      //------------
6169            this_run->Set_GL_RUN(row);      this_run->Set_GL_RUN(row);
6170                                        
6171            Bool_t this_BAD = false;      Bool_t this_BAD = false;
6172            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;
6173            else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;      else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;
6174            else{      else{
6175  //                printf("Missing or corrupted header!! \n");        //                  printf("Missing or corrupted header!! \n");
6176                    this_ONLINE = false;        this_ONLINE = false;
6177                    this_BAD = true;        this_BAD = true;
6178            };      };
6179    
6180            //-----------------------------------      //-----------------------------------
6181            //compare with previous(next in time)      //compare with previous(next in time)
6182            //-----------------------------------      //-----------------------------------
6183            CHECK = false;      CHECK = false;
6184            UInt_t interval=0;      UInt_t interval=0;
6185                        
6186            if( nrow != 0){      if( nrow != 0){
6187                    
6188                                        
6189                    t1 = this_run->GetRUNTRAILER_TIME();        t1 = this_run->GetRUNTRAILER_TIME();
6190                    t2 = next_run->GetRUNHEADER_TIME();        t2 = next_run->GetRUNHEADER_TIME();
6191                    interval = (t2-t1);        interval = (t2-t1);
6192                                        
6193                    if(this_ONLINE && next_ONLINE){                               // this: ON-LINE + next: ON-LINE        if(this_ONLINE && next_ONLINE){                           // this: ON-LINE + next: ON-LINE
6194                                                        
6195                            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
6196                                                        
6197                            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
6198                                                        
6199                            if( !CHECK && this_run->VALIDATION ){          if( !CHECK && this_run->VALIDATION ){
6200                                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);            for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
6201                                    nseq=0;            nseq=0;
6202                            }          }
6203                                        
6204                    }else if( !this_ONLINE && next_ONLINE) {              // this: DEFAULT + next:ON-LINE        }else if( !this_ONLINE && next_ONLINE) {          // this: DEFAULT + next:ON-LINE
6205                                                        
6206                            CHECK = true;          CHECK = true;
6207    
6208                    }else if( !next_ONLINE ){                                             // this:ANY + next:DEFAULT        }else if( !next_ONLINE ){                                         // this:ANY + next:DEFAULT
6209                                                        
6210                            assignVALIDATION(next_run->ID,true);          assignVALIDATION(next_run->ID,true);
6211                            nseq=0;          nseq=0;
6212                    }        }
6213            }      }
6214    
6215            //----------------------------      //----------------------------
6216            //check run sequence for calib      //check run sequence for calib
6217            //----------------------------      //----------------------------
6218            if( CHECK ){      if( CHECK ){
6219                    // check if calibration exists        // check if calibration exists
6220                    if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);        if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);
6221                    Bool_t MISSING = MissingTRK_CALIB(t1,t2);        Bool_t MISSING = MissingTRK_CALIB(t1,t2);
6222                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],!MISSING);        for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],!MISSING);
6223                    nseq=0;        nseq=0;
6224            };      };
6225            //--------------      //--------------
6226            //store run info      //store run info
6227            //--------------      //--------------
6228            *next_run   = *this_run;      *next_run   = *this_run;
6229            next_ONLINE = this_ONLINE;      next_ONLINE = this_ONLINE;
6230            if( !this_BAD ){      if( !this_BAD ){
6231                    if(nseq < nseq_max){        if(nseq < nseq_max){
6232                            sequence[nseq] = this_run->ID;          sequence[nseq] = this_run->ID;
6233                            nseq++;          nseq++;
6234                    }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);        }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);
6235            };      };
6236                        
6237            if ( IsDebug() ) printf("%i Run %u \n",nrow,this_run->ID);      if ( IsDebug() ) printf("%i Run %u \n",nrow,this_run->ID);
6238            nrow++;      nrow++;
6239                        
6240    };    };
6241    delete this_run;    delete this_run;
# Line 5563  Int_t PamelaDBOperations::ValidateRuns(T Line 6251  Int_t PamelaDBOperations::ValidateRuns(T
6251   */   */
6252  Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){  Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
6253                    
6254          GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();    GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();
6255                    
6256          // get the closest VALIDATED calibration before the run start (t2)    // get the closest calibration before the run start (t2)
6257          if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true);      //>>> missing    if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true);    //>>> missing
6258                    
6259          if ( trkcalib->TO_TIME  < t2 ) return(true);                                    //>>> missing    if ( trkcalib->TO_TIME  < t2 ) return(true);                                  //>>> missing
6260                    
6261          //==============================================================    //==============================================================
6262          // Check is done first on the basis of time between calibration,    // Check is done first on the basis of time between calibration,
6263          // which should be equal to the time between ascending-nodes.    // which should be equal to the time between ascending-nodes.
6264          //==============================================================    //==============================================================
6265          if ( t2 - trkcalib->FROM_TIME > 5700) {    if ( t2 - trkcalib->FROM_TIME > 5700) {
6266                  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);
6267          //==============================================================      //==============================================================
6268          // there might be a missing calibration, due to:      // there might be a missing calibration, due to:
6269          // - MM full      // - MM full
6270          // - corrupted packets      // - corrupted packets
6271          // - loss of data      // - loss of data
6272          // 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
6273          //==============================================================      //==============================================================
6274                  Bool_t DOWNLOAD = false;      Bool_t DOWNLOAD = false;
6275                  // check if the calib was skipped becouse of download .... DA FARE!!      // check if the calib was skipped becouse of download .... DA FARE!!
6276                  if(DOWNLOAD)return(false);      if(DOWNLOAD)return(false);
6277                                    
6278                  return(true);                                   //>>> missing      return(true);                                       //>>> missing
6279                                    
6280          };    };
6281                    
6282          //==============================================================    //==============================================================
6283          // 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,
6284          // it is enough to say that there are no missing calibrations    // it is enough to say that there are no missing calibrations
6285          //==============================================================    //==============================================================
6286          // the long time interval bewteen runs might be due to download    // the long time interval bewteen runs might be due to download
6287          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);
6288          return(false);    return(false);
6289                    
6290  };  };
6291  /**  /**
# Line 5606  Bool_t PamelaDBOperations::MissingTRK_CA Line 6294  Bool_t PamelaDBOperations::MissingTRK_CA
6294   * @param validation true/false   * @param validation true/false
6295   */   */
6296  Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){  Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){
6297          TSQLResult *result = 0;    TSQLResult *result = 0;
6298          stringstream oss;    stringstream oss;
6299          oss.str("");    oss.str("");
6300          oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";    oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";
6301          //    //
6302  //      if ( IsDebug() )    //    if ( IsDebug() )
6303  //      printf(" Set VALIDATION = %i for run %i \n",validation,idrun);    //    printf(" Set VALIDATION = %i for run %i \n",validation,idrun);
6304          if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());    if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());
6305          result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
6306          if ( !result ) throw -4;    if ( !result ) throw -4;
6307          return(0);    return(0);
6308  }  }
6309    
6310    
# Line 6259  void PamelaDBOperations::RemoveCALIBS(){ Line 6947  void PamelaDBOperations::RemoveCALIBS(){
6947   * Rearrange calibration tables   * Rearrange calibration tables
6948   *   *
6949   **/   **/
6950  UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh ){  UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh , TFile *file){
6951    
6952        if(!caltrk) return 0;
6953    
6954        if ( IsDebug() ) cout << "ValidateTrkCalib:"<<endl;
6955    
6956        UInt_t validate = 1;
6957      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};
6958      UInt_t timeaftercalib=120000; //2000;      UInt_t timeaftercalib=120000; //2000;
6959  //  ----------      TString classname = caltrk->GetName();
6960  //  Check CRCs  
6961  //  ----------  //  ----------------------------------
6962    //  Check CRCs and failed calibrations
6963    //  ----------------------------------
6964      for(Int_t ipkt=0; ipkt<6; ipkt++){      for(Int_t ipkt=0; ipkt<6; ipkt++){
6965          if( caltrk->crc_hcal[ipkt] )return 0; // :-(          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
6966          for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] )return 0; // :-(              if( caltrk->crc_hcal[ipkt] ){
6967    //              if(IsDebug())cout<<"(CRC Header)";
6968                    validate = 0;
6969                    if(IsDebug())cout <<endl<<" *** CRC *** (header DSPn "<<caltrk->DSPnumber[ipkt]<<")";
6970            
6971                }
6972                for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] ){
6973    //              if(IsDebug())cout<<"(CRC Pkt-"<<ilad<<")";
6974                    if(IsDebug())cout <<endl<<" *** CRC *** (data DSPn "<<caltrk->DSPnumber[ipkt]<<" ladder "<<ilad<<")";
6975                    validate = 0;
6976                }
6977                if( !(caltrk->ncalib_event[ipkt]==0 && caltrk->cal_flag[ipkt]==0) ){
6978                    if(IsDebug())cout <<endl<<" *** FAILURE ***     (data DSPn "<<caltrk->DSPnumber[ipkt]<<")";
6979                    validate = 0;
6980                }
6981            }else{
6982    //          validate=0;
6983                if(IsDebug())cout <<endl<<" *** DSPn *** ("<< caltrk->DSPnumber[ipkt] <<" @pkt "<<ipkt<<")";
6984            }
6985      }      }
6986    
6987  //  -----------------------  //  -----------------------
6988  //  Check missing packets:  //  Check missing packets:
6989  //  -----------------------  //  -----------------------
# Line 6295  UInt_t PamelaDBOperations::ValidateTrkCa Line 7009  UInt_t PamelaDBOperations::ValidateTrkCa
7009  //  Check if it is first or second calibration packet  //  Check if it is first or second calibration packet
7010  //  -------------------------------------------------  //  -------------------------------------------------
7011      UInt_t build=0;      UInt_t build=0;
     TString classname = caltrk->GetName();  
7012      UInt_t base=0;      UInt_t base=0;
7013      UInt_t mask=0;      UInt_t mask=0;
7014      if(classname.Contains("CalibTrk1Event")){      if(classname.Contains("CalibTrk1Event")){
# Line 6306  UInt_t PamelaDBOperations::ValidateTrkCa Line 7019  UInt_t PamelaDBOperations::ValidateTrkCa
7019          base=18;          base=18;
7020          mask=0xFC0000;          mask=0xFC0000;
7021      }      }
7022  //  -------------------------------------------------  //  ----------------------------------------------------
7023  //  Count number of packets and set build variable  //  Count number of valid packets and set build variable
7024  //  -------------------------------------------------  //  ----------------------------------------------------
7025        if(IsDebug())cout <<endl<< " DSP: ";
7026      Int_t  npkts=0;      Int_t  npkts=0;
7027      for(Int_t ipkt=0; ipkt<6; ipkt++){      for(Int_t ipkt=0; ipkt<6; ipkt++){
7028          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
7029                if(IsDebug())cout <<" "<<caltrk->DSPnumber[ipkt];
7030              npkts++;              npkts++;
7031              build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );              build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );
7032          }  //          cout << caltrk->DSPnumber[ipkt]
7033            };
7034      }      }
7035  //    if( npkts==6 )return 1; // :-)      if(IsDebug())cout << " ==> "<< hex << build << dec;
7036    //  ----------------------------------------------------
7037  //    cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime()<<endl;  //  If the number of valid packets is 6, ok exit...
7038    //  ----------------------------------------------------
7039  //  -----------------------------------------------      if( npkts==6 ){
7040  //  If missing packets: check the acq configuration          return validate; // exit
7041        }
7042    ////////////////////////////////////////////////////////
7043    //  ...otherwise there might be some missing packets
7044    //
7045    //  In this case check the acq configuration
7046  //  (some DSPs might be excluded from acquisition)  //  (some DSPs might be excluded from acquisition)
7047  //  -----------------------------------------------  ////////////////////////////////////////////////////////
7048    
7049        if(!eh || !file || (file&&file->IsZombie()) ){
7050            if ( IsDebug() )cout << " *** MISSING VIEW *** eh="<<eh<<" file="<<file<<" cannot validate"<<endl;
7051            return (0);
7052        }
7053        
7054  //  -----------------------------------------------  //  -----------------------------------------------
7055  //  retrieve the first run header after calib  //  retrieve the first run header after calib
7056  //  -----------------------------------------------  //  -----------------------------------------------
7057       PacketType *pctp;      
7058       EventCounter *cod;      PacketType *pctp;
7059       cod = eh->GetCounter();      EventCounter *cod;
7060       Int_t irun = cod->Get(pctp->RunHeader);      cod = eh->GetCounter();
7061       TTree *rh=(TTree*)file->Get("RunHeader");      Int_t irun = cod->Get(pctp->RunHeader);
7062       if ( !rh || rh->IsZombie() ) throw -17;      TTree *rh=(TTree*)file->Get("RunHeader");
7063       if( rh->GetEntries() == irun ){      if ( !rh || rh->IsZombie() ) throw -17;
7064            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (1)  -- cannot validate :-( "<<endl;      if( rh->GetEntries() <= irun ){
7065           return 0; // :-(          if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (1) -- cannot validate :-( "<<endl;
7066       }          return 0; // :-(
7067        }
7068       RunHeaderEvent *run  = 0;      RunHeaderEvent *run  = 0;
7069       EventHeader    *hrun = 0;      EventHeader    *hrun = 0;
7070       rh->SetBranchAddress("RunHeader", &run);      rh->SetBranchAddress("RunHeader", &run);
7071       rh->SetBranchAddress("Header", &hrun);      rh->SetBranchAddress("Header", &hrun);
7072       rh->GetEntry(irun);      rh->GetEntry(irun);    
7073  //     cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime() << " Run " << hrun->GetPscuHeader()->GetOrbitalTime() <<endl;      if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){
7074            if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (2) -- cannot validate :-( "<<endl;
7075       if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){          return 0; // :-(
7076            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (2) -- cannot validate :-( "<<endl;      }
7077           return 0; // :-(  
7078       }      UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());
7079            if( dtime > timeaftercalib ){
7080       if( !run->RM_ACQ_AFTER_CALIB ){          if ( IsDebug() ) cout << " *** MISSING-PKT *** run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;
7081            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) RM_ACQ_AFTER_CALIB=0    -- cannot validate :-( "<<endl;          return 0; // :-(
7082           return 0; // :-(      }
7083       }  
7084        if ( IsDebug() ) cout <<endl<< " ACQ_BUILD_INFO ==> "<<hex<<(run->ACQ_BUILD_INFO & mask)<<dec;
7085       UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());  
7086       if( dtime > timeaftercalib ){      if( (run->ACQ_BUILD_INFO & mask) != build ){
7087           if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;          validate=0; // :-(
7088           return 0; // :-(          cout <<endl<< " *** MISSING-PKT *** packet mismatch: ACQ_BUILD_INFO="<<hex<<(run->ACQ_BUILD_INFO&mask)<<" != "<<build<<dec;
7089       }      };
7090        
7091        return validate;
7092    
      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; // :-)  
7093    
7094  }  }
7095    
# Line 6378  UInt_t PamelaDBOperations::ValidateTrkCa Line 7099  UInt_t PamelaDBOperations::ValidateTrkCa
7099   *   *
7100   **/   **/
7101  UInt_t PamelaDBOperations::Check(){  UInt_t PamelaDBOperations::Check(){
7102          return(this->Check(0,0));    return(this->Check(0,0));
7103  }  }
7104    
7105  UInt_t PamelaDBOperations::Check(UInt_t from, UInt_t to){  UInt_t PamelaDBOperations::Check(UInt_t from, UInt_t to){
7106    //    //
7107          if ( IsDebug() ) printf(" from %u to %u \n",from,to);    if ( IsDebug() ) printf(" from %u to %u \n",from,to);
7108    //    //
7109    UInt_t test = 0;    UInt_t test = 0;
7110    //    //
# Line 6424  UInt_t PamelaDBOperations::Check(UInt_t Line 7145  UInt_t PamelaDBOperations::Check(UInt_t
7145      //      //
7146      if ( from > 0 && nid <= from ) goto ss;      if ( from > 0 && nid <= from ) goto ss;
7147      if ( to > 0 && nid >= to ) goto ss;      if ( to > 0 && nid >= to ) goto ss;
7148  //      //
7149      if ( (UInt_t)atoll(row->GetField(4)) > 1 ){      if ( (UInt_t)atoll(row->GetField(4)) > 1 ){
7150        //        //
7151        //        //
# Line 6455  UInt_t PamelaDBOperations::Check(UInt_t Line 7176  UInt_t PamelaDBOperations::Check(UInt_t
7176              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)));  
7177              row3 = result3->Next();              row3 = result3->Next();
7178            };            };
7179  //      delete result3;            //    delete result3;
7180    
7181          };          };
7182          //          //
# Line 6476  UInt_t PamelaDBOperations::Check(UInt_t Line 7197  UInt_t PamelaDBOperations::Check(UInt_t
7197              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)));
7198              row3 = result3->Next();              row3 = result3->Next();
7199            };            };
7200  //      delete result3;            //    delete result3;
7201          };          };
7202          //          //
7203          oss.str("");          oss.str("");
# Line 6496  UInt_t PamelaDBOperations::Check(UInt_t Line 7217  UInt_t PamelaDBOperations::Check(UInt_t
7217              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)));
7218              row3 = result3->Next();              row3 = result3->Next();
7219            };            };
7220   //     delete result3;            //    delete result3;
7221    
7222          };          };
7223        };        };
# Line 6517  UInt_t PamelaDBOperations::Check(UInt_t Line 7238  UInt_t PamelaDBOperations::Check(UInt_t
7238            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)));
7239            row3 = result3->Next();            row3 = result3->Next();
7240          };          };
7241  //      delete result3;          //      delete result3;
7242        };        };
7243        //        //
7244      };      };
# Line 6543  UInt_t PamelaDBOperations::Check(UInt_t Line 7264  UInt_t PamelaDBOperations::Check(UInt_t
7264        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
7265        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7266        test = 1;        test = 1;
7267  //      delete result2;        //        delete result2;
7268      };      };
7269      //      //
7270      if ( (thisrtt < prevrht) && (thisrht != prevrht) ){      if ( (thisrtt < prevrht) && (thisrht != prevrht) ){
# Line 6565  UInt_t PamelaDBOperations::Check(UInt_t Line 7286  UInt_t PamelaDBOperations::Check(UInt_t
7286        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
7287        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7288        test = 1;        test = 1;
7289  //      delete result2;        //        delete result2;
7290      };      };
7291      //      //
7292      if ( (thisrht > thisrtt) && (thisrht != prevrht) ){      if ( (thisrht > thisrtt) && (thisrht != prevrht) ){
# Line 6587  UInt_t PamelaDBOperations::Check(UInt_t Line 7308  UInt_t PamelaDBOperations::Check(UInt_t
7308        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
7309        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7310        test = 1;        test = 1;
7311  //      delete result2;        //        delete result2;
7312      };      };
7313  ss:    ss:
7314      //      //
7315      prevrht = thisrht;      prevrht = thisrht;
7316      prevrtt = thisrtt;      prevrtt = thisrtt;
7317      previd = thisid;      previd = thisid;
7318      prevl0id = thisl0id;      prevl0id = thisl0id;
7319      row = result->Next();      row = result->Next();
7320  //    if ( result2 ) delete result2;      //    if ( result2 ) delete result2;
7321  //    if ( result3 ) delete result3;      //    if ( result3 ) delete result3;
7322    };    };
7323    //    //
7324    return(test);    return(test);

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

  ViewVC Help
Powered by ViewVC 1.1.23