/[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.39 by mocchiut, Tue Oct 14 12:59:14 2014 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-"<< (float)chlastts <<")<50000 AND ABS(REAL_TIME_INIT-"<< atof(row2->GetField(10)) <<")<50000 group by BOOT_NUMBER order by BOOT_NUMBER asc;"; // even more relaxed conditions... 091214 [9REDtest3: error -29] // 10RED MYSQL operators BUG:
230                  /*
231    
232    mysql> select CAST(1322000646 AS UNSIGNED INTEGER)-1322017203.;
233    +--------------------------------------------------+
234    | CAST(1322000646 AS UNSIGNED INTEGER)-1322017203. |
235    +--------------------------------------------------+
236    |                                           -16557 |
237    +--------------------------------------------------+
238    1 row in set (0.06 sec)
239    
240    mysql> select CAST(1322000646 AS UNSIGNED INTEGER)-1322017203;
241    +-------------------------------------------------+
242    | CAST(1322000646 AS UNSIGNED INTEGER)-1322017203 |
243    +-------------------------------------------------+
244    |                            18446744073709535059 |
245    +-------------------------------------------------+
246    1 row in set (0.02 sec)
247    
248                  */
249                  if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
250                  result3 = conn->Query(qu.str().c_str());
251                  if ( result3 ){
252                    row3 = result3->Next();
253                    if ( row3 && result3->GetRowCount() == 1 ){
254                      chboot = (UInt_t)atoll(row3->GetField(0));
255                      if ( debug ) printf(" Found boot_number = %u \n",chboot);
256                    } else {
257                      if ( debug ) printf(" AGH CANNOT DETERMINE THE BOOT NUMBER... \n");
258                      throw -29;
259                    };
260                  };
261                };
262              };
263              //
264            chpktinit = (UInt_t)atoll(row2->GetField(6));            chpktinit = (UInt_t)atoll(row2->GetField(6));
265            chpktfinal = (UInt_t)atoll(row2->GetField(7));            chpktfinal = (UInt_t)atoll(row2->GetField(7));
266            chobtinit = (UInt_t)atoll(row2->GetField(8));            chobtinit = (UInt_t)atoll(row2->GetField(8));
# Line 182  void PamelaDBOperations::OpenL0File(TStr Line 273  void PamelaDBOperations::OpenL0File(TStr
273          throw -85;          throw -85;
274        };        };
275        filerootname = chpath + chfile;// + ".root";        filerootname = chpath + chfile;// + ".root";
       if ( debug ) printf(" chewbacca: filename is %s \n",filerootname.Data());  
276      };      };
277      this->SetRootName(filerootname);      this->SetRootName(filerootname);
     file = TFile::Open(this->GetRootName().Data());  
   } else {  
     this->SetRootName("");  
278    };    };
279      if ( debug ) printf(" Filename is %s \n",filerootname.Data());
280      file = TFile::Open(this->GetRootName().Data());
281      //  } else {
282      //    this->SetRootName("");
283      //    this->SetRootName(filerootname);
284      //  };
285  }  }
286    
287  //  //
# Line 388  void PamelaDBOperations::SetOrbitNo(UInt Line 481  void PamelaDBOperations::SetOrbitNo(UInt
481      return;      return;
482    };    };
483    //    //
484    TString name = this->GetRootFile();    if ( !chewbacca ){
485    Int_t nlength = name.Length();      TString name = this->GetRootFile();
486    if ( nlength < 5 ) return;      Int_t nlength = name.Length();
487    TString dwo = 0;      if ( nlength < 5 ){
488    for (Int_t i = 0; i<5; i++){        if ( IsDebug() ) printf(" Agh problems determining the orbit number! name = %s \n",name.Data());
489      dwo.Append(name[i],1);        return;
490    };      };
491    if ( dwo.IsDigit() ){      TString dwo = "";
492      dworbit = (UInt_t)dwo.Atoi();      for (Int_t i = 0; i<5; i++){
   } else {  
     dwo="";  
     for (Int_t i = 8; i<13; i++){  
493        dwo.Append(name[i],1);        dwo.Append(name[i],1);
494      };          };
495      if ( dwo.IsDigit() ) dworbit = (UInt_t)dwo.Atoi();      if ( dwo.IsDigit() ){
496          dworbit = (UInt_t)dwo.Atoi();
497        } else {
498          dwo="";
499          for (Int_t i = 8; i<13; i++){
500            dwo.Append(name[i],1);
501          };    
502          if ( dwo.IsDigit() ) dworbit = (UInt_t)dwo.Atoi();
503        };
504        if ( IsDebug() ) printf(" Downlink orbit is %i (dwo = %s) \n",dworbit,dwo.Data());
505    };    };
   if ( IsDebug() ) printf(" Downlink orbit is %i (dwo = %s) \n",dworbit,dwo.Data());  
506    return;    return;
507  };  };
508    
# Line 435  TString PamelaDBOperations::GetRawPath() Line 533  TString PamelaDBOperations::GetRawPath()
533    
534  TString PamelaDBOperations::GetRootPath(){  TString PamelaDBOperations::GetRootPath(){
535    if ( STATIC ){    if ( STATIC ){
536      return((TString)gSystem->DirName(filerootname.Data())+'/');      return((TString)gSystem->DirName(this->GetRootName().Data())+'/');
537    } else {    } else {    
538      return((TString)gSystem->ExpandPathName("$PAM_L0")+'/');      if ( KEEPENV ){
539          return((TString)gSystem->ExpandPathName(gSystem->DirName(filerootname.Data()))+'/');
540        } else {
541          return((TString)gSystem->ExpandPathName("$PAM_L0")+'/');
542        };
543    };    };
544  };  };
545    
# Line 490  void PamelaDBOperations::SetCommonGLRUN( Line 592  void PamelaDBOperations::SetCommonGLRUN(
592  };  };
593    
594  /**  /**
595     *
596     * Set the variables which belogns to physendrun tree
597     *
598     */
599    void PamelaDBOperations::SetPhysEndRunVariables(){
600      //
601      //
602      //
603      TTree *T = 0;
604      T = (TTree*)file->Get("PhysEndRun");
605      if ( !T || T->IsZombie() ) throw -90;
606      //
607      PhysEndRunEvent *pher= 0;
608      EventHeader *eh = 0;
609      T->SetBranchAddress("PhysEndRun", &pher);
610      T->SetBranchAddress("Header", &eh);
611      //
612      UInt_t phobt = 0;
613      UInt_t phpkt = 0;
614      //
615      glrun->SetPHYSENDRUN_MASK_S3S2S12(0);
616      glrun->SetPHYSENDRUN_MASK_S11CRC(0);
617      //
618      for (Int_t p=0; p<T->GetEntries(); p++){
619        //
620        T->GetEntry(p);
621        //
622        phobt = (UInt_t)eh->GetPscuHeader()->GetOrbitalTime();
623        phpkt = (UInt_t)eh->GetPscuHeader()->GetCounter();
624        //
625        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())  ){
626          if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() || glrun->GetPHYSENDRUN_MASK_S11CRC() ){
627            if ( IsDebug() ) printf(" WARNING while looping in physendrun: found two PhysEndRun packet for the same RUN! \n");
628            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);
629            if ( PEDANTIC && IsDebug() ) printf(" ERROR while looping in physendrun: found two PhysEndRun packet for the same RUN!\n ");
630            if ( PEDANTIC ) throw -91;
631          } else {
632            glrun->SetPHYSENDRUN_MASK_S3S2S12((UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S3S2S12);
633            glrun->SetPHYSENDRUN_MASK_S11CRC((UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S11CRC);
634          };
635        };
636      };
637      //
638    };
639    
640    /**
641   * Patch, look for upper limits to avoid processing retransmitted data   * Patch, look for upper limits to avoid processing retransmitted data
642   */   */
643  Int_t PamelaDBOperations::SetUpperLimits(){  Int_t PamelaDBOperations::SetUpperLimits(){
# Line 603  Int_t PamelaDBOperations::SetUpperLimits Line 751  Int_t PamelaDBOperations::SetUpperLimits
751      UInt_t tjump = 50000;      UInt_t tjump = 50000;
752      //UInt_t tjump = 100;      //UInt_t tjump = 100;
753      while ( tjump > 0 ){      while ( tjump > 0 ){
754        pktlast = numeric_limits<UInt_t>::max();        //      pktlast = numeric_limits<UInt_t>::max();
755        while ( pktlast > chpktmax && (Int_t)(nevent-1-it) >= 0 ){        pktlast = chpktmax + 1;
756          while ( PKT(pktlast) > PKT(chpktmax) && (Int_t)(nevent-1-it) >= 0 ){
757          if ( (Int_t)(nevent-1-it) >= 0 ){          if ( (Int_t)(nevent-1-it) >= 0 ){
758            T->GetEntry(nevent-1-it);            T->GetEntry(nevent-1-it);
759            ph = eh->GetPscuHeader();            ph = eh->GetPscuHeader();
# Line 612  Int_t PamelaDBOperations::SetUpperLimits Line 761  Int_t PamelaDBOperations::SetUpperLimits
761          } else {          } else {
762            pktlast = chpktmax + 1;            pktlast = chpktmax + 1;
763          };          };
764          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));
765          it += tjump;          it += tjump;
766        };        };
767        if ( tjump > 1 ) it -= 2*tjump;        if ( tjump > 1 ) it -= 2*tjump;
# Line 636  Int_t PamelaDBOperations::SetUpperLimits Line 785  Int_t PamelaDBOperations::SetUpperLimits
785      tjump = 50000;      tjump = 50000;
786      //tjump = 100;      //tjump = 100;
787      while ( tjump > 0 ){      while ( tjump > 0 ){
788        pktlast = 0;        //      pktlast = 0;
789        while ( pktlast < chpktmin && it < (Int_t)nevent ){        pktlast = chpktmin - 1;
790          if ( debug ) printf("LLlook for down %i %i %llu %llu \n",it,pktlast,PKT(pktlast),PKT(chpktmin));
791          while ( PKT(pktlast) < PKT(chpktmin) && it < (Int_t)nevent ){
792          if ( it < (Int_t)nevent ){          if ( it < (Int_t)nevent ){
793            T->GetEntry(it);            T->GetEntry(it);
794            ph = eh->GetPscuHeader();            ph = eh->GetPscuHeader();
# Line 731  Int_t PamelaDBOperations::SetUpperLimits Line 882  Int_t PamelaDBOperations::SetUpperLimits
882      ph = eh->GetPscuHeader();      ph = eh->GetPscuHeader();
883      pktlast = ph->GetCounter();      pktlast = ph->GetCounter();
884      nevent = upperentry - chminentry;      nevent = upperentry - chminentry;
885        if ( ((Int_t)upperentry - (Int_t)chminentry) < 0 ) nevent = 0; // nevent is UInt_t! 090112 [8RED: error -88]
886        if ( IsDebug() ) printf(" Setting nevent to %u - upperentry %i chminentry %i \n",nevent,upperentry,chminentry);
887      //      //
888    } else {    } else {
889      upperpkt = PKT(pktlast);      upperpkt = PKT(pktlast);
# Line 739  Int_t PamelaDBOperations::SetUpperLimits Line 892  Int_t PamelaDBOperations::SetUpperLimits
892    };    };
893    //    //
894    if ( chewbacca && nevent < 1 ) {    if ( chewbacca && nevent < 1 ) {
895          pktfirst = chpktmin;      if ( IsDebug() ) printf(" chewbacca and no events in the file \n");
896          upperpkt = PKT(chpktmax);      pktfirst = chpktmin;
897          pktlast = chpktmax;      upperpkt = PKT(chpktmax);
898          obtfirst = chobtmin;      pktlast = chpktmax;
899          obtlast = chobtmax;      obtfirst = chobtmin;
900          upperobt = OBT(chobtmax);      obtlast = chobtmax;
901        upperobt = OBT(chobtmax);
902    };    };
903    //    //
904    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 906  Int_t PamelaDBOperations::SetUpperLimits
906    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);
907    //    //
908    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)) ){
909          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));
910          if ( PEDANTIC ) throw -88;      if ( PEDANTIC ) throw -88;
911          return(32);      return(32);
912    };    };
913    //    //
914    if ( !nevent ) return(64);    if ( !nevent ) return(64);
# Line 764  Int_t PamelaDBOperations::SetUpperLimits Line 918  Int_t PamelaDBOperations::SetUpperLimits
918    //  if ( nevent < jump ) jump = int(nevent/10);    //  if ( nevent < jump ) jump = int(nevent/10);
919    //  if ( !jump ) jump = 1;    //  if ( !jump ) jump = 1;
920    //    //
921    if ( (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) || (labs(PKT(pktlast)-PKT(pktfirst))<deltapkt && labs(OBT(obtlast)-OBT(obtfirst))<deltaobt) && nevent > deltapkt ){  
922      if ( ((PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) || (labs(PKT(pktlast)-PKT(pktfirst))<deltapkt && labs(OBT(obtlast)-OBT(obtfirst))<deltaobt)) && nevent > deltapkt ){
923      //      //
924      if ( IsDebug() ) printf(" starting jump %i \n",jump);      if ( IsDebug() ) printf(" starting jump %i \n",jump);
925      //    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 1195  Int_t PamelaDBOperations::SetUpperLimits
1195          upperpkt = pkth;          upperpkt = pkth;
1196          upperobt = obth;          upperobt = obth;
1197          rhev = lasthead+1;          rhev = lasthead+1;
1198      } else {        } else {
1199          rhev = lasthead;          rhev = lasthead;
1200        };        };
1201        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 1234  UInt_t PamelaDBOperations::AssignRunID()
1234    stringstream   oss;    stringstream   oss;
1235    //      //  
1236    oss.str("");    oss.str("");
1237    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.
1238        if ( !strcmp(tag.Data(),"NONE") ){
1239          oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< chiby.Data() <<"');";
1240        } else {
1241          oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< tag.Data() <<"');";
1242        };
1243      } else {
1244        oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< tag.Data() <<"');";
1245      };
1246    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1247    if ( !result ) throw -10;    if ( !result ) throw -10;
1248    oss.str("");    oss.str("");
# Line 1203  void PamelaDBOperations::CheckConnection Line 1366  void PamelaDBOperations::CheckConnection
1366    stringstream oss;    stringstream oss;
1367    //      //  
1368    oss.str("");    oss.str("");
1369    oss << "SET time_zone='+0:00';";    oss << "SET time_zone='+0:00'; SET sql_mode = 'NO_UNSIGNED_SUBTRACTION';";
1370    TSQLResult *result = 0;    TSQLResult *result = 0;
1371    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1372    if ( !result ) throw -10;    if ( !result ) throw -10;
# Line 1227  void PamelaDBOperations::LockTables(){   Line 1390  void PamelaDBOperations::LockTables(){  
1390    stringstream oss;    stringstream oss;
1391    //      //  
1392    oss.str("");    oss.str("");
1393    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;";
1394    TSQLResult *result = 0;    TSQLResult *result = 0;
1395    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1396    if ( !result ) throw -10;    if ( !result ) throw -10;
# Line 1260  void PamelaDBOperations::UnLockTables(){ Line 1423  void PamelaDBOperations::UnLockTables(){
1423   */   */
1424  Long64_t PamelaDBOperations::PKT(UInt_t pkt_num){    Long64_t PamelaDBOperations::PKT(UInt_t pkt_num){  
1425    //    //
1426  //  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));
1427    //    //
1428    if ( pkt_num < (ppktfirst/2) && ppktfirst > (16777214/2)  ){    if ( pkt_num < (ppktfirst/2) && ppktfirst > (16777214/2)  ){
1429  //    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);
1430      return((Long64_t)pkt_num+16777215LL);      return((Long64_t)pkt_num+16777215LL);
1431    };    };
1432    //    //
1433    if ( pkt_num > ((Long64_t)ppktfirst*2) && pkt_num > (16777214/2) ){    if ( pkt_num > ((Long64_t)ppktfirst*2) && pkt_num > (16777214/2) ){
1434  //    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);
1435      return((Long64_t)pkt_num-16777215LL);      return((Long64_t)pkt_num-16777215LL);
1436    };    };
1437    //    //
1438  //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)pkt_num);    //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)pkt_num);
1439    return((Long64_t)pkt_num);    return((Long64_t)pkt_num);
1440    //    //
1441  };  };
# Line 1282  Long64_t PamelaDBOperations::PKT(UInt_t Line 1445  Long64_t PamelaDBOperations::PKT(UInt_t
1445   */   */
1446  Long64_t PamelaDBOperations::OBT(UInt_t obt){    Long64_t PamelaDBOperations::OBT(UInt_t obt){  
1447    //    //
1448  //  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));
1449    //    //
1450    if ( obt < (pobtfirst/2) && pobtfirst > (numeric_limits<UInt_t>::max()/2) ){    if ( obt < ((Long64_t)pobtfirst/2) && pobtfirst > (numeric_limits<UInt_t>::max()/2) ){
1451  //    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());
1452      return((Long64_t)obt+(Long64_t)numeric_limits<UInt_t>::max());      return((Long64_t)obt+(Long64_t)numeric_limits<UInt_t>::max());
1453    };    };
1454    //    //
1455    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) ){
1456  //    if ( IsDebug() ) printf(" pobtfirst*2 %lld \n",((Long64_t)pobtfirst*2));      //    if ( IsDebug() ) printf(" pobtfirst*2 %lld \n",((Long64_t)pobtfirst*2));
1457  //    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());
1458      return((Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());      return((Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());
1459    };    };
1460    //    //
1461  //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)obt);    //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)obt);
1462    return((Long64_t)obt);    return((Long64_t)obt);
1463  };  };
1464    
# Line 1331  void PamelaDBOperations::FillClass(Bool_ Line 1494  void PamelaDBOperations::FillClass(Bool_
1494    UInt_t lastPkt = 0;    UInt_t lastPkt = 0;
1495    UInt_t rhtime = 0;    UInt_t rhtime = 0;
1496    UInt_t rttime = 0;    UInt_t rttime = 0;
1497      //
1498      if ( IsDebug() ) printf(" A firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1499      //
1500    if ( !mishead ){    if ( !mishead ){
1501      codh = ehh->GetCounter();      codh = ehh->GetCounter();
1502      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1) ){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){      
1503          if ( IsDebug() ) printf(" B firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1504        firstev = 1;        firstev = 1;
1505        lastev = 0;        lastev = 0;
1506      } else {      } else {
# Line 1346  void PamelaDBOperations::FillClass(Bool_ Line 1513  void PamelaDBOperations::FillClass(Bool_
1513    };    };
1514    if ( !mistrail ){    if ( !mistrail ){
1515      codt = eht->GetCounter();      codt = eht->GetCounter();
1516      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1)){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1)){      
1517          if ( IsDebug() ) printf(" C firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1518        lastev = 0;        lastev = 0;
1519        firstev = lastev+1;        firstev = lastev+1;
1520      } else {      } else {
# Line 1363  void PamelaDBOperations::FillClass(Bool_ Line 1531  void PamelaDBOperations::FillClass(Bool_
1531    if ( mishead ) {    if ( mishead ) {
1532      glrun->Set_GL_RUNH0();      glrun->Set_GL_RUNH0();
1533      //      //
1534      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1) ){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){      
1535        firstObt = lastObt;        firstObt = lastObt;
1536        firstPkt = lastPkt;        firstPkt = lastPkt;
1537        rhtime = rttime;        rhtime = rttime;
# Line 1382  void PamelaDBOperations::FillClass(Bool_ Line 1550  void PamelaDBOperations::FillClass(Bool_
1550    if ( mistrail ){    if ( mistrail ){
1551      glrun->Set_GL_RUNT0();      glrun->Set_GL_RUNT0();
1552      //      //
1553      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1) ){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){      
1554        lastObt = firstObt;        lastObt = firstObt;
1555        lastPkt = firstPkt;        lastPkt = firstPkt;
1556        rttime = rhtime;        rttime = rhtime;
# Line 1398  void PamelaDBOperations::FillClass(Bool_ Line 1566  void PamelaDBOperations::FillClass(Bool_
1566      glrun->SetRUNTRAILER_PKT(lastPkt);      glrun->SetRUNTRAILER_PKT(lastPkt);
1567      //          //    
1568    };    };
1569      //
1570      // ad hoc solution for INF EV_TO [8RED] 090113
1571      //
1572      if ( !firstev && lastev == -1 ){
1573        if ( IsDebug() ) printf(" EE firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1574        firstev = 1;
1575        lastev = 0;
1576      };
1577    glrun->SetEV_FROM((UInt_t)firstev);    glrun->SetEV_FROM((UInt_t)firstev);
1578    glrun->SetEV_TO((UInt_t)lastev);    glrun->SetEV_TO((UInt_t)lastev);
1579    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 1581  void PamelaDBOperations::FillClass(Bool_
1581    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);
1582    //    //
1583    this->SetCommonGLRUN(rhtime,rttime);    this->SetCommonGLRUN(rhtime,rttime);
1584      this->SetPhysEndRunVariables();
1585    //    //
1586  };  };
1587    
# Line 1416  void PamelaDBOperations::FillClass(Bool_ Line 1593  void PamelaDBOperations::FillClass(Bool_
1593   * Insert a new row into GL_RAW table.   * Insert a new row into GL_RAW table.
1594   */   */
1595  Int_t PamelaDBOperations::insertPamelaRawFile(){  Int_t PamelaDBOperations::insertPamelaRawFile(){
1596    
1597        //
1598        Bool_t idr =  this->SetID_RAW();
1599        if ( idr ) return(1);
1600    
1601        GL_RAW glraw = GL_RAW();
1602        
1603        glraw.PATH = GetRawPath();
1604        glraw.NAME = GetRawFile();
1605        //    glraw.BOOT_NUMBER = 0;//???
1606        glraw.BOOT_NUMBER = this->GetBOOTnumber();
1607        
1608        if( insertPamelaRawFile(&glraw) )return(1);
1609        //
1610        idr =  this->SetID_RAW();
1611        if ( !idr ) throw -11;
1612        
1613        return(0);
1614    }
1615    /**
1616     * Insert a new row into GL_RAW table.
1617     */
1618    Int_t PamelaDBOperations::insertPamelaRawFile(GL_RAW *glraw){
1619    //    //
1620    stringstream oss;      if(!glraw)return(1);//?? ok I think
1621    //      //
1622    Bool_t idr =  this->SetID_RAW();      stringstream oss;
1623    if ( idr ) return(1);      //
1624    //      oss.str("");
1625    oss.str("");      if ( STATIC ){
1626    if ( STATIC ){          oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"
1627      oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"              << glraw->PATH << "', '" << glraw->NAME << "')";
1628          << this->GetRawPath().Data() << "', '" << this->GetRawFile().Data() << "')";      } else {
1629    } else {          oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('$PAM_RAW', '" << glraw->NAME << "')";
1630      oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('$PAM_RAW', '" << this->GetRawFile().Data() << "')";      };
1631    };      if ( debug ) cout <<oss.str().c_str() <<endl;
1632    if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;      if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
1633    //      //
1634    idr =  this->SetID_RAW();      oss.str("");
1635    if ( !idr ) throw -11;      oss << "SELECT ID FROM GL_RAW WHERE NAME=\""<<glraw->NAME<<"\";";
1636    //      if ( debug ) cout << oss.str().c_str()<<endl;
1637    return(0);      if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
1638        //
1639        TSQLResult *result = 0;
1640        TSQLRow    *row    = 0;
1641        result = conn->Query(oss.str().c_str());
1642        if ( result == NULL ) throw -4;
1643        row = result->Next();
1644        if ( !row ) return(1);
1645        glraw->ID = (UInt_t)atoll(row->GetField(0));
1646        if ( debug ) printf(" The ID of the RAW file is %u \n",glraw->ID);
1647        delete result;
1648        delete row;
1649        //
1650        return(0);
1651  }  }
1652    
1653    
# Line 1445  Int_t PamelaDBOperations::insertPamelaRa Line 1658  Int_t PamelaDBOperations::insertPamelaRa
1658  Int_t PamelaDBOperations::insertPamelaGL_TIMESYNC(){  Int_t PamelaDBOperations::insertPamelaGL_TIMESYNC(){
1659    //    //
1660    Int_t signal = 0;    Int_t signal = 0;
1661    UInt_t idresof = 0;    //  UInt_t idresof = 0;
1662      idresof = 0;
1663    stringstream   oss;    stringstream   oss;
1664    TSQLResult *result = 0;    TSQLResult *result = 0;
1665    TSQLRow *row = 0;    TSQLRow *row = 0;
# Line 1467  Int_t PamelaDBOperations::insertPamelaGL Line 1681  Int_t PamelaDBOperations::insertPamelaGL
1681      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
1682      if ( !result ) throw -10;      if ( !result ) throw -10;
1683      row = result->Next();      row = result->Next();
1684        if ( !row ) throw -92;
1685      idresof = (UInt_t)atoll(row->GetField(0));      idresof = (UInt_t)atoll(row->GetField(0));
1686      existsts = true;      existsts = true;
1687      goto eout;      goto eout;
# Line 1488  Int_t PamelaDBOperations::insertPamelaGL Line 1703  Int_t PamelaDBOperations::insertPamelaGL
1703      if ( !row ){      if ( !row ){
1704        oss.str("");        oss.str("");
1705        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< "
1706            << dworbit << " order by FROM_ORBIT desc limit 1;";            << dworbit << " AND SPECIAL_FILE='' order by FROM_ORBIT desc limit 1;";
1707        if ( IsDebug() ) printf(" %s \n",oss.str().c_str());        if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
1708        result = conn->Query(oss.str().c_str());        result = conn->Query(oss.str().c_str());
1709        if ( !result ) throw -10;        if ( !result ) throw -10;
# Line 1535  Int_t PamelaDBOperations::insertPamelaGL Line 1750  Int_t PamelaDBOperations::insertPamelaGL
1750      TYPE = 0;      TYPE = 0;
1751      TSYNC = 0;      TSYNC = 0;
1752      //      //
1753      Double_t minimum = 0.;      //    Double_t minimum = 0.;
1754      Double_t maximum = 0.;      // Double_t maximum = 0.;
1755      Double_t minimum2 = 0.;      //Double_t minimum2 = 0.;
1756      Double_t maximum2 = 0.;      Double_t maximum2 = 0.;
1757      //      //
1758      //      //
# Line 1545  Int_t PamelaDBOperations::insertPamelaGL Line 1760  Int_t PamelaDBOperations::insertPamelaGL
1760      pamela::McmdRecord *mcrc = 0;      pamela::McmdRecord *mcrc = 0;
1761      TArrayC *mcmddata = 0;      TArrayC *mcmddata = 0;
1762      //      //
1763      minimum = numeric_limits<Double_t>::max();      //    minimum = numeric_limits<Double_t>::max();
1764      maximum = numeric_limits<Double_t>::min();      //    maximum = numeric_limits<Double_t>::min();
1765      minimum2 = numeric_limits<Double_t>::max();      //    minimum2 = numeric_limits<Double_t>::max();
1766      maximum2 = numeric_limits<Double_t>::min();      maximum2 = numeric_limits<Double_t>::min();
1767      //      //
1768      T = (TTree*)file->Get("Mcmd");      T = (TTree*)file->Get("Mcmd");
# Line 1746  Int_t PamelaDBOperations::insertPamelaGL Line 1961  Int_t PamelaDBOperations::insertPamelaGL
1961   * 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.
1962   */   */
1963  Int_t PamelaDBOperations::insertPamelaRootFile(){  Int_t PamelaDBOperations::insertPamelaRootFile(){
1964    stringstream oss;  
1965    TSQLResult *result = 0;      stringstream oss;
1966    TSQLRow    *row    = 0;      TSQLResult *result = 0;
1967    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;  
1968      //      //
1969      row = result->Next();      // ----------------------
1970        // determine the timesync
1971        // ----------------------
1972        UInt_t idtimesync = 0;
1973      //      //
1974      if ( !row ) throw -3;      if ( chewbacca ){
1975      idtimesync = (UInt_t)atoll(row->GetField(0));          oss.str("");
1976    } else {          oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" and ID_RESURS_OFFSET="<< idresof <<" limit 1;"; // 10RED BUG!!!! without 'and ID_RESURS_OFFSET="<< idresof ' this query is not enough to ensure finding the correct line in GL_TIMSYNC...
1977      oss.str("");          if ( debug ) printf(" %s \n",oss.str().c_str());
1978      if ( STATIC ){          result = conn->Query(oss.str().c_str());
1979        oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "          //
1980            << " LEFT JOIN GL_ROOT "          if ( !result ) throw -3;
1981            << " ON GL_RAW.ID = GL_ROOT.ID_RAW "          //
1982            << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "          row = result->Next();
1983            << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";          //
1984            if ( !row ) throw -3;
1985            idtimesync = (UInt_t)atoll(row->GetField(0));
1986      } else {      } else {
1987        oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "          oss.str("");
1988            << " LEFT JOIN GL_ROOT "          if ( STATIC ){
1989            << " ON GL_RAW.ID = GL_ROOT.ID_RAW "              oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1990            << " WHERE GL_RAW.PATH = '$PAM_RAW' AND "                  << " LEFT JOIN GL_ROOT "
1991            << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";                  << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1992                    << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "
1993                    << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1994            } else {
1995                oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1996                    << " LEFT JOIN GL_ROOT "
1997                    << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1998                    << " WHERE GL_RAW.PATH = '$PAM_RAW' AND "
1999                    << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
2000            };
2001            result = conn->Query(oss.str().c_str());
2002            //
2003            if ( !result ) throw -12;
2004            //
2005            row = result->Next();
2006            //
2007            if ( !row ) throw -10;
2008            if ( row != NULL && (UInt_t)atoll(row->GetField(0))>0 ){
2009                idroot = (UInt_t)atoll(row->GetField(2));
2010                delete row;
2011                delete result;
2012                return(1);
2013            };
2014            //
2015            // determine which timesync has to be used
2016            //
2017            oss.str("");
2018            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;";
2019            result = conn->Query(oss.str().c_str());
2020            //
2021            if ( !result ) throw -3;
2022            //
2023            row = result->Next();
2024            //
2025            if ( !row ) throw -3;
2026            idtimesync = (UInt_t)atoll(row->GetField(0));
2027      };      };
2028      result = conn->Query(oss.str().c_str());      
2029      //      delete row;
2030      if ( !result ) throw -12;      delete result;
2031      //  
2032      row = result->Next();      // ----------------------
2033      //      // insert root file
2034      if ( !row ) throw -10;      // ----------------------
2035      if ( row != NULL && (UInt_t)atoll(row->GetField(0))>0 ){  
2036        idroot = (UInt_t)atoll(row->GetField(2));      GL_ROOT glroot = GL_ROOT();
2037        return(1);      
2038        glroot.ID_RAW = GetID_RAW();
2039        glroot.ID_TIMESYNC = idtimesync;
2040        if ( STATIC ){
2041          glroot.PATH = GetRootPath();
2042        } else {
2043          if ( KEEPENV ){
2044            glroot.PATH = gSystem->DirName(filerootname.Data());
2045          } else {
2046            glroot.PATH = "$PAM_L0";
2047          };
2048      };      };
2049      //      glroot.NAME = GetRootFile();
2050      // determine which timesync has to be used  
2051      //      if ( insertPamelaRootFile(&glroot) )return 1;
2052      oss.str("");  
2053      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);
2054      result = conn->Query(oss.str().c_str());      
2055      //  
2056      if ( !result ) throw -3;      return (0);
2057      //  }
2058      row = result->Next();  /**
2059      //   * Insert all the new rows into GL_ROOT.
2060      if ( !row ) throw -3;   * The raw file indicates in the parameters should be already been stored in the database.
2061      idtimesync = (UInt_t)atoll(row->GetField(0));   */
2062    };  Int_t PamelaDBOperations::insertPamelaRootFile(GL_ROOT *glroot){
2063      stringstream oss;
2064      TSQLResult *result = 0;
2065      TSQLRow    *row    = 0;
2066      //
2067    //    //
2068    oss.str("");    oss.str("");
2069    if ( STATIC ){    oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
2070      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() << "')";  
   };  
2071    //    //
2072    if ( debug ) printf(" query is %s \n",oss.str().c_str());    if ( debug ) printf("%s \n",oss.str().c_str());
2073    if (conn->Query(oss.str().c_str()) == 0) throw -4;    if (conn->Query(oss.str().c_str()) == 0) throw -4;
2074    //    //
2075    delete result;    delete result;
2076    //    //
2077    oss.str("");    oss.str("");
2078    //  oss << "SELECT ID FROM GL_ROOT WHERE ID_RAW=" << this->GetID_RAW() << ";";    //  oss << "SELECT ID FROM GL_ROOT WHERE ID_RAW=" << this->GetID_RAW() << ";";
2079    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() <<"';";  
   };  
2080    //    //
2081    if ( debug ) printf(" query is %s \n",oss.str().c_str());    if ( debug ) printf("%s \n",oss.str().c_str());
2082    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
2083    if ( !result ) throw -12;    if ( !result ) throw -12;
2084    row = result->Next();    row = result->Next();
2085    if ( !row ) throw -3;    if ( !row ) throw -3;
2086    this->SetID_ROOT((UInt_t)atoll(row->GetField(0)));  
2087    if ( debug ) printf(" The ID of the ROOT file is %u \n",this->GetID_ROOT());    glroot->ID = (UInt_t)atoll(row->GetField(0));
2088    
2089      if ( debug ) printf(" The ID of the ROOT file is %u \n",glroot->ID);
2090    //    //
2091    delete result;    delete result;
2092    //    //
# Line 1929  Int_t PamelaDBOperations::assignBOOT_NUM Line 2182  Int_t PamelaDBOperations::assignBOOT_NUM
2182      UInt_t lowerts = tsync-(obt0/1000)-5;      UInt_t lowerts = tsync-(obt0/1000)-5;
2183      if ( chewbacca ){      if ( chewbacca ){
2184        oss.str("");        oss.str("");
2185        oss << "select BOOT_NUMBER from ROOT_TABLE where LAST_TIME_SYNC_INFO-(OBT_TIME_SYNC)<"        oss << "select BOOT_NUMBER from ROOT_TABLE where CAST((LAST_TIME_SYNC_INFO-(OBT_TIME_SYNC)) AS SIGNED INT)<" // 10RED MYSQL OPERATORS BUG
2186            << upperts            << upperts
2187            << " AND LAST_TIME_SYNC_INFO-(OBT_TIME_SYNC)>"            << " AND CAST((LAST_TIME_SYNC_INFO-(OBT_TIME_SYNC)) AS SIGNED INT)>" // 10RED MYSQL OPERATORS BUG
2188            << lowerts            << lowerts
2189            << " AND BOOT_NUMBER>1;";            << " AND BOOT_NUMBER>1;";
2190      } else {      } else {
2191        oss.str("");        oss.str("");
2192        oss << "select GL_RAW.BOOT_NUMBER from GL_TIMESYNC LEFT JOIN GL_RAW ON GL_RAW.ID = GL_TIMESYNC.ID_RAW where TIMESYNC-(OBT0/1000)<"        oss << "select GL_RAW.BOOT_NUMBER from GL_TIMESYNC LEFT JOIN GL_RAW ON GL_RAW.ID = GL_TIMESYNC.ID_RAW where CAST((TIMESYNC-(OBT0/1000)) AS SIGNED INT)<" // 10RED MYSQL OPERATORS BUG
2193            << upperts            << upperts
2194            << " AND TIMESYNC-(OBT0/1000)>"            << " AND CAST((TIMESYNC-(OBT0/1000)) AS SIGNED INT)>" // 10RED MYSQL OPERATORS BUG
2195            << lowerts            << lowerts
2196            << " AND GL_RAW.BOOT_NUMBER>0 GROUP BY GL_TIMESYNC.OBT0;";            << " AND GL_RAW.BOOT_NUMBER>0 GROUP BY GL_TIMESYNC.OBT0;";
2197      };      };
# Line 2037  Int_t PamelaDBOperations::insertPamelaRU Line 2290  Int_t PamelaDBOperations::insertPamelaRU
2290    //    //
2291    // no runtrailers in the file!    // no runtrailers in the file!
2292    //    //
2293    if ( !rtev ){    if ( IsDebug() ) printf(" Start rtev %i rhev %i nrtev %i nrhev %i \n",rtev,rhev,nrtev,nrhev);
2294      if ( !rhev ){    if ( !rtev || (chewbacca && !nrtev) ){
2295        if ( IsDebug() ) printf(" No runtrailers \n");
2296        if ( !rhev || (chewbacca && !nrhev) ){
2297        if ( IsDebug() ) printf(" No runheaders nor runtrailers!! \n");        if ( IsDebug() ) printf(" No runheaders nor runtrailers!! \n");
2298        if ( !(upperentry-chminentry) ){        if ( !(upperentry-chminentry) ){
2299          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 2316  Int_t PamelaDBOperations::insertPamelaRU
2316            cod = ehh->GetCounter();            cod = ehh->GetCounter();
2317            tcod = (UInt_t)cod->Get(pctp->Physics);            tcod = (UInt_t)cod->Get(pctp->Physics);
2318            evbefh = TMath::Max(chminentry,tcod);            evbefh = TMath::Max(chminentry,tcod);
2319  //        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
2320            if ( (UInt_t)evbefh == upperentry || !upperentry ) evbefh = upperentry + 1;            if ( (UInt_t)evbefh == upperentry || !upperentry ) evbefh = upperentry + 1;
2321  //            //
2322          if ( debug ) printf(" evbefh %i upperentry %u \n",evbefh,upperentry);            if ( debug ) printf(" evbefh %i upperentry %u \n",evbefh,upperentry);
2323            //            //
2324            this->HandleRunFragments(false,true,evbefh,upperentry);            this->HandleRunFragments(false,true,evbefh,upperentry);
2325            //            //
# Line 2075  Int_t PamelaDBOperations::insertPamelaRU Line 2330  Int_t PamelaDBOperations::insertPamelaRU
2330      //      //
2331    } else {    } else {
2332      //      //
2333        if ( IsDebug() ) printf(" We have runtrailers \n");
2334      Int_t conptt = -1;      Int_t conptt = -1;
2335      for (Int_t ptt=0; ptt<rtev; ptt++){      for (Int_t ptt=0; ptt<rtev; ptt++){
2336        //        //
# Line 2091  Int_t PamelaDBOperations::insertPamelaRU Line 2347  Int_t PamelaDBOperations::insertPamelaRU
2347          ptht = cod->Get(pctp->RunHeader) - 1;          ptht = cod->Get(pctp->RunHeader) - 1;
2348          //      evbeft = cod->Get(pctp->Physics);          //      evbeft = cod->Get(pctp->Physics);
2349          tcod = (UInt_t)cod->Get(pctp->Physics);          tcod = (UInt_t)cod->Get(pctp->Physics);
2350          if ( !tcod ) tcod = 1;          if ( !tcod ) tcod = 1;    // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
2351          evbeft = TMath::Min(upperentry,(tcod-1));          evbeft = TMath::Min(upperentry,(tcod-1));
2352          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));
2353          //          //
# Line 2130  Int_t PamelaDBOperations::insertPamelaRU Line 2386  Int_t PamelaDBOperations::insertPamelaRU
2386            obth = phh->GetOrbitalTime();            obth = phh->GetOrbitalTime();
2387            cod = ehh->GetCounter();            cod = ehh->GetCounter();
2388            tcod = (UInt_t)cod->Get(pctp->Physics);            tcod = (UInt_t)cod->Get(pctp->Physics);
2389            if ( !tcod ) tcod = 1;            if ( !tcod ) tcod = 1; // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
2390            evbefh = TMath::Max(chminentry,(tcod-1));            evbefh = TMath::Max(chminentry,(tcod-1));
2391            //            //
2392            if ( PKT(pkth) >= PKT(pktfirst) && PKT(pkth) <= upperpkt ){            if ( PKT(pkth) >= PKT(pktfirst) && PKT(pkth) <= upperpkt ){
# Line 2169  Int_t PamelaDBOperations::insertPamelaRU Line 2425  Int_t PamelaDBOperations::insertPamelaRU
2425                //                //
2426                this->HandleRunFragments(true,true,chminentry,(evbefh));                this->HandleRunFragments(true,true,chminentry,(evbefh));
2427                //                //
2428                  // what about pth=ptht-1
2429              };              };
2430            };            };
2431            //            //
# Line 2191  Int_t PamelaDBOperations::insertPamelaRU Line 2448  Int_t PamelaDBOperations::insertPamelaRU
2448                cod = ehh->GetCounter();                cod = ehh->GetCounter();
2449                //            evbeft = cod->Get(pctp->Physics);                //            evbeft = cod->Get(pctp->Physics);
2450                tcod = (UInt_t)cod->Get(pctp->Physics);                tcod = (UInt_t)cod->Get(pctp->Physics);
2451                if ( !tcod ) tcod = 1;                if ( !tcod ) tcod = 1; // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
2452                evbeft = TMath::Min(upperentry,(tcod-1));                evbeft = TMath::Min(upperentry,(tcod-1));
2453                rh->GetEntry(pth);                rh->GetEntry(pth);
2454                phh = ehh->GetPscuHeader();                phh = ehh->GetPscuHeader();
# Line 2231  Int_t PamelaDBOperations::insertPamelaRU Line 2488  Int_t PamelaDBOperations::insertPamelaRU
2488          //      if ( ptt+1 == rtev){            //      if ( ptt+1 == rtev){  
2489          if ( conptt+1 == nrtev ){            if ( conptt+1 == nrtev ){  
2490            //    if ( conptt+1 == (nrtev+nrtbef )){              //    if ( conptt+1 == (nrtev+nrtbef )){  
2491              if ( IsDebug() ) printf(" >>>>>>>>>>> %i %u %i %u \n",ptht,rhev,nrtev,conptt);
2492            ptht++;            ptht++;
2493            if ( ptht < rhev ){            if ( ptht < rhev ){
2494              rh->GetEntry(ptht);              rh->GetEntry(ptht);
2495                //pth++;
2496                //if ( pth < rhev ){
2497                //rh->GetEntry(pth);
2498              phh = ehh->GetPscuHeader();              phh = ehh->GetPscuHeader();
2499              pkth = phh->GetCounter();              pkth = phh->GetCounter();
2500              obth = phh->GetOrbitalTime();              obth = phh->GetOrbitalTime();
# Line 2257  Int_t PamelaDBOperations::insertPamelaRU Line 2518  Int_t PamelaDBOperations::insertPamelaRU
2518              if ( (UInt_t)evbeft < upperentry-1 && upperentry>0 ){              if ( (UInt_t)evbeft < upperentry-1 && upperentry>0 ){
2519                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);
2520                //                //
2521                if ( (ptt-1) < 0 ) throw -15; // should never arrive here!                //              if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
2522                rt->GetEntry(ptt-1);                if ( (rtev-1) < 0 || ptt < 0 ) throw -15; // should never arrive here!
2523                  //              rt->GetEntry(ptt-1);
2524                  rt->GetEntry(rtev-1);
2525                cod = eht->GetCounter();                cod = eht->GetCounter();
2526                tcod = (UInt_t)cod->Get(pctp->Physics);                tcod = (UInt_t)cod->Get(pctp->Physics)+1;
2527                evbefh = TMath::Max(chminentry,tcod);                evbefh = TMath::Max(chminentry,tcod);
2528                //            evbefh = cod->Get(pctp->Physics);                //            evbefh = cod->Get(pctp->Physics);
2529                rt->GetEntry(ptt);                rt->GetEntry(ptt);
# Line 2367  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2630  Bool_t PamelaDBOperations::IsRunAlreadyI
2630        //        //
2631        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");
2632        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2633  //       oss.str("");        //       oss.str("");
2634  //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2635  //       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());      
2636  //       conn->Query(oss.str().c_str());        //       conn->Query(oss.str().c_str());
2637        if ( signal ) signal = false;        if ( signal ) signal = false;
2638        goto gonext;              goto gonext;      
2639        //        //
# Line 2385  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2648  Bool_t PamelaDBOperations::IsRunAlreadyI
2648        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");
2649        //        //
2650        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2651  //       oss.str("");        //       oss.str("");
2652  //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2653  //       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());      
2654  //       conn->Query(oss.str().c_str());        //       conn->Query(oss.str().c_str());
2655        //        //
2656        if ( signal ) signal = false;        if ( signal ) signal = false;
2657        goto gonext;        goto gonext;
# Line 2403  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2666  Bool_t PamelaDBOperations::IsRunAlreadyI
2666        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");
2667        //        //
2668        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2669  //       oss.str("");        //       oss.str("");
2670  //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2671  //       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());      
2672  //       conn->Query(oss.str().c_str());        //       conn->Query(oss.str().c_str());
2673        if ( signal ) signal = false;        if ( signal ) signal = false;
2674        //        //
2675      };      };
# Line 2488  void PamelaDBOperations::HandleRunFragme Line 2751  void PamelaDBOperations::HandleRunFragme
2751      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");
2752      //      //
2753    } 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 ){  
2754      //      //
2755      // 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
2756      //      //
2757      if ( IsDebug() ) printf(" The run is new \n");      if ( firstev != (lastev+1) ){ // could be a problem sometimes (?)
2758      if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");        if ( rhfirstev != firstev && !mishead ) mishead = true;
2759          if ( rtlastev != lastev && !mistrail ) mistrail = true;
2760        };
2761      //      //
2762      glrun->SetID(this->AssignRunID());      if ( IsDebug() ) printf(" bhere firstev is %i lastev is %i \n",firstev,lastev);
2763      glrun->SetID_RUN_FRAG(0);      this->FillClass(mishead,mistrail,firstev,lastev);
2764      glrun->Fill_GL_RUN_FRAGMENTS(conn);      if ( IsDebug() ) printf(" chere firstev is %i lastev is %i \n",firstev,lastev);
2765      //      //
2766    } else {      if ( IsDebug() ) printf("The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
2767      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());
2768      if ( PEDANTIC ) throw -69;      //
2769      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  
2770      //      //
2771      oss.str("");      oss.str("");
2772      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 "
2773          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
2774          << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "          << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
2775          << " ID != " << glrun->ID          << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
2776          << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!          << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
2777            << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2778            << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
2779            << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
2780            << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2781            << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
2782            << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
2783            << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2784            << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
2785            << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
2786      //      //
2787      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());
2788      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
2789      //      //
2790      if ( !result ) throw -4;      if ( !result ) throw -4;
2791      //      //
2792      row = result->Next();      row = result->Next();
2793      //      //
2794      if ( !row && NoFrag() ){      if ( !row ){
2795          //
2796          // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
2797          //
2798          if ( IsDebug() ) printf(" The run is new \n");
2799          if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
2800          //
2801          glrun->SetID(this->AssignRunID());
2802          glrun->SetID_RUN_FRAG(0);
2803          glrun->Fill_GL_RUN_FRAGMENTS(conn);
2804          //
2805        } else {
2806          if ( IsDebug() ) printf(" The run is already present in the fragment table, relaxed %u \n",RELAXED);
2807          if ( !RELAXED ){
2808            if ( PEDANTIC ) throw -69;
2809            return;
2810          } else {
2811            glrun->SetID((UInt_t)atoll(row->GetField(0)));
2812            glrun->SetID_RUN_FRAG(0);
2813          };
2814        };
2815        //
2816        if ( chewbacca && mishead && mistrail ) goto justcheck;
2817        //
2818        // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
2819        //    
2820        if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
2821          // missing it no way we can found a piece in the frag table
2822        //        //
2823        oss.str("");        oss.str("");
2824        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 "
2825            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2826            << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "            << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2827            << " ID != " << glrun->ID            << " ID != " << glrun->ID
2828            << " 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!!
2829        //        //
2830        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());
2831        result = conn->Query(oss.str().c_str());        result = conn->Query(oss.str().c_str());
2832        //        //
2833        if ( !result ) throw -4;        if ( !result ) throw -4;
2834        //        //
       foundinrun = true;  
       //  
2835        row = result->Next();        row = result->Next();
2836        //        //
2837      };        if ( !row && NoFrag() ){
2838      //          //
2839      if ( !row ){          oss.str("");
2840        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 "
2841        found = false;              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2842      } else {              << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2843        //              << " ID != " << glrun->ID
2844        found = false; // default value              << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
2845        //          //
2846        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());
2847        //          result = conn->Query(oss.str().c_str());
2848        // if we have both runheader and runtrailer we can check with pkt_counter:          //
2849            if ( !result ) throw -4;
2850            //
2851            foundinrun = true;
2852            //
2853            row = result->Next();
2854            //
2855          };
2856        //        //
2857        if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){        if ( !row ){
2858          ULong64_t chkpkt = 0;            if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2859          ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());          found = false;
2860          ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));        } else {
2861            //
2862            found = false; // default value
2863            //
2864            if ( IsDebug() ) printf(" A Found a possible candidate, checking if it is the good one... \n");
2865          //          //
2866          chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;            // if we have both runheader and runtrailer we can check with pkt_counter:
2867          //          //
2868          if ( labs(chkpkt-pktt)<2 ){          if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){
2869              ULong64_t chkpkt = 0;  
2870              ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
2871              ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
2872            //            //
2873            if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);            chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;  
2874            //            //
2875            found = true;            if ( labs(chkpkt-pktt)<2 ){
2876                //
2877                if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
2878                //
2879                found = true;
2880                if ( IsDebug() ) printf(" where firstev is %i lastev is %i \n",firstev,lastev);
2881                //
2882              } else {
2883                //
2884                if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);            
2885                //
2886                found = false;
2887                //
2888              };
2889            };
2890            if ( !found && chewbacca ) goto justcheck;
2891            if ( !found ){
2892            //            //
2893          } 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
2894            //            //
2895            if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);                  ULong64_t chkpkt1 = 0;
2896              ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
2897              ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
2898              chkpkt1 = labs(orunh1-dbrunt1);
2899            //            //
2900            found = false;            ULong64_t chkpkt2 = 0;
2901              ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());
2902              ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
2903              chkpkt2 = labs(orunh2-dbrunt2);
2904            //            //
2905              ULong64_t chkpkt3 = 0;
2906              ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());
2907              ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
2908              chkpkt3 = labs(orunh3-dbrunt3);
2909              //
2910              if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
2911                //  if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){
2912                //
2913                if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
2914                //
2915                found = true;
2916                //
2917              } else {
2918                //
2919                if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
2920                //
2921                found = false;
2922                //
2923              };
2924          };          };
2925        };        };
2926        if ( !found && chewbacca ) goto justcheck;        //
2927        if ( !found ){        if ( found ){
2928            //
2929            // 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
2930            //
2931            if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
2932          //          //
2933          // 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 ){
2934              glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2935              glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2936            };
2937          //          //
2938          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);  
2939          //          //
2940          if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){          //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
2941            //    if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){          //
2942            //          oss.str("");
2943            if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);          oss << " ID="<<row->GetField(0)<<";";
2944            //          //
2945            found = true;          glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos
2946            //          if ( IsDebug() ) printf(" there firstev is %i lastev is %i \n",firstev,lastev);
2947          } else {          //
2948            // merge infos
2949            //
2950            UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());
2951            ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
2952            UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
2953            ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
2954            if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2955            TTree *T= 0;
2956            T = (TTree*)file->Get("Physics");
2957            if ( !T || T->IsZombie() ) throw -16;
2958            EventHeader *eh = 0;
2959            PscuHeader *ph = 0;
2960            T->SetBranchAddress("Header", &eh);
2961            while ( apkt > bpkt && aobt > bobt && firstev < lastev ){
2962              T->GetEntry(firstev);
2963              ph = eh->GetPscuHeader();
2964              bpkt = PKT(ph->GetCounter());
2965              bobt = OBT(ph->GetOrbitalTime());    
2966              firstev++;
2967              if ( PEDANTIC ) throw -71;
2968            };
2969            if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2970            //
2971            glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
2972            glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
2973            glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
2974            glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());
2975            glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());
2976            //
2977            if ( IsDebug() ) printf(" here firstev is %i lastev is %i \n",firstev,lastev);
2978            //
2979            glrun->SetEV_FROM(firstev);
2980            glrun->SetEV_TO(lastev); // EM 10 RED ghost run bug
2981            glrun->SetNEVENTS(lastev-firstev+1);
2982            //
2983            glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
2984            glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
2985            glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
2986            glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());
2987            glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());
2988            glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());
2989            glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());
2990            glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());
2991            glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());
2992            glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());
2993            glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());  
2994            glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());  
2995            glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());  
2996            glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());  
2997            glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());  
2998            glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());  
2999            //
3000            if ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
3001            if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
3002            //
3003            if ( !IsRunAlreadyInserted() ){
3004              //
3005              //    glrun->SetID(this->AssignRunID());
3006              glrun->SetID_RUN_FRAG(glrun1->GetID());
3007              glrun->Fill_GL_RUN(conn);
3008            //            //
3009            if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);            // set id number
3010            //            //
3011            found = false;            glrun1->SetID_RUN_FRAG(glrun->GetID());
3012              glrun1->Fill_GL_RUN(conn);
3013            //            //
3014          };          };
3015        };          // delete old entry in fragment table
3016      };          //
3017      //          glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3018      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() ){  
3019          //          //
3020          //      glrun->SetID(this->AssignRunID());          delete glrun1;
         glrun->SetID_RUN_FRAG(glrun1->GetID());  
         glrun->Fill_GL_RUN(conn);  
3021          //          //
         // set id number  
3022          //          //
3023          glrun1->SetID_RUN_FRAG(glrun->GetID());          return;
         glrun1->Fill_GL_RUN(conn);  
3024          //          //
3025        };        };
       // delete old entry in fragment table  
       //  
       glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       //  
       delete glrun1;  
       //  
       //  
       return;  
3026        //        //
3027      };      };
3028      //      //
3029    };      if ( mistrail && ( rtlastev == lastev || chewbacca )) { // look for runtrailer (only when at the end of the file, if at the beginning and the runh is
3030    //        // 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() ){  
3031        //        //
3032        oss.str("");        oss.str("");
3033        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 "
3034            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3035            << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "            << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
3036            << " ID != " << glrun->ID            << " ID != " << glrun->ID
3037            << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";            << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
3038        //        //
3039        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());
3040        result = conn->Query(oss.str().c_str());        result = conn->Query(oss.str().c_str());
3041        //        //
3042        if ( !result ) throw -4;        if ( !result ) throw -4;
3043        //        //
       foundinrun = true;  
3044        row = result->Next();        row = result->Next();
3045        //        //
3046      };        if ( !row && NoFrag() ){
3047      //          //
3048      if ( !row ){          oss.str("");
3049        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 "
3050        found = false;              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3051      } else {              << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
3052        //              << " ID != " << glrun->ID
3053        found = false; // default value              << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
3054        //          //
3055        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());
3056        //          result = conn->Query(oss.str().c_str());
3057        // if we have both runheader and runtrailer we can check with pkt_counter:          //
3058            if ( !result ) throw -4;
3059            //
3060            foundinrun = true;
3061            row = result->Next();
3062            //
3063          };
3064        //        //
3065        if ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){        if ( !row ){
3066          ULong64_t chkpkt = 0;            if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
3067          ULong64_t pktt = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));          found = false;
3068          ULong64_t pkth = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());        } else {
3069            //
3070            found = false; // default value
3071          //          //
3072          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");
3073          //          //
3074          if ( labs(chkpkt-pktt)<2 ){          // if we have both runheader and runtrailer we can check with pkt_counter:
3075            //
3076            if ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){
3077              ULong64_t chkpkt = 0;  
3078              ULong64_t pktt = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
3079              ULong64_t pkth = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
3080            //            //
3081            if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);            chkpkt = pkth + (ULong64_t)((UInt_t)atoll(row->GetField(1))) + 1ULL + 1ULL;  
3082            //            //
3083            found = true;            if ( labs(chkpkt-pktt)<2 ){
3084                //
3085                if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
3086                //
3087                found = true;
3088                //
3089              } else {
3090                //
3091                if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);            
3092                //
3093                found = false;
3094                //
3095              };
3096            };
3097            if ( !found && chewbacca ) goto justcheck;
3098            if ( !found ){
3099            //            //
3100          } 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
3101            //            //
3102            if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);                  ULong64_t chkpkt1 = 0;
3103              ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
3104              ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
3105              chkpkt1 = labs(orunh1-dbrunt1);
3106            //            //
3107            found = false;            ULong64_t chkpkt2 = 0;
3108              ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNTRAILER_OBT());
3109              ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
3110              chkpkt2 = labs(orunh2-dbrunt2);
3111              //
3112              ULong64_t chkpkt3 = 0;
3113              ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNTRAILER_TIME());
3114              ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
3115              chkpkt3 = labs(orunh3-dbrunt3);
3116            //            //
3117              if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
3118                //
3119                if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
3120                //
3121                found = true;
3122                //
3123              } else {
3124                //
3125                if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
3126                //
3127                found = false;
3128                //
3129              };
3130          };          };
3131        };        };
3132        if ( !found && chewbacca ) goto justcheck;        //
3133        if ( !found ){        if ( found ){
3134            //
3135            // 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
3136            //
3137            if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
3138          //          //
3139          // 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 ){
3140              glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3141              glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
3142            };
3143          //          //
3144          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);  
3145          //          //
3146          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);  
3147          //          //
3148          ULong64_t chkpkt3 = 0;          oss.str("");
3149          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);  
3150          //          //
3151          if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){          glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runtrailer infos
3152            //          //
3153            if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);          // merge infos
3154            //          //
3155            found = true;          UInt_t apkt = PKT(glrun->GetRUNTRAILER_PKT());
3156            //          ULong64_t aobt = OBT(glrun->GetRUNTRAILER_OBT());
3157          } else {          UInt_t bpkt = PKT(glrun1->GetRUNHEADER_PKT());
3158            ULong64_t bobt = OBT(glrun1->GetRUNHEADER_OBT());
3159            if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
3160            TTree *T= 0;
3161            T = (TTree*)file->Get("Physics");
3162            if ( !T || T->IsZombie() ) throw -16;
3163            EventHeader *eh = 0;
3164            PscuHeader *ph = 0;
3165            T->SetBranchAddress("Header", &eh);
3166            while ( apkt > bpkt && aobt > bobt && lastev > 0 ){
3167              T->GetEntry(lastev);
3168              ph = eh->GetPscuHeader();
3169              apkt = PKT(ph->GetCounter());
3170              aobt = OBT(ph->GetOrbitalTime());    
3171              lastev--;
3172              if ( PEDANTIC && !RELAXED) throw -72;
3173            };
3174            if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
3175            //
3176            glrun->SetEV_FROM(firstev); // EM 10RED ghost run bug
3177            glrun->SetEV_TO(lastev);
3178            glrun->SetNEVENTS(lastev-firstev+1);
3179            glrun->SetPKT_COUNTER(glrun1->GetPKT_COUNTER());
3180            glrun->SetPKT_READY_COUNTER(glrun1->GetPKT_READY_COUNTER());
3181            glrun->SetRUNTRAILER_TIME(glrun1->GetRUNTRAILER_TIME());
3182            glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());
3183            glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());
3184            //
3185            glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());
3186            glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());
3187            glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());
3188            glrun1->SetCOMPILATIONTIMESTAMP(glrun->GetCOMPILATIONTIMESTAMP());
3189            glrun1->SetFAV_WRK_SCHEDULE(glrun->GetFAV_WRK_SCHEDULE());
3190            glrun1->SetEFF_WRK_SCHEDULE(glrun->GetEFF_WRK_SCHEDULE());
3191            glrun1->SetPRH_VAR_TRG_MODE_A(glrun->GetPRH_VAR_TRG_MODE_A());
3192            glrun1->SetPRH_VAR_TRG_MODE_B(glrun->GetPRH_VAR_TRG_MODE_B());
3193            glrun1->SetACQ_BUILD_INFO(glrun->GetACQ_BUILD_INFO());
3194            glrun1->SetACQ_VAR_INFO(glrun->GetACQ_VAR_INFO());
3195            glrun1->SetRM_ACQ_AFTER_CALIB(glrun->GetRM_ACQ_AFTER_CALIB());  
3196            glrun1->SetRM_ACQ_SETTING_MODE(glrun->GetRM_ACQ_SETTING_MODE());  
3197            glrun1->SetTRK_CALIB_USED(glrun->GetTRK_CALIB_USED());  
3198            glrun1->SetCAL_DSP_MASK(glrun->GetCAL_DSP_MASK());  
3199            glrun1->SetLAST_TIMESYNC(glrun->GetLAST_TIMESYNC());  
3200            glrun1->SetOBT_TIMESYNC(glrun->GetOBT_TIMESYNC());  
3201            //
3202            if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ) glrun1->SetPHYSENDRUN_MASK_S3S2S12(glrun->GetPHYSENDRUN_MASK_S3S2S12());
3203            if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) glrun1->SetPHYSENDRUN_MASK_S11CRC(glrun->GetPHYSENDRUN_MASK_S11CRC());
3204            //
3205            if ( !IsRunAlreadyInserted() ){
3206              //
3207              //    glrun->SetID(this->AssignRunID());
3208              //
3209              glrun->SetID_RUN_FRAG(glrun1->GetID());
3210              glrun->Fill_GL_RUN(conn);
3211            //            //
3212            if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);            // set id number
3213            //            //
3214            found = false;            glrun1->SetID_RUN_FRAG(glrun->GetID());
3215              glrun1->Fill_GL_RUN(conn);
3216            //            //
3217          };          };
3218            //
3219            // delete old entries in fragment table
3220            //
3221            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3222            glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3223            //
3224            delete glrun1;
3225            //
3226            return;
3227            //
3228        };        };
3229          //
3230      };      };
3231      //      //
3232      if ( found ){    justcheck:
3233        //      //
3234        // 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");  
       };  
3235        //        //
3236        GL_RUN *glrun1 = new GL_RUN();        if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");
3237        //        //
3238        //      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?
3239        //        //
3240        oss.str("");        oss.str("");
3241        oss << " ID="<<row->GetField(0)<<";";        oss << " SELECT ID,ID_ROOT_L0 FROM GL_RUN WHERE "
3242              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3243              << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3244              << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3245              << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3246              << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3247              << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3248              << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3249              << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3250              << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3251              << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3252              << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3253              << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3254              << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3255        //        //
3256        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());
3257          result = conn->Query(oss.str().c_str());
3258        //        //
3259        // merge infos        if ( !result ) throw -4;
3260        //        //
3261        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());    
3262        //        //
3263        if ( !IsRunAlreadyInserted() ){        if ( row ){
         //  
         //      glrun->SetID(this->AssignRunID());  
3264          //          //
3265          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
3266          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.
3267          //          //
3268          // set id number          // 090112 [8RED (-70): RUN ALREADY INSERTED]
3269            // 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!
3270          //          //
3271          glrun1->SetID_RUN_FRAG(glrun->GetID());          Bool_t OK = false;
3272          glrun1->Fill_GL_RUN(conn);          UInt_t IDRL2A = 0;
3273            UInt_t IDRL2B = 0;
3274            if ( chewbacca ){
3275              if ( result->GetRowCount() >= 2 ){
3276                //
3277                if ( IsDebug() ) printf(" RH---| gap |---RT case, number of pieces in the GL_RUN table: %i \n",result->GetRowCount());
3278                OK = true;
3279                IDRL2A = (UInt_t)atoll(row->GetField(0));
3280                //
3281                while ( row ){
3282                  //
3283                  TSQLResult *trresult = 0;
3284                  TSQLRow    *trrow    = 0;
3285                  //
3286                  stringstream tross;
3287                  tross.str("");
3288                  //
3289                  tross << " SELECT RUNHEADER_PKT, RUNTRAILER_PKT FROM GL_RUN_TRASH where ID=" << row->GetField(0) << ";";
3290                  if ( IsDebug() ) printf(" check in the gl_run_trash table for pkt intervals: query is \n %s \n",tross.str().c_str());
3291                  trresult = conn->Query(tross.str().c_str());
3292                  if ( !trresult ) throw -4;
3293                  trrow = trresult->Next();
3294                  if ( !trrow || trresult->GetRowCount() != 1 ){
3295                    OK = false;
3296                    if ( IsDebug() ) printf(" OPS! no such run (or multiple runs!) in GL_RUN_TRASH table, something wrong is going on! \n");
3297                    break;
3298                  };
3299                  //
3300                  UInt_t pktH =  (UInt_t)atoll(row->GetField(0));
3301                  UInt_t pktT =  (UInt_t)atoll(row->GetField(1));
3302                  delete trresult;
3303                  if (
3304                      (PKT(pktH) >= PKT(glrun->GetRUNHEADER_PKT()) && PKT(pktH) <= PKT(glrun->GetRUNTRAILER_PKT())) ||
3305                      (PKT(pktT) >= PKT(glrun->GetRUNHEADER_PKT()) && PKT(pktT) <= PKT(glrun->GetRUNTRAILER_PKT())) ||
3306                      (PKT(pktH) <= PKT(glrun->GetRUNTRAILER_PKT()) && PKT(pktT) >= PKT(glrun->GetRUNTRAILER_PKT())) ){            
3307                    OK = false;
3308                    if ( IsDebug() ) printf(" The run is overlapping with already inserted ones!! \n");
3309                    break;          
3310                  };
3311                  //PKT(glrun->GetRUNHEADER_PKT())  PKT(glrun->GetRUNTRAILER_PKT())
3312                  row = result->Next();
3313                };
3314                
3315                //    if ( result->GetRowCount() == 2 ) {
3316                //      IDRL2A = (UInt_t)atoll(row->GetField(0));
3317                //      UInt_t IDRL0A = (UInt_t)atoll(row->GetField(1));
3318                //      row = result->Next();
3319                //      IDRL2B = (UInt_t)atoll(row->GetField(0));
3320                //      UInt_t IDRL0B = (UInt_t)atoll(row->GetField(1));
3321                //      if ( IsDebug() ) printf(" IDRL0A %u B %u IDRL2A %u B %u \n",IDRL0A,IDRL0B,IDRL2A,IDRL2B);
3322                //      //      if ( IDRL0A == IDRL0B ){ //091230 why this condition???? RH could be in a file and RT in another one...
3323                //      if ( true ){
3324                //        TSQLResult *result2 = 0;
3325                //        TSQLRow    *row2    = 0;
3326                //        oss.str("");
3327                //        oss << "select PKT_NUMBER_FINAL from ROOT_TABLE_MERGING where REAL_TIME_INIT<" << chrtinit << " order by REAL_TIME_INIT desc limit 1;";
3328                //        if ( IsDebug() ) printf(" Check if we are in the case RH---| small gap |---RT: query is \n %s \n",oss.str().c_str());
3329                //        result2 = conn->Query(oss.str().c_str());
3330                //        //
3331                //        if ( !result2 ) throw -4;
3332                //        //
3333                //        row2 = result2->Next();
3334                //        //
3335                //        if ( row2 ){
3336                //          UInt_t PKA = (UInt_t)atoll(row2->GetField(0));
3337                //          delete result2;
3338                //          oss.str("");
3339                //          oss << "select PKT_NUMBER_INIT from ROOT_TABLE_MERGING where REAL_TIME_INIT>" << chrtinit << " order by REAL_TIME_INIT asc limit 1;";
3340                //          if ( IsDebug() ) printf(" Check if we are in the case RH---| small gap |---RT: query is \n %s \n",oss.str().c_str());
3341                //          result2 = conn->Query(oss.str().c_str());
3342                //          //
3343                //          if ( !result2 ) throw -4;
3344                //          //
3345                //          row2 = result2->Next();
3346                //          //
3347                //          if ( row2 ){
3348                //            UInt_t PKB = (UInt_t)atoll(row2->GetField(0));
3349                //            //
3350                //            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);
3351                //            if ( PKT(PKA)+1LL == PKT(glrun->GetRUNHEADER_PKT()) && PKT(PKB) == PKT(glrun->GetRUNTRAILER_PKT())+1LL ){
3352                //              if ( IsDebug() ) printf(" Ok, we are in the case: RH---| small gap |---RT \n");
3353                //              OK = true;
3354                //            };
3355                //          };
3356                //        };                  
3357                //      };
3358                //    };      
3359              };
3360            };
3361            if ( OK ){
3362              //
3363              // 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  
3364              //
3365              // 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 )
3366              //
3367              if ( IsDebug() ) printf(" Ok, we are in the case: RH---| small gap |---RT \n");
3368              //
3369              GL_RUN *glA = new GL_RUN();
3370              glA->Query_GL_RUN(IDRL2A,conn);
3371              //
3372              glrun->SetRUNHEADER_TIME(glA->GetRUNHEADER_TIME());
3373              glrun->SetRUNHEADER_OBT(glA->GetRUNHEADER_OBT());
3374              glrun->SetRUNHEADER_PKT(glA->GetRUNHEADER_PKT());
3375              //
3376              glrun->SetRUNTRAILER_TIME(glA->GetRUNTRAILER_TIME());
3377              glrun->SetRUNTRAILER_OBT(glA->GetRUNTRAILER_OBT());
3378              glrun->SetRUNTRAILER_PKT(glA->GetRUNTRAILER_PKT());
3379              //
3380              if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glA->GetPHYSENDRUN_MASK_S3S2S12());
3381              if ( glA->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glA->GetPHYSENDRUN_MASK_S11CRC());
3382              //          
3383              if ( glA->GetACQ_BUILD_INFO() != 0 ){
3384                //
3385                // the first piece contains a good runheader we can update all the other runs with correct infos!
3386                //
3387                glrun->SetCOMPILATIONTIMESTAMP(glA->GetCOMPILATIONTIMESTAMP());
3388                glrun->SetFAV_WRK_SCHEDULE(glA->GetFAV_WRK_SCHEDULE());
3389                glrun->SetEFF_WRK_SCHEDULE(glA->GetEFF_WRK_SCHEDULE());
3390                glrun->SetPRH_VAR_TRG_MODE_A(glA->GetPRH_VAR_TRG_MODE_A());
3391                glrun->SetPRH_VAR_TRG_MODE_B(glA->GetPRH_VAR_TRG_MODE_B());
3392                glrun->SetACQ_BUILD_INFO(glA->GetACQ_BUILD_INFO());
3393                glrun->SetACQ_VAR_INFO(glA->GetACQ_VAR_INFO());
3394                glrun->SetRM_ACQ_AFTER_CALIB(glA->GetRM_ACQ_AFTER_CALIB());
3395                glrun->SetRM_ACQ_SETTING_MODE(glA->GetRM_ACQ_SETTING_MODE());
3396                glrun->SetTRK_CALIB_USED(glA->GetTRK_CALIB_USED());
3397                glrun->SetCAL_DSP_MASK(glA->GetCAL_DSP_MASK());
3398                glrun->SetLAST_TIMESYNC(glA->GetLAST_TIMESYNC());
3399                glrun->SetOBT_TIMESYNC(glA->GetOBT_TIMESYNC());
3400                //
3401              };
3402              //
3403              if ( glA->GetPKT_READY_COUNTER() != 0 ){
3404                //
3405                // the first piece contains a good runtrailer we can update all the other runs with correct infos!
3406                //
3407                glrun->SetPKT_COUNTER(glA->GetPKT_COUNTER());
3408                glrun->SetPKT_READY_COUNTER(glA->GetPKT_READY_COUNTER());
3409              };
3410              //
3411              // update runheader ROOT_ID_FRAG
3412              //
3413              oss.str("");
3414              oss << "UPDATE GL_RUN SET ID_RUN_FRAG = " << glrun->GetID() << " where ID = " << IDRL2A << ";";
3415              if ( IsDebug() ) printf(" update gl_run to have cross indexing: %s\n",oss.str().c_str());
3416              conn->Query(oss.str().c_str());
3417              //
3418              oss.str("");
3419              oss << "SELECT ID FROM GL_RUN WHERE ID_RUN_FRAG = " << IDRL2A << ";";
3420              if ( IsDebug() ) printf(" update gl_run to have cross indexing: %s\n",oss.str().c_str());
3421              TSQLResult *tsresult = 0;
3422              TSQLRow    *tsrow    = 0;
3423              tsresult=conn->Query(oss.str().c_str());
3424              if ( !tsresult ) throw -4;
3425              tsrow = tsresult->Next();
3426              if ( !tsrow || tsresult->GetRowCount() != 1 ) throw -4;
3427              IDRL2B = (UInt_t)atoll(tsrow->GetField(0));
3428              glrun->SetID_RUN_FRAG(IDRL2B);
3429              //
3430              // fill the new run in GL_RUN
3431              //
3432              glrun->Fill_GL_RUN(conn);    
3433              //
3434              glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3435              delete glA;
3436              //
3437            } else {
3438    //        //
3439    //        // this is the case in which we must insert a piece of run between two fragments in the GL_RUN table
3440    //        //
3441    //        // 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 )
3442    //        //
3443    //        GL_RUN *glA = new GL_RUN();
3444    //        glA->Query_GL_RUN(IDRL2A,conn);
3445    //        //
3446    //        if ( glA->GetACQ_BUILD_INFO() != 0 ){
3447    //          //
3448    //          // the first piece contains a good runheader we can update all the other runs with correct infos!
3449    //          //
3450    //          oss.str("");
3451    //          oss << "UPDATE GL_RUN_FRAGMENTS SET "
3452    //              << " RUNHEADER_TIME=" << glA->GetRUNHEADER_TIME()<< " , "
3453    //              << " RUNHEADER_OBT=" << glA->GetRUNHEADER_OBT()<< " , "
3454    //              << " RUNHEADER_PKT=" << glA->GetRUNHEADER_PKT()<< " , "
3455    //              << " COMPILATIONTIMESTAMP=" << glA->GetCOMPILATIONTIMESTAMP()<< " , "
3456    //              << " FAV_WRK_SCHEDULE=" << glA->GetFAV_WRK_SCHEDULE()<< " , "
3457    //              << " EFF_WRK_SCHEDULE=" << glA->GetEFF_WRK_SCHEDULE()<< " , "
3458    //              << " PRH_VAR_TRG_MODE_A=" << glA->GetPRH_VAR_TRG_MODE_A()<< " , "
3459    //              << " PRH_VAR_TRG_MODE_B=" << glA->GetPRH_VAR_TRG_MODE_B()<< " , "
3460    //              << " ACQ_BUILD_INFO=" << glA->GetACQ_BUILD_INFO()<< " , "
3461    //              << " ACQ_VAR_INFO=" << glA->GetACQ_VAR_INFO()<< " , "
3462    //              << " RM_ACQ_AFTER_CALIB=" << glA->GetRM_ACQ_AFTER_CALIB()<< " , "  
3463    //              << " RM_ACQ_SETTING_MODE=" << glA->GetRM_ACQ_SETTING_MODE()<< " , "  
3464    //              << " TRK_CALIB_USED=" << glA->GetTRK_CALIB_USED()<< " , "  
3465    //              << " CAL_DSP_MASK=" << glA->GetCAL_DSP_MASK()<< " , "  
3466    //              << " LAST_TIMESYNC=" << glA->GetLAST_TIMESYNC()<< " , ";
3467    //          //
3468    //          if ( glA->GetPHYSENDRUN_MASK_S3S2S12() )
3469    //            oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12() << " , ";
3470    //          if ( glA->GetPHYSENDRUN_MASK_S11CRC() )
3471    //            oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC() << " , ";
3472    //          //        
3473    //          oss << " OBT_TIMESYNC=" << glA->GetOBT_TIMESYNC();
3474    //          oss << " WHERE ID=" << glrun->GetID() << ";";
3475    //          if ( IsDebug() ) printf(" update with correct infos: %s\n",oss.str().c_str());
3476    //          conn->Query(oss.str().c_str());    
3477    //          //
3478    //        } else {
3479    //          //
3480    //          // sig no runheader, let set anyway what is possible...
3481    //          //
3482    //          oss.str("");
3483    //          oss << "UPDATE GL_RUN_FRAGMENTS SET "
3484    //              << " RUNHEADER_TIME=" << glA->GetRUNHEADER_TIME()<< " , ";
3485    //          //
3486    //          if ( glA->GetPHYSENDRUN_MASK_S3S2S12() )
3487    //            oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , ";
3488    //          if ( glA->GetPHYSENDRUN_MASK_S11CRC() )
3489    //            oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , ";
3490    //          //        
3491    //          oss << " RUNHEADER_OBT=" << glA->GetRUNHEADER_OBT()<< " , "
3492    //              << " RUNHEADER_PKT=" << glA->GetRUNHEADER_PKT();
3493    //          oss << " WHERE ID=" << glrun->GetID() << ";";
3494    //          if ( IsDebug() ) printf(" update with correct infos2: %s\n",oss.str().c_str());
3495    //          conn->Query(oss.str().c_str());    
3496    //        };
3497    //        //
3498    //        // update runheader ROOT_ID_FRAG
3499    //        //
3500    //        oss.str("");
3501    //        oss << "UPDATE GL_RUN SET ID_RUN_FRAG = " << glrun->GetID() << " where ID = " << IDRL2A << ";";
3502    //        if ( IsDebug() ) printf(" update gl_run to have cross indexing: %s\n",oss.str().c_str());
3503    //        conn->Query(oss.str().c_str());
3504    //        //
3505    //        // now let's look for runtrailer if any in the last run
3506    //        //
3507    //        glA->Query_GL_RUN(IDRL2B,conn);
3508    //        //
3509    //        if ( glA->GetPKT_READY_COUNTER() != 0 ){
3510    //          //
3511    //          // the first piece contains a good runtrailer we can update all the other runs with correct infos!
3512    //          //
3513    //          oss.str("");
3514    //          oss << "UPDATE GL_RUN_FRAGMENTS SET "
3515    //              << " RUNTRAILER_TIME=" << glA->GetRUNTRAILER_TIME()<< " , "
3516    //              << " RUNTRAILER_OBT=" << glA->GetRUNTRAILER_OBT()<< " , "
3517    //              << " RUNTRAILER_PKT=" << glA->GetRUNTRAILER_PKT()<< " , "
3518    //              << " PKT_COUNTER=" << glA->GetPKT_COUNTER()<< " , ";
3519    //          //
3520    //          if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ){
3521    //            oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
3522    //          if ( glA->GetPHYSENDRUN_MASK_S11CRC() ) {
3523    //            oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
3524    //          //        
3525    //          oss << " PKT_READY_COUNTER=" << glA->GetPKT_READY_COUNTER()
3526    //              << " WHERE ID=" << glrun->GetID() << ";";
3527    //          if ( IsDebug() ) printf(" update with correct trailer infos: %s\n",oss.str().c_str());
3528    //          conn->Query(oss.str().c_str());    
3529    //          //
3530    //        } else {
3531    //          //
3532    //          // sig no runtrailer, let set anyway what is possible...
3533    //          //
3534    //          oss.str("");
3535    //          oss << "UPDATE GL_RUN_FRAGMENTS SET "
3536    //              << " RUNTRAILER_TIME=" << glA->GetRUNTRAILER_TIME()<< " , "
3537    //              << " RUNTRAILER_OBT=" << glA->GetRUNTRAILER_OBT()<< " , ";
3538    //            //
3539    //          if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ){
3540    //            oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
3541    //          if ( glA->GetPHYSENDRUN_MASK_S11CRC() ){
3542    //            oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
3543    //          //        
3544    //          oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()
3545    //              << " WHERE ID=" << glrun->GetID() << ";";
3546    //          if ( IsDebug() ) printf(" update with correct trailer infos2: %s\n",oss.str().c_str());
3547    //          conn->Query(oss.str().c_str());    
3548    //        };
3549    //        //
3550    //        UInt_t myi = glrun->GetID();
3551    //        oss.str("");
3552    //        oss << " ID= "<< myi;
3553    //        //
3554    //        glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);  
3555    //        //
3556    //        // fill the new run in GL_RUN
3557    //        //
3558    //        glrun->SetID_RUN_FRAG(IDRL2B);
3559    //        glrun->Fill_GL_RUN(conn);    
3560    //        glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3561    //        delete glA;
3562    //        //
3563    //      } else {
3564              //
3565              // is just a repetition
3566              //
3567              if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");        
3568              if ( PEDANTIC ) throw -70;
3569            };
3570          //          //
3571          } else {
3572            if ( NoFrag() ){
3573              glrun->SetID_RUN_FRAG(glrun->GetID());
3574              glrun->Fill_GL_RUN(conn);    
3575              glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3576            };    
3577        };        };
       //  
       // delete old entries in fragment table  
       //  
       glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       //  
       delete glrun1;  
       //  
       return;  
       //  
3578      };      };
3579      //    }; // EEE
   };  
3580    //    //
3581   justcheck:    return;
3582    };
3583    
3584    
3585    /**
3586     * Handle run without header or trailer
3587     **/
3588    void PamelaDBOperations::HandleMissingHoT(Bool_t mishead, Bool_t mistrail, UInt_t firstev, UInt_t lastev){  
3589    //    //
3590    if ( !found ){          //
3591      // is the piece of run good (no other packets inside)?
3592      //
3593      if ( !this->IsRunConsistent(mishead,mistrail,firstev,lastev)){
3594        //
3595        // if not, handle other pieces and continue with the first one
3596      //      //
3597      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");
3598      //      //
3599      // 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 {  
3600      //      //
3601      this->FillClass(mishead,mistrail,firstev,lastev);      this->FillClass(mishead,mistrail,firstev,lastev);
3602      //      //
# Line 3015  void PamelaDBOperations::HandleMissingHo Line 3604  void PamelaDBOperations::HandleMissingHo
3604        glrun->SetID(this->AssignRunID());        glrun->SetID(this->AssignRunID());
3605        glrun->SetID_RUN_FRAG(0);        glrun->SetID_RUN_FRAG(0);
3606        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...
3607      };        };
3608      //      //
3609    };    };
3610    //    //
# Line 3031  Bool_t PamelaDBOperations::IsRunConsiste Line 3620  Bool_t PamelaDBOperations::IsRunConsiste
3620    //      //  
3621    EventCounter *code=0;    EventCounter *code=0;
3622    //    //
3623    UInt_t nevent = 0;    //  UInt_t nevent = 0;
3624    UInt_t checkfirst = 0;    UInt_t checkfirst = 0;
3625    UInt_t checklast = 0;    UInt_t checklast = 0;
3626    UInt_t firstentry = 0;    UInt_t firstentry = 0;
# Line 3053  Bool_t PamelaDBOperations::IsRunConsiste Line 3642  Bool_t PamelaDBOperations::IsRunConsiste
3642    EventHeader *eh = 0;    EventHeader *eh = 0;
3643    PscuHeader *ph = 0;    PscuHeader *ph = 0;
3644    T->SetBranchAddress("Header", &eh);    T->SetBranchAddress("Header", &eh);
3645    nevent = T->GetEntries();    //  nevent = T->GetEntries();
3646    //    //
3647    //    //
3648    if ( firstev == lastev+1 || lastev == firstev ) { // no events inside the run!    if ( firstev == lastev+1 || lastev == firstev ) { // no events inside the run!
3649      //if ( firstev <= lastev+1 ) { // no events inside the run!      //if ( firstev <= lastev+1 ) { // no events inside the run!
3650      if ( IsDebug() ) printf(" Checking but no events in the run! \n");      if ( IsDebug() ) printf(" Checking but no events in the run! \n");
3651        firstev = lastev+1; // this is necessary for files with no Physics entries, should have no influence on other files
3652      // return true is correct      // return true is correct
3653      return(true);      return(true);
3654      //      //
# Line 3068  Bool_t PamelaDBOperations::IsRunConsiste Line 3658  Bool_t PamelaDBOperations::IsRunConsiste
3658      code = eh->GetCounter();      code = eh->GetCounter();
3659      checkfirst = 0;      checkfirst = 0;
3660      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3661         if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
3662       };      };
3663      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);
3664      //      //
3665      T->GetEntry(lastev);      T->GetEntry(lastev);
3666      code = eh->GetCounter();      code = eh->GetCounter();
3667      checklast = 0;      checklast = 0;
3668      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3669         if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
3670       };      };
3671      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);
3672      //      //
3673      if ( checkfirst == checklast ){      if ( checkfirst == checklast ){
# Line 3088  Bool_t PamelaDBOperations::IsRunConsiste Line 3678  Bool_t PamelaDBOperations::IsRunConsiste
3678        //        //
3679      } else {      } else {
3680        //        //
3681        if ( IsDebug() ) printf(" There are no-phyics packets inside the run!\n");        if ( IsDebug() ) printf(" There are no-physics packets inside the run!\n");
3682        //        //
3683        // HERE WE MUST HANDLE THAT RUNS AND GO BACK        // HERE WE MUST HANDLE THAT RUNS AND GO BACK
3684        //        //
3685  //      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");
3686        //        //
3687        Bool_t emptyruns = false;        Bool_t emptyruns = false;
3688        UInt_t check = 0;        UInt_t check = 0;
3689        UInt_t lastevtemp = lastev;        UInt_t lastevtemp = lastev;
3690        UInt_t firstevno = firstev;        UInt_t firstevno = firstev;
3691          UInt_t rhchko=0;
3692          UInt_t rhchk=0;
3693        //        //
3694        for (UInt_t i=firstev; i<=lastev; i++){        for (UInt_t i=firstev; i<=lastev; i++){
3695          //          //
# Line 3106  Bool_t PamelaDBOperations::IsRunConsiste Line 3698  Bool_t PamelaDBOperations::IsRunConsiste
3698          //          //
3699          check = 0;          check = 0;
3700          //          //
3701    
3702            // if we have a runheader set lastev then exit
3703            //
3704          for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){          for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3705            if ( strcmp(*Iter,"Physics") ) check += code->Get(GetPacketType(*Iter));            if ( strcmp(*Iter,"Physics") ) check += code->Get(GetPacketType(*Iter));
3706          };          };
3707            // check here if we have a runheader
3708            rhchko = rhchk;  
3709            rhchk = code->Get(GetPacketType("RunHeader"));    
3710          //          //
3711          if ( checkfirst < check || i == lastev ){          if ( checkfirst < check || i == lastev ){
3712            //            //
# Line 3184  Bool_t PamelaDBOperations::IsRunConsiste Line 3782  Bool_t PamelaDBOperations::IsRunConsiste
3782            };            };
3783            //                  //      
3784            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
3785              this->SetPhysEndRunVariables();
3786            //            //
3787            if ( chminentry == firstentry  ){ // EEE            if ( chminentry == firstentry  ){ // EEE
3788              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");
3789  //              //
3790  //          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
3791  //              //
   
   
   
   
   
   
   
   
   
   
   
   
   
   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  
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
3792    
3793                mishead = true;
3794    
3795    
3796                UInt_t rhfirstev = firstentry;
3797                //  UInt_t rtlastev = lastentry;
3798                Bool_t found = false;
3799                Bool_t foundinrun = false;
3800                //
3801                TSQLResult *result = 0;
3802                TSQLRow    *row    = 0;
3803                //
3804                stringstream oss;
3805                oss.str("");
3806                //
3807                // we have now the good first piece of a run, fill the glrun object
3808                //
3809                //  if ( rhfirstev != firstev && !mishead ) mishead = true;
3810                //  if ( rtlastev != lastev && !mistrail ) mistrail = true;
3811                //
3812                //  this->FillClass(mishead,mistrail,firstev,lastev);
3813                //
3814                if ( IsDebug() ) printf("zz The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
3815                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());
3816                //
3817                // First of all insert the run in the fragment table...
3818                //
3819                oss.str("");
3820                oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
3821                    << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3822                    << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3823                    << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3824                    << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3825                    << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3826                    << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3827                    << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3828                    << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3829                    << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3830                    << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3831                    << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3832                    << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3833                    << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3834                //
3835                if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3836                result = conn->Query(oss.str().c_str());
3837                //
3838                if ( !result ) throw -4;
3839                //
3840                row = result->Next();
3841                //
3842                if ( !row ){
3843                  //
3844                  // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
3845                  //
3846                  if ( IsDebug() ) printf(" The run is new \n");
3847                  if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
3848                  //
3849                  glrun->SetID(this->AssignRunID());
3850                  glrun->SetID_RUN_FRAG(0);
3851                  glrun->Fill_GL_RUN_FRAGMENTS(conn);
3852                  //
3853                } else {
3854                  if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
3855                  if ( PEDANTIC ) throw -69;
3856                  //    return;
3857                };
3858                //
3859                if ( chewbacca && mishead && mistrail ) goto zjustcheck;
3860                //
3861                // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
3862                //
3863                if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
3864                  // missing it no way we can found a piece in the frag table
3865                  //
3866                  oss.str("");
3867                  oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "
3868                      << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3869                      << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3870                      << " ID != " << glrun->ID
3871                      << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
3872                  //
3873                  if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());
3874                  result = conn->Query(oss.str().c_str());
3875                  //
3876                  if ( !result ) throw -4;
3877                  //
3878                  row = result->Next();
3879                  //
3880                  if ( !row && NoFrag() ){
3881                    //
3882                    oss.str("");
3883                    oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
3884                        << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3885                        << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3886                        << " ID != " << glrun->ID
3887                        << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
3888                    //
3889                    if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
3890                    result = conn->Query(oss.str().c_str());
3891                    //
3892                    if ( !result ) throw -4;
3893                    //
3894                    foundinrun = true;
3895                    //
3896                    row = result->Next();
3897                    //
3898                  };
3899                  //
3900                  if ( !row ){
3901                    if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
3902                    found = false;
3903                  } else {
3904                    //
3905                    found = false; // default value
3906                    //
3907                    if ( IsDebug() ) printf(" C Found a possible candidate, checking if it is the good one... \n");
3908                    //
3909                    // if we have both runheader and runtrailer we can check with pkt_counter:
3910                    //
3911                    if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){
3912                      ULong64_t chkpkt = 0;
3913                      ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
3914                      ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
3915                      //
3916                      chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;
3917                      //
3918                      if ( labs(chkpkt-pktt)<2 ){
3919                        //
3920                        if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
3921                        //
3922                        found = true;
3923                        //
3924                      } else {
3925                        //
3926                        if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);
3927                        //
3928                        found = false;
3929                        //
3930                      };
3931                    };
3932                    if ( !found && chewbacca ) goto zjustcheck;
3933                    if ( !found ){
3934                      //
3935                      // 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
3936                      //
3937                      ULong64_t chkpkt1 = 0;
3938                      ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
3939                      ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
3940                      chkpkt1 = labs(orunh1-dbrunt1);
3941                      //
3942                      ULong64_t chkpkt2 = 0;
3943                      ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());
3944                      ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
3945                      chkpkt2 = labs(orunh2-dbrunt2);
3946                      //
3947                      ULong64_t chkpkt3 = 0;
3948                      ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());
3949                      ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
3950                      chkpkt3 = labs(orunh3-dbrunt3);
3951                      //
3952                      if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
3953                        //    if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){
3954                        //
3955                        if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
3956                        //
3957                        found = true;
3958                        //
3959                      } else {
3960                        //
3961                        if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
3962                        //
3963                        found = false;
3964                        //
3965                      };
3966                    };
3967                  };
3968                  //
3969                  if ( found ){
3970                    //
3971                    // 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
3972                    //
3973                    if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
3974                    //
3975                    if ( foundinrun ){
3976                      glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3977                      glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
3978                    };
3979                    //
3980                    GL_RUN *glrun1 = new GL_RUN();
3981                    //
3982                    //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
3983                    //
3984                    oss.str("");
3985                    oss << " ID="<<row->GetField(0)<<";";
3986                    //
3987                    glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos
3988                    //
3989                    // merge infos
3990                    //
3991                    UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());
3992                    ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
3993                    UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
3994                    ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
3995                    if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
3996                    TTree *T= 0;
3997                    T = (TTree*)file->Get("Physics");
3998                    if ( !T || T->IsZombie() ) throw -16;
3999                    EventHeader *eh = 0;
4000                    PscuHeader *ph = 0;
4001                    T->SetBranchAddress("Header", &eh);
4002                    while ( apkt > bpkt && aobt > bobt && firstev < lastev ){
4003                      T->GetEntry(firstev);
4004                      ph = eh->GetPscuHeader();
4005                      bpkt = PKT(ph->GetCounter());
4006                      bobt = OBT(ph->GetOrbitalTime());
4007                      firstev++;
4008                      if ( PEDANTIC ) throw -71;
4009                    };
4010                    if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
4011                    //
4012                    glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
4013                    glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
4014                    glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
4015                    glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());
4016                    glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());
4017                    //
4018                    glrun->SetEV_FROM(firstev);
4019                    glrun->SetEV_TO(lastev); // 10 RED ghost run bug
4020                    glrun->SetNEVENTS(lastev-firstev+1);
4021                    //
4022                    glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
4023                    glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
4024                    glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
4025                    glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());
4026                    glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());
4027                    glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());
4028                    glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());
4029                    glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());
4030                    glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());
4031                    glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());
4032                    glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());
4033                    glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());
4034                    glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());
4035                    glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());
4036                    glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());
4037                    glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());
4038                    //
4039                    if ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
4040                    if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
4041                    //
4042                    if ( !IsRunAlreadyInserted() ){
4043                      //
4044                      //      glrun->SetID(this->AssignRunID());
4045                      glrun->SetID_RUN_FRAG(glrun1->GetID());
4046                      glrun->Fill_GL_RUN(conn);
4047                      //
4048                      // set id number
4049                      //
4050                      glrun1->SetID_RUN_FRAG(glrun->GetID());
4051                      glrun1->Fill_GL_RUN(conn);
4052                      //
4053                    };
4054                    // delete old entry in fragment table
4055                    //
4056                    glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
4057                    glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
4058                    //
4059                    delete glrun1;
4060                    //
4061                    //
4062                    //      return;
4063                    //
4064                  };
4065                  //
4066                };
4067                //
4068                //
4069              zjustcheck:
4070                //
4071                if ( !found ){
4072                  //
4073                  if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");
4074                  //
4075                  // not found, has this run already inserted in the GL_RUN or in the GL_RUN_FRAGMENTS table?
4076                  //
4077                  oss.str("");
4078                  oss << " SELECT ID FROM GL_RUN WHERE "
4079                      << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
4080                      << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
4081                      << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
4082                      << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
4083                      << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
4084                      << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
4085                      << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
4086                      << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
4087                      << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
4088                      << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
4089                      << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
4090                      << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
4091                      << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
4092                  //
4093                  if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
4094                  result = conn->Query(oss.str().c_str());
4095                  //
4096                  if ( !result ) throw -4;
4097                  //
4098                  row = result->Next();
4099                  //
4100                  if ( row ){
4101                    if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");
4102                    if ( PEDANTIC ) throw -70;
4103                  } else {
4104                    if ( NoFrag() ){
4105                      glrun->SetID_RUN_FRAG(glrun->GetID());
4106                      glrun->Fill_GL_RUN(conn);
4107                      glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
4108                    };
4109                  };
4110                }; // EEE
4111    
4112    
4113            } else {            } else {
4114            if ( !IsRunAlreadyInserted() ){              if ( !IsRunAlreadyInserted() ){
4115              glrun->SetID(this->AssignRunID());                glrun->SetID(this->AssignRunID());
4116              glrun->SetID_RUN_FRAG(0);                glrun->SetID_RUN_FRAG(0);
4117              glrun->Fill_GL_RUN(conn);                glrun->Fill_GL_RUN(conn);
4118            };              };
4119            }; // EEE            }; // EEE
4120            //            //
4121            firstevno = lastentry + 1;            firstevno = lastentry + 1;
# Line 3564  Bool_t PamelaDBOperations::IsRunConsiste Line 4124  Bool_t PamelaDBOperations::IsRunConsiste
4124            //            //
4125          };          };
4126          //          //
4127            if ( i > firstev ){
4128              if ( rhchko != rhchk ){
4129                if ( IsDebug() ) printf("oh oh... we have a runheader! stop here and handle later the remaining piece\n");
4130                lastev = i;
4131                return(false);
4132              };
4133            };
4134            //
4135          if ( check == checklast && i != lastev ){          if ( check == checklast && i != lastev ){
4136            lastevtemp = i - 1;            lastevtemp = i - 1;
4137            i = lastev - 1;            i = lastev - 1;
# Line 3596  void PamelaDBOperations::HandleSuspiciou Line 4164  void PamelaDBOperations::HandleSuspiciou
4164    EventCounter *code=0;    EventCounter *code=0;
4165    UInt_t firstev = 0;    UInt_t firstev = 0;
4166    UInt_t lastev = 0;    UInt_t lastev = 0;
4167    UInt_t nevent = 0;    //  UInt_t nevent = 0;
4168    UInt_t checkfirst = 0;    UInt_t checkfirst = 0;
4169    UInt_t checklast = 0;    UInt_t checklast = 0;
4170    UInt_t firstentry = 0;    UInt_t firstentry = 0;
# Line 3621  void PamelaDBOperations::HandleSuspiciou Line 4189  void PamelaDBOperations::HandleSuspiciou
4189    EventHeader *eh = 0;    EventHeader *eh = 0;
4190    PscuHeader *ph = 0;    PscuHeader *ph = 0;
4191    T->SetBranchAddress("Header", &eh);    T->SetBranchAddress("Header", &eh);
4192    nevent = T->GetEntries();    //  nevent = T->GetEntries();
4193    //    //
4194    codt = eht->GetCounter();    codt = eht->GetCounter();
4195    codh = ehh->GetCounter();    codh = ehh->GetCounter();
# Line 3647  void PamelaDBOperations::HandleSuspiciou Line 4215  void PamelaDBOperations::HandleSuspiciou
4215      code = eh->GetCounter();      code = eh->GetCounter();
4216      checkfirst = 0;      checkfirst = 0;
4217      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
4218         if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
4219         if ( !strcmp(*Iter,"RunHeader") ) nrunh1++;        if ( !strcmp(*Iter,"RunHeader") ) nrunh1++;
4220       };      };
4221      if ( IsDebug() ) printf(" Check first is %i \n",checkfirst);      if ( IsDebug() ) printf(" Check first is %i \n",checkfirst);
4222      //      //
4223      T->GetEntry(lastev);      T->GetEntry(lastev);
4224      code = eh->GetCounter();      code = eh->GetCounter();
4225      checklast = 0;      checklast = 0;
4226      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
4227         if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
4228       };      };
4229      if ( IsDebug() ) printf(" Check last is %i \n",checklast);      if ( IsDebug() ) printf(" Check last is %i \n",checklast);
4230      //      //
4231      if ( checkfirst == checklast ){      if ( checkfirst == checklast ){
# Line 3769  void PamelaDBOperations::HandleSuspiciou Line 4337  void PamelaDBOperations::HandleSuspiciou
4337            };            };
4338            //                  //      
4339            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
4340              this->SetPhysEndRunVariables();
4341            //            //
4342            if ( !IsRunAlreadyInserted() ){            if ( !IsRunAlreadyInserted() ){
4343              glrun->SetID(this->AssignRunID());              glrun->SetID(this->AssignRunID());
# Line 3808  void PamelaDBOperations::HandleSuspiciou Line 4377  void PamelaDBOperations::HandleSuspiciou
4377              if ( IsDebug() ) printf(" We have the runtrailer \n");              if ( IsDebug() ) printf(" We have the runtrailer \n");
4378              //                  //    
4379              this->SetCommonGLRUN(firstTime,lastTime);              this->SetCommonGLRUN(firstTime,lastTime);
4380                this->SetPhysEndRunVariables();
4381              //              //
4382              if ( !IsRunAlreadyInserted() ){              if ( !IsRunAlreadyInserted() ){
4383                glrun->SetID(this->AssignRunID());                glrun->SetID(this->AssignRunID());
# Line 3853  Int_t PamelaDBOperations::insertCALO_CAL Line 4423  Int_t PamelaDBOperations::insertCALO_CAL
4423    UInt_t totime = 0;    UInt_t totime = 0;
4424    UInt_t obt = 0;    UInt_t obt = 0;
4425    UInt_t pkt = 0;    UInt_t pkt = 0;
4426      Float_t totped = 0.;
4427    //    //
4428    tr = (TTree*)file->Get("CalibCalPed");    tr = (TTree*)file->Get("CalibCalPed");
4429    if ( !tr || tr->IsZombie() ) throw -21;    if ( !tr || tr->IsZombie() ) throw -21;
# Line 3870  Int_t PamelaDBOperations::insertCALO_CAL Line 4441  Int_t PamelaDBOperations::insertCALO_CAL
4441        if ( calibCalPed->cstwerr[section] ){        if ( calibCalPed->cstwerr[section] ){
4442          valid = 1;          valid = 1;
4443          if ( calibCalPed->cperror[section] ) valid = 0;          if ( calibCalPed->cperror[section] ) valid = 0;
4444            //
4445            // 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.]
4446            //
4447            totped = 0.;
4448            Int_t ns = 0;
4449            if ( section == 2 ) ns = 3;
4450            if ( section == 3 ) ns = 1;
4451            if ( section == 1 ) ns = 2;
4452            for (UInt_t ss=0; ss<96; ss++){
4453              totped += fabs(calibCalPed->calped[ns][0][ss]);
4454            }
4455            if ( totped < 1. ){
4456              if ( IsDebug() ) printf(" Section %i totped %f -  No calibration data! Calorimeter power problems? \n",section,totped);
4457              valid = 0;
4458            };
4459            //
4460          ph = eh->GetPscuHeader();          ph = eh->GetPscuHeader();
4461          obt = ph->GetOrbitalTime();            obt = ph->GetOrbitalTime();  
4462          pkt = ph->GetCounter();            pkt = ph->GetCounter();  
# Line 4037  Int_t PamelaDBOperations::insertCALOPULS Line 4624  Int_t PamelaDBOperations::insertCALOPULS
4624    tr->SetBranchAddress("Header", &eh);    tr->SetBranchAddress("Header", &eh);
4625    nevents = tr->GetEntries();    nevents = tr->GetEntries();
4626    //    //
4627      Float_t totpul = 0.;
4628      //
4629    if ( nevents > 0 ){    if ( nevents > 0 ){
4630      //      //
4631      for (UInt_t i=0; i < nevents; i++){      for (UInt_t i=0; i < nevents; i++){
# Line 4046  Int_t PamelaDBOperations::insertCALOPULS Line 4635  Int_t PamelaDBOperations::insertCALOPULS
4635          if ( cp1->pstwerr[section] && cp1->unpackError == 0 ){          if ( cp1->pstwerr[section] && cp1->unpackError == 0 ){
4636            valid = 1;            valid = 1;
4637            if ( cp1->pperror[section] ) valid = 0;            if ( cp1->pperror[section] ) valid = 0;
4638              //
4639              // 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.]
4640              //
4641              totpul = 0.;
4642              Int_t ns = 0;
4643              if ( section == 2 ) ns = 3;
4644              if ( section == 3 ) ns = 1;
4645              if ( section == 1 ) ns = 2;
4646              for (UInt_t ss=0; ss<96; ss++){
4647                totpul += cp1->calpuls[ns][0][ss];
4648              }
4649              if ( totpul >= 3145632. ){
4650                if ( IsDebug() ) printf(" PULSE1 Section %i totpul %f -  No calibration data! Calorimeter power problems? \n",section,totpul);
4651                valid = 0;
4652              };
4653              //
4654            ph = eh->GetPscuHeader();            ph = eh->GetPscuHeader();
4655            obt = ph->GetOrbitalTime();              obt = ph->GetOrbitalTime();  
4656            pkt = ph->GetCounter();              pkt = ph->GetCounter();  
# Line 4203  Int_t PamelaDBOperations::insertCALOPULS Line 4808  Int_t PamelaDBOperations::insertCALOPULS
4808          if ( cp2->pstwerr[section] && cp2->unpackError == 0 ){          if ( cp2->pstwerr[section] && cp2->unpackError == 0 ){
4809            valid = 1;            valid = 1;
4810            if ( cp2->pperror[section] ) valid = 0;            if ( cp2->pperror[section] ) valid = 0;
4811              //
4812              // 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.]
4813              //
4814              totpul = 0.;
4815              Int_t ns = 0;
4816              if ( section == 2 ) ns = 3;
4817              if ( section == 3 ) ns = 1;
4818              if ( section == 1 ) ns = 2;
4819              for (UInt_t ss=0; ss<96; ss++){
4820                totpul += cp2->calpuls[ns][0][ss];
4821              }
4822              if ( totpul >= 3145632. ){
4823                if ( IsDebug() ) printf(" PULSE2 Section %i totpul %f -  No calibration data! Calorimeter power problems? \n",section,totpul);
4824                valid = 0;
4825              };
4826              //
4827            ph = eh->GetPscuHeader();            ph = eh->GetPscuHeader();
4828            obt = ph->GetOrbitalTime();              obt = ph->GetOrbitalTime();  
4829            pkt = ph->GetCounter();              pkt = ph->GetCounter();  
# Line 4382  Int_t PamelaDBOperations::insertCALOPULS Line 5003  Int_t PamelaDBOperations::insertCALOPULS
5003   * Fill the GL_TRK_CALIB table   * Fill the GL_TRK_CALIB table
5004   */   */
5005  void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){  void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){
5006    //      
5007    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;  
5008      //      //
5009    } else {      glcal->ID         = 0;
5010        glcal->ID_ROOT_L0 = GetID_ROOT();
5011        glcal->EV_ROOT_CALIBTRK1 = t1;
5012        glcal->EV_ROOT_CALIBTRK2 = t2;
5013        glcal->FROM_TIME = fromtime;
5014        glcal->TO_TIME   = 0;
5015        glcal->OBT1      = obt1;
5016        glcal->OBT2      = obt2;
5017        glcal->PKT1      = pkt1;
5018        glcal->PKT2      = pkt2;
5019        glcal->BOOT_NUMBER = GetBOOTnumber();
5020        glcal->VALIDATION = valid;
5021      //      //
5022      // we have to insert a new calibration, check where to place it      HandleTRK_CALIB(glcal);
5023      //      //
5024      oss.str("");      delete glcal;
5025      oss << " SELECT ID,TO_TIME FROM GL_TRK_CALIB WHERE "  }
5026          << " FROM_TIME < "<< fromtime << " AND "  /**
5027          << " TO_TIME > "<< fromtime << ";";   * Fill the GL_TRK_CALIB table
5028     */
5029    void PamelaDBOperations::HandleTRK_CALIB(GL_TRK_CALIB *glcal){
5030    
5031        Bool_t pk1 = (glcal->OBT1>0&&glcal->PKT1>0);
5032        Bool_t pk2 = (glcal->OBT2>0&&glcal->PKT2>0);
5033        UInt_t boot_number = glcal->BOOT_NUMBER;
5034        UInt_t obt1 = glcal->OBT1;
5035        UInt_t obt2 = glcal->OBT2;
5036        UInt_t pkt1 = glcal->PKT1;
5037        UInt_t pkt2 = glcal->PKT2;
5038        UInt_t fromtime = glcal->FROM_TIME;
5039        UInt_t totime = 0;
5040        UInt_t idroot = glcal->ID_ROOT_L0;
5041        UInt_t t1 = glcal->EV_ROOT_CALIBTRK1;
5042        UInt_t t2 = glcal->EV_ROOT_CALIBTRK2;
5043        UInt_t valid = glcal->VALIDATION;
5044      //      //
5045      if ( IsDebug() ) printf(" Check where to place the trk calibration: query is \n %s \n",oss.str().c_str());      TSQLResult *result = 0;
5046      result = conn->Query(oss.str().c_str());      TSQLRow    *row    = 0;
5047      //      //
5048      if ( !result ) throw -4;      stringstream oss;
5049        oss.str("");
5050      //      //
     row = result->Next();  
5051      //      //
5052      if ( !row ){      if ( !pk1 && !pk2 ){
5053        //          if ( IsDebug() ) printf(" Cannot handle trk calibration with both packet missing!\n");
5054        // 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;  
       //  
5055      };      };
5056      //      //
5057      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 << "',";  
5058      //      //
5059      if ( !pk1 ){      oss.str("");
5060        oss << "NULL,";      oss << " SELECT ID FROM GL_TRK_CALIB WHERE "
5061            << " BOOT_NUMBER = "<< boot_number; //
5062        oss << " AND FROM_TIME="<<fromtime; /// NEWNEWNEW -- VA BENE ?!?!?!?!
5063        oss << " AND ( ( ";  
5064        if ( pk1 ){
5065            oss << " OBT1 = "<< obt1 << " AND "
5066                << " PKT1 = "<< pkt1
5067                << " ) OR ( ";
5068      } else {      } else {
5069        oss << "'"          oss << " PKT1 = "<< pkt2-1
5070            << t1 << "',";              << " ) OR ( ";  
5071      };      };      
5072      //      if ( pk2 ){
5073      if ( !pk2 ){          oss << " OBT2 = "<< obt2 << " AND "
5074        oss << "NULL,'";              << " PKT2 = "<< pkt2;
5075      } else {      } else {
5076        oss << "'"          oss << " PKT2 = "<< pkt1+1;
5077            << t2 << "','";      };      
5078      };      oss << " ) );";  
5079        //
5080        if ( IsDebug() ) printf(" Check if the trk calibration has already been inserted: query is \n %s \n",oss.str().c_str());
5081        result = conn->Query(oss.str().c_str());
5082      //      //
5083      oss << fromtime << "','"      if ( !result ) throw -4;
         << totime << "','"  
         << obt1 << "','"  
         << pkt1 << "','"  
         << obt2 << "','"  
         << pkt2 << "','"  
         << this->GetBOOTnumber() << "','"  
         << valid << "');";  
5084      //      //
5085      if ( IsDebug() ) printf(" Insert the new trk calibration: query is \n %s \n",oss.str().c_str());      row = result->Next();
5086      //      //
5087        if ( row ){
5088            //
5089            if ( IsDebug() ) printf(" Trk calibration already inserted in the DB\n");
5090            if ( PEDANTIC ) throw -80;
5091            //
5092        } else {
5093            //
5094            // we have to insert a new calibration, check where to place it
5095            //
5096            oss.str("");
5097            oss << " SELECT ID,TO_TIME FROM GL_TRK_CALIB WHERE "
5098                << " FROM_TIME < "<< fromtime << " AND "
5099                << " TO_TIME > "<< fromtime << ";";
5100            //
5101            if ( IsDebug() ) printf(" Check where to place the trk calibration: query is \n %s \n",oss.str().c_str());
5102            result = conn->Query(oss.str().c_str());
5103            //
5104            if ( !result ) throw -4;
5105            //
5106            row = result->Next();
5107            //
5108            if ( !row ){
5109                //
5110                // no calibrations in the db contain our calibration
5111                //
5112                if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB\n");
5113                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
5114                //
5115                oss.str("");
5116                oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "
5117                    << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
5118                //
5119                if ( IsDebug() ) printf(" Check the upper limit for 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                row = result->Next();
5125                if ( !row ){
5126                    totime = numeric_limits<UInt_t>::max();
5127                } else {
5128                    totime = (UInt_t)atoll(row->GetField(0));
5129                };
5130                //
5131            } else {
5132                //
5133                // determine upper and lower limits and make space for the new calibration
5134                //
5135                totime = (UInt_t)atoll(row->GetField(1));
5136                //
5137                oss.str("");
5138                oss << " UPDATE GL_TRK_CALIB SET "  
5139                    << " TO_TIME = "<< fromtime << " WHERE "  // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
5140                    << " ID = "<< row->GetField(0) << ";";
5141                //
5142                if ( IsDebug() ) printf(" Make space for the new trk calibration: query is \n %s \n",oss.str().c_str());
5143                result = conn->Query(oss.str().c_str());
5144                //
5145                if ( !result ) throw -4;
5146                //
5147            };
5148            //
5149            oss.str("");
5150            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) "
5151                << " VALUES (NULL,' "
5152                << idroot << "',";
5153            //
5154            if ( !pk1 ){
5155                oss << "NULL,";
5156            } else {
5157                oss << "'"
5158                    << t1 << "',";
5159            };
5160            //
5161            if ( !pk2 ){
5162                oss << "NULL,'";
5163            } else {
5164                oss << "'"
5165                    << t2 << "','";
5166            };
5167            //
5168            oss << fromtime << "','"
5169                << totime << "','"
5170                << obt1 << "','"
5171                << pkt1 << "','"
5172                << obt2 << "','"
5173                << pkt2 << "','"
5174                << boot_number << "','"
5175                << valid << "');";
5176            //
5177            if ( IsDebug() ) printf(" Insert the new trk calibration: query is \n %s \n",oss.str().c_str());
5178            //
5179            result = conn->Query(oss.str().c_str());
5180            //
5181            if ( !result ) throw -4;
5182            //
5183        };
5184        
5185        oss.str("");
5186        oss << " SELECT ID FROM GL_TRK_CALIB ORDER BY ID DESC LIMIT 1 ;";  
5187        if ( IsDebug() ) cout << oss.str().c_str() << endl;
5188      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
5189        if ( !result ) throw -4;;
5190        row = result->Next();
5191        if(row)glcal->ID = (UInt_t)atoll(row->GetField(0));
5192      //      //
5193      if ( !result ) throw -4;      delete result; // mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
5194      //      //
   };  
   //  
5195  };  };
5196    
5197  /**  /**
5198   * Scan tracker calibrations packets, fill the GL_TRK_CALIB table   * Scan tracker calibrations packets, fill the GL_TRK_CALIB table
5199   */   */
5200  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++){  
5201      //      //
5202      pret2 = t2;      CalibTrk1Event *caltrk1 = 0;
5203      tr1->GetEntry(t1);      CalibTrk2Event *caltrk2 = 0;
5204        TTree *tr1 = 0;
5205        TTree *tr2 = 0;
5206        EventHeader *eh1 = 0;
5207        PscuHeader *ph1 = 0;
5208        EventHeader *eh2 = 0;
5209        PscuHeader *ph2 = 0;
5210      //      //
5211      ph1 = eh1->GetPscuHeader();      PacketType *pctp=0;
5212      obt1 = ph1->GetOrbitalTime();        EventCounter *codt2=0;
     pkt1 = ph1->GetCounter();    
     fromtime = this->GetAbsTime(ph1->GetOrbitalTime());    
5213      //      //
5214  //     valid = 1;      Int_t nevents1 = 0;
5215  //     //      Int_t nevents2 = 0;
 //     if ( caltrk1->unpackError != 0 && caltrk1->good0 == 0 ) valid = 0;// CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT1  
5216      //      //
5217        fromtime = 0;
5218      //      //
5219      if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->PKT(pkt1) <= upperpkt && this->OBT(obt1) >= this->OBT(obtfirst) && this->OBT(obt1) <= upperobt ){      obt1 = 0;
5220        //    if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->OBT(obt1) >= this->OBT(obtfirst) ){      pkt1 = 0;
5221        //      obt2 = 0;
5222        if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u \n",fromtime,obt1,pkt1);      pkt2 = 0;
5223        //            //
5224        valid = ValidateTrkCalib( caltrk1, eh1 );      tr1 = (TTree*)file->Get("CalibTrk1");
5225        if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;      if ( !tr1 || tr1->IsZombie() ) throw -22;
5226        //      tr2 = (TTree*)file->Get("CalibTrk2");
5227        // Do we have the second calibration packet?      if ( !tr2 || tr2->IsZombie() ) throw -23;
5228        //      //
5229        while ( t2t1cal < t1+1 ){ // get the calibration packet2 that follows the packet1      tr1->SetBranchAddress("CalibTrk1", &caltrk1);
5230        tr1->SetBranchAddress("Header", &eh1);
5231        nevents1 = tr1->GetEntries();
5232        tr2->SetBranchAddress("CalibTrk2", &caltrk2);
5233        tr2->SetBranchAddress("Header", &eh2);
5234        nevents2 = tr2->GetEntries();
5235        //
5236        if ( !nevents1 && !nevents2 ) return(1);
5237        //
5238        t2 = -1;
5239        Int_t pret2 = 0;
5240        Int_t t2t1cal = 0;
5241        //
5242        bool MISSING_pkt1 = true;
5243        bool MISSING_pkt2 = true;
5244        int  ncalib = 0;
5245        bool try_to_recover = false;
5246        //
5247        for (t1=0; t1 < nevents1; t1++){//loop over packet1
5248          //          //
5249          t2++;          pret2 = t2;
5250            tr1->GetEntry(t1);
5251          //          //
5252          pret2 = t2 - 1; // EMILIANO          ph1 = eh1->GetPscuHeader();
5253            obt1 = ph1->GetOrbitalTime();  
5254            pkt1 = ph1->GetCounter();  
5255            fromtime = GetAbsTime(ph1->GetOrbitalTime());  
5256          //          //
5257          if ( t2 < nevents2 ){          // chek if the packet number and obt are consistent with the other packets ???
5258            tr2->GetEntry(t2);          //
5259            codt2 = eh2->GetCounter();          if ( PKT(pkt1) >= PKT(pktfirst) && PKT(pkt1) <= upperpkt && OBT(obt1) >= OBT(obtfirst) && OBT(obt1) <= upperobt ){
5260            t2t1cal = codt2->Get(pctp->CalibTrk1);              //    if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->OBT(obt1) >= this->OBT(obtfirst) ){
5261            //              //
5262            ph2 = eh2->GetPscuHeader();              if ( IsDebug() ) printf("\n Trk calibration1 %u at time %u obt %u pkt %u \n",t1,fromtime,obt1,pkt1);
5263            obt2 = ph2->GetOrbitalTime();                //      
5264            pkt2 = ph2->GetCounter();                valid = ValidateTrkCalib( caltrk1, eh1 );
5265            //              if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;
5266            if ( IsDebug() ) printf(" This is a trk calibration2 at obt %u pkt %u t2 is %u , t2t1cal is %u \n",obt2,pkt2,t2,t2t1cal);                    //
5267  //        if ( caltrk2->unpackError != 0 || caltrk2->good0 == 0 ) valid = 0; // CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT2              // Do we have the second calibration packet?
5268            //                    //
5269          } else {              if ( IsDebug() ) cout << " Loop over calibration2 to search associated calibration: "<<endl;
5270            //              while ( t2t1cal < t1+1 ){ // get the calibration packet2 that follows the packet1
5271            // running out of vector without finding the corresponding calibration, sig                  //
5272            //                  t2++;
5273            if ( IsDebug() ) printf(" t2 >= nevents2 \n");                  //
5274            pret2 = t2;                  pret2 = t2 - 1; // EMILIANO
5275            obt2 = 0;                  //
5276            //      pkt2 = pkt1+2;                  if ( t2 < nevents2 ){
5277            pkt2 = 0;                      tr2->GetEntry(t2);
5278            t2t1cal = t1+1;                      codt2 = eh2->GetCounter();
5279          };                      t2t1cal = codt2->Get(pctp->CalibTrk1);
5280          //      if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) && (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){                      //
5281                        ph2 = eh2->GetPscuHeader();
5282                        obt2 = ph2->GetOrbitalTime();  
5283                        pkt2 = ph2->GetCounter();  
5284                        //
5285                        if ( IsDebug() ) printf(" >> trk calibration2 at obt %u pkt %u t2 is %u , t2t1cal is %u \n",obt2,pkt2,t2,t2t1cal);    
5286                        //    if ( caltrk2->unpackError != 0 || caltrk2->good0 == 0 ) valid = 0; // CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT2
5287                        //    
5288                    } else {
5289                        //
5290                        // running out of vector without finding the corresponding calibration, sig
5291                        //
5292                        if ( IsDebug() ) printf(" t2 >= nevents2 \n");
5293                        pret2 = t2;
5294                        obt2 = 0;
5295                        //    pkt2 = pkt1+2;
5296                        pkt2 = 0;
5297                        t2t1cal = t1+1;
5298                    };
5299                    //      if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) && (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){
5300    
5301          // EMILIANO                  // EMILIANO
5302  //      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) ){
5303  //        //    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) ){
5304  //        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");
5305  //        //                  //        //
5306  //        // running out of vector without finding the corresponding calibration, sig                  //        // running out of vector without finding the corresponding calibration, sig
5307  //        //                  //        //
5308  //        pret2 = t2;                  //        pret2 = t2;
5309  //        obt2 = 0;                  //        obt2 = 0;
5310  //        //      pkt2 = pkt1+2;                  //        //      pkt2 = pkt1+2;
5311  //        pkt2 = 0;                  //        pkt2 = 0;
5312  //        t2t1cal = t1+1;                  //        t2t1cal = t1+1;
5313  //      };                  //      };
5314    
5315    
5316                    //
5317                };
5318                //
5319                if ( IsDebug() ) printf(" Check if trk calibration2 is the right one \n");
5320                //
5321                // EMILIANO
5322                if ( ( PKT(pkt2) < PKT(pktfirst) || PKT(pkt2) > upperpkt) || (OBT(obt2) < OBT(obtfirst) || OBT(obt2) > upperobt) ){
5323                    //      if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){
5324                    if ( IsDebug() ) printf(" *WARNING*  The calibration found is outside the interval, sig \n");
5325                    //
5326                    // running out of vector without finding the corresponding calibration, sig
5327                    //
5328                    pret2 = t2;
5329                    obt2 = 0;
5330                    pkt2 = 0;
5331                };
5332                if ( PKT(pkt2) == PKT(pkt1)+1 ){
5333                    if ( IsDebug() ) cout << " ...OK"<<endl;
5334                    // =======================
5335                    // The calibration is good
5336                    // =======================
5337                    //
5338    //      if ( IsDebug() ) printf(" Found trk calibration2 at obt %u pkt %u t2 is %u \n",obt2,pkt2,t2);
5339    //      if ( IsDebug() ) printf(" Trk calibration2 at obt %u pkt %u t2 is %u is good \n",obt2,pkt2,t2);
5340    //        if ( IsDebug() ) printf("\n Trk calibration2 at time %u obt %u pkt %u \n",fromtime,obt2,pkt2);
5341                    if ( IsDebug() ) printf(" Trk calibration2 %u at time %u obt %u pkt %u \n",t2,fromtime,obt2,pkt2);
5342                    //
5343                    UInt_t valid2 = ValidateTrkCalib( caltrk2, eh2 );
5344                    if ( IsDebug() ) cout << " pkt2 validation --> "<<valid2<<endl;
5345    //      valid = valid & valid2;
5346                    valid = valid & valid2; //QUESTO VA CAMBIATO
5347                    //
5348                    // Handle good calib
5349                    //
5350                    MISSING_pkt1 = false;
5351                    MISSING_pkt2 = false;
5352    //              this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5353                    //
5354                    // Check for missing calibtrk1
5355                    //
5356                    if ( t2 != pret2+1 ){
5357                        //
5358                        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);
5359                        //
5360                        while ( t2 > pret2+1 ){
5361                            //
5362                            // handle missing calib1
5363                            //
5364                            pret2++;
5365                            //
5366                            obt1 = 0;
5367                            pkt1 = 0;
5368                            //
5369                            tr2->GetEntry(pret2);
5370                            ph2 = eh2->GetPscuHeader();
5371                            obt2 = ph2->GetOrbitalTime();  
5372                            pkt2 = ph2->GetCounter();  
5373                            //
5374                            fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
5375                            //
5376                            valid = 0;
5377                            MISSING_pkt1 = true;
5378                            MISSING_pkt2 = false;
5379    //                      this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5380                            //
5381                        };
5382                        //
5383                    };
5384                    //
5385                } else if ( this->PKT(pkt2) > this->PKT(pkt1)+1 ){
5386                    //
5387                    // Check for missing calibtrk2
5388                    //
5389                    if ( IsDebug() ) printf(" Missing the trk calibration2! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);
5390                    t2 = pret2;
5391                    //
5392                    // handle missing calib2
5393                    //
5394                    obt2 = 0;
5395                    pkt2 = 0;
5396                    valid = 0;
5397                    MISSING_pkt1 = false;
5398                    MISSING_pkt2 = true;
5399    //              this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5400                    //
5401                };
5402                //
5403    
5404                if( !(MISSING_pkt1&MISSING_pkt2) ){
5405                  this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5406                  ncalib++;
5407                  if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
5408                }
5409    
5410    
5411            } else {
5412              //
5413                if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u OUTSIDE the considered time interval \n",fromtime,obt1,pkt1);
5414                //      if ( PEDANTIC ) throw -79;
5415                //
5416            };
5417            //    
5418    
5419        }; //end loop on pkt1
5420    
5421    
5422    
5423        //
5424        // we have one more calib pkt2 !
5425        //
5426        t2++;
5427        while ( t2 < nevents2 ){
5428          //          //
5429        };          // 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  
5430          //          //
5431          this->HandleTRK_CALIB(true,true);          if ( IsDebug() ) printf(" t2 is %u nevents2 is %u \n",t2,nevents2);
5432            obt1 = 0;
5433            pkt1 = 0;
5434          //          //
5435          // Check for missing calibtrk1          tr2->GetEntry(t2);
5436            ph2 = eh2->GetPscuHeader();
5437            obt2 = ph2->GetOrbitalTime();  
5438            pkt2 = ph2->GetCounter();  
5439          //          //
5440          if ( t2 != pret2+1 ){          fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
5441            //          valid = 0;
5442            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 ){
5443            //          // EMILIANO
5444            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 ){
5445              //              //    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();    
5446              //              //
5447              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);
5448              //              //
5449              valid = 0;              MISSING_pkt1 = true;
5450              this->HandleTRK_CALIB(false,true);              MISSING_pkt2 = false;
5451                this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5452                ncalib++;
5453                if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
5454              //              //
           };  
           //  
5455          };          };
5456          //          //
5457        } 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;  
5458          //          //
5459          // handle missing calib2      };
5460    
5461    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
5462    // -----------------------------------------------------------------
5463    // in case of corruption, check if the calibration can be recovered
5464    // from another chewbacca file
5465    // -----------------------------------------------------------------
5466    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
5467    
5468    //    cout <<" TRY TO RECOVER ?? "<<try_to_recover<<endl;
5469        
5470        if(chewbacca&&try_to_recover){
5471    
5472    
5473            if ( IsDebug() ) cout << endl << ">>>> TRY TO RECOVER TRACKER CALIBRATIONS <<<<"<<endl;
5474    
5475            TSQLResult *rresult = 0; // 10RED bug, result is re-used inside result looop...
5476            TSQLResult *result = 0; // 10RED bug, result is re-used inside result looop...
5477            TSQLRow    *row    = 0;
5478          //          //
5479          obt2 = 0;          stringstream oss;
5480          pkt2 = 0;          oss.str("");
         valid = 0;  
         this->HandleTRK_CALIB(true,false);        
5481          //          //
5482        };  
5483        //          ////////////////////////////////////////////////////////////////////////
5484      } else {          // retrieve the name of the current file:
5485        //          ////////////////////////////////////////////////////////////////////////        
5486        if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u OUTSIDE the considered time interval \n",fromtime,obt1,pkt1);          oss.str("");
5487        //      if ( PEDANTIC ) throw -79;          oss << "SELECT NAME FROM GL_ROOT where ID=" << GetID_ROOT() <<";";
5488        //          if ( IsDebug() ) cout << oss.str().c_str() << endl;
5489      };  
5490      //              result = conn->Query(oss.str().c_str());
5491    };          if ( !result ) throw -4;;
5492    //          row = result->Next();
5493    // we have one more calib pkt2 !          TString thisfilename = (TString)row->GetField(0);
5494    //          if ( IsDebug() ) cout << "Current file ==> "<<thisfilename<<endl;      
5495    t2++;  
5496    while ( t2 < nevents2 ){          ////////////////////////////////////////////////////////////////////////        
5497      //          // read all the calibrations inserted
5498      // handle missing calib1          ////////////////////////////////////////////////////////////////////////        
5499      //          oss.str("");
5500      if ( IsDebug() ) printf(" t2 is %u nevents2 is %u \n",t2,nevents2);          oss << " SELECT ";
5501      obt1 = 0;          oss << " ID,FROM_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,TO_TIME";
5502      pkt1 = 0;          oss << " FROM GL_TRK_CALIB ";
5503      //          oss << " ORDER BY ID DESC LIMIT "<<ncalib<<"; ";        
5504      tr2->GetEntry(t2);          if ( IsDebug() ) cout << oss.str().c_str() << endl;
5505      ph2 = eh2->GetPscuHeader();  
5506      obt2 = ph2->GetOrbitalTime();            rresult = conn->Query(oss.str().c_str());
5507      pkt2 = ph2->GetCounter();            if ( !result ) throw -4;;
5508      //          if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5509      fromtime = this->GetAbsTime(ph2->GetOrbitalTime());          
5510      valid = 0;          // -----------------------------------
5511  //  if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->PKT(pkt1) <= upperpkt && this->OBT(obt1) >= this->OBT(obtfirst) && this->OBT(obt1) <= upperobt ){          // loop over calibrations ...
5512   // EMILIANO          // -----------------------------------
5513      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;
5514        //    if ( this->PKT(pkt2) > this->PKT(pktfirst) || this->OBT(obt2) > this->OBT(obtfirst) ){          do {
5515        //              row = rresult->Next();
5516        if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);              if(!row)break;
5517        //              
5518        this->HandleTRK_CALIB(false,true);              UInt_t id       = (UInt_t)atoll(row->GetField(0));
5519        //              UInt_t fromtime = (UInt_t)atoll(row->GetField(1));
5520      };              UInt_t obt1     = (UInt_t)atoll(row->GetField(2));
5521      //              UInt_t pkt1     = (UInt_t)atoll(row->GetField(3));
5522      t2++;              UInt_t obt2     = (UInt_t)atoll(row->GetField(4));
5523      //              UInt_t pkt2     = (UInt_t)atoll(row->GetField(5));
5524    };              UInt_t boot     = (UInt_t)atoll(row->GetField(6));
5525                UInt_t valid    = (UInt_t)atoll(row->GetField(7));
5526                bool MISSING_pkt1 = (row->GetFieldLength(8)==0);
5527                bool MISSING_pkt2 = (row->GetFieldLength(9)==0);
5528                UInt_t totime   = (UInt_t)atoll(row->GetField(10));
5529    
5530                // -------------------------------------
5531                // ...check if the entry is corrupted...
5532                // -------------------------------------
5533                cout <<"*** "<< MISSING_pkt1 << MISSING_pkt2 << valid <<endl;
5534                bool CORRUPTED = (MISSING_pkt1||MISSING_pkt2||!valid);
5535    
5536                if ( IsDebug() ) cout << "("<<nn<<")  ID = "<<id<<" from GL_TRK_CALIB  ==>  corrupted ? "<<CORRUPTED<<endl;
5537    
5538    //          if( !CORRUPTED  )continue; // nothing to do
5539    
5540                /////////////////////////////////////////////////////////  
5541                // if it is corrupted, ...look for ather chewbacca files
5542                // containing the same calibrations ...
5543                /////////////////////////////////////////////////////////
5544    
5545                bool this_MISSING_pkt1 = false;
5546                bool this_MISSING_pkt2 = false;
5547                int  this_t1=0;
5548                int  this_t2=0;;
5549                UInt_t this_valid = 0;
5550    
5551                TString path       = "";
5552                TString name       = "";
5553                TString raw        = "";
5554                //      UInt_t obt0        = 0;
5555                //      UInt_t timesync    = 0;
5556                //      UInt_t boot_number = 0;
5557                bool   FOUND       = false;
5558    
5559                if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
5560    
5561    //          for(int itable=0; itable<2; itable++){
5562                for(int itable=0; itable<1; itable++){
5563    
5564                    // ------------------------------------------------------
5565                    // loop over both ROOT_TABLE and ROOT_TABLE_BAD
5566                    // ------------------------------------------------------
5567    
5568                    TString table = "ROOT_TABLE";
5569                    if(itable==1)table = "ROOT_TABLE_BAD";
5570    
5571                    oss.str("");
5572                    oss << " SELECT ";
5573                    oss << " FOLDER_NAME,FILE_NAME,OBT_TIME_SYNC,LAST_TIME_SYNC_INFO,BOOT_NUMBER,INPUT_NAME ";
5574                    oss << " FROM "<<table;
5575                    oss << " WHERE 1 " << endl;
5576                    oss << " AND FILE_NAME != \""<< thisfilename<<"\"";
5577                    if( !MISSING_pkt1 ){
5578                        oss << " AND ";
5579                        oss << " PKT_NUMBER_INIT < "<<pkt1;
5580                        oss << " AND ";
5581                        oss << " PKT_NUMBER_FINAL > "<<pkt1;
5582                        oss << " AND ";
5583                        oss << " PKT_OBT_INIT < "<<obt1;
5584                        oss << " AND ";
5585                        oss << " PKT_OBT_FINAL > "<<obt1;
5586                    }else{
5587                        if(pkt2>1) pkt1 = pkt2-1;//serve dopo                  
5588                    }
5589                    if( !MISSING_pkt2 ){
5590                        oss << " AND ";
5591                        oss << " PKT_NUMBER_INIT < "<<pkt2;
5592                        oss << " AND ";
5593                        oss << " PKT_NUMBER_FINAL > "<<pkt2;
5594                        oss << " AND ";
5595                        oss << " PKT_OBT_INIT < "<<obt2;
5596                        oss << " AND ";
5597                        oss << " PKT_OBT_FINAL > "<<obt2;
5598                    }else{
5599                        if(pkt1>0) pkt2 = pkt1+1;//serve dopo
5600                    }
5601                    if( boot> 0 ){
5602                        oss << " AND ";
5603                        oss << " BOOT_NUMBER = "<<boot;
5604                    }else{
5605                    }
5606                    oss << " ORDER BY BAD_PKT_CALREAD ASC; ";
5607                
5608                    TSQLResult *result2 = 0;
5609                    TSQLRow    *row2    = 0;
5610    
5611                    if ( IsDebug() ) cout << oss.str().c_str() << endl;        
5612                    result2 = conn->Query(oss.str().c_str());
5613                    if ( !result2 ) throw -4;;
5614                    if ( IsDebug() ) cout <<"Rows: "<<result2->GetRowCount()<<endl;
5615    
5616                    // ------------------------------------------------------
5617                    // loop over files containing repetition (if any)
5618                    // ------------------------------------------------------
5619                    do {
5620                        row2 = result2->Next();
5621                        if(!row2)break;
5622                    
5623                        // ------------------------------------------------------
5624                        // ... a repetition is found ...
5625                        // ------------------------------------------------------
5626                        path       = (TString)row2->GetField(0);
5627                        name       = (TString)row2->GetField(1);
5628                        raw        = (TString)row2->GetField(5);
5629                        //              obt0        = (UInt_t)atoll(row2->GetField(2));
5630                        //              timesync    = (UInt_t)atoll(row2->GetField(3));
5631                        //              boot_number = (UInt_t)atoll(row2->GetField(4));
5632                    
5633                        if ( IsDebug() ) cout << "- - - - - - - - - - -" <<endl;
5634    //                  cout << path <<endl;
5635    //                  cout << "File    : " <<name <<endl;
5636    //                  cout << obt0 <<endl;
5637    //                  cout << timesync <<endl;
5638    //                  cout << "boot n. : "<<boot_number <<endl;
5639    //                  cout << raw <<endl;
5640    
5641                        // ------------------------------------------------------
5642                        // ... retrieve the calibration packets.
5643                        // ------------------------------------------------------
5644                        if ( IsDebug() ) printf(" file is %s/%s \n",((TString)gSystem->ExpandPathName(path.Data())).Data(),name.Data());
5645                        TFile *file = new TFile(((TString)gSystem->ExpandPathName(path.Data()))+"/"+name); // EM, path could be symbolic and we must expand it
5646                        if(!file)throw -100;
5647                        if(file->IsZombie())throw -100;
5648                        //
5649                        tr1 = (TTree*)file->Get("CalibTrk1");
5650                        if ( !tr1 || tr1->IsZombie() ) throw -22;
5651                        tr2 = (TTree*)file->Get("CalibTrk2");
5652                        if ( !tr2 || tr2->IsZombie() ) throw -23;
5653                        //
5654                        tr1->SetBranchAddress("CalibTrk1", &caltrk1);
5655                        tr1->SetBranchAddress("Header", &eh1);
5656                        nevents1 = tr1->GetEntries();
5657                        tr2->SetBranchAddress("CalibTrk2", &caltrk2);
5658                        tr2->SetBranchAddress("Header", &eh2);
5659                        nevents2 = tr2->GetEntries();
5660                        for(this_t1=0; this_t1<nevents1; this_t1++){
5661                            tr1->GetEntry(this_t1);
5662                            if(
5663                                (UInt_t)eh1->GetPscuHeader()->GetCounter() == pkt1 &&
5664                                true) break;
5665                            this_MISSING_pkt1 = true;
5666                        }
5667                        for(this_t2=0; this_t2<nevents2; this_t2++){
5668                            tr2->GetEntry(this_t2);
5669                            if(
5670                                (UInt_t)eh2->GetPscuHeader()->GetCounter() == pkt2 &&
5671                                true) break;
5672                            this_MISSING_pkt2 = true;
5673                        }
5674                        this_valid =
5675                            ValidateTrkCalib( caltrk1, eh1, file )
5676                            *
5677                            ValidateTrkCalib( caltrk2, eh2, file );
5678                                
5679                        // ---------------------------------------------------------------------
5680                        // accept the calibration if it is better than the previous:
5681                        //
5682                        // - if the new calibration is perfect (both valid packets)
5683                        // - if the new calibration has both the packets and the previous does not
5684                        // ---------------------------------------------------------------------
5685                        if(
5686                            ( !this_MISSING_pkt1&&!this_MISSING_pkt2&&this_valid )||
5687                            ( (MISSING_pkt1||MISSING_pkt2) && (!this_MISSING_pkt1&&!this_MISSING_pkt2) )||
5688                            false)FOUND=true;      
5689                
5690                        if(file)file->Close();
5691    
5692                        if(FOUND)break;
5693    
5694                    }while(1);//endl loop over root table entries
5695                    
5696                    delete result2; // 10RED potential memory leak
5697                    if(FOUND)break;
5698    
5699                }//end loop over tables
5700    
5701                if(FOUND){
5702    
5703                  if ( IsDebug() ) cout << " >>> REPETITION FOUND :-) <<<" <<endl;
5704    
5705                  ////////////////////////////////////////////
5706                  // insert a new entry in GL_TRK_CALIB and
5707                  // modify the time-tag of the previous one
5708                  ////////////////////////////////////////////
5709    
5710                  // ---------------------------------------------------------------------
5711                  // step 1: insert a new raw file in GL_RAW
5712                  // ---------------------------------------------------------------------
5713                  //
5714                  // check if the raw file already exist
5715                  //
5716                  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
5717                  //                oss.str("");
5718                  //                oss << "SELECT ID FROM GL_RAW where NAME=\"" << gSystem->BaseName(raw.Data()) <<"\";";
5719                  //                if ( IsDebug() ) cout << oss.str().c_str() << endl;
5720                    
5721                  //                result = conn->Query(oss.str().c_str());
5722                  //                if ( !result ) throw -4;;
5723                  //                if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5724                  //                if( result->GetRowCount() == 0){
5725                  //                    if ( IsDebug() ) cout << " << Insert new RAW file >> "<<endl;
5726                  //                    // - - - - - - - - - - -
5727                  //                    // insert new raw file
5728                  //                    // - - - - - - - - - - -
5729                  //                    GL_RAW glraw = GL_RAW();    
5730                  //                    glraw.PATH        = gSystem->DirName(raw.Data());
5731                  //                    glraw.NAME        = gSystem->BaseName(raw.Data());
5732                  //                    glraw.BOOT_NUMBER = boot_number;
5733                  //                    //
5734                  //                    insertPamelaRawFile( &glraw );
5735                  //                    //              
5736                  //                    id_raw = glraw.ID;              
5737                  //                }else{
5738                  //                    row = result->Next();
5739                  //                    id_raw = (UInt_t)atoll(row->GetField(0));
5740                  //                }
5741                  //                if ( IsDebug() ) cout << "ID_RAW = "<<id_raw<<endl;
5742    
5743                  // ---------------------------------------------------------------------
5744                  // step 1(bis): retrieve the timesync id associated to the file
5745                  // (NB, uso lo stesso associato al file iniziale)
5746                  // ---------------------------------------------------------------------
5747                  UInt_t idtimesync = 0;
5748                  oss.str("");
5749                  oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" and ID_RESURS_OFFSET="<< idresof <<" limit 1;"; // 10RED BUG!!!! without 'and ID_RESURS_OFFSET="<< idresof ' this query is not enough to ensure finding the correct line in GL_TIMSYNC...
5750                  if ( debug ) printf(" %s \n",oss.str().c_str());
5751                  result = conn->Query(oss.str().c_str());
5752                  if ( !result ) throw -3;
5753                    row = result->Next();
5754                    if ( !row ) throw -3;
5755                    idtimesync = (UInt_t)atoll(row->GetField(0));
5756                    if ( IsDebug() ) cout << "ID_TIMESYNC = "<<idtimesync<<endl;
5757                    
5758                    delete result;// mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
5759                    // ---------------------------------------------------------------------
5760                    // step 2: insert a new root file in GL_ROOT
5761                    // ---------------------------------------------------------------------
5762                    //
5763                    // check if the root file already exist
5764                    //
5765                    UInt_t id_root = 0;
5766                    oss.str("");
5767                    oss << "SELECT ID FROM GL_ROOT where NAME=\"" << gSystem->BaseName(name.Data()) <<"\";";
5768                    if ( IsDebug() ) cout << oss.str().c_str() << endl;
5769                    
5770                    result = conn->Query(oss.str().c_str());
5771                    if ( !result ) throw -4;;
5772                    if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5773                    if( result->GetRowCount() == 0){
5774                        if ( IsDebug() ) cout << " << Insert new ROOT file >> "<<endl;
5775                        // - - - - - - - - - - -
5776                        // insert new root file
5777                        // - - - - - - - - - - -
5778                        GL_ROOT glroot = GL_ROOT();            
5779                        glroot.ID_RAW      = id_raw;
5780                        glroot.ID_TIMESYNC = idtimesync;
5781                        //
5782                        // 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,
5783                        //             NOT STATIC NOT KEEPENV = $PAM_L0 must be used in the DB
5784                        //
5785                        if ( STATIC ){
5786                          glroot.PATH        = (TString)gSystem->ExpandPathName(path);
5787                        } else {
5788                          if ( KEEPENV ){
5789                            glroot.PATH      = path;
5790                          } else {
5791                            glroot.PATH      = "$PAM_L0";
5792                          };
5793                        };
5794                        //              glroot.PATH        = path;
5795                        glroot.NAME        = name;
5796                        //
5797                        insertPamelaRootFile( &glroot );
5798                        //              
5799                        id_root = glroot.ID;                    
5800                    }else{
5801                        row = result->Next();
5802                        if(row)id_root = (UInt_t)atoll(row->GetField(0));
5803                    }
5804                    if ( IsDebug() ) cout << "ID_ROOT = "<<id_root<<endl;
5805    
5806                    delete result;// mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
5807                    // ---------------------------------------------------------------------
5808                    // step 3: modify time-tag of corrupted GL_TRK_CALIB entry
5809                    // ---------------------------------------------------------------------
5810                    if ( IsDebug() ) cout << " << Modify time-tag of calibration ID="<<id<<" >> "<<endl;
5811                    oss.str("");
5812                    oss << " UPDATE GL_TRK_CALIB SET "  
5813                        << " TO_TIME=0 , FROM_TIME=0  WHERE "
5814                        << " ID = "<< id  << ";";
5815                    if ( IsDebug() ) cout << oss.str().c_str() << endl;
5816                    result = conn->Query(oss.str().c_str());
5817                    if ( !result ) throw -4;;
5818    
5819                    delete result; // mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
5820    
5821                    // ---------------------------------------------------------------------
5822                    // step 4: insert the new calibration:
5823                    // ---------------------------------------------------------------------
5824                    if ( IsDebug() ) cout << " << Insert new TRK calibration >> "<<endl;
5825                    //
5826                    GL_TRK_CALIB glcal = GL_TRK_CALIB();        
5827                    //
5828                    glcal.ID_ROOT_L0        = id_root;
5829                    glcal.EV_ROOT_CALIBTRK1 = this_t1;
5830                    glcal.EV_ROOT_CALIBTRK2 = this_t2;
5831                    glcal.FROM_TIME         = fromtime;
5832                    glcal.TO_TIME           = totime;
5833                    glcal.OBT1              = obt1;
5834                    glcal.OBT2              = obt2;
5835                    glcal.PKT1              = pkt1;
5836                    glcal.PKT2              = pkt1;
5837                    glcal.BOOT_NUMBER       = GetBOOTnumber();
5838                    glcal.VALIDATION        = this_valid;
5839                    //
5840                    HandleTRK_CALIB(&glcal);
5841                    if ( IsDebug() ) cout << "ID = "<<glcal.ID<<endl;
5842                    //
5843                    
5844                }
5845                if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
5846    
5847            }while(1);//end loop over calibrations
5848            
5849            
5850            if( rresult )delete rresult; // 10RED bug
5851            if( row    )delete row;
5852            
5853            
5854    
5855            
5856    
5857    
5858        }
5859    
5860    
5861    //      // ------------------------------
5862    //      // try to recover the calibration
5863    //      // ------------------------------
5864    //      cout << "TRY TO RECOVER TRACKER CALIBRATION"<<endl;
5865    //      //
5866    //      ULong64_t time  = 0; //absolute time
5867    //      string    path[100]; //mettere un limite massimo
5868    //      int       nrows = 0;
5869    //      UInt_t    pkt   = 0;
5870    //      UInt_t    obt   = 0;
5871    //      char     *type  = "";
5872    //      EventHeader *eh   = new EventHeader();
5873    //      CalibTrk1Event *c = new CalibTrk1Event();
5874            
5875    //       //
5876    //       if(which_is_not_valid==1 || which_is_not_valid==3){
5877    //        //
5878    //        cout << "PKT1 --> missing or corrupted "<<endl;
5879    //        type = "CalibTrk1";
5880    //        pkt  = pkt1;
5881    //        obt  = obt1;
5882    //        time = this->GetAbsTime(obt1);
5883    //        if( pkt1 == 0 ){//missing
5884    //            time = this->GetAbsTime(obt2);
5885    //            pkt  = pkt2-1;          
5886    //        }
5887    //        //
5888    //       }else if (which_is_not_valid==2 || which_is_not_valid==3){
5889    //        //
5890    //        cout << "PKT2--> missing or corrupted "<<endl;
5891    //        type = "CalibTrk2 ";
5892    //        pkt  = pkt2;
5893    //        obt  = obt2;
5894    //        time = this->GetAbsTime(obt2);
5895    //        if( pkt2 == 0 ){//missing
5896    //            time = this->GetAbsTime(obt1);
5897    //            pkt  = pkt1+1;          
5898    //        }
5899    //        //
5900    //       }else{
5901    //        cout << "this should not happen!!! "<<endl;
5902    //        trow -666;
5903    //       }
5904          
5905    //       nrows = Query_ROOT_TABLE(time,conn,path);// get the list of file which might contain the packet
5906          
5907    
5908    //       for(int r=0; r<nrows; r++){ //loop over rows
5909    //        if(path)cout << r << " >>>> "<<(path+r)->c_str() << endl;
5910    //        /// verifica che il file non sia quello gia` aperto
5911    //       }
5912    
5913    //       ////////////////////////////////////////////////////////////////////////
5914    
5915    //       TSQLResult *result = 0;
5916    //       TSQLRow    *row    = 0;
5917    //       //
5918    //       stringstream oss;
5919    //       oss.str("");
5920    //       // ----------------------------------------
5921    //       // read the id of last calibration inserted
5922    //       // ----------------------------------------
5923    //       oss.str("");
5924    //       oss << " SELECT ";
5925    //       oss << " (ID,ID_ROOT_L0,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,FROM_TIME,TO_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION) ";
5926    //       oss << " ORDER BY ID DESC LIMIT 1; ";
5927          
5928    //       result = conn->Query(oss.str().c_str());
5929    //       row = result->Next();
5930    //       if( !row )throw -666;
5931    
5932    //       if( result )delete result;
5933    //       if( row    )delete row;
5934    
5935    //       UInt_t id = (UInt_t)atoll(row->GetField(0));
5936    
5937    //       // -------------------------------------
5938    //       // ...and modify it with new parameters
5939    //       // -------------------------------------
5940          
5941    
5942    //   }
5943    //    //
5944    return(0);    return(0);
5945  };  };
# Line 4967  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6148  Int_t PamelaDBOperations::CleanGL_RUN_FR
6148      memset(myid,0,500*sizeof(UInt_t));      memset(myid,0,500*sizeof(UInt_t));
6149      //      //
6150      oss.str("");      oss.str("");
6151      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;";
6152      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());
6153      nresult = conn->Query(oss.str().c_str());      nresult = conn->Query(oss.str().c_str());
6154      //      //
# Line 4998  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6179  Int_t PamelaDBOperations::CleanGL_RUN_FR
6179            while ( anr ){            while ( anr ){
6180              //              //
6181              oss.str("");              oss.str("");
6182              oss << "SELECT ID,RUNTRAILER_TIME,RUNTRAILER_PKT,BOOT_NUMBER FROM GL_RUN_FRAGMENTS WHERE BOOT_NUMBER=" << mbo << " AND RUNHEADER_PKT=" << mrhp <<  "+1 AND ABS(RUNHEADER_TIME-"<< mrht <<")<=1 AND INSERT_TIME <= '" << clean_time->AsSQLString() << "' order BY RUNHEADER_TIME asc;";              oss << "SELECT ID,RUNTRAILER_TIME,RUNTRAILER_PKT,BOOT_NUMBER FROM GL_RUN_FRAGMENTS WHERE BOOT_NUMBER=" << mbo << " AND RUNHEADER_PKT=" << mrhp <<  "+1 AND ABS(RUNHEADER_TIME-"<< (float)mrht <<")<=1 AND INSERT_TIME <= '" << clean_time->AsSQLString() << "' order BY RUNHEADER_TIME asc;"; // 10RED MYSQL OPERATOR BUG
6183              if ( IsDebug() ) printf(" In the loop searching for fragmented runs : query is \n %s \n",oss.str().c_str());              if ( IsDebug() ) printf(" In the loop searching for fragmented runs : query is \n %s \n",oss.str().c_str());
6184              //              //
6185              nresult1 = conn->Query(oss.str().c_str());              nresult1 = conn->Query(oss.str().c_str());
# Line 5061  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6242  Int_t PamelaDBOperations::CleanGL_RUN_FR
6242                    << " RM_ACQ_SETTING_MODE=" << glrun->GetRM_ACQ_SETTING_MODE()<< " , "                      << " RM_ACQ_SETTING_MODE=" << glrun->GetRM_ACQ_SETTING_MODE()<< " , "  
6243                    << " TRK_CALIB_USED=" << glrun->GetTRK_CALIB_USED()<< " , "                      << " TRK_CALIB_USED=" << glrun->GetTRK_CALIB_USED()<< " , "  
6244                    << " CAL_DSP_MASK=" << glrun->GetCAL_DSP_MASK()<< " , "                      << " CAL_DSP_MASK=" << glrun->GetCAL_DSP_MASK()<< " , "  
6245                    << " LAST_TIMESYNC=" << glrun->GetLAST_TIMESYNC()<< " , "                      << " LAST_TIMESYNC=" << glrun->GetLAST_TIMESYNC()<< " , ";
6246                    << " OBT_TIMESYNC=" << glrun->GetOBT_TIMESYNC()                //
6247                    << " WHERE ID=" << myid[u] << ";";                if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
6248                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12() << " , ";
6249                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
6250                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC() << " , ";
6251                  //              
6252                  oss << " OBT_TIMESYNC=" << glrun->GetOBT_TIMESYNC();
6253                  oss << " WHERE ID=" << myid[u] << ";";
6254                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
6255              };              };
6256              //              //
# Line 5074  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6261  Int_t PamelaDBOperations::CleanGL_RUN_FR
6261              for (UInt_t u=1; u <= nid ; u++){              for (UInt_t u=1; u <= nid ; u++){
6262                oss.str("");                oss.str("");
6263                oss << "UPDATE GL_RUN_FRAGMENTS SET "                oss << "UPDATE GL_RUN_FRAGMENTS SET "
6264                    << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , "                    << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , ";
6265                    << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "                //
6266                    << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT()<< ";";                if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
6267                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , ";
6268                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
6269                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , ";
6270                  //              
6271                  oss << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "
6272                      << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT();
6273                  oss << " WHERE ID=" << myid[u] << ";"; // BUG!!! 090112
6274                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
6275              };                  };    
6276            };            };
# Line 5098  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6292  Int_t PamelaDBOperations::CleanGL_RUN_FR
6292                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
6293                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "
6294                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< " , "                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< " , "
6295                    << " PKT_COUNTER=" << glrun->GetPKT_COUNTER()<< " , "                    << " PKT_COUNTER=" << glrun->GetPKT_COUNTER()<< " , ";
6296                    << " PKT_READY_COUNTER=" << glrun->GetPKT_READY_COUNTER()                //
6297                  if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
6298                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
6299                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) {
6300                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
6301                  //              
6302                  oss << " PKT_READY_COUNTER=" << glrun->GetPKT_READY_COUNTER()
6303                    << " WHERE ID=" << myid[u] << ";";                    << " WHERE ID=" << myid[u] << ";";
6304                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
6305              };              };
# Line 5112  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6312  Int_t PamelaDBOperations::CleanGL_RUN_FR
6312                oss.str("");                oss.str("");
6313                oss << "UPDATE GL_RUN_FRAGMENTS SET "                oss << "UPDATE GL_RUN_FRAGMENTS SET "
6314                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
6315                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , ";
6316                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< ";";                //
6317                  if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
6318                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
6319                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ){
6320                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
6321                  //              
6322                  oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT();
6323                  oss << " WHERE ID=" << myid[u] << ";"; // BUG!!! 090112
6324                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
6325              };                  };    
6326            };            };
# Line 5164  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6371  Int_t PamelaDBOperations::CleanGL_RUN_FR
6371                row2 = result2->Next();                row2 = result2->Next();
6372                //                //
6373                if ( row2 ){                if ( row2 ){
6374                  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");
6375                  if ( PEDANTIC ) throw -83;                  if ( PEDANTIC ) throw -83;
6376                  row2->Close();                  row2->Close();
6377                };                };
# Line 5241  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6448  Int_t PamelaDBOperations::CleanGL_RUN_FR
6448        glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);          glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);  
6449        //        //
6450        oss.str("");        oss.str("");
6451        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 "
6452            << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND ("            << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND ("
6453            << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "            << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
6454            << " 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 6479  Int_t PamelaDBOperations::CleanGL_RUN_FR
6479          glrun->SetID_RUN_FRAG(glrun->GetID());          glrun->SetID_RUN_FRAG(glrun->GetID());
6480          glrun->Fill_GL_RUN(conn);            glrun->Fill_GL_RUN(conn);  
6481          //          //
6482  //      oss.str("");          //      oss.str("");
6483  //      oss << " SELECT ID FROM GL_RUN WHERE "          //      oss << " SELECT ID FROM GL_RUN WHERE "
6484  //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "          //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
6485  //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "          //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
6486  //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "          //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
6487  //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "          //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
6488  //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";          //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
6489  //      //          //      //
6490  //      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());
6491  //      result2 = conn->Query(oss.str().c_str());          //      result2 = conn->Query(oss.str().c_str());
6492  //      //          //      //
6493  //      if ( !result2 ) throw -4;          //      if ( !result2 ) throw -4;
6494  //      //          //      //
6495  //      row2 = result2->Next();          //      row2 = result2->Next();
6496  //      //          //      //
6497  //      if ( !row2 ) throw -25;          //      if ( !row2 ) throw -25;
6498  //      //          //      //
6499  //      oss.str("");          //      oss.str("");
6500  //      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);
6501  //      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());
6502  //      result2 = conn->Query(oss.str().c_str());          //      result2 = conn->Query(oss.str().c_str());
6503  //      //          //      //
6504  //      if ( !result2 ) throw -4;          //      if ( !result2 ) throw -4;
6505          //          //
6506          moved++;          moved++;
6507          //          //
6508        } else {        } else {
6509          if ( IsDebug() ) printf(" The already exist in the GL_RUN table! \n");  
6510          if ( PEDANTIC ) throw -83;          // questa parte mah mah mah... da controllare
6511    
6512            //
6513            // 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
6514            // "small gap" piece... we recognize this since: we have two entries from this query, the pkt number is consistent with our pkt number.
6515            //
6516            // 090112 [8RED (-70): RUN ALREADY INSERTED]
6517            //
6518            Bool_t OK = false;
6519            UInt_t IDRL2A = 0;
6520            UInt_t IDRL2B = 0;
6521              if ( result2->GetRowCount() == 2 ){
6522                IDRL2A = (UInt_t)atoll(row2->GetField(0));
6523                UInt_t IDRL0A = (UInt_t)atoll(row2->GetField(4));
6524                row2 = result2->Next();
6525                IDRL2B = (UInt_t)atoll(row2->GetField(0));
6526                UInt_t IDRL0B = (UInt_t)atoll(row2->GetField(4));
6527                if ( IsDebug() ) printf(" IDRL0A %u B %u IDRL2A %u B %u \n",IDRL0A,IDRL0B,IDRL2A,IDRL2B);
6528                //      if ( IDRL0A == IDRL0B ){
6529    //            TSQLResult *result2a = 0;
6530    //            TSQLRow    *row2a    = 0;
6531    //            oss.str("");
6532    //            oss << "select PKT_NUMBER_FINAL from ROOT_TABLE_MERGING where REAL_TIME_INIT<" << chrtinit << " order by REAL_TIME_INIT desc limit 1;";
6533    //            if ( IsDebug() ) printf(" Check if we are in the case RH---| small gap |---RT: query is \n %s \n",oss.str().c_str());
6534    //            result2a = conn->Query(oss.str().c_str());
6535    //            //
6536    //            if ( !result2a ) throw -4;
6537    //            //
6538    //            row2a = result2a->Next();
6539    //            //
6540    //            if ( row2a ){
6541    //              UInt_t PKA = (UInt_t)atoll(row2a->GetField(0));
6542    //              delete result2a;
6543    //              oss.str("");
6544    //              oss << "select PKT_NUMBER_INIT from ROOT_TABLE_MERGING where REAL_TIME_INIT>" << chrtinit << " order by REAL_TIME_INIT asc limit 1;";
6545    //              if ( IsDebug() ) printf(" Check if we are in the case RH---| small gap |---RT: query is \n %s \n",oss.str().c_str());
6546    //              result2a = conn->Query(oss.str().c_str());
6547    //              //
6548    //              if ( !result2a ) throw -4;
6549    //              //
6550    //              row2a = result2a->Next();
6551    //              //
6552    //              if ( row2a ){
6553    //                UInt_t PKB = (UInt_t)atoll(row2a->GetField(0));
6554    //                //
6555    //                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);
6556    //                if ( PKT(PKA)+1LL == PKT(glrun->GetRUNHEADER_PKT()) && PKT(PKB) == PKT(glrun->GetRUNTRAILER_PKT())+1LL ){
6557    //                  if ( IsDebug() ) printf(" Ok, we are in the case: RH---| small gap |---RT \n");
6558                        OK = true;
6559                        //            };
6560                        //          };
6561                        //        };                  
6562                        //    };
6563              };      
6564            if ( OK ){
6565              //
6566              // this is the case in which we must insert a piece of run between two fragments in the GL_RUN table
6567              //
6568              // 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 )
6569              //
6570              GL_RUN *glA = new GL_RUN();
6571              glA->Query_GL_RUN(IDRL2A,conn);
6572              //
6573              if ( glA->GetACQ_BUILD_INFO() != 0 ){
6574                //
6575                // the first piece contains a good runheader we can update all the other runs with correct infos!
6576                //
6577                oss.str("");
6578                oss << "UPDATE GL_RUN_FRAGMENTS SET "
6579                    << " RUNHEADER_TIME=" << glA->GetRUNHEADER_TIME()<< " , "
6580                    << " RUNHEADER_OBT=" << glA->GetRUNHEADER_OBT()<< " , "
6581                    << " RUNHEADER_PKT=" << glA->GetRUNHEADER_PKT()<< " , "
6582                    << " COMPILATIONTIMESTAMP=" << glA->GetCOMPILATIONTIMESTAMP()<< " , "
6583                    << " FAV_WRK_SCHEDULE=" << glA->GetFAV_WRK_SCHEDULE()<< " , "
6584                    << " EFF_WRK_SCHEDULE=" << glA->GetEFF_WRK_SCHEDULE()<< " , "
6585                    << " PRH_VAR_TRG_MODE_A=" << glA->GetPRH_VAR_TRG_MODE_A()<< " , "
6586                    << " PRH_VAR_TRG_MODE_B=" << glA->GetPRH_VAR_TRG_MODE_B()<< " , "
6587                    << " ACQ_BUILD_INFO=" << glA->GetACQ_BUILD_INFO()<< " , "
6588                    << " ACQ_VAR_INFO=" << glA->GetACQ_VAR_INFO()<< " , "
6589                    << " RM_ACQ_AFTER_CALIB=" << glA->GetRM_ACQ_AFTER_CALIB()<< " , "  
6590                    << " RM_ACQ_SETTING_MODE=" << glA->GetRM_ACQ_SETTING_MODE()<< " , "  
6591                    << " TRK_CALIB_USED=" << glA->GetTRK_CALIB_USED()<< " , "  
6592                    << " CAL_DSP_MASK=" << glA->GetCAL_DSP_MASK()<< " , "  
6593                    << " LAST_TIMESYNC=" << glA->GetLAST_TIMESYNC()<< " , ";
6594                //
6595                if ( glA->GetPHYSENDRUN_MASK_S3S2S12() )
6596                  oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12() << " , ";
6597                if ( glA->GetPHYSENDRUN_MASK_S11CRC() )
6598                  oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC() << " , ";
6599                //        
6600                oss << " OBT_TIMESYNC=" << glA->GetOBT_TIMESYNC();
6601                oss << " WHERE ID=" << glrun->GetID() << ";";
6602                if ( IsDebug() ) printf(" update with correct infos: %s\n",oss.str().c_str());
6603                conn->Query(oss.str().c_str());    
6604                //
6605              } else {
6606                //
6607                // sig no runheader, let set anyway what is possible...
6608                //
6609                oss.str("");
6610                oss << "UPDATE GL_RUN_FRAGMENTS SET "
6611                    << " RUNHEADER_TIME=" << glA->GetRUNHEADER_TIME()<< " , ";
6612                //
6613                if ( glA->GetPHYSENDRUN_MASK_S3S2S12() )
6614                  oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , ";
6615                if ( glA->GetPHYSENDRUN_MASK_S11CRC() )
6616                  oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , ";
6617                //        
6618                oss << " RUNHEADER_OBT=" << glA->GetRUNHEADER_OBT()<< " , "
6619                    << " RUNHEADER_PKT=" << glA->GetRUNHEADER_PKT();
6620                oss << " WHERE ID=" << glrun->GetID() << ";";
6621                if ( IsDebug() ) printf(" update with correct infos2: %s\n",oss.str().c_str());
6622                conn->Query(oss.str().c_str());    
6623              };
6624              //
6625              // update runheader ROOT_ID_FRAG
6626              //
6627              oss.str("");
6628              oss << "UPDATE GL_RUN SET ID_RUN_FRAG = " << glrun->GetID() << " where ID = " << IDRL2A << ";";
6629              if ( IsDebug() ) printf(" update gl_run to have cross indexing: %s\n",oss.str().c_str());
6630              conn->Query(oss.str().c_str());
6631              //
6632              // now let's look for runtrailer if any in the last run
6633              //
6634              glA->Query_GL_RUN(IDRL2B,conn);
6635              //
6636              if ( glA->GetPKT_READY_COUNTER() != 0 ){
6637                //
6638                // the first piece contains a good runtrailer we can update all the other runs with correct infos!
6639                //
6640                oss.str("");
6641                oss << "UPDATE GL_RUN_FRAGMENTS SET "
6642                    << " RUNTRAILER_TIME=" << glA->GetRUNTRAILER_TIME()<< " , "
6643                    << " RUNTRAILER_OBT=" << glA->GetRUNTRAILER_OBT()<< " , "
6644                    << " RUNTRAILER_PKT=" << glA->GetRUNTRAILER_PKT()<< " , "
6645                    << " PKT_COUNTER=" << glA->GetPKT_COUNTER()<< " , ";
6646                //
6647                if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ){
6648                  oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
6649                if ( glA->GetPHYSENDRUN_MASK_S11CRC() ) {
6650                  oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
6651                //        
6652                oss << " PKT_READY_COUNTER=" << glA->GetPKT_READY_COUNTER()
6653                    << " WHERE ID=" << glrun->GetID() << ";";
6654                if ( IsDebug() ) printf(" update with correct trailer infos: %s\n",oss.str().c_str());
6655                conn->Query(oss.str().c_str());    
6656                //
6657              } else {
6658                //
6659                // sig no runtrailer, let set anyway what is possible...
6660                //
6661                oss.str("");
6662                oss << "UPDATE GL_RUN_FRAGMENTS SET "
6663                    << " RUNTRAILER_TIME=" << glA->GetRUNTRAILER_TIME()<< " , "
6664                    << " RUNTRAILER_OBT=" << glA->GetRUNTRAILER_OBT()<< " , ";
6665                  //
6666                if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ){
6667                  oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
6668                if ( glA->GetPHYSENDRUN_MASK_S11CRC() ){
6669                  oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
6670                //        
6671                oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()
6672                    << " WHERE ID=" << glrun->GetID() << ";";
6673                if ( IsDebug() ) printf(" update with correct trailer infos2: %s\n",oss.str().c_str());
6674                conn->Query(oss.str().c_str());    
6675              };
6676              //
6677              UInt_t myi = glrun->GetID();
6678              oss.str("");
6679              oss << " ID= "<< myi;
6680              //
6681              glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);  
6682              //
6683              // fill the new run in GL_RUN
6684              //
6685              glrun->SetID_RUN_FRAG(IDRL2B);
6686              glrun->Fill_GL_RUN(conn);    
6687              glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
6688              delete glA;
6689              moved++;
6690              //
6691            } else {
6692              //
6693              // is just a repetition
6694              //
6695              if ( IsDebug() ) printf(" The run %u is already present in the GL_RUN table...\n",glrun->GetID());    
6696              //      printf(" CCCCCCCCICCCCCCCCCCCCIOOOOOOOOOO si muove Ciccio! %u \n",glrun->GetID());
6697              //      if ( PEDANTIC && glrun->GetID() != 61563 ) throw -83;
6698              if ( PEDANTIC ) throw -83;
6699            };
6700            //      if ( IsDebug() ) printf(" The run already exists in the GL_RUN table! ...\n");
6701            //      if ( PEDANTIC ) throw -83;
6702        };        };
6703        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));      
6704        //        //
6705        //        //
6706        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
6707  //      oss.str("");        //      oss.str("");
6708  //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);        //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);
6709  //       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());
6710  //       result2 = conn->Query(oss.str().c_str());        //       result2 = conn->Query(oss.str().c_str());
6711  //      //        //      //
6712  //      if ( !result2 ) throw -4;        //      if ( !result2 ) throw -4;
6713  //      //        //      //
6714        row = result->Next();        row = result->Next();
6715      };      };
6716    };    };
# Line 5366  Int_t PamelaDBOperations::ValidateRuns(T Line 6764  Int_t PamelaDBOperations::ValidateRuns(T
6764      // 2) get the OBT of the last validated run      // 2) get the OBT of the last validated run
6765      // --------------------------------------------------------------      // --------------------------------------------------------------
6766      oss.str("");      oss.str("");
6767      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
6768        oss << " SELECT * FROM GL_RUN  WHERE VALIDATION>0 AND RUNHEADER_TIME<="<< t_start
6769          <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";          <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
6770      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());
6771      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
# Line 5457  Int_t PamelaDBOperations::ValidateRuns(T Line 6856  Int_t PamelaDBOperations::ValidateRuns(T
6856    GL_RUN* this_run = new GL_RUN();    GL_RUN* this_run = new GL_RUN();
6857    GL_RUN* next_run = new GL_RUN();    GL_RUN* next_run = new GL_RUN();
6858    Int_t   nseq_max = 1000;    Int_t   nseq_max = 1000;
6859  //  UInt_t* sequence = new UInt_t[100];    //  UInt_t* sequence = new UInt_t[100];
6860    vector<UInt_t> sequence(nseq_max);    vector<UInt_t> sequence(nseq_max);
6861    Int_t   nseq = 0;    Int_t   nseq = 0;
6862    Bool_t CHECK = false;    Bool_t CHECK = false;
# Line 5472  Int_t PamelaDBOperations::ValidateRuns(T Line 6871  Int_t PamelaDBOperations::ValidateRuns(T
6871    // ---------------------------------------------------------------------------------    // ---------------------------------------------------------------------------------
6872    while(1){    while(1){
6873                        
6874            row = result->Next();      row = result->Next();
6875            if( row == NULL ) break;      if( row == NULL ) break;
6876                        
6877            //------------      //------------
6878            //get run info      //get run info
6879            //------------      //------------
6880            this_run->Set_GL_RUN(row);      this_run->Set_GL_RUN(row);
6881                                        
6882            Bool_t this_BAD = false;      Bool_t this_BAD = false;
6883            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;
6884            else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;      else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;
6885            else{      else{
6886  //                printf("Missing or corrupted header!! \n");        //                  printf("Missing or corrupted header!! \n");
6887                    this_ONLINE = false;        this_ONLINE = false;
6888                    this_BAD = true;        this_BAD = true;
6889            };      };
6890    
6891            //-----------------------------------      //-----------------------------------
6892            //compare with previous(next in time)      //compare with previous(next in time)
6893            //-----------------------------------      //-----------------------------------
6894            CHECK = false;      CHECK = false;
6895            UInt_t interval=0;      UInt_t interval=0;
6896                        
6897            if( nrow != 0){      if( nrow != 0){
6898                    
6899                                        
6900                    t1 = this_run->GetRUNTRAILER_TIME();        t1 = this_run->GetRUNTRAILER_TIME();
6901                    t2 = next_run->GetRUNHEADER_TIME();        t2 = next_run->GetRUNHEADER_TIME();
6902                    interval = (t2-t1);        interval = (t2-t1);
6903                                        
6904                    if(this_ONLINE && next_ONLINE){                               // this: ON-LINE + next: ON-LINE        if(this_ONLINE && next_ONLINE){                           // this: ON-LINE + next: ON-LINE
6905                                                        
6906                            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
6907                                                        
6908                            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
6909                                                        
6910                            if( !CHECK && this_run->VALIDATION ){          if( !CHECK && this_run->VALIDATION ){
6911                                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);            //      for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
6912                                    nseq=0;            for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],this_run->VALIDATION);
6913                            }            nseq=0;
6914            }
6915                                        
6916                    }else if( !this_ONLINE && next_ONLINE) {              // this: DEFAULT + next:ON-LINE        }else if( !this_ONLINE && next_ONLINE) {          // this: DEFAULT + next:ON-LINE
6917                                                        
6918                            CHECK = true;          CHECK = true;
6919    
6920                    }else if( !next_ONLINE ){                                             // this:ANY + next:DEFAULT        }else if( !next_ONLINE ){                                         // this:ANY + next:DEFAULT
6921                                                        
6922                            assignVALIDATION(next_run->ID,true);          assignVALIDATION(next_run->ID,true);
6923                            nseq=0;          nseq=0;
6924                    }        }
6925            }      }
6926    
6927            //----------------------------      //----------------------------
6928            //check run sequence for calib      //check run sequence for calib
6929            //----------------------------      //----------------------------
6930            if( CHECK ){      if( CHECK ){
6931                    // check if calibration exists        // check if calibration exists
6932                    if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);        if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);
6933                    Bool_t MISSING = MissingTRK_CALIB(t1,t2);        //      Bool_t MISSING = MissingTRK_CALIB(t1,t2);
6934                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],!MISSING);        UInt_t MISSING = MissingTRK_CALIB(t1,t2);
6935                    nseq=0;        UInt_t val = 0;
6936            };        if ( MISSING == 1 ) val = 0;
6937            //--------------        if ( MISSING == 0 ) val = 1;
6938            //store run info        if ( MISSING == 2 ) val = 2;
6939            //--------------        for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],val);
6940            *next_run   = *this_run;        nseq=0;
6941            next_ONLINE = this_ONLINE;      };
6942            if( !this_BAD ){      //--------------
6943                    if(nseq < nseq_max){      //store run info
6944                            sequence[nseq] = this_run->ID;      //--------------
6945                            nseq++;      *next_run   = *this_run;
6946                    }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);      next_ONLINE = this_ONLINE;
6947            };      if( !this_BAD ){
6948          if(nseq < nseq_max){
6949            sequence[nseq] = this_run->ID;
6950            nseq++;
6951          }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);
6952        };
6953                        
6954            if ( IsDebug() ) printf("%i Run %u \n",nrow,this_run->ID);      if ( IsDebug() ) printf("%i Run %u \n",nrow,this_run->ID);
6955            nrow++;      nrow++;
6956                        
6957    };    };
6958    delete this_run;    delete this_run;
# Line 5561  Int_t PamelaDBOperations::ValidateRuns(T Line 6966  Int_t PamelaDBOperations::ValidateRuns(T
6966   * @param t2 To absolute time   * @param t2 To absolute time
6967   * @return true if there might be a missing calibration   * @return true if there might be a missing calibration
6968   */   */
6969  Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){  //Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
6970    UInt_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
6971                    
6972          GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();    GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();
6973                    
6974          // get the closest VALIDATED calibration before the run start (t2)    // get the closest calibration before the run start (t2)
6975          if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true);      //>>> missing    //  if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true);        //>>> missing
6976      if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(1);       //>>> missing
6977                    
6978          if ( trkcalib->TO_TIME  < t2 ) return(true);                                    //>>> missing    //  if ( trkcalib->TO_TIME  < t2 ) return(true);                                      //>>> missing
6979      if ( trkcalib->TO_TIME  < t2 ) return(1);                                     //>>> missing
6980                    
6981          //==============================================================    //==============================================================
6982          // Check is done first on the basis of time between calibration,    // Check is done first on the basis of time between calibration,
6983          // which should be equal to the time between ascending-nodes.    // which should be equal to the time between ascending-nodes.
6984          //==============================================================    //==============================================================
6985          if ( t2 - trkcalib->FROM_TIME > 5700) {    if ( t2 - trkcalib->FROM_TIME > 5700) {
6986                  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);
6987          //==============================================================      //==============================================================
6988          // there might be a missing calibration, due to:      // there might be a missing calibration, due to:
6989          // - MM full      // - MM full
6990          // - corrupted packets      // - corrupted packets
6991          // - loss of data      // - loss of data
6992          // 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
6993          //==============================================================      //==============================================================
6994                  Bool_t DOWNLOAD = false;      Bool_t DOWNLOAD = false;
6995                  // check if the calib was skipped becouse of download .... DA FARE!!      // check if the calib was skipped becouse of download .... DA FARE!!
6996                  if(DOWNLOAD)return(false);      //    if(DOWNLOAD)return(false);
6997        if(DOWNLOAD)return(0);
6998                                    
6999                  return(true);                                   //>>> missing      //    return(true);                                         //>>> missing
7000        return(1);                                  //>>> missing
7001                                    
7002          };    };
7003                    
7004          //==============================================================    //==============================================================
7005          // 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,
7006          // it is enough to say that there are no missing calibrations    // it is enough to say that there are no missing calibrations
7007          //==============================================================    //==============================================================
7008          // the long time interval bewteen runs might be due to download    // the long time interval bewteen runs might be due to download
7009          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);
7010          return(false);    if ( trkcalib->VALIDATION ) return(0);
7011      if ( IsDebug() )printf("Calibration is not validated... :-/ ==> OK but with VALIDATION=2! \n");
7012      return(2);
7013                    
7014  };  };
7015  /**  /**
# Line 5606  Bool_t PamelaDBOperations::MissingTRK_CA Line 7018  Bool_t PamelaDBOperations::MissingTRK_CA
7018   * @param validation true/false   * @param validation true/false
7019   */   */
7020  Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){  Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){
7021          TSQLResult *result = 0;    return(this->assignVALIDATION(idrun,(UInt_t)validation));
7022          stringstream oss;  }
7023          oss.str("");  
7024          oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";  Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, UInt_t validation){
7025          //    TSQLResult *result = 0;
7026  //      if ( IsDebug() )    stringstream oss;
7027  //      printf(" Set VALIDATION = %i for run %i \n",validation,idrun);    oss.str("");
7028          if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());    oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";
7029          result = conn->Query(oss.str().c_str());    //
7030          if ( !result ) throw -4;    //    if ( IsDebug() )
7031          return(0);    //    printf(" Set VALIDATION = %i for run %i \n",validation,idrun);
7032      if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());
7033      result = conn->Query(oss.str().c_str());
7034      if ( !result ) throw -4;
7035      return(0);
7036  }  }
7037    
7038    
# Line 5802  Int_t PamelaDBOperations::removeFile(TSt Line 7218  Int_t PamelaDBOperations::removeFile(TSt
7218    stringstream myquery;    stringstream myquery;
7219    //      //  
7220    myquery.str("");    myquery.str("");
7221    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() <<"';";
7222    //    //
7223    pResult = conn->Query(myquery.str().c_str());    pResult = conn->Query(myquery.str().c_str());
7224    //    //
# Line 5818  Int_t PamelaDBOperations::removeFile(TSt Line 7234  Int_t PamelaDBOperations::removeFile(TSt
7234    //    //
7235    this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));    this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));
7236    this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));    this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));
7237      UInt_t idtsy=(UInt_t)atoll(Row->GetField(2));
7238    //    //
7239    this->ValidationOFF();    this->ValidationOFF();
7240    //    //
# Line 5825  Int_t PamelaDBOperations::removeFile(TSt Line 7242  Int_t PamelaDBOperations::removeFile(TSt
7242    //    //
7243    this->RemoveRUNS();    this->RemoveRUNS();
7244    //    //
7245    this->RemoveFILES();    this->RemoveFILES(idtsy);
7246    //    //
7247    this->SetID_ROOT(0);    this->SetID_ROOT(0);
7248    this->SetID_RAW(0);    this->SetID_RAW(0);
# Line 6045  void PamelaDBOperations::RemoveRUNS(){ Line 7462  void PamelaDBOperations::RemoveRUNS(){
7462   * Rearrange calibration tables   * Rearrange calibration tables
7463   *   *
7464   **/   **/
7465  void PamelaDBOperations::RemoveFILES(){  void PamelaDBOperations::RemoveFILES(UInt_t idtsy){
7466    stringstream myquery;    stringstream myquery;
7467    //    //
7468    myquery.str("");    myquery.str("");
# Line 6055  void PamelaDBOperations::RemoveFILES(){ Line 7472  void PamelaDBOperations::RemoveFILES(){
7472    //    //
7473    conn->Query(myquery.str().c_str());    conn->Query(myquery.str().c_str());
7474    //    //
7475      myquery.str("");
7476      myquery << " DELETE FROM GL_ROOT WHERE ID=" <<this->GetID_ROOT() <<";";
7477      //
7478      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
7479      //
7480      conn->Query(myquery.str().c_str());  //
7481      //
7482      if ( !chewbacca ){
7483        myquery.str("");
7484        myquery << " DELETE FROM GL_TIMESYNC WHERE ID=" << idtsy <<";";
7485        //
7486        if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
7487        //
7488        conn->Query(myquery.str().c_str());
7489      };
7490      //
7491  };  };
7492    
7493  /**  /**
# Line 6259  void PamelaDBOperations::RemoveCALIBS(){ Line 7692  void PamelaDBOperations::RemoveCALIBS(){
7692   * Rearrange calibration tables   * Rearrange calibration tables
7693   *   *
7694   **/   **/
7695  UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh ){  UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh , TFile *file){
7696    
7697        if(!caltrk) return 0;
7698    
7699        if ( IsDebug() ) cout << "ValidateTrkCalib:"<<endl;
7700    
7701        UInt_t validate = 1;
7702      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};
7703      UInt_t timeaftercalib=120000; //2000;      UInt_t timeaftercalib=120000; //2000;
7704  //  ----------      TString classname = caltrk->GetName();
7705  //  Check CRCs  
7706  //  ----------  //  ----------------------------------
7707    //  Check CRCs and failed calibrations
7708    //  ----------------------------------
7709      for(Int_t ipkt=0; ipkt<6; ipkt++){      for(Int_t ipkt=0; ipkt<6; ipkt++){
7710          if( caltrk->crc_hcal[ipkt] )return 0; // :-(          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
7711          for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] )return 0; // :-(              if( caltrk->crc_hcal[ipkt] ){
7712    //              if(IsDebug())cout<<"(CRC Header)";
7713                    validate = 0;
7714                    if(IsDebug())cout <<endl<<" *** CRC *** (header DSPn "<<caltrk->DSPnumber[ipkt]<<")";
7715            
7716                }
7717                for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] ){
7718    //              if(IsDebug())cout<<"(CRC Pkt-"<<ilad<<")";
7719                    if(IsDebug())cout <<endl<<" *** CRC *** (data DSPn "<<caltrk->DSPnumber[ipkt]<<" ladder "<<ilad<<")";
7720                    validate = 0;
7721                }
7722                if( !(caltrk->ncalib_event[ipkt]==0 && caltrk->cal_flag[ipkt]==0) ){
7723                    if(IsDebug())cout <<endl<<" *** FAILURE ***     (data DSPn "<<caltrk->DSPnumber[ipkt]<<")";
7724                    validate = 0;
7725                }
7726            }else{
7727    //          validate=0;
7728                if(IsDebug())cout <<endl<<" *** DSPn *** ("<< caltrk->DSPnumber[ipkt] <<" @pkt "<<ipkt<<")";
7729            }
7730      }      }
7731    
7732  //  -----------------------  //  -----------------------
7733  //  Check missing packets:  //  Check missing packets:
7734  //  -----------------------  //  -----------------------
# Line 6295  UInt_t PamelaDBOperations::ValidateTrkCa Line 7754  UInt_t PamelaDBOperations::ValidateTrkCa
7754  //  Check if it is first or second calibration packet  //  Check if it is first or second calibration packet
7755  //  -------------------------------------------------  //  -------------------------------------------------
7756      UInt_t build=0;      UInt_t build=0;
     TString classname = caltrk->GetName();  
7757      UInt_t base=0;      UInt_t base=0;
7758      UInt_t mask=0;      UInt_t mask=0;
7759      if(classname.Contains("CalibTrk1Event")){      if(classname.Contains("CalibTrk1Event")){
# Line 6306  UInt_t PamelaDBOperations::ValidateTrkCa Line 7764  UInt_t PamelaDBOperations::ValidateTrkCa
7764          base=18;          base=18;
7765          mask=0xFC0000;          mask=0xFC0000;
7766      }      }
7767  //  -------------------------------------------------  //  ----------------------------------------------------
7768  //  Count number of packets and set build variable  //  Count number of valid packets and set build variable
7769  //  -------------------------------------------------  //  ----------------------------------------------------
7770        if(IsDebug())cout <<endl<< " DSP: ";
7771      Int_t  npkts=0;      Int_t  npkts=0;
7772      for(Int_t ipkt=0; ipkt<6; ipkt++){      for(Int_t ipkt=0; ipkt<6; ipkt++){
7773          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
7774                if(IsDebug())cout <<" "<<caltrk->DSPnumber[ipkt];
7775              npkts++;              npkts++;
7776              build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );              build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );
7777          }  //          cout << caltrk->DSPnumber[ipkt]
7778            };
7779      }      }
7780  //    if( npkts==6 )return 1; // :-)      if(IsDebug())cout << " ==> "<< hex << build << dec;
7781    //  ----------------------------------------------------
7782  //    cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime()<<endl;  //  If the number of valid packets is 6, ok exit...
7783    //  ----------------------------------------------------
7784  //  -----------------------------------------------      if( npkts==6 ){
7785  //  If missing packets: check the acq configuration          return validate; // exit
7786        }
7787    ////////////////////////////////////////////////////////
7788    //  ...otherwise there might be some missing packets
7789    //
7790    //  In this case check the acq configuration
7791  //  (some DSPs might be excluded from acquisition)  //  (some DSPs might be excluded from acquisition)
7792  //  -----------------------------------------------  ////////////////////////////////////////////////////////
7793    
7794        if(!eh || !file || (file&&file->IsZombie()) ){
7795            if ( IsDebug() )cout << " *** MISSING VIEW *** eh="<<eh<<" file="<<file<<" cannot validate"<<endl;
7796            return (0);
7797        }
7798        
7799  //  -----------------------------------------------  //  -----------------------------------------------
7800  //  retrieve the first run header after calib  //  retrieve the first run header after calib
7801  //  -----------------------------------------------  //  -----------------------------------------------
7802       PacketType *pctp;      
7803       EventCounter *cod;      PacketType *pctp;
7804       cod = eh->GetCounter();      EventCounter *cod;
7805       Int_t irun = cod->Get(pctp->RunHeader);      cod = eh->GetCounter();
7806       TTree *rh=(TTree*)file->Get("RunHeader");      Int_t irun = cod->Get(pctp->RunHeader);
7807       if ( !rh || rh->IsZombie() ) throw -17;      TTree *rh=(TTree*)file->Get("RunHeader");
7808       if( rh->GetEntries() == irun ){      if ( !rh || rh->IsZombie() ) throw -17;
7809            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (1)  -- cannot validate :-( "<<endl;      if( rh->GetEntries() <= irun ){
7810           return 0; // :-(          if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (1) -- cannot validate :-( "<<endl;
7811       }          return 0; // :-(
7812        }
7813       RunHeaderEvent *run  = 0;      RunHeaderEvent *run  = 0;
7814       EventHeader    *hrun = 0;      EventHeader    *hrun = 0;
7815       rh->SetBranchAddress("RunHeader", &run);      rh->SetBranchAddress("RunHeader", &run);
7816       rh->SetBranchAddress("Header", &hrun);      rh->SetBranchAddress("Header", &hrun);
7817       rh->GetEntry(irun);      rh->GetEntry(irun);    
7818  //     cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime() << " Run " << hrun->GetPscuHeader()->GetOrbitalTime() <<endl;      if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){
7819            if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (2) -- cannot validate :-( "<<endl;
7820       if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){          return 0; // :-(
7821            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (2) -- cannot validate :-( "<<endl;      }
7822           return 0; // :-(  
7823       }      UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());
7824            if( dtime > timeaftercalib ){
7825       if( !run->RM_ACQ_AFTER_CALIB ){          if ( IsDebug() ) cout << " *** MISSING-PKT *** run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;
7826            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) RM_ACQ_AFTER_CALIB=0    -- cannot validate :-( "<<endl;          return 0; // :-(
7827           return 0; // :-(      }
7828       }  
7829        if ( IsDebug() ) cout <<endl<< " ACQ_BUILD_INFO ==> "<<hex<<(run->ACQ_BUILD_INFO & mask)<<dec;
7830       UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());  
7831       if( dtime > timeaftercalib ){      if( (run->ACQ_BUILD_INFO & mask) != build ){
7832           if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;          validate=0; // :-(
7833           return 0; // :-(          cout <<endl<< " *** MISSING-PKT *** packet mismatch: ACQ_BUILD_INFO="<<hex<<(run->ACQ_BUILD_INFO&mask)<<" != "<<build<<dec;
7834       }      };
7835        
7836        return validate;
7837    
      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; // :-)  
7838    
7839  }  }
7840    
# Line 6378  UInt_t PamelaDBOperations::ValidateTrkCa Line 7844  UInt_t PamelaDBOperations::ValidateTrkCa
7844   *   *
7845   **/   **/
7846  UInt_t PamelaDBOperations::Check(){  UInt_t PamelaDBOperations::Check(){
7847          return(this->Check(0,0));    return(this->Check(0,0));
7848  }  }
7849    
7850  UInt_t PamelaDBOperations::Check(UInt_t from, UInt_t to){  UInt_t PamelaDBOperations::Check(UInt_t from, UInt_t to){
7851    //    //
7852          if ( IsDebug() ) printf(" from %u to %u \n",from,to);    if ( IsDebug() ) printf(" from %u to %u \n",from,to);
7853    //    //
7854    UInt_t test = 0;    UInt_t test = 0;
7855    //    //
# Line 6424  UInt_t PamelaDBOperations::Check(UInt_t Line 7890  UInt_t PamelaDBOperations::Check(UInt_t
7890      //      //
7891      if ( from > 0 && nid <= from ) goto ss;      if ( from > 0 && nid <= from ) goto ss;
7892      if ( to > 0 && nid >= to ) goto ss;      if ( to > 0 && nid >= to ) goto ss;
7893  //      //
7894      if ( (UInt_t)atoll(row->GetField(4)) > 1 ){      if ( (UInt_t)atoll(row->GetField(4)) > 1 ){
7895        //        //
7896        //        //
# Line 6455  UInt_t PamelaDBOperations::Check(UInt_t Line 7921  UInt_t PamelaDBOperations::Check(UInt_t
7921              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)));  
7922              row3 = result3->Next();              row3 = result3->Next();
7923            };            };
7924  //      delete result3;            //    delete result3;
7925    
7926          };          };
7927          //          //
# Line 6476  UInt_t PamelaDBOperations::Check(UInt_t Line 7942  UInt_t PamelaDBOperations::Check(UInt_t
7942              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)));
7943              row3 = result3->Next();              row3 = result3->Next();
7944            };            };
7945  //      delete result3;            //    delete result3;
7946          };          };
7947          //          //
7948          oss.str("");          oss.str("");
# Line 6496  UInt_t PamelaDBOperations::Check(UInt_t Line 7962  UInt_t PamelaDBOperations::Check(UInt_t
7962              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)));
7963              row3 = result3->Next();              row3 = result3->Next();
7964            };            };
7965   //     delete result3;            //    delete result3;
7966    
7967          };          };
7968        };        };
# Line 6517  UInt_t PamelaDBOperations::Check(UInt_t Line 7983  UInt_t PamelaDBOperations::Check(UInt_t
7983            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)));
7984            row3 = result3->Next();            row3 = result3->Next();
7985          };          };
7986  //      delete result3;          //      delete result3;
7987        };        };
7988        //        //
7989      };      };
# Line 6543  UInt_t PamelaDBOperations::Check(UInt_t Line 8009  UInt_t PamelaDBOperations::Check(UInt_t
8009        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
8010        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
8011        test = 1;        test = 1;
8012  //      delete result2;        //        delete result2;
8013      };      };
8014      //      //
8015      if ( (thisrtt < prevrht) && (thisrht != prevrht) ){      if ( (thisrtt < prevrht) && (thisrht != prevrht) ){
# Line 6565  UInt_t PamelaDBOperations::Check(UInt_t Line 8031  UInt_t PamelaDBOperations::Check(UInt_t
8031        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
8032        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
8033        test = 1;        test = 1;
8034  //      delete result2;        //        delete result2;
8035      };      };
8036      //      //
8037      if ( (thisrht > thisrtt) && (thisrht != prevrht) ){      if ( (thisrht > thisrtt) && (thisrht != prevrht) ){
# Line 6587  UInt_t PamelaDBOperations::Check(UInt_t Line 8053  UInt_t PamelaDBOperations::Check(UInt_t
8053        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
8054        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
8055        test = 1;        test = 1;
8056  //      delete result2;        //        delete result2;
8057      };      };
8058  ss:    ss:
8059      //      //
8060      prevrht = thisrht;      prevrht = thisrht;
8061      prevrtt = thisrtt;      prevrtt = thisrtt;
8062      previd = thisid;      previd = thisid;
8063      prevl0id = thisl0id;      prevl0id = thisl0id;
8064      row = result->Next();      row = result->Next();
8065  //    if ( result2 ) delete result2;      //    if ( result2 ) delete result2;
8066  //    if ( result3 ) delete result3;      //    if ( result3 ) delete result3;
8067    };    };
8068    //    //
8069    return(test);    return(test);

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

  ViewVC Help
Powered by ViewVC 1.1.23