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

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

  ViewVC Help
Powered by ViewVC 1.1.23