/[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.35 by mocchiut, Wed Apr 10 08:54:28 2013 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      RELAXED = false;
64    chewbacca = false;    chewbacca = false;
65    chminentry = 0;    chminentry = 0;
66    chID = 0;    chID = 0;
# Line 76  PamelaDBOperations::PamelaDBOperations(T Line 77  PamelaDBOperations::PamelaDBOperations(T
77      //      //
78    };    };
79    //    //
80      KEEPENV = false;
81      if ( keepenv ) KEEPENV=true;
82    STATIC=false;    STATIC=false;
83    if ( staticp ) STATIC=true;    if ( staticp ) STATIC=true;
84    //    //
# Line 85  PamelaDBOperations::PamelaDBOperations(T Line 88  PamelaDBOperations::PamelaDBOperations(T
88    //    //
89    glrun = new GL_RUN();    glrun = new GL_RUN();
90    //    //
91    if ( !chewbacca ){    //   if ( !chewbacca ){
92      if ( !boot ) SetNOBOOT(false);    //     if ( !boot ) SetNOBOOT(false);
93      SetTsync(tsync,gpamela);    //     SetTsync(tsync,gpamela);
94      SetBOOTnumber(boot,gpamela);    //     SetBOOTnumber(boot,gpamela);
95      SetObt0(obt0);    //     SetObt0(obt0);
96    };    //   };
97    //    //
98    SetTLEPath(tlefilename);    SetTLEPath(tlefilename);
99    //    //
# Line 99  PamelaDBOperations::PamelaDBOperations(T Line 102  PamelaDBOperations::PamelaDBOperations(T
102    if (INSERT_RAW) SetRawName(filerawname);    if (INSERT_RAW) SetRawName(filerawname);
103    //    //
104    INSERT_ROOT = !filerootname.IsNull();    INSERT_ROOT = !filerootname.IsNull();
105      if ( INSERT_ROOT ) this->SetRootName(filerootname);
106    this->SetOrbitNo(dwinput);    this->SetOrbitNo(dwinput);
107    //    //
108    this->SetID_RAW(0);    this->SetID_RAW(0);
# Line 122  void PamelaDBOperations::Close(){ Line 126  void PamelaDBOperations::Close(){
126  //  //
127  // SETTERS  // SETTERS
128  //  //
129    void PamelaDBOperations::NotChewbacca(UInt_t boot, UInt_t tsync, UInt_t obt0, Bool_t gpamela){
130      if ( !boot ) SetNOBOOT(false);
131      SetTsync(tsync,gpamela);
132      SetBOOTnumber(boot,gpamela);
133      SetObt0(obt0);
134    };
135    
136  void PamelaDBOperations::OpenL0File(TString filerootname){  void PamelaDBOperations::OpenL0File(TString filerootname){
137    if( INSERT_ROOT ){    if( INSERT_ROOT ){
# Line 132  void PamelaDBOperations::OpenL0File(TStr Line 142  void PamelaDBOperations::OpenL0File(TStr
142        stringstream qu;        stringstream qu;
143        TSQLResult *result = 0;        TSQLResult *result = 0;
144        TSQLResult *result2 = 0;        TSQLResult *result2 = 0;
145          TSQLResult *result3 = 0;
146        TSQLRow    *row    = 0;            TSQLRow    *row    = 0;    
147        TSQLRow    *row2    = 0;            TSQLRow    *row2    = 0;    
148          TSQLRow    *row3    = 0;    
149        TString chpath;        TString chpath;
150        TString chfile;        TString chfile;
151        UInt_t ridn = 0;        UInt_t ridn = 0;
152        qu.str("");        qu.str("");
153        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,REAL_TIME_INIT from ROOT_TABLE_MERGING where ID_N=" << chID << ";";
154        if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());        if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
155        result = conn->Query(qu.str().c_str());        result = conn->Query(qu.str().c_str());
156        if ( result ){        if ( result ){
# Line 149  void PamelaDBOperations::OpenL0File(TStr Line 161  void PamelaDBOperations::OpenL0File(TStr
161            chpktmax = (UInt_t)atoll(row->GetField(2));            chpktmax = (UInt_t)atoll(row->GetField(2));
162            chobtmin = (UInt_t)atoll(row->GetField(3));            chobtmin = (UInt_t)atoll(row->GetField(3));
163            chobtmax = (UInt_t)atoll(row->GetField(4));            chobtmax = (UInt_t)atoll(row->GetField(4));
164              chiby = (TString)(row->GetField(5));
165              chrtinit = (UInt_t)atoll(row->GetField(6));
166          } else {          } else {
167            throw -84;            throw -84;
168          };          };
# Line 157  void PamelaDBOperations::OpenL0File(TStr Line 171  void PamelaDBOperations::OpenL0File(TStr
171        };        };
172        delete result;        delete result;
173        qu.str("");        qu.str("");
174        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 << ";";
175        if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());        if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
176        result2 = conn->Query(qu.str().c_str());        result2 = conn->Query(qu.str().c_str());
177        if ( result2 ){        if ( result2 ){
178          row2 = result2->Next();          row2 = result2->Next();
179          if ( row2 ){          if ( row2 ){
180            chpath = (TString)gSystem->ExpandPathName(row2->GetField(0))+'/';            if ( KEEPENV ){
181                chpath = (TString)(row2->GetField(0))+'/';
182              } else {
183                chpath = (TString)gSystem->ExpandPathName(row2->GetField(0))+'/';
184              };
185            chfile = (TString)(row2->GetField(1));            chfile = (TString)(row2->GetField(1));
186            chobtts = (UInt_t)atoll(row2->GetField(2));            chobtts = (UInt_t)atoll(row2->GetField(2));
187            chlastts = (UInt_t)atoll(row2->GetField(3));            chlastts = (UInt_t)atoll(row2->GetField(3));
188            chresursts = (UInt_t)atoll(row2->GetField(4));            chresursts = (UInt_t)atoll(row2->GetField(4));
189            chboot = (UInt_t)atoll(row2->GetField(5));            chboot = (UInt_t)atoll(row2->GetField(5));
190            //            //
191              if ( !chboot ){
192                if ( debug ) printf(" mmm... no BOOT number determined by chewbacca, try to find it looking at DB \n");
193                //
194                // new feature: check in ROOT_TABLE (timewise) the previous and the next BOOT number != 0 , if it is the same we know this one!
195                // if it is different roll back to the old behaviour
196                //
197                qu.str("");
198                qu << "SELECT BOOT_NUMBER from ROOT_TABLE where BOOT_NUMBER!=0 AND REAL_TIME_INIT>"<< row2->GetField(10) <<" order by REAL_TIME_INIT asc limit 1;";
199                if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
200                UInt_t chbootA = 0;
201                UInt_t chbootB = 1;
202                result3 = conn->Query(qu.str().c_str());
203                if ( result3 ){
204                  row3 = result3->Next();
205                  if ( row3 ){
206                    chbootA = (UInt_t)atoll(row3->GetField(0));
207                    if ( debug ) printf(" Found boot_number A = %u \n",chbootA);
208                  };
209                };
210                delete result3;
211                qu.str("");
212                qu << "SELECT BOOT_NUMBER from ROOT_TABLE where BOOT_NUMBER!=0 AND REAL_TIME_INIT<"<< row2->GetField(10) <<" order by REAL_TIME_INIT desc limit 1;";
213                if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
214                result3 = conn->Query(qu.str().c_str());
215                if ( result3 ){
216                  row3 = result3->Next();
217                  if ( row3 ){
218                    chbootB = (UInt_t)atoll(row3->GetField(0));
219                    if ( debug ) printf(" Found boot_number B = %u \n",chbootB);
220                  };
221                };
222                if ( chbootA == chbootB ){
223                  chboot = chbootA;
224                  if ( debug ) printf(" Found boot_number! it is %u \n",chboot);
225                } else {        
226                  qu.str("");
227                  //            qu << "SELECT BOOT_NUMBER from ROOT_TABLE where BOOT_NUMBER!=0 AND ABS(LAST_TIME_SYNC_INFO-"<< chlastts <<")<10000 AND ABS(REAL_TIME_INIT-"<< row2->GetField(10) <<")<7200 group by BOOT_NUMBER order by BOOT_NUMBER asc;";
228                  //            qu << "SELECT BOOT_NUMBER from ROOT_TABLE where BOOT_NUMBER!=0 AND ABS(LAST_TIME_SYNC_INFO-"<< chlastts <<")<40000 AND ABS(REAL_TIME_INIT-"<< row2->GetField(10) <<")<40000 group by BOOT_NUMBER order by BOOT_NUMBER asc;"; // relax conditions... 090112 [8RED: error -29]
229                  qu << "SELECT BOOT_NUMBER from ROOT_TABLE where BOOT_NUMBER!=0 AND ABS(LAST_TIME_SYNC_INFO-"<< chlastts <<")<50000 AND ABS(REAL_TIME_INIT-"<< row2->GetField(10) <<")<50000 group by BOOT_NUMBER order by BOOT_NUMBER asc;"; // even more relaxed conditions... 091214 [9REDtest3: error -29]
230                  if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
231                  result3 = conn->Query(qu.str().c_str());
232                  if ( result3 ){
233                    row3 = result3->Next();
234                    if ( row3 && result3->GetRowCount() == 1 ){
235                      chboot = (UInt_t)atoll(row3->GetField(0));
236                      if ( debug ) printf(" Found boot_number = %u \n",chboot);
237                    } else {
238                      if ( debug ) printf(" AGH CANNOT DETERMINE THE BOOT NUMBER... \n");
239                      throw -29;
240                    };
241                  };
242                };
243              };
244              //
245            chpktinit = (UInt_t)atoll(row2->GetField(6));            chpktinit = (UInt_t)atoll(row2->GetField(6));
246            chpktfinal = (UInt_t)atoll(row2->GetField(7));            chpktfinal = (UInt_t)atoll(row2->GetField(7));
247            chobtinit = (UInt_t)atoll(row2->GetField(8));            chobtinit = (UInt_t)atoll(row2->GetField(8));
# Line 182  void PamelaDBOperations::OpenL0File(TStr Line 254  void PamelaDBOperations::OpenL0File(TStr
254          throw -85;          throw -85;
255        };        };
256        filerootname = chpath + chfile;// + ".root";        filerootname = chpath + chfile;// + ".root";
       if ( debug ) printf(" chewbacca: filename is %s \n",filerootname.Data());  
257      };      };
258      this->SetRootName(filerootname);      this->SetRootName(filerootname);
     file = TFile::Open(this->GetRootName().Data());  
   } else {  
     this->SetRootName("");  
259    };    };
260      if ( debug ) printf(" Filename is %s \n",filerootname.Data());
261      file = TFile::Open(this->GetRootName().Data());
262      //  } else {
263      //    this->SetRootName("");
264      //    this->SetRootName(filerootname);
265      //  };
266  }  }
267    
268  //  //
# Line 388  void PamelaDBOperations::SetOrbitNo(UInt Line 462  void PamelaDBOperations::SetOrbitNo(UInt
462      return;      return;
463    };    };
464    //    //
465    TString name = this->GetRootFile();    if ( !chewbacca ){
466    Int_t nlength = name.Length();      TString name = this->GetRootFile();
467    if ( nlength < 5 ) return;      Int_t nlength = name.Length();
468    TString dwo = 0;      if ( nlength < 5 ){
469    for (Int_t i = 0; i<5; i++){        if ( IsDebug() ) printf(" Agh problems determining the orbit number! name = %s \n",name.Data());
470      dwo.Append(name[i],1);        return;
471    };      };
472    if ( dwo.IsDigit() ){      TString dwo = "";
473      dworbit = (UInt_t)dwo.Atoi();      for (Int_t i = 0; i<5; i++){
   } else {  
     dwo="";  
     for (Int_t i = 8; i<13; i++){  
474        dwo.Append(name[i],1);        dwo.Append(name[i],1);
475      };          };
476      if ( dwo.IsDigit() ) dworbit = (UInt_t)dwo.Atoi();      if ( dwo.IsDigit() ){
477          dworbit = (UInt_t)dwo.Atoi();
478        } else {
479          dwo="";
480          for (Int_t i = 8; i<13; i++){
481            dwo.Append(name[i],1);
482          };    
483          if ( dwo.IsDigit() ) dworbit = (UInt_t)dwo.Atoi();
484        };
485        if ( IsDebug() ) printf(" Downlink orbit is %i (dwo = %s) \n",dworbit,dwo.Data());
486    };    };
   if ( IsDebug() ) printf(" Downlink orbit is %i (dwo = %s) \n",dworbit,dwo.Data());  
487    return;    return;
488  };  };
489    
# Line 435  TString PamelaDBOperations::GetRawPath() Line 514  TString PamelaDBOperations::GetRawPath()
514    
515  TString PamelaDBOperations::GetRootPath(){  TString PamelaDBOperations::GetRootPath(){
516    if ( STATIC ){    if ( STATIC ){
517      return((TString)gSystem->DirName(filerootname.Data())+'/');      return((TString)gSystem->DirName(this->GetRootName().Data())+'/');
518    } else {    } else {    
519      return((TString)gSystem->ExpandPathName("$PAM_L0")+'/');      if ( KEEPENV ){
520          return((TString)gSystem->ExpandPathName(gSystem->DirName(filerootname.Data()))+'/');
521        } else {
522          return((TString)gSystem->ExpandPathName("$PAM_L0")+'/');
523        };
524    };    };
525  };  };
526    
# Line 490  void PamelaDBOperations::SetCommonGLRUN( Line 573  void PamelaDBOperations::SetCommonGLRUN(
573  };  };
574    
575  /**  /**
576     *
577     * Set the variables which belogns to physendrun tree
578     *
579     */
580    void PamelaDBOperations::SetPhysEndRunVariables(){
581      //
582      //
583      //
584      TTree *T = 0;
585      T = (TTree*)file->Get("PhysEndRun");
586      if ( !T || T->IsZombie() ) throw -90;
587      //
588      PhysEndRunEvent *pher= 0;
589      EventHeader *eh = 0;
590      T->SetBranchAddress("PhysEndRun", &pher);
591      T->SetBranchAddress("Header", &eh);
592      //
593      UInt_t phobt = 0;
594      UInt_t phpkt = 0;
595      //
596      glrun->SetPHYSENDRUN_MASK_S3S2S12(0);
597      glrun->SetPHYSENDRUN_MASK_S11CRC(0);
598      //
599      for (Int_t p=0; p<T->GetEntries(); p++){
600        //
601        T->GetEntry(p);
602        //
603        phobt = (UInt_t)eh->GetPscuHeader()->GetOrbitalTime();
604        phpkt = (UInt_t)eh->GetPscuHeader()->GetCounter();
605        //
606        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())  ){
607          if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() || glrun->GetPHYSENDRUN_MASK_S11CRC() ){
608            if ( IsDebug() ) printf(" WARNING while looping in physendrun: found two PhysEndRun packet for the same RUN! \n");
609            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);
610            if ( PEDANTIC && IsDebug() ) printf(" ERROR while looping in physendrun: found two PhysEndRun packet for the same RUN!\n ");
611            if ( PEDANTIC ) throw -91;
612          } else {
613            glrun->SetPHYSENDRUN_MASK_S3S2S12((UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S3S2S12);
614            glrun->SetPHYSENDRUN_MASK_S11CRC((UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S11CRC);
615          };
616        };
617      };
618      //
619    };
620    
621    /**
622   * Patch, look for upper limits to avoid processing retransmitted data   * Patch, look for upper limits to avoid processing retransmitted data
623   */   */
624  Int_t PamelaDBOperations::SetUpperLimits(){  Int_t PamelaDBOperations::SetUpperLimits(){
# Line 603  Int_t PamelaDBOperations::SetUpperLimits Line 732  Int_t PamelaDBOperations::SetUpperLimits
732      UInt_t tjump = 50000;      UInt_t tjump = 50000;
733      //UInt_t tjump = 100;      //UInt_t tjump = 100;
734      while ( tjump > 0 ){      while ( tjump > 0 ){
735        pktlast = numeric_limits<UInt_t>::max();        //      pktlast = numeric_limits<UInt_t>::max();
736        while ( pktlast > chpktmax && (Int_t)(nevent-1-it) >= 0 ){        pktlast = chpktmax + 1;
737          while ( PKT(pktlast) > PKT(chpktmax) && (Int_t)(nevent-1-it) >= 0 ){
738          if ( (Int_t)(nevent-1-it) >= 0 ){          if ( (Int_t)(nevent-1-it) >= 0 ){
739            T->GetEntry(nevent-1-it);            T->GetEntry(nevent-1-it);
740            ph = eh->GetPscuHeader();            ph = eh->GetPscuHeader();
# Line 612  Int_t PamelaDBOperations::SetUpperLimits Line 742  Int_t PamelaDBOperations::SetUpperLimits
742          } else {          } else {
743            pktlast = chpktmax + 1;            pktlast = chpktmax + 1;
744          };          };
745          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));
746          it += tjump;          it += tjump;
747        };        };
748        if ( tjump > 1 ) it -= 2*tjump;        if ( tjump > 1 ) it -= 2*tjump;
# Line 636  Int_t PamelaDBOperations::SetUpperLimits Line 766  Int_t PamelaDBOperations::SetUpperLimits
766      tjump = 50000;      tjump = 50000;
767      //tjump = 100;      //tjump = 100;
768      while ( tjump > 0 ){      while ( tjump > 0 ){
769        pktlast = 0;        //      pktlast = 0;
770        while ( pktlast < chpktmin && it < (Int_t)nevent ){        pktlast = chpktmin - 1;
771          if ( debug ) printf("LLlook for down %i %i %llu %llu \n",it,pktlast,PKT(pktlast),PKT(chpktmin));
772          while ( PKT(pktlast) < PKT(chpktmin) && it < (Int_t)nevent ){
773          if ( it < (Int_t)nevent ){          if ( it < (Int_t)nevent ){
774            T->GetEntry(it);            T->GetEntry(it);
775            ph = eh->GetPscuHeader();            ph = eh->GetPscuHeader();
# Line 731  Int_t PamelaDBOperations::SetUpperLimits Line 863  Int_t PamelaDBOperations::SetUpperLimits
863      ph = eh->GetPscuHeader();      ph = eh->GetPscuHeader();
864      pktlast = ph->GetCounter();      pktlast = ph->GetCounter();
865      nevent = upperentry - chminentry;      nevent = upperentry - chminentry;
866        if ( ((Int_t)upperentry - (Int_t)chminentry) < 0 ) nevent = 0; // nevent is UInt_t! 090112 [8RED: error -88]
867        if ( IsDebug() ) printf(" Setting nevent to %u - upperentry %i chminentry %i \n",nevent,upperentry,chminentry);
868      //      //
869    } else {    } else {
870      upperpkt = PKT(pktlast);      upperpkt = PKT(pktlast);
# Line 739  Int_t PamelaDBOperations::SetUpperLimits Line 873  Int_t PamelaDBOperations::SetUpperLimits
873    };    };
874    //    //
875    if ( chewbacca && nevent < 1 ) {    if ( chewbacca && nevent < 1 ) {
876          pktfirst = chpktmin;      if ( IsDebug() ) printf(" chewbacca and no events in the file \n");
877          upperpkt = PKT(chpktmax);      pktfirst = chpktmin;
878          pktlast = chpktmax;      upperpkt = PKT(chpktmax);
879          obtfirst = chobtmin;      pktlast = chpktmax;
880          obtlast = chobtmax;      obtfirst = chobtmin;
881          upperobt = OBT(chobtmax);      obtlast = chobtmax;
882        upperobt = OBT(chobtmax);
883    };    };
884    //    //
885    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 887  Int_t PamelaDBOperations::SetUpperLimits
887    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);
888    //    //
889    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)) ){
890          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));
891          if ( PEDANTIC ) throw -88;      if ( PEDANTIC ) throw -88;
892          return(32);      return(32);
893    };    };
894    //    //
895    if ( !nevent ) return(64);    if ( !nevent ) return(64);
# Line 764  Int_t PamelaDBOperations::SetUpperLimits Line 899  Int_t PamelaDBOperations::SetUpperLimits
899    //  if ( nevent < jump ) jump = int(nevent/10);    //  if ( nevent < jump ) jump = int(nevent/10);
900    //  if ( !jump ) jump = 1;    //  if ( !jump ) jump = 1;
901    //    //
902    if ( (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) || (labs(PKT(pktlast)-PKT(pktfirst))<deltapkt && labs(OBT(obtlast)-OBT(obtfirst))<deltaobt) && nevent > deltapkt ){  
903      if ( ((PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) || (labs(PKT(pktlast)-PKT(pktfirst))<deltapkt && labs(OBT(obtlast)-OBT(obtfirst))<deltaobt)) && nevent > deltapkt ){
904      //      //
905      if ( IsDebug() ) printf(" starting jump %i \n",jump);      if ( IsDebug() ) printf(" starting jump %i \n",jump);
906      //    if ( IsDebug() ) printf(" (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(" (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));
# Line 1040  Int_t PamelaDBOperations::SetUpperLimits Line 1176  Int_t PamelaDBOperations::SetUpperLimits
1176          upperpkt = pkth;          upperpkt = pkth;
1177          upperobt = obth;          upperobt = obth;
1178          rhev = lasthead+1;          rhev = lasthead+1;
1179      } else {        } else {
1180          rhev = lasthead;          rhev = lasthead;
1181        };        };
1182        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 1215  UInt_t PamelaDBOperations::AssignRunID()
1215    stringstream   oss;    stringstream   oss;
1216    //      //  
1217    oss.str("");    oss.str("");
1218    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.
1219        if ( !strcmp(tag.Data(),"NONE") ){
1220          oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< chiby.Data() <<"');";
1221        } else {
1222          oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< tag.Data() <<"');";
1223        };
1224      } else {
1225        oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< tag.Data() <<"');";
1226      };
1227    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1228    if ( !result ) throw -10;    if ( !result ) throw -10;
1229    oss.str("");    oss.str("");
# Line 1227  void PamelaDBOperations::LockTables(){   Line 1371  void PamelaDBOperations::LockTables(){  
1371    stringstream oss;    stringstream oss;
1372    //      //  
1373    oss.str("");    oss.str("");
1374    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;";
1375    TSQLResult *result = 0;    TSQLResult *result = 0;
1376    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1377    if ( !result ) throw -10;    if ( !result ) throw -10;
# Line 1260  void PamelaDBOperations::UnLockTables(){ Line 1404  void PamelaDBOperations::UnLockTables(){
1404   */   */
1405  Long64_t PamelaDBOperations::PKT(UInt_t pkt_num){    Long64_t PamelaDBOperations::PKT(UInt_t pkt_num){  
1406    //    //
1407  //  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));
1408    //    //
1409    if ( pkt_num < (ppktfirst/2) && ppktfirst > (16777214/2)  ){    if ( pkt_num < (ppktfirst/2) && ppktfirst > (16777214/2)  ){
1410  //    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);
1411      return((Long64_t)pkt_num+16777215LL);      return((Long64_t)pkt_num+16777215LL);
1412    };    };
1413    //    //
1414    if ( pkt_num > ((Long64_t)ppktfirst*2) && pkt_num > (16777214/2) ){    if ( pkt_num > ((Long64_t)ppktfirst*2) && pkt_num > (16777214/2) ){
1415  //    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);
1416      return((Long64_t)pkt_num-16777215LL);      return((Long64_t)pkt_num-16777215LL);
1417    };    };
1418    //    //
1419  //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)pkt_num);    //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)pkt_num);
1420    return((Long64_t)pkt_num);    return((Long64_t)pkt_num);
1421    //    //
1422  };  };
# Line 1282  Long64_t PamelaDBOperations::PKT(UInt_t Line 1426  Long64_t PamelaDBOperations::PKT(UInt_t
1426   */   */
1427  Long64_t PamelaDBOperations::OBT(UInt_t obt){    Long64_t PamelaDBOperations::OBT(UInt_t obt){  
1428    //    //
1429  //  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));
1430    //    //
1431    if ( obt < (pobtfirst/2) && pobtfirst > (numeric_limits<UInt_t>::max()/2) ){    if ( obt < ((Long64_t)pobtfirst/2) && pobtfirst > (numeric_limits<UInt_t>::max()/2) ){
1432  //    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());
1433      return((Long64_t)obt+(Long64_t)numeric_limits<UInt_t>::max());      return((Long64_t)obt+(Long64_t)numeric_limits<UInt_t>::max());
1434    };    };
1435    //    //
1436    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) ){
1437  //    if ( IsDebug() ) printf(" pobtfirst*2 %lld \n",((Long64_t)pobtfirst*2));      //    if ( IsDebug() ) printf(" pobtfirst*2 %lld \n",((Long64_t)pobtfirst*2));
1438  //    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());
1439      return((Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());      return((Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());
1440    };    };
1441    //    //
1442  //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)obt);    //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)obt);
1443    return((Long64_t)obt);    return((Long64_t)obt);
1444  };  };
1445    
# Line 1331  void PamelaDBOperations::FillClass(Bool_ Line 1475  void PamelaDBOperations::FillClass(Bool_
1475    UInt_t lastPkt = 0;    UInt_t lastPkt = 0;
1476    UInt_t rhtime = 0;    UInt_t rhtime = 0;
1477    UInt_t rttime = 0;    UInt_t rttime = 0;
1478      //
1479      if ( IsDebug() ) printf(" A firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1480      //
1481    if ( !mishead ){    if ( !mishead ){
1482      codh = ehh->GetCounter();      codh = ehh->GetCounter();
1483      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1) ){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){      
1484          if ( IsDebug() ) printf(" B firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1485        firstev = 1;        firstev = 1;
1486        lastev = 0;        lastev = 0;
1487      } else {      } else {
# Line 1346  void PamelaDBOperations::FillClass(Bool_ Line 1494  void PamelaDBOperations::FillClass(Bool_
1494    };    };
1495    if ( !mistrail ){    if ( !mistrail ){
1496      codt = eht->GetCounter();      codt = eht->GetCounter();
1497      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1)){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1)){      
1498          if ( IsDebug() ) printf(" C firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1499        lastev = 0;        lastev = 0;
1500        firstev = lastev+1;        firstev = lastev+1;
1501      } else {      } else {
# Line 1363  void PamelaDBOperations::FillClass(Bool_ Line 1512  void PamelaDBOperations::FillClass(Bool_
1512    if ( mishead ) {    if ( mishead ) {
1513      glrun->Set_GL_RUNH0();      glrun->Set_GL_RUNH0();
1514      //      //
1515      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1) ){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){      
1516        firstObt = lastObt;        firstObt = lastObt;
1517        firstPkt = lastPkt;        firstPkt = lastPkt;
1518        rhtime = rttime;        rhtime = rttime;
# Line 1382  void PamelaDBOperations::FillClass(Bool_ Line 1531  void PamelaDBOperations::FillClass(Bool_
1531    if ( mistrail ){    if ( mistrail ){
1532      glrun->Set_GL_RUNT0();      glrun->Set_GL_RUNT0();
1533      //      //
1534      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1) ){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){      
1535        lastObt = firstObt;        lastObt = firstObt;
1536        lastPkt = firstPkt;        lastPkt = firstPkt;
1537        rttime = rhtime;        rttime = rhtime;
# Line 1398  void PamelaDBOperations::FillClass(Bool_ Line 1547  void PamelaDBOperations::FillClass(Bool_
1547      glrun->SetRUNTRAILER_PKT(lastPkt);      glrun->SetRUNTRAILER_PKT(lastPkt);
1548      //          //    
1549    };    };
1550      //
1551      // ad hoc solution for INF EV_TO [8RED] 090113
1552      //
1553      if ( !firstev && lastev == -1 ){
1554        if ( IsDebug() ) printf(" EE firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1555        firstev = 1;
1556        lastev = 0;
1557      };
1558    glrun->SetEV_FROM((UInt_t)firstev);    glrun->SetEV_FROM((UInt_t)firstev);
1559    glrun->SetEV_TO((UInt_t)lastev);    glrun->SetEV_TO((UInt_t)lastev);
1560    glrun->SetNEVENTS((UInt_t)lastev-(UInt_t)firstev+1);    glrun->SetNEVENTS((UInt_t)lastev-(UInt_t)firstev+1);
# Line 1405  void PamelaDBOperations::FillClass(Bool_ Line 1562  void PamelaDBOperations::FillClass(Bool_
1562    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);
1563    //    //
1564    this->SetCommonGLRUN(rhtime,rttime);    this->SetCommonGLRUN(rhtime,rttime);
1565      this->SetPhysEndRunVariables();
1566    //    //
1567  };  };
1568    
# Line 1416  void PamelaDBOperations::FillClass(Bool_ Line 1574  void PamelaDBOperations::FillClass(Bool_
1574   * Insert a new row into GL_RAW table.   * Insert a new row into GL_RAW table.
1575   */   */
1576  Int_t PamelaDBOperations::insertPamelaRawFile(){  Int_t PamelaDBOperations::insertPamelaRawFile(){
1577    
1578        //
1579        Bool_t idr =  this->SetID_RAW();
1580        if ( idr ) return(1);
1581    
1582        GL_RAW glraw = GL_RAW();
1583        
1584        glraw.PATH = GetRawPath();
1585        glraw.NAME = GetRawFile();
1586        //    glraw.BOOT_NUMBER = 0;//???
1587        glraw.BOOT_NUMBER = this->GetBOOTnumber();
1588        
1589        if( insertPamelaRawFile(&glraw) )return(1);
1590        //
1591        idr =  this->SetID_RAW();
1592        if ( !idr ) throw -11;
1593        
1594        return(0);
1595    }
1596    /**
1597     * Insert a new row into GL_RAW table.
1598     */
1599    Int_t PamelaDBOperations::insertPamelaRawFile(GL_RAW *glraw){
1600    //    //
1601    stringstream oss;      if(!glraw)return(1);//?? ok I think
1602    //      //
1603    Bool_t idr =  this->SetID_RAW();      stringstream oss;
1604    if ( idr ) return(1);      //
1605    //      oss.str("");
1606    oss.str("");      if ( STATIC ){
1607    if ( STATIC ){          oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"
1608      oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"              << glraw->PATH << "', '" << glraw->NAME << "')";
1609          << this->GetRawPath().Data() << "', '" << this->GetRawFile().Data() << "')";      } else {
1610    } else {          oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('$PAM_RAW', '" << glraw->NAME << "')";
1611      oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('$PAM_RAW', '" << this->GetRawFile().Data() << "')";      };
1612    };      if ( debug ) cout <<oss.str().c_str() <<endl;
1613    if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;      if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
1614    //      //
1615    idr =  this->SetID_RAW();      oss.str("");
1616    if ( !idr ) throw -11;      oss << "SELECT ID FROM GL_RAW WHERE NAME=\""<<glraw->NAME<<"\";";
1617    //      if ( debug ) cout << oss.str().c_str()<<endl;
1618    return(0);      if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
1619        //
1620        TSQLResult *result = 0;
1621        TSQLRow    *row    = 0;
1622        result = conn->Query(oss.str().c_str());
1623        if ( result == NULL ) throw -4;
1624        row = result->Next();
1625        if ( !row ) return(1);
1626        glraw->ID = (UInt_t)atoll(row->GetField(0));
1627        if ( debug ) printf(" The ID of the RAW file is %u \n",glraw->ID);
1628        delete result;
1629        delete row;
1630        //
1631        return(0);
1632  }  }
1633    
1634    
# Line 1467  Int_t PamelaDBOperations::insertPamelaGL Line 1661  Int_t PamelaDBOperations::insertPamelaGL
1661      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
1662      if ( !result ) throw -10;      if ( !result ) throw -10;
1663      row = result->Next();      row = result->Next();
1664        if ( !row ) throw -92;
1665      idresof = (UInt_t)atoll(row->GetField(0));      idresof = (UInt_t)atoll(row->GetField(0));
1666      existsts = true;      existsts = true;
1667      goto eout;      goto eout;
# Line 1488  Int_t PamelaDBOperations::insertPamelaGL Line 1683  Int_t PamelaDBOperations::insertPamelaGL
1683      if ( !row ){      if ( !row ){
1684        oss.str("");        oss.str("");
1685        oss << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE),ID FROM GL_RESURS_OFFSET WHERE FROM_ORBIT< "        oss << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE),ID FROM GL_RESURS_OFFSET WHERE FROM_ORBIT< "
1686            << dworbit << " order by FROM_ORBIT desc limit 1;";            << dworbit << " AND SPECIAL_FILE='' order by FROM_ORBIT desc limit 1;";
1687        if ( IsDebug() ) printf(" %s \n",oss.str().c_str());        if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
1688        result = conn->Query(oss.str().c_str());        result = conn->Query(oss.str().c_str());
1689        if ( !result ) throw -10;        if ( !result ) throw -10;
# Line 1535  Int_t PamelaDBOperations::insertPamelaGL Line 1730  Int_t PamelaDBOperations::insertPamelaGL
1730      TYPE = 0;      TYPE = 0;
1731      TSYNC = 0;      TSYNC = 0;
1732      //      //
1733      Double_t minimum = 0.;      //    Double_t minimum = 0.;
1734      Double_t maximum = 0.;      // Double_t maximum = 0.;
1735      Double_t minimum2 = 0.;      //Double_t minimum2 = 0.;
1736      Double_t maximum2 = 0.;      Double_t maximum2 = 0.;
1737      //      //
1738      //      //
# Line 1545  Int_t PamelaDBOperations::insertPamelaGL Line 1740  Int_t PamelaDBOperations::insertPamelaGL
1740      pamela::McmdRecord *mcrc = 0;      pamela::McmdRecord *mcrc = 0;
1741      TArrayC *mcmddata = 0;      TArrayC *mcmddata = 0;
1742      //      //
1743      minimum = numeric_limits<Double_t>::max();      //    minimum = numeric_limits<Double_t>::max();
1744      maximum = numeric_limits<Double_t>::min();      //    maximum = numeric_limits<Double_t>::min();
1745      minimum2 = numeric_limits<Double_t>::max();      //    minimum2 = numeric_limits<Double_t>::max();
1746      maximum2 = numeric_limits<Double_t>::min();      maximum2 = numeric_limits<Double_t>::min();
1747      //      //
1748      T = (TTree*)file->Get("Mcmd");      T = (TTree*)file->Get("Mcmd");
# Line 1746  Int_t PamelaDBOperations::insertPamelaGL Line 1941  Int_t PamelaDBOperations::insertPamelaGL
1941   * 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.
1942   */   */
1943  Int_t PamelaDBOperations::insertPamelaRootFile(){  Int_t PamelaDBOperations::insertPamelaRootFile(){
1944    stringstream oss;  
1945    TSQLResult *result = 0;      stringstream oss;
1946    TSQLRow    *row    = 0;      TSQLResult *result = 0;
1947    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;  
1948      //      //
1949      row = result->Next();      // ----------------------
1950        // determine the timesync
1951        // ----------------------
1952        UInt_t idtimesync = 0;
1953      //      //
1954      if ( !row ) throw -3;      if ( chewbacca ){
1955      idtimesync = (UInt_t)atoll(row->GetField(0));          oss.str("");
1956    } else {          oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" limit 1;";
1957      oss.str("");          if ( debug ) printf(" %s \n",oss.str().c_str());
1958      if ( STATIC ){          result = conn->Query(oss.str().c_str());
1959        oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "          //
1960            << " LEFT JOIN GL_ROOT "          if ( !result ) throw -3;
1961            << " ON GL_RAW.ID = GL_ROOT.ID_RAW "          //
1962            << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "          row = result->Next();
1963            << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";          //
1964            if ( !row ) throw -3;
1965            idtimesync = (UInt_t)atoll(row->GetField(0));
1966      } else {      } else {
1967        oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "          oss.str("");
1968            << " LEFT JOIN GL_ROOT "          if ( STATIC ){
1969            << " ON GL_RAW.ID = GL_ROOT.ID_RAW "              oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1970            << " WHERE GL_RAW.PATH = '$PAM_RAW' AND "                  << " LEFT JOIN GL_ROOT "
1971            << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";                  << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1972                    << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "
1973                    << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1974            } else {
1975                oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1976                    << " LEFT JOIN GL_ROOT "
1977                    << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1978                    << " WHERE GL_RAW.PATH = '$PAM_RAW' AND "
1979                    << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1980            };
1981            result = conn->Query(oss.str().c_str());
1982            //
1983            if ( !result ) throw -12;
1984            //
1985            row = result->Next();
1986            //
1987            if ( !row ) throw -10;
1988            if ( row != NULL && (UInt_t)atoll(row->GetField(0))>0 ){
1989                idroot = (UInt_t)atoll(row->GetField(2));
1990                delete row;
1991                delete result;
1992                return(1);
1993            };
1994            //
1995            // determine which timesync has to be used
1996            //
1997            oss.str("");
1998            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;";
1999            result = conn->Query(oss.str().c_str());
2000            //
2001            if ( !result ) throw -3;
2002            //
2003            row = result->Next();
2004            //
2005            if ( !row ) throw -3;
2006            idtimesync = (UInt_t)atoll(row->GetField(0));
2007      };      };
2008      result = conn->Query(oss.str().c_str());      
2009      //      delete row;
2010      if ( !result ) throw -12;      delete result;
2011      //  
2012      row = result->Next();      // ----------------------
2013      //      // insert root file
2014      if ( !row ) throw -10;      // ----------------------
2015      if ( row != NULL && (UInt_t)atoll(row->GetField(0))>0 ){  
2016        idroot = (UInt_t)atoll(row->GetField(2));      GL_ROOT glroot = GL_ROOT();
2017        return(1);      
2018        glroot.ID_RAW = GetID_RAW();
2019        glroot.ID_TIMESYNC = idtimesync;
2020        if ( STATIC ){
2021          glroot.PATH = GetRootPath();
2022        } else {
2023          if ( KEEPENV ){
2024            glroot.PATH = gSystem->DirName(filerootname.Data());
2025          } else {
2026            glroot.PATH = "$PAM_L0";
2027          };
2028      };      };
2029      //      glroot.NAME = GetRootFile();
2030      // determine which timesync has to be used  
2031      //      if ( insertPamelaRootFile(&glroot) )return 1;
2032      oss.str("");  
2033      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);
2034      result = conn->Query(oss.str().c_str());      
2035      //  
2036      if ( !result ) throw -3;      return (0);
2037      //  }
2038      row = result->Next();  /**
2039      //   * Insert all the new rows into GL_ROOT.
2040      if ( !row ) throw -3;   * The raw file indicates in the parameters should be already been stored in the database.
2041      idtimesync = (UInt_t)atoll(row->GetField(0));   */
2042    };  Int_t PamelaDBOperations::insertPamelaRootFile(GL_ROOT *glroot){
2043      stringstream oss;
2044      TSQLResult *result = 0;
2045      TSQLRow    *row    = 0;
2046      //
2047    //    //
2048    oss.str("");    oss.str("");
2049    if ( STATIC ){    oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
2050      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() << "')";  
   };  
2051    //    //
2052    if ( debug ) printf(" query is %s \n",oss.str().c_str());    if ( debug ) printf("%s \n",oss.str().c_str());
2053    if (conn->Query(oss.str().c_str()) == 0) throw -4;    if (conn->Query(oss.str().c_str()) == 0) throw -4;
2054    //    //
2055    delete result;    delete result;
2056    //    //
2057    oss.str("");    oss.str("");
2058    //  oss << "SELECT ID FROM GL_ROOT WHERE ID_RAW=" << this->GetID_RAW() << ";";    //  oss << "SELECT ID FROM GL_ROOT WHERE ID_RAW=" << this->GetID_RAW() << ";";
2059    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() <<"';";  
   };  
2060    //    //
2061    if ( debug ) printf(" query is %s \n",oss.str().c_str());    if ( debug ) printf("%s \n",oss.str().c_str());
2062    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
2063    if ( !result ) throw -12;    if ( !result ) throw -12;
2064    row = result->Next();    row = result->Next();
2065    if ( !row ) throw -3;    if ( !row ) throw -3;
2066    this->SetID_ROOT((UInt_t)atoll(row->GetField(0)));  
2067    if ( debug ) printf(" The ID of the ROOT file is %u \n",this->GetID_ROOT());    glroot->ID = (UInt_t)atoll(row->GetField(0));
2068    
2069      if ( debug ) printf(" The ID of the ROOT file is %u \n",glroot->ID);
2070    //    //
2071    delete result;    delete result;
2072    //    //
# Line 2037  Int_t PamelaDBOperations::insertPamelaRU Line 2270  Int_t PamelaDBOperations::insertPamelaRU
2270    //    //
2271    // no runtrailers in the file!    // no runtrailers in the file!
2272    //    //
2273    if ( !rtev ){    if ( IsDebug() ) printf(" Start rtev %i rhev %i nrtev %i nrhev %i \n",rtev,rhev,nrtev,nrhev);
2274      if ( !rhev ){    if ( !rtev || (chewbacca && !nrtev) ){
2275        if ( IsDebug() ) printf(" No runtrailers \n");
2276        if ( !rhev || (chewbacca && !nrhev) ){
2277        if ( IsDebug() ) printf(" No runheaders nor runtrailers!! \n");        if ( IsDebug() ) printf(" No runheaders nor runtrailers!! \n");
2278        if ( !(upperentry-chminentry) ){        if ( !(upperentry-chminentry) ){
2279          if ( IsDebug() ) printf(" No physics events nor runs in the file \n"); // di nuovo potrebbe esserci un runtrailer senza eventi (riempimento MM)          if ( IsDebug() ) printf(" No physics events nor runs in the file \n"); // di nuovo potrebbe esserci un runtrailer senza eventi (riempimento MM)
# Line 2061  Int_t PamelaDBOperations::insertPamelaRU Line 2296  Int_t PamelaDBOperations::insertPamelaRU
2296            cod = ehh->GetCounter();            cod = ehh->GetCounter();
2297            tcod = (UInt_t)cod->Get(pctp->Physics);            tcod = (UInt_t)cod->Get(pctp->Physics);
2298            evbefh = TMath::Max(chminentry,tcod);            evbefh = TMath::Max(chminentry,tcod);
2299  //        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
2300            if ( (UInt_t)evbefh == upperentry || !upperentry ) evbefh = upperentry + 1;            if ( (UInt_t)evbefh == upperentry || !upperentry ) evbefh = upperentry + 1;
2301  //            //
2302          if ( debug ) printf(" evbefh %i upperentry %u \n",evbefh,upperentry);            if ( debug ) printf(" evbefh %i upperentry %u \n",evbefh,upperentry);
2303            //            //
2304            this->HandleRunFragments(false,true,evbefh,upperentry);            this->HandleRunFragments(false,true,evbefh,upperentry);
2305            //            //
# Line 2075  Int_t PamelaDBOperations::insertPamelaRU Line 2310  Int_t PamelaDBOperations::insertPamelaRU
2310      //      //
2311    } else {    } else {
2312      //      //
2313        if ( IsDebug() ) printf(" We have runtrailers \n");
2314      Int_t conptt = -1;      Int_t conptt = -1;
2315      for (Int_t ptt=0; ptt<rtev; ptt++){      for (Int_t ptt=0; ptt<rtev; ptt++){
2316        //        //
# Line 2091  Int_t PamelaDBOperations::insertPamelaRU Line 2327  Int_t PamelaDBOperations::insertPamelaRU
2327          ptht = cod->Get(pctp->RunHeader) - 1;          ptht = cod->Get(pctp->RunHeader) - 1;
2328          //      evbeft = cod->Get(pctp->Physics);          //      evbeft = cod->Get(pctp->Physics);
2329          tcod = (UInt_t)cod->Get(pctp->Physics);          tcod = (UInt_t)cod->Get(pctp->Physics);
2330          if ( !tcod ) tcod = 1;          if ( !tcod ) tcod = 1;    // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
2331          evbeft = TMath::Min(upperentry,(tcod-1));          evbeft = TMath::Min(upperentry,(tcod-1));
2332          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));
2333          //          //
# Line 2130  Int_t PamelaDBOperations::insertPamelaRU Line 2366  Int_t PamelaDBOperations::insertPamelaRU
2366            obth = phh->GetOrbitalTime();            obth = phh->GetOrbitalTime();
2367            cod = ehh->GetCounter();            cod = ehh->GetCounter();
2368            tcod = (UInt_t)cod->Get(pctp->Physics);            tcod = (UInt_t)cod->Get(pctp->Physics);
2369            if ( !tcod ) tcod = 1;            if ( !tcod ) tcod = 1; // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
2370            evbefh = TMath::Max(chminentry,(tcod-1));            evbefh = TMath::Max(chminentry,(tcod-1));
2371            //            //
2372            if ( PKT(pkth) >= PKT(pktfirst) && PKT(pkth) <= upperpkt ){            if ( PKT(pkth) >= PKT(pktfirst) && PKT(pkth) <= upperpkt ){
# Line 2169  Int_t PamelaDBOperations::insertPamelaRU Line 2405  Int_t PamelaDBOperations::insertPamelaRU
2405                //                //
2406                this->HandleRunFragments(true,true,chminentry,(evbefh));                this->HandleRunFragments(true,true,chminentry,(evbefh));
2407                //                //
2408                  // what about pth=ptht-1
2409              };              };
2410            };            };
2411            //            //
# Line 2191  Int_t PamelaDBOperations::insertPamelaRU Line 2428  Int_t PamelaDBOperations::insertPamelaRU
2428                cod = ehh->GetCounter();                cod = ehh->GetCounter();
2429                //            evbeft = cod->Get(pctp->Physics);                //            evbeft = cod->Get(pctp->Physics);
2430                tcod = (UInt_t)cod->Get(pctp->Physics);                tcod = (UInt_t)cod->Get(pctp->Physics);
2431                if ( !tcod ) tcod = 1;                if ( !tcod ) tcod = 1; // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
2432                evbeft = TMath::Min(upperentry,(tcod-1));                evbeft = TMath::Min(upperentry,(tcod-1));
2433                rh->GetEntry(pth);                rh->GetEntry(pth);
2434                phh = ehh->GetPscuHeader();                phh = ehh->GetPscuHeader();
# Line 2231  Int_t PamelaDBOperations::insertPamelaRU Line 2468  Int_t PamelaDBOperations::insertPamelaRU
2468          //      if ( ptt+1 == rtev){            //      if ( ptt+1 == rtev){  
2469          if ( conptt+1 == nrtev ){            if ( conptt+1 == nrtev ){  
2470            //    if ( conptt+1 == (nrtev+nrtbef )){              //    if ( conptt+1 == (nrtev+nrtbef )){  
2471              if ( IsDebug() ) printf(" >>>>>>>>>>> %i %u %i %u \n",ptht,rhev,nrtev,conptt);
2472            ptht++;            ptht++;
2473            if ( ptht < rhev ){            if ( ptht < rhev ){
2474              rh->GetEntry(ptht);              rh->GetEntry(ptht);
2475                //pth++;
2476                //if ( pth < rhev ){
2477                //rh->GetEntry(pth);
2478              phh = ehh->GetPscuHeader();              phh = ehh->GetPscuHeader();
2479              pkth = phh->GetCounter();              pkth = phh->GetCounter();
2480              obth = phh->GetOrbitalTime();              obth = phh->GetOrbitalTime();
# Line 2257  Int_t PamelaDBOperations::insertPamelaRU Line 2498  Int_t PamelaDBOperations::insertPamelaRU
2498              if ( (UInt_t)evbeft < upperentry-1 && upperentry>0 ){              if ( (UInt_t)evbeft < upperentry-1 && upperentry>0 ){
2499                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);
2500                //                //
2501                if ( (ptt-1) < 0 ) throw -15; // should never arrive here!                //              if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
2502                rt->GetEntry(ptt-1);                if ( (rtev-1) < 0 || ptt < 0 ) throw -15; // should never arrive here!
2503                  //              rt->GetEntry(ptt-1);
2504                  rt->GetEntry(rtev-1);
2505                cod = eht->GetCounter();                cod = eht->GetCounter();
2506                tcod = (UInt_t)cod->Get(pctp->Physics);                tcod = (UInt_t)cod->Get(pctp->Physics)+1;
2507                evbefh = TMath::Max(chminentry,tcod);                evbefh = TMath::Max(chminentry,tcod);
2508                //            evbefh = cod->Get(pctp->Physics);                //            evbefh = cod->Get(pctp->Physics);
2509                rt->GetEntry(ptt);                rt->GetEntry(ptt);
# Line 2367  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2610  Bool_t PamelaDBOperations::IsRunAlreadyI
2610        //        //
2611        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");
2612        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2613  //       oss.str("");        //       oss.str("");
2614  //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2615  //       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());      
2616  //       conn->Query(oss.str().c_str());        //       conn->Query(oss.str().c_str());
2617        if ( signal ) signal = false;        if ( signal ) signal = false;
2618        goto gonext;              goto gonext;      
2619        //        //
# Line 2385  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2628  Bool_t PamelaDBOperations::IsRunAlreadyI
2628        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");
2629        //        //
2630        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2631  //       oss.str("");        //       oss.str("");
2632  //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2633  //       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());      
2634  //       conn->Query(oss.str().c_str());        //       conn->Query(oss.str().c_str());
2635        //        //
2636        if ( signal ) signal = false;        if ( signal ) signal = false;
2637        goto gonext;        goto gonext;
# Line 2403  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2646  Bool_t PamelaDBOperations::IsRunAlreadyI
2646        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");
2647        //        //
2648        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2649  //       oss.str("");        //       oss.str("");
2650  //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2651  //       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());      
2652  //       conn->Query(oss.str().c_str());        //       conn->Query(oss.str().c_str());
2653        if ( signal ) signal = false;        if ( signal ) signal = false;
2654        //        //
2655      };      };
# Line 2488  void PamelaDBOperations::HandleRunFragme Line 2731  void PamelaDBOperations::HandleRunFragme
2731      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");
2732      //      //
2733    } 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 ){  
2734      //      //
2735      // 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
2736      //      //
2737      if ( IsDebug() ) printf(" The run is new \n");      if ( firstev != (lastev+1) ){ // could be a problem sometimes (?)
2738      if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");        if ( rhfirstev != firstev && !mishead ) mishead = true;
2739          if ( rtlastev != lastev && !mistrail ) mistrail = true;
2740        };
2741      //      //
2742      glrun->SetID(this->AssignRunID());      if ( IsDebug() ) printf(" bhere firstev is %i lastev is %i \n",firstev,lastev);
2743      glrun->SetID_RUN_FRAG(0);      this->FillClass(mishead,mistrail,firstev,lastev);
2744      glrun->Fill_GL_RUN_FRAGMENTS(conn);      if ( IsDebug() ) printf(" chere firstev is %i lastev is %i \n",firstev,lastev);
2745      //      //
2746    } else {      if ( IsDebug() ) printf("The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
2747      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());
2748      if ( PEDANTIC ) throw -69;      //
2749      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  
2750      //      //
2751      oss.str("");      oss.str("");
2752      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 "
2753          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
2754          << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "          << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
2755          << " ID != " << glrun->ID          << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
2756          << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!          << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
2757            << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2758            << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
2759            << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
2760            << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2761            << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
2762            << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
2763            << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2764            << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
2765            << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
2766      //      //
2767      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());
2768      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
2769      //      //
2770      if ( !result ) throw -4;      if ( !result ) throw -4;
2771      //      //
2772      row = result->Next();      row = result->Next();
2773      //      //
2774      if ( !row && NoFrag() ){      if ( !row ){
2775          //
2776          // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
2777          //
2778          if ( IsDebug() ) printf(" The run is new \n");
2779          if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
2780          //
2781          glrun->SetID(this->AssignRunID());
2782          glrun->SetID_RUN_FRAG(0);
2783          glrun->Fill_GL_RUN_FRAGMENTS(conn);
2784          //
2785        } else {
2786          if ( IsDebug() ) printf(" The run is already present in the fragment table, relaxed %u \n",RELAXED);
2787          if ( !RELAXED ){
2788            if ( PEDANTIC ) throw -69;
2789            return;
2790          } else {
2791            glrun->SetID((UInt_t)atoll(row->GetField(0)));
2792            glrun->SetID_RUN_FRAG(0);
2793          };
2794        };
2795        //
2796        if ( chewbacca && mishead && mistrail ) goto justcheck;
2797        //
2798        // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
2799        //    
2800        if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
2801          // missing it no way we can found a piece in the frag table
2802        //        //
2803        oss.str("");        oss.str("");
2804        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 "
2805            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2806            << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "            << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2807            << " ID != " << glrun->ID            << " ID != " << glrun->ID
2808            << " 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!!
2809        //        //
2810        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());
2811        result = conn->Query(oss.str().c_str());        result = conn->Query(oss.str().c_str());
2812        //        //
2813        if ( !result ) throw -4;        if ( !result ) throw -4;
2814        //        //
       foundinrun = true;  
       //  
2815        row = result->Next();        row = result->Next();
2816        //        //
2817      };        if ( !row && NoFrag() ){
2818      //          //
2819      if ( !row ){          oss.str("");
2820        if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");          oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
2821        found = false;              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2822      } else {              << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2823        //              << " ID != " << glrun->ID
2824        found = false; // default value              << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
2825        //          //
2826        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());
2827        //          result = conn->Query(oss.str().c_str());
2828        // if we have both runheader and runtrailer we can check with pkt_counter:          //
2829            if ( !result ) throw -4;
2830            //
2831            foundinrun = true;
2832            //
2833            row = result->Next();
2834            //
2835          };
2836        //        //
2837        if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){        if ( !row ){
2838          ULong64_t chkpkt = 0;            if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2839          ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());          found = false;
2840          ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));        } else {
2841            //
2842            found = false; // default value
2843            //
2844            if ( IsDebug() ) printf(" A Found a possible candidate, checking if it is the good one... \n");
2845          //          //
2846          chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;            // if we have both runheader and runtrailer we can check with pkt_counter:
2847          //          //
2848          if ( labs(chkpkt-pktt)<2 ){          if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){
2849              ULong64_t chkpkt = 0;  
2850              ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
2851              ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
2852            //            //
2853            if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);            chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;  
2854            //            //
2855            found = true;            if ( labs(chkpkt-pktt)<2 ){
2856                //
2857                if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
2858                //
2859                found = true;
2860                if ( IsDebug() ) printf(" where firstev is %i lastev is %i \n",firstev,lastev);
2861                //
2862              } else {
2863                //
2864                if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);            
2865                //
2866                found = false;
2867                //
2868              };
2869            };
2870            if ( !found && chewbacca ) goto justcheck;
2871            if ( !found ){
2872            //            //
2873          } 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
2874            //            //
2875            if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);                  ULong64_t chkpkt1 = 0;
2876              ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
2877              ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
2878              chkpkt1 = labs(orunh1-dbrunt1);
2879            //            //
2880            found = false;            ULong64_t chkpkt2 = 0;
2881              ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());
2882              ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
2883              chkpkt2 = labs(orunh2-dbrunt2);
2884            //            //
2885              ULong64_t chkpkt3 = 0;
2886              ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());
2887              ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
2888              chkpkt3 = labs(orunh3-dbrunt3);
2889              //
2890              if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
2891                //  if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){
2892                //
2893                if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
2894                //
2895                found = true;
2896                //
2897              } else {
2898                //
2899                if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
2900                //
2901                found = false;
2902                //
2903              };
2904          };          };
2905        };        };
2906        if ( !found && chewbacca ) goto justcheck;        //
2907        if ( !found ){        if ( found ){
2908            //
2909            // 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
2910            //
2911            if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
2912          //          //
2913          // 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 ){
2914              glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2915              glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2916            };
2917          //          //
2918          ULong64_t chkpkt1 = 0;          GL_RUN *glrun1 = new GL_RUN();
         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);  
2919          //          //
2920          if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){          //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
2921            //    if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){          //
2922            //          oss.str("");
2923            if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);          oss << " ID="<<row->GetField(0)<<";";
2924            //          //
2925            found = true;          glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos
2926            //          if ( IsDebug() ) printf(" there firstev is %i lastev is %i \n",firstev,lastev);
2927          } else {          //
2928            // merge infos
2929            //
2930            UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());
2931            ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
2932            UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
2933            ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
2934            if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2935            TTree *T= 0;
2936            T = (TTree*)file->Get("Physics");
2937            if ( !T || T->IsZombie() ) throw -16;
2938            EventHeader *eh = 0;
2939            PscuHeader *ph = 0;
2940            T->SetBranchAddress("Header", &eh);
2941            while ( apkt > bpkt && aobt > bobt && firstev < lastev ){
2942              T->GetEntry(firstev);
2943              ph = eh->GetPscuHeader();
2944              bpkt = PKT(ph->GetCounter());
2945              bobt = OBT(ph->GetOrbitalTime());    
2946              firstev++;
2947              if ( PEDANTIC ) throw -71;
2948            };
2949            if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2950            //
2951            glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
2952            glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
2953            glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
2954            glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());
2955            glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());
2956            //
2957            if ( IsDebug() ) printf(" here firstev is %i lastev is %i \n",firstev,lastev);
2958            //
2959            glrun->SetEV_FROM(firstev);
2960            glrun->SetNEVENTS(lastev-firstev+1);
2961            //
2962            glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
2963            glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
2964            glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
2965            glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());
2966            glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());
2967            glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());
2968            glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());
2969            glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());
2970            glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());
2971            glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());
2972            glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());  
2973            glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());  
2974            glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());  
2975            glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());  
2976            glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());  
2977            glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());  
2978            //
2979            if ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
2980            if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
2981            //
2982            if ( !IsRunAlreadyInserted() ){
2983              //
2984              //    glrun->SetID(this->AssignRunID());
2985              glrun->SetID_RUN_FRAG(glrun1->GetID());
2986              glrun->Fill_GL_RUN(conn);
2987            //            //
2988            if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);            // set id number
2989            //            //
2990            found = false;            glrun1->SetID_RUN_FRAG(glrun->GetID());
2991              glrun1->Fill_GL_RUN(conn);
2992            //            //
2993          };          };
2994        };          // delete old entry in fragment table
2995      };          //
2996      //          glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2997      if ( found ){          glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
       //  
       // 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() ){  
2998          //          //
2999          //      glrun->SetID(this->AssignRunID());          delete glrun1;
         glrun->SetID_RUN_FRAG(glrun1->GetID());  
         glrun->Fill_GL_RUN(conn);  
3000          //          //
         // set id number  
3001          //          //
3002          glrun1->SetID_RUN_FRAG(glrun->GetID());          return;
         glrun1->Fill_GL_RUN(conn);  
3003          //          //
3004        };        };
       // delete old entry in fragment table  
       //  
       glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       //  
       delete glrun1;  
       //  
       //  
       return;  
3005        //        //
3006      };      };
3007      //      //
3008    };      if ( mistrail && ( rtlastev == lastev || chewbacca )) { // look for runtrailer (only when at the end of the file, if at the beginning and the runh is
3009    //        // 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() ){  
3010        //        //
3011        oss.str("");        oss.str("");
3012        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 "
3013            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3014            << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "            << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
3015            << " ID != " << glrun->ID            << " ID != " << glrun->ID
3016            << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";            << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
3017        //        //
3018        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());
3019        result = conn->Query(oss.str().c_str());        result = conn->Query(oss.str().c_str());
3020        //        //
3021        if ( !result ) throw -4;        if ( !result ) throw -4;
3022        //        //
       foundinrun = true;  
3023        row = result->Next();        row = result->Next();
3024        //        //
3025      };        if ( !row && NoFrag() ){
3026      //          //
3027      if ( !row ){          oss.str("");
3028        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 "
3029        found = false;              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3030      } else {              << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
3031        //              << " ID != " << glrun->ID
3032        found = false; // default value              << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
3033        //          //
3034        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());
3035        //          result = conn->Query(oss.str().c_str());
3036        // if we have both runheader and runtrailer we can check with pkt_counter:          //
3037            if ( !result ) throw -4;
3038            //
3039            foundinrun = true;
3040            row = result->Next();
3041            //
3042          };
3043        //        //
3044        if ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){        if ( !row ){
3045          ULong64_t chkpkt = 0;            if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
3046          ULong64_t pktt = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));          found = false;
3047          ULong64_t pkth = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());        } else {
3048            //
3049            found = false; // default value
3050          //          //
3051          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");
3052          //          //
3053          if ( labs(chkpkt-pktt)<2 ){          // if we have both runheader and runtrailer we can check with pkt_counter:
3054            //
3055            if ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){
3056              ULong64_t chkpkt = 0;  
3057              ULong64_t pktt = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
3058              ULong64_t pkth = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
3059            //            //
3060            if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);            chkpkt = pkth + (ULong64_t)((UInt_t)atoll(row->GetField(1))) + 1ULL + 1ULL;  
3061            //            //
3062            found = true;            if ( labs(chkpkt-pktt)<2 ){
3063                //
3064                if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
3065                //
3066                found = true;
3067                //
3068              } else {
3069                //
3070                if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);            
3071                //
3072                found = false;
3073                //
3074              };
3075            };
3076            if ( !found && chewbacca ) goto justcheck;
3077            if ( !found ){
3078            //            //
3079          } 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
3080            //            //
3081            if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);                  ULong64_t chkpkt1 = 0;
3082              ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
3083              ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
3084              chkpkt1 = labs(orunh1-dbrunt1);
3085            //            //
3086            found = false;            ULong64_t chkpkt2 = 0;
3087              ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNTRAILER_OBT());
3088              ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
3089              chkpkt2 = labs(orunh2-dbrunt2);
3090              //
3091              ULong64_t chkpkt3 = 0;
3092              ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNTRAILER_TIME());
3093              ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
3094              chkpkt3 = labs(orunh3-dbrunt3);
3095            //            //
3096              if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
3097                //
3098                if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
3099                //
3100                found = true;
3101                //
3102              } else {
3103                //
3104                if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
3105                //
3106                found = false;
3107                //
3108              };
3109          };          };
3110        };        };
3111        if ( !found && chewbacca ) goto justcheck;        //
3112        if ( !found ){        if ( found ){
3113            //
3114            // 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
3115            //
3116            if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
3117          //          //
3118          // 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 ){
3119              glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3120              glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
3121            };
3122          //          //
3123          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);  
3124          //          //
3125          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);  
3126          //          //
3127          ULong64_t chkpkt3 = 0;          oss.str("");
3128          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);  
3129          //          //
3130          if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){          glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runtrailer infos
3131            //          //
3132            if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);          // merge infos
3133            //          //
3134            found = true;          UInt_t apkt = PKT(glrun->GetRUNTRAILER_PKT());
3135            //          ULong64_t aobt = OBT(glrun->GetRUNTRAILER_OBT());
3136          } else {          UInt_t bpkt = PKT(glrun1->GetRUNHEADER_PKT());
3137            ULong64_t bobt = OBT(glrun1->GetRUNHEADER_OBT());
3138            if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
3139            TTree *T= 0;
3140            T = (TTree*)file->Get("Physics");
3141            if ( !T || T->IsZombie() ) throw -16;
3142            EventHeader *eh = 0;
3143            PscuHeader *ph = 0;
3144            T->SetBranchAddress("Header", &eh);
3145            while ( apkt > bpkt && aobt > bobt && lastev > 0 ){
3146              T->GetEntry(lastev);
3147              ph = eh->GetPscuHeader();
3148              apkt = PKT(ph->GetCounter());
3149              aobt = OBT(ph->GetOrbitalTime());    
3150              lastev--;
3151              if ( PEDANTIC && !RELAXED) throw -72;
3152            };
3153            if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
3154            //
3155            glrun->SetEV_TO(lastev);
3156            glrun->SetNEVENTS(lastev-firstev+1);
3157            glrun->SetPKT_COUNTER(glrun1->GetPKT_COUNTER());
3158            glrun->SetPKT_READY_COUNTER(glrun1->GetPKT_READY_COUNTER());
3159            glrun->SetRUNTRAILER_TIME(glrun1->GetRUNTRAILER_TIME());
3160            glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());
3161            glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());
3162            //
3163            glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());
3164            glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());
3165            glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());
3166            glrun1->SetCOMPILATIONTIMESTAMP(glrun->GetCOMPILATIONTIMESTAMP());
3167            glrun1->SetFAV_WRK_SCHEDULE(glrun->GetFAV_WRK_SCHEDULE());
3168            glrun1->SetEFF_WRK_SCHEDULE(glrun->GetEFF_WRK_SCHEDULE());
3169            glrun1->SetPRH_VAR_TRG_MODE_A(glrun->GetPRH_VAR_TRG_MODE_A());
3170            glrun1->SetPRH_VAR_TRG_MODE_B(glrun->GetPRH_VAR_TRG_MODE_B());
3171            glrun1->SetACQ_BUILD_INFO(glrun->GetACQ_BUILD_INFO());
3172            glrun1->SetACQ_VAR_INFO(glrun->GetACQ_VAR_INFO());
3173            glrun1->SetRM_ACQ_AFTER_CALIB(glrun->GetRM_ACQ_AFTER_CALIB());  
3174            glrun1->SetRM_ACQ_SETTING_MODE(glrun->GetRM_ACQ_SETTING_MODE());  
3175            glrun1->SetTRK_CALIB_USED(glrun->GetTRK_CALIB_USED());  
3176            glrun1->SetCAL_DSP_MASK(glrun->GetCAL_DSP_MASK());  
3177            glrun1->SetLAST_TIMESYNC(glrun->GetLAST_TIMESYNC());  
3178            glrun1->SetOBT_TIMESYNC(glrun->GetOBT_TIMESYNC());  
3179            //
3180            if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ) glrun1->SetPHYSENDRUN_MASK_S3S2S12(glrun->GetPHYSENDRUN_MASK_S3S2S12());
3181            if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) glrun1->SetPHYSENDRUN_MASK_S11CRC(glrun->GetPHYSENDRUN_MASK_S11CRC());
3182            //
3183            if ( !IsRunAlreadyInserted() ){
3184              //
3185              //    glrun->SetID(this->AssignRunID());
3186              //
3187              glrun->SetID_RUN_FRAG(glrun1->GetID());
3188              glrun->Fill_GL_RUN(conn);
3189            //            //
3190            if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);            // set id number
3191            //            //
3192            found = false;            glrun1->SetID_RUN_FRAG(glrun->GetID());
3193              glrun1->Fill_GL_RUN(conn);
3194            //            //
3195          };          };
3196            //
3197            // delete old entries in fragment table
3198            //
3199            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3200            glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3201            //
3202            delete glrun1;
3203            //
3204            return;
3205            //
3206        };        };
3207          //
3208      };      };
3209      //      //
3210      if ( found ){    justcheck:
3211        //      //
3212        // 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");  
       };  
3213        //        //
3214        GL_RUN *glrun1 = new GL_RUN();        if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");
3215        //        //
3216        //      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?
3217        //        //
3218        oss.str("");        oss.str("");
3219        oss << " ID="<<row->GetField(0)<<";";        oss << " SELECT ID,ID_ROOT_L0 FROM GL_RUN WHERE "
3220              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3221              << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3222              << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3223              << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3224              << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3225              << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3226              << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3227              << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3228              << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3229              << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3230              << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3231              << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3232              << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3233        //        //
3234        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());
3235          result = conn->Query(oss.str().c_str());
3236        //        //
3237        // merge infos        if ( !result ) throw -4;
3238        //        //
3239        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());    
3240        //        //
3241        if ( !IsRunAlreadyInserted() ){        if ( row ){
         //  
         //      glrun->SetID(this->AssignRunID());  
3242          //          //
3243          glrun->SetID_RUN_FRAG(glrun1->GetID());          // we end up here if chewbacca and we have RH---| small gap |---RT, in this case the two pieces are attached and moved to GL_RUN. We are now processing the
3244          glrun->Fill_GL_RUN(conn);          // "small gap" piece... we recognize this since: we have two entries from this query, the pkt number is consistent with our pkt number.
3245          //          //
3246          // set id number          // 090112 [8RED (-70): RUN ALREADY INSERTED]
3247            // 093012 [8RED (-70): RUN ALREADY INSERTED] try to be more general... the run has not been instered yet if the runheader-trailer PKT interval is not covered by already inserted runs, NOTICE: we must look in the GL_RUN_TRASH table!
3248          //          //
3249          glrun1->SetID_RUN_FRAG(glrun->GetID());          Bool_t OK = false;
3250          glrun1->Fill_GL_RUN(conn);          UInt_t IDRL2A = 0;
3251            UInt_t IDRL2B = 0;
3252            if ( chewbacca ){
3253              if ( result->GetRowCount() >= 2 ){
3254                //
3255                if ( IsDebug() ) printf(" RH---| gap |---RT case, number of pieces in the GL_RUN table: %i \n",result->GetRowCount());
3256                OK = true;
3257                IDRL2A = (UInt_t)atoll(row->GetField(0));
3258                //
3259                while ( row ){
3260                  //
3261                  TSQLResult *trresult = 0;
3262                  TSQLRow    *trrow    = 0;
3263                  //
3264                  stringstream tross;
3265                  tross.str("");
3266                  //
3267                  tross << " SELECT RUNHEADER_PKT, RUNTRAILER_PKT FROM GL_RUN_TRASH where ID=" << row->GetField(0) << ";";
3268                  if ( IsDebug() ) printf(" check in the gl_run_trash table for pkt intervals: query is \n %s \n",tross.str().c_str());
3269                  trresult = conn->Query(tross.str().c_str());
3270                  if ( !trresult ) throw -4;
3271                  trrow = trresult->Next();
3272                  if ( !trrow || trresult->GetRowCount() != 1 ){
3273                    OK = false;
3274                    if ( IsDebug() ) printf(" OPS! no such run (or multiple runs!) in GL_RUN_TRASH table, something wrong is going on! \n");
3275                    break;
3276                  };
3277                  //
3278                  UInt_t pktH =  (UInt_t)atoll(row->GetField(0));
3279                  UInt_t pktT =  (UInt_t)atoll(row->GetField(1));
3280                  delete trresult;
3281                  if (
3282                      (PKT(pktH) >= PKT(glrun->GetRUNHEADER_PKT()) && PKT(pktH) <= PKT(glrun->GetRUNTRAILER_PKT())) ||
3283                      (PKT(pktT) >= PKT(glrun->GetRUNHEADER_PKT()) && PKT(pktT) <= PKT(glrun->GetRUNTRAILER_PKT())) ||
3284                      (PKT(pktH) <= PKT(glrun->GetRUNTRAILER_PKT()) && PKT(pktT) >= PKT(glrun->GetRUNTRAILER_PKT())) ){            
3285                    OK = false;
3286                    if ( IsDebug() ) printf(" The run is overlapping with already inserted ones!! \n");
3287                    break;          
3288                  };
3289                  //PKT(glrun->GetRUNHEADER_PKT())  PKT(glrun->GetRUNTRAILER_PKT())
3290                  row = result->Next();
3291                };
3292                
3293                //    if ( result->GetRowCount() == 2 ) {
3294                //      IDRL2A = (UInt_t)atoll(row->GetField(0));
3295                //      UInt_t IDRL0A = (UInt_t)atoll(row->GetField(1));
3296                //      row = result->Next();
3297                //      IDRL2B = (UInt_t)atoll(row->GetField(0));
3298                //      UInt_t IDRL0B = (UInt_t)atoll(row->GetField(1));
3299                //      if ( IsDebug() ) printf(" IDRL0A %u B %u IDRL2A %u B %u \n",IDRL0A,IDRL0B,IDRL2A,IDRL2B);
3300                //      //      if ( IDRL0A == IDRL0B ){ //091230 why this condition???? RH could be in a file and RT in another one...
3301                //      if ( true ){
3302                //        TSQLResult *result2 = 0;
3303                //        TSQLRow    *row2    = 0;
3304                //        oss.str("");
3305                //        oss << "select PKT_NUMBER_FINAL from ROOT_TABLE_MERGING where REAL_TIME_INIT<" << chrtinit << " order by REAL_TIME_INIT desc limit 1;";
3306                //        if ( IsDebug() ) printf(" Check if we are in the case RH---| small gap |---RT: query is \n %s \n",oss.str().c_str());
3307                //        result2 = conn->Query(oss.str().c_str());
3308                //        //
3309                //        if ( !result2 ) throw -4;
3310                //        //
3311                //        row2 = result2->Next();
3312                //        //
3313                //        if ( row2 ){
3314                //          UInt_t PKA = (UInt_t)atoll(row2->GetField(0));
3315                //          delete result2;
3316                //          oss.str("");
3317                //          oss << "select PKT_NUMBER_INIT from ROOT_TABLE_MERGING where REAL_TIME_INIT>" << chrtinit << " order by REAL_TIME_INIT asc limit 1;";
3318                //          if ( IsDebug() ) printf(" Check if we are in the case RH---| small gap |---RT: query is \n %s \n",oss.str().c_str());
3319                //          result2 = conn->Query(oss.str().c_str());
3320                //          //
3321                //          if ( !result2 ) throw -4;
3322                //          //
3323                //          row2 = result2->Next();
3324                //          //
3325                //          if ( row2 ){
3326                //            UInt_t PKB = (UInt_t)atoll(row2->GetField(0));
3327                //            //
3328                //            if ( IsDebug() ) printf(" PKT(PKA) + 1 %llu == runheaderpkt %llu && PKB = runtrailer %llu + 1 %llu \n",PKT(PKA)+1LL, PKT(glrun->GetRUNHEADER_PKT()),PKT(PKB), PKT(glrun->GetRUNTRAILER_PKT())+1LL);
3329                //            if ( PKT(PKA)+1LL == PKT(glrun->GetRUNHEADER_PKT()) && PKT(PKB) == PKT(glrun->GetRUNTRAILER_PKT())+1LL ){
3330                //              if ( IsDebug() ) printf(" Ok, we are in the case: RH---| small gap |---RT \n");
3331                //              OK = true;
3332                //            };
3333                //          };
3334                //        };                  
3335                //      };
3336                //    };      
3337              };
3338            };
3339            if ( OK ){
3340              //
3341              // this is the case in which we must insert a piece of run between two fragments in the GL_RUN table // we arrive here ONLY with internal pieces of runs, never runheader or runtrailer by definition  
3342              //
3343              // we have to update with runheader/trailer infos our run and we have to change the ROOT_ID_FRAG of the header piece ( 1/2 2/1 must become 1/3 3/2 2/1 )
3344              //
3345              if ( IsDebug() ) printf(" Ok, we are in the case: RH---| small gap |---RT \n");
3346              //
3347              GL_RUN *glA = new GL_RUN();
3348              glA->Query_GL_RUN(IDRL2A,conn);
3349              //
3350              glrun->SetRUNHEADER_TIME(glA->GetRUNHEADER_TIME());
3351              glrun->SetRUNHEADER_OBT(glA->GetRUNHEADER_OBT());
3352              glrun->SetRUNHEADER_PKT(glA->GetRUNHEADER_PKT());
3353              //
3354              glrun->SetRUNTRAILER_TIME(glA->GetRUNTRAILER_TIME());
3355              glrun->SetRUNTRAILER_OBT(glA->GetRUNTRAILER_OBT());
3356              glrun->SetRUNTRAILER_PKT(glA->GetRUNTRAILER_PKT());
3357              //
3358              if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glA->GetPHYSENDRUN_MASK_S3S2S12());
3359              if ( glA->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glA->GetPHYSENDRUN_MASK_S11CRC());
3360              //          
3361              if ( glA->GetACQ_BUILD_INFO() != 0 ){
3362                //
3363                // the first piece contains a good runheader we can update all the other runs with correct infos!
3364                //
3365                glrun->SetCOMPILATIONTIMESTAMP(glA->GetCOMPILATIONTIMESTAMP());
3366                glrun->SetFAV_WRK_SCHEDULE(glA->GetFAV_WRK_SCHEDULE());
3367                glrun->SetEFF_WRK_SCHEDULE(glA->GetEFF_WRK_SCHEDULE());
3368                glrun->SetPRH_VAR_TRG_MODE_A(glA->GetPRH_VAR_TRG_MODE_A());
3369                glrun->SetPRH_VAR_TRG_MODE_B(glA->GetPRH_VAR_TRG_MODE_B());
3370                glrun->SetACQ_BUILD_INFO(glA->GetACQ_BUILD_INFO());
3371                glrun->SetACQ_VAR_INFO(glA->GetACQ_VAR_INFO());
3372                glrun->SetRM_ACQ_AFTER_CALIB(glA->GetRM_ACQ_AFTER_CALIB());
3373                glrun->SetRM_ACQ_SETTING_MODE(glA->GetRM_ACQ_SETTING_MODE());
3374                glrun->SetTRK_CALIB_USED(glA->GetTRK_CALIB_USED());
3375                glrun->SetCAL_DSP_MASK(glA->GetCAL_DSP_MASK());
3376                glrun->SetLAST_TIMESYNC(glA->GetLAST_TIMESYNC());
3377                glrun->SetOBT_TIMESYNC(glA->GetOBT_TIMESYNC());
3378                //
3379              };
3380              //
3381              if ( glA->GetPKT_READY_COUNTER() != 0 ){
3382                //
3383                // the first piece contains a good runtrailer we can update all the other runs with correct infos!
3384                //
3385                glrun->SetPKT_COUNTER(glA->GetPKT_COUNTER());
3386                glrun->SetPKT_READY_COUNTER(glA->GetPKT_READY_COUNTER());
3387              };
3388              //
3389              // update runheader ROOT_ID_FRAG
3390              //
3391              oss.str("");
3392              oss << "UPDATE GL_RUN SET ID_RUN_FRAG = " << glrun->GetID() << " where ID = " << IDRL2A << ";";
3393              if ( IsDebug() ) printf(" update gl_run to have cross indexing: %s\n",oss.str().c_str());
3394              conn->Query(oss.str().c_str());
3395              //
3396              oss.str("");
3397              oss << "SELECT ID FROM GL_RUN WHERE ID_RUN_FRAG = " << IDRL2A << ";";
3398              if ( IsDebug() ) printf(" update gl_run to have cross indexing: %s\n",oss.str().c_str());
3399              TSQLResult *tsresult = 0;
3400              TSQLRow    *tsrow    = 0;
3401              tsresult=conn->Query(oss.str().c_str());
3402              if ( !tsresult ) throw -4;
3403              tsrow = tsresult->Next();
3404              if ( !tsrow || tsresult->GetRowCount() != 1 ) throw -4;
3405              IDRL2B = (UInt_t)atoll(tsrow->GetField(0));
3406              glrun->SetID_RUN_FRAG(IDRL2B);
3407              //
3408              // fill the new run in GL_RUN
3409              //
3410              glrun->Fill_GL_RUN(conn);    
3411              //
3412              glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3413              delete glA;
3414              //
3415            } else {
3416    //        //
3417    //        // this is the case in which we must insert a piece of run between two fragments in the GL_RUN table
3418    //        //
3419    //        // we have to update with runheader/trailer infos our run and we have to change the ROOT_ID_FRAG of the header piece ( 1/2 2/1 must become 1/3 3/2 2/1 )
3420    //        //
3421    //        GL_RUN *glA = new GL_RUN();
3422    //        glA->Query_GL_RUN(IDRL2A,conn);
3423    //        //
3424    //        if ( glA->GetACQ_BUILD_INFO() != 0 ){
3425    //          //
3426    //          // the first piece contains a good runheader we can update all the other runs with correct infos!
3427    //          //
3428    //          oss.str("");
3429    //          oss << "UPDATE GL_RUN_FRAGMENTS SET "
3430    //              << " RUNHEADER_TIME=" << glA->GetRUNHEADER_TIME()<< " , "
3431    //              << " RUNHEADER_OBT=" << glA->GetRUNHEADER_OBT()<< " , "
3432    //              << " RUNHEADER_PKT=" << glA->GetRUNHEADER_PKT()<< " , "
3433    //              << " COMPILATIONTIMESTAMP=" << glA->GetCOMPILATIONTIMESTAMP()<< " , "
3434    //              << " FAV_WRK_SCHEDULE=" << glA->GetFAV_WRK_SCHEDULE()<< " , "
3435    //              << " EFF_WRK_SCHEDULE=" << glA->GetEFF_WRK_SCHEDULE()<< " , "
3436    //              << " PRH_VAR_TRG_MODE_A=" << glA->GetPRH_VAR_TRG_MODE_A()<< " , "
3437    //              << " PRH_VAR_TRG_MODE_B=" << glA->GetPRH_VAR_TRG_MODE_B()<< " , "
3438    //              << " ACQ_BUILD_INFO=" << glA->GetACQ_BUILD_INFO()<< " , "
3439    //              << " ACQ_VAR_INFO=" << glA->GetACQ_VAR_INFO()<< " , "
3440    //              << " RM_ACQ_AFTER_CALIB=" << glA->GetRM_ACQ_AFTER_CALIB()<< " , "  
3441    //              << " RM_ACQ_SETTING_MODE=" << glA->GetRM_ACQ_SETTING_MODE()<< " , "  
3442    //              << " TRK_CALIB_USED=" << glA->GetTRK_CALIB_USED()<< " , "  
3443    //              << " CAL_DSP_MASK=" << glA->GetCAL_DSP_MASK()<< " , "  
3444    //              << " LAST_TIMESYNC=" << glA->GetLAST_TIMESYNC()<< " , ";
3445    //          //
3446    //          if ( glA->GetPHYSENDRUN_MASK_S3S2S12() )
3447    //            oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12() << " , ";
3448    //          if ( glA->GetPHYSENDRUN_MASK_S11CRC() )
3449    //            oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC() << " , ";
3450    //          //        
3451    //          oss << " OBT_TIMESYNC=" << glA->GetOBT_TIMESYNC();
3452    //          oss << " WHERE ID=" << glrun->GetID() << ";";
3453    //          if ( IsDebug() ) printf(" update with correct infos: %s\n",oss.str().c_str());
3454    //          conn->Query(oss.str().c_str());    
3455    //          //
3456    //        } else {
3457    //          //
3458    //          // sig no runheader, let set anyway what is possible...
3459    //          //
3460    //          oss.str("");
3461    //          oss << "UPDATE GL_RUN_FRAGMENTS SET "
3462    //              << " RUNHEADER_TIME=" << glA->GetRUNHEADER_TIME()<< " , ";
3463    //          //
3464    //          if ( glA->GetPHYSENDRUN_MASK_S3S2S12() )
3465    //            oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , ";
3466    //          if ( glA->GetPHYSENDRUN_MASK_S11CRC() )
3467    //            oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , ";
3468    //          //        
3469    //          oss << " RUNHEADER_OBT=" << glA->GetRUNHEADER_OBT()<< " , "
3470    //              << " RUNHEADER_PKT=" << glA->GetRUNHEADER_PKT();
3471    //          oss << " WHERE ID=" << glrun->GetID() << ";";
3472    //          if ( IsDebug() ) printf(" update with correct infos2: %s\n",oss.str().c_str());
3473    //          conn->Query(oss.str().c_str());    
3474    //        };
3475    //        //
3476    //        // update runheader ROOT_ID_FRAG
3477    //        //
3478    //        oss.str("");
3479    //        oss << "UPDATE GL_RUN SET ID_RUN_FRAG = " << glrun->GetID() << " where ID = " << IDRL2A << ";";
3480    //        if ( IsDebug() ) printf(" update gl_run to have cross indexing: %s\n",oss.str().c_str());
3481    //        conn->Query(oss.str().c_str());
3482    //        //
3483    //        // now let's look for runtrailer if any in the last run
3484    //        //
3485    //        glA->Query_GL_RUN(IDRL2B,conn);
3486    //        //
3487    //        if ( glA->GetPKT_READY_COUNTER() != 0 ){
3488    //          //
3489    //          // the first piece contains a good runtrailer we can update all the other runs with correct infos!
3490    //          //
3491    //          oss.str("");
3492    //          oss << "UPDATE GL_RUN_FRAGMENTS SET "
3493    //              << " RUNTRAILER_TIME=" << glA->GetRUNTRAILER_TIME()<< " , "
3494    //              << " RUNTRAILER_OBT=" << glA->GetRUNTRAILER_OBT()<< " , "
3495    //              << " RUNTRAILER_PKT=" << glA->GetRUNTRAILER_PKT()<< " , "
3496    //              << " PKT_COUNTER=" << glA->GetPKT_COUNTER()<< " , ";
3497    //          //
3498    //          if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ){
3499    //            oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
3500    //          if ( glA->GetPHYSENDRUN_MASK_S11CRC() ) {
3501    //            oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
3502    //          //        
3503    //          oss << " PKT_READY_COUNTER=" << glA->GetPKT_READY_COUNTER()
3504    //              << " WHERE ID=" << glrun->GetID() << ";";
3505    //          if ( IsDebug() ) printf(" update with correct trailer infos: %s\n",oss.str().c_str());
3506    //          conn->Query(oss.str().c_str());    
3507    //          //
3508    //        } else {
3509    //          //
3510    //          // sig no runtrailer, let set anyway what is possible...
3511    //          //
3512    //          oss.str("");
3513    //          oss << "UPDATE GL_RUN_FRAGMENTS SET "
3514    //              << " RUNTRAILER_TIME=" << glA->GetRUNTRAILER_TIME()<< " , "
3515    //              << " RUNTRAILER_OBT=" << glA->GetRUNTRAILER_OBT()<< " , ";
3516    //            //
3517    //          if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ){
3518    //            oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
3519    //          if ( glA->GetPHYSENDRUN_MASK_S11CRC() ){
3520    //            oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
3521    //          //        
3522    //          oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()
3523    //              << " WHERE ID=" << glrun->GetID() << ";";
3524    //          if ( IsDebug() ) printf(" update with correct trailer infos2: %s\n",oss.str().c_str());
3525    //          conn->Query(oss.str().c_str());    
3526    //        };
3527    //        //
3528    //        UInt_t myi = glrun->GetID();
3529    //        oss.str("");
3530    //        oss << " ID= "<< myi;
3531    //        //
3532    //        glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);  
3533    //        //
3534    //        // fill the new run in GL_RUN
3535    //        //
3536    //        glrun->SetID_RUN_FRAG(IDRL2B);
3537    //        glrun->Fill_GL_RUN(conn);    
3538    //        glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3539    //        delete glA;
3540    //        //
3541    //      } else {
3542              //
3543              // is just a repetition
3544              //
3545              if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");        
3546              if ( PEDANTIC ) throw -70;
3547            };
3548          //          //
3549          } else {
3550            if ( NoFrag() ){
3551              glrun->SetID_RUN_FRAG(glrun->GetID());
3552              glrun->Fill_GL_RUN(conn);    
3553              glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3554            };    
3555        };        };
       //  
       // delete old entries in fragment table  
       //  
       glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       //  
       delete glrun1;  
       //  
       return;  
       //  
3556      };      };
3557      //    }; // EEE
   };  
3558    //    //
3559   justcheck:    return;
3560    };
3561    
3562    
3563    /**
3564     * Handle run without header or trailer
3565     **/
3566    void PamelaDBOperations::HandleMissingHoT(Bool_t mishead, Bool_t mistrail, UInt_t firstev, UInt_t lastev){  
3567    //    //
3568    if ( !found ){          //
3569      // is the piece of run good (no other packets inside)?
3570      //
3571      if ( !this->IsRunConsistent(mishead,mistrail,firstev,lastev)){
3572        //
3573        // if not, handle other pieces and continue with the first one
3574      //      //
3575      if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");      if ( IsDebug() ) printf("The run is not consistent, it contains non-physics packets! The run has been handled \n");
3576      //      //
3577      // not found, has this run already inserted in the GL_RUN or in the GL_RUN_FRAGMENTS table?    } else {
     //  
     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  
   //  
   return;  
 };  
   
   
 /**  
  * Handle run without header or trailer  
  **/  
 void PamelaDBOperations::HandleMissingHoT(Bool_t mishead, Bool_t mistrail, UInt_t firstev, UInt_t lastev){    
   //  
   //  
   // is the piece of run good (no other packets inside)?  
   //  
   if ( !this->IsRunConsistent(mishead,mistrail,firstev,lastev)){  
     //  
     // if not, handle other pieces and continue with the first one  
     //  
     if ( IsDebug() ) printf("The run is not consistent, it contains non-physics packets! The run has been handled \n");  
     //  
   } else {  
3578      //      //
3579      this->FillClass(mishead,mistrail,firstev,lastev);      this->FillClass(mishead,mistrail,firstev,lastev);
3580      //      //
# Line 3015  void PamelaDBOperations::HandleMissingHo Line 3582  void PamelaDBOperations::HandleMissingHo
3582        glrun->SetID(this->AssignRunID());        glrun->SetID(this->AssignRunID());
3583        glrun->SetID_RUN_FRAG(0);        glrun->SetID_RUN_FRAG(0);
3584        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...
3585      };        };
3586      //      //
3587    };    };
3588    //    //
# Line 3031  Bool_t PamelaDBOperations::IsRunConsiste Line 3598  Bool_t PamelaDBOperations::IsRunConsiste
3598    //      //  
3599    EventCounter *code=0;    EventCounter *code=0;
3600    //    //
3601    UInt_t nevent = 0;    //  UInt_t nevent = 0;
3602    UInt_t checkfirst = 0;    UInt_t checkfirst = 0;
3603    UInt_t checklast = 0;    UInt_t checklast = 0;
3604    UInt_t firstentry = 0;    UInt_t firstentry = 0;
# Line 3053  Bool_t PamelaDBOperations::IsRunConsiste Line 3620  Bool_t PamelaDBOperations::IsRunConsiste
3620    EventHeader *eh = 0;    EventHeader *eh = 0;
3621    PscuHeader *ph = 0;    PscuHeader *ph = 0;
3622    T->SetBranchAddress("Header", &eh);    T->SetBranchAddress("Header", &eh);
3623    nevent = T->GetEntries();    //  nevent = T->GetEntries();
3624    //    //
3625    //    //
3626    if ( firstev == lastev+1 || lastev == firstev ) { // no events inside the run!    if ( firstev == lastev+1 || lastev == firstev ) { // no events inside the run!
3627      //if ( firstev <= lastev+1 ) { // no events inside the run!      //if ( firstev <= lastev+1 ) { // no events inside the run!
3628      if ( IsDebug() ) printf(" Checking but no events in the run! \n");      if ( IsDebug() ) printf(" Checking but no events in the run! \n");
3629        firstev = lastev+1; // this is necessary for files with no Physics entries, should have no influence on other files
3630      // return true is correct      // return true is correct
3631      return(true);      return(true);
3632      //      //
# Line 3068  Bool_t PamelaDBOperations::IsRunConsiste Line 3636  Bool_t PamelaDBOperations::IsRunConsiste
3636      code = eh->GetCounter();      code = eh->GetCounter();
3637      checkfirst = 0;      checkfirst = 0;
3638      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3639         if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
3640       };      };
3641      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);
3642      //      //
3643      T->GetEntry(lastev);      T->GetEntry(lastev);
3644      code = eh->GetCounter();      code = eh->GetCounter();
3645      checklast = 0;      checklast = 0;
3646      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3647         if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
3648       };      };
3649      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);
3650      //      //
3651      if ( checkfirst == checklast ){      if ( checkfirst == checklast ){
# Line 3088  Bool_t PamelaDBOperations::IsRunConsiste Line 3656  Bool_t PamelaDBOperations::IsRunConsiste
3656        //        //
3657      } else {      } else {
3658        //        //
3659        if ( IsDebug() ) printf(" There are no-phyics packets inside the run!\n");        if ( IsDebug() ) printf(" There are no-physics packets inside the run!\n");
3660        //        //
3661        // HERE WE MUST HANDLE THAT RUNS AND GO BACK        // HERE WE MUST HANDLE THAT RUNS AND GO BACK
3662        //        //
3663  //      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");
3664        //        //
3665        Bool_t emptyruns = false;        Bool_t emptyruns = false;
3666        UInt_t check = 0;        UInt_t check = 0;
3667        UInt_t lastevtemp = lastev;        UInt_t lastevtemp = lastev;
3668        UInt_t firstevno = firstev;        UInt_t firstevno = firstev;
3669          UInt_t rhchko=0;
3670          UInt_t rhchk=0;
3671        //        //
3672        for (UInt_t i=firstev; i<=lastev; i++){        for (UInt_t i=firstev; i<=lastev; i++){
3673          //          //
# Line 3106  Bool_t PamelaDBOperations::IsRunConsiste Line 3676  Bool_t PamelaDBOperations::IsRunConsiste
3676          //          //
3677          check = 0;          check = 0;
3678          //          //
3679    
3680            // if we have a runheader set lastev then exit
3681            //
3682          for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){          for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3683            if ( strcmp(*Iter,"Physics") ) check += code->Get(GetPacketType(*Iter));            if ( strcmp(*Iter,"Physics") ) check += code->Get(GetPacketType(*Iter));
3684          };          };
3685            // check here if we have a runheader
3686            rhchko = rhchk;  
3687            rhchk = code->Get(GetPacketType("RunHeader"));    
3688          //          //
3689          if ( checkfirst < check || i == lastev ){          if ( checkfirst < check || i == lastev ){
3690            //            //
# Line 3184  Bool_t PamelaDBOperations::IsRunConsiste Line 3760  Bool_t PamelaDBOperations::IsRunConsiste
3760            };            };
3761            //                  //      
3762            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
3763              this->SetPhysEndRunVariables();
3764            //            //
3765            if ( chminentry == firstentry  ){ // EEE            if ( chminentry == firstentry  ){ // EEE
3766              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");
3767  //              //
3768  //          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
3769  //              //
   
   
   
   
   
   
   
   
   
   
   
   
   
   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  
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
3770    
3771                mishead = true;
3772    
3773    
3774                UInt_t rhfirstev = firstentry;
3775                //  UInt_t rtlastev = lastentry;
3776                Bool_t found = false;
3777                Bool_t foundinrun = false;
3778                //
3779                TSQLResult *result = 0;
3780                TSQLRow    *row    = 0;
3781                //
3782                stringstream oss;
3783                oss.str("");
3784                //
3785                // we have now the good first piece of a run, fill the glrun object
3786                //
3787                //  if ( rhfirstev != firstev && !mishead ) mishead = true;
3788                //  if ( rtlastev != lastev && !mistrail ) mistrail = true;
3789                //
3790                //  this->FillClass(mishead,mistrail,firstev,lastev);
3791                //
3792                if ( IsDebug() ) printf("zz The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
3793                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());
3794                //
3795                // First of all insert the run in the fragment table...
3796                //
3797                oss.str("");
3798                oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
3799                    << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3800                    << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3801                    << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3802                    << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3803                    << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3804                    << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3805                    << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3806                    << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3807                    << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3808                    << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3809                    << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3810                    << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3811                    << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3812                //
3813                if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3814                result = conn->Query(oss.str().c_str());
3815                //
3816                if ( !result ) throw -4;
3817                //
3818                row = result->Next();
3819                //
3820                if ( !row ){
3821                  //
3822                  // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
3823                  //
3824                  if ( IsDebug() ) printf(" The run is new \n");
3825                  if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
3826                  //
3827                  glrun->SetID(this->AssignRunID());
3828                  glrun->SetID_RUN_FRAG(0);
3829                  glrun->Fill_GL_RUN_FRAGMENTS(conn);
3830                  //
3831                } else {
3832                  if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
3833                  if ( PEDANTIC ) throw -69;
3834                  //    return;
3835                };
3836                //
3837                if ( chewbacca && mishead && mistrail ) goto zjustcheck;
3838                //
3839                // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
3840                //
3841                if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
3842                  // missing it no way we can found a piece in the frag table
3843                  //
3844                  oss.str("");
3845                  oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "
3846                      << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3847                      << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3848                      << " ID != " << glrun->ID
3849                      << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
3850                  //
3851                  if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());
3852                  result = conn->Query(oss.str().c_str());
3853                  //
3854                  if ( !result ) throw -4;
3855                  //
3856                  row = result->Next();
3857                  //
3858                  if ( !row && NoFrag() ){
3859                    //
3860                    oss.str("");
3861                    oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
3862                        << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3863                        << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3864                        << " ID != " << glrun->ID
3865                        << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
3866                    //
3867                    if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
3868                    result = conn->Query(oss.str().c_str());
3869                    //
3870                    if ( !result ) throw -4;
3871                    //
3872                    foundinrun = true;
3873                    //
3874                    row = result->Next();
3875                    //
3876                  };
3877                  //
3878                  if ( !row ){
3879                    if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
3880                    found = false;
3881                  } else {
3882                    //
3883                    found = false; // default value
3884                    //
3885                    if ( IsDebug() ) printf(" C Found a possible candidate, checking if it is the good one... \n");
3886                    //
3887                    // if we have both runheader and runtrailer we can check with pkt_counter:
3888                    //
3889                    if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){
3890                      ULong64_t chkpkt = 0;
3891                      ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
3892                      ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
3893                      //
3894                      chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;
3895                      //
3896                      if ( labs(chkpkt-pktt)<2 ){
3897                        //
3898                        if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
3899                        //
3900                        found = true;
3901                        //
3902                      } else {
3903                        //
3904                        if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);
3905                        //
3906                        found = false;
3907                        //
3908                      };
3909                    };
3910                    if ( !found && chewbacca ) goto zjustcheck;
3911                    if ( !found ){
3912                      //
3913                      // 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
3914                      //
3915                      ULong64_t chkpkt1 = 0;
3916                      ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
3917                      ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
3918                      chkpkt1 = labs(orunh1-dbrunt1);
3919                      //
3920                      ULong64_t chkpkt2 = 0;
3921                      ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());
3922                      ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
3923                      chkpkt2 = labs(orunh2-dbrunt2);
3924                      //
3925                      ULong64_t chkpkt3 = 0;
3926                      ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());
3927                      ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
3928                      chkpkt3 = labs(orunh3-dbrunt3);
3929                      //
3930                      if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
3931                        //    if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){
3932                        //
3933                        if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
3934                        //
3935                        found = true;
3936                        //
3937                      } else {
3938                        //
3939                        if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
3940                        //
3941                        found = false;
3942                        //
3943                      };
3944                    };
3945                  };
3946                  //
3947                  if ( found ){
3948                    //
3949                    // 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
3950                    //
3951                    if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
3952                    //
3953                    if ( foundinrun ){
3954                      glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3955                      glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
3956                    };
3957                    //
3958                    GL_RUN *glrun1 = new GL_RUN();
3959                    //
3960                    //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
3961                    //
3962                    oss.str("");
3963                    oss << " ID="<<row->GetField(0)<<";";
3964                    //
3965                    glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos
3966                    //
3967                    // merge infos
3968                    //
3969                    UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());
3970                    ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
3971                    UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
3972                    ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
3973                    if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
3974                    TTree *T= 0;
3975                    T = (TTree*)file->Get("Physics");
3976                    if ( !T || T->IsZombie() ) throw -16;
3977                    EventHeader *eh = 0;
3978                    PscuHeader *ph = 0;
3979                    T->SetBranchAddress("Header", &eh);
3980                    while ( apkt > bpkt && aobt > bobt && firstev < lastev ){
3981                      T->GetEntry(firstev);
3982                      ph = eh->GetPscuHeader();
3983                      bpkt = PKT(ph->GetCounter());
3984                      bobt = OBT(ph->GetOrbitalTime());
3985                      firstev++;
3986                      if ( PEDANTIC ) throw -71;
3987                    };
3988                    if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
3989                    //
3990                    glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
3991                    glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
3992                    glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
3993                    glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());
3994                    glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());
3995                    //
3996                    glrun->SetEV_FROM(firstev);
3997                    glrun->SetNEVENTS(lastev-firstev+1);
3998                    //
3999                    glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
4000                    glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
4001                    glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
4002                    glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());
4003                    glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());
4004                    glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());
4005                    glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());
4006                    glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());
4007                    glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());
4008                    glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());
4009                    glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());
4010                    glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());
4011                    glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());
4012                    glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());
4013                    glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());
4014                    glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());
4015                    //
4016                    if ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
4017                    if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
4018                    //
4019                    if ( !IsRunAlreadyInserted() ){
4020                      //
4021                      //      glrun->SetID(this->AssignRunID());
4022                      glrun->SetID_RUN_FRAG(glrun1->GetID());
4023                      glrun->Fill_GL_RUN(conn);
4024                      //
4025                      // set id number
4026                      //
4027                      glrun1->SetID_RUN_FRAG(glrun->GetID());
4028                      glrun1->Fill_GL_RUN(conn);
4029                      //
4030                    };
4031                    // delete old entry in fragment table
4032                    //
4033                    glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
4034                    glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
4035                    //
4036                    delete glrun1;
4037                    //
4038                    //
4039                    //      return;
4040                    //
4041                  };
4042                  //
4043                };
4044                //
4045                //
4046              zjustcheck:
4047                //
4048                if ( !found ){
4049                  //
4050                  if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");
4051                  //
4052                  // not found, has this run already inserted in the GL_RUN or in the GL_RUN_FRAGMENTS table?
4053                  //
4054                  oss.str("");
4055                  oss << " SELECT ID FROM GL_RUN WHERE "
4056                      << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
4057                      << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
4058                      << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
4059                      << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
4060                      << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
4061                      << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
4062                      << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
4063                      << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
4064                      << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
4065                      << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
4066                      << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
4067                      << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
4068                      << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
4069                  //
4070                  if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
4071                  result = conn->Query(oss.str().c_str());
4072                  //
4073                  if ( !result ) throw -4;
4074                  //
4075                  row = result->Next();
4076                  //
4077                  if ( row ){
4078                    if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");
4079                    if ( PEDANTIC ) throw -70;
4080                  } else {
4081                    if ( NoFrag() ){
4082                      glrun->SetID_RUN_FRAG(glrun->GetID());
4083                      glrun->Fill_GL_RUN(conn);
4084                      glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
4085                    };
4086                  };
4087                }; // EEE
4088    
4089    
4090            } else {            } else {
4091            if ( !IsRunAlreadyInserted() ){              if ( !IsRunAlreadyInserted() ){
4092              glrun->SetID(this->AssignRunID());                glrun->SetID(this->AssignRunID());
4093              glrun->SetID_RUN_FRAG(0);                glrun->SetID_RUN_FRAG(0);
4094              glrun->Fill_GL_RUN(conn);                glrun->Fill_GL_RUN(conn);
4095            };              };
4096            }; // EEE            }; // EEE
4097            //            //
4098            firstevno = lastentry + 1;            firstevno = lastentry + 1;
# Line 3564  Bool_t PamelaDBOperations::IsRunConsiste Line 4101  Bool_t PamelaDBOperations::IsRunConsiste
4101            //            //
4102          };          };
4103          //          //
4104            if ( i > firstev ){
4105              if ( rhchko != rhchk ){
4106                if ( IsDebug() ) printf("oh oh... we have a runheader! stop here and handle later the remaining piece\n");
4107                lastev = i;
4108                return(false);
4109              };
4110            };
4111            //
4112          if ( check == checklast && i != lastev ){          if ( check == checklast && i != lastev ){
4113            lastevtemp = i - 1;            lastevtemp = i - 1;
4114            i = lastev - 1;            i = lastev - 1;
# Line 3596  void PamelaDBOperations::HandleSuspiciou Line 4141  void PamelaDBOperations::HandleSuspiciou
4141    EventCounter *code=0;    EventCounter *code=0;
4142    UInt_t firstev = 0;    UInt_t firstev = 0;
4143    UInt_t lastev = 0;    UInt_t lastev = 0;
4144    UInt_t nevent = 0;    //  UInt_t nevent = 0;
4145    UInt_t checkfirst = 0;    UInt_t checkfirst = 0;
4146    UInt_t checklast = 0;    UInt_t checklast = 0;
4147    UInt_t firstentry = 0;    UInt_t firstentry = 0;
# Line 3621  void PamelaDBOperations::HandleSuspiciou Line 4166  void PamelaDBOperations::HandleSuspiciou
4166    EventHeader *eh = 0;    EventHeader *eh = 0;
4167    PscuHeader *ph = 0;    PscuHeader *ph = 0;
4168    T->SetBranchAddress("Header", &eh);    T->SetBranchAddress("Header", &eh);
4169    nevent = T->GetEntries();    //  nevent = T->GetEntries();
4170    //    //
4171    codt = eht->GetCounter();    codt = eht->GetCounter();
4172    codh = ehh->GetCounter();    codh = ehh->GetCounter();
# Line 3647  void PamelaDBOperations::HandleSuspiciou Line 4192  void PamelaDBOperations::HandleSuspiciou
4192      code = eh->GetCounter();      code = eh->GetCounter();
4193      checkfirst = 0;      checkfirst = 0;
4194      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
4195         if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
4196         if ( !strcmp(*Iter,"RunHeader") ) nrunh1++;        if ( !strcmp(*Iter,"RunHeader") ) nrunh1++;
4197       };      };
4198      if ( IsDebug() ) printf(" Check first is %i \n",checkfirst);      if ( IsDebug() ) printf(" Check first is %i \n",checkfirst);
4199      //      //
4200      T->GetEntry(lastev);      T->GetEntry(lastev);
4201      code = eh->GetCounter();      code = eh->GetCounter();
4202      checklast = 0;      checklast = 0;
4203      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
4204         if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
4205       };      };
4206      if ( IsDebug() ) printf(" Check last is %i \n",checklast);      if ( IsDebug() ) printf(" Check last is %i \n",checklast);
4207      //      //
4208      if ( checkfirst == checklast ){      if ( checkfirst == checklast ){
# Line 3769  void PamelaDBOperations::HandleSuspiciou Line 4314  void PamelaDBOperations::HandleSuspiciou
4314            };            };
4315            //                  //      
4316            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
4317              this->SetPhysEndRunVariables();
4318            //            //
4319            if ( !IsRunAlreadyInserted() ){            if ( !IsRunAlreadyInserted() ){
4320              glrun->SetID(this->AssignRunID());              glrun->SetID(this->AssignRunID());
# Line 3808  void PamelaDBOperations::HandleSuspiciou Line 4354  void PamelaDBOperations::HandleSuspiciou
4354              if ( IsDebug() ) printf(" We have the runtrailer \n");              if ( IsDebug() ) printf(" We have the runtrailer \n");
4355              //                  //    
4356              this->SetCommonGLRUN(firstTime,lastTime);              this->SetCommonGLRUN(firstTime,lastTime);
4357                this->SetPhysEndRunVariables();
4358              //              //
4359              if ( !IsRunAlreadyInserted() ){              if ( !IsRunAlreadyInserted() ){
4360                glrun->SetID(this->AssignRunID());                glrun->SetID(this->AssignRunID());
# Line 3853  Int_t PamelaDBOperations::insertCALO_CAL Line 4400  Int_t PamelaDBOperations::insertCALO_CAL
4400    UInt_t totime = 0;    UInt_t totime = 0;
4401    UInt_t obt = 0;    UInt_t obt = 0;
4402    UInt_t pkt = 0;    UInt_t pkt = 0;
4403      Float_t totped = 0.;
4404    //    //
4405    tr = (TTree*)file->Get("CalibCalPed");    tr = (TTree*)file->Get("CalibCalPed");
4406    if ( !tr || tr->IsZombie() ) throw -21;    if ( !tr || tr->IsZombie() ) throw -21;
# Line 3870  Int_t PamelaDBOperations::insertCALO_CAL Line 4418  Int_t PamelaDBOperations::insertCALO_CAL
4418        if ( calibCalPed->cstwerr[section] ){        if ( calibCalPed->cstwerr[section] ){
4419          valid = 1;          valid = 1;
4420          if ( calibCalPed->cperror[section] ) valid = 0;          if ( calibCalPed->cperror[section] ) valid = 0;
4421            //
4422            // check pedestal values for one plane, if all zeros calibration is not valid (calorimeter power problems) [8th data reduction bug, fixed on 25/11/2009 by E.M.]
4423            //
4424            totped = 0.;
4425            Int_t ns = 0;
4426            if ( section == 2 ) ns = 3;
4427            if ( section == 3 ) ns = 1;
4428            if ( section == 1 ) ns = 2;
4429            for (UInt_t ss=0; ss<96; ss++){
4430              totped += fabs(calibCalPed->calped[ns][0][ss]);
4431            }
4432            if ( totped < 1. ){
4433              if ( IsDebug() ) printf(" Section %i totped %f -  No calibration data! Calorimeter power problems? \n",section,totped);
4434              valid = 0;
4435            };
4436            //
4437          ph = eh->GetPscuHeader();          ph = eh->GetPscuHeader();
4438          obt = ph->GetOrbitalTime();            obt = ph->GetOrbitalTime();  
4439          pkt = ph->GetCounter();            pkt = ph->GetCounter();  
# Line 4037  Int_t PamelaDBOperations::insertCALOPULS Line 4601  Int_t PamelaDBOperations::insertCALOPULS
4601    tr->SetBranchAddress("Header", &eh);    tr->SetBranchAddress("Header", &eh);
4602    nevents = tr->GetEntries();    nevents = tr->GetEntries();
4603    //    //
4604      Float_t totpul = 0.;
4605      //
4606    if ( nevents > 0 ){    if ( nevents > 0 ){
4607      //      //
4608      for (UInt_t i=0; i < nevents; i++){      for (UInt_t i=0; i < nevents; i++){
# Line 4046  Int_t PamelaDBOperations::insertCALOPULS Line 4612  Int_t PamelaDBOperations::insertCALOPULS
4612          if ( cp1->pstwerr[section] && cp1->unpackError == 0 ){          if ( cp1->pstwerr[section] && cp1->unpackError == 0 ){
4613            valid = 1;            valid = 1;
4614            if ( cp1->pperror[section] ) valid = 0;            if ( cp1->pperror[section] ) valid = 0;
4615              //
4616              // check pulse values for one plane, if all zeros calibration is not valid (calorimeter power problems) [8th data reduction bug, fixed on 25/11/2009 by E.M.]
4617              //
4618              totpul = 0.;
4619              Int_t ns = 0;
4620              if ( section == 2 ) ns = 3;
4621              if ( section == 3 ) ns = 1;
4622              if ( section == 1 ) ns = 2;
4623              for (UInt_t ss=0; ss<96; ss++){
4624                totpul += cp1->calpuls[ns][0][ss];
4625              }
4626              if ( totpul >= 3145632. ){
4627                if ( IsDebug() ) printf(" PULSE1 Section %i totpul %f -  No calibration data! Calorimeter power problems? \n",section,totpul);
4628                valid = 0;
4629              };
4630              //
4631            ph = eh->GetPscuHeader();            ph = eh->GetPscuHeader();
4632            obt = ph->GetOrbitalTime();              obt = ph->GetOrbitalTime();  
4633            pkt = ph->GetCounter();              pkt = ph->GetCounter();  
# Line 4203  Int_t PamelaDBOperations::insertCALOPULS Line 4785  Int_t PamelaDBOperations::insertCALOPULS
4785          if ( cp2->pstwerr[section] && cp2->unpackError == 0 ){          if ( cp2->pstwerr[section] && cp2->unpackError == 0 ){
4786            valid = 1;            valid = 1;
4787            if ( cp2->pperror[section] ) valid = 0;            if ( cp2->pperror[section] ) valid = 0;
4788              //
4789              // check pulse values for one plane, if all zeros calibration is not valid (calorimeter power problems) [8th data reduction bug, fixed on 25/11/2009 by E.M.]
4790              //
4791              totpul = 0.;
4792              Int_t ns = 0;
4793              if ( section == 2 ) ns = 3;
4794              if ( section == 3 ) ns = 1;
4795              if ( section == 1 ) ns = 2;
4796              for (UInt_t ss=0; ss<96; ss++){
4797                totpul += cp2->calpuls[ns][0][ss];
4798              }
4799              if ( totpul >= 3145632. ){
4800                if ( IsDebug() ) printf(" PULSE2 Section %i totpul %f -  No calibration data! Calorimeter power problems? \n",section,totpul);
4801                valid = 0;
4802              };
4803              //
4804            ph = eh->GetPscuHeader();            ph = eh->GetPscuHeader();
4805            obt = ph->GetOrbitalTime();              obt = ph->GetOrbitalTime();  
4806            pkt = ph->GetCounter();              pkt = ph->GetCounter();  
# Line 4382  Int_t PamelaDBOperations::insertCALOPULS Line 4980  Int_t PamelaDBOperations::insertCALOPULS
4980   * Fill the GL_TRK_CALIB table   * Fill the GL_TRK_CALIB table
4981   */   */
4982  void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){  void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){
4983    //      
4984    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;  
4985      //      //
4986    } else {      glcal->ID         = 0;
4987        glcal->ID_ROOT_L0 = GetID_ROOT();
4988        glcal->EV_ROOT_CALIBTRK1 = t1;
4989        glcal->EV_ROOT_CALIBTRK2 = t2;
4990        glcal->FROM_TIME = fromtime;
4991        glcal->TO_TIME   = 0;
4992        glcal->OBT1      = obt1;
4993        glcal->OBT2      = obt2;
4994        glcal->PKT1      = pkt1;
4995        glcal->PKT2      = pkt2;
4996        glcal->BOOT_NUMBER = GetBOOTnumber();
4997        glcal->VALIDATION = valid;
4998      //      //
4999      // we have to insert a new calibration, check where to place it      HandleTRK_CALIB(glcal);
5000      //      //
5001      oss.str("");      delete glcal;
5002      oss << " SELECT ID,TO_TIME FROM GL_TRK_CALIB WHERE "  }
5003          << " FROM_TIME < "<< fromtime << " AND "  /**
5004          << " TO_TIME > "<< fromtime << ";";   * Fill the GL_TRK_CALIB table
5005     */
5006    void PamelaDBOperations::HandleTRK_CALIB(GL_TRK_CALIB *glcal){
5007    
5008        Bool_t pk1 = (glcal->OBT1>0&&glcal->PKT1>0);
5009        Bool_t pk2 = (glcal->OBT2>0&&glcal->PKT2>0);
5010        UInt_t boot_number = glcal->BOOT_NUMBER;
5011        UInt_t obt1 = glcal->OBT1;
5012        UInt_t obt2 = glcal->OBT2;
5013        UInt_t pkt1 = glcal->PKT1;
5014        UInt_t pkt2 = glcal->PKT2;
5015        UInt_t fromtime = glcal->FROM_TIME;
5016        UInt_t totime = 0;
5017        UInt_t idroot = glcal->ID_ROOT_L0;
5018        UInt_t t1 = glcal->EV_ROOT_CALIBTRK1;
5019        UInt_t t2 = glcal->EV_ROOT_CALIBTRK2;
5020        UInt_t valid = glcal->VALIDATION;
5021      //      //
5022      if ( IsDebug() ) printf(" Check where to place the trk calibration: query is \n %s \n",oss.str().c_str());      TSQLResult *result = 0;
5023      result = conn->Query(oss.str().c_str());      TSQLRow    *row    = 0;
5024      //      //
5025      if ( !result ) throw -4;      stringstream oss;
5026        oss.str("");
5027      //      //
     row = result->Next();  
5028      //      //
5029      if ( !row ){      if ( !pk1 && !pk2 ){
5030        //          if ( IsDebug() ) printf(" Cannot handle trk calibration with both packet missing!\n");
5031        // 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;  
       //  
5032      };      };
5033      //      //
5034      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 << "',";  
5035      //      //
5036      if ( !pk1 ){      oss.str("");
5037        oss << "NULL,";      oss << " SELECT ID FROM GL_TRK_CALIB WHERE "
5038            << " BOOT_NUMBER = "<< boot_number; //
5039        oss << " AND FROM_TIME="<<fromtime; /// NEWNEWNEW -- VA BENE ?!?!?!?!
5040        oss << " AND ( ( ";  
5041        if ( pk1 ){
5042            oss << " OBT1 = "<< obt1 << " AND "
5043                << " PKT1 = "<< pkt1
5044                << " ) OR ( ";
5045      } else {      } else {
5046        oss << "'"          oss << " PKT1 = "<< pkt2-1
5047            << t1 << "',";              << " ) OR ( ";  
5048      };      };      
5049      //      if ( pk2 ){
5050      if ( !pk2 ){          oss << " OBT2 = "<< obt2 << " AND "
5051        oss << "NULL,'";              << " PKT2 = "<< pkt2;
5052      } else {      } else {
5053        oss << "'"          oss << " PKT2 = "<< pkt1+1;
5054            << t2 << "','";      };      
5055      };      oss << " ) );";  
5056        //
5057        if ( IsDebug() ) printf(" Check if the trk calibration has already been inserted: query is \n %s \n",oss.str().c_str());
5058        result = conn->Query(oss.str().c_str());
5059      //      //
5060      oss << fromtime << "','"      if ( !result ) throw -4;
         << totime << "','"  
         << obt1 << "','"  
         << pkt1 << "','"  
         << obt2 << "','"  
         << pkt2 << "','"  
         << this->GetBOOTnumber() << "','"  
         << valid << "');";  
5061      //      //
5062      if ( IsDebug() ) printf(" Insert the new trk calibration: query is \n %s \n",oss.str().c_str());      row = result->Next();
5063      //      //
5064        if ( row ){
5065            //
5066            if ( IsDebug() ) printf(" Trk calibration already inserted in the DB\n");
5067            if ( PEDANTIC ) throw -80;
5068            //
5069        } else {
5070            //
5071            // we have to insert a new calibration, check where to place it
5072            //
5073            oss.str("");
5074            oss << " SELECT ID,TO_TIME FROM GL_TRK_CALIB WHERE "
5075                << " FROM_TIME < "<< fromtime << " AND "
5076                << " TO_TIME > "<< fromtime << ";";
5077            //
5078            if ( IsDebug() ) printf(" Check where to place the trk calibration: query is \n %s \n",oss.str().c_str());
5079            result = conn->Query(oss.str().c_str());
5080            //
5081            if ( !result ) throw -4;
5082            //
5083            row = result->Next();
5084            //
5085            if ( !row ){
5086                //
5087                // no calibrations in the db contain our calibration
5088                //
5089                if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB\n");
5090                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
5091                //
5092                oss.str("");
5093                oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "
5094                    << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
5095                //
5096                if ( IsDebug() ) printf(" Check the upper limit for calibration: query is \n %s \n",oss.str().c_str());
5097                result = conn->Query(oss.str().c_str());
5098                //
5099                if ( !result ) throw -4;
5100                //
5101                row = result->Next();
5102                if ( !row ){
5103                    totime = numeric_limits<UInt_t>::max();
5104                } else {
5105                    totime = (UInt_t)atoll(row->GetField(0));
5106                };
5107                //
5108            } else {
5109                //
5110                // determine upper and lower limits and make space for the new calibration
5111                //
5112                totime = (UInt_t)atoll(row->GetField(1));
5113                //
5114                oss.str("");
5115                oss << " UPDATE GL_TRK_CALIB SET "  
5116                    << " TO_TIME = "<< fromtime << " WHERE "  // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
5117                    << " ID = "<< row->GetField(0) << ";";
5118                //
5119                if ( IsDebug() ) printf(" Make space for the new trk calibration: query is \n %s \n",oss.str().c_str());
5120                result = conn->Query(oss.str().c_str());
5121                //
5122                if ( !result ) throw -4;
5123                //
5124            };
5125            //
5126            oss.str("");
5127            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) "
5128                << " VALUES (NULL,' "
5129                << idroot << "',";
5130            //
5131            if ( !pk1 ){
5132                oss << "NULL,";
5133            } else {
5134                oss << "'"
5135                    << t1 << "',";
5136            };
5137            //
5138            if ( !pk2 ){
5139                oss << "NULL,'";
5140            } else {
5141                oss << "'"
5142                    << t2 << "','";
5143            };
5144            //
5145            oss << fromtime << "','"
5146                << totime << "','"
5147                << obt1 << "','"
5148                << pkt1 << "','"
5149                << obt2 << "','"
5150                << pkt2 << "','"
5151                << boot_number << "','"
5152                << valid << "');";
5153            //
5154            if ( IsDebug() ) printf(" Insert the new trk calibration: query is \n %s \n",oss.str().c_str());
5155            //
5156            result = conn->Query(oss.str().c_str());
5157            //
5158            if ( !result ) throw -4;
5159            //
5160        };
5161        
5162        oss.str("");
5163        oss << " SELECT ID FROM GL_TRK_CALIB ORDER BY ID DESC LIMIT 1 ;";  
5164        if ( IsDebug() ) cout << oss.str().c_str() << endl;
5165      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
5166        if ( !result ) throw -4;;
5167        row = result->Next();
5168        if(row)glcal->ID = (UInt_t)atoll(row->GetField(0));
5169      //      //
5170      if ( !result ) throw -4;      delete result; // mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
5171      //      //
   };  
   //  
5172  };  };
5173    
5174  /**  /**
5175   * Scan tracker calibrations packets, fill the GL_TRK_CALIB table   * Scan tracker calibrations packets, fill the GL_TRK_CALIB table
5176   */   */
5177  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++){  
5178      //      //
5179      pret2 = t2;      CalibTrk1Event *caltrk1 = 0;
5180      tr1->GetEntry(t1);      CalibTrk2Event *caltrk2 = 0;
5181        TTree *tr1 = 0;
5182        TTree *tr2 = 0;
5183        EventHeader *eh1 = 0;
5184        PscuHeader *ph1 = 0;
5185        EventHeader *eh2 = 0;
5186        PscuHeader *ph2 = 0;
5187      //      //
5188      ph1 = eh1->GetPscuHeader();      PacketType *pctp=0;
5189      obt1 = ph1->GetOrbitalTime();        EventCounter *codt2=0;
     pkt1 = ph1->GetCounter();    
     fromtime = this->GetAbsTime(ph1->GetOrbitalTime());    
5190      //      //
5191  //     valid = 1;      Int_t nevents1 = 0;
5192  //     //      Int_t nevents2 = 0;
 //     if ( caltrk1->unpackError != 0 && caltrk1->good0 == 0 ) valid = 0;// CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT1  
5193      //      //
5194        fromtime = 0;
5195      //      //
5196      if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->PKT(pkt1) <= upperpkt && this->OBT(obt1) >= this->OBT(obtfirst) && this->OBT(obt1) <= upperobt ){      obt1 = 0;
5197        //    if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->OBT(obt1) >= this->OBT(obtfirst) ){      pkt1 = 0;
5198        //      obt2 = 0;
5199        if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u \n",fromtime,obt1,pkt1);      pkt2 = 0;
5200        //            //
5201        valid = ValidateTrkCalib( caltrk1, eh1 );      tr1 = (TTree*)file->Get("CalibTrk1");
5202        if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;      if ( !tr1 || tr1->IsZombie() ) throw -22;
5203        //      tr2 = (TTree*)file->Get("CalibTrk2");
5204        // Do we have the second calibration packet?      if ( !tr2 || tr2->IsZombie() ) throw -23;
5205        //      //
5206        while ( t2t1cal < t1+1 ){ // get the calibration packet2 that follows the packet1      tr1->SetBranchAddress("CalibTrk1", &caltrk1);
5207        tr1->SetBranchAddress("Header", &eh1);
5208        nevents1 = tr1->GetEntries();
5209        tr2->SetBranchAddress("CalibTrk2", &caltrk2);
5210        tr2->SetBranchAddress("Header", &eh2);
5211        nevents2 = tr2->GetEntries();
5212        //
5213        if ( !nevents1 && !nevents2 ) return(1);
5214        //
5215        t2 = -1;
5216        Int_t pret2 = 0;
5217        Int_t t2t1cal = 0;
5218        //
5219        bool MISSING_pkt1 = true;
5220        bool MISSING_pkt2 = true;
5221        int  ncalib = 0;
5222        bool try_to_recover = false;
5223        //
5224        for (t1=0; t1 < nevents1; t1++){//loop over packet1
5225          //          //
5226          t2++;          pret2 = t2;
5227            tr1->GetEntry(t1);
5228          //          //
5229          pret2 = t2 - 1; // EMILIANO          ph1 = eh1->GetPscuHeader();
5230            obt1 = ph1->GetOrbitalTime();  
5231            pkt1 = ph1->GetCounter();  
5232            fromtime = GetAbsTime(ph1->GetOrbitalTime());  
5233          //          //
5234          if ( t2 < nevents2 ){          // chek if the packet number and obt are consistent with the other packets ???
5235            tr2->GetEntry(t2);          //
5236            codt2 = eh2->GetCounter();          if ( PKT(pkt1) >= PKT(pktfirst) && PKT(pkt1) <= upperpkt && OBT(obt1) >= OBT(obtfirst) && OBT(obt1) <= upperobt ){
5237            t2t1cal = codt2->Get(pctp->CalibTrk1);              //    if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->OBT(obt1) >= this->OBT(obtfirst) ){
5238            //              //
5239            ph2 = eh2->GetPscuHeader();              if ( IsDebug() ) printf("\n Trk calibration1 %u at time %u obt %u pkt %u \n",t1,fromtime,obt1,pkt1);
5240            obt2 = ph2->GetOrbitalTime();                //      
5241            pkt2 = ph2->GetCounter();                valid = ValidateTrkCalib( caltrk1, eh1 );
5242            //              if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;
5243            if ( IsDebug() ) printf(" This is a trk calibration2 at obt %u pkt %u t2 is %u , t2t1cal is %u \n",obt2,pkt2,t2,t2t1cal);                    //
5244  //        if ( caltrk2->unpackError != 0 || caltrk2->good0 == 0 ) valid = 0; // CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT2              // Do we have the second calibration packet?
5245            //                    //
5246          } else {              if ( IsDebug() ) cout << " Loop over calibration2 to search associated calibration: "<<endl;
5247            //              while ( t2t1cal < t1+1 ){ // get the calibration packet2 that follows the packet1
5248            // running out of vector without finding the corresponding calibration, sig                  //
5249            //                  t2++;
5250            if ( IsDebug() ) printf(" t2 >= nevents2 \n");                  //
5251            pret2 = t2;                  pret2 = t2 - 1; // EMILIANO
5252            obt2 = 0;                  //
5253            //      pkt2 = pkt1+2;                  if ( t2 < nevents2 ){
5254            pkt2 = 0;                      tr2->GetEntry(t2);
5255            t2t1cal = t1+1;                      codt2 = eh2->GetCounter();
5256          };                      t2t1cal = codt2->Get(pctp->CalibTrk1);
5257          //      if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) && (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){                      //
5258                        ph2 = eh2->GetPscuHeader();
5259                        obt2 = ph2->GetOrbitalTime();  
5260                        pkt2 = ph2->GetCounter();  
5261                        //
5262                        if ( IsDebug() ) printf(" >> trk calibration2 at obt %u pkt %u t2 is %u , t2t1cal is %u \n",obt2,pkt2,t2,t2t1cal);    
5263                        //    if ( caltrk2->unpackError != 0 || caltrk2->good0 == 0 ) valid = 0; // CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT2
5264                        //    
5265                    } else {
5266                        //
5267                        // running out of vector without finding the corresponding calibration, sig
5268                        //
5269                        if ( IsDebug() ) printf(" t2 >= nevents2 \n");
5270                        pret2 = t2;
5271                        obt2 = 0;
5272                        //    pkt2 = pkt1+2;
5273                        pkt2 = 0;
5274                        t2t1cal = t1+1;
5275                    };
5276                    //      if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) && (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){
5277    
5278          // EMILIANO                  // EMILIANO
5279  //      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->PKT(pkt2) > upperpkt) || (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){
5280  //        //    if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){                  //        //    if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){
5281  //        if ( IsDebug() ) printf(" running out of vector without finding the corresponding calibration, sig \n");                  //        if ( IsDebug() ) printf(" running out of vector without finding the corresponding calibration, sig \n");
5282  //        //                  //        //
5283  //        // running out of vector without finding the corresponding calibration, sig                  //        // running out of vector without finding the corresponding calibration, sig
5284  //        //                  //        //
5285  //        pret2 = t2;                  //        pret2 = t2;
5286  //        obt2 = 0;                  //        obt2 = 0;
5287  //        //      pkt2 = pkt1+2;                  //        //      pkt2 = pkt1+2;
5288  //        pkt2 = 0;                  //        pkt2 = 0;
5289  //        t2t1cal = t1+1;                  //        t2t1cal = t1+1;
5290  //      };                  //      };
5291    
5292    
5293                    //
5294                };
5295                //
5296                if ( IsDebug() ) printf(" Check if trk calibration2 is the right one \n");
5297                //
5298                // EMILIANO
5299                if ( ( PKT(pkt2) < PKT(pktfirst) || PKT(pkt2) > upperpkt) || (OBT(obt2) < OBT(obtfirst) || OBT(obt2) > upperobt) ){
5300                    //      if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){
5301                    if ( IsDebug() ) printf(" *WARNING*  The calibration found is outside the interval, sig \n");
5302                    //
5303                    // running out of vector without finding the corresponding calibration, sig
5304                    //
5305                    pret2 = t2;
5306                    obt2 = 0;
5307                    pkt2 = 0;
5308                };
5309                if ( PKT(pkt2) == PKT(pkt1)+1 ){
5310                    if ( IsDebug() ) cout << " ...OK"<<endl;
5311                    // =======================
5312                    // The calibration is good
5313                    // =======================
5314                    //
5315    //      if ( IsDebug() ) printf(" Found trk calibration2 at obt %u pkt %u t2 is %u \n",obt2,pkt2,t2);
5316    //      if ( IsDebug() ) printf(" Trk calibration2 at obt %u pkt %u t2 is %u is good \n",obt2,pkt2,t2);
5317    //        if ( IsDebug() ) printf("\n Trk calibration2 at time %u obt %u pkt %u \n",fromtime,obt2,pkt2);
5318                    if ( IsDebug() ) printf(" Trk calibration2 %u at time %u obt %u pkt %u \n",t2,fromtime,obt2,pkt2);
5319                    //
5320                    UInt_t valid2 = ValidateTrkCalib( caltrk2, eh2 );
5321                    if ( IsDebug() ) cout << " pkt2 validation --> "<<valid2<<endl;
5322    //      valid = valid & valid2;
5323                    valid = valid & valid2; //QUESTO VA CAMBIATO
5324                    //
5325                    // Handle good calib
5326                    //
5327                    MISSING_pkt1 = false;
5328                    MISSING_pkt2 = false;
5329    //              this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5330                    //
5331                    // Check for missing calibtrk1
5332                    //
5333                    if ( t2 != pret2+1 ){
5334                        //
5335                        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);
5336                        //
5337                        while ( t2 > pret2+1 ){
5338                            //
5339                            // handle missing calib1
5340                            //
5341                            pret2++;
5342                            //
5343                            obt1 = 0;
5344                            pkt1 = 0;
5345                            //
5346                            tr2->GetEntry(pret2);
5347                            ph2 = eh2->GetPscuHeader();
5348                            obt2 = ph2->GetOrbitalTime();  
5349                            pkt2 = ph2->GetCounter();  
5350                            //
5351                            fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
5352                            //
5353                            valid = 0;
5354                            MISSING_pkt1 = true;
5355                            MISSING_pkt2 = false;
5356    //                      this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5357                            //
5358                        };
5359                        //
5360                    };
5361                    //
5362                } else if ( this->PKT(pkt2) > this->PKT(pkt1)+1 ){
5363                    //
5364                    // Check for missing calibtrk2
5365                    //
5366                    if ( IsDebug() ) printf(" Missing the trk calibration2! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);
5367                    t2 = pret2;
5368                    //
5369                    // handle missing calib2
5370                    //
5371                    obt2 = 0;
5372                    pkt2 = 0;
5373                    valid = 0;
5374                    MISSING_pkt1 = false;
5375                    MISSING_pkt2 = true;
5376    //              this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5377                    //
5378                };
5379                //
5380    
5381                if( !(MISSING_pkt1&MISSING_pkt2) ){
5382                  this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5383                  ncalib++;
5384                  if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
5385                }
5386    
5387    
5388            } else {
5389              //
5390                if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u OUTSIDE the considered time interval \n",fromtime,obt1,pkt1);
5391                //      if ( PEDANTIC ) throw -79;
5392                //
5393            };
5394            //    
5395    
5396        }; //end loop on pkt1
5397    
5398    
5399    
5400        //
5401        // we have one more calib pkt2 !
5402        //
5403        t2++;
5404        while ( t2 < nevents2 ){
5405          //          //
5406        };          // 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  
5407          //          //
5408          this->HandleTRK_CALIB(true,true);          if ( IsDebug() ) printf(" t2 is %u nevents2 is %u \n",t2,nevents2);
5409            obt1 = 0;
5410            pkt1 = 0;
5411          //          //
5412          // Check for missing calibtrk1          tr2->GetEntry(t2);
5413            ph2 = eh2->GetPscuHeader();
5414            obt2 = ph2->GetOrbitalTime();  
5415            pkt2 = ph2->GetCounter();  
5416          //          //
5417          if ( t2 != pret2+1 ){          fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
5418            //          valid = 0;
5419            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 ){
5420            //          // EMILIANO
5421            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 ){
5422              //              //    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();    
5423              //              //
5424              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);
5425              //              //
5426              valid = 0;              MISSING_pkt1 = true;
5427              this->HandleTRK_CALIB(false,true);              MISSING_pkt2 = false;
5428                this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5429                ncalib++;
5430                if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
5431              //              //
           };  
           //  
5432          };          };
5433          //          //
5434        } 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;  
5435          //          //
5436          // handle missing calib2      };
5437    
5438    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
5439    // -----------------------------------------------------------------
5440    // in case of corruption, check if the calibration can be recovered
5441    // from another chewbacca file
5442    // -----------------------------------------------------------------
5443    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
5444    
5445    //    cout <<" TRY TO RECOVER ?? "<<try_to_recover<<endl;
5446        
5447        if(chewbacca&&try_to_recover){
5448    
5449    
5450            if ( IsDebug() ) cout << endl << ">>>> TRY TO RECOVER TRACKER CALIBRATIONS <<<<"<<endl;
5451    
5452            TSQLResult *rresult = 0; // 10RED bug, result is re-used inside result looop...
5453            TSQLResult *result = 0; // 10RED bug, result is re-used inside result looop...
5454            TSQLRow    *row    = 0;
5455          //          //
5456          obt2 = 0;          stringstream oss;
5457          pkt2 = 0;          oss.str("");
         valid = 0;  
         this->HandleTRK_CALIB(true,false);        
5458          //          //
5459        };  
5460        //          ////////////////////////////////////////////////////////////////////////
5461      } else {          // retrieve the name of the current file:
5462        //          ////////////////////////////////////////////////////////////////////////        
5463        if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u OUTSIDE the considered time interval \n",fromtime,obt1,pkt1);          oss.str("");
5464        //      if ( PEDANTIC ) throw -79;          oss << "SELECT NAME FROM GL_ROOT where ID=" << GetID_ROOT() <<";";
5465        //          if ( IsDebug() ) cout << oss.str().c_str() << endl;
5466      };  
5467      //              result = conn->Query(oss.str().c_str());
5468    };          if ( !result ) throw -4;;
5469    //          row = result->Next();
5470    // we have one more calib pkt2 !          TString thisfilename = (TString)row->GetField(0);
5471    //          if ( IsDebug() ) cout << "Current file ==> "<<thisfilename<<endl;      
5472    t2++;  
5473    while ( t2 < nevents2 ){          ////////////////////////////////////////////////////////////////////////        
5474      //          // read all the calibrations inserted
5475      // handle missing calib1          ////////////////////////////////////////////////////////////////////////        
5476      //          oss.str("");
5477      if ( IsDebug() ) printf(" t2 is %u nevents2 is %u \n",t2,nevents2);          oss << " SELECT ";
5478      obt1 = 0;          oss << " ID,FROM_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,TO_TIME";
5479      pkt1 = 0;          oss << " FROM GL_TRK_CALIB ";
5480      //          oss << " ORDER BY ID DESC LIMIT "<<ncalib<<"; ";        
5481      tr2->GetEntry(t2);          if ( IsDebug() ) cout << oss.str().c_str() << endl;
5482      ph2 = eh2->GetPscuHeader();  
5483      obt2 = ph2->GetOrbitalTime();            rresult = conn->Query(oss.str().c_str());
5484      pkt2 = ph2->GetCounter();            if ( !result ) throw -4;;
5485      //          if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5486      fromtime = this->GetAbsTime(ph2->GetOrbitalTime());          
5487      valid = 0;          // -----------------------------------
5488  //  if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->PKT(pkt1) <= upperpkt && this->OBT(obt1) >= this->OBT(obtfirst) && this->OBT(obt1) <= upperobt ){          // loop over calibrations ...
5489   // EMILIANO          // -----------------------------------
5490      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;
5491        //    if ( this->PKT(pkt2) > this->PKT(pktfirst) || this->OBT(obt2) > this->OBT(obtfirst) ){          do {
5492        //              row = rresult->Next();
5493        if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);              if(!row)break;
5494        //              
5495        this->HandleTRK_CALIB(false,true);              UInt_t id       = (UInt_t)atoll(row->GetField(0));
5496        //              UInt_t fromtime = (UInt_t)atoll(row->GetField(1));
5497      };              UInt_t obt1     = (UInt_t)atoll(row->GetField(2));
5498      //              UInt_t pkt1     = (UInt_t)atoll(row->GetField(3));
5499      t2++;              UInt_t obt2     = (UInt_t)atoll(row->GetField(4));
5500      //              UInt_t pkt2     = (UInt_t)atoll(row->GetField(5));
5501    };              UInt_t boot     = (UInt_t)atoll(row->GetField(6));
5502                UInt_t valid    = (UInt_t)atoll(row->GetField(7));
5503                bool MISSING_pkt1 = (row->GetFieldLength(8)==0);
5504                bool MISSING_pkt2 = (row->GetFieldLength(9)==0);
5505                UInt_t totime   = (UInt_t)atoll(row->GetField(10));
5506    
5507                // -------------------------------------
5508                // ...check if the entry is corrupted...
5509                // -------------------------------------
5510                cout <<"*** "<< MISSING_pkt1 << MISSING_pkt2 << valid <<endl;
5511                bool CORRUPTED = (MISSING_pkt1||MISSING_pkt2||!valid);
5512    
5513                if ( IsDebug() ) cout << "("<<nn<<")  ID = "<<id<<" from GL_TRK_CALIB  ==>  corrupted ? "<<CORRUPTED<<endl;
5514    
5515    //          if( !CORRUPTED  )continue; // nothing to do
5516    
5517                /////////////////////////////////////////////////////////  
5518                // if it is corrupted, ...look for ather chewbacca files
5519                // containing the same calibrations ...
5520                /////////////////////////////////////////////////////////
5521    
5522                bool this_MISSING_pkt1 = false;
5523                bool this_MISSING_pkt2 = false;
5524                int  this_t1=0;
5525                int  this_t2=0;;
5526                UInt_t this_valid = 0;
5527    
5528                TString path       = "";
5529                TString name       = "";
5530                TString raw        = "";
5531                //      UInt_t obt0        = 0;
5532                //      UInt_t timesync    = 0;
5533                //      UInt_t boot_number = 0;
5534                bool   FOUND       = false;
5535    
5536                if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
5537    
5538    //          for(int itable=0; itable<2; itable++){
5539                for(int itable=0; itable<1; itable++){
5540    
5541                    // ------------------------------------------------------
5542                    // loop over both ROOT_TABLE and ROOT_TABLE_BAD
5543                    // ------------------------------------------------------
5544    
5545                    TString table = "ROOT_TABLE";
5546                    if(itable==1)table = "ROOT_TABLE_BAD";
5547    
5548                    oss.str("");
5549                    oss << " SELECT ";
5550                    oss << " FOLDER_NAME,FILE_NAME,OBT_TIME_SYNC,LAST_TIME_SYNC_INFO,BOOT_NUMBER,INPUT_NAME ";
5551                    oss << " FROM "<<table;
5552                    oss << " WHERE 1 " << endl;
5553                    oss << " AND FILE_NAME != \""<< thisfilename<<"\"";
5554                    if( !MISSING_pkt1 ){
5555                        oss << " AND ";
5556                        oss << " PKT_NUMBER_INIT < "<<pkt1;
5557                        oss << " AND ";
5558                        oss << " PKT_NUMBER_FINAL > "<<pkt1;
5559                        oss << " AND ";
5560                        oss << " PKT_OBT_INIT < "<<obt1;
5561                        oss << " AND ";
5562                        oss << " PKT_OBT_FINAL > "<<obt1;
5563                    }else{
5564                        if(pkt2>1) pkt1 = pkt2-1;//serve dopo                  
5565                    }
5566                    if( !MISSING_pkt2 ){
5567                        oss << " AND ";
5568                        oss << " PKT_NUMBER_INIT < "<<pkt2;
5569                        oss << " AND ";
5570                        oss << " PKT_NUMBER_FINAL > "<<pkt2;
5571                        oss << " AND ";
5572                        oss << " PKT_OBT_INIT < "<<obt2;
5573                        oss << " AND ";
5574                        oss << " PKT_OBT_FINAL > "<<obt2;
5575                    }else{
5576                        if(pkt1>0) pkt2 = pkt1+1;//serve dopo
5577                    }
5578                    if( boot> 0 ){
5579                        oss << " AND ";
5580                        oss << " BOOT_NUMBER = "<<boot;
5581                    }else{
5582                    }
5583                    oss << " ORDER BY BAD_PKT_CALREAD ASC; ";
5584                
5585                    TSQLResult *result2 = 0;
5586                    TSQLRow    *row2    = 0;
5587    
5588                    if ( IsDebug() ) cout << oss.str().c_str() << endl;        
5589                    result2 = conn->Query(oss.str().c_str());
5590                    if ( !result2 ) throw -4;;
5591                    if ( IsDebug() ) cout <<"Rows: "<<result2->GetRowCount()<<endl;
5592    
5593                    // ------------------------------------------------------
5594                    // loop over files containing repetition (if any)
5595                    // ------------------------------------------------------
5596                    do {
5597                        row2 = result2->Next();
5598                        if(!row2)break;
5599                    
5600                        // ------------------------------------------------------
5601                        // ... a repetition is found ...
5602                        // ------------------------------------------------------
5603                        path       = (TString)row2->GetField(0);
5604                        name       = (TString)row2->GetField(1);
5605                        raw        = (TString)row2->GetField(5);
5606                        //              obt0        = (UInt_t)atoll(row2->GetField(2));
5607                        //              timesync    = (UInt_t)atoll(row2->GetField(3));
5608                        //              boot_number = (UInt_t)atoll(row2->GetField(4));
5609                    
5610                        if ( IsDebug() ) cout << "- - - - - - - - - - -" <<endl;
5611    //                  cout << path <<endl;
5612    //                  cout << "File    : " <<name <<endl;
5613    //                  cout << obt0 <<endl;
5614    //                  cout << timesync <<endl;
5615    //                  cout << "boot n. : "<<boot_number <<endl;
5616    //                  cout << raw <<endl;
5617    
5618                        // ------------------------------------------------------
5619                        // ... retrieve the calibration packets.
5620                        // ------------------------------------------------------
5621                        if ( IsDebug() ) printf(" file is %s/%s \n",((TString)gSystem->ExpandPathName(path.Data())).Data(),name.Data());
5622                        TFile *file = new TFile(((TString)gSystem->ExpandPathName(path.Data()))+"/"+name); // EM, path could be symbolic and we must expand it
5623                        if(!file)throw -100;
5624                        if(file->IsZombie())throw -100;
5625                        //
5626                        tr1 = (TTree*)file->Get("CalibTrk1");
5627                        if ( !tr1 || tr1->IsZombie() ) throw -22;
5628                        tr2 = (TTree*)file->Get("CalibTrk2");
5629                        if ( !tr2 || tr2->IsZombie() ) throw -23;
5630                        //
5631                        tr1->SetBranchAddress("CalibTrk1", &caltrk1);
5632                        tr1->SetBranchAddress("Header", &eh1);
5633                        nevents1 = tr1->GetEntries();
5634                        tr2->SetBranchAddress("CalibTrk2", &caltrk2);
5635                        tr2->SetBranchAddress("Header", &eh2);
5636                        nevents2 = tr2->GetEntries();
5637                        for(this_t1=0; this_t1<nevents1; this_t1++){
5638                            tr1->GetEntry(this_t1);
5639                            if(
5640                                (UInt_t)eh1->GetPscuHeader()->GetCounter() == pkt1 &&
5641                                true) break;
5642                            this_MISSING_pkt1 = true;
5643                        }
5644                        for(this_t2=0; this_t2<nevents2; this_t2++){
5645                            tr2->GetEntry(this_t2);
5646                            if(
5647                                (UInt_t)eh2->GetPscuHeader()->GetCounter() == pkt2 &&
5648                                true) break;
5649                            this_MISSING_pkt2 = true;
5650                        }
5651                        this_valid =
5652                            ValidateTrkCalib( caltrk1, eh1, file )
5653                            *
5654                            ValidateTrkCalib( caltrk2, eh2, file );
5655                                
5656                        // ---------------------------------------------------------------------
5657                        // accept the calibration if it is better than the previous:
5658                        //
5659                        // - if the new calibration is perfect (both valid packets)
5660                        // - if the new calibration has both the packets and the previous does not
5661                        // ---------------------------------------------------------------------
5662                        if(
5663                            ( !this_MISSING_pkt1&&!this_MISSING_pkt2&&this_valid )||
5664                            ( (MISSING_pkt1||MISSING_pkt2) && (!this_MISSING_pkt1&&!this_MISSING_pkt2) )||
5665                            false)FOUND=true;      
5666                
5667                        if(file)file->Close();
5668    
5669                        if(FOUND)break;
5670    
5671                    }while(1);//endl loop over root table entries
5672                    
5673                    delete result2; // 10RED potential memory leak
5674                    if(FOUND)break;
5675    
5676                }//end loop over tables
5677    
5678                if(FOUND){
5679    
5680                  if ( IsDebug() ) cout << " >>> REPETITION FOUND :-) <<<" <<endl;
5681    
5682                  ////////////////////////////////////////////
5683                  // insert a new entry in GL_TRK_CALIB and
5684                  // modify the time-tag of the previous one
5685                  ////////////////////////////////////////////
5686    
5687                  // ---------------------------------------------------------------------
5688                  // step 1: insert a new raw file in GL_RAW
5689                  // ---------------------------------------------------------------------
5690                  //
5691                  // check if the raw file already exist
5692                  //
5693                  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
5694                  //                oss.str("");
5695                  //                oss << "SELECT ID FROM GL_RAW where NAME=\"" << gSystem->BaseName(raw.Data()) <<"\";";
5696                  //                if ( IsDebug() ) cout << oss.str().c_str() << endl;
5697                    
5698                  //                result = conn->Query(oss.str().c_str());
5699                  //                if ( !result ) throw -4;;
5700                  //                if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5701                  //                if( result->GetRowCount() == 0){
5702                  //                    if ( IsDebug() ) cout << " << Insert new RAW file >> "<<endl;
5703                  //                    // - - - - - - - - - - -
5704                  //                    // insert new raw file
5705                  //                    // - - - - - - - - - - -
5706                  //                    GL_RAW glraw = GL_RAW();    
5707                  //                    glraw.PATH        = gSystem->DirName(raw.Data());
5708                  //                    glraw.NAME        = gSystem->BaseName(raw.Data());
5709                  //                    glraw.BOOT_NUMBER = boot_number;
5710                  //                    //
5711                  //                    insertPamelaRawFile( &glraw );
5712                  //                    //              
5713                  //                    id_raw = glraw.ID;              
5714                  //                }else{
5715                  //                    row = result->Next();
5716                  //                    id_raw = (UInt_t)atoll(row->GetField(0));
5717                  //                }
5718                  //                if ( IsDebug() ) cout << "ID_RAW = "<<id_raw<<endl;
5719    
5720                  // ---------------------------------------------------------------------
5721                  // step 1(bis): retrieve the timesync id associated to the file
5722                  // (NB, uso lo stesso associato al file iniziale)
5723                  // ---------------------------------------------------------------------
5724                  UInt_t idtimesync = 0;
5725                  oss.str("");
5726                  oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" limit 1;";
5727                  if ( debug ) printf(" %s \n",oss.str().c_str());
5728                  result = conn->Query(oss.str().c_str());
5729                  if ( !result ) throw -3;
5730                    row = result->Next();
5731                    if ( !row ) throw -3;
5732                    idtimesync = (UInt_t)atoll(row->GetField(0));
5733                    if ( IsDebug() ) cout << "ID_TIMESYNC = "<<idtimesync<<endl;
5734                    
5735                    delete result;// mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
5736                    // ---------------------------------------------------------------------
5737                    // step 2: insert a new root file in GL_ROOT
5738                    // ---------------------------------------------------------------------
5739                    //
5740                    // check if the root file already exist
5741                    //
5742                    UInt_t id_root = 0;
5743                    oss.str("");
5744                    oss << "SELECT ID FROM GL_ROOT where NAME=\"" << gSystem->BaseName(name.Data()) <<"\";";
5745                    if ( IsDebug() ) cout << oss.str().c_str() << endl;
5746                    
5747                    result = conn->Query(oss.str().c_str());
5748                    if ( !result ) throw -4;;
5749                    if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5750                    if( result->GetRowCount() == 0){
5751                        if ( IsDebug() ) cout << " << Insert new ROOT file >> "<<endl;
5752                        // - - - - - - - - - - -
5753                        // insert new root file
5754                        // - - - - - - - - - - -
5755                        GL_ROOT glroot = GL_ROOT();            
5756                        glroot.ID_RAW      = id_raw;
5757                        glroot.ID_TIMESYNC = idtimesync;
5758                        //
5759                        // 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,
5760                        //             NOT STATIC NOT KEEPENV = $PAM_L0 must be used in the DB
5761                        //
5762                        if ( STATIC ){
5763                          glroot.PATH        = (TString)gSystem->ExpandPathName(path);
5764                        } else {
5765                          if ( KEEPENV ){
5766                            glroot.PATH      = path;
5767                          } else {
5768                            glroot.PATH      = "$PAM_L0";
5769                          };
5770                        };
5771                        //              glroot.PATH        = path;
5772                        glroot.NAME        = name;
5773                        //
5774                        insertPamelaRootFile( &glroot );
5775                        //              
5776                        id_root = glroot.ID;                    
5777                    }else{
5778                        row = result->Next();
5779                        if(row)id_root = (UInt_t)atoll(row->GetField(0));
5780                    }
5781                    if ( IsDebug() ) cout << "ID_ROOT = "<<id_root<<endl;
5782    
5783                    delete result;// mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
5784                    // ---------------------------------------------------------------------
5785                    // step 3: modify time-tag of corrupted GL_TRK_CALIB entry
5786                    // ---------------------------------------------------------------------
5787                    if ( IsDebug() ) cout << " << Modify time-tag of calibration ID="<<id<<" >> "<<endl;
5788                    oss.str("");
5789                    oss << " UPDATE GL_TRK_CALIB SET "  
5790                        << " TO_TIME=0 , FROM_TIME=0  WHERE "
5791                        << " ID = "<< id  << ";";
5792                    if ( IsDebug() ) cout << oss.str().c_str() << endl;
5793                    result = conn->Query(oss.str().c_str());
5794                    if ( !result ) throw -4;;
5795    
5796                    delete result; // mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
5797    
5798                    // ---------------------------------------------------------------------
5799                    // step 4: insert the new calibration:
5800                    // ---------------------------------------------------------------------
5801                    if ( IsDebug() ) cout << " << Insert new TRK calibration >> "<<endl;
5802                    //
5803                    GL_TRK_CALIB glcal = GL_TRK_CALIB();        
5804                    //
5805                    glcal.ID_ROOT_L0        = id_root;
5806                    glcal.EV_ROOT_CALIBTRK1 = this_t1;
5807                    glcal.EV_ROOT_CALIBTRK2 = this_t2;
5808                    glcal.FROM_TIME         = fromtime;
5809                    glcal.TO_TIME           = totime;
5810                    glcal.OBT1              = obt1;
5811                    glcal.OBT2              = obt2;
5812                    glcal.PKT1              = pkt1;
5813                    glcal.PKT2              = pkt1;
5814                    glcal.BOOT_NUMBER       = GetBOOTnumber();
5815                    glcal.VALIDATION        = this_valid;
5816                    //
5817                    HandleTRK_CALIB(&glcal);
5818                    if ( IsDebug() ) cout << "ID = "<<glcal.ID<<endl;
5819                    //
5820                    
5821                }
5822                if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
5823    
5824            }while(1);//end loop over calibrations
5825            
5826            
5827            if( rresult )delete rresult; // 10RED bug
5828            if( row    )delete row;
5829            
5830            
5831    
5832            
5833    
5834    
5835        }
5836    
5837    
5838    //      // ------------------------------
5839    //      // try to recover the calibration
5840    //      // ------------------------------
5841    //      cout << "TRY TO RECOVER TRACKER CALIBRATION"<<endl;
5842    //      //
5843    //      ULong64_t time  = 0; //absolute time
5844    //      string    path[100]; //mettere un limite massimo
5845    //      int       nrows = 0;
5846    //      UInt_t    pkt   = 0;
5847    //      UInt_t    obt   = 0;
5848    //      char     *type  = "";
5849    //      EventHeader *eh   = new EventHeader();
5850    //      CalibTrk1Event *c = new CalibTrk1Event();
5851            
5852    //       //
5853    //       if(which_is_not_valid==1 || which_is_not_valid==3){
5854    //        //
5855    //        cout << "PKT1 --> missing or corrupted "<<endl;
5856    //        type = "CalibTrk1";
5857    //        pkt  = pkt1;
5858    //        obt  = obt1;
5859    //        time = this->GetAbsTime(obt1);
5860    //        if( pkt1 == 0 ){//missing
5861    //            time = this->GetAbsTime(obt2);
5862    //            pkt  = pkt2-1;          
5863    //        }
5864    //        //
5865    //       }else if (which_is_not_valid==2 || which_is_not_valid==3){
5866    //        //
5867    //        cout << "PKT2--> missing or corrupted "<<endl;
5868    //        type = "CalibTrk2 ";
5869    //        pkt  = pkt2;
5870    //        obt  = obt2;
5871    //        time = this->GetAbsTime(obt2);
5872    //        if( pkt2 == 0 ){//missing
5873    //            time = this->GetAbsTime(obt1);
5874    //            pkt  = pkt1+1;          
5875    //        }
5876    //        //
5877    //       }else{
5878    //        cout << "this should not happen!!! "<<endl;
5879    //        trow -666;
5880    //       }
5881          
5882    //       nrows = Query_ROOT_TABLE(time,conn,path);// get the list of file which might contain the packet
5883          
5884    
5885    //       for(int r=0; r<nrows; r++){ //loop over rows
5886    //        if(path)cout << r << " >>>> "<<(path+r)->c_str() << endl;
5887    //        /// verifica che il file non sia quello gia` aperto
5888    //       }
5889    
5890    //       ////////////////////////////////////////////////////////////////////////
5891    
5892    //       TSQLResult *result = 0;
5893    //       TSQLRow    *row    = 0;
5894    //       //
5895    //       stringstream oss;
5896    //       oss.str("");
5897    //       // ----------------------------------------
5898    //       // read the id of last calibration inserted
5899    //       // ----------------------------------------
5900    //       oss.str("");
5901    //       oss << " SELECT ";
5902    //       oss << " (ID,ID_ROOT_L0,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,FROM_TIME,TO_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION) ";
5903    //       oss << " ORDER BY ID DESC LIMIT 1; ";
5904          
5905    //       result = conn->Query(oss.str().c_str());
5906    //       row = result->Next();
5907    //       if( !row )throw -666;
5908    
5909    //       if( result )delete result;
5910    //       if( row    )delete row;
5911    
5912    //       UInt_t id = (UInt_t)atoll(row->GetField(0));
5913    
5914    //       // -------------------------------------
5915    //       // ...and modify it with new parameters
5916    //       // -------------------------------------
5917          
5918    
5919    //   }
5920    //    //
5921    return(0);    return(0);
5922  };  };
# Line 4967  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6125  Int_t PamelaDBOperations::CleanGL_RUN_FR
6125      memset(myid,0,500*sizeof(UInt_t));      memset(myid,0,500*sizeof(UInt_t));
6126      //      //
6127      oss.str("");      oss.str("");
6128      oss << "SELECT ID,RUNTRAILER_TIME,RUNTRAILER_PKT,BOOT_NUMBER FROM GL_RUN_FRAGMENTS WHERE INSERT_TIME <= '" << clean_time->AsSQLString() << "'order BY RUNHEADER_TIME asc;";      oss << "SELECT ID,RUNTRAILER_TIME,RUNTRAILER_PKT,BOOT_NUMBER FROM GL_RUN_FRAGMENTS WHERE INSERT_TIME <= '" << clean_time->AsSQLString() << "' order BY RUNHEADER_TIME asc;";
6129      if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS runs older than %s : query is \n %s \n",clean_time->AsSQLString(),oss.str().c_str());      if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS runs older than %s : query is \n %s \n",clean_time->AsSQLString(),oss.str().c_str());
6130      nresult = conn->Query(oss.str().c_str());      nresult = conn->Query(oss.str().c_str());
6131      //      //
# Line 5061  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6219  Int_t PamelaDBOperations::CleanGL_RUN_FR
6219                    << " RM_ACQ_SETTING_MODE=" << glrun->GetRM_ACQ_SETTING_MODE()<< " , "                      << " RM_ACQ_SETTING_MODE=" << glrun->GetRM_ACQ_SETTING_MODE()<< " , "  
6220                    << " TRK_CALIB_USED=" << glrun->GetTRK_CALIB_USED()<< " , "                      << " TRK_CALIB_USED=" << glrun->GetTRK_CALIB_USED()<< " , "  
6221                    << " CAL_DSP_MASK=" << glrun->GetCAL_DSP_MASK()<< " , "                      << " CAL_DSP_MASK=" << glrun->GetCAL_DSP_MASK()<< " , "  
6222                    << " LAST_TIMESYNC=" << glrun->GetLAST_TIMESYNC()<< " , "                      << " LAST_TIMESYNC=" << glrun->GetLAST_TIMESYNC()<< " , ";
6223                    << " OBT_TIMESYNC=" << glrun->GetOBT_TIMESYNC()                //
6224                    << " WHERE ID=" << myid[u] << ";";                if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
6225                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12() << " , ";
6226                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
6227                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC() << " , ";
6228                  //              
6229                  oss << " OBT_TIMESYNC=" << glrun->GetOBT_TIMESYNC();
6230                  oss << " WHERE ID=" << myid[u] << ";";
6231                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
6232              };              };
6233              //              //
# Line 5074  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6238  Int_t PamelaDBOperations::CleanGL_RUN_FR
6238              for (UInt_t u=1; u <= nid ; u++){              for (UInt_t u=1; u <= nid ; u++){
6239                oss.str("");                oss.str("");
6240                oss << "UPDATE GL_RUN_FRAGMENTS SET "                oss << "UPDATE GL_RUN_FRAGMENTS SET "
6241                    << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , "                    << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , ";
6242                    << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "                //
6243                    << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT()<< ";";                if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
6244                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , ";
6245                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
6246                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , ";
6247                  //              
6248                  oss << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "
6249                      << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT();
6250                  oss << " WHERE ID=" << myid[u] << ";"; // BUG!!! 090112
6251                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
6252              };                  };    
6253            };            };
# Line 5098  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6269  Int_t PamelaDBOperations::CleanGL_RUN_FR
6269                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
6270                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "
6271                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< " , "                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< " , "
6272                    << " PKT_COUNTER=" << glrun->GetPKT_COUNTER()<< " , "                    << " PKT_COUNTER=" << glrun->GetPKT_COUNTER()<< " , ";
6273                    << " PKT_READY_COUNTER=" << glrun->GetPKT_READY_COUNTER()                //
6274                  if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
6275                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
6276                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) {
6277                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
6278                  //              
6279                  oss << " PKT_READY_COUNTER=" << glrun->GetPKT_READY_COUNTER()
6280                    << " WHERE ID=" << myid[u] << ";";                    << " WHERE ID=" << myid[u] << ";";
6281                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
6282              };              };
# Line 5112  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6289  Int_t PamelaDBOperations::CleanGL_RUN_FR
6289                oss.str("");                oss.str("");
6290                oss << "UPDATE GL_RUN_FRAGMENTS SET "                oss << "UPDATE GL_RUN_FRAGMENTS SET "
6291                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
6292                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , ";
6293                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< ";";                //
6294                  if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
6295                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
6296                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ){
6297                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
6298                  //              
6299                  oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT();
6300                  oss << " WHERE ID=" << myid[u] << ";"; // BUG!!! 090112
6301                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
6302              };                  };    
6303            };            };
# Line 5164  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6348  Int_t PamelaDBOperations::CleanGL_RUN_FR
6348                row2 = result2->Next();                row2 = result2->Next();
6349                //                //
6350                if ( row2 ){                if ( row2 ){
6351                  if ( IsDebug() ) printf(" The already exist in the GL_RUN table! \n");                  if ( IsDebug() ) printf(" The run already exists in the GL_RUN table! \n");
6352                  if ( PEDANTIC ) throw -83;                  if ( PEDANTIC ) throw -83;
6353                  row2->Close();                  row2->Close();
6354                };                };
# Line 5241  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6425  Int_t PamelaDBOperations::CleanGL_RUN_FR
6425        glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);          glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);  
6426        //        //
6427        oss.str("");        oss.str("");
6428        oss << " SELECT ID,NEVENTS,TRK_CALIB_USED,PKT_COUNTER FROM GL_RUN WHERE "        oss << " SELECT ID,NEVENTS,TRK_CALIB_USED,PKT_COUNTER,ID_ROOT_L0 FROM GL_RUN WHERE "
6429            << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND ("            << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND ("
6430            << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "            << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
6431            << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("            << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
# Line 5272  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6456  Int_t PamelaDBOperations::CleanGL_RUN_FR
6456          glrun->SetID_RUN_FRAG(glrun->GetID());          glrun->SetID_RUN_FRAG(glrun->GetID());
6457          glrun->Fill_GL_RUN(conn);            glrun->Fill_GL_RUN(conn);  
6458          //          //
6459  //      oss.str("");          //      oss.str("");
6460  //      oss << " SELECT ID FROM GL_RUN WHERE "          //      oss << " SELECT ID FROM GL_RUN WHERE "
6461  //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "          //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
6462  //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "          //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
6463  //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "          //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
6464  //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "          //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
6465  //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";          //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
6466  //      //          //      //
6467  //      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());
6468  //      result2 = conn->Query(oss.str().c_str());          //      result2 = conn->Query(oss.str().c_str());
6469  //      //          //      //
6470  //      if ( !result2 ) throw -4;          //      if ( !result2 ) throw -4;
6471  //      //          //      //
6472  //      row2 = result2->Next();          //      row2 = result2->Next();
6473  //      //          //      //
6474  //      if ( !row2 ) throw -25;          //      if ( !row2 ) throw -25;
6475  //      //          //      //
6476  //      oss.str("");          //      oss.str("");
6477  //      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);
6478  //      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());
6479  //      result2 = conn->Query(oss.str().c_str());          //      result2 = conn->Query(oss.str().c_str());
6480  //      //          //      //
6481  //      if ( !result2 ) throw -4;          //      if ( !result2 ) throw -4;
6482          //          //
6483          moved++;          moved++;
6484          //          //
6485        } else {        } else {
6486          if ( IsDebug() ) printf(" The already exist in the GL_RUN table! \n");  
6487          if ( PEDANTIC ) throw -83;          // questa parte mah mah mah... da controllare
6488    
6489            //
6490            // we end up here if chewbacca and we have RH---| small gap |---RT, in this case the two pieces are attached and moved to GL_RUN. We are now processing the
6491            // "small gap" piece... we recognize this since: we have two entries from this query, the pkt number is consistent with our pkt number.
6492            //
6493            // 090112 [8RED (-70): RUN ALREADY INSERTED]
6494            //
6495            Bool_t OK = false;
6496            UInt_t IDRL2A = 0;
6497            UInt_t IDRL2B = 0;
6498              if ( result2->GetRowCount() == 2 ){
6499                IDRL2A = (UInt_t)atoll(row2->GetField(0));
6500                UInt_t IDRL0A = (UInt_t)atoll(row2->GetField(4));
6501                row2 = result2->Next();
6502                IDRL2B = (UInt_t)atoll(row2->GetField(0));
6503                UInt_t IDRL0B = (UInt_t)atoll(row2->GetField(4));
6504                if ( IsDebug() ) printf(" IDRL0A %u B %u IDRL2A %u B %u \n",IDRL0A,IDRL0B,IDRL2A,IDRL2B);
6505                //      if ( IDRL0A == IDRL0B ){
6506    //            TSQLResult *result2a = 0;
6507    //            TSQLRow    *row2a    = 0;
6508    //            oss.str("");
6509    //            oss << "select PKT_NUMBER_FINAL from ROOT_TABLE_MERGING where REAL_TIME_INIT<" << chrtinit << " order by REAL_TIME_INIT desc limit 1;";
6510    //            if ( IsDebug() ) printf(" Check if we are in the case RH---| small gap |---RT: query is \n %s \n",oss.str().c_str());
6511    //            result2a = conn->Query(oss.str().c_str());
6512    //            //
6513    //            if ( !result2a ) throw -4;
6514    //            //
6515    //            row2a = result2a->Next();
6516    //            //
6517    //            if ( row2a ){
6518    //              UInt_t PKA = (UInt_t)atoll(row2a->GetField(0));
6519    //              delete result2a;
6520    //              oss.str("");
6521    //              oss << "select PKT_NUMBER_INIT from ROOT_TABLE_MERGING where REAL_TIME_INIT>" << chrtinit << " order by REAL_TIME_INIT asc limit 1;";
6522    //              if ( IsDebug() ) printf(" Check if we are in the case RH---| small gap |---RT: query is \n %s \n",oss.str().c_str());
6523    //              result2a = conn->Query(oss.str().c_str());
6524    //              //
6525    //              if ( !result2a ) throw -4;
6526    //              //
6527    //              row2a = result2a->Next();
6528    //              //
6529    //              if ( row2a ){
6530    //                UInt_t PKB = (UInt_t)atoll(row2a->GetField(0));
6531    //                //
6532    //                if ( IsDebug() ) printf(" PKT(PKA) + 1 %llu == runheaderpkt %llu && PKB = runtrailer %llu + 1 %llu \n",PKT(PKA)+1LL, PKT(glrun->GetRUNHEADER_PKT()),PKT(PKB), PKT(glrun->GetRUNTRAILER_PKT())+1LL);
6533    //                if ( PKT(PKA)+1LL == PKT(glrun->GetRUNHEADER_PKT()) && PKT(PKB) == PKT(glrun->GetRUNTRAILER_PKT())+1LL ){
6534    //                  if ( IsDebug() ) printf(" Ok, we are in the case: RH---| small gap |---RT \n");
6535                        OK = true;
6536                        //            };
6537                        //          };
6538                        //        };                  
6539                        //    };
6540              };      
6541            if ( OK ){
6542              //
6543              // this is the case in which we must insert a piece of run between two fragments in the GL_RUN table
6544              //
6545              // we have to update with runheader/trailer infos our run and we have to change the ROOT_ID_FRAG of the header piece ( 1/2 2/1 must become 1/3 3/2 2/1 )
6546              //
6547              GL_RUN *glA = new GL_RUN();
6548              glA->Query_GL_RUN(IDRL2A,conn);
6549              //
6550              if ( glA->GetACQ_BUILD_INFO() != 0 ){
6551                //
6552                // the first piece contains a good runheader we can update all the other runs with correct infos!
6553                //
6554                oss.str("");
6555                oss << "UPDATE GL_RUN_FRAGMENTS SET "
6556                    << " RUNHEADER_TIME=" << glA->GetRUNHEADER_TIME()<< " , "
6557                    << " RUNHEADER_OBT=" << glA->GetRUNHEADER_OBT()<< " , "
6558                    << " RUNHEADER_PKT=" << glA->GetRUNHEADER_PKT()<< " , "
6559                    << " COMPILATIONTIMESTAMP=" << glA->GetCOMPILATIONTIMESTAMP()<< " , "
6560                    << " FAV_WRK_SCHEDULE=" << glA->GetFAV_WRK_SCHEDULE()<< " , "
6561                    << " EFF_WRK_SCHEDULE=" << glA->GetEFF_WRK_SCHEDULE()<< " , "
6562                    << " PRH_VAR_TRG_MODE_A=" << glA->GetPRH_VAR_TRG_MODE_A()<< " , "
6563                    << " PRH_VAR_TRG_MODE_B=" << glA->GetPRH_VAR_TRG_MODE_B()<< " , "
6564                    << " ACQ_BUILD_INFO=" << glA->GetACQ_BUILD_INFO()<< " , "
6565                    << " ACQ_VAR_INFO=" << glA->GetACQ_VAR_INFO()<< " , "
6566                    << " RM_ACQ_AFTER_CALIB=" << glA->GetRM_ACQ_AFTER_CALIB()<< " , "  
6567                    << " RM_ACQ_SETTING_MODE=" << glA->GetRM_ACQ_SETTING_MODE()<< " , "  
6568                    << " TRK_CALIB_USED=" << glA->GetTRK_CALIB_USED()<< " , "  
6569                    << " CAL_DSP_MASK=" << glA->GetCAL_DSP_MASK()<< " , "  
6570                    << " LAST_TIMESYNC=" << glA->GetLAST_TIMESYNC()<< " , ";
6571                //
6572                if ( glA->GetPHYSENDRUN_MASK_S3S2S12() )
6573                  oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12() << " , ";
6574                if ( glA->GetPHYSENDRUN_MASK_S11CRC() )
6575                  oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC() << " , ";
6576                //        
6577                oss << " OBT_TIMESYNC=" << glA->GetOBT_TIMESYNC();
6578                oss << " WHERE ID=" << glrun->GetID() << ";";
6579                if ( IsDebug() ) printf(" update with correct infos: %s\n",oss.str().c_str());
6580                conn->Query(oss.str().c_str());    
6581                //
6582              } else {
6583                //
6584                // sig no runheader, let set anyway what is possible...
6585                //
6586                oss.str("");
6587                oss << "UPDATE GL_RUN_FRAGMENTS SET "
6588                    << " RUNHEADER_TIME=" << glA->GetRUNHEADER_TIME()<< " , ";
6589                //
6590                if ( glA->GetPHYSENDRUN_MASK_S3S2S12() )
6591                  oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , ";
6592                if ( glA->GetPHYSENDRUN_MASK_S11CRC() )
6593                  oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , ";
6594                //        
6595                oss << " RUNHEADER_OBT=" << glA->GetRUNHEADER_OBT()<< " , "
6596                    << " RUNHEADER_PKT=" << glA->GetRUNHEADER_PKT();
6597                oss << " WHERE ID=" << glrun->GetID() << ";";
6598                if ( IsDebug() ) printf(" update with correct infos2: %s\n",oss.str().c_str());
6599                conn->Query(oss.str().c_str());    
6600              };
6601              //
6602              // update runheader ROOT_ID_FRAG
6603              //
6604              oss.str("");
6605              oss << "UPDATE GL_RUN SET ID_RUN_FRAG = " << glrun->GetID() << " where ID = " << IDRL2A << ";";
6606              if ( IsDebug() ) printf(" update gl_run to have cross indexing: %s\n",oss.str().c_str());
6607              conn->Query(oss.str().c_str());
6608              //
6609              // now let's look for runtrailer if any in the last run
6610              //
6611              glA->Query_GL_RUN(IDRL2B,conn);
6612              //
6613              if ( glA->GetPKT_READY_COUNTER() != 0 ){
6614                //
6615                // the first piece contains a good runtrailer we can update all the other runs with correct infos!
6616                //
6617                oss.str("");
6618                oss << "UPDATE GL_RUN_FRAGMENTS SET "
6619                    << " RUNTRAILER_TIME=" << glA->GetRUNTRAILER_TIME()<< " , "
6620                    << " RUNTRAILER_OBT=" << glA->GetRUNTRAILER_OBT()<< " , "
6621                    << " RUNTRAILER_PKT=" << glA->GetRUNTRAILER_PKT()<< " , "
6622                    << " PKT_COUNTER=" << glA->GetPKT_COUNTER()<< " , ";
6623                //
6624                if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ){
6625                  oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
6626                if ( glA->GetPHYSENDRUN_MASK_S11CRC() ) {
6627                  oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
6628                //        
6629                oss << " PKT_READY_COUNTER=" << glA->GetPKT_READY_COUNTER()
6630                    << " WHERE ID=" << glrun->GetID() << ";";
6631                if ( IsDebug() ) printf(" update with correct trailer infos: %s\n",oss.str().c_str());
6632                conn->Query(oss.str().c_str());    
6633                //
6634              } else {
6635                //
6636                // sig no runtrailer, let set anyway what is possible...
6637                //
6638                oss.str("");
6639                oss << "UPDATE GL_RUN_FRAGMENTS SET "
6640                    << " RUNTRAILER_TIME=" << glA->GetRUNTRAILER_TIME()<< " , "
6641                    << " RUNTRAILER_OBT=" << glA->GetRUNTRAILER_OBT()<< " , ";
6642                  //
6643                if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ){
6644                  oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
6645                if ( glA->GetPHYSENDRUN_MASK_S11CRC() ){
6646                  oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
6647                //        
6648                oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()
6649                    << " WHERE ID=" << glrun->GetID() << ";";
6650                if ( IsDebug() ) printf(" update with correct trailer infos2: %s\n",oss.str().c_str());
6651                conn->Query(oss.str().c_str());    
6652              };
6653              //
6654              UInt_t myi = glrun->GetID();
6655              oss.str("");
6656              oss << " ID= "<< myi;
6657              //
6658              glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);  
6659              //
6660              // fill the new run in GL_RUN
6661              //
6662              glrun->SetID_RUN_FRAG(IDRL2B);
6663              glrun->Fill_GL_RUN(conn);    
6664              glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
6665              delete glA;
6666              moved++;
6667              //
6668            } else {
6669              //
6670              // is just a repetition
6671              //
6672              if ( IsDebug() ) printf(" The run %u is already present in the GL_RUN table...\n",glrun->GetID());    
6673              //      printf(" CCCCCCCCICCCCCCCCCCCCIOOOOOOOOOO si muove Ciccio! %u \n",glrun->GetID());
6674              //      if ( PEDANTIC && glrun->GetID() != 61563 ) throw -83;
6675              if ( PEDANTIC ) throw -83;
6676            };
6677            //      if ( IsDebug() ) printf(" The run already exists in the GL_RUN table! ...\n");
6678            //      if ( PEDANTIC ) throw -83;
6679        };        };
6680        if ( IsDebug() ) printf(" Delete run %s from the GL_RUN_FRAGMENTS table \n",row->GetField(0));              if ( IsDebug() ) printf(" Delete run %s from the GL_RUN_FRAGMENTS table \n",row->GetField(0));      
6681        //        //
6682        //        //
6683        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
6684  //      oss.str("");        //      oss.str("");
6685  //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);        //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);
6686  //       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());
6687  //       result2 = conn->Query(oss.str().c_str());        //       result2 = conn->Query(oss.str().c_str());
6688  //      //        //      //
6689  //      if ( !result2 ) throw -4;        //      if ( !result2 ) throw -4;
6690  //      //        //      //
6691        row = result->Next();        row = result->Next();
6692      };      };
6693    };    };
# Line 5366  Int_t PamelaDBOperations::ValidateRuns(T Line 6741  Int_t PamelaDBOperations::ValidateRuns(T
6741      // 2) get the OBT of the last validated run      // 2) get the OBT of the last validated run
6742      // --------------------------------------------------------------      // --------------------------------------------------------------
6743      oss.str("");      oss.str("");
6744      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
6745        oss << " SELECT * FROM GL_RUN  WHERE VALIDATION>0 AND RUNHEADER_TIME<="<< t_start
6746          <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";          <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
6747      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());
6748      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
# Line 5457  Int_t PamelaDBOperations::ValidateRuns(T Line 6833  Int_t PamelaDBOperations::ValidateRuns(T
6833    GL_RUN* this_run = new GL_RUN();    GL_RUN* this_run = new GL_RUN();
6834    GL_RUN* next_run = new GL_RUN();    GL_RUN* next_run = new GL_RUN();
6835    Int_t   nseq_max = 1000;    Int_t   nseq_max = 1000;
6836  //  UInt_t* sequence = new UInt_t[100];    //  UInt_t* sequence = new UInt_t[100];
6837    vector<UInt_t> sequence(nseq_max);    vector<UInt_t> sequence(nseq_max);
6838    Int_t   nseq = 0;    Int_t   nseq = 0;
6839    Bool_t CHECK = false;    Bool_t CHECK = false;
# Line 5472  Int_t PamelaDBOperations::ValidateRuns(T Line 6848  Int_t PamelaDBOperations::ValidateRuns(T
6848    // ---------------------------------------------------------------------------------    // ---------------------------------------------------------------------------------
6849    while(1){    while(1){
6850                        
6851            row = result->Next();      row = result->Next();
6852            if( row == NULL ) break;      if( row == NULL ) break;
6853                        
6854            //------------      //------------
6855            //get run info      //get run info
6856            //------------      //------------
6857            this_run->Set_GL_RUN(row);      this_run->Set_GL_RUN(row);
6858                                        
6859            Bool_t this_BAD = false;      Bool_t this_BAD = false;
6860            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;
6861            else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;      else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;
6862            else{      else{
6863  //                printf("Missing or corrupted header!! \n");        //                  printf("Missing or corrupted header!! \n");
6864                    this_ONLINE = false;        this_ONLINE = false;
6865                    this_BAD = true;        this_BAD = true;
6866            };      };
6867    
6868            //-----------------------------------      //-----------------------------------
6869            //compare with previous(next in time)      //compare with previous(next in time)
6870            //-----------------------------------      //-----------------------------------
6871            CHECK = false;      CHECK = false;
6872            UInt_t interval=0;      UInt_t interval=0;
6873                        
6874            if( nrow != 0){      if( nrow != 0){
6875                    
6876                                        
6877                    t1 = this_run->GetRUNTRAILER_TIME();        t1 = this_run->GetRUNTRAILER_TIME();
6878                    t2 = next_run->GetRUNHEADER_TIME();        t2 = next_run->GetRUNHEADER_TIME();
6879                    interval = (t2-t1);        interval = (t2-t1);
6880                                        
6881                    if(this_ONLINE && next_ONLINE){                               // this: ON-LINE + next: ON-LINE        if(this_ONLINE && next_ONLINE){                           // this: ON-LINE + next: ON-LINE
6882                                                        
6883                            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
6884                                                        
6885                            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
6886                                                        
6887                            if( !CHECK && this_run->VALIDATION ){          if( !CHECK && this_run->VALIDATION ){
6888                                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);            //      for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
6889                                    nseq=0;            for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],this_run->VALIDATION);
6890                            }            nseq=0;
6891            }
6892                                        
6893                    }else if( !this_ONLINE && next_ONLINE) {              // this: DEFAULT + next:ON-LINE        }else if( !this_ONLINE && next_ONLINE) {          // this: DEFAULT + next:ON-LINE
6894                                                        
6895                            CHECK = true;          CHECK = true;
6896    
6897                    }else if( !next_ONLINE ){                                             // this:ANY + next:DEFAULT        }else if( !next_ONLINE ){                                         // this:ANY + next:DEFAULT
6898                                                        
6899                            assignVALIDATION(next_run->ID,true);          assignVALIDATION(next_run->ID,true);
6900                            nseq=0;          nseq=0;
6901                    }        }
6902            }      }
6903    
6904            //----------------------------      //----------------------------
6905            //check run sequence for calib      //check run sequence for calib
6906            //----------------------------      //----------------------------
6907            if( CHECK ){      if( CHECK ){
6908                    // check if calibration exists        // check if calibration exists
6909                    if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);        if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);
6910                    Bool_t MISSING = MissingTRK_CALIB(t1,t2);        //      Bool_t MISSING = MissingTRK_CALIB(t1,t2);
6911                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],!MISSING);        UInt_t MISSING = MissingTRK_CALIB(t1,t2);
6912                    nseq=0;        UInt_t val = 0;
6913            };        if ( MISSING == 1 ) val = 0;
6914            //--------------        if ( MISSING == 0 ) val = 1;
6915            //store run info        if ( MISSING == 2 ) val = 2;
6916            //--------------        for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],val);
6917            *next_run   = *this_run;        nseq=0;
6918            next_ONLINE = this_ONLINE;      };
6919            if( !this_BAD ){      //--------------
6920                    if(nseq < nseq_max){      //store run info
6921                            sequence[nseq] = this_run->ID;      //--------------
6922                            nseq++;      *next_run   = *this_run;
6923                    }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);      next_ONLINE = this_ONLINE;
6924            };      if( !this_BAD ){
6925          if(nseq < nseq_max){
6926            sequence[nseq] = this_run->ID;
6927            nseq++;
6928          }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);
6929        };
6930                        
6931            if ( IsDebug() ) printf("%i Run %u \n",nrow,this_run->ID);      if ( IsDebug() ) printf("%i Run %u \n",nrow,this_run->ID);
6932            nrow++;      nrow++;
6933                        
6934    };    };
6935    delete this_run;    delete this_run;
# Line 5561  Int_t PamelaDBOperations::ValidateRuns(T Line 6943  Int_t PamelaDBOperations::ValidateRuns(T
6943   * @param t2 To absolute time   * @param t2 To absolute time
6944   * @return true if there might be a missing calibration   * @return true if there might be a missing calibration
6945   */   */
6946  Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){  //Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
6947    UInt_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
6948                    
6949          GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();    GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();
6950                    
6951          // get the closest VALIDATED calibration before the run start (t2)    // get the closest calibration before the run start (t2)
6952          if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true);      //>>> missing    //  if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true);        //>>> missing
6953      if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(1);       //>>> missing
6954                    
6955          if ( trkcalib->TO_TIME  < t2 ) return(true);                                    //>>> missing    //  if ( trkcalib->TO_TIME  < t2 ) return(true);                                      //>>> missing
6956      if ( trkcalib->TO_TIME  < t2 ) return(1);                                     //>>> missing
6957                    
6958          //==============================================================    //==============================================================
6959          // Check is done first on the basis of time between calibration,    // Check is done first on the basis of time between calibration,
6960          // which should be equal to the time between ascending-nodes.    // which should be equal to the time between ascending-nodes.
6961          //==============================================================    //==============================================================
6962          if ( t2 - trkcalib->FROM_TIME > 5700) {    if ( t2 - trkcalib->FROM_TIME > 5700) {
6963                  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);
6964          //==============================================================      //==============================================================
6965          // there might be a missing calibration, due to:      // there might be a missing calibration, due to:
6966          // - MM full      // - MM full
6967          // - corrupted packets      // - corrupted packets
6968          // - loss of data      // - loss of data
6969          // 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
6970          //==============================================================      //==============================================================
6971                  Bool_t DOWNLOAD = false;      Bool_t DOWNLOAD = false;
6972                  // check if the calib was skipped becouse of download .... DA FARE!!      // check if the calib was skipped becouse of download .... DA FARE!!
6973                  if(DOWNLOAD)return(false);      //    if(DOWNLOAD)return(false);
6974        if(DOWNLOAD)return(0);
6975                                    
6976                  return(true);                                   //>>> missing      //    return(true);                                         //>>> missing
6977        return(1);                                  //>>> missing
6978                                    
6979          };    };
6980                    
6981          //==============================================================    //==============================================================
6982          // 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,
6983          // it is enough to say that there are no missing calibrations    // it is enough to say that there are no missing calibrations
6984          //==============================================================    //==============================================================
6985          // the long time interval bewteen runs might be due to download    // the long time interval bewteen runs might be due to download
6986          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);
6987          return(false);    if ( trkcalib->VALIDATION ) return(0);
6988      if ( IsDebug() )printf("Calibration is not validated... :-/ ==> OK but with VALIDATION=2! \n");
6989      return(2);
6990                    
6991  };  };
6992  /**  /**
# Line 5606  Bool_t PamelaDBOperations::MissingTRK_CA Line 6995  Bool_t PamelaDBOperations::MissingTRK_CA
6995   * @param validation true/false   * @param validation true/false
6996   */   */
6997  Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){  Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){
6998          TSQLResult *result = 0;    return(this->assignVALIDATION(idrun,(UInt_t)validation));
6999          stringstream oss;  }
7000          oss.str("");  
7001          oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";  Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, UInt_t validation){
7002          //    TSQLResult *result = 0;
7003  //      if ( IsDebug() )    stringstream oss;
7004  //      printf(" Set VALIDATION = %i for run %i \n",validation,idrun);    oss.str("");
7005          if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());    oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";
7006          result = conn->Query(oss.str().c_str());    //
7007          if ( !result ) throw -4;    //    if ( IsDebug() )
7008          return(0);    //    printf(" Set VALIDATION = %i for run %i \n",validation,idrun);
7009      if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());
7010      result = conn->Query(oss.str().c_str());
7011      if ( !result ) throw -4;
7012      return(0);
7013  }  }
7014    
7015    
# Line 5802  Int_t PamelaDBOperations::removeFile(TSt Line 7195  Int_t PamelaDBOperations::removeFile(TSt
7195    stringstream myquery;    stringstream myquery;
7196    //      //  
7197    myquery.str("");    myquery.str("");
7198    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() <<"';";
7199    //    //
7200    pResult = conn->Query(myquery.str().c_str());    pResult = conn->Query(myquery.str().c_str());
7201    //    //
# Line 5818  Int_t PamelaDBOperations::removeFile(TSt Line 7211  Int_t PamelaDBOperations::removeFile(TSt
7211    //    //
7212    this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));    this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));
7213    this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));    this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));
7214      UInt_t idtsy=(UInt_t)atoll(Row->GetField(2));
7215    //    //
7216    this->ValidationOFF();    this->ValidationOFF();
7217    //    //
# Line 5825  Int_t PamelaDBOperations::removeFile(TSt Line 7219  Int_t PamelaDBOperations::removeFile(TSt
7219    //    //
7220    this->RemoveRUNS();    this->RemoveRUNS();
7221    //    //
7222    this->RemoveFILES();    this->RemoveFILES(idtsy);
7223    //    //
7224    this->SetID_ROOT(0);    this->SetID_ROOT(0);
7225    this->SetID_RAW(0);    this->SetID_RAW(0);
# Line 6045  void PamelaDBOperations::RemoveRUNS(){ Line 7439  void PamelaDBOperations::RemoveRUNS(){
7439   * Rearrange calibration tables   * Rearrange calibration tables
7440   *   *
7441   **/   **/
7442  void PamelaDBOperations::RemoveFILES(){  void PamelaDBOperations::RemoveFILES(UInt_t idtsy){
7443    stringstream myquery;    stringstream myquery;
7444    //    //
7445    myquery.str("");    myquery.str("");
# Line 6055  void PamelaDBOperations::RemoveFILES(){ Line 7449  void PamelaDBOperations::RemoveFILES(){
7449    //    //
7450    conn->Query(myquery.str().c_str());    conn->Query(myquery.str().c_str());
7451    //    //
7452      myquery.str("");
7453      myquery << " DELETE FROM GL_ROOT WHERE ID=" <<this->GetID_ROOT() <<";";
7454      //
7455      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
7456      //
7457      conn->Query(myquery.str().c_str());  //
7458      //
7459      if ( !chewbacca ){
7460        myquery.str("");
7461        myquery << " DELETE FROM GL_TIMESYNC WHERE ID=" << idtsy <<";";
7462        //
7463        if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
7464        //
7465        conn->Query(myquery.str().c_str());
7466      };
7467      //
7468  };  };
7469    
7470  /**  /**
# Line 6259  void PamelaDBOperations::RemoveCALIBS(){ Line 7669  void PamelaDBOperations::RemoveCALIBS(){
7669   * Rearrange calibration tables   * Rearrange calibration tables
7670   *   *
7671   **/   **/
7672  UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh ){  UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh , TFile *file){
7673    
7674        if(!caltrk) return 0;
7675    
7676        if ( IsDebug() ) cout << "ValidateTrkCalib:"<<endl;
7677    
7678        UInt_t validate = 1;
7679      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};
7680      UInt_t timeaftercalib=120000; //2000;      UInt_t timeaftercalib=120000; //2000;
7681  //  ----------      TString classname = caltrk->GetName();
7682  //  Check CRCs  
7683  //  ----------  //  ----------------------------------
7684    //  Check CRCs and failed calibrations
7685    //  ----------------------------------
7686      for(Int_t ipkt=0; ipkt<6; ipkt++){      for(Int_t ipkt=0; ipkt<6; ipkt++){
7687          if( caltrk->crc_hcal[ipkt] )return 0; // :-(          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
7688          for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] )return 0; // :-(              if( caltrk->crc_hcal[ipkt] ){
7689    //              if(IsDebug())cout<<"(CRC Header)";
7690                    validate = 0;
7691                    if(IsDebug())cout <<endl<<" *** CRC *** (header DSPn "<<caltrk->DSPnumber[ipkt]<<")";
7692            
7693                }
7694                for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] ){
7695    //              if(IsDebug())cout<<"(CRC Pkt-"<<ilad<<")";
7696                    if(IsDebug())cout <<endl<<" *** CRC *** (data DSPn "<<caltrk->DSPnumber[ipkt]<<" ladder "<<ilad<<")";
7697                    validate = 0;
7698                }
7699                if( !(caltrk->ncalib_event[ipkt]==0 && caltrk->cal_flag[ipkt]==0) ){
7700                    if(IsDebug())cout <<endl<<" *** FAILURE ***     (data DSPn "<<caltrk->DSPnumber[ipkt]<<")";
7701                    validate = 0;
7702                }
7703            }else{
7704    //          validate=0;
7705                if(IsDebug())cout <<endl<<" *** DSPn *** ("<< caltrk->DSPnumber[ipkt] <<" @pkt "<<ipkt<<")";
7706            }
7707      }      }
7708    
7709  //  -----------------------  //  -----------------------
7710  //  Check missing packets:  //  Check missing packets:
7711  //  -----------------------  //  -----------------------
# Line 6295  UInt_t PamelaDBOperations::ValidateTrkCa Line 7731  UInt_t PamelaDBOperations::ValidateTrkCa
7731  //  Check if it is first or second calibration packet  //  Check if it is first or second calibration packet
7732  //  -------------------------------------------------  //  -------------------------------------------------
7733      UInt_t build=0;      UInt_t build=0;
     TString classname = caltrk->GetName();  
7734      UInt_t base=0;      UInt_t base=0;
7735      UInt_t mask=0;      UInt_t mask=0;
7736      if(classname.Contains("CalibTrk1Event")){      if(classname.Contains("CalibTrk1Event")){
# Line 6306  UInt_t PamelaDBOperations::ValidateTrkCa Line 7741  UInt_t PamelaDBOperations::ValidateTrkCa
7741          base=18;          base=18;
7742          mask=0xFC0000;          mask=0xFC0000;
7743      }      }
7744  //  -------------------------------------------------  //  ----------------------------------------------------
7745  //  Count number of packets and set build variable  //  Count number of valid packets and set build variable
7746  //  -------------------------------------------------  //  ----------------------------------------------------
7747        if(IsDebug())cout <<endl<< " DSP: ";
7748      Int_t  npkts=0;      Int_t  npkts=0;
7749      for(Int_t ipkt=0; ipkt<6; ipkt++){      for(Int_t ipkt=0; ipkt<6; ipkt++){
7750          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
7751                if(IsDebug())cout <<" "<<caltrk->DSPnumber[ipkt];
7752              npkts++;              npkts++;
7753              build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );              build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );
7754          }  //          cout << caltrk->DSPnumber[ipkt]
7755            };
7756      }      }
7757  //    if( npkts==6 )return 1; // :-)      if(IsDebug())cout << " ==> "<< hex << build << dec;
7758    //  ----------------------------------------------------
7759  //    cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime()<<endl;  //  If the number of valid packets is 6, ok exit...
7760    //  ----------------------------------------------------
7761  //  -----------------------------------------------      if( npkts==6 ){
7762  //  If missing packets: check the acq configuration          return validate; // exit
7763        }
7764    ////////////////////////////////////////////////////////
7765    //  ...otherwise there might be some missing packets
7766    //
7767    //  In this case check the acq configuration
7768  //  (some DSPs might be excluded from acquisition)  //  (some DSPs might be excluded from acquisition)
7769  //  -----------------------------------------------  ////////////////////////////////////////////////////////
7770    
7771        if(!eh || !file || (file&&file->IsZombie()) ){
7772            if ( IsDebug() )cout << " *** MISSING VIEW *** eh="<<eh<<" file="<<file<<" cannot validate"<<endl;
7773            return (0);
7774        }
7775        
7776  //  -----------------------------------------------  //  -----------------------------------------------
7777  //  retrieve the first run header after calib  //  retrieve the first run header after calib
7778  //  -----------------------------------------------  //  -----------------------------------------------
7779       PacketType *pctp;      
7780       EventCounter *cod;      PacketType *pctp;
7781       cod = eh->GetCounter();      EventCounter *cod;
7782       Int_t irun = cod->Get(pctp->RunHeader);      cod = eh->GetCounter();
7783       TTree *rh=(TTree*)file->Get("RunHeader");      Int_t irun = cod->Get(pctp->RunHeader);
7784       if ( !rh || rh->IsZombie() ) throw -17;      TTree *rh=(TTree*)file->Get("RunHeader");
7785       if( rh->GetEntries() == irun ){      if ( !rh || rh->IsZombie() ) throw -17;
7786            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (1)  -- cannot validate :-( "<<endl;      if( rh->GetEntries() <= irun ){
7787           return 0; // :-(          if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (1) -- cannot validate :-( "<<endl;
7788       }          return 0; // :-(
7789        }
7790       RunHeaderEvent *run  = 0;      RunHeaderEvent *run  = 0;
7791       EventHeader    *hrun = 0;      EventHeader    *hrun = 0;
7792       rh->SetBranchAddress("RunHeader", &run);      rh->SetBranchAddress("RunHeader", &run);
7793       rh->SetBranchAddress("Header", &hrun);      rh->SetBranchAddress("Header", &hrun);
7794       rh->GetEntry(irun);      rh->GetEntry(irun);    
7795  //     cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime() << " Run " << hrun->GetPscuHeader()->GetOrbitalTime() <<endl;      if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){
7796            if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (2) -- cannot validate :-( "<<endl;
7797       if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){          return 0; // :-(
7798            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (2) -- cannot validate :-( "<<endl;      }
7799           return 0; // :-(  
7800       }      UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());
7801            if( dtime > timeaftercalib ){
7802       if( !run->RM_ACQ_AFTER_CALIB ){          if ( IsDebug() ) cout << " *** MISSING-PKT *** run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;
7803            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) RM_ACQ_AFTER_CALIB=0    -- cannot validate :-( "<<endl;          return 0; // :-(
7804           return 0; // :-(      }
7805       }  
7806        if ( IsDebug() ) cout <<endl<< " ACQ_BUILD_INFO ==> "<<hex<<(run->ACQ_BUILD_INFO & mask)<<dec;
7807       UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());  
7808       if( dtime > timeaftercalib ){      if( (run->ACQ_BUILD_INFO & mask) != build ){
7809           if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;          validate=0; // :-(
7810           return 0; // :-(          cout <<endl<< " *** MISSING-PKT *** packet mismatch: ACQ_BUILD_INFO="<<hex<<(run->ACQ_BUILD_INFO&mask)<<" != "<<build<<dec;
7811       }      };
7812        
7813        return validate;
7814    
      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; // :-)  
7815    
7816  }  }
7817    
# Line 6378  UInt_t PamelaDBOperations::ValidateTrkCa Line 7821  UInt_t PamelaDBOperations::ValidateTrkCa
7821   *   *
7822   **/   **/
7823  UInt_t PamelaDBOperations::Check(){  UInt_t PamelaDBOperations::Check(){
7824          return(this->Check(0,0));    return(this->Check(0,0));
7825  }  }
7826    
7827  UInt_t PamelaDBOperations::Check(UInt_t from, UInt_t to){  UInt_t PamelaDBOperations::Check(UInt_t from, UInt_t to){
7828    //    //
7829          if ( IsDebug() ) printf(" from %u to %u \n",from,to);    if ( IsDebug() ) printf(" from %u to %u \n",from,to);
7830    //    //
7831    UInt_t test = 0;    UInt_t test = 0;
7832    //    //
# Line 6424  UInt_t PamelaDBOperations::Check(UInt_t Line 7867  UInt_t PamelaDBOperations::Check(UInt_t
7867      //      //
7868      if ( from > 0 && nid <= from ) goto ss;      if ( from > 0 && nid <= from ) goto ss;
7869      if ( to > 0 && nid >= to ) goto ss;      if ( to > 0 && nid >= to ) goto ss;
7870  //      //
7871      if ( (UInt_t)atoll(row->GetField(4)) > 1 ){      if ( (UInt_t)atoll(row->GetField(4)) > 1 ){
7872        //        //
7873        //        //
# Line 6455  UInt_t PamelaDBOperations::Check(UInt_t Line 7898  UInt_t PamelaDBOperations::Check(UInt_t
7898              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)));  
7899              row3 = result3->Next();              row3 = result3->Next();
7900            };            };
7901  //      delete result3;            //    delete result3;
7902    
7903          };          };
7904          //          //
# Line 6476  UInt_t PamelaDBOperations::Check(UInt_t Line 7919  UInt_t PamelaDBOperations::Check(UInt_t
7919              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)));
7920              row3 = result3->Next();              row3 = result3->Next();
7921            };            };
7922  //      delete result3;            //    delete result3;
7923          };          };
7924          //          //
7925          oss.str("");          oss.str("");
# Line 6496  UInt_t PamelaDBOperations::Check(UInt_t Line 7939  UInt_t PamelaDBOperations::Check(UInt_t
7939              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)));
7940              row3 = result3->Next();              row3 = result3->Next();
7941            };            };
7942   //     delete result3;            //    delete result3;
7943    
7944          };          };
7945        };        };
# Line 6517  UInt_t PamelaDBOperations::Check(UInt_t Line 7960  UInt_t PamelaDBOperations::Check(UInt_t
7960            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)));
7961            row3 = result3->Next();            row3 = result3->Next();
7962          };          };
7963  //      delete result3;          //      delete result3;
7964        };        };
7965        //        //
7966      };      };
# Line 6543  UInt_t PamelaDBOperations::Check(UInt_t Line 7986  UInt_t PamelaDBOperations::Check(UInt_t
7986        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
7987        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7988        test = 1;        test = 1;
7989  //      delete result2;        //        delete result2;
7990      };      };
7991      //      //
7992      if ( (thisrtt < prevrht) && (thisrht != prevrht) ){      if ( (thisrtt < prevrht) && (thisrht != prevrht) ){
# Line 6565  UInt_t PamelaDBOperations::Check(UInt_t Line 8008  UInt_t PamelaDBOperations::Check(UInt_t
8008        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
8009        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
8010        test = 1;        test = 1;
8011  //      delete result2;        //        delete result2;
8012      };      };
8013      //      //
8014      if ( (thisrht > thisrtt) && (thisrht != prevrht) ){      if ( (thisrht > thisrtt) && (thisrht != prevrht) ){
# Line 6587  UInt_t PamelaDBOperations::Check(UInt_t Line 8030  UInt_t PamelaDBOperations::Check(UInt_t
8030        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
8031        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
8032        test = 1;        test = 1;
8033  //      delete result2;        //        delete result2;
8034      };      };
8035  ss:    ss:
8036      //      //
8037      prevrht = thisrht;      prevrht = thisrht;
8038      prevrtt = thisrtt;      prevrtt = thisrtt;
8039      previd = thisid;      previd = thisid;
8040      prevl0id = thisl0id;      prevl0id = thisl0id;
8041      row = result->Next();      row = result->Next();
8042  //    if ( result2 ) delete result2;      //    if ( result2 ) delete result2;
8043  //    if ( result3 ) delete result3;      //    if ( result3 ) delete result3;
8044    };    };
8045    //    //
8046    return(test);    return(test);

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

  ViewVC Help
Powered by ViewVC 1.1.23