/[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.19 by mocchiut, Mon Dec 22 11:05:10 2008 UTC
# Line 58  string getTleDatetime(cTle*); Line 58  string getTleDatetime(cTle*);
58   * @param debug        debug flag.   * @param debug        debug flag.
59   * @param tlefilename  ascii file with TLE 3 line elements.   * @param tlefilename  ascii file with TLE 3 line elements.
60   */   */
61  PamelaDBOperations::PamelaDBOperations(TString host, TString user, TString password, TString filerawname, TString filerootname, UInt_t boot, UInt_t tsync, UInt_t obt0, Bool_t debug, TString tlefilename, UInt_t dwinput, Bool_t staticp, Bool_t gpamela){  PamelaDBOperations::PamelaDBOperations(TString host, TString user, TString password, TString filerawname, TString filerootname, UInt_t boot, UInt_t tsync, UInt_t obt0, Bool_t debug, TString tlefilename, UInt_t dwinput, Bool_t staticp, Bool_t gpamela, Bool_t keepenv){
62    //    //
63    chewbacca = false;    chewbacca = false;
64    chminentry = 0;    chminentry = 0;
# Line 76  PamelaDBOperations::PamelaDBOperations(T Line 76  PamelaDBOperations::PamelaDBOperations(T
76      //      //
77    };    };
78    //    //
79      KEEPENV = false;
80      if ( keepenv ) KEEPENV=true;
81    STATIC=false;    STATIC=false;
82    if ( staticp ) STATIC=true;    if ( staticp ) STATIC=true;
83    //    //
# Line 99  PamelaDBOperations::PamelaDBOperations(T Line 101  PamelaDBOperations::PamelaDBOperations(T
101    if (INSERT_RAW) SetRawName(filerawname);    if (INSERT_RAW) SetRawName(filerawname);
102    //    //
103    INSERT_ROOT = !filerootname.IsNull();    INSERT_ROOT = !filerootname.IsNull();
104      if ( INSERT_ROOT ) this->SetRootName(filerootname);
105    this->SetOrbitNo(dwinput);    this->SetOrbitNo(dwinput);
106    //    //
107    this->SetID_RAW(0);    this->SetID_RAW(0);
# Line 132  void PamelaDBOperations::OpenL0File(TStr Line 135  void PamelaDBOperations::OpenL0File(TStr
135        stringstream qu;        stringstream qu;
136        TSQLResult *result = 0;        TSQLResult *result = 0;
137        TSQLResult *result2 = 0;        TSQLResult *result2 = 0;
138          TSQLResult *result3 = 0;
139        TSQLRow    *row    = 0;            TSQLRow    *row    = 0;    
140        TSQLRow    *row2    = 0;            TSQLRow    *row2    = 0;    
141          TSQLRow    *row3    = 0;    
142        TString chpath;        TString chpath;
143        TString chfile;        TString chfile;
144        UInt_t ridn = 0;        UInt_t ridn = 0;
145        qu.str("");        qu.str("");
146        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 << ";";
147        if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());        if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
148        result = conn->Query(qu.str().c_str());        result = conn->Query(qu.str().c_str());
149        if ( result ){        if ( result ){
# Line 149  void PamelaDBOperations::OpenL0File(TStr Line 154  void PamelaDBOperations::OpenL0File(TStr
154            chpktmax = (UInt_t)atoll(row->GetField(2));            chpktmax = (UInt_t)atoll(row->GetField(2));
155            chobtmin = (UInt_t)atoll(row->GetField(3));            chobtmin = (UInt_t)atoll(row->GetField(3));
156            chobtmax = (UInt_t)atoll(row->GetField(4));            chobtmax = (UInt_t)atoll(row->GetField(4));
157              chiby = (TString)(row->GetField(5));
158          } else {          } else {
159            throw -84;            throw -84;
160          };          };
# Line 157  void PamelaDBOperations::OpenL0File(TStr Line 163  void PamelaDBOperations::OpenL0File(TStr
163        };        };
164        delete result;        delete result;
165        qu.str("");        qu.str("");
166        qu << "SELECT FOLDER_NAME,FILE_NAME,OBT_TIME_SYNC,LAST_TIME_SYNC_INFO,TIME_OFFSET,BOOT_NUMBER,PKT_NUMBER_INIT,PKT_NUMBER_FINAL,PKT_OBT_INIT,PKT_OBT_FINAL from ROOT_TABLE where ID_N=" << ridn << ";";        qu << "SELECT FOLDER_NAME,FILE_NAME,OBT_TIME_SYNC,LAST_TIME_SYNC_INFO,TIME_OFFSET,BOOT_NUMBER,PKT_NUMBER_INIT,PKT_NUMBER_FINAL,PKT_OBT_INIT,PKT_OBT_FINAL,REAL_TIME_INIT from ROOT_TABLE where ID_N=" << ridn << ";";
167        if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());        if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
168        result2 = conn->Query(qu.str().c_str());        result2 = conn->Query(qu.str().c_str());
169        if ( result2 ){        if ( result2 ){
170          row2 = result2->Next();          row2 = result2->Next();
171          if ( row2 ){          if ( row2 ){
172            chpath = (TString)gSystem->ExpandPathName(row2->GetField(0))+'/';            if ( KEEPENV ){
173                chpath = (TString)(row2->GetField(0))+'/';
174              } else {
175                chpath = (TString)gSystem->ExpandPathName(row2->GetField(0))+'/';
176              };
177            chfile = (TString)(row2->GetField(1));            chfile = (TString)(row2->GetField(1));
178            chobtts = (UInt_t)atoll(row2->GetField(2));            chobtts = (UInt_t)atoll(row2->GetField(2));
179            chlastts = (UInt_t)atoll(row2->GetField(3));            chlastts = (UInt_t)atoll(row2->GetField(3));
180            chresursts = (UInt_t)atoll(row2->GetField(4));            chresursts = (UInt_t)atoll(row2->GetField(4));
181            chboot = (UInt_t)atoll(row2->GetField(5));            chboot = (UInt_t)atoll(row2->GetField(5));
182            //            //
183              if ( !chboot ){
184                qu.str("");
185                qu << "SELECT BOOT_NUMBER from ROOT_TABLE where BOOT_NUMBER!=0 AND ABS(LAST_TIME_SYNC_INFO-"<< chlastts <<")<10000 AND (REAL_TIME_INIT-"<< row2->GetField(10) <<")<7200 group by BOOT_NUMBER order by BOOT_NUMBER asc;";
186                if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
187                result3 = conn->Query(qu.str().c_str());
188                if ( result3 ){
189                  row3 = result3->Next();
190                  if ( row3 && result3->GetRowCount() == 1 ){
191                    chboot = (UInt_t)atoll(row3->GetField(0));
192                    if ( debug ) printf(" Found boot_number = %u \n",chboot);
193                  } else {
194                    if ( debug ) printf(" AGH CANNOT DETERMINE THE BOOT NUMBER... \n");
195                    throw -29;
196                  };
197                };
198              };
199              //
200            chpktinit = (UInt_t)atoll(row2->GetField(6));            chpktinit = (UInt_t)atoll(row2->GetField(6));
201            chpktfinal = (UInt_t)atoll(row2->GetField(7));            chpktfinal = (UInt_t)atoll(row2->GetField(7));
202            chobtinit = (UInt_t)atoll(row2->GetField(8));            chobtinit = (UInt_t)atoll(row2->GetField(8));
# Line 182  void PamelaDBOperations::OpenL0File(TStr Line 209  void PamelaDBOperations::OpenL0File(TStr
209          throw -85;          throw -85;
210        };        };
211        filerootname = chpath + chfile;// + ".root";        filerootname = chpath + chfile;// + ".root";
       if ( debug ) printf(" chewbacca: filename is %s \n",filerootname.Data());  
212      };      };
213      this->SetRootName(filerootname);      this->SetRootName(filerootname);
     file = TFile::Open(this->GetRootName().Data());  
   } else {  
     this->SetRootName("");  
214    };    };
215      if ( debug ) printf(" Filename is %s \n",filerootname.Data());
216      file = TFile::Open(this->GetRootName().Data());
217      //  } else {
218      //    this->SetRootName("");
219      //    this->SetRootName(filerootname);
220      //  };
221  }  }
222    
223  //  //
# Line 388  void PamelaDBOperations::SetOrbitNo(UInt Line 417  void PamelaDBOperations::SetOrbitNo(UInt
417      return;      return;
418    };    };
419    //    //
420    TString name = this->GetRootFile();    if ( !chewbacca ){
421    Int_t nlength = name.Length();      TString name = this->GetRootFile();
422    if ( nlength < 5 ) return;      Int_t nlength = name.Length();
423    TString dwo = 0;      if ( nlength < 5 ){
424    for (Int_t i = 0; i<5; i++){        if ( IsDebug() ) printf(" Agh problems determining the orbit number! name = %s \n",name.Data());
425      dwo.Append(name[i],1);        return;
426    };      };
427    if ( dwo.IsDigit() ){      TString dwo = 0;
428      dworbit = (UInt_t)dwo.Atoi();      for (Int_t i = 0; i<5; i++){
   } else {  
     dwo="";  
     for (Int_t i = 8; i<13; i++){  
429        dwo.Append(name[i],1);        dwo.Append(name[i],1);
430      };          };
431      if ( dwo.IsDigit() ) dworbit = (UInt_t)dwo.Atoi();      if ( dwo.IsDigit() ){
432          dworbit = (UInt_t)dwo.Atoi();
433        } else {
434          dwo="";
435          for (Int_t i = 8; i<13; i++){
436            dwo.Append(name[i],1);
437          };    
438          if ( dwo.IsDigit() ) dworbit = (UInt_t)dwo.Atoi();
439        };
440        if ( IsDebug() ) printf(" Downlink orbit is %i (dwo = %s) \n",dworbit,dwo.Data());
441    };    };
   if ( IsDebug() ) printf(" Downlink orbit is %i (dwo = %s) \n",dworbit,dwo.Data());  
442    return;    return;
443  };  };
444    
# Line 435  TString PamelaDBOperations::GetRawPath() Line 469  TString PamelaDBOperations::GetRawPath()
469    
470  TString PamelaDBOperations::GetRootPath(){  TString PamelaDBOperations::GetRootPath(){
471    if ( STATIC ){    if ( STATIC ){
472      return((TString)gSystem->DirName(filerootname.Data())+'/');      return((TString)gSystem->DirName(this->GetRootName().Data())+'/');
473    } else {    } else {    
474      return((TString)gSystem->ExpandPathName("$PAM_L0")+'/');      if ( KEEPENV ){
475          return((TString)gSystem->ExpandPathName(gSystem->DirName(filerootname.Data()))+'/');
476        } else {
477          return((TString)gSystem->ExpandPathName("$PAM_L0")+'/');
478        };
479    };    };
480  };  };
481    
# Line 490  void PamelaDBOperations::SetCommonGLRUN( Line 528  void PamelaDBOperations::SetCommonGLRUN(
528  };  };
529    
530  /**  /**
531     *
532     * Set the variables which belogns to physendrun tree
533     *
534     */
535    void PamelaDBOperations::SetPhysEndRunVariables(){
536      //
537      //
538      //
539      TTree *T = 0;
540      T = (TTree*)file->Get("PhysEndRun");
541      if ( !T || T->IsZombie() ) throw -90;
542      //
543      PhysEndRunEvent *pher= 0;
544      EventHeader *eh = 0;
545      T->SetBranchAddress("PhysEndRun", &pher);
546      T->SetBranchAddress("Header", &eh);
547      //
548      UInt_t phobt = 0;
549      UInt_t phpkt = 0;
550      //
551      glrun->SetPHYSENDRUN_MASK_S3S2S12(0);
552      glrun->SetPHYSENDRUN_MASK_S11CRC(0);
553      //
554      for (Int_t p=0; p<T->GetEntries(); p++){
555        //
556        T->GetEntry(p);
557        //
558        phobt = (UInt_t)eh->GetPscuHeader()->GetOrbitalTime();
559        phpkt = (UInt_t)eh->GetPscuHeader()->GetCounter();
560        //
561        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())  ){
562          if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() || glrun->GetPHYSENDRUN_MASK_S11CRC() ){
563            if ( IsDebug() ) printf(" WARNING while looping in physendrun: found two PhysEndRun packet for the same RUN! \n");
564            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);
565            if ( PEDANTIC && IsDebug() ) printf(" ERROR while looping in physendrun: found two PhysEndRun packet for the same RUN!\n ");
566            if ( PEDANTIC ) throw -91;
567          } else {
568            glrun->SetPHYSENDRUN_MASK_S3S2S12((UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S3S2S12);
569            glrun->SetPHYSENDRUN_MASK_S11CRC((UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S11CRC);
570          };
571        };
572      };
573      //
574    };
575    
576    /**
577   * Patch, look for upper limits to avoid processing retransmitted data   * Patch, look for upper limits to avoid processing retransmitted data
578   */   */
579  Int_t PamelaDBOperations::SetUpperLimits(){  Int_t PamelaDBOperations::SetUpperLimits(){
# Line 603  Int_t PamelaDBOperations::SetUpperLimits Line 687  Int_t PamelaDBOperations::SetUpperLimits
687      UInt_t tjump = 50000;      UInt_t tjump = 50000;
688      //UInt_t tjump = 100;      //UInt_t tjump = 100;
689      while ( tjump > 0 ){      while ( tjump > 0 ){
690        pktlast = numeric_limits<UInt_t>::max();        //      pktlast = numeric_limits<UInt_t>::max();
691        while ( pktlast > chpktmax && (Int_t)(nevent-1-it) >= 0 ){        pktlast = chpktmax + 1;
692          while ( PKT(pktlast) > PKT(chpktmax) && (Int_t)(nevent-1-it) >= 0 ){
693          if ( (Int_t)(nevent-1-it) >= 0 ){          if ( (Int_t)(nevent-1-it) >= 0 ){
694            T->GetEntry(nevent-1-it);            T->GetEntry(nevent-1-it);
695            ph = eh->GetPscuHeader();            ph = eh->GetPscuHeader();
# Line 612  Int_t PamelaDBOperations::SetUpperLimits Line 697  Int_t PamelaDBOperations::SetUpperLimits
697          } else {          } else {
698            pktlast = chpktmax + 1;            pktlast = chpktmax + 1;
699          };          };
700          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));
701          it += tjump;          it += tjump;
702        };        };
703        if ( tjump > 1 ) it -= 2*tjump;        if ( tjump > 1 ) it -= 2*tjump;
# Line 636  Int_t PamelaDBOperations::SetUpperLimits Line 721  Int_t PamelaDBOperations::SetUpperLimits
721      tjump = 50000;      tjump = 50000;
722      //tjump = 100;      //tjump = 100;
723      while ( tjump > 0 ){      while ( tjump > 0 ){
724        pktlast = 0;        //      pktlast = 0;
725        while ( pktlast < chpktmin && it < (Int_t)nevent ){        pktlast = chpktmin - 1;
726          if ( debug ) printf("LLlook for down %i %i %llu %llu \n",it,pktlast,PKT(pktlast),PKT(chpktmin));
727          while ( PKT(pktlast) < PKT(chpktmin) && it < (Int_t)nevent ){
728          if ( it < (Int_t)nevent ){          if ( it < (Int_t)nevent ){
729            T->GetEntry(it);            T->GetEntry(it);
730            ph = eh->GetPscuHeader();            ph = eh->GetPscuHeader();
# Line 739  Int_t PamelaDBOperations::SetUpperLimits Line 826  Int_t PamelaDBOperations::SetUpperLimits
826    };    };
827    //    //
828    if ( chewbacca && nevent < 1 ) {    if ( chewbacca && nevent < 1 ) {
829          pktfirst = chpktmin;      pktfirst = chpktmin;
830          upperpkt = PKT(chpktmax);      upperpkt = PKT(chpktmax);
831          pktlast = chpktmax;      pktlast = chpktmax;
832          obtfirst = chobtmin;      obtfirst = chobtmin;
833          obtlast = chobtmax;      obtlast = chobtmax;
834          upperobt = OBT(chobtmax);      upperobt = OBT(chobtmax);
835    };    };
836    //    //
837    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 839  Int_t PamelaDBOperations::SetUpperLimits
839    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);
840    //    //
841    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)) ){
842          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));
843          if ( PEDANTIC ) throw -88;      if ( PEDANTIC ) throw -88;
844          return(32);      return(32);
845    };    };
846    //    //
847    if ( !nevent ) return(64);    if ( !nevent ) return(64);
# Line 1040  Int_t PamelaDBOperations::SetUpperLimits Line 1127  Int_t PamelaDBOperations::SetUpperLimits
1127          upperpkt = pkth;          upperpkt = pkth;
1128          upperobt = obth;          upperobt = obth;
1129          rhev = lasthead+1;          rhev = lasthead+1;
1130      } else {        } else {
1131          rhev = lasthead;          rhev = lasthead;
1132        };        };
1133        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 1166  UInt_t PamelaDBOperations::AssignRunID()
1166    stringstream   oss;    stringstream   oss;
1167    //      //  
1168    oss.str("");    oss.str("");
1169    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.
1170        if ( !strcmp(tag.Data(),"NONE") ){
1171          oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< chiby.Data() <<"');";
1172        } else {
1173          oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< tag.Data() <<"');";
1174        };
1175      } else {
1176        oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< tag.Data() <<"');";
1177      };
1178    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1179    if ( !result ) throw -10;    if ( !result ) throw -10;
1180    oss.str("");    oss.str("");
# Line 1227  void PamelaDBOperations::LockTables(){   Line 1322  void PamelaDBOperations::LockTables(){  
1322    stringstream oss;    stringstream oss;
1323    //      //  
1324    oss.str("");    oss.str("");
1325    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;";
1326    TSQLResult *result = 0;    TSQLResult *result = 0;
1327    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1328    if ( !result ) throw -10;    if ( !result ) throw -10;
# Line 1260  void PamelaDBOperations::UnLockTables(){ Line 1355  void PamelaDBOperations::UnLockTables(){
1355   */   */
1356  Long64_t PamelaDBOperations::PKT(UInt_t pkt_num){    Long64_t PamelaDBOperations::PKT(UInt_t pkt_num){  
1357    //    //
1358  //  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));
1359    //    //
1360    if ( pkt_num < (ppktfirst/2) && ppktfirst > (16777214/2)  ){    if ( pkt_num < (ppktfirst/2) && ppktfirst > (16777214/2)  ){
1361  //    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);
1362      return((Long64_t)pkt_num+16777215LL);      return((Long64_t)pkt_num+16777215LL);
1363    };    };
1364    //    //
1365    if ( pkt_num > ((Long64_t)ppktfirst*2) && pkt_num > (16777214/2) ){    if ( pkt_num > ((Long64_t)ppktfirst*2) && pkt_num > (16777214/2) ){
1366  //    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);
1367      return((Long64_t)pkt_num-16777215LL);      return((Long64_t)pkt_num-16777215LL);
1368    };    };
1369    //    //
1370  //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)pkt_num);    //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)pkt_num);
1371    return((Long64_t)pkt_num);    return((Long64_t)pkt_num);
1372    //    //
1373  };  };
# Line 1282  Long64_t PamelaDBOperations::PKT(UInt_t Line 1377  Long64_t PamelaDBOperations::PKT(UInt_t
1377   */   */
1378  Long64_t PamelaDBOperations::OBT(UInt_t obt){    Long64_t PamelaDBOperations::OBT(UInt_t obt){  
1379    //    //
1380  //  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));
1381    //    //
1382    if ( obt < (pobtfirst/2) && pobtfirst > (numeric_limits<UInt_t>::max()/2) ){    if ( obt < ((Long64_t)pobtfirst/2) && pobtfirst > (numeric_limits<UInt_t>::max()/2) ){
1383  //    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());
1384      return((Long64_t)obt+(Long64_t)numeric_limits<UInt_t>::max());      return((Long64_t)obt+(Long64_t)numeric_limits<UInt_t>::max());
1385    };    };
1386    //    //
1387    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) ){
1388  //    if ( IsDebug() ) printf(" pobtfirst*2 %lld \n",((Long64_t)pobtfirst*2));      //    if ( IsDebug() ) printf(" pobtfirst*2 %lld \n",((Long64_t)pobtfirst*2));
1389  //    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());
1390      return((Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());      return((Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());
1391    };    };
1392    //    //
1393  //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)obt);    //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)obt);
1394    return((Long64_t)obt);    return((Long64_t)obt);
1395  };  };
1396    
# Line 1331  void PamelaDBOperations::FillClass(Bool_ Line 1426  void PamelaDBOperations::FillClass(Bool_
1426    UInt_t lastPkt = 0;    UInt_t lastPkt = 0;
1427    UInt_t rhtime = 0;    UInt_t rhtime = 0;
1428    UInt_t rttime = 0;    UInt_t rttime = 0;
1429      //
1430      if ( IsDebug() ) printf(" A firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1431      //
1432    if ( !mishead ){    if ( !mishead ){
1433      codh = ehh->GetCounter();      codh = ehh->GetCounter();
1434      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1) ){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){      
1435          if ( IsDebug() ) printf(" B firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1436        firstev = 1;        firstev = 1;
1437        lastev = 0;        lastev = 0;
1438      } else {      } else {
# Line 1346  void PamelaDBOperations::FillClass(Bool_ Line 1445  void PamelaDBOperations::FillClass(Bool_
1445    };    };
1446    if ( !mistrail ){    if ( !mistrail ){
1447      codt = eht->GetCounter();      codt = eht->GetCounter();
1448      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1)){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1)){      
1449          if ( IsDebug() ) printf(" C firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1450        lastev = 0;        lastev = 0;
1451        firstev = lastev+1;        firstev = lastev+1;
1452      } else {      } else {
# Line 1363  void PamelaDBOperations::FillClass(Bool_ Line 1463  void PamelaDBOperations::FillClass(Bool_
1463    if ( mishead ) {    if ( mishead ) {
1464      glrun->Set_GL_RUNH0();      glrun->Set_GL_RUNH0();
1465      //      //
1466      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1) ){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){      
1467        firstObt = lastObt;        firstObt = lastObt;
1468        firstPkt = lastPkt;        firstPkt = lastPkt;
1469        rhtime = rttime;        rhtime = rttime;
# Line 1382  void PamelaDBOperations::FillClass(Bool_ Line 1482  void PamelaDBOperations::FillClass(Bool_
1482    if ( mistrail ){    if ( mistrail ){
1483      glrun->Set_GL_RUNT0();      glrun->Set_GL_RUNT0();
1484      //      //
1485      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1) ){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){      
1486        lastObt = firstObt;        lastObt = firstObt;
1487        lastPkt = firstPkt;        lastPkt = firstPkt;
1488        rttime = rhtime;        rttime = rhtime;
# Line 1405  void PamelaDBOperations::FillClass(Bool_ Line 1505  void PamelaDBOperations::FillClass(Bool_
1505    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);
1506    //    //
1507    this->SetCommonGLRUN(rhtime,rttime);    this->SetCommonGLRUN(rhtime,rttime);
1508      this->SetPhysEndRunVariables();
1509    //    //
1510  };  };
1511    
# Line 1416  void PamelaDBOperations::FillClass(Bool_ Line 1517  void PamelaDBOperations::FillClass(Bool_
1517   * Insert a new row into GL_RAW table.   * Insert a new row into GL_RAW table.
1518   */   */
1519  Int_t PamelaDBOperations::insertPamelaRawFile(){  Int_t PamelaDBOperations::insertPamelaRawFile(){
1520    
1521        //
1522        Bool_t idr =  this->SetID_RAW();
1523        if ( idr ) return(1);
1524    
1525        GL_RAW glraw = GL_RAW();
1526        
1527        glraw.PATH = GetRawPath();
1528        glraw.NAME = GetRawFile();
1529        //    glraw.BOOT_NUMBER = 0;//???
1530        glraw.BOOT_NUMBER = this->GetBOOTnumber();
1531        
1532        if( insertPamelaRawFile(&glraw) )return(1);
1533        //
1534        idr =  this->SetID_RAW();
1535        if ( !idr ) throw -11;
1536        
1537        return(0);
1538    }
1539    /**
1540     * Insert a new row into GL_RAW table.
1541     */
1542    Int_t PamelaDBOperations::insertPamelaRawFile(GL_RAW *glraw){
1543    //    //
1544    stringstream oss;      if(!glraw)return(1);//?? ok I think
1545    //      //
1546    Bool_t idr =  this->SetID_RAW();      stringstream oss;
1547    if ( idr ) return(1);      //
1548    //      oss.str("");
1549    oss.str("");      if ( STATIC ){
1550    if ( STATIC ){          oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"
1551      oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"              << glraw->PATH << "', '" << glraw->NAME << "')";
1552          << this->GetRawPath().Data() << "', '" << this->GetRawFile().Data() << "')";      } else {
1553    } else {          oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('$PAM_RAW', '" << glraw->NAME << "')";
1554      oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('$PAM_RAW', '" << this->GetRawFile().Data() << "')";      };
1555    };      if ( debug ) cout <<oss.str().c_str() <<endl;
1556    if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;      if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
1557    //      //
1558    idr =  this->SetID_RAW();      oss.str("");
1559    if ( !idr ) throw -11;      oss << "SELECT ID FROM GL_RAW WHERE NAME=\""<<glraw->NAME<<"\";";
1560    //      if ( debug ) cout << oss.str().c_str()<<endl;
1561    return(0);      if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
1562        //
1563        TSQLResult *result = 0;
1564        TSQLRow    *row    = 0;
1565        result = conn->Query(oss.str().c_str());
1566        if ( result == NULL ) throw -4;
1567        row = result->Next();
1568        if ( !row ) return(1);
1569        glraw->ID = (UInt_t)atoll(row->GetField(0));
1570        if ( debug ) printf(" The ID of the RAW file is %u \n",glraw->ID);
1571        delete result;
1572        delete row;
1573        //
1574        return(0);
1575  }  }
1576    
1577    
# Line 1467  Int_t PamelaDBOperations::insertPamelaGL Line 1604  Int_t PamelaDBOperations::insertPamelaGL
1604      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
1605      if ( !result ) throw -10;      if ( !result ) throw -10;
1606      row = result->Next();      row = result->Next();
1607        if ( !row ) throw -92;
1608      idresof = (UInt_t)atoll(row->GetField(0));      idresof = (UInt_t)atoll(row->GetField(0));
1609      existsts = true;      existsts = true;
1610      goto eout;      goto eout;
# Line 1746  Int_t PamelaDBOperations::insertPamelaGL Line 1884  Int_t PamelaDBOperations::insertPamelaGL
1884   * 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.
1885   */   */
1886  Int_t PamelaDBOperations::insertPamelaRootFile(){  Int_t PamelaDBOperations::insertPamelaRootFile(){
1887    stringstream oss;  
1888    TSQLResult *result = 0;      stringstream oss;
1889    TSQLRow    *row    = 0;      TSQLResult *result = 0;
1890    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;  
1891      //      //
1892      row = result->Next();      // ----------------------
1893        // determine the timesync
1894        // ----------------------
1895        UInt_t idtimesync = 0;
1896      //      //
1897      if ( !row ) throw -3;      if ( chewbacca ){
1898      idtimesync = (UInt_t)atoll(row->GetField(0));          oss.str("");
1899    } else {          oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" limit 1;";
1900      oss.str("");          if ( debug ) printf(" %s \n",oss.str().c_str());
1901      if ( STATIC ){          result = conn->Query(oss.str().c_str());
1902        oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "          //
1903            << " LEFT JOIN GL_ROOT "          if ( !result ) throw -3;
1904            << " ON GL_RAW.ID = GL_ROOT.ID_RAW "          //
1905            << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "          row = result->Next();
1906            << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";          //
1907            if ( !row ) throw -3;
1908            idtimesync = (UInt_t)atoll(row->GetField(0));
1909      } else {      } else {
1910        oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "          oss.str("");
1911            << " LEFT JOIN GL_ROOT "          if ( STATIC ){
1912            << " ON GL_RAW.ID = GL_ROOT.ID_RAW "              oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1913            << " WHERE GL_RAW.PATH = '$PAM_RAW' AND "                  << " LEFT JOIN GL_ROOT "
1914            << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";                  << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1915                    << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "
1916                    << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1917            } else {
1918                oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1919                    << " LEFT JOIN GL_ROOT "
1920                    << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1921                    << " WHERE GL_RAW.PATH = '$PAM_RAW' AND "
1922                    << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1923            };
1924            result = conn->Query(oss.str().c_str());
1925            //
1926            if ( !result ) throw -12;
1927            //
1928            row = result->Next();
1929            //
1930            if ( !row ) throw -10;
1931            if ( row != NULL && (UInt_t)atoll(row->GetField(0))>0 ){
1932                idroot = (UInt_t)atoll(row->GetField(2));
1933                delete row;
1934                delete result;
1935                return(1);
1936            };
1937            //
1938            // determine which timesync has to be used
1939            //
1940            oss.str("");
1941            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;";
1942            result = conn->Query(oss.str().c_str());
1943            //
1944            if ( !result ) throw -3;
1945            //
1946            row = result->Next();
1947            //
1948            if ( !row ) throw -3;
1949            idtimesync = (UInt_t)atoll(row->GetField(0));
1950      };      };
1951      result = conn->Query(oss.str().c_str());      
1952      //      delete row;
1953      if ( !result ) throw -12;      delete result;
1954      //  
1955      row = result->Next();      // ----------------------
1956      //      // insert root file
1957      if ( !row ) throw -10;      // ----------------------
1958      if ( row != NULL && (UInt_t)atoll(row->GetField(0))>0 ){  
1959        idroot = (UInt_t)atoll(row->GetField(2));      GL_ROOT glroot = GL_ROOT();
1960        return(1);      
1961        glroot.ID_RAW = GetID_RAW();
1962        glroot.ID_TIMESYNC = idtimesync;
1963        if ( STATIC ){
1964          glroot.PATH = GetRootPath();
1965        } else {
1966          if ( KEEPENV ){
1967            glroot.PATH = gSystem->DirName(filerootname.Data());
1968          } else {
1969            glroot.PATH = "$PAM_L0";
1970          };
1971      };      };
1972      //      glroot.NAME = GetRootFile();
1973      // determine which timesync has to be used  
1974      //      if ( insertPamelaRootFile(&glroot) )return 1;
1975      oss.str("");  
1976      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);
1977      result = conn->Query(oss.str().c_str());      
1978      //  
1979      if ( !result ) throw -3;      return (0);
1980      //  }
1981      row = result->Next();  /**
1982      //   * Insert all the new rows into GL_ROOT.
1983      if ( !row ) throw -3;   * The raw file indicates in the parameters should be already been stored in the database.
1984      idtimesync = (UInt_t)atoll(row->GetField(0));   */
1985    };  Int_t PamelaDBOperations::insertPamelaRootFile(GL_ROOT *glroot){
1986      stringstream oss;
1987      TSQLResult *result = 0;
1988      TSQLRow    *row    = 0;
1989      //
1990    //    //
1991    oss.str("");    oss.str("");
1992    if ( STATIC ){    oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
1993      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() << "')";  
   };  
1994    //    //
1995    if ( debug ) printf(" query is %s \n",oss.str().c_str());    if ( debug ) printf("%s \n",oss.str().c_str());
1996    if (conn->Query(oss.str().c_str()) == 0) throw -4;    if (conn->Query(oss.str().c_str()) == 0) throw -4;
1997    //    //
1998    delete result;    delete result;
1999    //    //
2000    oss.str("");    oss.str("");
2001    //  oss << "SELECT ID FROM GL_ROOT WHERE ID_RAW=" << this->GetID_RAW() << ";";    //  oss << "SELECT ID FROM GL_ROOT WHERE ID_RAW=" << this->GetID_RAW() << ";";
2002    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() <<"';";  
   };  
2003    //    //
2004    if ( debug ) printf(" query is %s \n",oss.str().c_str());    if ( debug ) printf("%s \n",oss.str().c_str());
2005    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
2006    if ( !result ) throw -12;    if ( !result ) throw -12;
2007    row = result->Next();    row = result->Next();
2008    if ( !row ) throw -3;    if ( !row ) throw -3;
2009    this->SetID_ROOT((UInt_t)atoll(row->GetField(0)));  
2010    if ( debug ) printf(" The ID of the ROOT file is %u \n",this->GetID_ROOT());    glroot->ID = (UInt_t)atoll(row->GetField(0));
2011    
2012      if ( debug ) printf(" The ID of the ROOT file is %u \n",glroot->ID);
2013    //    //
2014    delete result;    delete result;
2015    //    //
# Line 2061  Int_t PamelaDBOperations::insertPamelaRU Line 2237  Int_t PamelaDBOperations::insertPamelaRU
2237            cod = ehh->GetCounter();            cod = ehh->GetCounter();
2238            tcod = (UInt_t)cod->Get(pctp->Physics);            tcod = (UInt_t)cod->Get(pctp->Physics);
2239            evbefh = TMath::Max(chminentry,tcod);            evbefh = TMath::Max(chminentry,tcod);
2240  //        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
2241            if ( (UInt_t)evbefh == upperentry || !upperentry ) evbefh = upperentry + 1;            if ( (UInt_t)evbefh == upperentry || !upperentry ) evbefh = upperentry + 1;
2242  //            //
2243          if ( debug ) printf(" evbefh %i upperentry %u \n",evbefh,upperentry);            if ( debug ) printf(" evbefh %i upperentry %u \n",evbefh,upperentry);
2244            //            //
2245            this->HandleRunFragments(false,true,evbefh,upperentry);            this->HandleRunFragments(false,true,evbefh,upperentry);
2246            //            //
# Line 2091  Int_t PamelaDBOperations::insertPamelaRU Line 2267  Int_t PamelaDBOperations::insertPamelaRU
2267          ptht = cod->Get(pctp->RunHeader) - 1;          ptht = cod->Get(pctp->RunHeader) - 1;
2268          //      evbeft = cod->Get(pctp->Physics);          //      evbeft = cod->Get(pctp->Physics);
2269          tcod = (UInt_t)cod->Get(pctp->Physics);          tcod = (UInt_t)cod->Get(pctp->Physics);
2270          if ( !tcod ) tcod = 1;          if ( !tcod ) tcod = 1;    // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
2271          evbeft = TMath::Min(upperentry,(tcod-1));          evbeft = TMath::Min(upperentry,(tcod-1));
2272          if ( debug ) printf(" Loop in runtrailers, evbeft is %u upperentry %u cod->getetc %u \n",evbeft,upperentry,cod->Get(pctp->Physics));          if ( debug ) printf(" Loop in runtrailers, evbeft is %u upperentry %u cod->getetc %u \n",evbeft,upperentry,cod->Get(pctp->Physics));
2273          //          //
# Line 2130  Int_t PamelaDBOperations::insertPamelaRU Line 2306  Int_t PamelaDBOperations::insertPamelaRU
2306            obth = phh->GetOrbitalTime();            obth = phh->GetOrbitalTime();
2307            cod = ehh->GetCounter();            cod = ehh->GetCounter();
2308            tcod = (UInt_t)cod->Get(pctp->Physics);            tcod = (UInt_t)cod->Get(pctp->Physics);
2309            if ( !tcod ) tcod = 1;            if ( !tcod ) tcod = 1; // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
2310            evbefh = TMath::Max(chminentry,(tcod-1));            evbefh = TMath::Max(chminentry,(tcod-1));
2311            //            //
2312            if ( PKT(pkth) >= PKT(pktfirst) && PKT(pkth) <= upperpkt ){            if ( PKT(pkth) >= PKT(pktfirst) && PKT(pkth) <= upperpkt ){
# Line 2169  Int_t PamelaDBOperations::insertPamelaRU Line 2345  Int_t PamelaDBOperations::insertPamelaRU
2345                //                //
2346                this->HandleRunFragments(true,true,chminentry,(evbefh));                this->HandleRunFragments(true,true,chminentry,(evbefh));
2347                //                //
2348                  // what about pth=ptht-1
2349              };              };
2350            };            };
2351            //            //
# Line 2191  Int_t PamelaDBOperations::insertPamelaRU Line 2368  Int_t PamelaDBOperations::insertPamelaRU
2368                cod = ehh->GetCounter();                cod = ehh->GetCounter();
2369                //            evbeft = cod->Get(pctp->Physics);                //            evbeft = cod->Get(pctp->Physics);
2370                tcod = (UInt_t)cod->Get(pctp->Physics);                tcod = (UInt_t)cod->Get(pctp->Physics);
2371                if ( !tcod ) tcod = 1;                if ( !tcod ) tcod = 1; // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
2372                evbeft = TMath::Min(upperentry,(tcod-1));                evbeft = TMath::Min(upperentry,(tcod-1));
2373                rh->GetEntry(pth);                rh->GetEntry(pth);
2374                phh = ehh->GetPscuHeader();                phh = ehh->GetPscuHeader();
# Line 2231  Int_t PamelaDBOperations::insertPamelaRU Line 2408  Int_t PamelaDBOperations::insertPamelaRU
2408          //      if ( ptt+1 == rtev){            //      if ( ptt+1 == rtev){  
2409          if ( conptt+1 == nrtev ){            if ( conptt+1 == nrtev ){  
2410            //    if ( conptt+1 == (nrtev+nrtbef )){              //    if ( conptt+1 == (nrtev+nrtbef )){  
2411              if ( IsDebug() ) printf(" >>>>>>>>>>> %i %u %i %u \n",ptht,rhev,nrtev,conptt);
2412            ptht++;            ptht++;
2413            if ( ptht < rhev ){            if ( ptht < rhev ){
2414              rh->GetEntry(ptht);              rh->GetEntry(ptht);
2415                //pth++;
2416                //if ( pth < rhev ){
2417                //rh->GetEntry(pth);
2418              phh = ehh->GetPscuHeader();              phh = ehh->GetPscuHeader();
2419              pkth = phh->GetCounter();              pkth = phh->GetCounter();
2420              obth = phh->GetOrbitalTime();              obth = phh->GetOrbitalTime();
# Line 2257  Int_t PamelaDBOperations::insertPamelaRU Line 2438  Int_t PamelaDBOperations::insertPamelaRU
2438              if ( (UInt_t)evbeft < upperentry-1 && upperentry>0 ){              if ( (UInt_t)evbeft < upperentry-1 && upperentry>0 ){
2439                if ( IsDebug() ) printf(" Piece of run at the end of the file with NO RUNHEADER! evbeft %u upperentry-1 %u \n",(UInt_t)evbeft,upperentry-1);                if ( IsDebug() ) printf(" Piece of run at the end of the file with NO RUNHEADER! evbeft %u upperentry-1 %u \n",(UInt_t)evbeft,upperentry-1);
2440                //                //
2441                if ( (ptt-1) < 0 ) throw -15; // should never arrive here!                //              if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
2442                rt->GetEntry(ptt-1);                if ( (rtev-1) < 0 || ptt < 0 ) throw -15; // should never arrive here!
2443                  //              rt->GetEntry(ptt-1);
2444                  rt->GetEntry(rtev-1);
2445                cod = eht->GetCounter();                cod = eht->GetCounter();
2446                tcod = (UInt_t)cod->Get(pctp->Physics);                tcod = (UInt_t)cod->Get(pctp->Physics)+1;
2447                evbefh = TMath::Max(chminentry,tcod);                evbefh = TMath::Max(chminentry,tcod);
2448                //            evbefh = cod->Get(pctp->Physics);                //            evbefh = cod->Get(pctp->Physics);
2449                rt->GetEntry(ptt);                rt->GetEntry(ptt);
# Line 2367  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2550  Bool_t PamelaDBOperations::IsRunAlreadyI
2550        //        //
2551        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");
2552        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2553  //       oss.str("");        //       oss.str("");
2554  //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2555  //       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());      
2556  //       conn->Query(oss.str().c_str());        //       conn->Query(oss.str().c_str());
2557        if ( signal ) signal = false;        if ( signal ) signal = false;
2558        goto gonext;              goto gonext;      
2559        //        //
# Line 2385  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2568  Bool_t PamelaDBOperations::IsRunAlreadyI
2568        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");
2569        //        //
2570        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2571  //       oss.str("");        //       oss.str("");
2572  //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2573  //       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());      
2574  //       conn->Query(oss.str().c_str());        //       conn->Query(oss.str().c_str());
2575        //        //
2576        if ( signal ) signal = false;        if ( signal ) signal = false;
2577        goto gonext;        goto gonext;
# Line 2403  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2586  Bool_t PamelaDBOperations::IsRunAlreadyI
2586        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");
2587        //        //
2588        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2589  //       oss.str("");        //       oss.str("");
2590  //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2591  //       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());      
2592  //       conn->Query(oss.str().c_str());        //       conn->Query(oss.str().c_str());
2593        if ( signal ) signal = false;        if ( signal ) signal = false;
2594        //        //
2595      };      };
# Line 2488  void PamelaDBOperations::HandleRunFragme Line 2671  void PamelaDBOperations::HandleRunFragme
2671      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");
2672      //      //
2673    } 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 ){  
2674      //      //
2675      // 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
2676      //      //
2677      if ( IsDebug() ) printf(" The run is new \n");      if ( firstev != (lastev+1) ){ // could be a problem sometimes (?)
2678      if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");        if ( rhfirstev != firstev && !mishead ) mishead = true;
2679          if ( rtlastev != lastev && !mistrail ) mistrail = true;
2680        };
2681      //      //
2682      glrun->SetID(this->AssignRunID());      if ( IsDebug() ) printf(" bhere firstev is %i lastev is %i \n",firstev,lastev);
2683      glrun->SetID_RUN_FRAG(0);      this->FillClass(mishead,mistrail,firstev,lastev);
2684      glrun->Fill_GL_RUN_FRAGMENTS(conn);      if ( IsDebug() ) printf(" chere firstev is %i lastev is %i \n",firstev,lastev);
2685      //      //
2686    } else {      if ( IsDebug() ) printf("The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
2687      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());
2688      if ( PEDANTIC ) throw -69;      //
2689      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  
2690      //      //
2691      oss.str("");      oss.str("");
2692      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 "
2693          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
2694          << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "          << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
2695          << " ID != " << glrun->ID          << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
2696          << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!          << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
2697            << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2698            << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
2699            << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
2700            << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2701            << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
2702            << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
2703            << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2704            << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
2705            << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
2706      //      //
2707      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());
2708      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
2709      //      //
2710      if ( !result ) throw -4;      if ( !result ) throw -4;
2711      //      //
2712      row = result->Next();      row = result->Next();
2713      //      //
2714      if ( !row && NoFrag() ){      if ( !row ){
2715          //
2716          // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
2717          //
2718          if ( IsDebug() ) printf(" The run is new \n");
2719          if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
2720          //
2721          glrun->SetID(this->AssignRunID());
2722          glrun->SetID_RUN_FRAG(0);
2723          glrun->Fill_GL_RUN_FRAGMENTS(conn);
2724          //
2725        } else {
2726          if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
2727          if ( PEDANTIC ) throw -69;
2728          return;
2729        };
2730        //
2731        if ( chewbacca && mishead && mistrail ) goto justcheck;
2732        //
2733        // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
2734        //    
2735        if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
2736          // missing it no way we can found a piece in the frag table
2737        //        //
2738        oss.str("");        oss.str("");
2739        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 "
2740            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2741            << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "            << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2742            << " ID != " << glrun->ID            << " ID != " << glrun->ID
2743            << " 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!!
2744        //        //
2745        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());
2746        result = conn->Query(oss.str().c_str());        result = conn->Query(oss.str().c_str());
2747        //        //
2748        if ( !result ) throw -4;        if ( !result ) throw -4;
2749        //        //
       foundinrun = true;  
       //  
2750        row = result->Next();        row = result->Next();
2751        //        //
2752      };        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)));  
2753          //          //
2754          chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;            oss.str("");
2755            oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
2756                << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2757                << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2758                << " ID != " << glrun->ID
2759                << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
2760            //
2761            if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
2762            result = conn->Query(oss.str().c_str());
2763            //
2764            if ( !result ) throw -4;
2765            //
2766            foundinrun = true;
2767            //
2768            row = result->Next();
2769          //          //
         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;  
           //  
         };  
2770        };        };
2771        if ( !found && chewbacca ) goto justcheck;        //
2772        if ( !found ){        if ( !row ){
2773            if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2774            found = false;
2775          } else {
2776            //
2777            found = false; // default value
2778          //          //
2779          // if we arrive here we were not able to decide if the two pieces matches using only the pkt counter information, we must check times and obts          if ( IsDebug() ) printf(" A Found a possible candidate, checking if it is the good one... \n");
2780          //          //
2781          ULong64_t chkpkt1 = 0;          // if we have both runheader and runtrailer we can check with pkt_counter:
         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);  
2782          //          //
2783          if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){          if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){
2784            //    if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){            ULong64_t chkpkt = 0;  
2785              ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
2786              ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
2787            //            //
2788            if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);            chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;  
2789            //            //
2790            found = true;            if ( labs(chkpkt-pktt)<2 ){
2791                //
2792                if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
2793                //
2794                found = true;
2795                if ( IsDebug() ) printf(" where firstev is %i lastev is %i \n",firstev,lastev);
2796                //
2797              } else {
2798                //
2799                if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);            
2800                //
2801                found = false;
2802                //
2803              };
2804            };
2805            if ( !found && chewbacca ) goto justcheck;
2806            if ( !found ){
2807            //            //
2808          } 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
2809            //            //
2810            if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);            ULong64_t chkpkt1 = 0;
2811              ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
2812              ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
2813              chkpkt1 = labs(orunh1-dbrunt1);
2814            //            //
2815            found = false;            ULong64_t chkpkt2 = 0;
2816              ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());
2817              ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
2818              chkpkt2 = labs(orunh2-dbrunt2);
2819            //            //
2820              ULong64_t chkpkt3 = 0;
2821              ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());
2822              ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
2823              chkpkt3 = labs(orunh3-dbrunt3);
2824              //
2825              if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
2826                //  if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){
2827                //
2828                if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
2829                //
2830                found = true;
2831                //
2832              } else {
2833                //
2834                if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
2835                //
2836                found = false;
2837                //
2838              };
2839          };          };
2840        };        };
     };  
     //  
     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));  
2841        //        //
2842        oss.str("");        if ( found ){
2843        oss << " ID="<<row->GetField(0)<<";";          //
2844        //          // 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
2845        glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos          //
2846        //          if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
2847        // merge infos          //
2848        //          if ( foundinrun ){
2849        UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());            glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2850        ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());            glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2851        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() ){  
2852          //          //
2853          //      glrun->SetID(this->AssignRunID());          GL_RUN *glrun1 = new GL_RUN();
2854          glrun->SetID_RUN_FRAG(glrun1->GetID());          //
2855          glrun->Fill_GL_RUN(conn);          //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
2856            //
2857            oss.str("");
2858            oss << " ID="<<row->GetField(0)<<";";
2859          //          //
2860          // set id number          glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos
2861            if ( IsDebug() ) printf(" there firstev is %i lastev is %i \n",firstev,lastev);
2862          //          //
2863          glrun1->SetID_RUN_FRAG(glrun->GetID());          // merge infos
2864          glrun1->Fill_GL_RUN(conn);          //
2865            UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());
2866            ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
2867            UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
2868            ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
2869            if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2870            TTree *T= 0;
2871            T = (TTree*)file->Get("Physics");
2872            if ( !T || T->IsZombie() ) throw -16;
2873            EventHeader *eh = 0;
2874            PscuHeader *ph = 0;
2875            T->SetBranchAddress("Header", &eh);
2876            while ( apkt > bpkt && aobt > bobt && firstev < lastev ){
2877              T->GetEntry(firstev);
2878              ph = eh->GetPscuHeader();
2879              bpkt = PKT(ph->GetCounter());
2880              bobt = OBT(ph->GetOrbitalTime());    
2881              firstev++;
2882              if ( PEDANTIC ) throw -71;
2883            };
2884            if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2885            //
2886            glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
2887            glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
2888            glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
2889            glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());
2890            glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());
2891            //
2892            if ( IsDebug() ) printf(" here firstev is %i lastev is %i \n",firstev,lastev);
2893            //
2894            glrun->SetEV_FROM(firstev);
2895            glrun->SetNEVENTS(lastev-firstev+1);
2896            //
2897            glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
2898            glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
2899            glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
2900            glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());
2901            glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());
2902            glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());
2903            glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());
2904            glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());
2905            glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());
2906            glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());
2907            glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());  
2908            glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());  
2909            glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());  
2910            glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());  
2911            glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());  
2912            glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());  
2913            //
2914            if ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
2915            if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
2916            //
2917            if ( !IsRunAlreadyInserted() ){
2918              //
2919              //    glrun->SetID(this->AssignRunID());
2920              glrun->SetID_RUN_FRAG(glrun1->GetID());
2921              glrun->Fill_GL_RUN(conn);
2922              //
2923              // set id number
2924              //
2925              glrun1->SetID_RUN_FRAG(glrun->GetID());
2926              glrun1->Fill_GL_RUN(conn);
2927              //
2928            };
2929            // delete old entry in fragment table
2930            //
2931            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2932            glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2933            //
2934            delete glrun1;
2935            //
2936            //
2937            return;
2938          //          //
2939        };        };
       // delete old entry in fragment table  
       //  
       glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       //  
       delete glrun1;  
       //  
       //  
       return;  
2940        //        //
2941      };      };
2942      //      //
2943    };      if ( mistrail && ( rtlastev == lastev || chewbacca )) { // look for runtrailer (only when at the end of the file, if at the beginning and the runh is
2944    //        // 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() ){  
2945        //        //
2946        oss.str("");        oss.str("");
2947        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 "
2948            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2949            << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "            << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2950            << " ID != " << glrun->ID            << " ID != " << glrun->ID
2951            << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";            << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2952        //        //
2953        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());
2954        result = conn->Query(oss.str().c_str());        result = conn->Query(oss.str().c_str());
2955        //        //
2956        if ( !result ) throw -4;        if ( !result ) throw -4;
2957        //        //
       foundinrun = true;  
2958        row = result->Next();        row = result->Next();
2959        //        //
2960      };        if ( !row && NoFrag() ){
2961      //          //
2962      if ( !row ){          oss.str("");
2963        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 "
2964        found = false;              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2965      } else {              << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2966        //              << " ID != " << glrun->ID
2967        found = false; // default value              << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2968        //          //
2969        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());
2970        //          result = conn->Query(oss.str().c_str());
2971        // if we have both runheader and runtrailer we can check with pkt_counter:          //
2972            if ( !result ) throw -4;
2973            //
2974            foundinrun = true;
2975            row = result->Next();
2976            //
2977          };
2978        //        //
2979        if ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){        if ( !row ){
2980          ULong64_t chkpkt = 0;            if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2981          ULong64_t pktt = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));          found = false;
2982          ULong64_t pkth = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());        } else {
2983            //
2984            found = false; // default value
2985          //          //
2986          chkpkt = pkth + (ULong64_t)((UInt_t)atoll(row->GetField(1))) + 1ULL + 1ULL;            if ( IsDebug() ) printf(" B Found a possible candidate, checking if it is the good one... \n");
2987          //          //
2988          if ( labs(chkpkt-pktt)<2 ){          // if we have both runheader and runtrailer we can check with pkt_counter:
2989            //
2990            if ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){
2991              ULong64_t chkpkt = 0;  
2992              ULong64_t pktt = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
2993              ULong64_t pkth = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
2994            //            //
2995            if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);            chkpkt = pkth + (ULong64_t)((UInt_t)atoll(row->GetField(1))) + 1ULL + 1ULL;  
2996            //            //
2997            found = true;            if ( labs(chkpkt-pktt)<2 ){
2998                //
2999                if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
3000                //
3001                found = true;
3002                //
3003              } else {
3004                //
3005                if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);            
3006                //
3007                found = false;
3008                //
3009              };
3010            };
3011            if ( !found && chewbacca ) goto justcheck;
3012            if ( !found ){
3013            //            //
3014          } 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
3015            //            //
3016            if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);                  ULong64_t chkpkt1 = 0;
3017              ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
3018              ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
3019              chkpkt1 = labs(orunh1-dbrunt1);
3020            //            //
3021            found = false;            ULong64_t chkpkt2 = 0;
3022              ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNTRAILER_OBT());
3023              ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
3024              chkpkt2 = labs(orunh2-dbrunt2);
3025            //            //
3026              ULong64_t chkpkt3 = 0;
3027              ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNTRAILER_TIME());
3028              ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
3029              chkpkt3 = labs(orunh3-dbrunt3);
3030              //
3031              if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
3032                //
3033                if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
3034                //
3035                found = true;
3036                //
3037              } else {
3038                //
3039                if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
3040                //
3041                found = false;
3042                //
3043              };
3044          };          };
3045        };        };
3046        if ( !found && chewbacca ) goto justcheck;        //
3047        if ( !found ){        if ( found ){
3048            //
3049            // 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
3050            //
3051            if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
3052          //          //
3053          // if we arrive here we were not able to decide if the two pieces matches using only the pkt counter information, we must check times and obts          if ( foundinrun ){
3054              glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3055              glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
3056            };
3057          //          //
3058          ULong64_t chkpkt1 = 0;          GL_RUN *glrun1 = new GL_RUN();
         ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());  
         ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));  
         chkpkt1 = labs(orunh1-dbrunt1);  
3059          //          //
3060          ULong64_t chkpkt2 = 0;          //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
         ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNTRAILER_OBT());  
         ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));  
         chkpkt2 = labs(orunh2-dbrunt2);  
3061          //          //
3062          ULong64_t chkpkt3 = 0;          oss.str("");
3063          ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNTRAILER_TIME());          oss << " ID="<<row->GetField(0)<<";";
         ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));  
         chkpkt3 = labs(orunh3-dbrunt3);  
3064          //          //
3065          if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){          glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runtrailer infos
3066            //          //
3067            if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);          // merge infos
3068            //          //
3069            found = true;          UInt_t apkt = PKT(glrun->GetRUNTRAILER_PKT());
3070            //          ULong64_t aobt = OBT(glrun->GetRUNTRAILER_OBT());
3071          } else {          UInt_t bpkt = PKT(glrun1->GetRUNHEADER_PKT());
3072            ULong64_t bobt = OBT(glrun1->GetRUNHEADER_OBT());
3073            if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
3074            TTree *T= 0;
3075            T = (TTree*)file->Get("Physics");
3076            if ( !T || T->IsZombie() ) throw -16;
3077            EventHeader *eh = 0;
3078            PscuHeader *ph = 0;
3079            T->SetBranchAddress("Header", &eh);
3080            while ( apkt > bpkt && aobt > bobt && lastev > 0 ){
3081              T->GetEntry(lastev);
3082              ph = eh->GetPscuHeader();
3083              apkt = PKT(ph->GetCounter());
3084              aobt = OBT(ph->GetOrbitalTime());    
3085              lastev--;
3086              if ( PEDANTIC ) throw -72;
3087            };
3088            if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
3089            //
3090            glrun->SetEV_TO(lastev);
3091            glrun->SetNEVENTS(lastev-firstev+1);
3092            glrun->SetPKT_COUNTER(glrun1->GetPKT_COUNTER());
3093            glrun->SetPKT_READY_COUNTER(glrun1->GetPKT_READY_COUNTER());
3094            glrun->SetRUNTRAILER_TIME(glrun1->GetRUNTRAILER_TIME());
3095            glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());
3096            glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());
3097            //
3098            glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());
3099            glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());
3100            glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());
3101            glrun1->SetCOMPILATIONTIMESTAMP(glrun->GetCOMPILATIONTIMESTAMP());
3102            glrun1->SetFAV_WRK_SCHEDULE(glrun->GetFAV_WRK_SCHEDULE());
3103            glrun1->SetEFF_WRK_SCHEDULE(glrun->GetEFF_WRK_SCHEDULE());
3104            glrun1->SetPRH_VAR_TRG_MODE_A(glrun->GetPRH_VAR_TRG_MODE_A());
3105            glrun1->SetPRH_VAR_TRG_MODE_B(glrun->GetPRH_VAR_TRG_MODE_B());
3106            glrun1->SetACQ_BUILD_INFO(glrun->GetACQ_BUILD_INFO());
3107            glrun1->SetACQ_VAR_INFO(glrun->GetACQ_VAR_INFO());
3108            glrun1->SetRM_ACQ_AFTER_CALIB(glrun->GetRM_ACQ_AFTER_CALIB());  
3109            glrun1->SetRM_ACQ_SETTING_MODE(glrun->GetRM_ACQ_SETTING_MODE());  
3110            glrun1->SetTRK_CALIB_USED(glrun->GetTRK_CALIB_USED());  
3111            glrun1->SetCAL_DSP_MASK(glrun->GetCAL_DSP_MASK());  
3112            glrun1->SetLAST_TIMESYNC(glrun->GetLAST_TIMESYNC());  
3113            glrun1->SetOBT_TIMESYNC(glrun->GetOBT_TIMESYNC());  
3114            //
3115            if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ) glrun1->SetPHYSENDRUN_MASK_S3S2S12(glrun->GetPHYSENDRUN_MASK_S3S2S12());
3116            if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) glrun1->SetPHYSENDRUN_MASK_S11CRC(glrun->GetPHYSENDRUN_MASK_S11CRC());
3117            //
3118            if ( !IsRunAlreadyInserted() ){
3119              //
3120              //    glrun->SetID(this->AssignRunID());
3121              //
3122              glrun->SetID_RUN_FRAG(glrun1->GetID());
3123              glrun->Fill_GL_RUN(conn);
3124            //            //
3125            if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);            // set id number
3126            //            //
3127            found = false;            glrun1->SetID_RUN_FRAG(glrun->GetID());
3128              glrun1->Fill_GL_RUN(conn);
3129            //            //
3130          };          };
3131            //
3132            // delete old entries in fragment table
3133            //
3134            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3135            glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3136            //
3137            delete glrun1;
3138            //
3139            return;
3140            //
3141        };        };
3142          //
3143      };      };
3144      //      //
3145      if ( found ){    justcheck:
3146        //      //
3147        // 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");  
       };  
3148        //        //
3149        GL_RUN *glrun1 = new GL_RUN();        if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");
3150        //        //
3151        //      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?
3152        //        //
3153        oss.str("");        oss.str("");
3154        oss << " ID="<<row->GetField(0)<<";";        oss << " SELECT ID FROM GL_RUN WHERE "
3155              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3156              << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3157              << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3158              << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3159              << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3160              << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3161              << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3162              << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3163              << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3164              << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3165              << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3166              << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3167              << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3168        //        //
3169        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());
3170          result = conn->Query(oss.str().c_str());
3171        //        //
3172        // merge infos        if ( !result ) throw -4;
3173        //        //
3174        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());    
3175        //        //
3176        if ( !IsRunAlreadyInserted() ){        if ( row ){
3177          //          if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");
3178          //      glrun->SetID(this->AssignRunID());          if ( PEDANTIC ) throw -70;
3179          //        } else {
3180          glrun->SetID_RUN_FRAG(glrun1->GetID());          if ( NoFrag() ){
3181          glrun->Fill_GL_RUN(conn);            glrun->SetID_RUN_FRAG(glrun->GetID());
3182          //            glrun->Fill_GL_RUN(conn);    
3183          // set id number            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3184          //          };    
         glrun1->SetID_RUN_FRAG(glrun->GetID());  
         glrun1->Fill_GL_RUN(conn);  
         //  
3185        };        };
       //  
       // 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");  
       };      
3186      };      };
   };  
3187    }; // EEE    }; // EEE
3188    //    //
3189    return;    return;
# Line 3015  void PamelaDBOperations::HandleMissingHo Line 3212  void PamelaDBOperations::HandleMissingHo
3212        glrun->SetID(this->AssignRunID());        glrun->SetID(this->AssignRunID());
3213        glrun->SetID_RUN_FRAG(0);        glrun->SetID_RUN_FRAG(0);
3214        glrun->Fill_GL_RUN(conn);    // it'ok we arrive here only inside a file hence in the middle of the runs...        glrun->Fill_GL_RUN(conn);    // it'ok we arrive here only inside a file hence in the middle of the runs...
3215      };        };
3216      //      //
3217    };    };
3218    //    //
# Line 3059  Bool_t PamelaDBOperations::IsRunConsiste Line 3256  Bool_t PamelaDBOperations::IsRunConsiste
3256    if ( firstev == lastev+1 || lastev == firstev ) { // no events inside the run!    if ( firstev == lastev+1 || lastev == firstev ) { // no events inside the run!
3257      //if ( firstev <= lastev+1 ) { // no events inside the run!      //if ( firstev <= lastev+1 ) { // no events inside the run!
3258      if ( IsDebug() ) printf(" Checking but no events in the run! \n");      if ( IsDebug() ) printf(" Checking but no events in the run! \n");
3259        firstev = lastev+1; // this is necessary for files with no Physics entries, should have no influence on other files
3260      // return true is correct      // return true is correct
3261      return(true);      return(true);
3262      //      //
# Line 3068  Bool_t PamelaDBOperations::IsRunConsiste Line 3266  Bool_t PamelaDBOperations::IsRunConsiste
3266      code = eh->GetCounter();      code = eh->GetCounter();
3267      checkfirst = 0;      checkfirst = 0;
3268      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3269         if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
3270       };      };
3271      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);
3272      //      //
3273      T->GetEntry(lastev);      T->GetEntry(lastev);
3274      code = eh->GetCounter();      code = eh->GetCounter();
3275      checklast = 0;      checklast = 0;
3276      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3277         if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
3278       };      };
3279      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);
3280      //      //
3281      if ( checkfirst == checklast ){      if ( checkfirst == checklast ){
# Line 3088  Bool_t PamelaDBOperations::IsRunConsiste Line 3286  Bool_t PamelaDBOperations::IsRunConsiste
3286        //        //
3287      } else {      } else {
3288        //        //
3289        if ( IsDebug() ) printf(" There are no-phyics packets inside the run!\n");        if ( IsDebug() ) printf(" There are no-physics packets inside the run!\n");
3290        //        //
3291        // HERE WE MUST HANDLE THAT RUNS AND GO BACK        // HERE WE MUST HANDLE THAT RUNS AND GO BACK
3292        //        //
3293  //      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");
3294        //        //
3295        Bool_t emptyruns = false;        Bool_t emptyruns = false;
3296        UInt_t check = 0;        UInt_t check = 0;
3297        UInt_t lastevtemp = lastev;        UInt_t lastevtemp = lastev;
3298        UInt_t firstevno = firstev;        UInt_t firstevno = firstev;
3299          UInt_t rhchko=0;
3300          UInt_t rhchk=0;
3301        //        //
3302        for (UInt_t i=firstev; i<=lastev; i++){        for (UInt_t i=firstev; i<=lastev; i++){
3303          //          //
# Line 3106  Bool_t PamelaDBOperations::IsRunConsiste Line 3306  Bool_t PamelaDBOperations::IsRunConsiste
3306          //          //
3307          check = 0;          check = 0;
3308          //          //
3309    
3310            // if we have a runheader set lastev then exit
3311            //
3312          for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){          for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3313            if ( strcmp(*Iter,"Physics") ) check += code->Get(GetPacketType(*Iter));            if ( strcmp(*Iter,"Physics") ) check += code->Get(GetPacketType(*Iter));
3314          };          };
3315            // check here if we have a runheader
3316            rhchko = rhchk;  
3317            rhchk = code->Get(GetPacketType("RunHeader"));    
3318          //          //
3319          if ( checkfirst < check || i == lastev ){          if ( checkfirst < check || i == lastev ){
3320            //            //
# Line 3184  Bool_t PamelaDBOperations::IsRunConsiste Line 3390  Bool_t PamelaDBOperations::IsRunConsiste
3390            };            };
3391            //                  //      
3392            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
3393              this->SetPhysEndRunVariables();
3394            //            //
3395            if ( chminentry == firstentry  ){ // EEE            if ( chminentry == firstentry  ){ // EEE
3396              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");
3397  //              //
3398  //          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
3399  //              //
   
   
   
   
   
   
   
   
   
   
   
   
   
   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  
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
3400    
3401                mishead = true;
3402    
3403    
3404                UInt_t rhfirstev = firstentry;
3405                //  UInt_t rtlastev = lastentry;
3406                Bool_t found = false;
3407                Bool_t foundinrun = false;
3408                //
3409                TSQLResult *result = 0;
3410                TSQLRow    *row    = 0;
3411                //
3412                stringstream oss;
3413                oss.str("");
3414                //
3415                // we have now the good first piece of a run, fill the glrun object
3416                //
3417                //  if ( rhfirstev != firstev && !mishead ) mishead = true;
3418                //  if ( rtlastev != lastev && !mistrail ) mistrail = true;
3419                //
3420                //  this->FillClass(mishead,mistrail,firstev,lastev);
3421                //
3422                if ( IsDebug() ) printf("zz The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
3423                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());
3424                //
3425                // First of all insert the run in the fragment table...
3426                //
3427                oss.str("");
3428                oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
3429                    << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3430                    << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3431                    << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3432                    << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3433                    << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3434                    << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3435                    << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3436                    << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3437                    << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3438                    << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3439                    << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3440                    << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3441                    << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3442                //
3443                if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3444                result = conn->Query(oss.str().c_str());
3445                //
3446                if ( !result ) throw -4;
3447                //
3448                row = result->Next();
3449                //
3450                if ( !row ){
3451                  //
3452                  // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
3453                  //
3454                  if ( IsDebug() ) printf(" The run is new \n");
3455                  if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
3456                  //
3457                  glrun->SetID(this->AssignRunID());
3458                  glrun->SetID_RUN_FRAG(0);
3459                  glrun->Fill_GL_RUN_FRAGMENTS(conn);
3460                  //
3461                } else {
3462                  if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
3463                  if ( PEDANTIC ) throw -69;
3464                  //    return;
3465                };
3466                //
3467                if ( chewbacca && mishead && mistrail ) goto zjustcheck;
3468                //
3469                // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
3470                //
3471                if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
3472                  // missing it no way we can found a piece in the frag table
3473                  //
3474                  oss.str("");
3475                  oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "
3476                      << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3477                      << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3478                      << " ID != " << glrun->ID
3479                      << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
3480                  //
3481                  if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());
3482                  result = conn->Query(oss.str().c_str());
3483                  //
3484                  if ( !result ) throw -4;
3485                  //
3486                  row = result->Next();
3487                  //
3488                  if ( !row && NoFrag() ){
3489                    //
3490                    oss.str("");
3491                    oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
3492                        << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3493                        << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3494                        << " ID != " << glrun->ID
3495                        << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
3496                    //
3497                    if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
3498                    result = conn->Query(oss.str().c_str());
3499                    //
3500                    if ( !result ) throw -4;
3501                    //
3502                    foundinrun = true;
3503                    //
3504                    row = result->Next();
3505                    //
3506                  };
3507                  //
3508                  if ( !row ){
3509                    if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
3510                    found = false;
3511                  } else {
3512                    //
3513                    found = false; // default value
3514                    //
3515                    if ( IsDebug() ) printf(" C Found a possible candidate, checking if it is the good one... \n");
3516                    //
3517                    // if we have both runheader and runtrailer we can check with pkt_counter:
3518                    //
3519                    if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){
3520                      ULong64_t chkpkt = 0;
3521                      ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
3522                      ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
3523                      //
3524                      chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;
3525                      //
3526                      if ( labs(chkpkt-pktt)<2 ){
3527                        //
3528                        if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
3529                        //
3530                        found = true;
3531                        //
3532                      } else {
3533                        //
3534                        if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);
3535                        //
3536                        found = false;
3537                        //
3538                      };
3539                    };
3540                    if ( !found && chewbacca ) goto zjustcheck;
3541                    if ( !found ){
3542                      //
3543                      // 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
3544                      //
3545                      ULong64_t chkpkt1 = 0;
3546                      ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
3547                      ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
3548                      chkpkt1 = labs(orunh1-dbrunt1);
3549                      //
3550                      ULong64_t chkpkt2 = 0;
3551                      ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());
3552                      ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
3553                      chkpkt2 = labs(orunh2-dbrunt2);
3554                      //
3555                      ULong64_t chkpkt3 = 0;
3556                      ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());
3557                      ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
3558                      chkpkt3 = labs(orunh3-dbrunt3);
3559                      //
3560                      if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
3561                        //    if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){
3562                        //
3563                        if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
3564                        //
3565                        found = true;
3566                        //
3567                      } else {
3568                        //
3569                        if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
3570                        //
3571                        found = false;
3572                        //
3573                      };
3574                    };
3575                  };
3576                  //
3577                  if ( found ){
3578                    //
3579                    // 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
3580                    //
3581                    if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
3582                    //
3583                    if ( foundinrun ){
3584                      glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3585                      glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
3586                    };
3587                    //
3588                    GL_RUN *glrun1 = new GL_RUN();
3589                    //
3590                    //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
3591                    //
3592                    oss.str("");
3593                    oss << " ID="<<row->GetField(0)<<";";
3594                    //
3595                    glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos
3596                    //
3597                    // merge infos
3598                    //
3599                    UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());
3600                    ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
3601                    UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
3602                    ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
3603                    if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
3604                    TTree *T= 0;
3605                    T = (TTree*)file->Get("Physics");
3606                    if ( !T || T->IsZombie() ) throw -16;
3607                    EventHeader *eh = 0;
3608                    PscuHeader *ph = 0;
3609                    T->SetBranchAddress("Header", &eh);
3610                    while ( apkt > bpkt && aobt > bobt && firstev < lastev ){
3611                      T->GetEntry(firstev);
3612                      ph = eh->GetPscuHeader();
3613                      bpkt = PKT(ph->GetCounter());
3614                      bobt = OBT(ph->GetOrbitalTime());
3615                      firstev++;
3616                      if ( PEDANTIC ) throw -71;
3617                    };
3618                    if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
3619                    //
3620                    glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
3621                    glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
3622                    glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
3623                    glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());
3624                    glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());
3625                    //
3626                    glrun->SetEV_FROM(firstev);
3627                    glrun->SetNEVENTS(lastev-firstev+1);
3628                    //
3629                    glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
3630                    glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
3631                    glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
3632                    glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());
3633                    glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());
3634                    glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());
3635                    glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());
3636                    glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());
3637                    glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());
3638                    glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());
3639                    glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());
3640                    glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());
3641                    glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());
3642                    glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());
3643                    glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());
3644                    glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());
3645                    //
3646                    if ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
3647                    if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
3648                    //
3649                    if ( !IsRunAlreadyInserted() ){
3650                      //
3651                      //      glrun->SetID(this->AssignRunID());
3652                      glrun->SetID_RUN_FRAG(glrun1->GetID());
3653                      glrun->Fill_GL_RUN(conn);
3654                      //
3655                      // set id number
3656                      //
3657                      glrun1->SetID_RUN_FRAG(glrun->GetID());
3658                      glrun1->Fill_GL_RUN(conn);
3659                      //
3660                    };
3661                    // delete old entry in fragment table
3662                    //
3663                    glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3664                    glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3665                    //
3666                    delete glrun1;
3667                    //
3668                    //
3669                    //      return;
3670                    //
3671                  };
3672                  //
3673                };
3674                //
3675                //
3676              zjustcheck:
3677                //
3678                if ( !found ){
3679                  //
3680                  if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");
3681                  //
3682                  // not found, has this run already inserted in the GL_RUN or in the GL_RUN_FRAGMENTS table?
3683                  //
3684                  oss.str("");
3685                  oss << " SELECT ID FROM GL_RUN WHERE "
3686                      << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3687                      << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3688                      << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3689                      << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3690                      << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3691                      << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3692                      << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3693                      << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3694                      << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3695                      << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3696                      << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3697                      << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3698                      << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3699                  //
3700                  if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3701                  result = conn->Query(oss.str().c_str());
3702                  //
3703                  if ( !result ) throw -4;
3704                  //
3705                  row = result->Next();
3706                  //
3707                  if ( row ){
3708                    if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");
3709                    if ( PEDANTIC ) throw -70;
3710                  } else {
3711                    if ( NoFrag() ){
3712                      glrun->SetID_RUN_FRAG(glrun->GetID());
3713                      glrun->Fill_GL_RUN(conn);
3714                      glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3715                    };
3716                  };
3717                }; // EEE
3718    
3719    
3720            } else {            } else {
3721            if ( !IsRunAlreadyInserted() ){              if ( !IsRunAlreadyInserted() ){
3722              glrun->SetID(this->AssignRunID());                glrun->SetID(this->AssignRunID());
3723              glrun->SetID_RUN_FRAG(0);                glrun->SetID_RUN_FRAG(0);
3724              glrun->Fill_GL_RUN(conn);                glrun->Fill_GL_RUN(conn);
3725            };              };
3726            }; // EEE            }; // EEE
3727            //            //
3728            firstevno = lastentry + 1;            firstevno = lastentry + 1;
# Line 3564  Bool_t PamelaDBOperations::IsRunConsiste Line 3731  Bool_t PamelaDBOperations::IsRunConsiste
3731            //            //
3732          };          };
3733          //          //
3734            if ( i > firstev ){
3735              if ( rhchko != rhchk ){
3736                if ( IsDebug() ) printf("oh oh... we have a runheader! stop here and handle later the remaining piece\n");
3737                lastev = i;
3738                return(false);
3739              };
3740            };
3741            //
3742          if ( check == checklast && i != lastev ){          if ( check == checklast && i != lastev ){
3743            lastevtemp = i - 1;            lastevtemp = i - 1;
3744            i = lastev - 1;            i = lastev - 1;
# Line 3647  void PamelaDBOperations::HandleSuspiciou Line 3822  void PamelaDBOperations::HandleSuspiciou
3822      code = eh->GetCounter();      code = eh->GetCounter();
3823      checkfirst = 0;      checkfirst = 0;
3824      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3825         if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
3826         if ( !strcmp(*Iter,"RunHeader") ) nrunh1++;        if ( !strcmp(*Iter,"RunHeader") ) nrunh1++;
3827       };      };
3828      if ( IsDebug() ) printf(" Check first is %i \n",checkfirst);      if ( IsDebug() ) printf(" Check first is %i \n",checkfirst);
3829      //      //
3830      T->GetEntry(lastev);      T->GetEntry(lastev);
3831      code = eh->GetCounter();      code = eh->GetCounter();
3832      checklast = 0;      checklast = 0;
3833      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3834         if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
3835       };      };
3836      if ( IsDebug() ) printf(" Check last is %i \n",checklast);      if ( IsDebug() ) printf(" Check last is %i \n",checklast);
3837      //      //
3838      if ( checkfirst == checklast ){      if ( checkfirst == checklast ){
# Line 3769  void PamelaDBOperations::HandleSuspiciou Line 3944  void PamelaDBOperations::HandleSuspiciou
3944            };            };
3945            //                  //      
3946            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
3947              this->SetPhysEndRunVariables();
3948            //            //
3949            if ( !IsRunAlreadyInserted() ){            if ( !IsRunAlreadyInserted() ){
3950              glrun->SetID(this->AssignRunID());              glrun->SetID(this->AssignRunID());
# Line 3808  void PamelaDBOperations::HandleSuspiciou Line 3984  void PamelaDBOperations::HandleSuspiciou
3984              if ( IsDebug() ) printf(" We have the runtrailer \n");              if ( IsDebug() ) printf(" We have the runtrailer \n");
3985              //                  //    
3986              this->SetCommonGLRUN(firstTime,lastTime);              this->SetCommonGLRUN(firstTime,lastTime);
3987                this->SetPhysEndRunVariables();
3988              //              //
3989              if ( !IsRunAlreadyInserted() ){              if ( !IsRunAlreadyInserted() ){
3990                glrun->SetID(this->AssignRunID());                glrun->SetID(this->AssignRunID());
# Line 4382  Int_t PamelaDBOperations::insertCALOPULS Line 4559  Int_t PamelaDBOperations::insertCALOPULS
4559   * Fill the GL_TRK_CALIB table   * Fill the GL_TRK_CALIB table
4560   */   */
4561  void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){  void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){
4562    //      
4563    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;  
4564      //      //
4565    } else {      glcal->ID         = 0;
4566        glcal->ID_ROOT_L0 = GetID_ROOT();
4567        glcal->EV_ROOT_CALIBTRK1 = t1;
4568        glcal->EV_ROOT_CALIBTRK2 = t2;
4569        glcal->FROM_TIME = fromtime;
4570        glcal->TO_TIME   = 0;
4571        glcal->OBT1      = obt1;
4572        glcal->OBT2      = obt2;
4573        glcal->PKT1      = pkt1;
4574        glcal->PKT2      = pkt2;
4575        glcal->BOOT_NUMBER = GetBOOTnumber();
4576        glcal->VALIDATION = valid;
4577      //      //
4578      // we have to insert a new calibration, check where to place it      HandleTRK_CALIB(glcal);
4579      //      //
4580      oss.str("");      delete glcal;
4581      oss << " SELECT ID,TO_TIME FROM GL_TRK_CALIB WHERE "  }
4582          << " FROM_TIME < "<< fromtime << " AND "  /**
4583          << " TO_TIME > "<< fromtime << ";";   * Fill the GL_TRK_CALIB table
4584     */
4585    void PamelaDBOperations::HandleTRK_CALIB(GL_TRK_CALIB *glcal){
4586    
4587        Bool_t pk1 = (glcal->OBT1>0&&glcal->PKT1>0);
4588        Bool_t pk2 = (glcal->OBT2>0&&glcal->PKT2>0);
4589        UInt_t boot_number = glcal->BOOT_NUMBER;
4590        UInt_t obt1 = glcal->OBT1;
4591        UInt_t obt2 = glcal->OBT2;
4592        UInt_t pkt1 = glcal->PKT1;
4593        UInt_t pkt2 = glcal->PKT2;
4594        UInt_t fromtime = glcal->FROM_TIME;
4595        UInt_t totime = 0;
4596        UInt_t idroot = glcal->ID_ROOT_L0;
4597        UInt_t t1 = glcal->EV_ROOT_CALIBTRK1;
4598        UInt_t t2 = glcal->EV_ROOT_CALIBTRK2;
4599        UInt_t valid = glcal->VALIDATION;
4600      //      //
4601      if ( IsDebug() ) printf(" Check where to place the trk calibration: query is \n %s \n",oss.str().c_str());      TSQLResult *result = 0;
4602      result = conn->Query(oss.str().c_str());      TSQLRow    *row    = 0;
4603      //      //
4604      if ( !result ) throw -4;      stringstream oss;
4605        oss.str("");
4606      //      //
     row = result->Next();  
4607      //      //
4608      if ( !row ){      if ( !pk1 && !pk2 ){
4609        //          if ( IsDebug() ) printf(" Cannot handle trk calibration with both packet missing!\n");
4610        // 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;  
       //  
4611      };      };
4612      //      //
4613      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 << "',";  
4614      //      //
4615      if ( !pk1 ){      oss.str("");
4616        oss << "NULL,";      oss << " SELECT ID FROM GL_TRK_CALIB WHERE "
4617            << " BOOT_NUMBER = "<< boot_number; //
4618        oss << " AND FROM_TIME="<<fromtime; /// NEWNEWNEW -- VA BENE ?!?!?!?!
4619        oss << " AND ( ( ";  
4620        if ( pk1 ){
4621            oss << " OBT1 = "<< obt1 << " AND "
4622                << " PKT1 = "<< pkt1
4623                << " ) OR ( ";
4624      } else {      } else {
4625        oss << "'"          oss << " PKT1 = "<< pkt2-1
4626            << t1 << "',";              << " ) OR ( ";  
4627      };      };      
4628      //      if ( pk2 ){
4629      if ( !pk2 ){          oss << " OBT2 = "<< obt2 << " AND "
4630        oss << "NULL,'";              << " PKT2 = "<< pkt2;
4631      } else {      } else {
4632        oss << "'"          oss << " PKT2 = "<< pkt1+1;
4633            << t2 << "','";      };      
4634      };      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());  
4635      //      //
4636        if ( IsDebug() ) printf(" Check if the trk calibration has already been inserted: query is \n %s \n",oss.str().c_str());
4637      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
4638      //      //
4639      if ( !result ) throw -4;      if ( !result ) throw -4;
4640      //      //
4641    };      row = result->Next();
4642    //      //
4643        if ( row ){
4644            //
4645            if ( IsDebug() ) printf(" Trk calibration already inserted in the DB\n");
4646            if ( PEDANTIC ) throw -80;
4647            //
4648        } else {
4649            //
4650            // we have to insert a new calibration, check where to place it
4651            //
4652            oss.str("");
4653            oss << " SELECT ID,TO_TIME FROM GL_TRK_CALIB WHERE "
4654                << " FROM_TIME < "<< fromtime << " AND "
4655                << " TO_TIME > "<< fromtime << ";";
4656            //
4657            if ( IsDebug() ) printf(" Check where to place the trk calibration: query is \n %s \n",oss.str().c_str());
4658            result = conn->Query(oss.str().c_str());
4659            //
4660            if ( !result ) throw -4;
4661            //
4662            row = result->Next();
4663            //
4664            if ( !row ){
4665                //
4666                // no calibrations in the db contain our calibration
4667                //
4668                if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB\n");
4669                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
4670                //
4671                oss.str("");
4672                oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "
4673                    << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
4674                //
4675                if ( IsDebug() ) printf(" Check the upper limit for calibration: query is \n %s \n",oss.str().c_str());
4676                result = conn->Query(oss.str().c_str());
4677                //
4678                if ( !result ) throw -4;
4679                //
4680                row = result->Next();
4681                if ( !row ){
4682                    totime = numeric_limits<UInt_t>::max();
4683                } else {
4684                    totime = (UInt_t)atoll(row->GetField(0));
4685                };
4686                //
4687            } else {
4688                //
4689                // determine upper and lower limits and make space for the new calibration
4690                //
4691                totime = (UInt_t)atoll(row->GetField(1));
4692                //
4693                oss.str("");
4694                oss << " UPDATE GL_TRK_CALIB SET "  
4695                    << " TO_TIME = "<< fromtime << " WHERE "  // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
4696                    << " ID = "<< row->GetField(0) << ";";
4697                //
4698                if ( IsDebug() ) printf(" Make space for the new trk calibration: query is \n %s \n",oss.str().c_str());
4699                result = conn->Query(oss.str().c_str());
4700                //
4701                if ( !result ) throw -4;
4702                //
4703            };
4704            //
4705            oss.str("");
4706            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) "
4707                << " VALUES (NULL,' "
4708                << idroot << "',";
4709            //
4710            if ( !pk1 ){
4711                oss << "NULL,";
4712            } else {
4713                oss << "'"
4714                    << t1 << "',";
4715            };
4716            //
4717            if ( !pk2 ){
4718                oss << "NULL,'";
4719            } else {
4720                oss << "'"
4721                    << t2 << "','";
4722            };
4723            //
4724            oss << fromtime << "','"
4725                << totime << "','"
4726                << obt1 << "','"
4727                << pkt1 << "','"
4728                << obt2 << "','"
4729                << pkt2 << "','"
4730                << boot_number << "','"
4731                << valid << "');";
4732            //
4733            if ( IsDebug() ) printf(" Insert the new trk calibration: query is \n %s \n",oss.str().c_str());
4734            //
4735            result = conn->Query(oss.str().c_str());
4736            //
4737            if ( !result ) throw -4;
4738            //
4739        };
4740        
4741        oss.str("");
4742        oss << " SELECT ID FROM GL_TRK_CALIB ORDER BY ID DESC LIMIT 1 ;";  
4743        if ( IsDebug() ) cout << oss.str().c_str() << endl;
4744        result = conn->Query(oss.str().c_str());
4745        if ( !result ) throw -4;;
4746        row = result->Next();
4747        if(row)glcal->ID = (UInt_t)atoll(row->GetField(0));
4748    
4749        //
4750  };  };
4751    
4752  /**  /**
4753   * Scan tracker calibrations packets, fill the GL_TRK_CALIB table   * Scan tracker calibrations packets, fill the GL_TRK_CALIB table
4754   */   */
4755  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++){  
4756      //      //
4757      pret2 = t2;      CalibTrk1Event *caltrk1 = 0;
4758      tr1->GetEntry(t1);      CalibTrk2Event *caltrk2 = 0;
4759        TTree *tr1 = 0;
4760        TTree *tr2 = 0;
4761        EventHeader *eh1 = 0;
4762        PscuHeader *ph1 = 0;
4763        EventHeader *eh2 = 0;
4764        PscuHeader *ph2 = 0;
4765      //      //
4766      ph1 = eh1->GetPscuHeader();      PacketType *pctp=0;
4767      obt1 = ph1->GetOrbitalTime();        EventCounter *codt2=0;
     pkt1 = ph1->GetCounter();    
     fromtime = this->GetAbsTime(ph1->GetOrbitalTime());    
4768      //      //
4769  //     valid = 1;      Int_t nevents1 = 0;
4770  //     //      Int_t nevents2 = 0;
 //     if ( caltrk1->unpackError != 0 && caltrk1->good0 == 0 ) valid = 0;// CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT1  
4771      //      //
4772        fromtime = 0;
4773      //      //
4774      if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->PKT(pkt1) <= upperpkt && this->OBT(obt1) >= this->OBT(obtfirst) && this->OBT(obt1) <= upperobt ){      obt1 = 0;
4775        //    if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->OBT(obt1) >= this->OBT(obtfirst) ){      pkt1 = 0;
4776        //      obt2 = 0;
4777        if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u \n",fromtime,obt1,pkt1);      pkt2 = 0;
4778        //            //
4779        valid = ValidateTrkCalib( caltrk1, eh1 );      tr1 = (TTree*)file->Get("CalibTrk1");
4780        if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;      if ( !tr1 || tr1->IsZombie() ) throw -22;
4781        //      tr2 = (TTree*)file->Get("CalibTrk2");
4782        // Do we have the second calibration packet?      if ( !tr2 || tr2->IsZombie() ) throw -23;
4783        //      //
4784        while ( t2t1cal < t1+1 ){ // get the calibration packet2 that follows the packet1      tr1->SetBranchAddress("CalibTrk1", &caltrk1);
4785        tr1->SetBranchAddress("Header", &eh1);
4786        nevents1 = tr1->GetEntries();
4787        tr2->SetBranchAddress("CalibTrk2", &caltrk2);
4788        tr2->SetBranchAddress("Header", &eh2);
4789        nevents2 = tr2->GetEntries();
4790        //
4791        if ( !nevents1 && !nevents2 ) return(1);
4792        //
4793        t2 = -1;
4794        Int_t pret2 = 0;
4795        Int_t t2t1cal = 0;
4796        //
4797        bool MISSING_pkt1 = true;
4798        bool MISSING_pkt2 = true;
4799        int  ncalib = 0;
4800        bool try_to_recover = false;
4801        //
4802        for (t1=0; t1 < nevents1; t1++){//loop over packet1
4803            //
4804            pret2 = t2;
4805            tr1->GetEntry(t1);
4806          //          //
4807          t2++;          ph1 = eh1->GetPscuHeader();
4808            obt1 = ph1->GetOrbitalTime();  
4809            pkt1 = ph1->GetCounter();  
4810            fromtime = GetAbsTime(ph1->GetOrbitalTime());  
4811          //          //
4812          pret2 = t2 - 1; // EMILIANO          // chek if the packet number and obt are consistent with the other packets ???
4813          //          //
4814          if ( t2 < nevents2 ){          if ( PKT(pkt1) >= PKT(pktfirst) && PKT(pkt1) <= upperpkt && OBT(obt1) >= OBT(obtfirst) && OBT(obt1) <= upperobt ){
4815            tr2->GetEntry(t2);              //    if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->OBT(obt1) >= this->OBT(obtfirst) ){
4816            codt2 = eh2->GetCounter();              //
4817            t2t1cal = codt2->Get(pctp->CalibTrk1);              if ( IsDebug() ) printf("\n Trk calibration1 %u at time %u obt %u pkt %u \n",t1,fromtime,obt1,pkt1);
4818            //              //      
4819            ph2 = eh2->GetPscuHeader();              valid = ValidateTrkCalib( caltrk1, eh1 );
4820            obt2 = ph2->GetOrbitalTime();                if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;
4821            pkt2 = ph2->GetCounter();                //
4822            //              // Do we have the second calibration packet?
4823            if ( IsDebug() ) printf(" This is a trk calibration2 at obt %u pkt %u t2 is %u , t2t1cal is %u \n",obt2,pkt2,t2,t2t1cal);                    //
4824  //        if ( caltrk2->unpackError != 0 || caltrk2->good0 == 0 ) valid = 0; // CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT2              if ( IsDebug() ) cout << " Loop over calibration2 to search associated calibration: "<<endl;
4825            //                    while ( t2t1cal < t1+1 ){ // get the calibration packet2 that follows the packet1
4826                    //
4827                    t2++;
4828                    //
4829                    pret2 = t2 - 1; // EMILIANO
4830                    //
4831                    if ( t2 < nevents2 ){
4832                        tr2->GetEntry(t2);
4833                        codt2 = eh2->GetCounter();
4834                        t2t1cal = codt2->Get(pctp->CalibTrk1);
4835                        //
4836                        ph2 = eh2->GetPscuHeader();
4837                        obt2 = ph2->GetOrbitalTime();  
4838                        pkt2 = ph2->GetCounter();  
4839                        //
4840                        if ( IsDebug() ) printf(" >> trk calibration2 at obt %u pkt %u t2 is %u , t2t1cal is %u \n",obt2,pkt2,t2,t2t1cal);    
4841                        //    if ( caltrk2->unpackError != 0 || caltrk2->good0 == 0 ) valid = 0; // CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT2
4842                        //    
4843                    } else {
4844                        //
4845                        // running out of vector without finding the corresponding calibration, sig
4846                        //
4847                        if ( IsDebug() ) printf(" t2 >= nevents2 \n");
4848                        pret2 = t2;
4849                        obt2 = 0;
4850                        //    pkt2 = pkt1+2;
4851                        pkt2 = 0;
4852                        t2t1cal = t1+1;
4853                    };
4854                    //      if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) && (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){
4855    
4856                    // EMILIANO
4857                    //      if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) || (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){
4858                    //        //    if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){
4859                    //        if ( IsDebug() ) printf(" running out of vector without finding the corresponding calibration, sig \n");
4860                    //        //
4861                    //        // running out of vector without finding the corresponding calibration, sig
4862                    //        //
4863                    //        pret2 = t2;
4864                    //        obt2 = 0;
4865                    //        //      pkt2 = pkt1+2;
4866                    //        pkt2 = 0;
4867                    //        t2t1cal = t1+1;
4868                    //      };
4869    
4870    
4871                    //
4872                };
4873                //
4874                if ( IsDebug() ) printf(" Check if trk calibration2 is the right one \n");
4875                //
4876                // EMILIANO
4877                if ( ( PKT(pkt2) < PKT(pktfirst) || PKT(pkt2) > upperpkt) || (OBT(obt2) < OBT(obtfirst) || OBT(obt2) > upperobt) ){
4878                    //      if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){
4879                    if ( IsDebug() ) printf(" *WARNING*  The calibration found is outside the interval, sig \n");
4880                    //
4881                    // running out of vector without finding the corresponding calibration, sig
4882                    //
4883                    pret2 = t2;
4884                    obt2 = 0;
4885                    pkt2 = 0;
4886                };
4887                if ( PKT(pkt2) == PKT(pkt1)+1 ){
4888                    if ( IsDebug() ) cout << " ...OK"<<endl;
4889                    // =======================
4890                    // The calibration is good
4891                    // =======================
4892                    //
4893    //      if ( IsDebug() ) printf(" Found trk calibration2 at obt %u pkt %u t2 is %u \n",obt2,pkt2,t2);
4894    //      if ( IsDebug() ) printf(" Trk calibration2 at obt %u pkt %u t2 is %u is good \n",obt2,pkt2,t2);
4895    //        if ( IsDebug() ) printf("\n Trk calibration2 at time %u obt %u pkt %u \n",fromtime,obt2,pkt2);
4896                    if ( IsDebug() ) printf(" Trk calibration2 %u at time %u obt %u pkt %u \n",t2,fromtime,obt2,pkt2);
4897                    //
4898                    UInt_t valid2 = ValidateTrkCalib( caltrk2, eh2 );
4899                    if ( IsDebug() ) cout << " pkt2 validation --> "<<valid2<<endl;
4900    //      valid = valid & valid2;
4901                    valid = valid & valid2; //QUESTO VA CAMBIATO
4902                    //
4903                    // Handle good calib
4904                    //
4905                    MISSING_pkt1 = false;
4906                    MISSING_pkt2 = false;
4907    //              this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4908                    //
4909                    // Check for missing calibtrk1
4910                    //
4911                    if ( t2 != pret2+1 ){
4912                        //
4913                        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);
4914                        //
4915                        while ( t2 > pret2+1 ){
4916                            //
4917                            // handle missing calib1
4918                            //
4919                            pret2++;
4920                            //
4921                            obt1 = 0;
4922                            pkt1 = 0;
4923                            //
4924                            tr2->GetEntry(pret2);
4925                            ph2 = eh2->GetPscuHeader();
4926                            obt2 = ph2->GetOrbitalTime();  
4927                            pkt2 = ph2->GetCounter();  
4928                            //
4929                            fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
4930                            //
4931                            valid = 0;
4932                            MISSING_pkt1 = true;
4933                            MISSING_pkt2 = false;
4934    //                      this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4935                            //
4936                        };
4937                        //
4938                    };
4939                    //
4940                } else if ( this->PKT(pkt2) > this->PKT(pkt1)+1 ){
4941                    //
4942                    // Check for missing calibtrk2
4943                    //
4944                    if ( IsDebug() ) printf(" Missing the trk calibration2! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);
4945                    t2 = pret2;
4946                    //
4947                    // handle missing calib2
4948                    //
4949                    obt2 = 0;
4950                    pkt2 = 0;
4951                    valid = 0;
4952                    MISSING_pkt1 = false;
4953                    MISSING_pkt2 = true;
4954    //              this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4955                    //
4956                };
4957                //
4958    
4959                if( !(MISSING_pkt1&MISSING_pkt2) ){
4960                  this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
4961                  ncalib++;
4962                  if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
4963                }
4964    
4965    
4966          } else {          } else {
4967            //            //
4968            // 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);
4969            //              //      if ( PEDANTIC ) throw -79;
4970            if ( IsDebug() ) printf(" t2 >= nevents2 \n");              //
           pret2 = t2;  
           obt2 = 0;  
           //      pkt2 = pkt1+2;  
           pkt2 = 0;  
           t2t1cal = t1+1;  
4971          };          };
4972          //      if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) && (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){          //    
4973    
4974          // 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;  
 //      };  
4975    
4976    
4977    
4978        //
4979        // we have one more calib pkt2 !
4980        //
4981        t2++;
4982        while ( t2 < nevents2 ){
4983          //          //
4984        };          // 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  
4985          //          //
4986          this->HandleTRK_CALIB(true,true);          if ( IsDebug() ) printf(" t2 is %u nevents2 is %u \n",t2,nevents2);
4987            obt1 = 0;
4988            pkt1 = 0;
4989          //          //
4990          // Check for missing calibtrk1          tr2->GetEntry(t2);
4991            ph2 = eh2->GetPscuHeader();
4992            obt2 = ph2->GetOrbitalTime();  
4993            pkt2 = ph2->GetCounter();  
4994          //          //
4995          if ( t2 != pret2+1 ){          fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
4996            //          valid = 0;
4997            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 ){
4998            //          // EMILIANO
4999            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 ){
5000              //              //    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();    
5001              //              //
5002              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);
5003              //              //
5004              valid = 0;              MISSING_pkt1 = true;
5005              this->HandleTRK_CALIB(false,true);              MISSING_pkt2 = false;
5006                this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5007                ncalib++;
5008                if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
5009              //              //
           };  
           //  
5010          };          };
5011          //          //
5012        } 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;  
5013          //          //
5014          // handle missing calib2      };
5015    
5016    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
5017    // -----------------------------------------------------------------
5018    // in case of corruption, check if the calibration can be recovered
5019    // from another chewbacca file
5020    // -----------------------------------------------------------------
5021    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
5022    
5023    //    cout <<" TRY TO RECOVER ?? "<<try_to_recover<<endl;
5024        
5025        if(chewbacca&&try_to_recover){
5026    
5027    
5028            if ( IsDebug() ) cout << endl << ">>>> TRY TO RECOVER TRACKER CALIBRATIONS <<<<"<<endl;
5029    
5030            TSQLResult *result = 0;
5031            TSQLRow    *row    = 0;
5032          //          //
5033          obt2 = 0;          stringstream oss;
5034          pkt2 = 0;          oss.str("");
         valid = 0;  
         this->HandleTRK_CALIB(true,false);        
5035          //          //
5036        };  
5037        //          ////////////////////////////////////////////////////////////////////////
5038      } else {          // retrieve the name of the current file:
5039        //          ////////////////////////////////////////////////////////////////////////        
5040        if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u OUTSIDE the considered time interval \n",fromtime,obt1,pkt1);          oss.str("");
5041        //      if ( PEDANTIC ) throw -79;          oss << "SELECT NAME FROM GL_ROOT where ID=" << GetID_ROOT() <<";";
5042        //          if ( IsDebug() ) cout << oss.str().c_str() << endl;
5043      };  
5044      //              result = conn->Query(oss.str().c_str());
5045    };          if ( !result ) throw -4;;
5046    //          row = result->Next();
5047    // we have one more calib pkt2 !          TString thisfilename = (TString)row->GetField(0);
5048    //          if ( IsDebug() ) cout << "Current file ==> "<<thisfilename<<endl;      
5049    t2++;  
5050    while ( t2 < nevents2 ){          ////////////////////////////////////////////////////////////////////////        
5051      //          // read all the calibrations inserted
5052      // handle missing calib1          ////////////////////////////////////////////////////////////////////////        
5053      //          oss.str("");
5054      if ( IsDebug() ) printf(" t2 is %u nevents2 is %u \n",t2,nevents2);          oss << " SELECT ";
5055      obt1 = 0;          oss << " ID,FROM_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,TO_TIME";
5056      pkt1 = 0;          oss << " FROM GL_TRK_CALIB ";
5057      //          oss << " ORDER BY ID DESC LIMIT "<<ncalib<<"; ";        
5058      tr2->GetEntry(t2);          if ( IsDebug() ) cout << oss.str().c_str() << endl;
5059      ph2 = eh2->GetPscuHeader();  
5060      obt2 = ph2->GetOrbitalTime();            result = conn->Query(oss.str().c_str());
5061      pkt2 = ph2->GetCounter();            if ( !result ) throw -4;;
5062      //          if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5063      fromtime = this->GetAbsTime(ph2->GetOrbitalTime());          
5064      valid = 0;          // -----------------------------------
5065  //  if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->PKT(pkt1) <= upperpkt && this->OBT(obt1) >= this->OBT(obtfirst) && this->OBT(obt1) <= upperobt ){          // loop over calibrations ...
5066   // EMILIANO          // -----------------------------------
5067      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;
5068        //    if ( this->PKT(pkt2) > this->PKT(pktfirst) || this->OBT(obt2) > this->OBT(obtfirst) ){          do {
5069        //              row = result->Next();
5070        if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);              if(!row)break;
5071        //              
5072        this->HandleTRK_CALIB(false,true);              UInt_t id       = (UInt_t)atoll(row->GetField(0));
5073        //              UInt_t fromtime = (UInt_t)atoll(row->GetField(1));
5074      };              UInt_t obt1     = (UInt_t)atoll(row->GetField(2));
5075      //              UInt_t pkt1     = (UInt_t)atoll(row->GetField(3));
5076      t2++;              UInt_t obt2     = (UInt_t)atoll(row->GetField(4));
5077      //              UInt_t pkt2     = (UInt_t)atoll(row->GetField(5));
5078    };              UInt_t boot     = (UInt_t)atoll(row->GetField(6));
5079                UInt_t valid    = (UInt_t)atoll(row->GetField(7));
5080                bool MISSING_pkt1 = (row->GetFieldLength(8)==0);
5081                bool MISSING_pkt2 = (row->GetFieldLength(9)==0);
5082                UInt_t totime   = (UInt_t)atoll(row->GetField(10));
5083    
5084                // -------------------------------------
5085                // ...check if the entry is corrupted...
5086                // -------------------------------------
5087                cout <<"*** "<< MISSING_pkt1 << MISSING_pkt2 << valid <<endl;
5088                bool CORRUPTED = (MISSING_pkt1||MISSING_pkt2||!valid);
5089    
5090                if ( IsDebug() ) cout << "("<<nn<<")  ID = "<<id<<" from GL_TRK_CALIB  ==>  corrupted ? "<<CORRUPTED<<endl;
5091    
5092    //          if( !CORRUPTED  )continue; // nothing to do
5093    
5094                /////////////////////////////////////////////////////////  
5095                // if it is corrupted, ...look for ather chewbacca files
5096                // containing the same calibrations ...
5097                /////////////////////////////////////////////////////////
5098    
5099                bool this_MISSING_pkt1 = false;
5100                bool this_MISSING_pkt2 = false;
5101                int  this_t1=0;
5102                int  this_t2=0;;
5103                UInt_t this_valid = 0;
5104    
5105                TString path       = "";
5106                TString name       = "";
5107                TString raw        = "";
5108                UInt_t obt0        = 0;
5109                UInt_t timesync    = 0;
5110                UInt_t boot_number = 0;
5111                bool   FOUND       = false;
5112    
5113                if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
5114    
5115    //          for(int itable=0; itable<2; itable++){
5116                for(int itable=0; itable<1; itable++){
5117    
5118                    // ------------------------------------------------------
5119                    // loop over both ROOT_TABLE and ROOT_TABLE_BAD
5120                    // ------------------------------------------------------
5121    
5122                    TString table = "ROOT_TABLE";
5123                    if(itable==1)table = "ROOT_TABLE_BAD";
5124    
5125                    oss.str("");
5126                    oss << " SELECT ";
5127                    oss << " FOLDER_NAME,FILE_NAME,OBT_TIME_SYNC,LAST_TIME_SYNC_INFO,BOOT_NUMBER,INPUT_NAME ";
5128                    oss << " FROM "<<table;
5129                    oss << " WHERE 1 " << endl;
5130                    oss << " AND FILE_NAME != \""<< thisfilename<<"\"";
5131                    if( !MISSING_pkt1 ){
5132                        oss << " AND ";
5133                        oss << " PKT_NUMBER_INIT < "<<pkt1;
5134                        oss << " AND ";
5135                        oss << " PKT_NUMBER_FINAL > "<<pkt1;
5136                        oss << " AND ";
5137                        oss << " PKT_OBT_INIT < "<<obt1;
5138                        oss << " AND ";
5139                        oss << " PKT_OBT_FINAL > "<<obt1;
5140                    }else{
5141                        if(pkt2>1) pkt1 = pkt2-1;//serve dopo                  
5142                    }
5143                    if( !MISSING_pkt2 ){
5144                        oss << " AND ";
5145                        oss << " PKT_NUMBER_INIT < "<<pkt2;
5146                        oss << " AND ";
5147                        oss << " PKT_NUMBER_FINAL > "<<pkt2;
5148                        oss << " AND ";
5149                        oss << " PKT_OBT_INIT < "<<obt2;
5150                        oss << " AND ";
5151                        oss << " PKT_OBT_FINAL > "<<obt2;
5152                    }else{
5153                        if(pkt1>0) pkt2 = pkt1+1;//serve dopo
5154                    }
5155                    if( boot> 0 ){
5156                        oss << " AND ";
5157                        oss << " BOOT_NUMBER = "<<boot;
5158                    }else{
5159                    }
5160                    oss << " ORDER BY BAD_PKT_CALREAD ASC; ";
5161                
5162                    TSQLResult *result2 = 0;
5163                    TSQLRow    *row2    = 0;
5164    
5165                    if ( IsDebug() ) cout << oss.str().c_str() << endl;        
5166                    result2 = conn->Query(oss.str().c_str());
5167                    if ( !result2 ) throw -4;;
5168                    if ( IsDebug() ) cout <<"Rows: "<<result2->GetRowCount()<<endl;
5169    
5170                    // ------------------------------------------------------
5171                    // loop over files containing repetition (if any)
5172                    // ------------------------------------------------------
5173                    do {
5174                        row2 = result2->Next();
5175                        if(!row2)break;
5176                    
5177                        // ------------------------------------------------------
5178                        // ... a repetition is found ...
5179                        // ------------------------------------------------------
5180                        path       = (TString)row2->GetField(0);
5181                        name       = (TString)row2->GetField(1);
5182                        raw        = (TString)row2->GetField(5);
5183                        obt0        = (UInt_t)atoll(row2->GetField(2));
5184                        timesync    = (UInt_t)atoll(row2->GetField(3));
5185                        boot_number = (UInt_t)atoll(row2->GetField(4));
5186                    
5187                        if ( IsDebug() ) cout << "- - - - - - - - - - -" <<endl;
5188    //                  cout << path <<endl;
5189    //                  cout << "File    : " <<name <<endl;
5190    //                  cout << obt0 <<endl;
5191    //                  cout << timesync <<endl;
5192    //                  cout << "boot n. : "<<boot_number <<endl;
5193    //                  cout << raw <<endl;
5194    
5195                        // ------------------------------------------------------
5196                        // ... retrieve the calibration packets.
5197                        // ------------------------------------------------------
5198                        if ( IsDebug() ) printf(" file is %s/%s \n",((TString)gSystem->ExpandPathName(path.Data())).Data(),name.Data());
5199                        TFile *file = new TFile(((TString)gSystem->ExpandPathName(path.Data()))+"/"+name); // EM, path could be symbolic and we must expand it
5200                        if(!file)throw -100;
5201                        if(file->IsZombie())throw -100;
5202                        //
5203                        tr1 = (TTree*)file->Get("CalibTrk1");
5204                        if ( !tr1 || tr1->IsZombie() ) throw -22;
5205                        tr2 = (TTree*)file->Get("CalibTrk2");
5206                        if ( !tr2 || tr2->IsZombie() ) throw -23;
5207                        //
5208                        tr1->SetBranchAddress("CalibTrk1", &caltrk1);
5209                        tr1->SetBranchAddress("Header", &eh1);
5210                        nevents1 = tr1->GetEntries();
5211                        tr2->SetBranchAddress("CalibTrk2", &caltrk2);
5212                        tr2->SetBranchAddress("Header", &eh2);
5213                        nevents2 = tr2->GetEntries();
5214                        for(this_t1=0; this_t1<nevents1; this_t1++){
5215                            tr1->GetEntry(this_t1);
5216                            if(
5217                                (UInt_t)eh1->GetPscuHeader()->GetCounter() == pkt1 &&
5218                                true) break;
5219                            this_MISSING_pkt1 = true;
5220                        }
5221                        for(this_t2=0; this_t2<nevents2; this_t2++){
5222                            tr2->GetEntry(this_t2);
5223                            if(
5224                                (UInt_t)eh2->GetPscuHeader()->GetCounter() == pkt2 &&
5225                                true) break;
5226                            this_MISSING_pkt2 = true;
5227                        }
5228                        this_valid =
5229                            ValidateTrkCalib( caltrk1, eh1, file )
5230                            *
5231                            ValidateTrkCalib( caltrk2, eh2, file );
5232                                
5233                        // ---------------------------------------------------------------------
5234                        // accept the calibration if it is better than the previous:
5235                        //
5236                        // - if the new calibration is perfect (both valid packets)
5237                        // - if the new calibration has both the packets and the previous does not
5238                        // ---------------------------------------------------------------------
5239                        if(
5240                            ( !this_MISSING_pkt1&&!this_MISSING_pkt2&&this_valid )||
5241                            ( (MISSING_pkt1||MISSING_pkt2) && (!this_MISSING_pkt1&&!this_MISSING_pkt2) )||
5242                            false)FOUND=true;      
5243                
5244                        if(file)file->Close();
5245    
5246                        if(FOUND)break;
5247    
5248                    }while(1);//endl loop over root table entries
5249    
5250                    if(FOUND)break;
5251    
5252                }//end loop over tables
5253    
5254                if(FOUND){
5255    
5256                if ( IsDebug() ) cout << " >>> REPETITION FOUND :-) <<<" <<endl;
5257    
5258                    ////////////////////////////////////////////
5259                    // insert a new entry in GL_TRK_CALIB and
5260                    // modify the time-tag of the previous one
5261                    ////////////////////////////////////////////
5262    
5263                    // ---------------------------------------------------------------------
5264                    // step 1: insert a new raw file in GL_RAW
5265                    // ---------------------------------------------------------------------
5266                    //
5267                    // check if the raw file already exist
5268                    //
5269                    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
5270    //              oss.str("");
5271    //              oss << "SELECT ID FROM GL_RAW where NAME=\"" << gSystem->BaseName(raw.Data()) <<"\";";
5272    //              if ( IsDebug() ) cout << oss.str().c_str() << endl;
5273                    
5274    //              result = conn->Query(oss.str().c_str());
5275    //              if ( !result ) throw -4;;
5276    //              if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5277    //              if( result->GetRowCount() == 0){
5278    //                  if ( IsDebug() ) cout << " << Insert new RAW file >> "<<endl;
5279    //                  // - - - - - - - - - - -
5280    //                  // insert new raw file
5281    //                  // - - - - - - - - - - -
5282    //                  GL_RAW glraw = GL_RAW();    
5283    //                  glraw.PATH        = gSystem->DirName(raw.Data());
5284    //                  glraw.NAME        = gSystem->BaseName(raw.Data());
5285    //                  glraw.BOOT_NUMBER = boot_number;
5286    //                  //
5287    //                  insertPamelaRawFile( &glraw );
5288    //                  //              
5289    //                  id_raw = glraw.ID;              
5290    //              }else{
5291    //                  row = result->Next();
5292    //                  id_raw = (UInt_t)atoll(row->GetField(0));
5293    //              }
5294    //              if ( IsDebug() ) cout << "ID_RAW = "<<id_raw<<endl;
5295    
5296                    // ---------------------------------------------------------------------
5297                    // step 1(bis): retrieve the timesync id associated to the file
5298                    // (NB, uso lo stesso associato al file iniziale)
5299                    // ---------------------------------------------------------------------
5300                    UInt_t idtimesync = 0;
5301                    oss.str("");
5302                    oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" limit 1;";
5303                    if ( debug ) printf(" %s \n",oss.str().c_str());
5304                    result = conn->Query(oss.str().c_str());
5305                    if ( !result ) throw -3;
5306                    row = result->Next();
5307                    if ( !row ) throw -3;
5308                    idtimesync = (UInt_t)atoll(row->GetField(0));
5309                    if ( IsDebug() ) cout << "ID_TIMESYNC = "<<idtimesync<<endl;
5310                    
5311                    // ---------------------------------------------------------------------
5312                    // step 2: insert a new root file in GL_ROOT
5313                    // ---------------------------------------------------------------------
5314                    //
5315                    // check if the root file already exist
5316                    //
5317                    UInt_t id_root = 0;
5318                    oss.str("");
5319                    oss << "SELECT ID FROM GL_ROOT where NAME=\"" << gSystem->BaseName(name.Data()) <<"\";";
5320                    if ( IsDebug() ) cout << oss.str().c_str() << endl;
5321                    
5322                    result = conn->Query(oss.str().c_str());
5323                    if ( !result ) throw -4;;
5324                    if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5325                    if( result->GetRowCount() == 0){
5326                        if ( IsDebug() ) cout << " << Insert new ROOT file >> "<<endl;
5327                        // - - - - - - - - - - -
5328                        // insert new root file
5329                        // - - - - - - - - - - -
5330                        GL_ROOT glroot = GL_ROOT();            
5331                        glroot.ID_RAW      = id_raw;
5332                        glroot.ID_TIMESYNC = idtimesync;
5333                        //
5334                        // 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,
5335                        //             NOT STATIC NOT KEEPENV = $PAM_L0 must be used in the DB
5336                        //
5337                        if ( STATIC ){
5338                          glroot.PATH        = (TString)gSystem->ExpandPathName(path);
5339                        } else {
5340                          if ( KEEPENV ){
5341                            glroot.PATH      = path;
5342                          } else {
5343                            glroot.PATH      = "$PAM_L0";
5344                          };
5345                        };
5346                        //              glroot.PATH        = path;
5347                        glroot.NAME        = name;
5348                        //
5349                        insertPamelaRootFile( &glroot );
5350                        //              
5351                        id_root = glroot.ID;                    
5352                    }else{
5353                        row = result->Next();
5354                        if(row)id_root = (UInt_t)atoll(row->GetField(0));
5355                    }
5356                    if ( IsDebug() ) cout << "ID_ROOT = "<<id_root<<endl;
5357    
5358                    // ---------------------------------------------------------------------
5359                    // step 3: modify time-tag of corrupted GL_TRK_CALIB entry
5360                    // ---------------------------------------------------------------------
5361                    if ( IsDebug() ) cout << " << Modify time-tag of calibration ID="<<id<<" >> "<<endl;
5362                    oss.str("");
5363                    oss << " UPDATE GL_TRK_CALIB SET "  
5364                        << " TO_TIME=0 , FROM_TIME=0  WHERE "
5365                        << " ID = "<< id  << ";";
5366                    if ( IsDebug() ) cout << oss.str().c_str() << endl;
5367                    result = conn->Query(oss.str().c_str());
5368                    if ( !result ) throw -4;;
5369    
5370                    // ---------------------------------------------------------------------
5371                    // step 4: insert the new calibration:
5372                    // ---------------------------------------------------------------------
5373                    if ( IsDebug() ) cout << " << Insert new TRK calibration >> "<<endl;
5374                    //
5375                    GL_TRK_CALIB glcal = GL_TRK_CALIB();        
5376                    //
5377                    glcal.ID_ROOT_L0        = id_root;
5378                    glcal.EV_ROOT_CALIBTRK1 = this_t1;
5379                    glcal.EV_ROOT_CALIBTRK2 = this_t2;
5380                    glcal.FROM_TIME         = fromtime;
5381                    glcal.TO_TIME           = totime;
5382                    glcal.OBT1              = obt1;
5383                    glcal.OBT2              = obt2;
5384                    glcal.PKT1              = pkt1;
5385                    glcal.PKT2              = pkt1;
5386                    glcal.BOOT_NUMBER       = GetBOOTnumber();
5387                    glcal.VALIDATION        = this_valid;
5388                    //
5389                    HandleTRK_CALIB(&glcal);
5390                    if ( IsDebug() ) cout << "ID = "<<glcal.ID<<endl;
5391                    //
5392                    
5393                }
5394                if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
5395    
5396            }while(1);//end loop over calibrations
5397            
5398            
5399            if( result )delete result;
5400            if( row    )delete row;
5401            
5402            
5403    
5404            
5405    
5406    
5407        }
5408    
5409    
5410    //      // ------------------------------
5411    //      // try to recover the calibration
5412    //      // ------------------------------
5413    //      cout << "TRY TO RECOVER TRACKER CALIBRATION"<<endl;
5414    //      //
5415    //      ULong64_t time  = 0; //absolute time
5416    //      string    path[100]; //mettere un limite massimo
5417    //      int       nrows = 0;
5418    //      UInt_t    pkt   = 0;
5419    //      UInt_t    obt   = 0;
5420    //      char     *type  = "";
5421    //      EventHeader *eh   = new EventHeader();
5422    //      CalibTrk1Event *c = new CalibTrk1Event();
5423            
5424    //       //
5425    //       if(which_is_not_valid==1 || which_is_not_valid==3){
5426    //        //
5427    //        cout << "PKT1 --> missing or corrupted "<<endl;
5428    //        type = "CalibTrk1";
5429    //        pkt  = pkt1;
5430    //        obt  = obt1;
5431    //        time = this->GetAbsTime(obt1);
5432    //        if( pkt1 == 0 ){//missing
5433    //            time = this->GetAbsTime(obt2);
5434    //            pkt  = pkt2-1;          
5435    //        }
5436    //        //
5437    //       }else if (which_is_not_valid==2 || which_is_not_valid==3){
5438    //        //
5439    //        cout << "PKT2--> missing or corrupted "<<endl;
5440    //        type = "CalibTrk2 ";
5441    //        pkt  = pkt2;
5442    //        obt  = obt2;
5443    //        time = this->GetAbsTime(obt2);
5444    //        if( pkt2 == 0 ){//missing
5445    //            time = this->GetAbsTime(obt1);
5446    //            pkt  = pkt1+1;          
5447    //        }
5448    //        //
5449    //       }else{
5450    //        cout << "this should not happen!!! "<<endl;
5451    //        trow -666;
5452    //       }
5453          
5454    //       nrows = Query_ROOT_TABLE(time,conn,path);// get the list of file which might contain the packet
5455          
5456    
5457    //       for(int r=0; r<nrows; r++){ //loop over rows
5458    //        if(path)cout << r << " >>>> "<<(path+r)->c_str() << endl;
5459    //        /// verifica che il file non sia quello gia` aperto
5460    //       }
5461    
5462    //       ////////////////////////////////////////////////////////////////////////
5463    
5464    //       TSQLResult *result = 0;
5465    //       TSQLRow    *row    = 0;
5466    //       //
5467    //       stringstream oss;
5468    //       oss.str("");
5469    //       // ----------------------------------------
5470    //       // read the id of last calibration inserted
5471    //       // ----------------------------------------
5472    //       oss.str("");
5473    //       oss << " SELECT ";
5474    //       oss << " (ID,ID_ROOT_L0,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,FROM_TIME,TO_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION) ";
5475    //       oss << " ORDER BY ID DESC LIMIT 1; ";
5476          
5477    //       result = conn->Query(oss.str().c_str());
5478    //       row = result->Next();
5479    //       if( !row )throw -666;
5480    
5481    //       if( result )delete result;
5482    //       if( row    )delete row;
5483    
5484    //       UInt_t id = (UInt_t)atoll(row->GetField(0));
5485    
5486    //       // -------------------------------------
5487    //       // ...and modify it with new parameters
5488    //       // -------------------------------------
5489          
5490    
5491    //   }
5492    //    //
5493    return(0);    return(0);
5494  };  };
# Line 5061  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 5791  Int_t PamelaDBOperations::CleanGL_RUN_FR
5791                    << " RM_ACQ_SETTING_MODE=" << glrun->GetRM_ACQ_SETTING_MODE()<< " , "                      << " RM_ACQ_SETTING_MODE=" << glrun->GetRM_ACQ_SETTING_MODE()<< " , "  
5792                    << " TRK_CALIB_USED=" << glrun->GetTRK_CALIB_USED()<< " , "                      << " TRK_CALIB_USED=" << glrun->GetTRK_CALIB_USED()<< " , "  
5793                    << " CAL_DSP_MASK=" << glrun->GetCAL_DSP_MASK()<< " , "                      << " CAL_DSP_MASK=" << glrun->GetCAL_DSP_MASK()<< " , "  
5794                    << " LAST_TIMESYNC=" << glrun->GetLAST_TIMESYNC()<< " , "                      << " LAST_TIMESYNC=" << glrun->GetLAST_TIMESYNC()<< " , ";
5795                    << " OBT_TIMESYNC=" << glrun->GetOBT_TIMESYNC()                //
5796                    << " WHERE ID=" << myid[u] << ";";                if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
5797                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12() << " , ";
5798                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
5799                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC() << " , ";
5800                  //              
5801                  oss << " OBT_TIMESYNC=" << glrun->GetOBT_TIMESYNC();
5802                  oss << " WHERE ID=" << myid[u] << ";";
5803                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
5804              };              };
5805              //              //
# Line 5074  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 5810  Int_t PamelaDBOperations::CleanGL_RUN_FR
5810              for (UInt_t u=1; u <= nid ; u++){              for (UInt_t u=1; u <= nid ; u++){
5811                oss.str("");                oss.str("");
5812                oss << "UPDATE GL_RUN_FRAGMENTS SET "                oss << "UPDATE GL_RUN_FRAGMENTS SET "
5813                    << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , "                    << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , ";
5814                    << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "                //
5815                  if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
5816                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , ";
5817                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
5818                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , ";
5819                  //              
5820                  oss << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "
5821                    << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT()<< ";";                    << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT()<< ";";
5822                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
5823              };                  };    
# Line 5098  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 5840  Int_t PamelaDBOperations::CleanGL_RUN_FR
5840                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
5841                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "
5842                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< " , "                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< " , "
5843                    << " PKT_COUNTER=" << glrun->GetPKT_COUNTER()<< " , "                    << " PKT_COUNTER=" << glrun->GetPKT_COUNTER()<< " , ";
5844                    << " PKT_READY_COUNTER=" << glrun->GetPKT_READY_COUNTER()                //
5845                  if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
5846                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
5847                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) {
5848                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
5849                  //              
5850                  oss << " PKT_READY_COUNTER=" << glrun->GetPKT_READY_COUNTER()
5851                    << " WHERE ID=" << myid[u] << ";";                    << " WHERE ID=" << myid[u] << ";";
5852                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
5853              };              };
# Line 5112  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 5860  Int_t PamelaDBOperations::CleanGL_RUN_FR
5860                oss.str("");                oss.str("");
5861                oss << "UPDATE GL_RUN_FRAGMENTS SET "                oss << "UPDATE GL_RUN_FRAGMENTS SET "
5862                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
5863                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , ";
5864                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< ";";                //
5865                  if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
5866                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
5867                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ){
5868                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
5869                  //              
5870                  oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< ";";
5871                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
5872              };                  };    
5873            };            };
# Line 5272  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6026  Int_t PamelaDBOperations::CleanGL_RUN_FR
6026          glrun->SetID_RUN_FRAG(glrun->GetID());          glrun->SetID_RUN_FRAG(glrun->GetID());
6027          glrun->Fill_GL_RUN(conn);            glrun->Fill_GL_RUN(conn);  
6028          //          //
6029  //      oss.str("");          //      oss.str("");
6030  //      oss << " SELECT ID FROM GL_RUN WHERE "          //      oss << " SELECT ID FROM GL_RUN WHERE "
6031  //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "          //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
6032  //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "          //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
6033  //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "          //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
6034  //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "          //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
6035  //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";          //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
6036  //      //          //      //
6037  //      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());
6038  //      result2 = conn->Query(oss.str().c_str());          //      result2 = conn->Query(oss.str().c_str());
6039  //      //          //      //
6040  //      if ( !result2 ) throw -4;          //      if ( !result2 ) throw -4;
6041  //      //          //      //
6042  //      row2 = result2->Next();          //      row2 = result2->Next();
6043  //      //          //      //
6044  //      if ( !row2 ) throw -25;          //      if ( !row2 ) throw -25;
6045  //      //          //      //
6046  //      oss.str("");          //      oss.str("");
6047  //      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);
6048  //      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());
6049  //      result2 = conn->Query(oss.str().c_str());          //      result2 = conn->Query(oss.str().c_str());
6050  //      //          //      //
6051  //      if ( !result2 ) throw -4;          //      if ( !result2 ) throw -4;
6052          //          //
6053          moved++;          moved++;
6054          //          //
# Line 5306  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6060  Int_t PamelaDBOperations::CleanGL_RUN_FR
6060        //        //
6061        //        //
6062        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
6063  //      oss.str("");        //      oss.str("");
6064  //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);        //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);
6065  //       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());
6066  //       result2 = conn->Query(oss.str().c_str());        //       result2 = conn->Query(oss.str().c_str());
6067  //      //        //      //
6068  //      if ( !result2 ) throw -4;        //      if ( !result2 ) throw -4;
6069  //      //        //      //
6070        row = result->Next();        row = result->Next();
6071      };      };
6072    };    };
# Line 5366  Int_t PamelaDBOperations::ValidateRuns(T Line 6120  Int_t PamelaDBOperations::ValidateRuns(T
6120      // 2) get the OBT of the last validated run      // 2) get the OBT of the last validated run
6121      // --------------------------------------------------------------      // --------------------------------------------------------------
6122      oss.str("");      oss.str("");
6123      oss << " SELECT * FROM GL_RUN  WHERE VALIDATION=1 AND RUNHEADER_TIME<="<< t_start      //    oss << " SELECT * FROM GL_RUN  WHERE VALIDATION=1 AND RUNHEADER_TIME<="<< t_start
6124        oss << " SELECT * FROM GL_RUN  WHERE VALIDATION>0 AND RUNHEADER_TIME<="<< t_start
6125          <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";          <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
6126      if ( IsDebug() ) printf(" Get stop validation-time: query is \n %s \n",oss.str().c_str());      if ( IsDebug() ) printf(" Get stop validation-time: query is \n %s \n",oss.str().c_str());
6127      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
# Line 5457  Int_t PamelaDBOperations::ValidateRuns(T Line 6212  Int_t PamelaDBOperations::ValidateRuns(T
6212    GL_RUN* this_run = new GL_RUN();    GL_RUN* this_run = new GL_RUN();
6213    GL_RUN* next_run = new GL_RUN();    GL_RUN* next_run = new GL_RUN();
6214    Int_t   nseq_max = 1000;    Int_t   nseq_max = 1000;
6215  //  UInt_t* sequence = new UInt_t[100];    //  UInt_t* sequence = new UInt_t[100];
6216    vector<UInt_t> sequence(nseq_max);    vector<UInt_t> sequence(nseq_max);
6217    Int_t   nseq = 0;    Int_t   nseq = 0;
6218    Bool_t CHECK = false;    Bool_t CHECK = false;
# Line 5472  Int_t PamelaDBOperations::ValidateRuns(T Line 6227  Int_t PamelaDBOperations::ValidateRuns(T
6227    // ---------------------------------------------------------------------------------    // ---------------------------------------------------------------------------------
6228    while(1){    while(1){
6229                        
6230            row = result->Next();      row = result->Next();
6231            if( row == NULL ) break;      if( row == NULL ) break;
6232                        
6233            //------------      //------------
6234            //get run info      //get run info
6235            //------------      //------------
6236            this_run->Set_GL_RUN(row);      this_run->Set_GL_RUN(row);
6237                                        
6238            Bool_t this_BAD = false;      Bool_t this_BAD = false;
6239            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;
6240            else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;      else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;
6241            else{      else{
6242  //                printf("Missing or corrupted header!! \n");        //                  printf("Missing or corrupted header!! \n");
6243                    this_ONLINE = false;        this_ONLINE = false;
6244                    this_BAD = true;        this_BAD = true;
6245            };      };
6246    
6247            //-----------------------------------      //-----------------------------------
6248            //compare with previous(next in time)      //compare with previous(next in time)
6249            //-----------------------------------      //-----------------------------------
6250            CHECK = false;      CHECK = false;
6251            UInt_t interval=0;      UInt_t interval=0;
6252                        
6253            if( nrow != 0){      if( nrow != 0){
6254                    
6255                                        
6256                    t1 = this_run->GetRUNTRAILER_TIME();        t1 = this_run->GetRUNTRAILER_TIME();
6257                    t2 = next_run->GetRUNHEADER_TIME();        t2 = next_run->GetRUNHEADER_TIME();
6258                    interval = (t2-t1);        interval = (t2-t1);
6259                                        
6260                    if(this_ONLINE && next_ONLINE){                               // this: ON-LINE + next: ON-LINE        if(this_ONLINE && next_ONLINE){                           // this: ON-LINE + next: ON-LINE
6261                                                        
6262                            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
6263                                                        
6264                            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
6265                                                        
6266                            if( !CHECK && this_run->VALIDATION ){          if( !CHECK && this_run->VALIDATION ){
6267                                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);            //      for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
6268                                    nseq=0;            for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],this_run->VALIDATION);
6269                            }            nseq=0;
6270            }
6271                                        
6272                    }else if( !this_ONLINE && next_ONLINE) {              // this: DEFAULT + next:ON-LINE        }else if( !this_ONLINE && next_ONLINE) {          // this: DEFAULT + next:ON-LINE
6273                                                        
6274                            CHECK = true;          CHECK = true;
6275    
6276                    }else if( !next_ONLINE ){                                             // this:ANY + next:DEFAULT        }else if( !next_ONLINE ){                                         // this:ANY + next:DEFAULT
6277                                                        
6278                            assignVALIDATION(next_run->ID,true);          assignVALIDATION(next_run->ID,true);
6279                            nseq=0;          nseq=0;
6280                    }        }
6281            }      }
6282    
6283            //----------------------------      //----------------------------
6284            //check run sequence for calib      //check run sequence for calib
6285            //----------------------------      //----------------------------
6286            if( CHECK ){      if( CHECK ){
6287                    // check if calibration exists        // check if calibration exists
6288                    if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);        if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);
6289                    Bool_t MISSING = MissingTRK_CALIB(t1,t2);        //      Bool_t MISSING = MissingTRK_CALIB(t1,t2);
6290                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],!MISSING);        UInt_t MISSING = MissingTRK_CALIB(t1,t2);
6291                    nseq=0;        UInt_t val = 0;
6292            };        if ( MISSING == 1 ) val = 0;
6293            //--------------        if ( MISSING == 0 ) val = 1;
6294            //store run info        if ( MISSING == 2 ) val = 2;
6295            //--------------        for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],val);
6296            *next_run   = *this_run;        nseq=0;
6297            next_ONLINE = this_ONLINE;      };
6298            if( !this_BAD ){      //--------------
6299                    if(nseq < nseq_max){      //store run info
6300                            sequence[nseq] = this_run->ID;      //--------------
6301                            nseq++;      *next_run   = *this_run;
6302                    }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);      next_ONLINE = this_ONLINE;
6303            };      if( !this_BAD ){
6304          if(nseq < nseq_max){
6305            sequence[nseq] = this_run->ID;
6306            nseq++;
6307          }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);
6308        };
6309                        
6310            if ( IsDebug() ) printf("%i Run %u \n",nrow,this_run->ID);      if ( IsDebug() ) printf("%i Run %u \n",nrow,this_run->ID);
6311            nrow++;      nrow++;
6312                        
6313    };    };
6314    delete this_run;    delete this_run;
# Line 5561  Int_t PamelaDBOperations::ValidateRuns(T Line 6322  Int_t PamelaDBOperations::ValidateRuns(T
6322   * @param t2 To absolute time   * @param t2 To absolute time
6323   * @return true if there might be a missing calibration   * @return true if there might be a missing calibration
6324   */   */
6325  Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){  //Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
6326    UInt_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
6327                    
6328          GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();    GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();
6329                    
6330          // get the closest VALIDATED calibration before the run start (t2)    // get the closest calibration before the run start (t2)
6331          if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true);      //>>> missing    //  if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true);        //>>> missing
6332      if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(1);       //>>> missing
6333                    
6334          if ( trkcalib->TO_TIME  < t2 ) return(true);                                    //>>> missing    //  if ( trkcalib->TO_TIME  < t2 ) return(true);                                      //>>> missing
6335      if ( trkcalib->TO_TIME  < t2 ) return(1);                                     //>>> missing
6336                    
6337          //==============================================================    //==============================================================
6338          // Check is done first on the basis of time between calibration,    // Check is done first on the basis of time between calibration,
6339          // which should be equal to the time between ascending-nodes.    // which should be equal to the time between ascending-nodes.
6340          //==============================================================    //==============================================================
6341          if ( t2 - trkcalib->FROM_TIME > 5700) {    if ( t2 - trkcalib->FROM_TIME > 5700) {
6342                  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);
6343          //==============================================================      //==============================================================
6344          // there might be a missing calibration, due to:      // there might be a missing calibration, due to:
6345          // - MM full      // - MM full
6346          // - corrupted packets      // - corrupted packets
6347          // - loss of data      // - loss of data
6348          // 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
6349          //==============================================================      //==============================================================
6350                  Bool_t DOWNLOAD = false;      Bool_t DOWNLOAD = false;
6351                  // check if the calib was skipped becouse of download .... DA FARE!!      // check if the calib was skipped becouse of download .... DA FARE!!
6352                  if(DOWNLOAD)return(false);      //    if(DOWNLOAD)return(false);
6353        if(DOWNLOAD)return(0);
6354                                    
6355                  return(true);                                   //>>> missing      //    return(true);                                         //>>> missing
6356        return(1);                                  //>>> missing
6357                                    
6358          };    };
6359                    
6360          //==============================================================    //==============================================================
6361          // 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,
6362          // it is enough to say that there are no missing calibrations    // it is enough to say that there are no missing calibrations
6363          //==============================================================    //==============================================================
6364          // the long time interval bewteen runs might be due to download    // the long time interval bewteen runs might be due to download
6365          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);
6366          return(false);    if ( trkcalib->VALIDATION ) return(0);
6367      if ( IsDebug() )printf("Calibration is not validated... :-/ ==> OK but with VALIDATION=2! \n");
6368      return(2);
6369                    
6370  };  };
6371  /**  /**
# Line 5606  Bool_t PamelaDBOperations::MissingTRK_CA Line 6374  Bool_t PamelaDBOperations::MissingTRK_CA
6374   * @param validation true/false   * @param validation true/false
6375   */   */
6376  Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){  Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){
6377          TSQLResult *result = 0;    return(this->assignVALIDATION(idrun,(UInt_t)validation));
6378          stringstream oss;  }
6379          oss.str("");  
6380          oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";  Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, UInt_t validation){
6381          //    TSQLResult *result = 0;
6382  //      if ( IsDebug() )    stringstream oss;
6383  //      printf(" Set VALIDATION = %i for run %i \n",validation,idrun);    oss.str("");
6384          if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());    oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";
6385          result = conn->Query(oss.str().c_str());    //
6386          if ( !result ) throw -4;    //    if ( IsDebug() )
6387          return(0);    //    printf(" Set VALIDATION = %i for run %i \n",validation,idrun);
6388      if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());
6389      result = conn->Query(oss.str().c_str());
6390      if ( !result ) throw -4;
6391      return(0);
6392  }  }
6393    
6394    
# Line 5802  Int_t PamelaDBOperations::removeFile(TSt Line 6574  Int_t PamelaDBOperations::removeFile(TSt
6574    stringstream myquery;    stringstream myquery;
6575    //      //  
6576    myquery.str("");    myquery.str("");
6577    myquery << " SELECT ID, ID_RAW FROM GL_ROOT where NAME='"<<remfile.Data() <<"';";    myquery << " SELECT ID,ID_RAW,ID_TIMESYNC FROM GL_ROOT where NAME='"<<remfile.Data() <<"';";
6578    //    //
6579    pResult = conn->Query(myquery.str().c_str());    pResult = conn->Query(myquery.str().c_str());
6580    //    //
# Line 5818  Int_t PamelaDBOperations::removeFile(TSt Line 6590  Int_t PamelaDBOperations::removeFile(TSt
6590    //    //
6591    this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));    this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));
6592    this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));    this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));
6593      UInt_t idtsy=(UInt_t)atoll(Row->GetField(2));
6594    //    //
6595    this->ValidationOFF();    this->ValidationOFF();
6596    //    //
# Line 5825  Int_t PamelaDBOperations::removeFile(TSt Line 6598  Int_t PamelaDBOperations::removeFile(TSt
6598    //    //
6599    this->RemoveRUNS();    this->RemoveRUNS();
6600    //    //
6601    this->RemoveFILES();    this->RemoveFILES(idtsy);
6602    //    //
6603    this->SetID_ROOT(0);    this->SetID_ROOT(0);
6604    this->SetID_RAW(0);    this->SetID_RAW(0);
# Line 6045  void PamelaDBOperations::RemoveRUNS(){ Line 6818  void PamelaDBOperations::RemoveRUNS(){
6818   * Rearrange calibration tables   * Rearrange calibration tables
6819   *   *
6820   **/   **/
6821  void PamelaDBOperations::RemoveFILES(){  void PamelaDBOperations::RemoveFILES(UInt_t idtsy){
6822    stringstream myquery;    stringstream myquery;
6823    //    //
6824    myquery.str("");    myquery.str("");
# Line 6055  void PamelaDBOperations::RemoveFILES(){ Line 6828  void PamelaDBOperations::RemoveFILES(){
6828    //    //
6829    conn->Query(myquery.str().c_str());    conn->Query(myquery.str().c_str());
6830    //    //
6831      myquery.str("");
6832      myquery << " DELETE FROM GL_ROOT WHERE ID=" <<this->GetID_ROOT() <<";";
6833      //
6834      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
6835      //
6836      conn->Query(myquery.str().c_str());  //
6837      //
6838      if ( !chewbacca ){
6839        myquery.str("");
6840        myquery << " DELETE FROM GL_TIMESYNC WHERE ID=" << idtsy <<";";
6841        //
6842        if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
6843        //
6844        conn->Query(myquery.str().c_str());
6845      };
6846      //
6847  };  };
6848    
6849  /**  /**
# Line 6259  void PamelaDBOperations::RemoveCALIBS(){ Line 7048  void PamelaDBOperations::RemoveCALIBS(){
7048   * Rearrange calibration tables   * Rearrange calibration tables
7049   *   *
7050   **/   **/
7051  UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh ){  UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh , TFile *file){
7052    
7053        if(!caltrk) return 0;
7054    
7055        if ( IsDebug() ) cout << "ValidateTrkCalib:"<<endl;
7056    
7057        UInt_t validate = 1;
7058      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};
7059      UInt_t timeaftercalib=120000; //2000;      UInt_t timeaftercalib=120000; //2000;
7060  //  ----------      TString classname = caltrk->GetName();
7061  //  Check CRCs  
7062  //  ----------  //  ----------------------------------
7063    //  Check CRCs and failed calibrations
7064    //  ----------------------------------
7065      for(Int_t ipkt=0; ipkt<6; ipkt++){      for(Int_t ipkt=0; ipkt<6; ipkt++){
7066          if( caltrk->crc_hcal[ipkt] )return 0; // :-(          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
7067          for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] )return 0; // :-(              if( caltrk->crc_hcal[ipkt] ){
7068    //              if(IsDebug())cout<<"(CRC Header)";
7069                    validate = 0;
7070                    if(IsDebug())cout <<endl<<" *** CRC *** (header DSPn "<<caltrk->DSPnumber[ipkt]<<")";
7071            
7072                }
7073                for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] ){
7074    //              if(IsDebug())cout<<"(CRC Pkt-"<<ilad<<")";
7075                    if(IsDebug())cout <<endl<<" *** CRC *** (data DSPn "<<caltrk->DSPnumber[ipkt]<<" ladder "<<ilad<<")";
7076                    validate = 0;
7077                }
7078                if( !(caltrk->ncalib_event[ipkt]==0 && caltrk->cal_flag[ipkt]==0) ){
7079                    if(IsDebug())cout <<endl<<" *** FAILURE ***     (data DSPn "<<caltrk->DSPnumber[ipkt]<<")";
7080                    validate = 0;
7081                }
7082            }else{
7083    //          validate=0;
7084                if(IsDebug())cout <<endl<<" *** DSPn *** ("<< caltrk->DSPnumber[ipkt] <<" @pkt "<<ipkt<<")";
7085            }
7086      }      }
7087    
7088  //  -----------------------  //  -----------------------
7089  //  Check missing packets:  //  Check missing packets:
7090  //  -----------------------  //  -----------------------
# Line 6295  UInt_t PamelaDBOperations::ValidateTrkCa Line 7110  UInt_t PamelaDBOperations::ValidateTrkCa
7110  //  Check if it is first or second calibration packet  //  Check if it is first or second calibration packet
7111  //  -------------------------------------------------  //  -------------------------------------------------
7112      UInt_t build=0;      UInt_t build=0;
     TString classname = caltrk->GetName();  
7113      UInt_t base=0;      UInt_t base=0;
7114      UInt_t mask=0;      UInt_t mask=0;
7115      if(classname.Contains("CalibTrk1Event")){      if(classname.Contains("CalibTrk1Event")){
# Line 6306  UInt_t PamelaDBOperations::ValidateTrkCa Line 7120  UInt_t PamelaDBOperations::ValidateTrkCa
7120          base=18;          base=18;
7121          mask=0xFC0000;          mask=0xFC0000;
7122      }      }
7123  //  -------------------------------------------------  //  ----------------------------------------------------
7124  //  Count number of packets and set build variable  //  Count number of valid packets and set build variable
7125  //  -------------------------------------------------  //  ----------------------------------------------------
7126        if(IsDebug())cout <<endl<< " DSP: ";
7127      Int_t  npkts=0;      Int_t  npkts=0;
7128      for(Int_t ipkt=0; ipkt<6; ipkt++){      for(Int_t ipkt=0; ipkt<6; ipkt++){
7129          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
7130                if(IsDebug())cout <<" "<<caltrk->DSPnumber[ipkt];
7131              npkts++;              npkts++;
7132              build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );              build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );
7133          }  //          cout << caltrk->DSPnumber[ipkt]
7134            };
7135      }      }
7136  //    if( npkts==6 )return 1; // :-)      if(IsDebug())cout << " ==> "<< hex << build << dec;
7137    //  ----------------------------------------------------
7138  //    cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime()<<endl;  //  If the number of valid packets is 6, ok exit...
7139    //  ----------------------------------------------------
7140  //  -----------------------------------------------      if( npkts==6 ){
7141  //  If missing packets: check the acq configuration          return validate; // exit
7142        }
7143    ////////////////////////////////////////////////////////
7144    //  ...otherwise there might be some missing packets
7145    //
7146    //  In this case check the acq configuration
7147  //  (some DSPs might be excluded from acquisition)  //  (some DSPs might be excluded from acquisition)
7148  //  -----------------------------------------------  ////////////////////////////////////////////////////////
7149    
7150        if(!eh || !file || (file&&file->IsZombie()) ){
7151            if ( IsDebug() )cout << " *** MISSING VIEW *** eh="<<eh<<" file="<<file<<" cannot validate"<<endl;
7152            return (0);
7153        }
7154        
7155  //  -----------------------------------------------  //  -----------------------------------------------
7156  //  retrieve the first run header after calib  //  retrieve the first run header after calib
7157  //  -----------------------------------------------  //  -----------------------------------------------
7158       PacketType *pctp;      
7159       EventCounter *cod;      PacketType *pctp;
7160       cod = eh->GetCounter();      EventCounter *cod;
7161       Int_t irun = cod->Get(pctp->RunHeader);      cod = eh->GetCounter();
7162       TTree *rh=(TTree*)file->Get("RunHeader");      Int_t irun = cod->Get(pctp->RunHeader);
7163       if ( !rh || rh->IsZombie() ) throw -17;      TTree *rh=(TTree*)file->Get("RunHeader");
7164       if( rh->GetEntries() == irun ){      if ( !rh || rh->IsZombie() ) throw -17;
7165            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (1)  -- cannot validate :-( "<<endl;      if( rh->GetEntries() <= irun ){
7166           return 0; // :-(          if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (1) -- cannot validate :-( "<<endl;
7167       }          return 0; // :-(
7168        }
7169       RunHeaderEvent *run  = 0;      RunHeaderEvent *run  = 0;
7170       EventHeader    *hrun = 0;      EventHeader    *hrun = 0;
7171       rh->SetBranchAddress("RunHeader", &run);      rh->SetBranchAddress("RunHeader", &run);
7172       rh->SetBranchAddress("Header", &hrun);      rh->SetBranchAddress("Header", &hrun);
7173       rh->GetEntry(irun);      rh->GetEntry(irun);    
7174  //     cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime() << " Run " << hrun->GetPscuHeader()->GetOrbitalTime() <<endl;      if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){
7175            if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (2) -- cannot validate :-( "<<endl;
7176       if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){          return 0; // :-(
7177            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (2) -- cannot validate :-( "<<endl;      }
7178           return 0; // :-(  
7179       }      UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());
7180            if( dtime > timeaftercalib ){
7181       if( !run->RM_ACQ_AFTER_CALIB ){          if ( IsDebug() ) cout << " *** MISSING-PKT *** run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;
7182            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) RM_ACQ_AFTER_CALIB=0    -- cannot validate :-( "<<endl;          return 0; // :-(
7183           return 0; // :-(      }
7184       }  
7185        if ( IsDebug() ) cout <<endl<< " ACQ_BUILD_INFO ==> "<<hex<<(run->ACQ_BUILD_INFO & mask)<<dec;
7186       UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());  
7187       if( dtime > timeaftercalib ){      if( (run->ACQ_BUILD_INFO & mask) != build ){
7188           if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;          validate=0; // :-(
7189           return 0; // :-(          cout <<endl<< " *** MISSING-PKT *** packet mismatch: ACQ_BUILD_INFO="<<hex<<(run->ACQ_BUILD_INFO&mask)<<" != "<<build<<dec;
7190       }      };
7191        
7192        return validate;
7193    
      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; // :-)  
7194    
7195  }  }
7196    
# Line 6378  UInt_t PamelaDBOperations::ValidateTrkCa Line 7200  UInt_t PamelaDBOperations::ValidateTrkCa
7200   *   *
7201   **/   **/
7202  UInt_t PamelaDBOperations::Check(){  UInt_t PamelaDBOperations::Check(){
7203          return(this->Check(0,0));    return(this->Check(0,0));
7204  }  }
7205    
7206  UInt_t PamelaDBOperations::Check(UInt_t from, UInt_t to){  UInt_t PamelaDBOperations::Check(UInt_t from, UInt_t to){
7207    //    //
7208          if ( IsDebug() ) printf(" from %u to %u \n",from,to);    if ( IsDebug() ) printf(" from %u to %u \n",from,to);
7209    //    //
7210    UInt_t test = 0;    UInt_t test = 0;
7211    //    //
# Line 6424  UInt_t PamelaDBOperations::Check(UInt_t Line 7246  UInt_t PamelaDBOperations::Check(UInt_t
7246      //      //
7247      if ( from > 0 && nid <= from ) goto ss;      if ( from > 0 && nid <= from ) goto ss;
7248      if ( to > 0 && nid >= to ) goto ss;      if ( to > 0 && nid >= to ) goto ss;
7249  //      //
7250      if ( (UInt_t)atoll(row->GetField(4)) > 1 ){      if ( (UInt_t)atoll(row->GetField(4)) > 1 ){
7251        //        //
7252        //        //
# Line 6455  UInt_t PamelaDBOperations::Check(UInt_t Line 7277  UInt_t PamelaDBOperations::Check(UInt_t
7277              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)));  
7278              row3 = result3->Next();              row3 = result3->Next();
7279            };            };
7280  //      delete result3;            //    delete result3;
7281    
7282          };          };
7283          //          //
# Line 6476  UInt_t PamelaDBOperations::Check(UInt_t Line 7298  UInt_t PamelaDBOperations::Check(UInt_t
7298              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)));
7299              row3 = result3->Next();              row3 = result3->Next();
7300            };            };
7301  //      delete result3;            //    delete result3;
7302          };          };
7303          //          //
7304          oss.str("");          oss.str("");
# Line 6496  UInt_t PamelaDBOperations::Check(UInt_t Line 7318  UInt_t PamelaDBOperations::Check(UInt_t
7318              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)));
7319              row3 = result3->Next();              row3 = result3->Next();
7320            };            };
7321   //     delete result3;            //    delete result3;
7322    
7323          };          };
7324        };        };
# Line 6517  UInt_t PamelaDBOperations::Check(UInt_t Line 7339  UInt_t PamelaDBOperations::Check(UInt_t
7339            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)));
7340            row3 = result3->Next();            row3 = result3->Next();
7341          };          };
7342  //      delete result3;          //      delete result3;
7343        };        };
7344        //        //
7345      };      };
# Line 6543  UInt_t PamelaDBOperations::Check(UInt_t Line 7365  UInt_t PamelaDBOperations::Check(UInt_t
7365        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
7366        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7367        test = 1;        test = 1;
7368  //      delete result2;        //        delete result2;
7369      };      };
7370      //      //
7371      if ( (thisrtt < prevrht) && (thisrht != prevrht) ){      if ( (thisrtt < prevrht) && (thisrht != prevrht) ){
# Line 6565  UInt_t PamelaDBOperations::Check(UInt_t Line 7387  UInt_t PamelaDBOperations::Check(UInt_t
7387        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
7388        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7389        test = 1;        test = 1;
7390  //      delete result2;        //        delete result2;
7391      };      };
7392      //      //
7393      if ( (thisrht > thisrtt) && (thisrht != prevrht) ){      if ( (thisrht > thisrtt) && (thisrht != prevrht) ){
# Line 6587  UInt_t PamelaDBOperations::Check(UInt_t Line 7409  UInt_t PamelaDBOperations::Check(UInt_t
7409        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
7410        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7411        test = 1;        test = 1;
7412  //      delete result2;        //        delete result2;
7413      };      };
7414  ss:    ss:
7415      //      //
7416      prevrht = thisrht;      prevrht = thisrht;
7417      prevrtt = thisrtt;      prevrtt = thisrtt;
7418      previd = thisid;      previd = thisid;
7419      prevl0id = thisl0id;      prevl0id = thisl0id;
7420      row = result->Next();      row = result->Next();
7421  //    if ( result2 ) delete result2;      //    if ( result2 ) delete result2;
7422  //    if ( result3 ) delete result3;      //    if ( result3 ) delete result3;
7423    };    };
7424    //    //
7425    return(test);    return(test);

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

  ViewVC Help
Powered by ViewVC 1.1.23