/[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.36 by mocchiut, Wed Apr 10 11:29:38 2013 UTC
# Line 58  string getTleDatetime(cTle*); Line 58  string getTleDatetime(cTle*);
58   * @param debug        debug flag.   * @param debug        debug flag.
59   * @param tlefilename  ascii file with TLE 3 line elements.   * @param tlefilename  ascii file with TLE 3 line elements.
60   */   */
61  PamelaDBOperations::PamelaDBOperations(TString host, TString user, TString password, TString filerawname, TString filerootname, UInt_t boot, UInt_t tsync, UInt_t obt0, Bool_t debug, TString tlefilename, UInt_t dwinput, Bool_t staticp, Bool_t gpamela){  PamelaDBOperations::PamelaDBOperations(TString host, TString user, TString password, TString filerawname, TString filerootname, UInt_t boot, UInt_t tsync, UInt_t obt0, Bool_t debug, TString tlefilename, UInt_t dwinput, Bool_t staticp, Bool_t gpamela, Bool_t keepenv){
62    //    //
63      RELAXED = false;
64    chewbacca = false;    chewbacca = false;
65    chminentry = 0;    chminentry = 0;
66    chID = 0;    chID = 0;
# Line 76  PamelaDBOperations::PamelaDBOperations(T Line 77  PamelaDBOperations::PamelaDBOperations(T
77      //      //
78    };    };
79    //    //
80      KEEPENV = false;
81      if ( keepenv ) KEEPENV=true;
82    STATIC=false;    STATIC=false;
83    if ( staticp ) STATIC=true;    if ( staticp ) STATIC=true;
84    //    //
# Line 85  PamelaDBOperations::PamelaDBOperations(T Line 88  PamelaDBOperations::PamelaDBOperations(T
88    //    //
89    glrun = new GL_RUN();    glrun = new GL_RUN();
90    //    //
91    if ( !chewbacca ){    //   if ( !chewbacca ){
92      if ( !boot ) SetNOBOOT(false);    //     if ( !boot ) SetNOBOOT(false);
93      SetTsync(tsync,gpamela);    //     SetTsync(tsync,gpamela);
94      SetBOOTnumber(boot,gpamela);    //     SetBOOTnumber(boot,gpamela);
95      SetObt0(obt0);    //     SetObt0(obt0);
96    };    //   };
97    //    //
98    SetTLEPath(tlefilename);    SetTLEPath(tlefilename);
99    //    //
# Line 99  PamelaDBOperations::PamelaDBOperations(T Line 102  PamelaDBOperations::PamelaDBOperations(T
102    if (INSERT_RAW) SetRawName(filerawname);    if (INSERT_RAW) SetRawName(filerawname);
103    //    //
104    INSERT_ROOT = !filerootname.IsNull();    INSERT_ROOT = !filerootname.IsNull();
105      if ( INSERT_ROOT ) this->SetRootName(filerootname);
106    this->SetOrbitNo(dwinput);    this->SetOrbitNo(dwinput);
107    //    //
108    this->SetID_RAW(0);    this->SetID_RAW(0);
# Line 122  void PamelaDBOperations::Close(){ Line 126  void PamelaDBOperations::Close(){
126  //  //
127  // SETTERS  // SETTERS
128  //  //
129    void PamelaDBOperations::NotChewbacca(UInt_t boot, UInt_t tsync, UInt_t obt0, Bool_t gpamela){
130      if ( !boot ) SetNOBOOT(false);
131      SetTsync(tsync,gpamela);
132      SetBOOTnumber(boot,gpamela);
133      SetObt0(obt0);
134    };
135    
136  void PamelaDBOperations::OpenL0File(TString filerootname){  void PamelaDBOperations::OpenL0File(TString filerootname){
137    if( INSERT_ROOT ){    if( INSERT_ROOT ){
# Line 132  void PamelaDBOperations::OpenL0File(TStr Line 142  void PamelaDBOperations::OpenL0File(TStr
142        stringstream qu;        stringstream qu;
143        TSQLResult *result = 0;        TSQLResult *result = 0;
144        TSQLResult *result2 = 0;        TSQLResult *result2 = 0;
145          TSQLResult *result3 = 0;
146        TSQLRow    *row    = 0;            TSQLRow    *row    = 0;    
147        TSQLRow    *row2    = 0;            TSQLRow    *row2    = 0;    
148          TSQLRow    *row3    = 0;    
149        TString chpath;        TString chpath;
150        TString chfile;        TString chfile;
151        UInt_t ridn = 0;        UInt_t ridn = 0;
152        qu.str("");        qu.str("");
153        qu << "SELECT ROOT_ID_N,PKT_NUMBER_INIT,PKT_NUMBER_FINAL,PKT_OBT_INIT,PKT_OBT_FINAL from ROOT_TABLE_MERGING where ID_N=" << chID << ";";        qu << "SELECT ROOT_ID_N,PKT_NUMBER_INIT,PKT_NUMBER_FINAL,PKT_OBT_INIT,PKT_OBT_FINAL,INSERTED_BY,REAL_TIME_INIT from ROOT_TABLE_MERGING where ID_N=" << chID << ";";
154        if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());        if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
155        result = conn->Query(qu.str().c_str());        result = conn->Query(qu.str().c_str());
156        if ( result ){        if ( result ){
# Line 149  void PamelaDBOperations::OpenL0File(TStr Line 161  void PamelaDBOperations::OpenL0File(TStr
161            chpktmax = (UInt_t)atoll(row->GetField(2));            chpktmax = (UInt_t)atoll(row->GetField(2));
162            chobtmin = (UInt_t)atoll(row->GetField(3));            chobtmin = (UInt_t)atoll(row->GetField(3));
163            chobtmax = (UInt_t)atoll(row->GetField(4));            chobtmax = (UInt_t)atoll(row->GetField(4));
164              chiby = (TString)(row->GetField(5));
165              chrtinit = (UInt_t)atoll(row->GetField(6));
166          } else {          } else {
167            throw -84;            throw -84;
168          };          };
# Line 157  void PamelaDBOperations::OpenL0File(TStr Line 171  void PamelaDBOperations::OpenL0File(TStr
171        };        };
172        delete result;        delete result;
173        qu.str("");        qu.str("");
174        qu << "SELECT FOLDER_NAME,FILE_NAME,OBT_TIME_SYNC,LAST_TIME_SYNC_INFO,TIME_OFFSET,BOOT_NUMBER,PKT_NUMBER_INIT,PKT_NUMBER_FINAL,PKT_OBT_INIT,PKT_OBT_FINAL from ROOT_TABLE where ID_N=" << ridn << ";";        qu << "SELECT FOLDER_NAME,FILE_NAME,OBT_TIME_SYNC,LAST_TIME_SYNC_INFO,TIME_OFFSET,BOOT_NUMBER,PKT_NUMBER_INIT,PKT_NUMBER_FINAL,PKT_OBT_INIT,PKT_OBT_FINAL,REAL_TIME_INIT from ROOT_TABLE where ID_N=" << ridn << ";";
175        if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());        if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
176        result2 = conn->Query(qu.str().c_str());        result2 = conn->Query(qu.str().c_str());
177        if ( result2 ){        if ( result2 ){
178          row2 = result2->Next();          row2 = result2->Next();
179          if ( row2 ){          if ( row2 ){
180            chpath = (TString)gSystem->ExpandPathName(row2->GetField(0))+'/';            if ( KEEPENV ){
181                chpath = (TString)(row2->GetField(0))+'/';
182              } else {
183                chpath = (TString)gSystem->ExpandPathName(row2->GetField(0))+'/';
184              };
185            chfile = (TString)(row2->GetField(1));            chfile = (TString)(row2->GetField(1));
186            chobtts = (UInt_t)atoll(row2->GetField(2));            chobtts = (UInt_t)atoll(row2->GetField(2));
187            chlastts = (UInt_t)atoll(row2->GetField(3));            chlastts = (UInt_t)atoll(row2->GetField(3));
188            chresursts = (UInt_t)atoll(row2->GetField(4));            chresursts = (UInt_t)atoll(row2->GetField(4));
189            chboot = (UInt_t)atoll(row2->GetField(5));            chboot = (UInt_t)atoll(row2->GetField(5));
190            //            //
191              if ( !chboot ){
192                if ( debug ) printf(" mmm... no BOOT number determined by chewbacca, try to find it looking at DB \n");
193                //
194                // new feature: check in ROOT_TABLE (timewise) the previous and the next BOOT number != 0 , if it is the same we know this one!
195                // if it is different roll back to the old behaviour
196                //
197                qu.str("");
198                qu << "SELECT BOOT_NUMBER from ROOT_TABLE where BOOT_NUMBER!=0 AND REAL_TIME_INIT>"<< row2->GetField(10) <<" order by REAL_TIME_INIT asc limit 1;";
199                if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
200                UInt_t chbootA = 0;
201                UInt_t chbootB = 1;
202                result3 = conn->Query(qu.str().c_str());
203                if ( result3 ){
204                  row3 = result3->Next();
205                  if ( row3 ){
206                    chbootA = (UInt_t)atoll(row3->GetField(0));
207                    if ( debug ) printf(" Found boot_number A = %u \n",chbootA);
208                  };
209                };
210                delete result3;
211                qu.str("");
212                qu << "SELECT BOOT_NUMBER from ROOT_TABLE where BOOT_NUMBER!=0 AND REAL_TIME_INIT<"<< row2->GetField(10) <<" order by REAL_TIME_INIT desc limit 1;";
213                if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
214                result3 = conn->Query(qu.str().c_str());
215                if ( result3 ){
216                  row3 = result3->Next();
217                  if ( row3 ){
218                    chbootB = (UInt_t)atoll(row3->GetField(0));
219                    if ( debug ) printf(" Found boot_number B = %u \n",chbootB);
220                  };
221                };
222                if ( chbootA == chbootB ){
223                  chboot = chbootA;
224                  if ( debug ) printf(" Found boot_number! it is %u \n",chboot);
225                } else {        
226                  qu.str("");
227                  //            qu << "SELECT BOOT_NUMBER from ROOT_TABLE where BOOT_NUMBER!=0 AND ABS(LAST_TIME_SYNC_INFO-"<< chlastts <<")<10000 AND ABS(REAL_TIME_INIT-"<< row2->GetField(10) <<")<7200 group by BOOT_NUMBER order by BOOT_NUMBER asc;";
228                  //            qu << "SELECT BOOT_NUMBER from ROOT_TABLE where BOOT_NUMBER!=0 AND ABS(LAST_TIME_SYNC_INFO-"<< chlastts <<")<40000 AND ABS(REAL_TIME_INIT-"<< row2->GetField(10) <<")<40000 group by BOOT_NUMBER order by BOOT_NUMBER asc;"; // relax conditions... 090112 [8RED: error -29]
229                  qu << "SELECT BOOT_NUMBER from ROOT_TABLE where BOOT_NUMBER!=0 AND ABS(LAST_TIME_SYNC_INFO-"<< (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 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 1467  Int_t PamelaDBOperations::insertPamelaGL Line 1680  Int_t PamelaDBOperations::insertPamelaGL
1680      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
1681      if ( !result ) throw -10;      if ( !result ) throw -10;
1682      row = result->Next();      row = result->Next();
1683        if ( !row ) throw -92;
1684      idresof = (UInt_t)atoll(row->GetField(0));      idresof = (UInt_t)atoll(row->GetField(0));
1685      existsts = true;      existsts = true;
1686      goto eout;      goto eout;
# Line 1488  Int_t PamelaDBOperations::insertPamelaGL Line 1702  Int_t PamelaDBOperations::insertPamelaGL
1702      if ( !row ){      if ( !row ){
1703        oss.str("");        oss.str("");
1704        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< "
1705            << dworbit << " order by FROM_ORBIT desc limit 1;";            << dworbit << " AND SPECIAL_FILE='' order by FROM_ORBIT desc limit 1;";
1706        if ( IsDebug() ) printf(" %s \n",oss.str().c_str());        if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
1707        result = conn->Query(oss.str().c_str());        result = conn->Query(oss.str().c_str());
1708        if ( !result ) throw -10;        if ( !result ) throw -10;
# Line 1535  Int_t PamelaDBOperations::insertPamelaGL Line 1749  Int_t PamelaDBOperations::insertPamelaGL
1749      TYPE = 0;      TYPE = 0;
1750      TSYNC = 0;      TSYNC = 0;
1751      //      //
1752      Double_t minimum = 0.;      //    Double_t minimum = 0.;
1753      Double_t maximum = 0.;      // Double_t maximum = 0.;
1754      Double_t minimum2 = 0.;      //Double_t minimum2 = 0.;
1755      Double_t maximum2 = 0.;      Double_t maximum2 = 0.;
1756      //      //
1757      //      //
# Line 1545  Int_t PamelaDBOperations::insertPamelaGL Line 1759  Int_t PamelaDBOperations::insertPamelaGL
1759      pamela::McmdRecord *mcrc = 0;      pamela::McmdRecord *mcrc = 0;
1760      TArrayC *mcmddata = 0;      TArrayC *mcmddata = 0;
1761      //      //
1762      minimum = numeric_limits<Double_t>::max();      //    minimum = numeric_limits<Double_t>::max();
1763      maximum = numeric_limits<Double_t>::min();      //    maximum = numeric_limits<Double_t>::min();
1764      minimum2 = numeric_limits<Double_t>::max();      //    minimum2 = numeric_limits<Double_t>::max();
1765      maximum2 = numeric_limits<Double_t>::min();      maximum2 = numeric_limits<Double_t>::min();
1766      //      //
1767      T = (TTree*)file->Get("Mcmd");      T = (TTree*)file->Get("Mcmd");
# Line 1746  Int_t PamelaDBOperations::insertPamelaGL Line 1960  Int_t PamelaDBOperations::insertPamelaGL
1960   * 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.
1961   */   */
1962  Int_t PamelaDBOperations::insertPamelaRootFile(){  Int_t PamelaDBOperations::insertPamelaRootFile(){
1963    stringstream oss;  
1964    TSQLResult *result = 0;      stringstream oss;
1965    TSQLRow    *row    = 0;      TSQLResult *result = 0;
1966    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;  
1967      //      //
1968      row = result->Next();      // ----------------------
1969        // determine the timesync
1970        // ----------------------
1971        UInt_t idtimesync = 0;
1972      //      //
1973      if ( !row ) throw -3;      if ( chewbacca ){
1974      idtimesync = (UInt_t)atoll(row->GetField(0));          oss.str("");
1975    } else {          oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" limit 1;";
1976      oss.str("");          if ( debug ) printf(" %s \n",oss.str().c_str());
1977      if ( STATIC ){          result = conn->Query(oss.str().c_str());
1978        oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "          //
1979            << " LEFT JOIN GL_ROOT "          if ( !result ) throw -3;
1980            << " ON GL_RAW.ID = GL_ROOT.ID_RAW "          //
1981            << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "          row = result->Next();
1982            << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";          //
1983            if ( !row ) throw -3;
1984            idtimesync = (UInt_t)atoll(row->GetField(0));
1985      } else {      } else {
1986        oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "          oss.str("");
1987            << " LEFT JOIN GL_ROOT "          if ( STATIC ){
1988            << " ON GL_RAW.ID = GL_ROOT.ID_RAW "              oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1989            << " WHERE GL_RAW.PATH = '$PAM_RAW' AND "                  << " LEFT JOIN GL_ROOT "
1990            << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";                  << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1991                    << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "
1992                    << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1993            } else {
1994                oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1995                    << " LEFT JOIN GL_ROOT "
1996                    << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1997                    << " WHERE GL_RAW.PATH = '$PAM_RAW' AND "
1998                    << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1999            };
2000            result = conn->Query(oss.str().c_str());
2001            //
2002            if ( !result ) throw -12;
2003            //
2004            row = result->Next();
2005            //
2006            if ( !row ) throw -10;
2007            if ( row != NULL && (UInt_t)atoll(row->GetField(0))>0 ){
2008                idroot = (UInt_t)atoll(row->GetField(2));
2009                delete row;
2010                delete result;
2011                return(1);
2012            };
2013            //
2014            // determine which timesync has to be used
2015            //
2016            oss.str("");
2017            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;";
2018            result = conn->Query(oss.str().c_str());
2019            //
2020            if ( !result ) throw -3;
2021            //
2022            row = result->Next();
2023            //
2024            if ( !row ) throw -3;
2025            idtimesync = (UInt_t)atoll(row->GetField(0));
2026      };      };
2027      result = conn->Query(oss.str().c_str());      
2028      //      delete row;
2029      if ( !result ) throw -12;      delete result;
2030      //  
2031      row = result->Next();      // ----------------------
2032      //      // insert root file
2033      if ( !row ) throw -10;      // ----------------------
2034      if ( row != NULL && (UInt_t)atoll(row->GetField(0))>0 ){  
2035        idroot = (UInt_t)atoll(row->GetField(2));      GL_ROOT glroot = GL_ROOT();
2036        return(1);      
2037        glroot.ID_RAW = GetID_RAW();
2038        glroot.ID_TIMESYNC = idtimesync;
2039        if ( STATIC ){
2040          glroot.PATH = GetRootPath();
2041        } else {
2042          if ( KEEPENV ){
2043            glroot.PATH = gSystem->DirName(filerootname.Data());
2044          } else {
2045            glroot.PATH = "$PAM_L0";
2046          };
2047      };      };
2048      //      glroot.NAME = GetRootFile();
2049      // determine which timesync has to be used  
2050      //      if ( insertPamelaRootFile(&glroot) )return 1;
2051      oss.str("");  
2052      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);
2053      result = conn->Query(oss.str().c_str());      
2054      //  
2055      if ( !result ) throw -3;      return (0);
2056      //  }
2057      row = result->Next();  /**
2058      //   * Insert all the new rows into GL_ROOT.
2059      if ( !row ) throw -3;   * The raw file indicates in the parameters should be already been stored in the database.
2060      idtimesync = (UInt_t)atoll(row->GetField(0));   */
2061    };  Int_t PamelaDBOperations::insertPamelaRootFile(GL_ROOT *glroot){
2062      stringstream oss;
2063      TSQLResult *result = 0;
2064      TSQLRow    *row    = 0;
2065      //
2066    //    //
2067    oss.str("");    oss.str("");
2068    if ( STATIC ){    oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
2069      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() << "')";  
   };  
2070    //    //
2071    if ( debug ) printf(" query is %s \n",oss.str().c_str());    if ( debug ) printf("%s \n",oss.str().c_str());
2072    if (conn->Query(oss.str().c_str()) == 0) throw -4;    if (conn->Query(oss.str().c_str()) == 0) throw -4;
2073    //    //
2074    delete result;    delete result;
2075    //    //
2076    oss.str("");    oss.str("");
2077    //  oss << "SELECT ID FROM GL_ROOT WHERE ID_RAW=" << this->GetID_RAW() << ";";    //  oss << "SELECT ID FROM GL_ROOT WHERE ID_RAW=" << this->GetID_RAW() << ";";
2078    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() <<"';";  
   };  
2079    //    //
2080    if ( debug ) printf(" query is %s \n",oss.str().c_str());    if ( debug ) printf("%s \n",oss.str().c_str());
2081    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
2082    if ( !result ) throw -12;    if ( !result ) throw -12;
2083    row = result->Next();    row = result->Next();
2084    if ( !row ) throw -3;    if ( !row ) throw -3;
2085    this->SetID_ROOT((UInt_t)atoll(row->GetField(0)));  
2086    if ( debug ) printf(" The ID of the ROOT file is %u \n",this->GetID_ROOT());    glroot->ID = (UInt_t)atoll(row->GetField(0));
2087    
2088      if ( debug ) printf(" The ID of the ROOT file is %u \n",glroot->ID);
2089    //    //
2090    delete result;    delete result;
2091    //    //
# Line 1929  Int_t PamelaDBOperations::assignBOOT_NUM Line 2181  Int_t PamelaDBOperations::assignBOOT_NUM
2181      UInt_t lowerts = tsync-(obt0/1000)-5;      UInt_t lowerts = tsync-(obt0/1000)-5;
2182      if ( chewbacca ){      if ( chewbacca ){
2183        oss.str("");        oss.str("");
2184        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
2185            << upperts            << upperts
2186            << " AND LAST_TIME_SYNC_INFO-(OBT_TIME_SYNC)>"            << " AND CAST((LAST_TIME_SYNC_INFO-(OBT_TIME_SYNC)) AS SIGNED INT)>" // 10RED MYSQL OPERATORS BUG
2187            << lowerts            << lowerts
2188            << " AND BOOT_NUMBER>1;";            << " AND BOOT_NUMBER>1;";
2189      } else {      } else {
2190        oss.str("");        oss.str("");
2191        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
2192            << upperts            << upperts
2193            << " AND TIMESYNC-(OBT0/1000)>"            << " AND CAST((TIMESYNC-(OBT0/1000)) AS SIGNED INT)>" // 10RED MYSQL OPERATORS BUG
2194            << lowerts            << lowerts
2195            << " AND GL_RAW.BOOT_NUMBER>0 GROUP BY GL_TIMESYNC.OBT0;";            << " AND GL_RAW.BOOT_NUMBER>0 GROUP BY GL_TIMESYNC.OBT0;";
2196      };      };
# Line 2037  Int_t PamelaDBOperations::insertPamelaRU Line 2289  Int_t PamelaDBOperations::insertPamelaRU
2289    //    //
2290    // no runtrailers in the file!    // no runtrailers in the file!
2291    //    //
2292    if ( !rtev ){    if ( IsDebug() ) printf(" Start rtev %i rhev %i nrtev %i nrhev %i \n",rtev,rhev,nrtev,nrhev);
2293      if ( !rhev ){    if ( !rtev || (chewbacca && !nrtev) ){
2294        if ( IsDebug() ) printf(" No runtrailers \n");
2295        if ( !rhev || (chewbacca && !nrhev) ){
2296        if ( IsDebug() ) printf(" No runheaders nor runtrailers!! \n");        if ( IsDebug() ) printf(" No runheaders nor runtrailers!! \n");
2297        if ( !(upperentry-chminentry) ){        if ( !(upperentry-chminentry) ){
2298          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 2315  Int_t PamelaDBOperations::insertPamelaRU
2315            cod = ehh->GetCounter();            cod = ehh->GetCounter();
2316            tcod = (UInt_t)cod->Get(pctp->Physics);            tcod = (UInt_t)cod->Get(pctp->Physics);
2317            evbefh = TMath::Max(chminentry,tcod);            evbefh = TMath::Max(chminentry,tcod);
2318  //        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
2319            if ( (UInt_t)evbefh == upperentry || !upperentry ) evbefh = upperentry + 1;            if ( (UInt_t)evbefh == upperentry || !upperentry ) evbefh = upperentry + 1;
2320  //            //
2321          if ( debug ) printf(" evbefh %i upperentry %u \n",evbefh,upperentry);            if ( debug ) printf(" evbefh %i upperentry %u \n",evbefh,upperentry);
2322            //            //
2323            this->HandleRunFragments(false,true,evbefh,upperentry);            this->HandleRunFragments(false,true,evbefh,upperentry);
2324            //            //
# Line 2075  Int_t PamelaDBOperations::insertPamelaRU Line 2329  Int_t PamelaDBOperations::insertPamelaRU
2329      //      //
2330    } else {    } else {
2331      //      //
2332        if ( IsDebug() ) printf(" We have runtrailers \n");
2333      Int_t conptt = -1;      Int_t conptt = -1;
2334      for (Int_t ptt=0; ptt<rtev; ptt++){      for (Int_t ptt=0; ptt<rtev; ptt++){
2335        //        //
# Line 2091  Int_t PamelaDBOperations::insertPamelaRU Line 2346  Int_t PamelaDBOperations::insertPamelaRU
2346          ptht = cod->Get(pctp->RunHeader) - 1;          ptht = cod->Get(pctp->RunHeader) - 1;
2347          //      evbeft = cod->Get(pctp->Physics);          //      evbeft = cod->Get(pctp->Physics);
2348          tcod = (UInt_t)cod->Get(pctp->Physics);          tcod = (UInt_t)cod->Get(pctp->Physics);
2349          if ( !tcod ) tcod = 1;          if ( !tcod ) tcod = 1;    // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
2350          evbeft = TMath::Min(upperentry,(tcod-1));          evbeft = TMath::Min(upperentry,(tcod-1));
2351          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));
2352          //          //
# Line 2130  Int_t PamelaDBOperations::insertPamelaRU Line 2385  Int_t PamelaDBOperations::insertPamelaRU
2385            obth = phh->GetOrbitalTime();            obth = phh->GetOrbitalTime();
2386            cod = ehh->GetCounter();            cod = ehh->GetCounter();
2387            tcod = (UInt_t)cod->Get(pctp->Physics);            tcod = (UInt_t)cod->Get(pctp->Physics);
2388            if ( !tcod ) tcod = 1;            if ( !tcod ) tcod = 1; // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
2389            evbefh = TMath::Max(chminentry,(tcod-1));            evbefh = TMath::Max(chminentry,(tcod-1));
2390            //            //
2391            if ( PKT(pkth) >= PKT(pktfirst) && PKT(pkth) <= upperpkt ){            if ( PKT(pkth) >= PKT(pktfirst) && PKT(pkth) <= upperpkt ){
# Line 2169  Int_t PamelaDBOperations::insertPamelaRU Line 2424  Int_t PamelaDBOperations::insertPamelaRU
2424                //                //
2425                this->HandleRunFragments(true,true,chminentry,(evbefh));                this->HandleRunFragments(true,true,chminentry,(evbefh));
2426                //                //
2427                  // what about pth=ptht-1
2428              };              };
2429            };            };
2430            //            //
# Line 2191  Int_t PamelaDBOperations::insertPamelaRU Line 2447  Int_t PamelaDBOperations::insertPamelaRU
2447                cod = ehh->GetCounter();                cod = ehh->GetCounter();
2448                //            evbeft = cod->Get(pctp->Physics);                //            evbeft = cod->Get(pctp->Physics);
2449                tcod = (UInt_t)cod->Get(pctp->Physics);                tcod = (UInt_t)cod->Get(pctp->Physics);
2450                if ( !tcod ) tcod = 1;                if ( !tcod ) tcod = 1; // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
2451                evbeft = TMath::Min(upperentry,(tcod-1));                evbeft = TMath::Min(upperentry,(tcod-1));
2452                rh->GetEntry(pth);                rh->GetEntry(pth);
2453                phh = ehh->GetPscuHeader();                phh = ehh->GetPscuHeader();
# Line 2231  Int_t PamelaDBOperations::insertPamelaRU Line 2487  Int_t PamelaDBOperations::insertPamelaRU
2487          //      if ( ptt+1 == rtev){            //      if ( ptt+1 == rtev){  
2488          if ( conptt+1 == nrtev ){            if ( conptt+1 == nrtev ){  
2489            //    if ( conptt+1 == (nrtev+nrtbef )){              //    if ( conptt+1 == (nrtev+nrtbef )){  
2490              if ( IsDebug() ) printf(" >>>>>>>>>>> %i %u %i %u \n",ptht,rhev,nrtev,conptt);
2491            ptht++;            ptht++;
2492            if ( ptht < rhev ){            if ( ptht < rhev ){
2493              rh->GetEntry(ptht);              rh->GetEntry(ptht);
2494                //pth++;
2495                //if ( pth < rhev ){
2496                //rh->GetEntry(pth);
2497              phh = ehh->GetPscuHeader();              phh = ehh->GetPscuHeader();
2498              pkth = phh->GetCounter();              pkth = phh->GetCounter();
2499              obth = phh->GetOrbitalTime();              obth = phh->GetOrbitalTime();
# Line 2257  Int_t PamelaDBOperations::insertPamelaRU Line 2517  Int_t PamelaDBOperations::insertPamelaRU
2517              if ( (UInt_t)evbeft < upperentry-1 && upperentry>0 ){              if ( (UInt_t)evbeft < upperentry-1 && upperentry>0 ){
2518                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);
2519                //                //
2520                if ( (ptt-1) < 0 ) throw -15; // should never arrive here!                //              if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
2521                rt->GetEntry(ptt-1);                if ( (rtev-1) < 0 || ptt < 0 ) throw -15; // should never arrive here!
2522                  //              rt->GetEntry(ptt-1);
2523                  rt->GetEntry(rtev-1);
2524                cod = eht->GetCounter();                cod = eht->GetCounter();
2525                tcod = (UInt_t)cod->Get(pctp->Physics);                tcod = (UInt_t)cod->Get(pctp->Physics)+1;
2526                evbefh = TMath::Max(chminentry,tcod);                evbefh = TMath::Max(chminentry,tcod);
2527                //            evbefh = cod->Get(pctp->Physics);                //            evbefh = cod->Get(pctp->Physics);
2528                rt->GetEntry(ptt);                rt->GetEntry(ptt);
# Line 2367  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2629  Bool_t PamelaDBOperations::IsRunAlreadyI
2629        //        //
2630        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");
2631        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2632  //       oss.str("");        //       oss.str("");
2633  //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2634  //       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());      
2635  //       conn->Query(oss.str().c_str());        //       conn->Query(oss.str().c_str());
2636        if ( signal ) signal = false;        if ( signal ) signal = false;
2637        goto gonext;              goto gonext;      
2638        //        //
# Line 2385  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2647  Bool_t PamelaDBOperations::IsRunAlreadyI
2647        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");
2648        //        //
2649        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2650  //       oss.str("");        //       oss.str("");
2651  //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2652  //       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());      
2653  //       conn->Query(oss.str().c_str());        //       conn->Query(oss.str().c_str());
2654        //        //
2655        if ( signal ) signal = false;        if ( signal ) signal = false;
2656        goto gonext;        goto gonext;
# Line 2403  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2665  Bool_t PamelaDBOperations::IsRunAlreadyI
2665        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");
2666        //        //
2667        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2668  //       oss.str("");        //       oss.str("");
2669  //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2670  //       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());      
2671  //       conn->Query(oss.str().c_str());        //       conn->Query(oss.str().c_str());
2672        if ( signal ) signal = false;        if ( signal ) signal = false;
2673        //        //
2674      };      };
# Line 2488  void PamelaDBOperations::HandleRunFragme Line 2750  void PamelaDBOperations::HandleRunFragme
2750      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");
2751      //      //
2752    } 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 ){  
2753      //      //
2754      // 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
2755      //      //
2756      if ( IsDebug() ) printf(" The run is new \n");      if ( firstev != (lastev+1) ){ // could be a problem sometimes (?)
2757      if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");        if ( rhfirstev != firstev && !mishead ) mishead = true;
2758          if ( rtlastev != lastev && !mistrail ) mistrail = true;
2759        };
2760      //      //
2761      glrun->SetID(this->AssignRunID());      if ( IsDebug() ) printf(" bhere firstev is %i lastev is %i \n",firstev,lastev);
2762      glrun->SetID_RUN_FRAG(0);      this->FillClass(mishead,mistrail,firstev,lastev);
2763      glrun->Fill_GL_RUN_FRAGMENTS(conn);      if ( IsDebug() ) printf(" chere firstev is %i lastev is %i \n",firstev,lastev);
2764      //      //
2765    } else {      if ( IsDebug() ) printf("The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
2766      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());
2767      if ( PEDANTIC ) throw -69;      //
2768      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  
2769      //      //
2770      oss.str("");      oss.str("");
2771      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 "
2772          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
2773          << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "          << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
2774          << " ID != " << glrun->ID          << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
2775          << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!          << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
2776            << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2777            << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
2778            << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
2779            << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2780            << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
2781            << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
2782            << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2783            << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
2784            << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
2785      //      //
2786      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());
2787      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
2788      //      //
2789      if ( !result ) throw -4;      if ( !result ) throw -4;
2790      //      //
2791      row = result->Next();      row = result->Next();
2792      //      //
2793      if ( !row && NoFrag() ){      if ( !row ){
2794          //
2795          // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
2796          //
2797          if ( IsDebug() ) printf(" The run is new \n");
2798          if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
2799          //
2800          glrun->SetID(this->AssignRunID());
2801          glrun->SetID_RUN_FRAG(0);
2802          glrun->Fill_GL_RUN_FRAGMENTS(conn);
2803          //
2804        } else {
2805          if ( IsDebug() ) printf(" The run is already present in the fragment table, relaxed %u \n",RELAXED);
2806          if ( !RELAXED ){
2807            if ( PEDANTIC ) throw -69;
2808            return;
2809          } else {
2810            glrun->SetID((UInt_t)atoll(row->GetField(0)));
2811            glrun->SetID_RUN_FRAG(0);
2812          };
2813        };
2814        //
2815        if ( chewbacca && mishead && mistrail ) goto justcheck;
2816        //
2817        // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
2818        //    
2819        if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
2820          // missing it no way we can found a piece in the frag table
2821        //        //
2822        oss.str("");        oss.str("");
2823        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 "
2824            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2825            << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "            << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2826            << " ID != " << glrun->ID            << " ID != " << glrun->ID
2827            << " 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!!
2828        //        //
2829        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());
2830        result = conn->Query(oss.str().c_str());        result = conn->Query(oss.str().c_str());
2831        //        //
2832        if ( !result ) throw -4;        if ( !result ) throw -4;
2833        //        //
       foundinrun = true;  
       //  
2834        row = result->Next();        row = result->Next();
2835        //        //
2836      };        if ( !row && NoFrag() ){
2837      //          //
2838      if ( !row ){          oss.str("");
2839        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 "
2840        found = false;              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2841      } else {              << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2842        //              << " ID != " << glrun->ID
2843        found = false; // default value              << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
2844        //          //
2845        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());
2846        //          result = conn->Query(oss.str().c_str());
2847        // if we have both runheader and runtrailer we can check with pkt_counter:          //
2848            if ( !result ) throw -4;
2849            //
2850            foundinrun = true;
2851            //
2852            row = result->Next();
2853            //
2854          };
2855        //        //
2856        if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){        if ( !row ){
2857          ULong64_t chkpkt = 0;            if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2858          ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());          found = false;
2859          ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));        } else {
2860            //
2861            found = false; // default value
2862            //
2863            if ( IsDebug() ) printf(" A Found a possible candidate, checking if it is the good one... \n");
2864          //          //
2865          chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;            // if we have both runheader and runtrailer we can check with pkt_counter:
2866          //          //
2867          if ( labs(chkpkt-pktt)<2 ){          if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){
2868              ULong64_t chkpkt = 0;  
2869              ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
2870              ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
2871            //            //
2872            if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);            chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;  
2873            //            //
2874            found = true;            if ( labs(chkpkt-pktt)<2 ){
2875                //
2876                if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
2877                //
2878                found = true;
2879                if ( IsDebug() ) printf(" where firstev is %i lastev is %i \n",firstev,lastev);
2880                //
2881              } else {
2882                //
2883                if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);            
2884                //
2885                found = false;
2886                //
2887              };
2888            };
2889            if ( !found && chewbacca ) goto justcheck;
2890            if ( !found ){
2891            //            //
2892          } 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
2893            //            //
2894            if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);                  ULong64_t chkpkt1 = 0;
2895              ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
2896              ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
2897              chkpkt1 = labs(orunh1-dbrunt1);
2898            //            //
2899            found = false;            ULong64_t chkpkt2 = 0;
2900              ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());
2901              ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
2902              chkpkt2 = labs(orunh2-dbrunt2);
2903            //            //
2904              ULong64_t chkpkt3 = 0;
2905              ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());
2906              ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
2907              chkpkt3 = labs(orunh3-dbrunt3);
2908              //
2909              if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
2910                //  if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){
2911                //
2912                if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
2913                //
2914                found = true;
2915                //
2916              } else {
2917                //
2918                if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
2919                //
2920                found = false;
2921                //
2922              };
2923          };          };
2924        };        };
2925        if ( !found && chewbacca ) goto justcheck;        //
2926        if ( !found ){        if ( found ){
2927            //
2928            // 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
2929            //
2930            if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
2931          //          //
2932          // 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 ){
2933              glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2934              glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2935            };
2936          //          //
2937          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);  
2938          //          //
2939          if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){          //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
2940            //    if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){          //
2941            //          oss.str("");
2942            if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);          oss << " ID="<<row->GetField(0)<<";";
2943            //          //
2944            found = true;          glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos
2945            //          if ( IsDebug() ) printf(" there firstev is %i lastev is %i \n",firstev,lastev);
2946          } else {          //
2947            // merge infos
2948            //
2949            UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());
2950            ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
2951            UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
2952            ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
2953            if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2954            TTree *T= 0;
2955            T = (TTree*)file->Get("Physics");
2956            if ( !T || T->IsZombie() ) throw -16;
2957            EventHeader *eh = 0;
2958            PscuHeader *ph = 0;
2959            T->SetBranchAddress("Header", &eh);
2960            while ( apkt > bpkt && aobt > bobt && firstev < lastev ){
2961              T->GetEntry(firstev);
2962              ph = eh->GetPscuHeader();
2963              bpkt = PKT(ph->GetCounter());
2964              bobt = OBT(ph->GetOrbitalTime());    
2965              firstev++;
2966              if ( PEDANTIC ) throw -71;
2967            };
2968            if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2969            //
2970            glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
2971            glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
2972            glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
2973            glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());
2974            glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());
2975            //
2976            if ( IsDebug() ) printf(" here firstev is %i lastev is %i \n",firstev,lastev);
2977            //
2978            glrun->SetEV_FROM(firstev);
2979            glrun->SetNEVENTS(lastev-firstev+1);
2980            //
2981            glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
2982            glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
2983            glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
2984            glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());
2985            glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());
2986            glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());
2987            glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());
2988            glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());
2989            glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());
2990            glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());
2991            glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());  
2992            glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());  
2993            glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());  
2994            glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());  
2995            glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());  
2996            glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());  
2997            //
2998            if ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
2999            if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
3000            //
3001            if ( !IsRunAlreadyInserted() ){
3002              //
3003              //    glrun->SetID(this->AssignRunID());
3004              glrun->SetID_RUN_FRAG(glrun1->GetID());
3005              glrun->Fill_GL_RUN(conn);
3006            //            //
3007            if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);            // set id number
3008            //            //
3009            found = false;            glrun1->SetID_RUN_FRAG(glrun->GetID());
3010              glrun1->Fill_GL_RUN(conn);
3011            //            //
3012          };          };
3013        };          // delete old entry in fragment table
3014      };          //
3015      //          glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3016      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() ){  
3017          //          //
3018          //      glrun->SetID(this->AssignRunID());          delete glrun1;
         glrun->SetID_RUN_FRAG(glrun1->GetID());  
         glrun->Fill_GL_RUN(conn);  
3019          //          //
         // set id number  
3020          //          //
3021          glrun1->SetID_RUN_FRAG(glrun->GetID());          return;
         glrun1->Fill_GL_RUN(conn);  
3022          //          //
3023        };        };
       // delete old entry in fragment table  
       //  
       glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       //  
       delete glrun1;  
       //  
       //  
       return;  
3024        //        //
3025      };      };
3026      //      //
3027    };      if ( mistrail && ( rtlastev == lastev || chewbacca )) { // look for runtrailer (only when at the end of the file, if at the beginning and the runh is
3028    //        // 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() ){  
3029        //        //
3030        oss.str("");        oss.str("");
3031        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 "
3032            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3033            << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "            << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
3034            << " ID != " << glrun->ID            << " ID != " << glrun->ID
3035            << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";            << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
3036        //        //
3037        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());
3038        result = conn->Query(oss.str().c_str());        result = conn->Query(oss.str().c_str());
3039        //        //
3040        if ( !result ) throw -4;        if ( !result ) throw -4;
3041        //        //
       foundinrun = true;  
3042        row = result->Next();        row = result->Next();
3043        //        //
3044      };        if ( !row && NoFrag() ){
3045      //          //
3046      if ( !row ){          oss.str("");
3047        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 "
3048        found = false;              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3049      } else {              << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
3050        //              << " ID != " << glrun->ID
3051        found = false; // default value              << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
3052        //          //
3053        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());
3054        //          result = conn->Query(oss.str().c_str());
3055        // if we have both runheader and runtrailer we can check with pkt_counter:          //
3056            if ( !result ) throw -4;
3057            //
3058            foundinrun = true;
3059            row = result->Next();
3060            //
3061          };
3062        //        //
3063        if ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){        if ( !row ){
3064          ULong64_t chkpkt = 0;            if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
3065          ULong64_t pktt = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));          found = false;
3066          ULong64_t pkth = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());        } else {
3067            //
3068            found = false; // default value
3069          //          //
3070          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");
3071          //          //
3072          if ( labs(chkpkt-pktt)<2 ){          // if we have both runheader and runtrailer we can check with pkt_counter:
3073            //
3074            if ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){
3075              ULong64_t chkpkt = 0;  
3076              ULong64_t pktt = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
3077              ULong64_t pkth = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
3078            //            //
3079            if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);            chkpkt = pkth + (ULong64_t)((UInt_t)atoll(row->GetField(1))) + 1ULL + 1ULL;  
3080            //            //
3081            found = true;            if ( labs(chkpkt-pktt)<2 ){
3082                //
3083                if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
3084                //
3085                found = true;
3086                //
3087              } else {
3088                //
3089                if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);            
3090                //
3091                found = false;
3092                //
3093              };
3094            };
3095            if ( !found && chewbacca ) goto justcheck;
3096            if ( !found ){
3097            //            //
3098          } 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
3099            //            //
3100            if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);                  ULong64_t chkpkt1 = 0;
3101              ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
3102              ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
3103              chkpkt1 = labs(orunh1-dbrunt1);
3104            //            //
3105            found = false;            ULong64_t chkpkt2 = 0;
3106              ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNTRAILER_OBT());
3107              ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
3108              chkpkt2 = labs(orunh2-dbrunt2);
3109              //
3110              ULong64_t chkpkt3 = 0;
3111              ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNTRAILER_TIME());
3112              ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
3113              chkpkt3 = labs(orunh3-dbrunt3);
3114            //            //
3115              if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
3116                //
3117                if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
3118                //
3119                found = true;
3120                //
3121              } else {
3122                //
3123                if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
3124                //
3125                found = false;
3126                //
3127              };
3128          };          };
3129        };        };
3130        if ( !found && chewbacca ) goto justcheck;        //
3131        if ( !found ){        if ( found ){
3132            //
3133            // 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
3134            //
3135            if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
3136          //          //
3137          // 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 ){
3138              glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3139              glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
3140            };
3141          //          //
3142          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);  
3143          //          //
3144          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);  
3145          //          //
3146          ULong64_t chkpkt3 = 0;          oss.str("");
3147          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);  
3148          //          //
3149          if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){          glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runtrailer infos
3150            //          //
3151            if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);          // merge infos
3152            //          //
3153            found = true;          UInt_t apkt = PKT(glrun->GetRUNTRAILER_PKT());
3154            //          ULong64_t aobt = OBT(glrun->GetRUNTRAILER_OBT());
3155          } else {          UInt_t bpkt = PKT(glrun1->GetRUNHEADER_PKT());
3156            ULong64_t bobt = OBT(glrun1->GetRUNHEADER_OBT());
3157            if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
3158            TTree *T= 0;
3159            T = (TTree*)file->Get("Physics");
3160            if ( !T || T->IsZombie() ) throw -16;
3161            EventHeader *eh = 0;
3162            PscuHeader *ph = 0;
3163            T->SetBranchAddress("Header", &eh);
3164            while ( apkt > bpkt && aobt > bobt && lastev > 0 ){
3165              T->GetEntry(lastev);
3166              ph = eh->GetPscuHeader();
3167              apkt = PKT(ph->GetCounter());
3168              aobt = OBT(ph->GetOrbitalTime());    
3169              lastev--;
3170              if ( PEDANTIC && !RELAXED) throw -72;
3171            };
3172            if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
3173            //
3174            glrun->SetEV_TO(lastev);
3175            glrun->SetNEVENTS(lastev-firstev+1);
3176            glrun->SetPKT_COUNTER(glrun1->GetPKT_COUNTER());
3177            glrun->SetPKT_READY_COUNTER(glrun1->GetPKT_READY_COUNTER());
3178            glrun->SetRUNTRAILER_TIME(glrun1->GetRUNTRAILER_TIME());
3179            glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());
3180            glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());
3181            //
3182            glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());
3183            glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());
3184            glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());
3185            glrun1->SetCOMPILATIONTIMESTAMP(glrun->GetCOMPILATIONTIMESTAMP());
3186            glrun1->SetFAV_WRK_SCHEDULE(glrun->GetFAV_WRK_SCHEDULE());
3187            glrun1->SetEFF_WRK_SCHEDULE(glrun->GetEFF_WRK_SCHEDULE());
3188            glrun1->SetPRH_VAR_TRG_MODE_A(glrun->GetPRH_VAR_TRG_MODE_A());
3189            glrun1->SetPRH_VAR_TRG_MODE_B(glrun->GetPRH_VAR_TRG_MODE_B());
3190            glrun1->SetACQ_BUILD_INFO(glrun->GetACQ_BUILD_INFO());
3191            glrun1->SetACQ_VAR_INFO(glrun->GetACQ_VAR_INFO());
3192            glrun1->SetRM_ACQ_AFTER_CALIB(glrun->GetRM_ACQ_AFTER_CALIB());  
3193            glrun1->SetRM_ACQ_SETTING_MODE(glrun->GetRM_ACQ_SETTING_MODE());  
3194            glrun1->SetTRK_CALIB_USED(glrun->GetTRK_CALIB_USED());  
3195            glrun1->SetCAL_DSP_MASK(glrun->GetCAL_DSP_MASK());  
3196            glrun1->SetLAST_TIMESYNC(glrun->GetLAST_TIMESYNC());  
3197            glrun1->SetOBT_TIMESYNC(glrun->GetOBT_TIMESYNC());  
3198            //
3199            if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ) glrun1->SetPHYSENDRUN_MASK_S3S2S12(glrun->GetPHYSENDRUN_MASK_S3S2S12());
3200            if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) glrun1->SetPHYSENDRUN_MASK_S11CRC(glrun->GetPHYSENDRUN_MASK_S11CRC());
3201            //
3202            if ( !IsRunAlreadyInserted() ){
3203              //
3204              //    glrun->SetID(this->AssignRunID());
3205              //
3206              glrun->SetID_RUN_FRAG(glrun1->GetID());
3207              glrun->Fill_GL_RUN(conn);
3208            //            //
3209            if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);            // set id number
3210            //            //
3211            found = false;            glrun1->SetID_RUN_FRAG(glrun->GetID());
3212              glrun1->Fill_GL_RUN(conn);
3213            //            //
3214          };          };
3215            //
3216            // delete old entries in fragment table
3217            //
3218            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3219            glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3220            //
3221            delete glrun1;
3222            //
3223            return;
3224            //
3225        };        };
3226          //
3227      };      };
3228      //      //
3229      if ( found ){    justcheck:
3230        //      //
3231        // 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");  
       };  
3232        //        //
3233        GL_RUN *glrun1 = new GL_RUN();        if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");
3234        //        //
3235        //      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?
3236        //        //
3237        oss.str("");        oss.str("");
3238        oss << " ID="<<row->GetField(0)<<";";        oss << " SELECT ID,ID_ROOT_L0 FROM GL_RUN WHERE "
3239              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3240              << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3241              << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3242              << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3243              << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3244              << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3245              << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3246              << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3247              << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3248              << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3249              << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3250              << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3251              << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3252        //        //
3253        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());
3254          result = conn->Query(oss.str().c_str());
3255        //        //
3256        // merge infos        if ( !result ) throw -4;
3257        //        //
3258        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());    
3259        //        //
3260        if ( !IsRunAlreadyInserted() ){        if ( row ){
         //  
         //      glrun->SetID(this->AssignRunID());  
3261          //          //
3262          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
3263          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.
3264          //          //
3265          // set id number          // 090112 [8RED (-70): RUN ALREADY INSERTED]
3266            // 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!
3267          //          //
3268          glrun1->SetID_RUN_FRAG(glrun->GetID());          Bool_t OK = false;
3269          glrun1->Fill_GL_RUN(conn);          UInt_t IDRL2A = 0;
3270            UInt_t IDRL2B = 0;
3271            if ( chewbacca ){
3272              if ( result->GetRowCount() >= 2 ){
3273                //
3274                if ( IsDebug() ) printf(" RH---| gap |---RT case, number of pieces in the GL_RUN table: %i \n",result->GetRowCount());
3275                OK = true;
3276                IDRL2A = (UInt_t)atoll(row->GetField(0));
3277                //
3278                while ( row ){
3279                  //
3280                  TSQLResult *trresult = 0;
3281                  TSQLRow    *trrow    = 0;
3282                  //
3283                  stringstream tross;
3284                  tross.str("");
3285                  //
3286                  tross << " SELECT RUNHEADER_PKT, RUNTRAILER_PKT FROM GL_RUN_TRASH where ID=" << row->GetField(0) << ";";
3287                  if ( IsDebug() ) printf(" check in the gl_run_trash table for pkt intervals: query is \n %s \n",tross.str().c_str());
3288                  trresult = conn->Query(tross.str().c_str());
3289                  if ( !trresult ) throw -4;
3290                  trrow = trresult->Next();
3291                  if ( !trrow || trresult->GetRowCount() != 1 ){
3292                    OK = false;
3293                    if ( IsDebug() ) printf(" OPS! no such run (or multiple runs!) in GL_RUN_TRASH table, something wrong is going on! \n");
3294                    break;
3295                  };
3296                  //
3297                  UInt_t pktH =  (UInt_t)atoll(row->GetField(0));
3298                  UInt_t pktT =  (UInt_t)atoll(row->GetField(1));
3299                  delete trresult;
3300                  if (
3301                      (PKT(pktH) >= PKT(glrun->GetRUNHEADER_PKT()) && PKT(pktH) <= PKT(glrun->GetRUNTRAILER_PKT())) ||
3302                      (PKT(pktT) >= PKT(glrun->GetRUNHEADER_PKT()) && PKT(pktT) <= PKT(glrun->GetRUNTRAILER_PKT())) ||
3303                      (PKT(pktH) <= PKT(glrun->GetRUNTRAILER_PKT()) && PKT(pktT) >= PKT(glrun->GetRUNTRAILER_PKT())) ){            
3304                    OK = false;
3305                    if ( IsDebug() ) printf(" The run is overlapping with already inserted ones!! \n");
3306                    break;          
3307                  };
3308                  //PKT(glrun->GetRUNHEADER_PKT())  PKT(glrun->GetRUNTRAILER_PKT())
3309                  row = result->Next();
3310                };
3311                
3312                //    if ( result->GetRowCount() == 2 ) {
3313                //      IDRL2A = (UInt_t)atoll(row->GetField(0));
3314                //      UInt_t IDRL0A = (UInt_t)atoll(row->GetField(1));
3315                //      row = result->Next();
3316                //      IDRL2B = (UInt_t)atoll(row->GetField(0));
3317                //      UInt_t IDRL0B = (UInt_t)atoll(row->GetField(1));
3318                //      if ( IsDebug() ) printf(" IDRL0A %u B %u IDRL2A %u B %u \n",IDRL0A,IDRL0B,IDRL2A,IDRL2B);
3319                //      //      if ( IDRL0A == IDRL0B ){ //091230 why this condition???? RH could be in a file and RT in another one...
3320                //      if ( true ){
3321                //        TSQLResult *result2 = 0;
3322                //        TSQLRow    *row2    = 0;
3323                //        oss.str("");
3324                //        oss << "select PKT_NUMBER_FINAL from ROOT_TABLE_MERGING where REAL_TIME_INIT<" << chrtinit << " order by REAL_TIME_INIT desc limit 1;";
3325                //        if ( IsDebug() ) printf(" Check if we are in the case RH---| small gap |---RT: query is \n %s \n",oss.str().c_str());
3326                //        result2 = conn->Query(oss.str().c_str());
3327                //        //
3328                //        if ( !result2 ) throw -4;
3329                //        //
3330                //        row2 = result2->Next();
3331                //        //
3332                //        if ( row2 ){
3333                //          UInt_t PKA = (UInt_t)atoll(row2->GetField(0));
3334                //          delete result2;
3335                //          oss.str("");
3336                //          oss << "select PKT_NUMBER_INIT from ROOT_TABLE_MERGING where REAL_TIME_INIT>" << chrtinit << " order by REAL_TIME_INIT asc limit 1;";
3337                //          if ( IsDebug() ) printf(" Check if we are in the case RH---| small gap |---RT: query is \n %s \n",oss.str().c_str());
3338                //          result2 = conn->Query(oss.str().c_str());
3339                //          //
3340                //          if ( !result2 ) throw -4;
3341                //          //
3342                //          row2 = result2->Next();
3343                //          //
3344                //          if ( row2 ){
3345                //            UInt_t PKB = (UInt_t)atoll(row2->GetField(0));
3346                //            //
3347                //            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);
3348                //            if ( PKT(PKA)+1LL == PKT(glrun->GetRUNHEADER_PKT()) && PKT(PKB) == PKT(glrun->GetRUNTRAILER_PKT())+1LL ){
3349                //              if ( IsDebug() ) printf(" Ok, we are in the case: RH---| small gap |---RT \n");
3350                //              OK = true;
3351                //            };
3352                //          };
3353                //        };                  
3354                //      };
3355                //    };      
3356              };
3357            };
3358            if ( OK ){
3359              //
3360              // 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  
3361              //
3362              // 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 )
3363              //
3364              if ( IsDebug() ) printf(" Ok, we are in the case: RH---| small gap |---RT \n");
3365              //
3366              GL_RUN *glA = new GL_RUN();
3367              glA->Query_GL_RUN(IDRL2A,conn);
3368              //
3369              glrun->SetRUNHEADER_TIME(glA->GetRUNHEADER_TIME());
3370              glrun->SetRUNHEADER_OBT(glA->GetRUNHEADER_OBT());
3371              glrun->SetRUNHEADER_PKT(glA->GetRUNHEADER_PKT());
3372              //
3373              glrun->SetRUNTRAILER_TIME(glA->GetRUNTRAILER_TIME());
3374              glrun->SetRUNTRAILER_OBT(glA->GetRUNTRAILER_OBT());
3375              glrun->SetRUNTRAILER_PKT(glA->GetRUNTRAILER_PKT());
3376              //
3377              if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glA->GetPHYSENDRUN_MASK_S3S2S12());
3378              if ( glA->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glA->GetPHYSENDRUN_MASK_S11CRC());
3379              //          
3380              if ( glA->GetACQ_BUILD_INFO() != 0 ){
3381                //
3382                // the first piece contains a good runheader we can update all the other runs with correct infos!
3383                //
3384                glrun->SetCOMPILATIONTIMESTAMP(glA->GetCOMPILATIONTIMESTAMP());
3385                glrun->SetFAV_WRK_SCHEDULE(glA->GetFAV_WRK_SCHEDULE());
3386                glrun->SetEFF_WRK_SCHEDULE(glA->GetEFF_WRK_SCHEDULE());
3387                glrun->SetPRH_VAR_TRG_MODE_A(glA->GetPRH_VAR_TRG_MODE_A());
3388                glrun->SetPRH_VAR_TRG_MODE_B(glA->GetPRH_VAR_TRG_MODE_B());
3389                glrun->SetACQ_BUILD_INFO(glA->GetACQ_BUILD_INFO());
3390                glrun->SetACQ_VAR_INFO(glA->GetACQ_VAR_INFO());
3391                glrun->SetRM_ACQ_AFTER_CALIB(glA->GetRM_ACQ_AFTER_CALIB());
3392                glrun->SetRM_ACQ_SETTING_MODE(glA->GetRM_ACQ_SETTING_MODE());
3393                glrun->SetTRK_CALIB_USED(glA->GetTRK_CALIB_USED());
3394                glrun->SetCAL_DSP_MASK(glA->GetCAL_DSP_MASK());
3395                glrun->SetLAST_TIMESYNC(glA->GetLAST_TIMESYNC());
3396                glrun->SetOBT_TIMESYNC(glA->GetOBT_TIMESYNC());
3397                //
3398              };
3399              //
3400              if ( glA->GetPKT_READY_COUNTER() != 0 ){
3401                //
3402                // the first piece contains a good runtrailer we can update all the other runs with correct infos!
3403                //
3404                glrun->SetPKT_COUNTER(glA->GetPKT_COUNTER());
3405                glrun->SetPKT_READY_COUNTER(glA->GetPKT_READY_COUNTER());
3406              };
3407              //
3408              // update runheader ROOT_ID_FRAG
3409              //
3410              oss.str("");
3411              oss << "UPDATE GL_RUN SET ID_RUN_FRAG = " << glrun->GetID() << " where ID = " << IDRL2A << ";";
3412              if ( IsDebug() ) printf(" update gl_run to have cross indexing: %s\n",oss.str().c_str());
3413              conn->Query(oss.str().c_str());
3414              //
3415              oss.str("");
3416              oss << "SELECT ID FROM GL_RUN WHERE ID_RUN_FRAG = " << IDRL2A << ";";
3417              if ( IsDebug() ) printf(" update gl_run to have cross indexing: %s\n",oss.str().c_str());
3418              TSQLResult *tsresult = 0;
3419              TSQLRow    *tsrow    = 0;
3420              tsresult=conn->Query(oss.str().c_str());
3421              if ( !tsresult ) throw -4;
3422              tsrow = tsresult->Next();
3423              if ( !tsrow || tsresult->GetRowCount() != 1 ) throw -4;
3424              IDRL2B = (UInt_t)atoll(tsrow->GetField(0));
3425              glrun->SetID_RUN_FRAG(IDRL2B);
3426              //
3427              // fill the new run in GL_RUN
3428              //
3429              glrun->Fill_GL_RUN(conn);    
3430              //
3431              glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3432              delete glA;
3433              //
3434            } else {
3435    //        //
3436    //        // this is the case in which we must insert a piece of run between two fragments in the GL_RUN table
3437    //        //
3438    //        // 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 )
3439    //        //
3440    //        GL_RUN *glA = new GL_RUN();
3441    //        glA->Query_GL_RUN(IDRL2A,conn);
3442    //        //
3443    //        if ( glA->GetACQ_BUILD_INFO() != 0 ){
3444    //          //
3445    //          // the first piece contains a good runheader we can update all the other runs with correct infos!
3446    //          //
3447    //          oss.str("");
3448    //          oss << "UPDATE GL_RUN_FRAGMENTS SET "
3449    //              << " RUNHEADER_TIME=" << glA->GetRUNHEADER_TIME()<< " , "
3450    //              << " RUNHEADER_OBT=" << glA->GetRUNHEADER_OBT()<< " , "
3451    //              << " RUNHEADER_PKT=" << glA->GetRUNHEADER_PKT()<< " , "
3452    //              << " COMPILATIONTIMESTAMP=" << glA->GetCOMPILATIONTIMESTAMP()<< " , "
3453    //              << " FAV_WRK_SCHEDULE=" << glA->GetFAV_WRK_SCHEDULE()<< " , "
3454    //              << " EFF_WRK_SCHEDULE=" << glA->GetEFF_WRK_SCHEDULE()<< " , "
3455    //              << " PRH_VAR_TRG_MODE_A=" << glA->GetPRH_VAR_TRG_MODE_A()<< " , "
3456    //              << " PRH_VAR_TRG_MODE_B=" << glA->GetPRH_VAR_TRG_MODE_B()<< " , "
3457    //              << " ACQ_BUILD_INFO=" << glA->GetACQ_BUILD_INFO()<< " , "
3458    //              << " ACQ_VAR_INFO=" << glA->GetACQ_VAR_INFO()<< " , "
3459    //              << " RM_ACQ_AFTER_CALIB=" << glA->GetRM_ACQ_AFTER_CALIB()<< " , "  
3460    //              << " RM_ACQ_SETTING_MODE=" << glA->GetRM_ACQ_SETTING_MODE()<< " , "  
3461    //              << " TRK_CALIB_USED=" << glA->GetTRK_CALIB_USED()<< " , "  
3462    //              << " CAL_DSP_MASK=" << glA->GetCAL_DSP_MASK()<< " , "  
3463    //              << " LAST_TIMESYNC=" << glA->GetLAST_TIMESYNC()<< " , ";
3464    //          //
3465    //          if ( glA->GetPHYSENDRUN_MASK_S3S2S12() )
3466    //            oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12() << " , ";
3467    //          if ( glA->GetPHYSENDRUN_MASK_S11CRC() )
3468    //            oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC() << " , ";
3469    //          //        
3470    //          oss << " OBT_TIMESYNC=" << glA->GetOBT_TIMESYNC();
3471    //          oss << " WHERE ID=" << glrun->GetID() << ";";
3472    //          if ( IsDebug() ) printf(" update with correct infos: %s\n",oss.str().c_str());
3473    //          conn->Query(oss.str().c_str());    
3474    //          //
3475    //        } else {
3476    //          //
3477    //          // sig no runheader, let set anyway what is possible...
3478    //          //
3479    //          oss.str("");
3480    //          oss << "UPDATE GL_RUN_FRAGMENTS SET "
3481    //              << " RUNHEADER_TIME=" << glA->GetRUNHEADER_TIME()<< " , ";
3482    //          //
3483    //          if ( glA->GetPHYSENDRUN_MASK_S3S2S12() )
3484    //            oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , ";
3485    //          if ( glA->GetPHYSENDRUN_MASK_S11CRC() )
3486    //            oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , ";
3487    //          //        
3488    //          oss << " RUNHEADER_OBT=" << glA->GetRUNHEADER_OBT()<< " , "
3489    //              << " RUNHEADER_PKT=" << glA->GetRUNHEADER_PKT();
3490    //          oss << " WHERE ID=" << glrun->GetID() << ";";
3491    //          if ( IsDebug() ) printf(" update with correct infos2: %s\n",oss.str().c_str());
3492    //          conn->Query(oss.str().c_str());    
3493    //        };
3494    //        //
3495    //        // update runheader ROOT_ID_FRAG
3496    //        //
3497    //        oss.str("");
3498    //        oss << "UPDATE GL_RUN SET ID_RUN_FRAG = " << glrun->GetID() << " where ID = " << IDRL2A << ";";
3499    //        if ( IsDebug() ) printf(" update gl_run to have cross indexing: %s\n",oss.str().c_str());
3500    //        conn->Query(oss.str().c_str());
3501    //        //
3502    //        // now let's look for runtrailer if any in the last run
3503    //        //
3504    //        glA->Query_GL_RUN(IDRL2B,conn);
3505    //        //
3506    //        if ( glA->GetPKT_READY_COUNTER() != 0 ){
3507    //          //
3508    //          // the first piece contains a good runtrailer we can update all the other runs with correct infos!
3509    //          //
3510    //          oss.str("");
3511    //          oss << "UPDATE GL_RUN_FRAGMENTS SET "
3512    //              << " RUNTRAILER_TIME=" << glA->GetRUNTRAILER_TIME()<< " , "
3513    //              << " RUNTRAILER_OBT=" << glA->GetRUNTRAILER_OBT()<< " , "
3514    //              << " RUNTRAILER_PKT=" << glA->GetRUNTRAILER_PKT()<< " , "
3515    //              << " PKT_COUNTER=" << glA->GetPKT_COUNTER()<< " , ";
3516    //          //
3517    //          if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ){
3518    //            oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
3519    //          if ( glA->GetPHYSENDRUN_MASK_S11CRC() ) {
3520    //            oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
3521    //          //        
3522    //          oss << " PKT_READY_COUNTER=" << glA->GetPKT_READY_COUNTER()
3523    //              << " WHERE ID=" << glrun->GetID() << ";";
3524    //          if ( IsDebug() ) printf(" update with correct trailer infos: %s\n",oss.str().c_str());
3525    //          conn->Query(oss.str().c_str());    
3526    //          //
3527    //        } else {
3528    //          //
3529    //          // sig no runtrailer, let set anyway what is possible...
3530    //          //
3531    //          oss.str("");
3532    //          oss << "UPDATE GL_RUN_FRAGMENTS SET "
3533    //              << " RUNTRAILER_TIME=" << glA->GetRUNTRAILER_TIME()<< " , "
3534    //              << " RUNTRAILER_OBT=" << glA->GetRUNTRAILER_OBT()<< " , ";
3535    //            //
3536    //          if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ){
3537    //            oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
3538    //          if ( glA->GetPHYSENDRUN_MASK_S11CRC() ){
3539    //            oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
3540    //          //        
3541    //          oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()
3542    //              << " WHERE ID=" << glrun->GetID() << ";";
3543    //          if ( IsDebug() ) printf(" update with correct trailer infos2: %s\n",oss.str().c_str());
3544    //          conn->Query(oss.str().c_str());    
3545    //        };
3546    //        //
3547    //        UInt_t myi = glrun->GetID();
3548    //        oss.str("");
3549    //        oss << " ID= "<< myi;
3550    //        //
3551    //        glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);  
3552    //        //
3553    //        // fill the new run in GL_RUN
3554    //        //
3555    //        glrun->SetID_RUN_FRAG(IDRL2B);
3556    //        glrun->Fill_GL_RUN(conn);    
3557    //        glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3558    //        delete glA;
3559    //        //
3560    //      } else {
3561              //
3562              // is just a repetition
3563              //
3564              if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");        
3565              if ( PEDANTIC ) throw -70;
3566            };
3567          //          //
3568          } else {
3569            if ( NoFrag() ){
3570              glrun->SetID_RUN_FRAG(glrun->GetID());
3571              glrun->Fill_GL_RUN(conn);    
3572              glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3573            };    
3574        };        };
       //  
       // delete old entries in fragment table  
       //  
       glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       //  
       delete glrun1;  
       //  
       return;  
       //  
3575      };      };
3576      //    }; // EEE
   };  
3577    //    //
3578   justcheck:    return;
3579    };
3580    
3581    
3582    /**
3583     * Handle run without header or trailer
3584     **/
3585    void PamelaDBOperations::HandleMissingHoT(Bool_t mishead, Bool_t mistrail, UInt_t firstev, UInt_t lastev){  
3586    //    //
3587    if ( !found ){          //
3588      // is the piece of run good (no other packets inside)?
3589      //
3590      if ( !this->IsRunConsistent(mishead,mistrail,firstev,lastev)){
3591        //
3592        // if not, handle other pieces and continue with the first one
3593      //      //
3594      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");
3595      //      //
3596      // 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 {  
3597      //      //
3598      this->FillClass(mishead,mistrail,firstev,lastev);      this->FillClass(mishead,mistrail,firstev,lastev);
3599      //      //
# Line 3015  void PamelaDBOperations::HandleMissingHo Line 3601  void PamelaDBOperations::HandleMissingHo
3601        glrun->SetID(this->AssignRunID());        glrun->SetID(this->AssignRunID());
3602        glrun->SetID_RUN_FRAG(0);        glrun->SetID_RUN_FRAG(0);
3603        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...
3604      };        };
3605      //      //
3606    };    };
3607    //    //
# Line 3031  Bool_t PamelaDBOperations::IsRunConsiste Line 3617  Bool_t PamelaDBOperations::IsRunConsiste
3617    //      //  
3618    EventCounter *code=0;    EventCounter *code=0;
3619    //    //
3620    UInt_t nevent = 0;    //  UInt_t nevent = 0;
3621    UInt_t checkfirst = 0;    UInt_t checkfirst = 0;
3622    UInt_t checklast = 0;    UInt_t checklast = 0;
3623    UInt_t firstentry = 0;    UInt_t firstentry = 0;
# Line 3053  Bool_t PamelaDBOperations::IsRunConsiste Line 3639  Bool_t PamelaDBOperations::IsRunConsiste
3639    EventHeader *eh = 0;    EventHeader *eh = 0;
3640    PscuHeader *ph = 0;    PscuHeader *ph = 0;
3641    T->SetBranchAddress("Header", &eh);    T->SetBranchAddress("Header", &eh);
3642    nevent = T->GetEntries();    //  nevent = T->GetEntries();
3643    //    //
3644    //    //
3645    if ( firstev == lastev+1 || lastev == firstev ) { // no events inside the run!    if ( firstev == lastev+1 || lastev == firstev ) { // no events inside the run!
3646      //if ( firstev <= lastev+1 ) { // no events inside the run!      //if ( firstev <= lastev+1 ) { // no events inside the run!
3647      if ( IsDebug() ) printf(" Checking but no events in the run! \n");      if ( IsDebug() ) printf(" Checking but no events in the run! \n");
3648        firstev = lastev+1; // this is necessary for files with no Physics entries, should have no influence on other files
3649      // return true is correct      // return true is correct
3650      return(true);      return(true);
3651      //      //
# Line 3068  Bool_t PamelaDBOperations::IsRunConsiste Line 3655  Bool_t PamelaDBOperations::IsRunConsiste
3655      code = eh->GetCounter();      code = eh->GetCounter();
3656      checkfirst = 0;      checkfirst = 0;
3657      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3658         if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
3659       };      };
3660      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);
3661      //      //
3662      T->GetEntry(lastev);      T->GetEntry(lastev);
3663      code = eh->GetCounter();      code = eh->GetCounter();
3664      checklast = 0;      checklast = 0;
3665      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3666         if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
3667       };      };
3668      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);
3669      //      //
3670      if ( checkfirst == checklast ){      if ( checkfirst == checklast ){
# Line 3088  Bool_t PamelaDBOperations::IsRunConsiste Line 3675  Bool_t PamelaDBOperations::IsRunConsiste
3675        //        //
3676      } else {      } else {
3677        //        //
3678        if ( IsDebug() ) printf(" There are no-phyics packets inside the run!\n");        if ( IsDebug() ) printf(" There are no-physics packets inside the run!\n");
3679        //        //
3680        // HERE WE MUST HANDLE THAT RUNS AND GO BACK        // HERE WE MUST HANDLE THAT RUNS AND GO BACK
3681        //        //
3682  //      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");
3683        //        //
3684        Bool_t emptyruns = false;        Bool_t emptyruns = false;
3685        UInt_t check = 0;        UInt_t check = 0;
3686        UInt_t lastevtemp = lastev;        UInt_t lastevtemp = lastev;
3687        UInt_t firstevno = firstev;        UInt_t firstevno = firstev;
3688          UInt_t rhchko=0;
3689          UInt_t rhchk=0;
3690        //        //
3691        for (UInt_t i=firstev; i<=lastev; i++){        for (UInt_t i=firstev; i<=lastev; i++){
3692          //          //
# Line 3106  Bool_t PamelaDBOperations::IsRunConsiste Line 3695  Bool_t PamelaDBOperations::IsRunConsiste
3695          //          //
3696          check = 0;          check = 0;
3697          //          //
3698    
3699            // if we have a runheader set lastev then exit
3700            //
3701          for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){          for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3702            if ( strcmp(*Iter,"Physics") ) check += code->Get(GetPacketType(*Iter));            if ( strcmp(*Iter,"Physics") ) check += code->Get(GetPacketType(*Iter));
3703          };          };
3704            // check here if we have a runheader
3705            rhchko = rhchk;  
3706            rhchk = code->Get(GetPacketType("RunHeader"));    
3707          //          //
3708          if ( checkfirst < check || i == lastev ){          if ( checkfirst < check || i == lastev ){
3709            //            //
# Line 3184  Bool_t PamelaDBOperations::IsRunConsiste Line 3779  Bool_t PamelaDBOperations::IsRunConsiste
3779            };            };
3780            //                  //      
3781            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
3782              this->SetPhysEndRunVariables();
3783            //            //
3784            if ( chminentry == firstentry  ){ // EEE            if ( chminentry == firstentry  ){ // EEE
3785              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");
3786  //              //
3787  //          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
3788  //              //
   
   
   
   
   
   
   
   
   
   
   
   
   
   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  
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
3789    
3790                mishead = true;
3791    
3792    
3793                UInt_t rhfirstev = firstentry;
3794                //  UInt_t rtlastev = lastentry;
3795                Bool_t found = false;
3796                Bool_t foundinrun = false;
3797                //
3798                TSQLResult *result = 0;
3799                TSQLRow    *row    = 0;
3800                //
3801                stringstream oss;
3802                oss.str("");
3803                //
3804                // we have now the good first piece of a run, fill the glrun object
3805                //
3806                //  if ( rhfirstev != firstev && !mishead ) mishead = true;
3807                //  if ( rtlastev != lastev && !mistrail ) mistrail = true;
3808                //
3809                //  this->FillClass(mishead,mistrail,firstev,lastev);
3810                //
3811                if ( IsDebug() ) printf("zz The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
3812                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());
3813                //
3814                // First of all insert the run in the fragment table...
3815                //
3816                oss.str("");
3817                oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
3818                    << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3819                    << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3820                    << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3821                    << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3822                    << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3823                    << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3824                    << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3825                    << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3826                    << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3827                    << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3828                    << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3829                    << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3830                    << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3831                //
3832                if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3833                result = conn->Query(oss.str().c_str());
3834                //
3835                if ( !result ) throw -4;
3836                //
3837                row = result->Next();
3838                //
3839                if ( !row ){
3840                  //
3841                  // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
3842                  //
3843                  if ( IsDebug() ) printf(" The run is new \n");
3844                  if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
3845                  //
3846                  glrun->SetID(this->AssignRunID());
3847                  glrun->SetID_RUN_FRAG(0);
3848                  glrun->Fill_GL_RUN_FRAGMENTS(conn);
3849                  //
3850                } else {
3851                  if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
3852                  if ( PEDANTIC ) throw -69;
3853                  //    return;
3854                };
3855                //
3856                if ( chewbacca && mishead && mistrail ) goto zjustcheck;
3857                //
3858                // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
3859                //
3860                if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
3861                  // missing it no way we can found a piece in the frag table
3862                  //
3863                  oss.str("");
3864                  oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "
3865                      << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3866                      << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3867                      << " ID != " << glrun->ID
3868                      << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
3869                  //
3870                  if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());
3871                  result = conn->Query(oss.str().c_str());
3872                  //
3873                  if ( !result ) throw -4;
3874                  //
3875                  row = result->Next();
3876                  //
3877                  if ( !row && NoFrag() ){
3878                    //
3879                    oss.str("");
3880                    oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
3881                        << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3882                        << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3883                        << " ID != " << glrun->ID
3884                        << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
3885                    //
3886                    if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
3887                    result = conn->Query(oss.str().c_str());
3888                    //
3889                    if ( !result ) throw -4;
3890                    //
3891                    foundinrun = true;
3892                    //
3893                    row = result->Next();
3894                    //
3895                  };
3896                  //
3897                  if ( !row ){
3898                    if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
3899                    found = false;
3900                  } else {
3901                    //
3902                    found = false; // default value
3903                    //
3904                    if ( IsDebug() ) printf(" C Found a possible candidate, checking if it is the good one... \n");
3905                    //
3906                    // if we have both runheader and runtrailer we can check with pkt_counter:
3907                    //
3908                    if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){
3909                      ULong64_t chkpkt = 0;
3910                      ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
3911                      ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
3912                      //
3913                      chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;
3914                      //
3915                      if ( labs(chkpkt-pktt)<2 ){
3916                        //
3917                        if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
3918                        //
3919                        found = true;
3920                        //
3921                      } else {
3922                        //
3923                        if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);
3924                        //
3925                        found = false;
3926                        //
3927                      };
3928                    };
3929                    if ( !found && chewbacca ) goto zjustcheck;
3930                    if ( !found ){
3931                      //
3932                      // 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
3933                      //
3934                      ULong64_t chkpkt1 = 0;
3935                      ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
3936                      ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
3937                      chkpkt1 = labs(orunh1-dbrunt1);
3938                      //
3939                      ULong64_t chkpkt2 = 0;
3940                      ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());
3941                      ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
3942                      chkpkt2 = labs(orunh2-dbrunt2);
3943                      //
3944                      ULong64_t chkpkt3 = 0;
3945                      ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());
3946                      ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
3947                      chkpkt3 = labs(orunh3-dbrunt3);
3948                      //
3949                      if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
3950                        //    if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){
3951                        //
3952                        if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
3953                        //
3954                        found = true;
3955                        //
3956                      } else {
3957                        //
3958                        if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
3959                        //
3960                        found = false;
3961                        //
3962                      };
3963                    };
3964                  };
3965                  //
3966                  if ( found ){
3967                    //
3968                    // 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
3969                    //
3970                    if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
3971                    //
3972                    if ( foundinrun ){
3973                      glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3974                      glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
3975                    };
3976                    //
3977                    GL_RUN *glrun1 = new GL_RUN();
3978                    //
3979                    //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
3980                    //
3981                    oss.str("");
3982                    oss << " ID="<<row->GetField(0)<<";";
3983                    //
3984                    glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos
3985                    //
3986                    // merge infos
3987                    //
3988                    UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());
3989                    ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
3990                    UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
3991                    ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
3992                    if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
3993                    TTree *T= 0;
3994                    T = (TTree*)file->Get("Physics");
3995                    if ( !T || T->IsZombie() ) throw -16;
3996                    EventHeader *eh = 0;
3997                    PscuHeader *ph = 0;
3998                    T->SetBranchAddress("Header", &eh);
3999                    while ( apkt > bpkt && aobt > bobt && firstev < lastev ){
4000                      T->GetEntry(firstev);
4001                      ph = eh->GetPscuHeader();
4002                      bpkt = PKT(ph->GetCounter());
4003                      bobt = OBT(ph->GetOrbitalTime());
4004                      firstev++;
4005                      if ( PEDANTIC ) throw -71;
4006                    };
4007                    if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
4008                    //
4009                    glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
4010                    glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
4011                    glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
4012                    glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());
4013                    glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());
4014                    //
4015                    glrun->SetEV_FROM(firstev);
4016                    glrun->SetNEVENTS(lastev-firstev+1);
4017                    //
4018                    glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
4019                    glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
4020                    glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
4021                    glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());
4022                    glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());
4023                    glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());
4024                    glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());
4025                    glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());
4026                    glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());
4027                    glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());
4028                    glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());
4029                    glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());
4030                    glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());
4031                    glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());
4032                    glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());
4033                    glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());
4034                    //
4035                    if ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
4036                    if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
4037                    //
4038                    if ( !IsRunAlreadyInserted() ){
4039                      //
4040                      //      glrun->SetID(this->AssignRunID());
4041                      glrun->SetID_RUN_FRAG(glrun1->GetID());
4042                      glrun->Fill_GL_RUN(conn);
4043                      //
4044                      // set id number
4045                      //
4046                      glrun1->SetID_RUN_FRAG(glrun->GetID());
4047                      glrun1->Fill_GL_RUN(conn);
4048                      //
4049                    };
4050                    // delete old entry in fragment table
4051                    //
4052                    glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
4053                    glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
4054                    //
4055                    delete glrun1;
4056                    //
4057                    //
4058                    //      return;
4059                    //
4060                  };
4061                  //
4062                };
4063                //
4064                //
4065              zjustcheck:
4066                //
4067                if ( !found ){
4068                  //
4069                  if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");
4070                  //
4071                  // not found, has this run already inserted in the GL_RUN or in the GL_RUN_FRAGMENTS table?
4072                  //
4073                  oss.str("");
4074                  oss << " SELECT ID FROM GL_RUN WHERE "
4075                      << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
4076                      << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
4077                      << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
4078                      << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
4079                      << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
4080                      << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
4081                      << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
4082                      << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
4083                      << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
4084                      << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
4085                      << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
4086                      << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
4087                      << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
4088                  //
4089                  if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
4090                  result = conn->Query(oss.str().c_str());
4091                  //
4092                  if ( !result ) throw -4;
4093                  //
4094                  row = result->Next();
4095                  //
4096                  if ( row ){
4097                    if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");
4098                    if ( PEDANTIC ) throw -70;
4099                  } else {
4100                    if ( NoFrag() ){
4101                      glrun->SetID_RUN_FRAG(glrun->GetID());
4102                      glrun->Fill_GL_RUN(conn);
4103                      glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
4104                    };
4105                  };
4106                }; // EEE
4107    
4108    
4109            } else {            } else {
4110            if ( !IsRunAlreadyInserted() ){              if ( !IsRunAlreadyInserted() ){
4111              glrun->SetID(this->AssignRunID());                glrun->SetID(this->AssignRunID());
4112              glrun->SetID_RUN_FRAG(0);                glrun->SetID_RUN_FRAG(0);
4113              glrun->Fill_GL_RUN(conn);                glrun->Fill_GL_RUN(conn);
4114            };              };
4115            }; // EEE            }; // EEE
4116            //            //
4117            firstevno = lastentry + 1;            firstevno = lastentry + 1;
# Line 3564  Bool_t PamelaDBOperations::IsRunConsiste Line 4120  Bool_t PamelaDBOperations::IsRunConsiste
4120            //            //
4121          };          };
4122          //          //
4123            if ( i > firstev ){
4124              if ( rhchko != rhchk ){
4125                if ( IsDebug() ) printf("oh oh... we have a runheader! stop here and handle later the remaining piece\n");
4126                lastev = i;
4127                return(false);
4128              };
4129            };
4130            //
4131          if ( check == checklast && i != lastev ){          if ( check == checklast && i != lastev ){
4132            lastevtemp = i - 1;            lastevtemp = i - 1;
4133            i = lastev - 1;            i = lastev - 1;
# Line 3596  void PamelaDBOperations::HandleSuspiciou Line 4160  void PamelaDBOperations::HandleSuspiciou
4160    EventCounter *code=0;    EventCounter *code=0;
4161    UInt_t firstev = 0;    UInt_t firstev = 0;
4162    UInt_t lastev = 0;    UInt_t lastev = 0;
4163    UInt_t nevent = 0;    //  UInt_t nevent = 0;
4164    UInt_t checkfirst = 0;    UInt_t checkfirst = 0;
4165    UInt_t checklast = 0;    UInt_t checklast = 0;
4166    UInt_t firstentry = 0;    UInt_t firstentry = 0;
# Line 3621  void PamelaDBOperations::HandleSuspiciou Line 4185  void PamelaDBOperations::HandleSuspiciou
4185    EventHeader *eh = 0;    EventHeader *eh = 0;
4186    PscuHeader *ph = 0;    PscuHeader *ph = 0;
4187    T->SetBranchAddress("Header", &eh);    T->SetBranchAddress("Header", &eh);
4188    nevent = T->GetEntries();    //  nevent = T->GetEntries();
4189    //    //
4190    codt = eht->GetCounter();    codt = eht->GetCounter();
4191    codh = ehh->GetCounter();    codh = ehh->GetCounter();
# Line 3647  void PamelaDBOperations::HandleSuspiciou Line 4211  void PamelaDBOperations::HandleSuspiciou
4211      code = eh->GetCounter();      code = eh->GetCounter();
4212      checkfirst = 0;      checkfirst = 0;
4213      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
4214         if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
4215         if ( !strcmp(*Iter,"RunHeader") ) nrunh1++;        if ( !strcmp(*Iter,"RunHeader") ) nrunh1++;
4216       };      };
4217      if ( IsDebug() ) printf(" Check first is %i \n",checkfirst);      if ( IsDebug() ) printf(" Check first is %i \n",checkfirst);
4218      //      //
4219      T->GetEntry(lastev);      T->GetEntry(lastev);
4220      code = eh->GetCounter();      code = eh->GetCounter();
4221      checklast = 0;      checklast = 0;
4222      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
4223         if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
4224       };      };
4225      if ( IsDebug() ) printf(" Check last is %i \n",checklast);      if ( IsDebug() ) printf(" Check last is %i \n",checklast);
4226      //      //
4227      if ( checkfirst == checklast ){      if ( checkfirst == checklast ){
# Line 3769  void PamelaDBOperations::HandleSuspiciou Line 4333  void PamelaDBOperations::HandleSuspiciou
4333            };            };
4334            //                  //      
4335            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
4336              this->SetPhysEndRunVariables();
4337            //            //
4338            if ( !IsRunAlreadyInserted() ){            if ( !IsRunAlreadyInserted() ){
4339              glrun->SetID(this->AssignRunID());              glrun->SetID(this->AssignRunID());
# Line 3808  void PamelaDBOperations::HandleSuspiciou Line 4373  void PamelaDBOperations::HandleSuspiciou
4373              if ( IsDebug() ) printf(" We have the runtrailer \n");              if ( IsDebug() ) printf(" We have the runtrailer \n");
4374              //                  //    
4375              this->SetCommonGLRUN(firstTime,lastTime);              this->SetCommonGLRUN(firstTime,lastTime);
4376                this->SetPhysEndRunVariables();
4377              //              //
4378              if ( !IsRunAlreadyInserted() ){              if ( !IsRunAlreadyInserted() ){
4379                glrun->SetID(this->AssignRunID());                glrun->SetID(this->AssignRunID());
# Line 3853  Int_t PamelaDBOperations::insertCALO_CAL Line 4419  Int_t PamelaDBOperations::insertCALO_CAL
4419    UInt_t totime = 0;    UInt_t totime = 0;
4420    UInt_t obt = 0;    UInt_t obt = 0;
4421    UInt_t pkt = 0;    UInt_t pkt = 0;
4422      Float_t totped = 0.;
4423    //    //
4424    tr = (TTree*)file->Get("CalibCalPed");    tr = (TTree*)file->Get("CalibCalPed");
4425    if ( !tr || tr->IsZombie() ) throw -21;    if ( !tr || tr->IsZombie() ) throw -21;
# Line 3870  Int_t PamelaDBOperations::insertCALO_CAL Line 4437  Int_t PamelaDBOperations::insertCALO_CAL
4437        if ( calibCalPed->cstwerr[section] ){        if ( calibCalPed->cstwerr[section] ){
4438          valid = 1;          valid = 1;
4439          if ( calibCalPed->cperror[section] ) valid = 0;          if ( calibCalPed->cperror[section] ) valid = 0;
4440            //
4441            // 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.]
4442            //
4443            totped = 0.;
4444            Int_t ns = 0;
4445            if ( section == 2 ) ns = 3;
4446            if ( section == 3 ) ns = 1;
4447            if ( section == 1 ) ns = 2;
4448            for (UInt_t ss=0; ss<96; ss++){
4449              totped += fabs(calibCalPed->calped[ns][0][ss]);
4450            }
4451            if ( totped < 1. ){
4452              if ( IsDebug() ) printf(" Section %i totped %f -  No calibration data! Calorimeter power problems? \n",section,totped);
4453              valid = 0;
4454            };
4455            //
4456          ph = eh->GetPscuHeader();          ph = eh->GetPscuHeader();
4457          obt = ph->GetOrbitalTime();            obt = ph->GetOrbitalTime();  
4458          pkt = ph->GetCounter();            pkt = ph->GetCounter();  
# Line 4037  Int_t PamelaDBOperations::insertCALOPULS Line 4620  Int_t PamelaDBOperations::insertCALOPULS
4620    tr->SetBranchAddress("Header", &eh);    tr->SetBranchAddress("Header", &eh);
4621    nevents = tr->GetEntries();    nevents = tr->GetEntries();
4622    //    //
4623      Float_t totpul = 0.;
4624      //
4625    if ( nevents > 0 ){    if ( nevents > 0 ){
4626      //      //
4627      for (UInt_t i=0; i < nevents; i++){      for (UInt_t i=0; i < nevents; i++){
# Line 4046  Int_t PamelaDBOperations::insertCALOPULS Line 4631  Int_t PamelaDBOperations::insertCALOPULS
4631          if ( cp1->pstwerr[section] && cp1->unpackError == 0 ){          if ( cp1->pstwerr[section] && cp1->unpackError == 0 ){
4632            valid = 1;            valid = 1;
4633            if ( cp1->pperror[section] ) valid = 0;            if ( cp1->pperror[section] ) valid = 0;
4634              //
4635              // 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.]
4636              //
4637              totpul = 0.;
4638              Int_t ns = 0;
4639              if ( section == 2 ) ns = 3;
4640              if ( section == 3 ) ns = 1;
4641              if ( section == 1 ) ns = 2;
4642              for (UInt_t ss=0; ss<96; ss++){
4643                totpul += cp1->calpuls[ns][0][ss];
4644              }
4645              if ( totpul >= 3145632. ){
4646                if ( IsDebug() ) printf(" PULSE1 Section %i totpul %f -  No calibration data! Calorimeter power problems? \n",section,totpul);
4647                valid = 0;
4648              };
4649              //
4650            ph = eh->GetPscuHeader();            ph = eh->GetPscuHeader();
4651            obt = ph->GetOrbitalTime();              obt = ph->GetOrbitalTime();  
4652            pkt = ph->GetCounter();              pkt = ph->GetCounter();  
# Line 4203  Int_t PamelaDBOperations::insertCALOPULS Line 4804  Int_t PamelaDBOperations::insertCALOPULS
4804          if ( cp2->pstwerr[section] && cp2->unpackError == 0 ){          if ( cp2->pstwerr[section] && cp2->unpackError == 0 ){
4805            valid = 1;            valid = 1;
4806            if ( cp2->pperror[section] ) valid = 0;            if ( cp2->pperror[section] ) valid = 0;
4807              //
4808              // 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.]
4809              //
4810              totpul = 0.;
4811              Int_t ns = 0;
4812              if ( section == 2 ) ns = 3;
4813              if ( section == 3 ) ns = 1;
4814              if ( section == 1 ) ns = 2;
4815              for (UInt_t ss=0; ss<96; ss++){
4816                totpul += cp2->calpuls[ns][0][ss];
4817              }
4818              if ( totpul >= 3145632. ){
4819                if ( IsDebug() ) printf(" PULSE2 Section %i totpul %f -  No calibration data! Calorimeter power problems? \n",section,totpul);
4820                valid = 0;
4821              };
4822              //
4823            ph = eh->GetPscuHeader();            ph = eh->GetPscuHeader();
4824            obt = ph->GetOrbitalTime();              obt = ph->GetOrbitalTime();  
4825            pkt = ph->GetCounter();              pkt = ph->GetCounter();  
# Line 4382  Int_t PamelaDBOperations::insertCALOPULS Line 4999  Int_t PamelaDBOperations::insertCALOPULS
4999   * Fill the GL_TRK_CALIB table   * Fill the GL_TRK_CALIB table
5000   */   */
5001  void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){  void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){
5002    //      
5003    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;  
5004      //      //
5005    } else {      glcal->ID         = 0;
5006        glcal->ID_ROOT_L0 = GetID_ROOT();
5007        glcal->EV_ROOT_CALIBTRK1 = t1;
5008        glcal->EV_ROOT_CALIBTRK2 = t2;
5009        glcal->FROM_TIME = fromtime;
5010        glcal->TO_TIME   = 0;
5011        glcal->OBT1      = obt1;
5012        glcal->OBT2      = obt2;
5013        glcal->PKT1      = pkt1;
5014        glcal->PKT2      = pkt2;
5015        glcal->BOOT_NUMBER = GetBOOTnumber();
5016        glcal->VALIDATION = valid;
5017      //      //
5018      // we have to insert a new calibration, check where to place it      HandleTRK_CALIB(glcal);
5019      //      //
5020      oss.str("");      delete glcal;
5021      oss << " SELECT ID,TO_TIME FROM GL_TRK_CALIB WHERE "  }
5022          << " FROM_TIME < "<< fromtime << " AND "  /**
5023          << " TO_TIME > "<< fromtime << ";";   * Fill the GL_TRK_CALIB table
5024     */
5025    void PamelaDBOperations::HandleTRK_CALIB(GL_TRK_CALIB *glcal){
5026    
5027        Bool_t pk1 = (glcal->OBT1>0&&glcal->PKT1>0);
5028        Bool_t pk2 = (glcal->OBT2>0&&glcal->PKT2>0);
5029        UInt_t boot_number = glcal->BOOT_NUMBER;
5030        UInt_t obt1 = glcal->OBT1;
5031        UInt_t obt2 = glcal->OBT2;
5032        UInt_t pkt1 = glcal->PKT1;
5033        UInt_t pkt2 = glcal->PKT2;
5034        UInt_t fromtime = glcal->FROM_TIME;
5035        UInt_t totime = 0;
5036        UInt_t idroot = glcal->ID_ROOT_L0;
5037        UInt_t t1 = glcal->EV_ROOT_CALIBTRK1;
5038        UInt_t t2 = glcal->EV_ROOT_CALIBTRK2;
5039        UInt_t valid = glcal->VALIDATION;
5040      //      //
5041      if ( IsDebug() ) printf(" Check where to place the trk calibration: query is \n %s \n",oss.str().c_str());      TSQLResult *result = 0;
5042      result = conn->Query(oss.str().c_str());      TSQLRow    *row    = 0;
5043      //      //
5044      if ( !result ) throw -4;      stringstream oss;
5045        oss.str("");
5046      //      //
     row = result->Next();  
5047      //      //
5048      if ( !row ){      if ( !pk1 && !pk2 ){
5049        //          if ( IsDebug() ) printf(" Cannot handle trk calibration with both packet missing!\n");
5050        // 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;  
       //  
5051      };      };
5052      //      //
5053      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 << "',";  
5054      //      //
5055      if ( !pk1 ){      oss.str("");
5056        oss << "NULL,";      oss << " SELECT ID FROM GL_TRK_CALIB WHERE "
5057            << " BOOT_NUMBER = "<< boot_number; //
5058        oss << " AND FROM_TIME="<<fromtime; /// NEWNEWNEW -- VA BENE ?!?!?!?!
5059        oss << " AND ( ( ";  
5060        if ( pk1 ){
5061            oss << " OBT1 = "<< obt1 << " AND "
5062                << " PKT1 = "<< pkt1
5063                << " ) OR ( ";
5064      } else {      } else {
5065        oss << "'"          oss << " PKT1 = "<< pkt2-1
5066            << t1 << "',";              << " ) OR ( ";  
5067      };      };      
5068      //      if ( pk2 ){
5069      if ( !pk2 ){          oss << " OBT2 = "<< obt2 << " AND "
5070        oss << "NULL,'";              << " PKT2 = "<< pkt2;
5071      } else {      } else {
5072        oss << "'"          oss << " PKT2 = "<< pkt1+1;
5073            << t2 << "','";      };      
5074      };      oss << " ) );";  
5075        //
5076        if ( IsDebug() ) printf(" Check if the trk calibration has already been inserted: query is \n %s \n",oss.str().c_str());
5077        result = conn->Query(oss.str().c_str());
5078      //      //
5079      oss << fromtime << "','"      if ( !result ) throw -4;
         << totime << "','"  
         << obt1 << "','"  
         << pkt1 << "','"  
         << obt2 << "','"  
         << pkt2 << "','"  
         << this->GetBOOTnumber() << "','"  
         << valid << "');";  
5080      //      //
5081      if ( IsDebug() ) printf(" Insert the new trk calibration: query is \n %s \n",oss.str().c_str());      row = result->Next();
5082      //      //
5083        if ( row ){
5084            //
5085            if ( IsDebug() ) printf(" Trk calibration already inserted in the DB\n");
5086            if ( PEDANTIC ) throw -80;
5087            //
5088        } else {
5089            //
5090            // we have to insert a new calibration, check where to place it
5091            //
5092            oss.str("");
5093            oss << " SELECT ID,TO_TIME FROM GL_TRK_CALIB WHERE "
5094                << " FROM_TIME < "<< fromtime << " AND "
5095                << " TO_TIME > "<< fromtime << ";";
5096            //
5097            if ( IsDebug() ) printf(" Check where to place the trk calibration: query is \n %s \n",oss.str().c_str());
5098            result = conn->Query(oss.str().c_str());
5099            //
5100            if ( !result ) throw -4;
5101            //
5102            row = result->Next();
5103            //
5104            if ( !row ){
5105                //
5106                // no calibrations in the db contain our calibration
5107                //
5108                if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB\n");
5109                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
5110                //
5111                oss.str("");
5112                oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "
5113                    << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
5114                //
5115                if ( IsDebug() ) printf(" Check the upper limit for calibration: query is \n %s \n",oss.str().c_str());
5116                result = conn->Query(oss.str().c_str());
5117                //
5118                if ( !result ) throw -4;
5119                //
5120                row = result->Next();
5121                if ( !row ){
5122                    totime = numeric_limits<UInt_t>::max();
5123                } else {
5124                    totime = (UInt_t)atoll(row->GetField(0));
5125                };
5126                //
5127            } else {
5128                //
5129                // determine upper and lower limits and make space for the new calibration
5130                //
5131                totime = (UInt_t)atoll(row->GetField(1));
5132                //
5133                oss.str("");
5134                oss << " UPDATE GL_TRK_CALIB SET "  
5135                    << " TO_TIME = "<< fromtime << " WHERE "  // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
5136                    << " ID = "<< row->GetField(0) << ";";
5137                //
5138                if ( IsDebug() ) printf(" Make space for the new trk calibration: query is \n %s \n",oss.str().c_str());
5139                result = conn->Query(oss.str().c_str());
5140                //
5141                if ( !result ) throw -4;
5142                //
5143            };
5144            //
5145            oss.str("");
5146            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) "
5147                << " VALUES (NULL,' "
5148                << idroot << "',";
5149            //
5150            if ( !pk1 ){
5151                oss << "NULL,";
5152            } else {
5153                oss << "'"
5154                    << t1 << "',";
5155            };
5156            //
5157            if ( !pk2 ){
5158                oss << "NULL,'";
5159            } else {
5160                oss << "'"
5161                    << t2 << "','";
5162            };
5163            //
5164            oss << fromtime << "','"
5165                << totime << "','"
5166                << obt1 << "','"
5167                << pkt1 << "','"
5168                << obt2 << "','"
5169                << pkt2 << "','"
5170                << boot_number << "','"
5171                << valid << "');";
5172            //
5173            if ( IsDebug() ) printf(" Insert the new trk calibration: query is \n %s \n",oss.str().c_str());
5174            //
5175            result = conn->Query(oss.str().c_str());
5176            //
5177            if ( !result ) throw -4;
5178            //
5179        };
5180        
5181        oss.str("");
5182        oss << " SELECT ID FROM GL_TRK_CALIB ORDER BY ID DESC LIMIT 1 ;";  
5183        if ( IsDebug() ) cout << oss.str().c_str() << endl;
5184      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
5185        if ( !result ) throw -4;;
5186        row = result->Next();
5187        if(row)glcal->ID = (UInt_t)atoll(row->GetField(0));
5188      //      //
5189      if ( !result ) throw -4;      delete result; // mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
5190      //      //
   };  
   //  
5191  };  };
5192    
5193  /**  /**
5194   * Scan tracker calibrations packets, fill the GL_TRK_CALIB table   * Scan tracker calibrations packets, fill the GL_TRK_CALIB table
5195   */   */
5196  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++){  
5197      //      //
5198      pret2 = t2;      CalibTrk1Event *caltrk1 = 0;
5199      tr1->GetEntry(t1);      CalibTrk2Event *caltrk2 = 0;
5200        TTree *tr1 = 0;
5201        TTree *tr2 = 0;
5202        EventHeader *eh1 = 0;
5203        PscuHeader *ph1 = 0;
5204        EventHeader *eh2 = 0;
5205        PscuHeader *ph2 = 0;
5206      //      //
5207      ph1 = eh1->GetPscuHeader();      PacketType *pctp=0;
5208      obt1 = ph1->GetOrbitalTime();        EventCounter *codt2=0;
     pkt1 = ph1->GetCounter();    
     fromtime = this->GetAbsTime(ph1->GetOrbitalTime());    
5209      //      //
5210  //     valid = 1;      Int_t nevents1 = 0;
5211  //     //      Int_t nevents2 = 0;
 //     if ( caltrk1->unpackError != 0 && caltrk1->good0 == 0 ) valid = 0;// CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT1  
5212      //      //
5213        fromtime = 0;
5214      //      //
5215      if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->PKT(pkt1) <= upperpkt && this->OBT(obt1) >= this->OBT(obtfirst) && this->OBT(obt1) <= upperobt ){      obt1 = 0;
5216        //    if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->OBT(obt1) >= this->OBT(obtfirst) ){      pkt1 = 0;
5217        //      obt2 = 0;
5218        if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u \n",fromtime,obt1,pkt1);      pkt2 = 0;
5219        //            //
5220        valid = ValidateTrkCalib( caltrk1, eh1 );      tr1 = (TTree*)file->Get("CalibTrk1");
5221        if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;      if ( !tr1 || tr1->IsZombie() ) throw -22;
5222        //      tr2 = (TTree*)file->Get("CalibTrk2");
5223        // Do we have the second calibration packet?      if ( !tr2 || tr2->IsZombie() ) throw -23;
5224        //      //
5225        while ( t2t1cal < t1+1 ){ // get the calibration packet2 that follows the packet1      tr1->SetBranchAddress("CalibTrk1", &caltrk1);
5226        tr1->SetBranchAddress("Header", &eh1);
5227        nevents1 = tr1->GetEntries();
5228        tr2->SetBranchAddress("CalibTrk2", &caltrk2);
5229        tr2->SetBranchAddress("Header", &eh2);
5230        nevents2 = tr2->GetEntries();
5231        //
5232        if ( !nevents1 && !nevents2 ) return(1);
5233        //
5234        t2 = -1;
5235        Int_t pret2 = 0;
5236        Int_t t2t1cal = 0;
5237        //
5238        bool MISSING_pkt1 = true;
5239        bool MISSING_pkt2 = true;
5240        int  ncalib = 0;
5241        bool try_to_recover = false;
5242        //
5243        for (t1=0; t1 < nevents1; t1++){//loop over packet1
5244          //          //
5245          t2++;          pret2 = t2;
5246            tr1->GetEntry(t1);
5247          //          //
5248          pret2 = t2 - 1; // EMILIANO          ph1 = eh1->GetPscuHeader();
5249            obt1 = ph1->GetOrbitalTime();  
5250            pkt1 = ph1->GetCounter();  
5251            fromtime = GetAbsTime(ph1->GetOrbitalTime());  
5252          //          //
5253          if ( t2 < nevents2 ){          // chek if the packet number and obt are consistent with the other packets ???
5254            tr2->GetEntry(t2);          //
5255            codt2 = eh2->GetCounter();          if ( PKT(pkt1) >= PKT(pktfirst) && PKT(pkt1) <= upperpkt && OBT(obt1) >= OBT(obtfirst) && OBT(obt1) <= upperobt ){
5256            t2t1cal = codt2->Get(pctp->CalibTrk1);              //    if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->OBT(obt1) >= this->OBT(obtfirst) ){
5257            //              //
5258            ph2 = eh2->GetPscuHeader();              if ( IsDebug() ) printf("\n Trk calibration1 %u at time %u obt %u pkt %u \n",t1,fromtime,obt1,pkt1);
5259            obt2 = ph2->GetOrbitalTime();                //      
5260            pkt2 = ph2->GetCounter();                valid = ValidateTrkCalib( caltrk1, eh1 );
5261            //              if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;
5262            if ( IsDebug() ) printf(" This is a trk calibration2 at obt %u pkt %u t2 is %u , t2t1cal is %u \n",obt2,pkt2,t2,t2t1cal);                    //
5263  //        if ( caltrk2->unpackError != 0 || caltrk2->good0 == 0 ) valid = 0; // CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT2              // Do we have the second calibration packet?
5264            //                    //
5265          } else {              if ( IsDebug() ) cout << " Loop over calibration2 to search associated calibration: "<<endl;
5266            //              while ( t2t1cal < t1+1 ){ // get the calibration packet2 that follows the packet1
5267            // running out of vector without finding the corresponding calibration, sig                  //
5268            //                  t2++;
5269            if ( IsDebug() ) printf(" t2 >= nevents2 \n");                  //
5270            pret2 = t2;                  pret2 = t2 - 1; // EMILIANO
5271            obt2 = 0;                  //
5272            //      pkt2 = pkt1+2;                  if ( t2 < nevents2 ){
5273            pkt2 = 0;                      tr2->GetEntry(t2);
5274            t2t1cal = t1+1;                      codt2 = eh2->GetCounter();
5275          };                      t2t1cal = codt2->Get(pctp->CalibTrk1);
5276          //      if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) && (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){                      //
5277                        ph2 = eh2->GetPscuHeader();
5278                        obt2 = ph2->GetOrbitalTime();  
5279                        pkt2 = ph2->GetCounter();  
5280                        //
5281                        if ( IsDebug() ) printf(" >> trk calibration2 at obt %u pkt %u t2 is %u , t2t1cal is %u \n",obt2,pkt2,t2,t2t1cal);    
5282                        //    if ( caltrk2->unpackError != 0 || caltrk2->good0 == 0 ) valid = 0; // CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT2
5283                        //    
5284                    } else {
5285                        //
5286                        // running out of vector without finding the corresponding calibration, sig
5287                        //
5288                        if ( IsDebug() ) printf(" t2 >= nevents2 \n");
5289                        pret2 = t2;
5290                        obt2 = 0;
5291                        //    pkt2 = pkt1+2;
5292                        pkt2 = 0;
5293                        t2t1cal = t1+1;
5294                    };
5295                    //      if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) && (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){
5296    
5297          // EMILIANO                  // EMILIANO
5298  //      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) ){
5299  //        //    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) ){
5300  //        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");
5301  //        //                  //        //
5302  //        // running out of vector without finding the corresponding calibration, sig                  //        // running out of vector without finding the corresponding calibration, sig
5303  //        //                  //        //
5304  //        pret2 = t2;                  //        pret2 = t2;
5305  //        obt2 = 0;                  //        obt2 = 0;
5306  //        //      pkt2 = pkt1+2;                  //        //      pkt2 = pkt1+2;
5307  //        pkt2 = 0;                  //        pkt2 = 0;
5308  //        t2t1cal = t1+1;                  //        t2t1cal = t1+1;
5309  //      };                  //      };
5310    
5311    
5312                    //
5313                };
5314                //
5315                if ( IsDebug() ) printf(" Check if trk calibration2 is the right one \n");
5316                //
5317                // EMILIANO
5318                if ( ( PKT(pkt2) < PKT(pktfirst) || PKT(pkt2) > upperpkt) || (OBT(obt2) < OBT(obtfirst) || OBT(obt2) > upperobt) ){
5319                    //      if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){
5320                    if ( IsDebug() ) printf(" *WARNING*  The calibration found is outside the interval, sig \n");
5321                    //
5322                    // running out of vector without finding the corresponding calibration, sig
5323                    //
5324                    pret2 = t2;
5325                    obt2 = 0;
5326                    pkt2 = 0;
5327                };
5328                if ( PKT(pkt2) == PKT(pkt1)+1 ){
5329                    if ( IsDebug() ) cout << " ...OK"<<endl;
5330                    // =======================
5331                    // The calibration is good
5332                    // =======================
5333                    //
5334    //      if ( IsDebug() ) printf(" Found trk calibration2 at obt %u pkt %u t2 is %u \n",obt2,pkt2,t2);
5335    //      if ( IsDebug() ) printf(" Trk calibration2 at obt %u pkt %u t2 is %u is good \n",obt2,pkt2,t2);
5336    //        if ( IsDebug() ) printf("\n Trk calibration2 at time %u obt %u pkt %u \n",fromtime,obt2,pkt2);
5337                    if ( IsDebug() ) printf(" Trk calibration2 %u at time %u obt %u pkt %u \n",t2,fromtime,obt2,pkt2);
5338                    //
5339                    UInt_t valid2 = ValidateTrkCalib( caltrk2, eh2 );
5340                    if ( IsDebug() ) cout << " pkt2 validation --> "<<valid2<<endl;
5341    //      valid = valid & valid2;
5342                    valid = valid & valid2; //QUESTO VA CAMBIATO
5343                    //
5344                    // Handle good calib
5345                    //
5346                    MISSING_pkt1 = false;
5347                    MISSING_pkt2 = false;
5348    //              this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5349                    //
5350                    // Check for missing calibtrk1
5351                    //
5352                    if ( t2 != pret2+1 ){
5353                        //
5354                        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);
5355                        //
5356                        while ( t2 > pret2+1 ){
5357                            //
5358                            // handle missing calib1
5359                            //
5360                            pret2++;
5361                            //
5362                            obt1 = 0;
5363                            pkt1 = 0;
5364                            //
5365                            tr2->GetEntry(pret2);
5366                            ph2 = eh2->GetPscuHeader();
5367                            obt2 = ph2->GetOrbitalTime();  
5368                            pkt2 = ph2->GetCounter();  
5369                            //
5370                            fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
5371                            //
5372                            valid = 0;
5373                            MISSING_pkt1 = true;
5374                            MISSING_pkt2 = false;
5375    //                      this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5376                            //
5377                        };
5378                        //
5379                    };
5380                    //
5381                } else if ( this->PKT(pkt2) > this->PKT(pkt1)+1 ){
5382                    //
5383                    // Check for missing calibtrk2
5384                    //
5385                    if ( IsDebug() ) printf(" Missing the trk calibration2! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);
5386                    t2 = pret2;
5387                    //
5388                    // handle missing calib2
5389                    //
5390                    obt2 = 0;
5391                    pkt2 = 0;
5392                    valid = 0;
5393                    MISSING_pkt1 = false;
5394                    MISSING_pkt2 = true;
5395    //              this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5396                    //
5397                };
5398                //
5399    
5400                if( !(MISSING_pkt1&MISSING_pkt2) ){
5401                  this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5402                  ncalib++;
5403                  if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
5404                }
5405    
5406    
5407            } else {
5408              //
5409                if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u OUTSIDE the considered time interval \n",fromtime,obt1,pkt1);
5410                //      if ( PEDANTIC ) throw -79;
5411                //
5412            };
5413            //    
5414    
5415        }; //end loop on pkt1
5416    
5417    
5418    
5419        //
5420        // we have one more calib pkt2 !
5421        //
5422        t2++;
5423        while ( t2 < nevents2 ){
5424          //          //
5425        };          // 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  
5426          //          //
5427          this->HandleTRK_CALIB(true,true);          if ( IsDebug() ) printf(" t2 is %u nevents2 is %u \n",t2,nevents2);
5428            obt1 = 0;
5429            pkt1 = 0;
5430          //          //
5431          // Check for missing calibtrk1          tr2->GetEntry(t2);
5432            ph2 = eh2->GetPscuHeader();
5433            obt2 = ph2->GetOrbitalTime();  
5434            pkt2 = ph2->GetCounter();  
5435          //          //
5436          if ( t2 != pret2+1 ){          fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
5437            //          valid = 0;
5438            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 ){
5439            //          // EMILIANO
5440            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 ){
5441              //              //    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();    
5442              //              //
5443              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);
5444              //              //
5445              valid = 0;              MISSING_pkt1 = true;
5446              this->HandleTRK_CALIB(false,true);              MISSING_pkt2 = false;
5447                this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5448                ncalib++;
5449                if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
5450              //              //
           };  
           //  
5451          };          };
5452          //          //
5453        } 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;  
5454          //          //
5455          // handle missing calib2      };
5456    
5457    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
5458    // -----------------------------------------------------------------
5459    // in case of corruption, check if the calibration can be recovered
5460    // from another chewbacca file
5461    // -----------------------------------------------------------------
5462    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
5463    
5464    //    cout <<" TRY TO RECOVER ?? "<<try_to_recover<<endl;
5465        
5466        if(chewbacca&&try_to_recover){
5467    
5468    
5469            if ( IsDebug() ) cout << endl << ">>>> TRY TO RECOVER TRACKER CALIBRATIONS <<<<"<<endl;
5470    
5471            TSQLResult *rresult = 0; // 10RED bug, result is re-used inside result looop...
5472            TSQLResult *result = 0; // 10RED bug, result is re-used inside result looop...
5473            TSQLRow    *row    = 0;
5474          //          //
5475          obt2 = 0;          stringstream oss;
5476          pkt2 = 0;          oss.str("");
         valid = 0;  
         this->HandleTRK_CALIB(true,false);        
5477          //          //
5478        };  
5479        //          ////////////////////////////////////////////////////////////////////////
5480      } else {          // retrieve the name of the current file:
5481        //          ////////////////////////////////////////////////////////////////////////        
5482        if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u OUTSIDE the considered time interval \n",fromtime,obt1,pkt1);          oss.str("");
5483        //      if ( PEDANTIC ) throw -79;          oss << "SELECT NAME FROM GL_ROOT where ID=" << GetID_ROOT() <<";";
5484        //          if ( IsDebug() ) cout << oss.str().c_str() << endl;
5485      };  
5486      //              result = conn->Query(oss.str().c_str());
5487    };          if ( !result ) throw -4;;
5488    //          row = result->Next();
5489    // we have one more calib pkt2 !          TString thisfilename = (TString)row->GetField(0);
5490    //          if ( IsDebug() ) cout << "Current file ==> "<<thisfilename<<endl;      
5491    t2++;  
5492    while ( t2 < nevents2 ){          ////////////////////////////////////////////////////////////////////////        
5493      //          // read all the calibrations inserted
5494      // handle missing calib1          ////////////////////////////////////////////////////////////////////////        
5495      //          oss.str("");
5496      if ( IsDebug() ) printf(" t2 is %u nevents2 is %u \n",t2,nevents2);          oss << " SELECT ";
5497      obt1 = 0;          oss << " ID,FROM_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,TO_TIME";
5498      pkt1 = 0;          oss << " FROM GL_TRK_CALIB ";
5499      //          oss << " ORDER BY ID DESC LIMIT "<<ncalib<<"; ";        
5500      tr2->GetEntry(t2);          if ( IsDebug() ) cout << oss.str().c_str() << endl;
5501      ph2 = eh2->GetPscuHeader();  
5502      obt2 = ph2->GetOrbitalTime();            rresult = conn->Query(oss.str().c_str());
5503      pkt2 = ph2->GetCounter();            if ( !result ) throw -4;;
5504      //          if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5505      fromtime = this->GetAbsTime(ph2->GetOrbitalTime());          
5506      valid = 0;          // -----------------------------------
5507  //  if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->PKT(pkt1) <= upperpkt && this->OBT(obt1) >= this->OBT(obtfirst) && this->OBT(obt1) <= upperobt ){          // loop over calibrations ...
5508   // EMILIANO          // -----------------------------------
5509      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;
5510        //    if ( this->PKT(pkt2) > this->PKT(pktfirst) || this->OBT(obt2) > this->OBT(obtfirst) ){          do {
5511        //              row = rresult->Next();
5512        if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);              if(!row)break;
5513        //              
5514        this->HandleTRK_CALIB(false,true);              UInt_t id       = (UInt_t)atoll(row->GetField(0));
5515        //              UInt_t fromtime = (UInt_t)atoll(row->GetField(1));
5516      };              UInt_t obt1     = (UInt_t)atoll(row->GetField(2));
5517      //              UInt_t pkt1     = (UInt_t)atoll(row->GetField(3));
5518      t2++;              UInt_t obt2     = (UInt_t)atoll(row->GetField(4));
5519      //              UInt_t pkt2     = (UInt_t)atoll(row->GetField(5));
5520    };              UInt_t boot     = (UInt_t)atoll(row->GetField(6));
5521                UInt_t valid    = (UInt_t)atoll(row->GetField(7));
5522                bool MISSING_pkt1 = (row->GetFieldLength(8)==0);
5523                bool MISSING_pkt2 = (row->GetFieldLength(9)==0);
5524                UInt_t totime   = (UInt_t)atoll(row->GetField(10));
5525    
5526                // -------------------------------------
5527                // ...check if the entry is corrupted...
5528                // -------------------------------------
5529                cout <<"*** "<< MISSING_pkt1 << MISSING_pkt2 << valid <<endl;
5530                bool CORRUPTED = (MISSING_pkt1||MISSING_pkt2||!valid);
5531    
5532                if ( IsDebug() ) cout << "("<<nn<<")  ID = "<<id<<" from GL_TRK_CALIB  ==>  corrupted ? "<<CORRUPTED<<endl;
5533    
5534    //          if( !CORRUPTED  )continue; // nothing to do
5535    
5536                /////////////////////////////////////////////////////////  
5537                // if it is corrupted, ...look for ather chewbacca files
5538                // containing the same calibrations ...
5539                /////////////////////////////////////////////////////////
5540    
5541                bool this_MISSING_pkt1 = false;
5542                bool this_MISSING_pkt2 = false;
5543                int  this_t1=0;
5544                int  this_t2=0;;
5545                UInt_t this_valid = 0;
5546    
5547                TString path       = "";
5548                TString name       = "";
5549                TString raw        = "";
5550                //      UInt_t obt0        = 0;
5551                //      UInt_t timesync    = 0;
5552                //      UInt_t boot_number = 0;
5553                bool   FOUND       = false;
5554    
5555                if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
5556    
5557    //          for(int itable=0; itable<2; itable++){
5558                for(int itable=0; itable<1; itable++){
5559    
5560                    // ------------------------------------------------------
5561                    // loop over both ROOT_TABLE and ROOT_TABLE_BAD
5562                    // ------------------------------------------------------
5563    
5564                    TString table = "ROOT_TABLE";
5565                    if(itable==1)table = "ROOT_TABLE_BAD";
5566    
5567                    oss.str("");
5568                    oss << " SELECT ";
5569                    oss << " FOLDER_NAME,FILE_NAME,OBT_TIME_SYNC,LAST_TIME_SYNC_INFO,BOOT_NUMBER,INPUT_NAME ";
5570                    oss << " FROM "<<table;
5571                    oss << " WHERE 1 " << endl;
5572                    oss << " AND FILE_NAME != \""<< thisfilename<<"\"";
5573                    if( !MISSING_pkt1 ){
5574                        oss << " AND ";
5575                        oss << " PKT_NUMBER_INIT < "<<pkt1;
5576                        oss << " AND ";
5577                        oss << " PKT_NUMBER_FINAL > "<<pkt1;
5578                        oss << " AND ";
5579                        oss << " PKT_OBT_INIT < "<<obt1;
5580                        oss << " AND ";
5581                        oss << " PKT_OBT_FINAL > "<<obt1;
5582                    }else{
5583                        if(pkt2>1) pkt1 = pkt2-1;//serve dopo                  
5584                    }
5585                    if( !MISSING_pkt2 ){
5586                        oss << " AND ";
5587                        oss << " PKT_NUMBER_INIT < "<<pkt2;
5588                        oss << " AND ";
5589                        oss << " PKT_NUMBER_FINAL > "<<pkt2;
5590                        oss << " AND ";
5591                        oss << " PKT_OBT_INIT < "<<obt2;
5592                        oss << " AND ";
5593                        oss << " PKT_OBT_FINAL > "<<obt2;
5594                    }else{
5595                        if(pkt1>0) pkt2 = pkt1+1;//serve dopo
5596                    }
5597                    if( boot> 0 ){
5598                        oss << " AND ";
5599                        oss << " BOOT_NUMBER = "<<boot;
5600                    }else{
5601                    }
5602                    oss << " ORDER BY BAD_PKT_CALREAD ASC; ";
5603                
5604                    TSQLResult *result2 = 0;
5605                    TSQLRow    *row2    = 0;
5606    
5607                    if ( IsDebug() ) cout << oss.str().c_str() << endl;        
5608                    result2 = conn->Query(oss.str().c_str());
5609                    if ( !result2 ) throw -4;;
5610                    if ( IsDebug() ) cout <<"Rows: "<<result2->GetRowCount()<<endl;
5611    
5612                    // ------------------------------------------------------
5613                    // loop over files containing repetition (if any)
5614                    // ------------------------------------------------------
5615                    do {
5616                        row2 = result2->Next();
5617                        if(!row2)break;
5618                    
5619                        // ------------------------------------------------------
5620                        // ... a repetition is found ...
5621                        // ------------------------------------------------------
5622                        path       = (TString)row2->GetField(0);
5623                        name       = (TString)row2->GetField(1);
5624                        raw        = (TString)row2->GetField(5);
5625                        //              obt0        = (UInt_t)atoll(row2->GetField(2));
5626                        //              timesync    = (UInt_t)atoll(row2->GetField(3));
5627                        //              boot_number = (UInt_t)atoll(row2->GetField(4));
5628                    
5629                        if ( IsDebug() ) cout << "- - - - - - - - - - -" <<endl;
5630    //                  cout << path <<endl;
5631    //                  cout << "File    : " <<name <<endl;
5632    //                  cout << obt0 <<endl;
5633    //                  cout << timesync <<endl;
5634    //                  cout << "boot n. : "<<boot_number <<endl;
5635    //                  cout << raw <<endl;
5636    
5637                        // ------------------------------------------------------
5638                        // ... retrieve the calibration packets.
5639                        // ------------------------------------------------------
5640                        if ( IsDebug() ) printf(" file is %s/%s \n",((TString)gSystem->ExpandPathName(path.Data())).Data(),name.Data());
5641                        TFile *file = new TFile(((TString)gSystem->ExpandPathName(path.Data()))+"/"+name); // EM, path could be symbolic and we must expand it
5642                        if(!file)throw -100;
5643                        if(file->IsZombie())throw -100;
5644                        //
5645                        tr1 = (TTree*)file->Get("CalibTrk1");
5646                        if ( !tr1 || tr1->IsZombie() ) throw -22;
5647                        tr2 = (TTree*)file->Get("CalibTrk2");
5648                        if ( !tr2 || tr2->IsZombie() ) throw -23;
5649                        //
5650                        tr1->SetBranchAddress("CalibTrk1", &caltrk1);
5651                        tr1->SetBranchAddress("Header", &eh1);
5652                        nevents1 = tr1->GetEntries();
5653                        tr2->SetBranchAddress("CalibTrk2", &caltrk2);
5654                        tr2->SetBranchAddress("Header", &eh2);
5655                        nevents2 = tr2->GetEntries();
5656                        for(this_t1=0; this_t1<nevents1; this_t1++){
5657                            tr1->GetEntry(this_t1);
5658                            if(
5659                                (UInt_t)eh1->GetPscuHeader()->GetCounter() == pkt1 &&
5660                                true) break;
5661                            this_MISSING_pkt1 = true;
5662                        }
5663                        for(this_t2=0; this_t2<nevents2; this_t2++){
5664                            tr2->GetEntry(this_t2);
5665                            if(
5666                                (UInt_t)eh2->GetPscuHeader()->GetCounter() == pkt2 &&
5667                                true) break;
5668                            this_MISSING_pkt2 = true;
5669                        }
5670                        this_valid =
5671                            ValidateTrkCalib( caltrk1, eh1, file )
5672                            *
5673                            ValidateTrkCalib( caltrk2, eh2, file );
5674                                
5675                        // ---------------------------------------------------------------------
5676                        // accept the calibration if it is better than the previous:
5677                        //
5678                        // - if the new calibration is perfect (both valid packets)
5679                        // - if the new calibration has both the packets and the previous does not
5680                        // ---------------------------------------------------------------------
5681                        if(
5682                            ( !this_MISSING_pkt1&&!this_MISSING_pkt2&&this_valid )||
5683                            ( (MISSING_pkt1||MISSING_pkt2) && (!this_MISSING_pkt1&&!this_MISSING_pkt2) )||
5684                            false)FOUND=true;      
5685                
5686                        if(file)file->Close();
5687    
5688                        if(FOUND)break;
5689    
5690                    }while(1);//endl loop over root table entries
5691                    
5692                    delete result2; // 10RED potential memory leak
5693                    if(FOUND)break;
5694    
5695                }//end loop over tables
5696    
5697                if(FOUND){
5698    
5699                  if ( IsDebug() ) cout << " >>> REPETITION FOUND :-) <<<" <<endl;
5700    
5701                  ////////////////////////////////////////////
5702                  // insert a new entry in GL_TRK_CALIB and
5703                  // modify the time-tag of the previous one
5704                  ////////////////////////////////////////////
5705    
5706                  // ---------------------------------------------------------------------
5707                  // step 1: insert a new raw file in GL_RAW
5708                  // ---------------------------------------------------------------------
5709                  //
5710                  // check if the raw file already exist
5711                  //
5712                  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
5713                  //                oss.str("");
5714                  //                oss << "SELECT ID FROM GL_RAW where NAME=\"" << gSystem->BaseName(raw.Data()) <<"\";";
5715                  //                if ( IsDebug() ) cout << oss.str().c_str() << endl;
5716                    
5717                  //                result = conn->Query(oss.str().c_str());
5718                  //                if ( !result ) throw -4;;
5719                  //                if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5720                  //                if( result->GetRowCount() == 0){
5721                  //                    if ( IsDebug() ) cout << " << Insert new RAW file >> "<<endl;
5722                  //                    // - - - - - - - - - - -
5723                  //                    // insert new raw file
5724                  //                    // - - - - - - - - - - -
5725                  //                    GL_RAW glraw = GL_RAW();    
5726                  //                    glraw.PATH        = gSystem->DirName(raw.Data());
5727                  //                    glraw.NAME        = gSystem->BaseName(raw.Data());
5728                  //                    glraw.BOOT_NUMBER = boot_number;
5729                  //                    //
5730                  //                    insertPamelaRawFile( &glraw );
5731                  //                    //              
5732                  //                    id_raw = glraw.ID;              
5733                  //                }else{
5734                  //                    row = result->Next();
5735                  //                    id_raw = (UInt_t)atoll(row->GetField(0));
5736                  //                }
5737                  //                if ( IsDebug() ) cout << "ID_RAW = "<<id_raw<<endl;
5738    
5739                  // ---------------------------------------------------------------------
5740                  // step 1(bis): retrieve the timesync id associated to the file
5741                  // (NB, uso lo stesso associato al file iniziale)
5742                  // ---------------------------------------------------------------------
5743                  UInt_t idtimesync = 0;
5744                  oss.str("");
5745                  oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" limit 1;";
5746                  if ( debug ) printf(" %s \n",oss.str().c_str());
5747                  result = conn->Query(oss.str().c_str());
5748                  if ( !result ) throw -3;
5749                    row = result->Next();
5750                    if ( !row ) throw -3;
5751                    idtimesync = (UInt_t)atoll(row->GetField(0));
5752                    if ( IsDebug() ) cout << "ID_TIMESYNC = "<<idtimesync<<endl;
5753                    
5754                    delete result;// mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
5755                    // ---------------------------------------------------------------------
5756                    // step 2: insert a new root file in GL_ROOT
5757                    // ---------------------------------------------------------------------
5758                    //
5759                    // check if the root file already exist
5760                    //
5761                    UInt_t id_root = 0;
5762                    oss.str("");
5763                    oss << "SELECT ID FROM GL_ROOT where NAME=\"" << gSystem->BaseName(name.Data()) <<"\";";
5764                    if ( IsDebug() ) cout << oss.str().c_str() << endl;
5765                    
5766                    result = conn->Query(oss.str().c_str());
5767                    if ( !result ) throw -4;;
5768                    if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5769                    if( result->GetRowCount() == 0){
5770                        if ( IsDebug() ) cout << " << Insert new ROOT file >> "<<endl;
5771                        // - - - - - - - - - - -
5772                        // insert new root file
5773                        // - - - - - - - - - - -
5774                        GL_ROOT glroot = GL_ROOT();            
5775                        glroot.ID_RAW      = id_raw;
5776                        glroot.ID_TIMESYNC = idtimesync;
5777                        //
5778                        // 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,
5779                        //             NOT STATIC NOT KEEPENV = $PAM_L0 must be used in the DB
5780                        //
5781                        if ( STATIC ){
5782                          glroot.PATH        = (TString)gSystem->ExpandPathName(path);
5783                        } else {
5784                          if ( KEEPENV ){
5785                            glroot.PATH      = path;
5786                          } else {
5787                            glroot.PATH      = "$PAM_L0";
5788                          };
5789                        };
5790                        //              glroot.PATH        = path;
5791                        glroot.NAME        = name;
5792                        //
5793                        insertPamelaRootFile( &glroot );
5794                        //              
5795                        id_root = glroot.ID;                    
5796                    }else{
5797                        row = result->Next();
5798                        if(row)id_root = (UInt_t)atoll(row->GetField(0));
5799                    }
5800                    if ( IsDebug() ) cout << "ID_ROOT = "<<id_root<<endl;
5801    
5802                    delete result;// mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
5803                    // ---------------------------------------------------------------------
5804                    // step 3: modify time-tag of corrupted GL_TRK_CALIB entry
5805                    // ---------------------------------------------------------------------
5806                    if ( IsDebug() ) cout << " << Modify time-tag of calibration ID="<<id<<" >> "<<endl;
5807                    oss.str("");
5808                    oss << " UPDATE GL_TRK_CALIB SET "  
5809                        << " TO_TIME=0 , FROM_TIME=0  WHERE "
5810                        << " ID = "<< id  << ";";
5811                    if ( IsDebug() ) cout << oss.str().c_str() << endl;
5812                    result = conn->Query(oss.str().c_str());
5813                    if ( !result ) throw -4;;
5814    
5815                    delete result; // mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
5816    
5817                    // ---------------------------------------------------------------------
5818                    // step 4: insert the new calibration:
5819                    // ---------------------------------------------------------------------
5820                    if ( IsDebug() ) cout << " << Insert new TRK calibration >> "<<endl;
5821                    //
5822                    GL_TRK_CALIB glcal = GL_TRK_CALIB();        
5823                    //
5824                    glcal.ID_ROOT_L0        = id_root;
5825                    glcal.EV_ROOT_CALIBTRK1 = this_t1;
5826                    glcal.EV_ROOT_CALIBTRK2 = this_t2;
5827                    glcal.FROM_TIME         = fromtime;
5828                    glcal.TO_TIME           = totime;
5829                    glcal.OBT1              = obt1;
5830                    glcal.OBT2              = obt2;
5831                    glcal.PKT1              = pkt1;
5832                    glcal.PKT2              = pkt1;
5833                    glcal.BOOT_NUMBER       = GetBOOTnumber();
5834                    glcal.VALIDATION        = this_valid;
5835                    //
5836                    HandleTRK_CALIB(&glcal);
5837                    if ( IsDebug() ) cout << "ID = "<<glcal.ID<<endl;
5838                    //
5839                    
5840                }
5841                if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
5842    
5843            }while(1);//end loop over calibrations
5844            
5845            
5846            if( rresult )delete rresult; // 10RED bug
5847            if( row    )delete row;
5848            
5849            
5850    
5851            
5852    
5853    
5854        }
5855    
5856    
5857    //      // ------------------------------
5858    //      // try to recover the calibration
5859    //      // ------------------------------
5860    //      cout << "TRY TO RECOVER TRACKER CALIBRATION"<<endl;
5861    //      //
5862    //      ULong64_t time  = 0; //absolute time
5863    //      string    path[100]; //mettere un limite massimo
5864    //      int       nrows = 0;
5865    //      UInt_t    pkt   = 0;
5866    //      UInt_t    obt   = 0;
5867    //      char     *type  = "";
5868    //      EventHeader *eh   = new EventHeader();
5869    //      CalibTrk1Event *c = new CalibTrk1Event();
5870            
5871    //       //
5872    //       if(which_is_not_valid==1 || which_is_not_valid==3){
5873    //        //
5874    //        cout << "PKT1 --> missing or corrupted "<<endl;
5875    //        type = "CalibTrk1";
5876    //        pkt  = pkt1;
5877    //        obt  = obt1;
5878    //        time = this->GetAbsTime(obt1);
5879    //        if( pkt1 == 0 ){//missing
5880    //            time = this->GetAbsTime(obt2);
5881    //            pkt  = pkt2-1;          
5882    //        }
5883    //        //
5884    //       }else if (which_is_not_valid==2 || which_is_not_valid==3){
5885    //        //
5886    //        cout << "PKT2--> missing or corrupted "<<endl;
5887    //        type = "CalibTrk2 ";
5888    //        pkt  = pkt2;
5889    //        obt  = obt2;
5890    //        time = this->GetAbsTime(obt2);
5891    //        if( pkt2 == 0 ){//missing
5892    //            time = this->GetAbsTime(obt1);
5893    //            pkt  = pkt1+1;          
5894    //        }
5895    //        //
5896    //       }else{
5897    //        cout << "this should not happen!!! "<<endl;
5898    //        trow -666;
5899    //       }
5900          
5901    //       nrows = Query_ROOT_TABLE(time,conn,path);// get the list of file which might contain the packet
5902          
5903    
5904    //       for(int r=0; r<nrows; r++){ //loop over rows
5905    //        if(path)cout << r << " >>>> "<<(path+r)->c_str() << endl;
5906    //        /// verifica che il file non sia quello gia` aperto
5907    //       }
5908    
5909    //       ////////////////////////////////////////////////////////////////////////
5910    
5911    //       TSQLResult *result = 0;
5912    //       TSQLRow    *row    = 0;
5913    //       //
5914    //       stringstream oss;
5915    //       oss.str("");
5916    //       // ----------------------------------------
5917    //       // read the id of last calibration inserted
5918    //       // ----------------------------------------
5919    //       oss.str("");
5920    //       oss << " SELECT ";
5921    //       oss << " (ID,ID_ROOT_L0,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,FROM_TIME,TO_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION) ";
5922    //       oss << " ORDER BY ID DESC LIMIT 1; ";
5923          
5924    //       result = conn->Query(oss.str().c_str());
5925    //       row = result->Next();
5926    //       if( !row )throw -666;
5927    
5928    //       if( result )delete result;
5929    //       if( row    )delete row;
5930    
5931    //       UInt_t id = (UInt_t)atoll(row->GetField(0));
5932    
5933    //       // -------------------------------------
5934    //       // ...and modify it with new parameters
5935    //       // -------------------------------------
5936          
5937    
5938    //   }
5939    //    //
5940    return(0);    return(0);
5941  };  };
# Line 4967  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6144  Int_t PamelaDBOperations::CleanGL_RUN_FR
6144      memset(myid,0,500*sizeof(UInt_t));      memset(myid,0,500*sizeof(UInt_t));
6145      //      //
6146      oss.str("");      oss.str("");
6147      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;";
6148      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());
6149      nresult = conn->Query(oss.str().c_str());      nresult = conn->Query(oss.str().c_str());
6150      //      //
# Line 4998  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6175  Int_t PamelaDBOperations::CleanGL_RUN_FR
6175            while ( anr ){            while ( anr ){
6176              //              //
6177              oss.str("");              oss.str("");
6178              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
6179              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());
6180              //              //
6181              nresult1 = conn->Query(oss.str().c_str());              nresult1 = conn->Query(oss.str().c_str());
# Line 5061  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6238  Int_t PamelaDBOperations::CleanGL_RUN_FR
6238                    << " RM_ACQ_SETTING_MODE=" << glrun->GetRM_ACQ_SETTING_MODE()<< " , "                      << " RM_ACQ_SETTING_MODE=" << glrun->GetRM_ACQ_SETTING_MODE()<< " , "  
6239                    << " TRK_CALIB_USED=" << glrun->GetTRK_CALIB_USED()<< " , "                      << " TRK_CALIB_USED=" << glrun->GetTRK_CALIB_USED()<< " , "  
6240                    << " CAL_DSP_MASK=" << glrun->GetCAL_DSP_MASK()<< " , "                      << " CAL_DSP_MASK=" << glrun->GetCAL_DSP_MASK()<< " , "  
6241                    << " LAST_TIMESYNC=" << glrun->GetLAST_TIMESYNC()<< " , "                      << " LAST_TIMESYNC=" << glrun->GetLAST_TIMESYNC()<< " , ";
6242                    << " OBT_TIMESYNC=" << glrun->GetOBT_TIMESYNC()                //
6243                    << " WHERE ID=" << myid[u] << ";";                if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
6244                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12() << " , ";
6245                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
6246                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC() << " , ";
6247                  //              
6248                  oss << " OBT_TIMESYNC=" << glrun->GetOBT_TIMESYNC();
6249                  oss << " WHERE ID=" << myid[u] << ";";
6250                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
6251              };              };
6252              //              //
# Line 5074  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6257  Int_t PamelaDBOperations::CleanGL_RUN_FR
6257              for (UInt_t u=1; u <= nid ; u++){              for (UInt_t u=1; u <= nid ; u++){
6258                oss.str("");                oss.str("");
6259                oss << "UPDATE GL_RUN_FRAGMENTS SET "                oss << "UPDATE GL_RUN_FRAGMENTS SET "
6260                    << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , "                    << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , ";
6261                    << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "                //
6262                    << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT()<< ";";                if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
6263                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , ";
6264                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
6265                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , ";
6266                  //              
6267                  oss << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "
6268                      << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT();
6269                  oss << " WHERE ID=" << myid[u] << ";"; // BUG!!! 090112
6270                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
6271              };                  };    
6272            };            };
# Line 5098  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6288  Int_t PamelaDBOperations::CleanGL_RUN_FR
6288                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
6289                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "
6290                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< " , "                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< " , "
6291                    << " PKT_COUNTER=" << glrun->GetPKT_COUNTER()<< " , "                    << " PKT_COUNTER=" << glrun->GetPKT_COUNTER()<< " , ";
6292                    << " PKT_READY_COUNTER=" << glrun->GetPKT_READY_COUNTER()                //
6293                  if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
6294                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
6295                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) {
6296                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
6297                  //              
6298                  oss << " PKT_READY_COUNTER=" << glrun->GetPKT_READY_COUNTER()
6299                    << " WHERE ID=" << myid[u] << ";";                    << " WHERE ID=" << myid[u] << ";";
6300                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
6301              };              };
# Line 5112  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6308  Int_t PamelaDBOperations::CleanGL_RUN_FR
6308                oss.str("");                oss.str("");
6309                oss << "UPDATE GL_RUN_FRAGMENTS SET "                oss << "UPDATE GL_RUN_FRAGMENTS SET "
6310                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
6311                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , ";
6312                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< ";";                //
6313                  if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
6314                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
6315                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ){
6316                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
6317                  //              
6318                  oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT();
6319                  oss << " WHERE ID=" << myid[u] << ";"; // BUG!!! 090112
6320                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
6321              };                  };    
6322            };            };
# Line 5164  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6367  Int_t PamelaDBOperations::CleanGL_RUN_FR
6367                row2 = result2->Next();                row2 = result2->Next();
6368                //                //
6369                if ( row2 ){                if ( row2 ){
6370                  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");
6371                  if ( PEDANTIC ) throw -83;                  if ( PEDANTIC ) throw -83;
6372                  row2->Close();                  row2->Close();
6373                };                };
# Line 5241  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6444  Int_t PamelaDBOperations::CleanGL_RUN_FR
6444        glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);          glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);  
6445        //        //
6446        oss.str("");        oss.str("");
6447        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 "
6448            << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND ("            << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND ("
6449            << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "            << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
6450            << " 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 6475  Int_t PamelaDBOperations::CleanGL_RUN_FR
6475          glrun->SetID_RUN_FRAG(glrun->GetID());          glrun->SetID_RUN_FRAG(glrun->GetID());
6476          glrun->Fill_GL_RUN(conn);            glrun->Fill_GL_RUN(conn);  
6477          //          //
6478  //      oss.str("");          //      oss.str("");
6479  //      oss << " SELECT ID FROM GL_RUN WHERE "          //      oss << " SELECT ID FROM GL_RUN WHERE "
6480  //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "          //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
6481  //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "          //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
6482  //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "          //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
6483  //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "          //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
6484  //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";          //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
6485  //      //          //      //
6486  //      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());
6487  //      result2 = conn->Query(oss.str().c_str());          //      result2 = conn->Query(oss.str().c_str());
6488  //      //          //      //
6489  //      if ( !result2 ) throw -4;          //      if ( !result2 ) throw -4;
6490  //      //          //      //
6491  //      row2 = result2->Next();          //      row2 = result2->Next();
6492  //      //          //      //
6493  //      if ( !row2 ) throw -25;          //      if ( !row2 ) throw -25;
6494  //      //          //      //
6495  //      oss.str("");          //      oss.str("");
6496  //      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);
6497  //      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());
6498  //      result2 = conn->Query(oss.str().c_str());          //      result2 = conn->Query(oss.str().c_str());
6499  //      //          //      //
6500  //      if ( !result2 ) throw -4;          //      if ( !result2 ) throw -4;
6501          //          //
6502          moved++;          moved++;
6503          //          //
6504        } else {        } else {
6505          if ( IsDebug() ) printf(" The already exist in the GL_RUN table! \n");  
6506          if ( PEDANTIC ) throw -83;          // questa parte mah mah mah... da controllare
6507    
6508            //
6509            // 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
6510            // "small gap" piece... we recognize this since: we have two entries from this query, the pkt number is consistent with our pkt number.
6511            //
6512            // 090112 [8RED (-70): RUN ALREADY INSERTED]
6513            //
6514            Bool_t OK = false;
6515            UInt_t IDRL2A = 0;
6516            UInt_t IDRL2B = 0;
6517              if ( result2->GetRowCount() == 2 ){
6518                IDRL2A = (UInt_t)atoll(row2->GetField(0));
6519                UInt_t IDRL0A = (UInt_t)atoll(row2->GetField(4));
6520                row2 = result2->Next();
6521                IDRL2B = (UInt_t)atoll(row2->GetField(0));
6522                UInt_t IDRL0B = (UInt_t)atoll(row2->GetField(4));
6523                if ( IsDebug() ) printf(" IDRL0A %u B %u IDRL2A %u B %u \n",IDRL0A,IDRL0B,IDRL2A,IDRL2B);
6524                //      if ( IDRL0A == IDRL0B ){
6525    //            TSQLResult *result2a = 0;
6526    //            TSQLRow    *row2a    = 0;
6527    //            oss.str("");
6528    //            oss << "select PKT_NUMBER_FINAL from ROOT_TABLE_MERGING where REAL_TIME_INIT<" << chrtinit << " order by REAL_TIME_INIT desc limit 1;";
6529    //            if ( IsDebug() ) printf(" Check if we are in the case RH---| small gap |---RT: query is \n %s \n",oss.str().c_str());
6530    //            result2a = conn->Query(oss.str().c_str());
6531    //            //
6532    //            if ( !result2a ) throw -4;
6533    //            //
6534    //            row2a = result2a->Next();
6535    //            //
6536    //            if ( row2a ){
6537    //              UInt_t PKA = (UInt_t)atoll(row2a->GetField(0));
6538    //              delete result2a;
6539    //              oss.str("");
6540    //              oss << "select PKT_NUMBER_INIT from ROOT_TABLE_MERGING where REAL_TIME_INIT>" << chrtinit << " order by REAL_TIME_INIT asc limit 1;";
6541    //              if ( IsDebug() ) printf(" Check if we are in the case RH---| small gap |---RT: query is \n %s \n",oss.str().c_str());
6542    //              result2a = conn->Query(oss.str().c_str());
6543    //              //
6544    //              if ( !result2a ) throw -4;
6545    //              //
6546    //              row2a = result2a->Next();
6547    //              //
6548    //              if ( row2a ){
6549    //                UInt_t PKB = (UInt_t)atoll(row2a->GetField(0));
6550    //                //
6551    //                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);
6552    //                if ( PKT(PKA)+1LL == PKT(glrun->GetRUNHEADER_PKT()) && PKT(PKB) == PKT(glrun->GetRUNTRAILER_PKT())+1LL ){
6553    //                  if ( IsDebug() ) printf(" Ok, we are in the case: RH---| small gap |---RT \n");
6554                        OK = true;
6555                        //            };
6556                        //          };
6557                        //        };                  
6558                        //    };
6559              };      
6560            if ( OK ){
6561              //
6562              // this is the case in which we must insert a piece of run between two fragments in the GL_RUN table
6563              //
6564              // 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 )
6565              //
6566              GL_RUN *glA = new GL_RUN();
6567              glA->Query_GL_RUN(IDRL2A,conn);
6568              //
6569              if ( glA->GetACQ_BUILD_INFO() != 0 ){
6570                //
6571                // the first piece contains a good runheader we can update all the other runs with correct infos!
6572                //
6573                oss.str("");
6574                oss << "UPDATE GL_RUN_FRAGMENTS SET "
6575                    << " RUNHEADER_TIME=" << glA->GetRUNHEADER_TIME()<< " , "
6576                    << " RUNHEADER_OBT=" << glA->GetRUNHEADER_OBT()<< " , "
6577                    << " RUNHEADER_PKT=" << glA->GetRUNHEADER_PKT()<< " , "
6578                    << " COMPILATIONTIMESTAMP=" << glA->GetCOMPILATIONTIMESTAMP()<< " , "
6579                    << " FAV_WRK_SCHEDULE=" << glA->GetFAV_WRK_SCHEDULE()<< " , "
6580                    << " EFF_WRK_SCHEDULE=" << glA->GetEFF_WRK_SCHEDULE()<< " , "
6581                    << " PRH_VAR_TRG_MODE_A=" << glA->GetPRH_VAR_TRG_MODE_A()<< " , "
6582                    << " PRH_VAR_TRG_MODE_B=" << glA->GetPRH_VAR_TRG_MODE_B()<< " , "
6583                    << " ACQ_BUILD_INFO=" << glA->GetACQ_BUILD_INFO()<< " , "
6584                    << " ACQ_VAR_INFO=" << glA->GetACQ_VAR_INFO()<< " , "
6585                    << " RM_ACQ_AFTER_CALIB=" << glA->GetRM_ACQ_AFTER_CALIB()<< " , "  
6586                    << " RM_ACQ_SETTING_MODE=" << glA->GetRM_ACQ_SETTING_MODE()<< " , "  
6587                    << " TRK_CALIB_USED=" << glA->GetTRK_CALIB_USED()<< " , "  
6588                    << " CAL_DSP_MASK=" << glA->GetCAL_DSP_MASK()<< " , "  
6589                    << " LAST_TIMESYNC=" << glA->GetLAST_TIMESYNC()<< " , ";
6590                //
6591                if ( glA->GetPHYSENDRUN_MASK_S3S2S12() )
6592                  oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12() << " , ";
6593                if ( glA->GetPHYSENDRUN_MASK_S11CRC() )
6594                  oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC() << " , ";
6595                //        
6596                oss << " OBT_TIMESYNC=" << glA->GetOBT_TIMESYNC();
6597                oss << " WHERE ID=" << glrun->GetID() << ";";
6598                if ( IsDebug() ) printf(" update with correct infos: %s\n",oss.str().c_str());
6599                conn->Query(oss.str().c_str());    
6600                //
6601              } else {
6602                //
6603                // sig no runheader, let set anyway what is possible...
6604                //
6605                oss.str("");
6606                oss << "UPDATE GL_RUN_FRAGMENTS SET "
6607                    << " RUNHEADER_TIME=" << glA->GetRUNHEADER_TIME()<< " , ";
6608                //
6609                if ( glA->GetPHYSENDRUN_MASK_S3S2S12() )
6610                  oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , ";
6611                if ( glA->GetPHYSENDRUN_MASK_S11CRC() )
6612                  oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , ";
6613                //        
6614                oss << " RUNHEADER_OBT=" << glA->GetRUNHEADER_OBT()<< " , "
6615                    << " RUNHEADER_PKT=" << glA->GetRUNHEADER_PKT();
6616                oss << " WHERE ID=" << glrun->GetID() << ";";
6617                if ( IsDebug() ) printf(" update with correct infos2: %s\n",oss.str().c_str());
6618                conn->Query(oss.str().c_str());    
6619              };
6620              //
6621              // update runheader ROOT_ID_FRAG
6622              //
6623              oss.str("");
6624              oss << "UPDATE GL_RUN SET ID_RUN_FRAG = " << glrun->GetID() << " where ID = " << IDRL2A << ";";
6625              if ( IsDebug() ) printf(" update gl_run to have cross indexing: %s\n",oss.str().c_str());
6626              conn->Query(oss.str().c_str());
6627              //
6628              // now let's look for runtrailer if any in the last run
6629              //
6630              glA->Query_GL_RUN(IDRL2B,conn);
6631              //
6632              if ( glA->GetPKT_READY_COUNTER() != 0 ){
6633                //
6634                // the first piece contains a good runtrailer we can update all the other runs with correct infos!
6635                //
6636                oss.str("");
6637                oss << "UPDATE GL_RUN_FRAGMENTS SET "
6638                    << " RUNTRAILER_TIME=" << glA->GetRUNTRAILER_TIME()<< " , "
6639                    << " RUNTRAILER_OBT=" << glA->GetRUNTRAILER_OBT()<< " , "
6640                    << " RUNTRAILER_PKT=" << glA->GetRUNTRAILER_PKT()<< " , "
6641                    << " PKT_COUNTER=" << glA->GetPKT_COUNTER()<< " , ";
6642                //
6643                if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ){
6644                  oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
6645                if ( glA->GetPHYSENDRUN_MASK_S11CRC() ) {
6646                  oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
6647                //        
6648                oss << " PKT_READY_COUNTER=" << glA->GetPKT_READY_COUNTER()
6649                    << " WHERE ID=" << glrun->GetID() << ";";
6650                if ( IsDebug() ) printf(" update with correct trailer infos: %s\n",oss.str().c_str());
6651                conn->Query(oss.str().c_str());    
6652                //
6653              } else {
6654                //
6655                // sig no runtrailer, let set anyway what is possible...
6656                //
6657                oss.str("");
6658                oss << "UPDATE GL_RUN_FRAGMENTS SET "
6659                    << " RUNTRAILER_TIME=" << glA->GetRUNTRAILER_TIME()<< " , "
6660                    << " RUNTRAILER_OBT=" << glA->GetRUNTRAILER_OBT()<< " , ";
6661                  //
6662                if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ){
6663                  oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
6664                if ( glA->GetPHYSENDRUN_MASK_S11CRC() ){
6665                  oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
6666                //        
6667                oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()
6668                    << " WHERE ID=" << glrun->GetID() << ";";
6669                if ( IsDebug() ) printf(" update with correct trailer infos2: %s\n",oss.str().c_str());
6670                conn->Query(oss.str().c_str());    
6671              };
6672              //
6673              UInt_t myi = glrun->GetID();
6674              oss.str("");
6675              oss << " ID= "<< myi;
6676              //
6677              glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);  
6678              //
6679              // fill the new run in GL_RUN
6680              //
6681              glrun->SetID_RUN_FRAG(IDRL2B);
6682              glrun->Fill_GL_RUN(conn);    
6683              glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
6684              delete glA;
6685              moved++;
6686              //
6687            } else {
6688              //
6689              // is just a repetition
6690              //
6691              if ( IsDebug() ) printf(" The run %u is already present in the GL_RUN table...\n",glrun->GetID());    
6692              //      printf(" CCCCCCCCICCCCCCCCCCCCIOOOOOOOOOO si muove Ciccio! %u \n",glrun->GetID());
6693              //      if ( PEDANTIC && glrun->GetID() != 61563 ) throw -83;
6694              if ( PEDANTIC ) throw -83;
6695            };
6696            //      if ( IsDebug() ) printf(" The run already exists in the GL_RUN table! ...\n");
6697            //      if ( PEDANTIC ) throw -83;
6698        };        };
6699        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));      
6700        //        //
6701        //        //
6702        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
6703  //      oss.str("");        //      oss.str("");
6704  //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);        //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);
6705  //       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());
6706  //       result2 = conn->Query(oss.str().c_str());        //       result2 = conn->Query(oss.str().c_str());
6707  //      //        //      //
6708  //      if ( !result2 ) throw -4;        //      if ( !result2 ) throw -4;
6709  //      //        //      //
6710        row = result->Next();        row = result->Next();
6711      };      };
6712    };    };
# Line 5366  Int_t PamelaDBOperations::ValidateRuns(T Line 6760  Int_t PamelaDBOperations::ValidateRuns(T
6760      // 2) get the OBT of the last validated run      // 2) get the OBT of the last validated run
6761      // --------------------------------------------------------------      // --------------------------------------------------------------
6762      oss.str("");      oss.str("");
6763      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
6764        oss << " SELECT * FROM GL_RUN  WHERE VALIDATION>0 AND RUNHEADER_TIME<="<< t_start
6765          <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";          <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
6766      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());
6767      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
# Line 5457  Int_t PamelaDBOperations::ValidateRuns(T Line 6852  Int_t PamelaDBOperations::ValidateRuns(T
6852    GL_RUN* this_run = new GL_RUN();    GL_RUN* this_run = new GL_RUN();
6853    GL_RUN* next_run = new GL_RUN();    GL_RUN* next_run = new GL_RUN();
6854    Int_t   nseq_max = 1000;    Int_t   nseq_max = 1000;
6855  //  UInt_t* sequence = new UInt_t[100];    //  UInt_t* sequence = new UInt_t[100];
6856    vector<UInt_t> sequence(nseq_max);    vector<UInt_t> sequence(nseq_max);
6857    Int_t   nseq = 0;    Int_t   nseq = 0;
6858    Bool_t CHECK = false;    Bool_t CHECK = false;
# Line 5472  Int_t PamelaDBOperations::ValidateRuns(T Line 6867  Int_t PamelaDBOperations::ValidateRuns(T
6867    // ---------------------------------------------------------------------------------    // ---------------------------------------------------------------------------------
6868    while(1){    while(1){
6869                        
6870            row = result->Next();      row = result->Next();
6871            if( row == NULL ) break;      if( row == NULL ) break;
6872                        
6873            //------------      //------------
6874            //get run info      //get run info
6875            //------------      //------------
6876            this_run->Set_GL_RUN(row);      this_run->Set_GL_RUN(row);
6877                                        
6878            Bool_t this_BAD = false;      Bool_t this_BAD = false;
6879            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;
6880            else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;      else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;
6881            else{      else{
6882  //                printf("Missing or corrupted header!! \n");        //                  printf("Missing or corrupted header!! \n");
6883                    this_ONLINE = false;        this_ONLINE = false;
6884                    this_BAD = true;        this_BAD = true;
6885            };      };
6886    
6887            //-----------------------------------      //-----------------------------------
6888            //compare with previous(next in time)      //compare with previous(next in time)
6889            //-----------------------------------      //-----------------------------------
6890            CHECK = false;      CHECK = false;
6891            UInt_t interval=0;      UInt_t interval=0;
6892                        
6893            if( nrow != 0){      if( nrow != 0){
6894                    
6895                                        
6896                    t1 = this_run->GetRUNTRAILER_TIME();        t1 = this_run->GetRUNTRAILER_TIME();
6897                    t2 = next_run->GetRUNHEADER_TIME();        t2 = next_run->GetRUNHEADER_TIME();
6898                    interval = (t2-t1);        interval = (t2-t1);
6899                                        
6900                    if(this_ONLINE && next_ONLINE){                               // this: ON-LINE + next: ON-LINE        if(this_ONLINE && next_ONLINE){                           // this: ON-LINE + next: ON-LINE
6901                                                        
6902                            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
6903                                                        
6904                            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
6905                                                        
6906                            if( !CHECK && this_run->VALIDATION ){          if( !CHECK && this_run->VALIDATION ){
6907                                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);            //      for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
6908                                    nseq=0;            for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],this_run->VALIDATION);
6909                            }            nseq=0;
6910            }
6911                                        
6912                    }else if( !this_ONLINE && next_ONLINE) {              // this: DEFAULT + next:ON-LINE        }else if( !this_ONLINE && next_ONLINE) {          // this: DEFAULT + next:ON-LINE
6913                                                        
6914                            CHECK = true;          CHECK = true;
6915    
6916                    }else if( !next_ONLINE ){                                             // this:ANY + next:DEFAULT        }else if( !next_ONLINE ){                                         // this:ANY + next:DEFAULT
6917                                                        
6918                            assignVALIDATION(next_run->ID,true);          assignVALIDATION(next_run->ID,true);
6919                            nseq=0;          nseq=0;
6920                    }        }
6921            }      }
6922    
6923            //----------------------------      //----------------------------
6924            //check run sequence for calib      //check run sequence for calib
6925            //----------------------------      //----------------------------
6926            if( CHECK ){      if( CHECK ){
6927                    // check if calibration exists        // check if calibration exists
6928                    if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);        if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);
6929                    Bool_t MISSING = MissingTRK_CALIB(t1,t2);        //      Bool_t MISSING = MissingTRK_CALIB(t1,t2);
6930                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],!MISSING);        UInt_t MISSING = MissingTRK_CALIB(t1,t2);
6931                    nseq=0;        UInt_t val = 0;
6932            };        if ( MISSING == 1 ) val = 0;
6933            //--------------        if ( MISSING == 0 ) val = 1;
6934            //store run info        if ( MISSING == 2 ) val = 2;
6935            //--------------        for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],val);
6936            *next_run   = *this_run;        nseq=0;
6937            next_ONLINE = this_ONLINE;      };
6938            if( !this_BAD ){      //--------------
6939                    if(nseq < nseq_max){      //store run info
6940                            sequence[nseq] = this_run->ID;      //--------------
6941                            nseq++;      *next_run   = *this_run;
6942                    }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);      next_ONLINE = this_ONLINE;
6943            };      if( !this_BAD ){
6944          if(nseq < nseq_max){
6945            sequence[nseq] = this_run->ID;
6946            nseq++;
6947          }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);
6948        };
6949                        
6950            if ( IsDebug() ) printf("%i Run %u \n",nrow,this_run->ID);      if ( IsDebug() ) printf("%i Run %u \n",nrow,this_run->ID);
6951            nrow++;      nrow++;
6952                        
6953    };    };
6954    delete this_run;    delete this_run;
# Line 5561  Int_t PamelaDBOperations::ValidateRuns(T Line 6962  Int_t PamelaDBOperations::ValidateRuns(T
6962   * @param t2 To absolute time   * @param t2 To absolute time
6963   * @return true if there might be a missing calibration   * @return true if there might be a missing calibration
6964   */   */
6965  Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){  //Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
6966    UInt_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
6967                    
6968          GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();    GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();
6969                    
6970          // get the closest VALIDATED calibration before the run start (t2)    // get the closest calibration before the run start (t2)
6971          if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true);      //>>> missing    //  if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true);        //>>> missing
6972      if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(1);       //>>> missing
6973                    
6974          if ( trkcalib->TO_TIME  < t2 ) return(true);                                    //>>> missing    //  if ( trkcalib->TO_TIME  < t2 ) return(true);                                      //>>> missing
6975      if ( trkcalib->TO_TIME  < t2 ) return(1);                                     //>>> missing
6976                    
6977          //==============================================================    //==============================================================
6978          // Check is done first on the basis of time between calibration,    // Check is done first on the basis of time between calibration,
6979          // which should be equal to the time between ascending-nodes.    // which should be equal to the time between ascending-nodes.
6980          //==============================================================    //==============================================================
6981          if ( t2 - trkcalib->FROM_TIME > 5700) {    if ( t2 - trkcalib->FROM_TIME > 5700) {
6982                  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);
6983          //==============================================================      //==============================================================
6984          // there might be a missing calibration, due to:      // there might be a missing calibration, due to:
6985          // - MM full      // - MM full
6986          // - corrupted packets      // - corrupted packets
6987          // - loss of data      // - loss of data
6988          // 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
6989          //==============================================================      //==============================================================
6990                  Bool_t DOWNLOAD = false;      Bool_t DOWNLOAD = false;
6991                  // check if the calib was skipped becouse of download .... DA FARE!!      // check if the calib was skipped becouse of download .... DA FARE!!
6992                  if(DOWNLOAD)return(false);      //    if(DOWNLOAD)return(false);
6993        if(DOWNLOAD)return(0);
6994                                    
6995                  return(true);                                   //>>> missing      //    return(true);                                         //>>> missing
6996        return(1);                                  //>>> missing
6997                                    
6998          };    };
6999                    
7000          //==============================================================    //==============================================================
7001          // 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,
7002          // it is enough to say that there are no missing calibrations    // it is enough to say that there are no missing calibrations
7003          //==============================================================    //==============================================================
7004          // the long time interval bewteen runs might be due to download    // the long time interval bewteen runs might be due to download
7005          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);
7006          return(false);    if ( trkcalib->VALIDATION ) return(0);
7007      if ( IsDebug() )printf("Calibration is not validated... :-/ ==> OK but with VALIDATION=2! \n");
7008      return(2);
7009                    
7010  };  };
7011  /**  /**
# Line 5606  Bool_t PamelaDBOperations::MissingTRK_CA Line 7014  Bool_t PamelaDBOperations::MissingTRK_CA
7014   * @param validation true/false   * @param validation true/false
7015   */   */
7016  Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){  Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){
7017          TSQLResult *result = 0;    return(this->assignVALIDATION(idrun,(UInt_t)validation));
7018          stringstream oss;  }
7019          oss.str("");  
7020          oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";  Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, UInt_t validation){
7021          //    TSQLResult *result = 0;
7022  //      if ( IsDebug() )    stringstream oss;
7023  //      printf(" Set VALIDATION = %i for run %i \n",validation,idrun);    oss.str("");
7024          if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());    oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";
7025          result = conn->Query(oss.str().c_str());    //
7026          if ( !result ) throw -4;    //    if ( IsDebug() )
7027          return(0);    //    printf(" Set VALIDATION = %i for run %i \n",validation,idrun);
7028      if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());
7029      result = conn->Query(oss.str().c_str());
7030      if ( !result ) throw -4;
7031      return(0);
7032  }  }
7033    
7034    
# Line 5802  Int_t PamelaDBOperations::removeFile(TSt Line 7214  Int_t PamelaDBOperations::removeFile(TSt
7214    stringstream myquery;    stringstream myquery;
7215    //      //  
7216    myquery.str("");    myquery.str("");
7217    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() <<"';";
7218    //    //
7219    pResult = conn->Query(myquery.str().c_str());    pResult = conn->Query(myquery.str().c_str());
7220    //    //
# Line 5818  Int_t PamelaDBOperations::removeFile(TSt Line 7230  Int_t PamelaDBOperations::removeFile(TSt
7230    //    //
7231    this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));    this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));
7232    this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));    this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));
7233      UInt_t idtsy=(UInt_t)atoll(Row->GetField(2));
7234    //    //
7235    this->ValidationOFF();    this->ValidationOFF();
7236    //    //
# Line 5825  Int_t PamelaDBOperations::removeFile(TSt Line 7238  Int_t PamelaDBOperations::removeFile(TSt
7238    //    //
7239    this->RemoveRUNS();    this->RemoveRUNS();
7240    //    //
7241    this->RemoveFILES();    this->RemoveFILES(idtsy);
7242    //    //
7243    this->SetID_ROOT(0);    this->SetID_ROOT(0);
7244    this->SetID_RAW(0);    this->SetID_RAW(0);
# Line 6045  void PamelaDBOperations::RemoveRUNS(){ Line 7458  void PamelaDBOperations::RemoveRUNS(){
7458   * Rearrange calibration tables   * Rearrange calibration tables
7459   *   *
7460   **/   **/
7461  void PamelaDBOperations::RemoveFILES(){  void PamelaDBOperations::RemoveFILES(UInt_t idtsy){
7462    stringstream myquery;    stringstream myquery;
7463    //    //
7464    myquery.str("");    myquery.str("");
# Line 6055  void PamelaDBOperations::RemoveFILES(){ Line 7468  void PamelaDBOperations::RemoveFILES(){
7468    //    //
7469    conn->Query(myquery.str().c_str());    conn->Query(myquery.str().c_str());
7470    //    //
7471      myquery.str("");
7472      myquery << " DELETE FROM GL_ROOT WHERE ID=" <<this->GetID_ROOT() <<";";
7473      //
7474      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
7475      //
7476      conn->Query(myquery.str().c_str());  //
7477      //
7478      if ( !chewbacca ){
7479        myquery.str("");
7480        myquery << " DELETE FROM GL_TIMESYNC WHERE ID=" << idtsy <<";";
7481        //
7482        if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
7483        //
7484        conn->Query(myquery.str().c_str());
7485      };
7486      //
7487  };  };
7488    
7489  /**  /**
# Line 6259  void PamelaDBOperations::RemoveCALIBS(){ Line 7688  void PamelaDBOperations::RemoveCALIBS(){
7688   * Rearrange calibration tables   * Rearrange calibration tables
7689   *   *
7690   **/   **/
7691  UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh ){  UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh , TFile *file){
7692    
7693        if(!caltrk) return 0;
7694    
7695        if ( IsDebug() ) cout << "ValidateTrkCalib:"<<endl;
7696    
7697        UInt_t validate = 1;
7698      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};
7699      UInt_t timeaftercalib=120000; //2000;      UInt_t timeaftercalib=120000; //2000;
7700  //  ----------      TString classname = caltrk->GetName();
7701  //  Check CRCs  
7702  //  ----------  //  ----------------------------------
7703    //  Check CRCs and failed calibrations
7704    //  ----------------------------------
7705      for(Int_t ipkt=0; ipkt<6; ipkt++){      for(Int_t ipkt=0; ipkt<6; ipkt++){
7706          if( caltrk->crc_hcal[ipkt] )return 0; // :-(          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
7707          for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] )return 0; // :-(              if( caltrk->crc_hcal[ipkt] ){
7708    //              if(IsDebug())cout<<"(CRC Header)";
7709                    validate = 0;
7710                    if(IsDebug())cout <<endl<<" *** CRC *** (header DSPn "<<caltrk->DSPnumber[ipkt]<<")";
7711            
7712                }
7713                for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] ){
7714    //              if(IsDebug())cout<<"(CRC Pkt-"<<ilad<<")";
7715                    if(IsDebug())cout <<endl<<" *** CRC *** (data DSPn "<<caltrk->DSPnumber[ipkt]<<" ladder "<<ilad<<")";
7716                    validate = 0;
7717                }
7718                if( !(caltrk->ncalib_event[ipkt]==0 && caltrk->cal_flag[ipkt]==0) ){
7719                    if(IsDebug())cout <<endl<<" *** FAILURE ***     (data DSPn "<<caltrk->DSPnumber[ipkt]<<")";
7720                    validate = 0;
7721                }
7722            }else{
7723    //          validate=0;
7724                if(IsDebug())cout <<endl<<" *** DSPn *** ("<< caltrk->DSPnumber[ipkt] <<" @pkt "<<ipkt<<")";
7725            }
7726      }      }
7727    
7728  //  -----------------------  //  -----------------------
7729  //  Check missing packets:  //  Check missing packets:
7730  //  -----------------------  //  -----------------------
# Line 6295  UInt_t PamelaDBOperations::ValidateTrkCa Line 7750  UInt_t PamelaDBOperations::ValidateTrkCa
7750  //  Check if it is first or second calibration packet  //  Check if it is first or second calibration packet
7751  //  -------------------------------------------------  //  -------------------------------------------------
7752      UInt_t build=0;      UInt_t build=0;
     TString classname = caltrk->GetName();  
7753      UInt_t base=0;      UInt_t base=0;
7754      UInt_t mask=0;      UInt_t mask=0;
7755      if(classname.Contains("CalibTrk1Event")){      if(classname.Contains("CalibTrk1Event")){
# Line 6306  UInt_t PamelaDBOperations::ValidateTrkCa Line 7760  UInt_t PamelaDBOperations::ValidateTrkCa
7760          base=18;          base=18;
7761          mask=0xFC0000;          mask=0xFC0000;
7762      }      }
7763  //  -------------------------------------------------  //  ----------------------------------------------------
7764  //  Count number of packets and set build variable  //  Count number of valid packets and set build variable
7765  //  -------------------------------------------------  //  ----------------------------------------------------
7766        if(IsDebug())cout <<endl<< " DSP: ";
7767      Int_t  npkts=0;      Int_t  npkts=0;
7768      for(Int_t ipkt=0; ipkt<6; ipkt++){      for(Int_t ipkt=0; ipkt<6; ipkt++){
7769          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
7770                if(IsDebug())cout <<" "<<caltrk->DSPnumber[ipkt];
7771              npkts++;              npkts++;
7772              build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );              build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );
7773          }  //          cout << caltrk->DSPnumber[ipkt]
7774            };
7775      }      }
7776  //    if( npkts==6 )return 1; // :-)      if(IsDebug())cout << " ==> "<< hex << build << dec;
7777    //  ----------------------------------------------------
7778  //    cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime()<<endl;  //  If the number of valid packets is 6, ok exit...
7779    //  ----------------------------------------------------
7780  //  -----------------------------------------------      if( npkts==6 ){
7781  //  If missing packets: check the acq configuration          return validate; // exit
7782        }
7783    ////////////////////////////////////////////////////////
7784    //  ...otherwise there might be some missing packets
7785    //
7786    //  In this case check the acq configuration
7787  //  (some DSPs might be excluded from acquisition)  //  (some DSPs might be excluded from acquisition)
7788  //  -----------------------------------------------  ////////////////////////////////////////////////////////
7789    
7790        if(!eh || !file || (file&&file->IsZombie()) ){
7791            if ( IsDebug() )cout << " *** MISSING VIEW *** eh="<<eh<<" file="<<file<<" cannot validate"<<endl;
7792            return (0);
7793        }
7794        
7795  //  -----------------------------------------------  //  -----------------------------------------------
7796  //  retrieve the first run header after calib  //  retrieve the first run header after calib
7797  //  -----------------------------------------------  //  -----------------------------------------------
7798       PacketType *pctp;      
7799       EventCounter *cod;      PacketType *pctp;
7800       cod = eh->GetCounter();      EventCounter *cod;
7801       Int_t irun = cod->Get(pctp->RunHeader);      cod = eh->GetCounter();
7802       TTree *rh=(TTree*)file->Get("RunHeader");      Int_t irun = cod->Get(pctp->RunHeader);
7803       if ( !rh || rh->IsZombie() ) throw -17;      TTree *rh=(TTree*)file->Get("RunHeader");
7804       if( rh->GetEntries() == irun ){      if ( !rh || rh->IsZombie() ) throw -17;
7805            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (1)  -- cannot validate :-( "<<endl;      if( rh->GetEntries() <= irun ){
7806           return 0; // :-(          if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (1) -- cannot validate :-( "<<endl;
7807       }          return 0; // :-(
7808        }
7809       RunHeaderEvent *run  = 0;      RunHeaderEvent *run  = 0;
7810       EventHeader    *hrun = 0;      EventHeader    *hrun = 0;
7811       rh->SetBranchAddress("RunHeader", &run);      rh->SetBranchAddress("RunHeader", &run);
7812       rh->SetBranchAddress("Header", &hrun);      rh->SetBranchAddress("Header", &hrun);
7813       rh->GetEntry(irun);      rh->GetEntry(irun);    
7814  //     cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime() << " Run " << hrun->GetPscuHeader()->GetOrbitalTime() <<endl;      if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){
7815            if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (2) -- cannot validate :-( "<<endl;
7816       if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){          return 0; // :-(
7817            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (2) -- cannot validate :-( "<<endl;      }
7818           return 0; // :-(  
7819       }      UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());
7820            if( dtime > timeaftercalib ){
7821       if( !run->RM_ACQ_AFTER_CALIB ){          if ( IsDebug() ) cout << " *** MISSING-PKT *** run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;
7822            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) RM_ACQ_AFTER_CALIB=0    -- cannot validate :-( "<<endl;          return 0; // :-(
7823           return 0; // :-(      }
7824       }  
7825        if ( IsDebug() ) cout <<endl<< " ACQ_BUILD_INFO ==> "<<hex<<(run->ACQ_BUILD_INFO & mask)<<dec;
7826       UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());  
7827       if( dtime > timeaftercalib ){      if( (run->ACQ_BUILD_INFO & mask) != build ){
7828           if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;          validate=0; // :-(
7829           return 0; // :-(          cout <<endl<< " *** MISSING-PKT *** packet mismatch: ACQ_BUILD_INFO="<<hex<<(run->ACQ_BUILD_INFO&mask)<<" != "<<build<<dec;
7830       }      };
7831        
7832        return validate;
7833    
      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; // :-)  
7834    
7835  }  }
7836    
# Line 6378  UInt_t PamelaDBOperations::ValidateTrkCa Line 7840  UInt_t PamelaDBOperations::ValidateTrkCa
7840   *   *
7841   **/   **/
7842  UInt_t PamelaDBOperations::Check(){  UInt_t PamelaDBOperations::Check(){
7843          return(this->Check(0,0));    return(this->Check(0,0));
7844  }  }
7845    
7846  UInt_t PamelaDBOperations::Check(UInt_t from, UInt_t to){  UInt_t PamelaDBOperations::Check(UInt_t from, UInt_t to){
7847    //    //
7848          if ( IsDebug() ) printf(" from %u to %u \n",from,to);    if ( IsDebug() ) printf(" from %u to %u \n",from,to);
7849    //    //
7850    UInt_t test = 0;    UInt_t test = 0;
7851    //    //
# Line 6424  UInt_t PamelaDBOperations::Check(UInt_t Line 7886  UInt_t PamelaDBOperations::Check(UInt_t
7886      //      //
7887      if ( from > 0 && nid <= from ) goto ss;      if ( from > 0 && nid <= from ) goto ss;
7888      if ( to > 0 && nid >= to ) goto ss;      if ( to > 0 && nid >= to ) goto ss;
7889  //      //
7890      if ( (UInt_t)atoll(row->GetField(4)) > 1 ){      if ( (UInt_t)atoll(row->GetField(4)) > 1 ){
7891        //        //
7892        //        //
# Line 6455  UInt_t PamelaDBOperations::Check(UInt_t Line 7917  UInt_t PamelaDBOperations::Check(UInt_t
7917              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)));  
7918              row3 = result3->Next();              row3 = result3->Next();
7919            };            };
7920  //      delete result3;            //    delete result3;
7921    
7922          };          };
7923          //          //
# Line 6476  UInt_t PamelaDBOperations::Check(UInt_t Line 7938  UInt_t PamelaDBOperations::Check(UInt_t
7938              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)));
7939              row3 = result3->Next();              row3 = result3->Next();
7940            };            };
7941  //      delete result3;            //    delete result3;
7942          };          };
7943          //          //
7944          oss.str("");          oss.str("");
# Line 6496  UInt_t PamelaDBOperations::Check(UInt_t Line 7958  UInt_t PamelaDBOperations::Check(UInt_t
7958              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)));
7959              row3 = result3->Next();              row3 = result3->Next();
7960            };            };
7961   //     delete result3;            //    delete result3;
7962    
7963          };          };
7964        };        };
# Line 6517  UInt_t PamelaDBOperations::Check(UInt_t Line 7979  UInt_t PamelaDBOperations::Check(UInt_t
7979            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)));
7980            row3 = result3->Next();            row3 = result3->Next();
7981          };          };
7982  //      delete result3;          //      delete result3;
7983        };        };
7984        //        //
7985      };      };
# Line 6543  UInt_t PamelaDBOperations::Check(UInt_t Line 8005  UInt_t PamelaDBOperations::Check(UInt_t
8005        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
8006        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
8007        test = 1;        test = 1;
8008  //      delete result2;        //        delete result2;
8009      };      };
8010      //      //
8011      if ( (thisrtt < prevrht) && (thisrht != prevrht) ){      if ( (thisrtt < prevrht) && (thisrht != prevrht) ){
# Line 6565  UInt_t PamelaDBOperations::Check(UInt_t Line 8027  UInt_t PamelaDBOperations::Check(UInt_t
8027        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
8028        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
8029        test = 1;        test = 1;
8030  //      delete result2;        //        delete result2;
8031      };      };
8032      //      //
8033      if ( (thisrht > thisrtt) && (thisrht != prevrht) ){      if ( (thisrht > thisrtt) && (thisrht != prevrht) ){
# Line 6587  UInt_t PamelaDBOperations::Check(UInt_t Line 8049  UInt_t PamelaDBOperations::Check(UInt_t
8049        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
8050        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
8051        test = 1;        test = 1;
8052  //      delete result2;        //        delete result2;
8053      };      };
8054  ss:    ss:
8055      //      //
8056      prevrht = thisrht;      prevrht = thisrht;
8057      prevrtt = thisrtt;      prevrtt = thisrtt;
8058      previd = thisid;      previd = thisid;
8059      prevl0id = thisl0id;      prevl0id = thisl0id;
8060      row = result->Next();      row = result->Next();
8061  //    if ( result2 ) delete result2;      //    if ( result2 ) delete result2;
8062  //    if ( result3 ) delete result3;      //    if ( result3 ) delete result3;
8063    };    };
8064    //    //
8065    return(test);    return(test);

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

  ViewVC Help
Powered by ViewVC 1.1.23