/[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.22 by mocchiut, Mon Jan 12 20:22:29 2009 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 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 132  void PamelaDBOperations::OpenL0File(TStr Line 136  void PamelaDBOperations::OpenL0File(TStr
136        stringstream qu;        stringstream qu;
137        TSQLResult *result = 0;        TSQLResult *result = 0;
138        TSQLResult *result2 = 0;        TSQLResult *result2 = 0;
139          TSQLResult *result3 = 0;
140        TSQLRow    *row    = 0;            TSQLRow    *row    = 0;    
141        TSQLRow    *row2    = 0;            TSQLRow    *row2    = 0;    
142          TSQLRow    *row3    = 0;    
143        TString chpath;        TString chpath;
144        TString chfile;        TString chfile;
145        UInt_t ridn = 0;        UInt_t ridn = 0;
146        qu.str("");        qu.str("");
147        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 << ";";
148        if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());        if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
149        result = conn->Query(qu.str().c_str());        result = conn->Query(qu.str().c_str());
150        if ( result ){        if ( result ){
# Line 149  void PamelaDBOperations::OpenL0File(TStr Line 155  void PamelaDBOperations::OpenL0File(TStr
155            chpktmax = (UInt_t)atoll(row->GetField(2));            chpktmax = (UInt_t)atoll(row->GetField(2));
156            chobtmin = (UInt_t)atoll(row->GetField(3));            chobtmin = (UInt_t)atoll(row->GetField(3));
157            chobtmax = (UInt_t)atoll(row->GetField(4));            chobtmax = (UInt_t)atoll(row->GetField(4));
158              chiby = (TString)(row->GetField(5));
159              chrtinit = (UInt_t)atoll(row->GetField(6));
160          } else {          } else {
161            throw -84;            throw -84;
162          };          };
# Line 157  void PamelaDBOperations::OpenL0File(TStr Line 165  void PamelaDBOperations::OpenL0File(TStr
165        };        };
166        delete result;        delete result;
167        qu.str("");        qu.str("");
168        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 << ";";
169        if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());        if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
170        result2 = conn->Query(qu.str().c_str());        result2 = conn->Query(qu.str().c_str());
171        if ( result2 ){        if ( result2 ){
172          row2 = result2->Next();          row2 = result2->Next();
173          if ( row2 ){          if ( row2 ){
174            chpath = (TString)gSystem->ExpandPathName(row2->GetField(0))+'/';            if ( KEEPENV ){
175                chpath = (TString)(row2->GetField(0))+'/';
176              } else {
177                chpath = (TString)gSystem->ExpandPathName(row2->GetField(0))+'/';
178              };
179            chfile = (TString)(row2->GetField(1));            chfile = (TString)(row2->GetField(1));
180            chobtts = (UInt_t)atoll(row2->GetField(2));            chobtts = (UInt_t)atoll(row2->GetField(2));
181            chlastts = (UInt_t)atoll(row2->GetField(3));            chlastts = (UInt_t)atoll(row2->GetField(3));
182            chresursts = (UInt_t)atoll(row2->GetField(4));            chresursts = (UInt_t)atoll(row2->GetField(4));
183            chboot = (UInt_t)atoll(row2->GetField(5));            chboot = (UInt_t)atoll(row2->GetField(5));
184            //            //
185              if ( !chboot ){
186                qu.str("");
187                //      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;";
188                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]
189                if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
190                result3 = conn->Query(qu.str().c_str());
191                if ( result3 ){
192                  row3 = result3->Next();
193                  if ( row3 && result3->GetRowCount() == 1 ){
194                    chboot = (UInt_t)atoll(row3->GetField(0));
195                    if ( debug ) printf(" Found boot_number = %u \n",chboot);
196                  } else {
197                    if ( debug ) printf(" AGH CANNOT DETERMINE THE BOOT NUMBER... \n");
198                    throw -29;
199                  };
200                };
201              };
202              //
203            chpktinit = (UInt_t)atoll(row2->GetField(6));            chpktinit = (UInt_t)atoll(row2->GetField(6));
204            chpktfinal = (UInt_t)atoll(row2->GetField(7));            chpktfinal = (UInt_t)atoll(row2->GetField(7));
205            chobtinit = (UInt_t)atoll(row2->GetField(8));            chobtinit = (UInt_t)atoll(row2->GetField(8));
# Line 182  void PamelaDBOperations::OpenL0File(TStr Line 212  void PamelaDBOperations::OpenL0File(TStr
212          throw -85;          throw -85;
213        };        };
214        filerootname = chpath + chfile;// + ".root";        filerootname = chpath + chfile;// + ".root";
       if ( debug ) printf(" chewbacca: filename is %s \n",filerootname.Data());  
215      };      };
216      this->SetRootName(filerootname);      this->SetRootName(filerootname);
     file = TFile::Open(this->GetRootName().Data());  
   } else {  
     this->SetRootName("");  
217    };    };
218      if ( debug ) printf(" Filename is %s \n",filerootname.Data());
219      file = TFile::Open(this->GetRootName().Data());
220      //  } else {
221      //    this->SetRootName("");
222      //    this->SetRootName(filerootname);
223      //  };
224  }  }
225    
226  //  //
# Line 388  void PamelaDBOperations::SetOrbitNo(UInt Line 420  void PamelaDBOperations::SetOrbitNo(UInt
420      return;      return;
421    };    };
422    //    //
423    TString name = this->GetRootFile();    if ( !chewbacca ){
424    Int_t nlength = name.Length();      TString name = this->GetRootFile();
425    if ( nlength < 5 ) return;      Int_t nlength = name.Length();
426    TString dwo = 0;      if ( nlength < 5 ){
427    for (Int_t i = 0; i<5; i++){        if ( IsDebug() ) printf(" Agh problems determining the orbit number! name = %s \n",name.Data());
428      dwo.Append(name[i],1);        return;
429    };      };
430    if ( dwo.IsDigit() ){      TString dwo = 0;
431      dworbit = (UInt_t)dwo.Atoi();      for (Int_t i = 0; i<5; i++){
   } else {  
     dwo="";  
     for (Int_t i = 8; i<13; i++){  
432        dwo.Append(name[i],1);        dwo.Append(name[i],1);
433      };          };
434      if ( dwo.IsDigit() ) dworbit = (UInt_t)dwo.Atoi();      if ( dwo.IsDigit() ){
435          dworbit = (UInt_t)dwo.Atoi();
436        } else {
437          dwo="";
438          for (Int_t i = 8; i<13; i++){
439            dwo.Append(name[i],1);
440          };    
441          if ( dwo.IsDigit() ) dworbit = (UInt_t)dwo.Atoi();
442        };
443        if ( IsDebug() ) printf(" Downlink orbit is %i (dwo = %s) \n",dworbit,dwo.Data());
444    };    };
   if ( IsDebug() ) printf(" Downlink orbit is %i (dwo = %s) \n",dworbit,dwo.Data());  
445    return;    return;
446  };  };
447    
# Line 435  TString PamelaDBOperations::GetRawPath() Line 472  TString PamelaDBOperations::GetRawPath()
472    
473  TString PamelaDBOperations::GetRootPath(){  TString PamelaDBOperations::GetRootPath(){
474    if ( STATIC ){    if ( STATIC ){
475      return((TString)gSystem->DirName(filerootname.Data())+'/');      return((TString)gSystem->DirName(this->GetRootName().Data())+'/');
476    } else {    } else {    
477      return((TString)gSystem->ExpandPathName("$PAM_L0")+'/');      if ( KEEPENV ){
478          return((TString)gSystem->ExpandPathName(gSystem->DirName(filerootname.Data()))+'/');
479        } else {
480          return((TString)gSystem->ExpandPathName("$PAM_L0")+'/');
481        };
482    };    };
483  };  };
484    
# Line 490  void PamelaDBOperations::SetCommonGLRUN( Line 531  void PamelaDBOperations::SetCommonGLRUN(
531  };  };
532    
533  /**  /**
534     *
535     * Set the variables which belogns to physendrun tree
536     *
537     */
538    void PamelaDBOperations::SetPhysEndRunVariables(){
539      //
540      //
541      //
542      TTree *T = 0;
543      T = (TTree*)file->Get("PhysEndRun");
544      if ( !T || T->IsZombie() ) throw -90;
545      //
546      PhysEndRunEvent *pher= 0;
547      EventHeader *eh = 0;
548      T->SetBranchAddress("PhysEndRun", &pher);
549      T->SetBranchAddress("Header", &eh);
550      //
551      UInt_t phobt = 0;
552      UInt_t phpkt = 0;
553      //
554      glrun->SetPHYSENDRUN_MASK_S3S2S12(0);
555      glrun->SetPHYSENDRUN_MASK_S11CRC(0);
556      //
557      for (Int_t p=0; p<T->GetEntries(); p++){
558        //
559        T->GetEntry(p);
560        //
561        phobt = (UInt_t)eh->GetPscuHeader()->GetOrbitalTime();
562        phpkt = (UInt_t)eh->GetPscuHeader()->GetCounter();
563        //
564        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())  ){
565          if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() || glrun->GetPHYSENDRUN_MASK_S11CRC() ){
566            if ( IsDebug() ) printf(" WARNING while looping in physendrun: found two PhysEndRun packet for the same RUN! \n");
567            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);
568            if ( PEDANTIC && IsDebug() ) printf(" ERROR while looping in physendrun: found two PhysEndRun packet for the same RUN!\n ");
569            if ( PEDANTIC ) throw -91;
570          } else {
571            glrun->SetPHYSENDRUN_MASK_S3S2S12((UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S3S2S12);
572            glrun->SetPHYSENDRUN_MASK_S11CRC((UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S11CRC);
573          };
574        };
575      };
576      //
577    };
578    
579    /**
580   * Patch, look for upper limits to avoid processing retransmitted data   * Patch, look for upper limits to avoid processing retransmitted data
581   */   */
582  Int_t PamelaDBOperations::SetUpperLimits(){  Int_t PamelaDBOperations::SetUpperLimits(){
# Line 603  Int_t PamelaDBOperations::SetUpperLimits Line 690  Int_t PamelaDBOperations::SetUpperLimits
690      UInt_t tjump = 50000;      UInt_t tjump = 50000;
691      //UInt_t tjump = 100;      //UInt_t tjump = 100;
692      while ( tjump > 0 ){      while ( tjump > 0 ){
693        pktlast = numeric_limits<UInt_t>::max();        //      pktlast = numeric_limits<UInt_t>::max();
694        while ( pktlast > chpktmax && (Int_t)(nevent-1-it) >= 0 ){        pktlast = chpktmax + 1;
695          while ( PKT(pktlast) > PKT(chpktmax) && (Int_t)(nevent-1-it) >= 0 ){
696          if ( (Int_t)(nevent-1-it) >= 0 ){          if ( (Int_t)(nevent-1-it) >= 0 ){
697            T->GetEntry(nevent-1-it);            T->GetEntry(nevent-1-it);
698            ph = eh->GetPscuHeader();            ph = eh->GetPscuHeader();
# Line 612  Int_t PamelaDBOperations::SetUpperLimits Line 700  Int_t PamelaDBOperations::SetUpperLimits
700          } else {          } else {
701            pktlast = chpktmax + 1;            pktlast = chpktmax + 1;
702          };          };
703          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));
704          it += tjump;          it += tjump;
705        };        };
706        if ( tjump > 1 ) it -= 2*tjump;        if ( tjump > 1 ) it -= 2*tjump;
# Line 636  Int_t PamelaDBOperations::SetUpperLimits Line 724  Int_t PamelaDBOperations::SetUpperLimits
724      tjump = 50000;      tjump = 50000;
725      //tjump = 100;      //tjump = 100;
726      while ( tjump > 0 ){      while ( tjump > 0 ){
727        pktlast = 0;        //      pktlast = 0;
728        while ( pktlast < chpktmin && it < (Int_t)nevent ){        pktlast = chpktmin - 1;
729          if ( debug ) printf("LLlook for down %i %i %llu %llu \n",it,pktlast,PKT(pktlast),PKT(chpktmin));
730          while ( PKT(pktlast) < PKT(chpktmin) && it < (Int_t)nevent ){
731          if ( it < (Int_t)nevent ){          if ( it < (Int_t)nevent ){
732            T->GetEntry(it);            T->GetEntry(it);
733            ph = eh->GetPscuHeader();            ph = eh->GetPscuHeader();
# Line 731  Int_t PamelaDBOperations::SetUpperLimits Line 821  Int_t PamelaDBOperations::SetUpperLimits
821      ph = eh->GetPscuHeader();      ph = eh->GetPscuHeader();
822      pktlast = ph->GetCounter();      pktlast = ph->GetCounter();
823      nevent = upperentry - chminentry;      nevent = upperentry - chminentry;
824        if ( ((Int_t)upperentry - (Int_t)chminentry) < 0 ) nevent = 0; // nevent is UInt_t! 090112 [8RED: error -88]
825        if ( IsDebug() ) printf(" Setting nevent to %u - upperentry %i chminentry %i \n",nevent,upperentry,chminentry);
826      //      //
827    } else {    } else {
828      upperpkt = PKT(pktlast);      upperpkt = PKT(pktlast);
# Line 739  Int_t PamelaDBOperations::SetUpperLimits Line 831  Int_t PamelaDBOperations::SetUpperLimits
831    };    };
832    //    //
833    if ( chewbacca && nevent < 1 ) {    if ( chewbacca && nevent < 1 ) {
834          pktfirst = chpktmin;      if ( IsDebug() ) printf(" chewbacca and no events in the file \n");
835          upperpkt = PKT(chpktmax);      pktfirst = chpktmin;
836          pktlast = chpktmax;      upperpkt = PKT(chpktmax);
837          obtfirst = chobtmin;      pktlast = chpktmax;
838          obtlast = chobtmax;      obtfirst = chobtmin;
839          upperobt = OBT(chobtmax);      obtlast = chobtmax;
840        upperobt = OBT(chobtmax);
841    };    };
842    //    //
843    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 845  Int_t PamelaDBOperations::SetUpperLimits
845    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);
846    //    //
847    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)) ){
848          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));
849          if ( PEDANTIC ) throw -88;      if ( PEDANTIC ) throw -88;
850          return(32);      return(32);
851    };    };
852    //    //
853    if ( !nevent ) return(64);    if ( !nevent ) return(64);
# Line 1040  Int_t PamelaDBOperations::SetUpperLimits Line 1133  Int_t PamelaDBOperations::SetUpperLimits
1133          upperpkt = pkth;          upperpkt = pkth;
1134          upperobt = obth;          upperobt = obth;
1135          rhev = lasthead+1;          rhev = lasthead+1;
1136      } else {        } else {
1137          rhev = lasthead;          rhev = lasthead;
1138        };        };
1139        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 1172  UInt_t PamelaDBOperations::AssignRunID()
1172    stringstream   oss;    stringstream   oss;
1173    //      //  
1174    oss.str("");    oss.str("");
1175    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.
1176        if ( !strcmp(tag.Data(),"NONE") ){
1177          oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< chiby.Data() <<"');";
1178        } else {
1179          oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< tag.Data() <<"');";
1180        };
1181      } else {
1182        oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< tag.Data() <<"');";
1183      };
1184    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1185    if ( !result ) throw -10;    if ( !result ) throw -10;
1186    oss.str("");    oss.str("");
# Line 1227  void PamelaDBOperations::LockTables(){   Line 1328  void PamelaDBOperations::LockTables(){  
1328    stringstream oss;    stringstream oss;
1329    //      //  
1330    oss.str("");    oss.str("");
1331    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;";
1332    TSQLResult *result = 0;    TSQLResult *result = 0;
1333    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
1334    if ( !result ) throw -10;    if ( !result ) throw -10;
# Line 1260  void PamelaDBOperations::UnLockTables(){ Line 1361  void PamelaDBOperations::UnLockTables(){
1361   */   */
1362  Long64_t PamelaDBOperations::PKT(UInt_t pkt_num){    Long64_t PamelaDBOperations::PKT(UInt_t pkt_num){  
1363    //    //
1364  //  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));
1365    //    //
1366    if ( pkt_num < (ppktfirst/2) && ppktfirst > (16777214/2)  ){    if ( pkt_num < (ppktfirst/2) && ppktfirst > (16777214/2)  ){
1367  //    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);
1368      return((Long64_t)pkt_num+16777215LL);      return((Long64_t)pkt_num+16777215LL);
1369    };    };
1370    //    //
1371    if ( pkt_num > ((Long64_t)ppktfirst*2) && pkt_num > (16777214/2) ){    if ( pkt_num > ((Long64_t)ppktfirst*2) && pkt_num > (16777214/2) ){
1372  //    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);
1373      return((Long64_t)pkt_num-16777215LL);      return((Long64_t)pkt_num-16777215LL);
1374    };    };
1375    //    //
1376  //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)pkt_num);    //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)pkt_num);
1377    return((Long64_t)pkt_num);    return((Long64_t)pkt_num);
1378    //    //
1379  };  };
# Line 1282  Long64_t PamelaDBOperations::PKT(UInt_t Line 1383  Long64_t PamelaDBOperations::PKT(UInt_t
1383   */   */
1384  Long64_t PamelaDBOperations::OBT(UInt_t obt){    Long64_t PamelaDBOperations::OBT(UInt_t obt){  
1385    //    //
1386  //  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));
1387    //    //
1388    if ( obt < (pobtfirst/2) && pobtfirst > (numeric_limits<UInt_t>::max()/2) ){    if ( obt < ((Long64_t)pobtfirst/2) && pobtfirst > (numeric_limits<UInt_t>::max()/2) ){
1389  //    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());
1390      return((Long64_t)obt+(Long64_t)numeric_limits<UInt_t>::max());      return((Long64_t)obt+(Long64_t)numeric_limits<UInt_t>::max());
1391    };    };
1392    //    //
1393    if ( 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) ){
1394  //    if ( IsDebug() ) printf(" pobtfirst*2 %lld \n",((Long64_t)pobtfirst*2));      //    if ( IsDebug() ) printf(" pobtfirst*2 %lld \n",((Long64_t)pobtfirst*2));
1395  //    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());
1396      return((Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());      return((Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());
1397    };    };
1398    //    //
1399  //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)obt);    //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)obt);
1400    return((Long64_t)obt);    return((Long64_t)obt);
1401  };  };
1402    
# Line 1331  void PamelaDBOperations::FillClass(Bool_ Line 1432  void PamelaDBOperations::FillClass(Bool_
1432    UInt_t lastPkt = 0;    UInt_t lastPkt = 0;
1433    UInt_t rhtime = 0;    UInt_t rhtime = 0;
1434    UInt_t rttime = 0;    UInt_t rttime = 0;
1435      //
1436      if ( IsDebug() ) printf(" A firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1437      //
1438    if ( !mishead ){    if ( !mishead ){
1439      codh = ehh->GetCounter();      codh = ehh->GetCounter();
1440      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1) ){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){      
1441          if ( IsDebug() ) printf(" B firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1442        firstev = 1;        firstev = 1;
1443        lastev = 0;        lastev = 0;
1444      } else {      } else {
# Line 1346  void PamelaDBOperations::FillClass(Bool_ Line 1451  void PamelaDBOperations::FillClass(Bool_
1451    };    };
1452    if ( !mistrail ){    if ( !mistrail ){
1453      codt = eht->GetCounter();      codt = eht->GetCounter();
1454      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1)){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1)){      
1455          if ( IsDebug() ) printf(" C firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
1456        lastev = 0;        lastev = 0;
1457        firstev = lastev+1;        firstev = lastev+1;
1458      } else {      } else {
# Line 1363  void PamelaDBOperations::FillClass(Bool_ Line 1469  void PamelaDBOperations::FillClass(Bool_
1469    if ( mishead ) {    if ( mishead ) {
1470      glrun->Set_GL_RUNH0();      glrun->Set_GL_RUNH0();
1471      //      //
1472      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1) ){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){      
1473        firstObt = lastObt;        firstObt = lastObt;
1474        firstPkt = lastPkt;        firstPkt = lastPkt;
1475        rhtime = rttime;        rhtime = rttime;
# Line 1382  void PamelaDBOperations::FillClass(Bool_ Line 1488  void PamelaDBOperations::FillClass(Bool_
1488    if ( mistrail ){    if ( mistrail ){
1489      glrun->Set_GL_RUNT0();      glrun->Set_GL_RUNT0();
1490      //      //
1491      if ( lastev+1 == firstev || (lastev == firstev && lastev != -1) ){            if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){      
1492        lastObt = firstObt;        lastObt = firstObt;
1493        lastPkt = firstPkt;        lastPkt = firstPkt;
1494        rttime = rhtime;        rttime = rhtime;
# Line 1405  void PamelaDBOperations::FillClass(Bool_ Line 1511  void PamelaDBOperations::FillClass(Bool_
1511    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);
1512    //    //
1513    this->SetCommonGLRUN(rhtime,rttime);    this->SetCommonGLRUN(rhtime,rttime);
1514      this->SetPhysEndRunVariables();
1515    //    //
1516  };  };
1517    
# Line 1416  void PamelaDBOperations::FillClass(Bool_ Line 1523  void PamelaDBOperations::FillClass(Bool_
1523   * Insert a new row into GL_RAW table.   * Insert a new row into GL_RAW table.
1524   */   */
1525  Int_t PamelaDBOperations::insertPamelaRawFile(){  Int_t PamelaDBOperations::insertPamelaRawFile(){
1526    
1527        //
1528        Bool_t idr =  this->SetID_RAW();
1529        if ( idr ) return(1);
1530    
1531        GL_RAW glraw = GL_RAW();
1532        
1533        glraw.PATH = GetRawPath();
1534        glraw.NAME = GetRawFile();
1535        //    glraw.BOOT_NUMBER = 0;//???
1536        glraw.BOOT_NUMBER = this->GetBOOTnumber();
1537        
1538        if( insertPamelaRawFile(&glraw) )return(1);
1539        //
1540        idr =  this->SetID_RAW();
1541        if ( !idr ) throw -11;
1542        
1543        return(0);
1544    }
1545    /**
1546     * Insert a new row into GL_RAW table.
1547     */
1548    Int_t PamelaDBOperations::insertPamelaRawFile(GL_RAW *glraw){
1549    //    //
1550    stringstream oss;      if(!glraw)return(1);//?? ok I think
1551    //      //
1552    Bool_t idr =  this->SetID_RAW();      stringstream oss;
1553    if ( idr ) return(1);      //
1554    //      oss.str("");
1555    oss.str("");      if ( STATIC ){
1556    if ( STATIC ){          oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"
1557      oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"              << glraw->PATH << "', '" << glraw->NAME << "')";
1558          << this->GetRawPath().Data() << "', '" << this->GetRawFile().Data() << "')";      } else {
1559    } else {          oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('$PAM_RAW', '" << glraw->NAME << "')";
1560      oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('$PAM_RAW', '" << this->GetRawFile().Data() << "')";      };
1561    };      if ( debug ) cout <<oss.str().c_str() <<endl;
1562    if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;      if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
1563    //      //
1564    idr =  this->SetID_RAW();      oss.str("");
1565    if ( !idr ) throw -11;      oss << "SELECT ID FROM GL_RAW WHERE NAME=\""<<glraw->NAME<<"\";";
1566    //      if ( debug ) cout << oss.str().c_str()<<endl;
1567    return(0);      if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
1568        //
1569        TSQLResult *result = 0;
1570        TSQLRow    *row    = 0;
1571        result = conn->Query(oss.str().c_str());
1572        if ( result == NULL ) throw -4;
1573        row = result->Next();
1574        if ( !row ) return(1);
1575        glraw->ID = (UInt_t)atoll(row->GetField(0));
1576        if ( debug ) printf(" The ID of the RAW file is %u \n",glraw->ID);
1577        delete result;
1578        delete row;
1579        //
1580        return(0);
1581  }  }
1582    
1583    
# Line 1467  Int_t PamelaDBOperations::insertPamelaGL Line 1610  Int_t PamelaDBOperations::insertPamelaGL
1610      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
1611      if ( !result ) throw -10;      if ( !result ) throw -10;
1612      row = result->Next();      row = result->Next();
1613        if ( !row ) throw -92;
1614      idresof = (UInt_t)atoll(row->GetField(0));      idresof = (UInt_t)atoll(row->GetField(0));
1615      existsts = true;      existsts = true;
1616      goto eout;      goto eout;
# Line 1488  Int_t PamelaDBOperations::insertPamelaGL Line 1632  Int_t PamelaDBOperations::insertPamelaGL
1632      if ( !row ){      if ( !row ){
1633        oss.str("");        oss.str("");
1634        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< "
1635            << dworbit << " order by FROM_ORBIT desc limit 1;";            << dworbit << " AND SPECIAL_FILE='' order by FROM_ORBIT desc limit 1;";
1636        if ( IsDebug() ) printf(" %s \n",oss.str().c_str());        if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
1637        result = conn->Query(oss.str().c_str());        result = conn->Query(oss.str().c_str());
1638        if ( !result ) throw -10;        if ( !result ) throw -10;
# Line 1746  Int_t PamelaDBOperations::insertPamelaGL Line 1890  Int_t PamelaDBOperations::insertPamelaGL
1890   * 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.
1891   */   */
1892  Int_t PamelaDBOperations::insertPamelaRootFile(){  Int_t PamelaDBOperations::insertPamelaRootFile(){
1893    stringstream oss;  
1894    TSQLResult *result = 0;      stringstream oss;
1895    TSQLRow    *row    = 0;      TSQLResult *result = 0;
1896    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;  
1897      //      //
1898      row = result->Next();      // ----------------------
1899        // determine the timesync
1900        // ----------------------
1901        UInt_t idtimesync = 0;
1902      //      //
1903      if ( !row ) throw -3;      if ( chewbacca ){
1904      idtimesync = (UInt_t)atoll(row->GetField(0));          oss.str("");
1905    } else {          oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" limit 1;";
1906      oss.str("");          if ( debug ) printf(" %s \n",oss.str().c_str());
1907      if ( STATIC ){          result = conn->Query(oss.str().c_str());
1908        oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "          //
1909            << " LEFT JOIN GL_ROOT "          if ( !result ) throw -3;
1910            << " ON GL_RAW.ID = GL_ROOT.ID_RAW "          //
1911            << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "          row = result->Next();
1912            << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";          //
1913            if ( !row ) throw -3;
1914            idtimesync = (UInt_t)atoll(row->GetField(0));
1915      } else {      } else {
1916        oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "          oss.str("");
1917            << " LEFT JOIN GL_ROOT "          if ( STATIC ){
1918            << " ON GL_RAW.ID = GL_ROOT.ID_RAW "              oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1919            << " WHERE GL_RAW.PATH = '$PAM_RAW' AND "                  << " LEFT JOIN GL_ROOT "
1920            << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";                  << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1921                    << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "
1922                    << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1923            } else {
1924                oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
1925                    << " LEFT JOIN GL_ROOT "
1926                    << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
1927                    << " WHERE GL_RAW.PATH = '$PAM_RAW' AND "
1928                    << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
1929            };
1930            result = conn->Query(oss.str().c_str());
1931            //
1932            if ( !result ) throw -12;
1933            //
1934            row = result->Next();
1935            //
1936            if ( !row ) throw -10;
1937            if ( row != NULL && (UInt_t)atoll(row->GetField(0))>0 ){
1938                idroot = (UInt_t)atoll(row->GetField(2));
1939                delete row;
1940                delete result;
1941                return(1);
1942            };
1943            //
1944            // determine which timesync has to be used
1945            //
1946            oss.str("");
1947            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;";
1948            result = conn->Query(oss.str().c_str());
1949            //
1950            if ( !result ) throw -3;
1951            //
1952            row = result->Next();
1953            //
1954            if ( !row ) throw -3;
1955            idtimesync = (UInt_t)atoll(row->GetField(0));
1956      };      };
1957      result = conn->Query(oss.str().c_str());      
1958      //      delete row;
1959      if ( !result ) throw -12;      delete result;
1960      //  
1961      row = result->Next();      // ----------------------
1962      //      // insert root file
1963      if ( !row ) throw -10;      // ----------------------
1964      if ( row != NULL && (UInt_t)atoll(row->GetField(0))>0 ){  
1965        idroot = (UInt_t)atoll(row->GetField(2));      GL_ROOT glroot = GL_ROOT();
1966        return(1);      
1967        glroot.ID_RAW = GetID_RAW();
1968        glroot.ID_TIMESYNC = idtimesync;
1969        if ( STATIC ){
1970          glroot.PATH = GetRootPath();
1971        } else {
1972          if ( KEEPENV ){
1973            glroot.PATH = gSystem->DirName(filerootname.Data());
1974          } else {
1975            glroot.PATH = "$PAM_L0";
1976          };
1977      };      };
1978      //      glroot.NAME = GetRootFile();
1979      // determine which timesync has to be used  
1980      //      if ( insertPamelaRootFile(&glroot) )return 1;
1981      oss.str("");  
1982      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);
1983      result = conn->Query(oss.str().c_str());      
1984      //  
1985      if ( !result ) throw -3;      return (0);
1986      //  }
1987      row = result->Next();  /**
1988      //   * Insert all the new rows into GL_ROOT.
1989      if ( !row ) throw -3;   * The raw file indicates in the parameters should be already been stored in the database.
1990      idtimesync = (UInt_t)atoll(row->GetField(0));   */
1991    };  Int_t PamelaDBOperations::insertPamelaRootFile(GL_ROOT *glroot){
1992      stringstream oss;
1993      TSQLResult *result = 0;
1994      TSQLRow    *row    = 0;
1995      //
1996    //    //
1997    oss.str("");    oss.str("");
1998    if ( STATIC ){    oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
1999      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() << "')";  
   };  
2000    //    //
2001    if ( debug ) printf(" query is %s \n",oss.str().c_str());    if ( debug ) printf("%s \n",oss.str().c_str());
2002    if (conn->Query(oss.str().c_str()) == 0) throw -4;    if (conn->Query(oss.str().c_str()) == 0) throw -4;
2003    //    //
2004    delete result;    delete result;
2005    //    //
2006    oss.str("");    oss.str("");
2007    //  oss << "SELECT ID FROM GL_ROOT WHERE ID_RAW=" << this->GetID_RAW() << ";";    //  oss << "SELECT ID FROM GL_ROOT WHERE ID_RAW=" << this->GetID_RAW() << ";";
2008    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() <<"';";  
   };  
2009    //    //
2010    if ( debug ) printf(" query is %s \n",oss.str().c_str());    if ( debug ) printf("%s \n",oss.str().c_str());
2011    result = conn->Query(oss.str().c_str());    result = conn->Query(oss.str().c_str());
2012    if ( !result ) throw -12;    if ( !result ) throw -12;
2013    row = result->Next();    row = result->Next();
2014    if ( !row ) throw -3;    if ( !row ) throw -3;
2015    this->SetID_ROOT((UInt_t)atoll(row->GetField(0)));  
2016    if ( debug ) printf(" The ID of the ROOT file is %u \n",this->GetID_ROOT());    glroot->ID = (UInt_t)atoll(row->GetField(0));
2017    
2018      if ( debug ) printf(" The ID of the ROOT file is %u \n",glroot->ID);
2019    //    //
2020    delete result;    delete result;
2021    //    //
# Line 2061  Int_t PamelaDBOperations::insertPamelaRU Line 2243  Int_t PamelaDBOperations::insertPamelaRU
2243            cod = ehh->GetCounter();            cod = ehh->GetCounter();
2244            tcod = (UInt_t)cod->Get(pctp->Physics);            tcod = (UInt_t)cod->Get(pctp->Physics);
2245            evbefh = TMath::Max(chminentry,tcod);            evbefh = TMath::Max(chminentry,tcod);
2246  //        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
2247            if ( (UInt_t)evbefh == upperentry || !upperentry ) evbefh = upperentry + 1;            if ( (UInt_t)evbefh == upperentry || !upperentry ) evbefh = upperentry + 1;
2248  //            //
2249          if ( debug ) printf(" evbefh %i upperentry %u \n",evbefh,upperentry);            if ( debug ) printf(" evbefh %i upperentry %u \n",evbefh,upperentry);
2250            //            //
2251            this->HandleRunFragments(false,true,evbefh,upperentry);            this->HandleRunFragments(false,true,evbefh,upperentry);
2252            //            //
# Line 2091  Int_t PamelaDBOperations::insertPamelaRU Line 2273  Int_t PamelaDBOperations::insertPamelaRU
2273          ptht = cod->Get(pctp->RunHeader) - 1;          ptht = cod->Get(pctp->RunHeader) - 1;
2274          //      evbeft = cod->Get(pctp->Physics);          //      evbeft = cod->Get(pctp->Physics);
2275          tcod = (UInt_t)cod->Get(pctp->Physics);          tcod = (UInt_t)cod->Get(pctp->Physics);
2276          if ( !tcod ) tcod = 1;          if ( !tcod ) tcod = 1;    // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
2277          evbeft = TMath::Min(upperentry,(tcod-1));          evbeft = TMath::Min(upperentry,(tcod-1));
2278          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));
2279          //          //
# Line 2130  Int_t PamelaDBOperations::insertPamelaRU Line 2312  Int_t PamelaDBOperations::insertPamelaRU
2312            obth = phh->GetOrbitalTime();            obth = phh->GetOrbitalTime();
2313            cod = ehh->GetCounter();            cod = ehh->GetCounter();
2314            tcod = (UInt_t)cod->Get(pctp->Physics);            tcod = (UInt_t)cod->Get(pctp->Physics);
2315            if ( !tcod ) tcod = 1;            if ( !tcod ) tcod = 1; // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
2316            evbefh = TMath::Max(chminentry,(tcod-1));            evbefh = TMath::Max(chminentry,(tcod-1));
2317            //            //
2318            if ( PKT(pkth) >= PKT(pktfirst) && PKT(pkth) <= upperpkt ){            if ( PKT(pkth) >= PKT(pktfirst) && PKT(pkth) <= upperpkt ){
# Line 2169  Int_t PamelaDBOperations::insertPamelaRU Line 2351  Int_t PamelaDBOperations::insertPamelaRU
2351                //                //
2352                this->HandleRunFragments(true,true,chminentry,(evbefh));                this->HandleRunFragments(true,true,chminentry,(evbefh));
2353                //                //
2354                  // what about pth=ptht-1
2355              };              };
2356            };            };
2357            //            //
# Line 2191  Int_t PamelaDBOperations::insertPamelaRU Line 2374  Int_t PamelaDBOperations::insertPamelaRU
2374                cod = ehh->GetCounter();                cod = ehh->GetCounter();
2375                //            evbeft = cod->Get(pctp->Physics);                //            evbeft = cod->Get(pctp->Physics);
2376                tcod = (UInt_t)cod->Get(pctp->Physics);                tcod = (UInt_t)cod->Get(pctp->Physics);
2377                if ( !tcod ) tcod = 1;                if ( !tcod ) tcod = 1; // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
2378                evbeft = TMath::Min(upperentry,(tcod-1));                evbeft = TMath::Min(upperentry,(tcod-1));
2379                rh->GetEntry(pth);                rh->GetEntry(pth);
2380                phh = ehh->GetPscuHeader();                phh = ehh->GetPscuHeader();
# Line 2231  Int_t PamelaDBOperations::insertPamelaRU Line 2414  Int_t PamelaDBOperations::insertPamelaRU
2414          //      if ( ptt+1 == rtev){            //      if ( ptt+1 == rtev){  
2415          if ( conptt+1 == nrtev ){            if ( conptt+1 == nrtev ){  
2416            //    if ( conptt+1 == (nrtev+nrtbef )){              //    if ( conptt+1 == (nrtev+nrtbef )){  
2417              if ( IsDebug() ) printf(" >>>>>>>>>>> %i %u %i %u \n",ptht,rhev,nrtev,conptt);
2418            ptht++;            ptht++;
2419            if ( ptht < rhev ){            if ( ptht < rhev ){
2420              rh->GetEntry(ptht);              rh->GetEntry(ptht);
2421                //pth++;
2422                //if ( pth < rhev ){
2423                //rh->GetEntry(pth);
2424              phh = ehh->GetPscuHeader();              phh = ehh->GetPscuHeader();
2425              pkth = phh->GetCounter();              pkth = phh->GetCounter();
2426              obth = phh->GetOrbitalTime();              obth = phh->GetOrbitalTime();
# Line 2257  Int_t PamelaDBOperations::insertPamelaRU Line 2444  Int_t PamelaDBOperations::insertPamelaRU
2444              if ( (UInt_t)evbeft < upperentry-1 && upperentry>0 ){              if ( (UInt_t)evbeft < upperentry-1 && upperentry>0 ){
2445                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);
2446                //                //
2447                if ( (ptt-1) < 0 ) throw -15; // should never arrive here!                //              if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
2448                rt->GetEntry(ptt-1);                if ( (rtev-1) < 0 || ptt < 0 ) throw -15; // should never arrive here!
2449                  //              rt->GetEntry(ptt-1);
2450                  rt->GetEntry(rtev-1);
2451                cod = eht->GetCounter();                cod = eht->GetCounter();
2452                tcod = (UInt_t)cod->Get(pctp->Physics);                tcod = (UInt_t)cod->Get(pctp->Physics)+1;
2453                evbefh = TMath::Max(chminentry,tcod);                evbefh = TMath::Max(chminentry,tcod);
2454                //            evbefh = cod->Get(pctp->Physics);                //            evbefh = cod->Get(pctp->Physics);
2455                rt->GetEntry(ptt);                rt->GetEntry(ptt);
# Line 2367  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2556  Bool_t PamelaDBOperations::IsRunAlreadyI
2556        //        //
2557        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");
2558        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2559  //       oss.str("");        //       oss.str("");
2560  //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2561  //       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());      
2562  //       conn->Query(oss.str().c_str());        //       conn->Query(oss.str().c_str());
2563        if ( signal ) signal = false;        if ( signal ) signal = false;
2564        goto gonext;              goto gonext;      
2565        //        //
# Line 2385  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2574  Bool_t PamelaDBOperations::IsRunAlreadyI
2574        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");
2575        //        //
2576        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2577  //       oss.str("");        //       oss.str("");
2578  //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2579  //       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());      
2580  //       conn->Query(oss.str().c_str());        //       conn->Query(oss.str().c_str());
2581        //        //
2582        if ( signal ) signal = false;        if ( signal ) signal = false;
2583        goto gonext;        goto gonext;
# Line 2403  Bool_t PamelaDBOperations::IsRunAlreadyI Line 2592  Bool_t PamelaDBOperations::IsRunAlreadyI
2592        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");
2593        //        //
2594        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2595  //       oss.str("");        //       oss.str("");
2596  //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";        //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
2597  //       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());      
2598  //       conn->Query(oss.str().c_str());        //       conn->Query(oss.str().c_str());
2599        if ( signal ) signal = false;        if ( signal ) signal = false;
2600        //        //
2601      };      };
# Line 2488  void PamelaDBOperations::HandleRunFragme Line 2677  void PamelaDBOperations::HandleRunFragme
2677      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");
2678      //      //
2679    } 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 ){  
2680      //      //
2681      // 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
2682      //      //
2683      if ( IsDebug() ) printf(" The run is new \n");      if ( firstev != (lastev+1) ){ // could be a problem sometimes (?)
2684      if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");        if ( rhfirstev != firstev && !mishead ) mishead = true;
2685          if ( rtlastev != lastev && !mistrail ) mistrail = true;
2686        };
2687      //      //
2688      glrun->SetID(this->AssignRunID());      if ( IsDebug() ) printf(" bhere firstev is %i lastev is %i \n",firstev,lastev);
2689      glrun->SetID_RUN_FRAG(0);      this->FillClass(mishead,mistrail,firstev,lastev);
2690      glrun->Fill_GL_RUN_FRAGMENTS(conn);      if ( IsDebug() ) printf(" chere firstev is %i lastev is %i \n",firstev,lastev);
2691      //      //
2692    } else {      if ( IsDebug() ) printf("The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
2693      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());
2694      if ( PEDANTIC ) throw -69;      //
2695      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  
2696      //      //
2697      oss.str("");      oss.str("");
2698      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 "
2699          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "          << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
2700          << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "          << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
2701          << " ID != " << glrun->ID          << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
2702          << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!          << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
2703            << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2704            << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
2705            << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
2706            << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2707            << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
2708            << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
2709            << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
2710            << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
2711            << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
2712      //      //
2713      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());
2714      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
2715      //      //
2716      if ( !result ) throw -4;      if ( !result ) throw -4;
2717      //      //
2718      row = result->Next();      row = result->Next();
2719      //      //
2720      if ( !row && NoFrag() ){      if ( !row ){
2721          //
2722          // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
2723          //
2724          if ( IsDebug() ) printf(" The run is new \n");
2725          if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
2726          //
2727          glrun->SetID(this->AssignRunID());
2728          glrun->SetID_RUN_FRAG(0);
2729          glrun->Fill_GL_RUN_FRAGMENTS(conn);
2730          //
2731        } else {
2732          if ( IsDebug() ) printf(" The run is already present in the fragment table, relaxed %u \n",RELAXED);
2733          if ( !RELAXED ){
2734            if ( PEDANTIC ) throw -69;
2735            return;
2736          } else {
2737            glrun->SetID((UInt_t)atoll(row->GetField(0)));
2738            glrun->SetID_RUN_FRAG(0);
2739          };
2740        };
2741        //
2742        if ( chewbacca && mishead && mistrail ) goto justcheck;
2743        //
2744        // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
2745        //    
2746        if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
2747          // missing it no way we can found a piece in the frag table
2748        //        //
2749        oss.str("");        oss.str("");
2750        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 "
2751            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2752            << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "            << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2753            << " ID != " << glrun->ID            << " ID != " << glrun->ID
2754            << " 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!!
2755        //        //
2756        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());
2757        result = conn->Query(oss.str().c_str());        result = conn->Query(oss.str().c_str());
2758        //        //
2759        if ( !result ) throw -4;        if ( !result ) throw -4;
2760        //        //
       foundinrun = true;  
       //  
2761        row = result->Next();        row = result->Next();
2762        //        //
2763      };        if ( !row && NoFrag() ){
     //  
     if ( !row ){  
       if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");  
       found = false;  
     } else {  
       //  
       found = false; // default value  
       //  
       if ( IsDebug() ) printf(" Found a possible candidate, checking if it is the good one... \n");  
       //  
       // if we have both runheader and runtrailer we can check with pkt_counter:  
       //  
       if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){  
         ULong64_t chkpkt = 0;    
         ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());  
         ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));  
2764          //          //
2765          chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;            oss.str("");
2766            oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
2767                << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2768                << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
2769                << " ID != " << glrun->ID
2770                << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
2771            //
2772            if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
2773            result = conn->Query(oss.str().c_str());
2774            //
2775            if ( !result ) throw -4;
2776            //
2777            foundinrun = true;
2778            //
2779            row = result->Next();
2780          //          //
         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;  
           //  
         };  
2781        };        };
2782        if ( !found && chewbacca ) goto justcheck;        //
2783        if ( !found ){        if ( !row ){
2784            if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2785            found = false;
2786          } else {
2787          //          //
2788          // if we arrive here we were not able to decide if the two pieces matches using only the pkt counter information, we must check times and obts          found = false; // default value
2789          //          //
2790          ULong64_t chkpkt1 = 0;          if ( IsDebug() ) printf(" A Found a possible candidate, checking if it is the good one... \n");
         ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());  
         ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));  
         chkpkt1 = labs(orunh1-dbrunt1);  
         //  
         ULong64_t chkpkt2 = 0;  
         ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());  
         ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));  
         chkpkt2 = labs(orunh2-dbrunt2);  
         //  
         ULong64_t chkpkt3 = 0;  
         ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());  
         ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));  
         chkpkt3 = labs(orunh3-dbrunt3);  
2791          //          //
2792          if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){          // if we have both runheader and runtrailer we can check with pkt_counter:
2793            //    if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){          //
2794            if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){
2795              ULong64_t chkpkt = 0;  
2796              ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
2797              ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
2798            //            //
2799            if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);            chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;  
2800            //            //
2801            found = true;            if ( labs(chkpkt-pktt)<2 ){
2802                //
2803                if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
2804                //
2805                found = true;
2806                if ( IsDebug() ) printf(" where firstev is %i lastev is %i \n",firstev,lastev);
2807                //
2808              } else {
2809                //
2810                if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);            
2811                //
2812                found = false;
2813                //
2814              };
2815            };
2816            if ( !found && chewbacca ) goto justcheck;
2817            if ( !found ){
2818            //            //
2819          } 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
2820            //            //
2821            if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);            ULong64_t chkpkt1 = 0;
2822              ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
2823              ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
2824              chkpkt1 = labs(orunh1-dbrunt1);
2825            //            //
2826            found = false;            ULong64_t chkpkt2 = 0;
2827              ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());
2828              ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
2829              chkpkt2 = labs(orunh2-dbrunt2);
2830              //
2831              ULong64_t chkpkt3 = 0;
2832              ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());
2833              ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
2834              chkpkt3 = labs(orunh3-dbrunt3);
2835            //            //
2836              if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
2837                //  if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){
2838                //
2839                if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
2840                //
2841                found = true;
2842                //
2843              } else {
2844                //
2845                if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
2846                //
2847                found = false;
2848                //
2849              };
2850          };          };
2851        };        };
     };  
     //  
     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  
2852        //        //
2853        UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());        if ( found ){
2854        ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());          //
2855        UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());          // 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
2856        ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());          //
2857        if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);          if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
2858        TTree *T= 0;          //
2859        T = (TTree*)file->Get("Physics");          if ( foundinrun ){
2860        if ( !T || T->IsZombie() ) throw -16;            glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
2861        EventHeader *eh = 0;            glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
2862        PscuHeader *ph = 0;          };
2863        T->SetBranchAddress("Header", &eh);          //
2864        while ( apkt > bpkt && aobt > bobt && firstev < lastev ){          GL_RUN *glrun1 = new GL_RUN();
2865          T->GetEntry(firstev);          //
2866          ph = eh->GetPscuHeader();          //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
         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() ){  
2867          //          //
2868          //      glrun->SetID(this->AssignRunID());          oss.str("");
2869          glrun->SetID_RUN_FRAG(glrun1->GetID());          oss << " ID="<<row->GetField(0)<<";";
2870          glrun->Fill_GL_RUN(conn);          //
2871            glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos
2872            if ( IsDebug() ) printf(" there firstev is %i lastev is %i \n",firstev,lastev);
2873          //          //
2874          // set id number          // merge infos
2875          //          //
2876          glrun1->SetID_RUN_FRAG(glrun->GetID());          UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());
2877          glrun1->Fill_GL_RUN(conn);          ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
2878            UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
2879            ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
2880            if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2881            TTree *T= 0;
2882            T = (TTree*)file->Get("Physics");
2883            if ( !T || T->IsZombie() ) throw -16;
2884            EventHeader *eh = 0;
2885            PscuHeader *ph = 0;
2886            T->SetBranchAddress("Header", &eh);
2887            while ( apkt > bpkt && aobt > bobt && firstev < lastev ){
2888              T->GetEntry(firstev);
2889              ph = eh->GetPscuHeader();
2890              bpkt = PKT(ph->GetCounter());
2891              bobt = OBT(ph->GetOrbitalTime());    
2892              firstev++;
2893              if ( PEDANTIC ) throw -71;
2894            };
2895            if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
2896            //
2897            glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
2898            glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
2899            glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
2900            glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());
2901            glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());
2902            //
2903            if ( IsDebug() ) printf(" here firstev is %i lastev is %i \n",firstev,lastev);
2904            //
2905            glrun->SetEV_FROM(firstev);
2906            glrun->SetNEVENTS(lastev-firstev+1);
2907            //
2908            glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
2909            glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
2910            glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
2911            glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());
2912            glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());
2913            glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());
2914            glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());
2915            glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());
2916            glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());
2917            glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());
2918            glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());  
2919            glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());  
2920            glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());  
2921            glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());  
2922            glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());  
2923            glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());  
2924            //
2925            if ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
2926            if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
2927            //
2928            if ( !IsRunAlreadyInserted() ){
2929              //
2930              //    glrun->SetID(this->AssignRunID());
2931              glrun->SetID_RUN_FRAG(glrun1->GetID());
2932              glrun->Fill_GL_RUN(conn);
2933              //
2934              // set id number
2935              //
2936              glrun1->SetID_RUN_FRAG(glrun->GetID());
2937              glrun1->Fill_GL_RUN(conn);
2938              //
2939            };
2940            // delete old entry in fragment table
2941            //
2942            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2943            glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
2944            //
2945            delete glrun1;
2946            //
2947            //
2948            return;
2949          //          //
2950        };        };
       // delete old entry in fragment table  
       //  
       glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       //  
       delete glrun1;  
       //  
       //  
       return;  
2951        //        //
2952      };      };
2953      //      //
2954    };      if ( mistrail && ( rtlastev == lastev || chewbacca )) { // look for runtrailer (only when at the end of the file, if at the beginning and the runh is
2955    //        // 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() ){  
2956        //        //
2957        oss.str("");        oss.str("");
2958        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 "
2959            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "            << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2960            << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "            << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2961            << " ID != " << glrun->ID            << " ID != " << glrun->ID
2962            << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";            << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2963        //        //
2964        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());
2965        result = conn->Query(oss.str().c_str());        result = conn->Query(oss.str().c_str());
2966        //        //
2967        if ( !result ) throw -4;        if ( !result ) throw -4;
2968        //        //
       foundinrun = true;  
2969        row = result->Next();        row = result->Next();
2970        //        //
2971      };        if ( !row && NoFrag() ){
2972      //          //
2973      if ( !row ){          oss.str("");
2974        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 "
2975        found = false;              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
2976      } else {              << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
2977        //              << " ID != " << glrun->ID
2978        found = false; // default value              << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
2979        //          //
2980        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());
2981        //          result = conn->Query(oss.str().c_str());
2982        // if we have both runheader and runtrailer we can check with pkt_counter:          //
2983            if ( !result ) throw -4;
2984            //
2985            foundinrun = true;
2986            row = result->Next();
2987            //
2988          };
2989        //        //
2990        if ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){        if ( !row ){
2991          ULong64_t chkpkt = 0;            if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
2992          ULong64_t pktt = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));          found = false;
2993          ULong64_t pkth = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());        } else {
2994          //          //
2995          chkpkt = pkth + (ULong64_t)((UInt_t)atoll(row->GetField(1))) + 1ULL + 1ULL;            found = false; // default value
2996          //          //
2997          if ( labs(chkpkt-pktt)<2 ){          if ( IsDebug() ) printf(" B Found a possible candidate, checking if it is the good one... \n");
2998            //
2999            // if we have both runheader and runtrailer we can check with pkt_counter:
3000            //
3001            if ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){
3002              ULong64_t chkpkt = 0;  
3003              ULong64_t pktt = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
3004              ULong64_t pkth = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
3005            //            //
3006            if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);            chkpkt = pkth + (ULong64_t)((UInt_t)atoll(row->GetField(1))) + 1ULL + 1ULL;  
3007            //            //
3008            found = true;            if ( labs(chkpkt-pktt)<2 ){
3009                //
3010                if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
3011                //
3012                found = true;
3013                //
3014              } else {
3015                //
3016                if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);            
3017                //
3018                found = false;
3019                //
3020              };
3021            };
3022            if ( !found && chewbacca ) goto justcheck;
3023            if ( !found ){
3024            //            //
3025          } 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
3026            //            //
3027            if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);                  ULong64_t chkpkt1 = 0;
3028              ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
3029              ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
3030              chkpkt1 = labs(orunh1-dbrunt1);
3031            //            //
3032            found = false;            ULong64_t chkpkt2 = 0;
3033              ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNTRAILER_OBT());
3034              ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
3035              chkpkt2 = labs(orunh2-dbrunt2);
3036            //            //
3037              ULong64_t chkpkt3 = 0;
3038              ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNTRAILER_TIME());
3039              ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
3040              chkpkt3 = labs(orunh3-dbrunt3);
3041              //
3042              if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
3043                //
3044                if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
3045                //
3046                found = true;
3047                //
3048              } else {
3049                //
3050                if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
3051                //
3052                found = false;
3053                //
3054              };
3055          };          };
3056        };        };
3057        if ( !found && chewbacca ) goto justcheck;        //
3058        if ( !found ){        if ( found ){
3059            //
3060            // 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
3061            //
3062            if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
3063          //          //
3064          // 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 ){
3065              glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3066              glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
3067            };
3068          //          //
3069          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);  
3070          //          //
3071          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);  
3072          //          //
3073          ULong64_t chkpkt3 = 0;          oss.str("");
3074          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);  
3075          //          //
3076          if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){          glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runtrailer infos
3077            //          //
3078            if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);          // merge infos
3079            //          //
3080            found = true;          UInt_t apkt = PKT(glrun->GetRUNTRAILER_PKT());
3081            //          ULong64_t aobt = OBT(glrun->GetRUNTRAILER_OBT());
3082          } else {          UInt_t bpkt = PKT(glrun1->GetRUNHEADER_PKT());
3083            ULong64_t bobt = OBT(glrun1->GetRUNHEADER_OBT());
3084            if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
3085            TTree *T= 0;
3086            T = (TTree*)file->Get("Physics");
3087            if ( !T || T->IsZombie() ) throw -16;
3088            EventHeader *eh = 0;
3089            PscuHeader *ph = 0;
3090            T->SetBranchAddress("Header", &eh);
3091            while ( apkt > bpkt && aobt > bobt && lastev > 0 ){
3092              T->GetEntry(lastev);
3093              ph = eh->GetPscuHeader();
3094              apkt = PKT(ph->GetCounter());
3095              aobt = OBT(ph->GetOrbitalTime());    
3096              lastev--;
3097              if ( PEDANTIC && !RELAXED) throw -72;
3098            };
3099            if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
3100            //
3101            glrun->SetEV_TO(lastev);
3102            glrun->SetNEVENTS(lastev-firstev+1);
3103            glrun->SetPKT_COUNTER(glrun1->GetPKT_COUNTER());
3104            glrun->SetPKT_READY_COUNTER(glrun1->GetPKT_READY_COUNTER());
3105            glrun->SetRUNTRAILER_TIME(glrun1->GetRUNTRAILER_TIME());
3106            glrun->SetRUNTRAILER_OBT(glrun1->GetRUNTRAILER_OBT());
3107            glrun->SetRUNTRAILER_PKT(glrun1->GetRUNTRAILER_PKT());
3108            //
3109            glrun1->SetRUNHEADER_TIME(glrun->GetRUNHEADER_TIME());
3110            glrun1->SetRUNHEADER_OBT(glrun->GetRUNHEADER_OBT());
3111            glrun1->SetRUNHEADER_PKT(glrun->GetRUNHEADER_PKT());
3112            glrun1->SetCOMPILATIONTIMESTAMP(glrun->GetCOMPILATIONTIMESTAMP());
3113            glrun1->SetFAV_WRK_SCHEDULE(glrun->GetFAV_WRK_SCHEDULE());
3114            glrun1->SetEFF_WRK_SCHEDULE(glrun->GetEFF_WRK_SCHEDULE());
3115            glrun1->SetPRH_VAR_TRG_MODE_A(glrun->GetPRH_VAR_TRG_MODE_A());
3116            glrun1->SetPRH_VAR_TRG_MODE_B(glrun->GetPRH_VAR_TRG_MODE_B());
3117            glrun1->SetACQ_BUILD_INFO(glrun->GetACQ_BUILD_INFO());
3118            glrun1->SetACQ_VAR_INFO(glrun->GetACQ_VAR_INFO());
3119            glrun1->SetRM_ACQ_AFTER_CALIB(glrun->GetRM_ACQ_AFTER_CALIB());  
3120            glrun1->SetRM_ACQ_SETTING_MODE(glrun->GetRM_ACQ_SETTING_MODE());  
3121            glrun1->SetTRK_CALIB_USED(glrun->GetTRK_CALIB_USED());  
3122            glrun1->SetCAL_DSP_MASK(glrun->GetCAL_DSP_MASK());  
3123            glrun1->SetLAST_TIMESYNC(glrun->GetLAST_TIMESYNC());  
3124            glrun1->SetOBT_TIMESYNC(glrun->GetOBT_TIMESYNC());  
3125            //
3126            if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ) glrun1->SetPHYSENDRUN_MASK_S3S2S12(glrun->GetPHYSENDRUN_MASK_S3S2S12());
3127            if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) glrun1->SetPHYSENDRUN_MASK_S11CRC(glrun->GetPHYSENDRUN_MASK_S11CRC());
3128            //
3129            if ( !IsRunAlreadyInserted() ){
3130              //
3131              //    glrun->SetID(this->AssignRunID());
3132              //
3133              glrun->SetID_RUN_FRAG(glrun1->GetID());
3134              glrun->Fill_GL_RUN(conn);
3135            //            //
3136            if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);            // set id number
3137            //            //
3138            found = false;            glrun1->SetID_RUN_FRAG(glrun->GetID());
3139              glrun1->Fill_GL_RUN(conn);
3140            //            //
3141          };          };
3142            //
3143            // delete old entries in fragment table
3144            //
3145            glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3146            glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3147            //
3148            delete glrun1;
3149            //
3150            return;
3151            //
3152        };        };
3153          //
3154      };      };
3155      //      //
3156      if ( found ){    justcheck:
3157        //      //
3158        // 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");  
       };  
3159        //        //
3160        GL_RUN *glrun1 = new GL_RUN();        if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");
3161        //        //
3162        //      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?
3163        //        //
3164        oss.str("");        oss.str("");
3165        oss << " ID="<<row->GetField(0)<<";";        oss << " SELECT ID,ID_ROOT_L0 FROM GL_RUN WHERE "
3166              << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3167              << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3168              << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3169              << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3170              << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3171              << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3172              << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3173              << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3174              << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3175              << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3176              << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3177              << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3178              << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3179        //        //
3180        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());
3181          result = conn->Query(oss.str().c_str());
3182        //        //
3183        // merge infos        if ( !result ) throw -4;
3184        //        //
3185        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());    
3186        //        //
3187        if ( !IsRunAlreadyInserted() ){        if ( row ){
         //  
         //      glrun->SetID(this->AssignRunID());  
3188          //          //
3189          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
3190          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.
3191          //          //
3192          // set id number          // 090112 [8RED (-70): RUN ALREADY INSERTED]
3193          //          //
3194          glrun1->SetID_RUN_FRAG(glrun->GetID());          Bool_t OK = false;
3195          glrun1->Fill_GL_RUN(conn);          UInt_t IDRL2A = 0;
3196            UInt_t IDRL2B = 0;
3197            if ( chewbacca ){
3198              if ( result->GetRowCount() == 2 ){
3199                IDRL2A = (UInt_t)atoll(row->GetField(0));
3200                UInt_t IDRL0A = (UInt_t)atoll(row->GetField(1));
3201                row = result->Next();
3202                IDRL2B = (UInt_t)atoll(row->GetField(0));
3203                UInt_t IDRL0B = (UInt_t)atoll(row->GetField(1));
3204                if ( IsDebug() ) printf(" IDRL0A %u B %u IDRL2A %u B %u \n",IDRL0A,IDRL0B,IDRL2A,IDRL2B);
3205                if ( IDRL0A == IDRL0B ){
3206                  TSQLResult *result2 = 0;
3207                  TSQLRow    *row2    = 0;
3208                  oss.str("");
3209                  oss << "select PKT_NUMBER_FINAL from ROOT_TABLE_MERGING where REAL_TIME_INIT<" << chrtinit << " order by REAL_TIME_INIT desc limit 1;";
3210                  if ( IsDebug() ) printf(" Check if we are in the case RH---| small gap |---RT: query is \n %s \n",oss.str().c_str());
3211                  result2 = conn->Query(oss.str().c_str());
3212                  //
3213                  if ( !result2 ) throw -4;
3214                  //
3215                  row2 = result2->Next();
3216                  //
3217                  if ( row2 ){
3218                    UInt_t PKA = (UInt_t)atoll(row2->GetField(0));
3219                    delete result2;
3220                    oss.str("");
3221                    oss << "select PKT_NUMBER_INIT from ROOT_TABLE_MERGING where REAL_TIME_INIT>" << chrtinit << " order by REAL_TIME_INIT asc limit 1;";
3222                    if ( IsDebug() ) printf(" Check if we are in the case RH---| small gap |---RT: query is \n %s \n",oss.str().c_str());
3223                    result2 = conn->Query(oss.str().c_str());
3224                    //
3225                    if ( !result2 ) throw -4;
3226                    //
3227                    row2 = result2->Next();
3228                    //
3229                    if ( row2 ){
3230                      UInt_t PKB = (UInt_t)atoll(row2->GetField(0));
3231                      //
3232                      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);
3233                      if ( PKT(PKA)+1LL == PKT(glrun->GetRUNHEADER_PKT()) && PKT(PKB) == PKT(glrun->GetRUNTRAILER_PKT())+1LL ){
3234                        if ( IsDebug() ) printf(" Ok, we are in the case: RH---| small gap |---RT \n");
3235                        OK = true;
3236                      };
3237                    };
3238                  };                  
3239                };
3240              };      
3241            };
3242            if ( OK ){
3243              //
3244              // this is the case in which we must insert a piece of run between two fragments in the GL_RUN table
3245              //
3246              // 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 )
3247              //
3248              GL_RUN *glA = new GL_RUN();
3249              glA->Query_GL_RUN(IDRL2A,conn);
3250              //
3251              if ( glA->GetACQ_BUILD_INFO() != 0 ){
3252                //
3253                // the first piece contains a good runheader we can update all the other runs with correct infos!
3254                //
3255                oss.str("");
3256                oss << "UPDATE GL_RUN_FRAGMENTS SET "
3257                    << " RUNHEADER_TIME=" << glA->GetRUNHEADER_TIME()<< " , "
3258                    << " RUNHEADER_OBT=" << glA->GetRUNHEADER_OBT()<< " , "
3259                    << " RUNHEADER_PKT=" << glA->GetRUNHEADER_PKT()<< " , "
3260                    << " COMPILATIONTIMESTAMP=" << glA->GetCOMPILATIONTIMESTAMP()<< " , "
3261                    << " FAV_WRK_SCHEDULE=" << glA->GetFAV_WRK_SCHEDULE()<< " , "
3262                    << " EFF_WRK_SCHEDULE=" << glA->GetEFF_WRK_SCHEDULE()<< " , "
3263                    << " PRH_VAR_TRG_MODE_A=" << glA->GetPRH_VAR_TRG_MODE_A()<< " , "
3264                    << " PRH_VAR_TRG_MODE_B=" << glA->GetPRH_VAR_TRG_MODE_B()<< " , "
3265                    << " ACQ_BUILD_INFO=" << glA->GetACQ_BUILD_INFO()<< " , "
3266                    << " ACQ_VAR_INFO=" << glA->GetACQ_VAR_INFO()<< " , "
3267                    << " RM_ACQ_AFTER_CALIB=" << glA->GetRM_ACQ_AFTER_CALIB()<< " , "  
3268                    << " RM_ACQ_SETTING_MODE=" << glA->GetRM_ACQ_SETTING_MODE()<< " , "  
3269                    << " TRK_CALIB_USED=" << glA->GetTRK_CALIB_USED()<< " , "  
3270                    << " CAL_DSP_MASK=" << glA->GetCAL_DSP_MASK()<< " , "  
3271                    << " LAST_TIMESYNC=" << glA->GetLAST_TIMESYNC()<< " , ";
3272                //
3273                if ( glA->GetPHYSENDRUN_MASK_S3S2S12() )
3274                  oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12() << " , ";
3275                if ( glA->GetPHYSENDRUN_MASK_S11CRC() )
3276                  oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC() << " , ";
3277                //        
3278                oss << " OBT_TIMESYNC=" << glA->GetOBT_TIMESYNC();
3279                oss << " WHERE ID=" << glrun->GetID() << ";";
3280                if ( IsDebug() ) printf(" update with correct infos: %s\n",oss.str().c_str());
3281                conn->Query(oss.str().c_str());    
3282                //
3283              } else {
3284                //
3285                // sig no runheader, let set anyway what is possible...
3286                //
3287                oss.str("");
3288                oss << "UPDATE GL_RUN_FRAGMENTS SET "
3289                    << " RUNHEADER_TIME=" << glA->GetRUNHEADER_TIME()<< " , ";
3290                //
3291                if ( glA->GetPHYSENDRUN_MASK_S3S2S12() )
3292                  oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , ";
3293                if ( glA->GetPHYSENDRUN_MASK_S11CRC() )
3294                  oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , ";
3295                //        
3296                oss << " RUNHEADER_OBT=" << glA->GetRUNHEADER_OBT()<< " , "
3297                    << " RUNHEADER_PKT=" << glA->GetRUNHEADER_PKT();
3298                oss << " WHERE ID=" << glrun->GetID() << ";";
3299                if ( IsDebug() ) printf(" update with correct infos2: %s\n",oss.str().c_str());
3300                conn->Query(oss.str().c_str());    
3301              };
3302              //
3303              // update runheader ROOT_ID_FRAG
3304              //
3305              oss.str("");
3306              oss << "UPDATE GL_RUN SET ID_RUN_FRAG = " << glrun->GetID() << " where ID = " << IDRL2A << ";";
3307              if ( IsDebug() ) printf(" update gl_run to have cross indexing: %s\n",oss.str().c_str());
3308              conn->Query(oss.str().c_str());
3309              //
3310              // now let's look for runtrailer if any in the last run
3311              //
3312              glA->Query_GL_RUN(IDRL2B,conn);
3313              //
3314              if ( glA->GetPKT_READY_COUNTER() != 0 ){
3315                //
3316                // the first piece contains a good runtrailer we can update all the other runs with correct infos!
3317                //
3318                oss.str("");
3319                oss << "UPDATE GL_RUN_FRAGMENTS SET "
3320                    << " RUNTRAILER_TIME=" << glA->GetRUNTRAILER_TIME()<< " , "
3321                    << " RUNTRAILER_OBT=" << glA->GetRUNTRAILER_OBT()<< " , "
3322                    << " RUNTRAILER_PKT=" << glA->GetRUNTRAILER_PKT()<< " , "
3323                    << " PKT_COUNTER=" << glA->GetPKT_COUNTER()<< " , ";
3324                //
3325                if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ){
3326                  oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
3327                if ( glA->GetPHYSENDRUN_MASK_S11CRC() ) {
3328                  oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
3329                //        
3330                oss << " PKT_READY_COUNTER=" << glA->GetPKT_READY_COUNTER()
3331                    << " WHERE ID=" << glrun->GetID() << ";";
3332                if ( IsDebug() ) printf(" update with correct trailer infos: %s\n",oss.str().c_str());
3333                conn->Query(oss.str().c_str());    
3334                //
3335              } else {
3336                //
3337                // sig no runtrailer, let set anyway what is possible...
3338                //
3339                oss.str("");
3340                oss << "UPDATE GL_RUN_FRAGMENTS SET "
3341                    << " RUNTRAILER_TIME=" << glA->GetRUNTRAILER_TIME()<< " , "
3342                    << " RUNTRAILER_OBT=" << glA->GetRUNTRAILER_OBT()<< " , ";
3343                  //
3344                if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ){
3345                  oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
3346                if ( glA->GetPHYSENDRUN_MASK_S11CRC() ){
3347                  oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
3348                //        
3349                oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()
3350                    << " WHERE ID=" << glrun->GetID() << ";";
3351                if ( IsDebug() ) printf(" update with correct trailer infos2: %s\n",oss.str().c_str());
3352                conn->Query(oss.str().c_str());    
3353              };
3354              //
3355              UInt_t myi = glrun->GetID();
3356              oss.str("");
3357              oss << " ID= "<< myi;
3358              //
3359              glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);  
3360              //
3361              // fill the new run in GL_RUN
3362              //
3363              glrun->SetID_RUN_FRAG(IDRL2B);
3364              glrun->Fill_GL_RUN(conn);    
3365              glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3366              //
3367            } else {
3368              //
3369              // is just a repetition
3370              //
3371              if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");        
3372              if ( PEDANTIC ) throw -70;
3373            };
3374          //          //
3375          } else {
3376            if ( NoFrag() ){
3377              glrun->SetID_RUN_FRAG(glrun->GetID());
3378              glrun->Fill_GL_RUN(conn);    
3379              glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3380            };    
3381        };        };
       //  
       // delete old entries in fragment table  
       //  
       glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       //  
       delete glrun1;  
       //  
       return;  
       //  
3382      };      };
     //  
   };  
   //  
  justcheck:  
   //  
   if ( !found ){        
     //  
     if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");  
     //  
     // not found, has this run already inserted in the GL_RUN or in the GL_RUN_FRAGMENTS table?  
     //  
     oss.str("");  
     oss << " SELECT ID FROM GL_RUN WHERE "  
         << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("  
         << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "  
         << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("  
         << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "  
         << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("  
         << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "  
         << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "  
         << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "  
         << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("  
         << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "  
         << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("  
         << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "  
         << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";  
     //  
     if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());  
     result = conn->Query(oss.str().c_str());  
     //  
     if ( !result ) throw -4;  
     //  
     row = result->Next();  
     //  
     if ( row ){  
       if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");  
       if ( PEDANTIC ) throw -70;  
     } else {  
       if ( NoFrag() ){  
         glrun->SetID_RUN_FRAG(glrun->GetID());  
         glrun->Fill_GL_RUN(conn);        
         glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");  
       };      
     };  
   };  
3383    }; // EEE    }; // EEE
3384    //    //
3385    return;    return;
# Line 3015  void PamelaDBOperations::HandleMissingHo Line 3408  void PamelaDBOperations::HandleMissingHo
3408        glrun->SetID(this->AssignRunID());        glrun->SetID(this->AssignRunID());
3409        glrun->SetID_RUN_FRAG(0);        glrun->SetID_RUN_FRAG(0);
3410        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...
3411      };        };
3412      //      //
3413    };    };
3414    //    //
# Line 3059  Bool_t PamelaDBOperations::IsRunConsiste Line 3452  Bool_t PamelaDBOperations::IsRunConsiste
3452    if ( firstev == lastev+1 || lastev == firstev ) { // no events inside the run!    if ( firstev == lastev+1 || lastev == firstev ) { // no events inside the run!
3453      //if ( firstev <= lastev+1 ) { // no events inside the run!      //if ( firstev <= lastev+1 ) { // no events inside the run!
3454      if ( IsDebug() ) printf(" Checking but no events in the run! \n");      if ( IsDebug() ) printf(" Checking but no events in the run! \n");
3455        firstev = lastev+1; // this is necessary for files with no Physics entries, should have no influence on other files
3456      // return true is correct      // return true is correct
3457      return(true);      return(true);
3458      //      //
# Line 3068  Bool_t PamelaDBOperations::IsRunConsiste Line 3462  Bool_t PamelaDBOperations::IsRunConsiste
3462      code = eh->GetCounter();      code = eh->GetCounter();
3463      checkfirst = 0;      checkfirst = 0;
3464      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3465         if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
3466       };      };
3467      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);
3468      //      //
3469      T->GetEntry(lastev);      T->GetEntry(lastev);
3470      code = eh->GetCounter();      code = eh->GetCounter();
3471      checklast = 0;      checklast = 0;
3472      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3473         if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
3474       };      };
3475      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);
3476      //      //
3477      if ( checkfirst == checklast ){      if ( checkfirst == checklast ){
# Line 3088  Bool_t PamelaDBOperations::IsRunConsiste Line 3482  Bool_t PamelaDBOperations::IsRunConsiste
3482        //        //
3483      } else {      } else {
3484        //        //
3485        if ( IsDebug() ) printf(" There are no-phyics packets inside the run!\n");        if ( IsDebug() ) printf(" There are no-physics packets inside the run!\n");
3486        //        //
3487        // HERE WE MUST HANDLE THAT RUNS AND GO BACK        // HERE WE MUST HANDLE THAT RUNS AND GO BACK
3488        //        //
3489  //      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");
3490        //        //
3491        Bool_t emptyruns = false;        Bool_t emptyruns = false;
3492        UInt_t check = 0;        UInt_t check = 0;
3493        UInt_t lastevtemp = lastev;        UInt_t lastevtemp = lastev;
3494        UInt_t firstevno = firstev;        UInt_t firstevno = firstev;
3495          UInt_t rhchko=0;
3496          UInt_t rhchk=0;
3497        //        //
3498        for (UInt_t i=firstev; i<=lastev; i++){        for (UInt_t i=firstev; i<=lastev; i++){
3499          //          //
# Line 3106  Bool_t PamelaDBOperations::IsRunConsiste Line 3502  Bool_t PamelaDBOperations::IsRunConsiste
3502          //          //
3503          check = 0;          check = 0;
3504          //          //
3505    
3506            // if we have a runheader set lastev then exit
3507            //
3508          for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){          for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
3509            if ( strcmp(*Iter,"Physics") ) check += code->Get(GetPacketType(*Iter));            if ( strcmp(*Iter,"Physics") ) check += code->Get(GetPacketType(*Iter));
3510          };          };
3511            // check here if we have a runheader
3512            rhchko = rhchk;  
3513            rhchk = code->Get(GetPacketType("RunHeader"));    
3514          //          //
3515          if ( checkfirst < check || i == lastev ){          if ( checkfirst < check || i == lastev ){
3516            //            //
# Line 3184  Bool_t PamelaDBOperations::IsRunConsiste Line 3586  Bool_t PamelaDBOperations::IsRunConsiste
3586            };            };
3587            //                  //      
3588            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
3589              this->SetPhysEndRunVariables();
3590            //            //
3591            if ( chminentry == firstentry  ){ // EEE            if ( chminentry == firstentry  ){ // EEE
3592              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");
3593  //              //
3594  //          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
3595  //              //
   
   
   
   
   
   
   
   
   
   
   
   
   
   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  
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
   
3596    
3597                mishead = true;
3598    
3599    
3600                UInt_t rhfirstev = firstentry;
3601                //  UInt_t rtlastev = lastentry;
3602                Bool_t found = false;
3603                Bool_t foundinrun = false;
3604                //
3605                TSQLResult *result = 0;
3606                TSQLRow    *row    = 0;
3607                //
3608                stringstream oss;
3609                oss.str("");
3610                //
3611                // we have now the good first piece of a run, fill the glrun object
3612                //
3613                //  if ( rhfirstev != firstev && !mishead ) mishead = true;
3614                //  if ( rtlastev != lastev && !mistrail ) mistrail = true;
3615                //
3616                //  this->FillClass(mishead,mistrail,firstev,lastev);
3617                //
3618                if ( IsDebug() ) printf("zz The run is good, is it the other piece in the GL_RUN_FRAGMENTS table?\n");
3619                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());
3620                //
3621                // First of all insert the run in the fragment table...
3622                //
3623                oss.str("");
3624                oss << " SELECT ID FROM GL_RUN_FRAGMENTS WHERE "
3625                    << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3626                    << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3627                    << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3628                    << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3629                    << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3630                    << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3631                    << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3632                    << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3633                    << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3634                    << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3635                    << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3636                    << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3637                    << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3638                //
3639                if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3640                result = conn->Query(oss.str().c_str());
3641                //
3642                if ( !result ) throw -4;
3643                //
3644                row = result->Next();
3645                //
3646                if ( !row ){
3647                  //
3648                  // no, insert this run in the GL_RUN_FRAGMENTS table (check if exist before!)
3649                  //
3650                  if ( IsDebug() ) printf(" The run is new \n");
3651                  if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
3652                  //
3653                  glrun->SetID(this->AssignRunID());
3654                  glrun->SetID_RUN_FRAG(0);
3655                  glrun->Fill_GL_RUN_FRAGMENTS(conn);
3656                  //
3657                } else {
3658                  if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
3659                  if ( PEDANTIC ) throw -69;
3660                  //    return;
3661                };
3662                //
3663                if ( chewbacca && mishead && mistrail ) goto zjustcheck;
3664                //
3665                // can we find the other piece of the run in the GL_RUN_FRAGMENTS table?
3666                //
3667                if ( mishead && ( rhfirstev == firstev || chewbacca ) ) { // look for runheader (only when at the beginning of the file, if at the end and the runh is
3668                  // missing it no way we can found a piece in the frag table
3669                  //
3670                  oss.str("");
3671                  oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN_FRAGMENTS WHERE "
3672                      << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3673                      << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3674                      << " ID != " << glrun->ID
3675                      << " ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
3676                  //
3677                  if ( IsDebug() ) printf(" look for runheader in the fragments table: query is \n %s \n",oss.str().c_str());
3678                  result = conn->Query(oss.str().c_str());
3679                  //
3680                  if ( !result ) throw -4;
3681                  //
3682                  row = result->Next();
3683                  //
3684                  if ( !row && NoFrag() ){
3685                    //
3686                    oss.str("");
3687                    oss << " SELECT ID,TRK_CALIB_USED,RUNTRAILER_TIME,RUNTRAILER_OBT,RUNHEADER_PKT,RUNTRAILER_PKT FROM GL_RUN WHERE "
3688                        << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
3689                        << " RUNHEADER_TIME <= " << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3690                        << " ID != " << glrun->ID
3691                        << " AND ID=ID_RUN_FRAG ORDER BY RUNHEADER_TIME DESC LIMIT 1;"; // DESC NOT ASC!!
3692                    //
3693                    if ( IsDebug() ) printf(" look for runheader in the GL_RUN table: query is \n %s \n",oss.str().c_str());
3694                    result = conn->Query(oss.str().c_str());
3695                    //
3696                    if ( !result ) throw -4;
3697                    //
3698                    foundinrun = true;
3699                    //
3700                    row = result->Next();
3701                    //
3702                  };
3703                  //
3704                  if ( !row ){
3705                    if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
3706                    found = false;
3707                  } else {
3708                    //
3709                    found = false; // default value
3710                    //
3711                    if ( IsDebug() ) printf(" C Found a possible candidate, checking if it is the good one... \n");
3712                    //
3713                    // if we have both runheader and runtrailer we can check with pkt_counter:
3714                    //
3715                    if ( !mistrail && (UInt_t)atoll(row->GetField(1)) != 0 ){
3716                      ULong64_t chkpkt = 0;
3717                      ULong64_t pktt = (ULong64_t)PKT(glrun->GetRUNTRAILER_PKT());
3718                      ULong64_t pkth = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
3719                      //
3720                      chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;
3721                      //
3722                      if ( labs(chkpkt-pktt)<2 ){
3723                        //
3724                        if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt);
3725                        //
3726                        found = true;
3727                        //
3728                      } else {
3729                        //
3730                        if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt);
3731                        //
3732                        found = false;
3733                        //
3734                      };
3735                    };
3736                    if ( !found && chewbacca ) goto zjustcheck;
3737                    if ( !found ){
3738                      //
3739                      // 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
3740                      //
3741                      ULong64_t chkpkt1 = 0;
3742                      ULong64_t orunh1 = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
3743                      ULong64_t dbrunt1 = (ULong64_t)PKT((UInt_t)atoll(row->GetField(5)));
3744                      chkpkt1 = labs(orunh1-dbrunt1);
3745                      //
3746                      ULong64_t chkpkt2 = 0;
3747                      ULong64_t orunh2 = (ULong64_t)OBT(glrun->GetRUNHEADER_OBT());
3748                      ULong64_t dbrunt2 = (ULong64_t)OBT((UInt_t)atoll(row->GetField(3)));
3749                      chkpkt2 = labs(orunh2-dbrunt2);
3750                      //
3751                      ULong64_t chkpkt3 = 0;
3752                      ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNHEADER_TIME());
3753                      ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
3754                      chkpkt3 = labs(orunh3-dbrunt3);
3755                      //
3756                      if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
3757                        //    if ( chkpkt1 < 100 && chkpkt2 < 30000 && chkpkt3 < 30 ){
3758                        //
3759                        if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3);
3760                        //
3761                        found = true;
3762                        //
3763                      } else {
3764                        //
3765                        if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3);
3766                        //
3767                        found = false;
3768                        //
3769                      };
3770                    };
3771                  };
3772                  //
3773                  if ( found ){
3774                    //
3775                    // 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
3776                    //
3777                    if ( IsDebug() ) printf(" now you can handle the piece of the run \n ");
3778                    //
3779                    if ( foundinrun ){
3780                      glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
3781                      glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
3782                    };
3783                    //
3784                    GL_RUN *glrun1 = new GL_RUN();
3785                    //
3786                    //      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
3787                    //
3788                    oss.str("");
3789                    oss << " ID="<<row->GetField(0)<<";";
3790                    //
3791                    glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runheader infos
3792                    //
3793                    // merge infos
3794                    //
3795                    UInt_t apkt = PKT(glrun1->GetRUNTRAILER_PKT());
3796                    ULong64_t aobt = OBT(glrun1->GetRUNTRAILER_OBT());
3797                    UInt_t bpkt = PKT(glrun->GetRUNHEADER_PKT());
3798                    ULong64_t bobt = OBT(glrun->GetRUNHEADER_OBT());
3799                    if ( IsDebug() ) printf(" Check overlapping events: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
3800                    TTree *T= 0;
3801                    T = (TTree*)file->Get("Physics");
3802                    if ( !T || T->IsZombie() ) throw -16;
3803                    EventHeader *eh = 0;
3804                    PscuHeader *ph = 0;
3805                    T->SetBranchAddress("Header", &eh);
3806                    while ( apkt > bpkt && aobt > bobt && firstev < lastev ){
3807                      T->GetEntry(firstev);
3808                      ph = eh->GetPscuHeader();
3809                      bpkt = PKT(ph->GetCounter());
3810                      bobt = OBT(ph->GetOrbitalTime());
3811                      firstev++;
3812                      if ( PEDANTIC ) throw -71;
3813                    };
3814                    if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu firstev is %i\n",apkt,bpkt,aobt,bobt,firstev);
3815                    //
3816                    glrun1->SetPKT_COUNTER(glrun->GetPKT_COUNTER());
3817                    glrun1->SetPKT_READY_COUNTER(glrun->GetPKT_READY_COUNTER());
3818                    glrun1->SetRUNTRAILER_TIME(glrun->GetRUNTRAILER_TIME());
3819                    glrun1->SetRUNTRAILER_OBT(glrun->GetRUNTRAILER_OBT());
3820                    glrun1->SetRUNTRAILER_PKT(glrun->GetRUNTRAILER_PKT());
3821                    //
3822                    glrun->SetEV_FROM(firstev);
3823                    glrun->SetNEVENTS(lastev-firstev+1);
3824                    //
3825                    glrun->SetRUNHEADER_TIME(glrun1->GetRUNHEADER_TIME());
3826                    glrun->SetRUNHEADER_OBT(glrun1->GetRUNHEADER_OBT());
3827                    glrun->SetRUNHEADER_PKT(glrun1->GetRUNHEADER_PKT());
3828                    glrun->SetCOMPILATIONTIMESTAMP(glrun1->GetCOMPILATIONTIMESTAMP());
3829                    glrun->SetFAV_WRK_SCHEDULE(glrun1->GetFAV_WRK_SCHEDULE());
3830                    glrun->SetEFF_WRK_SCHEDULE(glrun1->GetEFF_WRK_SCHEDULE());
3831                    glrun->SetPRH_VAR_TRG_MODE_A(glrun1->GetPRH_VAR_TRG_MODE_A());
3832                    glrun->SetPRH_VAR_TRG_MODE_B(glrun1->GetPRH_VAR_TRG_MODE_B());
3833                    glrun->SetACQ_BUILD_INFO(glrun1->GetACQ_BUILD_INFO());
3834                    glrun->SetACQ_VAR_INFO(glrun1->GetACQ_VAR_INFO());
3835                    glrun->SetRM_ACQ_AFTER_CALIB(glrun1->GetRM_ACQ_AFTER_CALIB());
3836                    glrun->SetRM_ACQ_SETTING_MODE(glrun1->GetRM_ACQ_SETTING_MODE());
3837                    glrun->SetTRK_CALIB_USED(glrun1->GetTRK_CALIB_USED());
3838                    glrun->SetCAL_DSP_MASK(glrun1->GetCAL_DSP_MASK());
3839                    glrun->SetLAST_TIMESYNC(glrun1->GetLAST_TIMESYNC());
3840                    glrun->SetOBT_TIMESYNC(glrun1->GetOBT_TIMESYNC());
3841                    //
3842                    if ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
3843                    if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
3844                    //
3845                    if ( !IsRunAlreadyInserted() ){
3846                      //
3847                      //      glrun->SetID(this->AssignRunID());
3848                      glrun->SetID_RUN_FRAG(glrun1->GetID());
3849                      glrun->Fill_GL_RUN(conn);
3850                      //
3851                      // set id number
3852                      //
3853                      glrun1->SetID_RUN_FRAG(glrun->GetID());
3854                      glrun1->Fill_GL_RUN(conn);
3855                      //
3856                    };
3857                    // delete old entry in fragment table
3858                    //
3859                    glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3860                    glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3861                    //
3862                    delete glrun1;
3863                    //
3864                    //
3865                    //      return;
3866                    //
3867                  };
3868                  //
3869                };
3870                //
3871                //
3872              zjustcheck:
3873                //
3874                if ( !found ){
3875                  //
3876                  if ( IsDebug() ) printf(" not found, check if we have already processed the file \n ");
3877                  //
3878                  // not found, has this run already inserted in the GL_RUN or in the GL_RUN_FRAGMENTS table?
3879                  //
3880                  oss.str("");
3881                  oss << " SELECT ID FROM GL_RUN WHERE "
3882                      << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND ("
3883                      << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
3884                      << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
3885                      << " RUNHEADER_OBT>=" << glrun->GetRUNHEADER_OBT() << " OR "
3886                      << " RUNHEADER_PKT>=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3887                      << " RUNTRAILER_OBT<=" << glrun->GetRUNTRAILER_OBT() << " OR "
3888                      << " RUNTRAILER_PKT<=" << glrun->GetRUNTRAILER_PKT() << ") ) OR "
3889                      << " (RUNHEADER_TIME<=" << (UInt_t)glrun->GetRUNHEADER_TIME() << " AND "
3890                      << " RUNTRAILER_TIME>=" << (UInt_t)glrun->GetRUNTRAILER_TIME() <<" AND ("
3891                      << " RUNHEADER_OBT<=" << glrun->GetRUNHEADER_OBT() << " OR "
3892                      << " RUNHEADER_PKT<=" << glrun->GetRUNHEADER_PKT() << ") AND ("
3893                      << " RUNTRAILER_OBT>=" << glrun->GetRUNTRAILER_OBT() << " OR "
3894                      << " RUNTRAILER_PKT>=" << glrun->GetRUNTRAILER_PKT() << ") ));";
3895                  //
3896                  if ( IsDebug() ) printf(" check if run has been inserted: query is \n %s \n",oss.str().c_str());
3897                  result = conn->Query(oss.str().c_str());
3898                  //
3899                  if ( !result ) throw -4;
3900                  //
3901                  row = result->Next();
3902                  //
3903                  if ( row ){
3904                    if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");
3905                    if ( PEDANTIC ) throw -70;
3906                  } else {
3907                    if ( NoFrag() ){
3908                      glrun->SetID_RUN_FRAG(glrun->GetID());
3909                      glrun->Fill_GL_RUN(conn);
3910                      glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
3911                    };
3912                  };
3913                }; // EEE
3914    
3915    
3916            } else {            } else {
3917            if ( !IsRunAlreadyInserted() ){              if ( !IsRunAlreadyInserted() ){
3918              glrun->SetID(this->AssignRunID());                glrun->SetID(this->AssignRunID());
3919              glrun->SetID_RUN_FRAG(0);                glrun->SetID_RUN_FRAG(0);
3920              glrun->Fill_GL_RUN(conn);                glrun->Fill_GL_RUN(conn);
3921            };              };
3922            }; // EEE            }; // EEE
3923            //            //
3924            firstevno = lastentry + 1;            firstevno = lastentry + 1;
# Line 3564  Bool_t PamelaDBOperations::IsRunConsiste Line 3927  Bool_t PamelaDBOperations::IsRunConsiste
3927            //            //
3928          };          };
3929          //          //
3930            if ( i > firstev ){
3931              if ( rhchko != rhchk ){
3932                if ( IsDebug() ) printf("oh oh... we have a runheader! stop here and handle later the remaining piece\n");
3933                lastev = i;
3934                return(false);
3935              };
3936            };
3937            //
3938          if ( check == checklast && i != lastev ){          if ( check == checklast && i != lastev ){
3939            lastevtemp = i - 1;            lastevtemp = i - 1;
3940            i = lastev - 1;            i = lastev - 1;
# Line 3647  void PamelaDBOperations::HandleSuspiciou Line 4018  void PamelaDBOperations::HandleSuspiciou
4018      code = eh->GetCounter();      code = eh->GetCounter();
4019      checkfirst = 0;      checkfirst = 0;
4020      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
4021         if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
4022         if ( !strcmp(*Iter,"RunHeader") ) nrunh1++;        if ( !strcmp(*Iter,"RunHeader") ) nrunh1++;
4023       };      };
4024      if ( IsDebug() ) printf(" Check first is %i \n",checkfirst);      if ( IsDebug() ) printf(" Check first is %i \n",checkfirst);
4025      //      //
4026      T->GetEntry(lastev);      T->GetEntry(lastev);
4027      code = eh->GetCounter();      code = eh->GetCounter();
4028      checklast = 0;      checklast = 0;
4029      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){      for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
4030         if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));        if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
4031       };      };
4032      if ( IsDebug() ) printf(" Check last is %i \n",checklast);      if ( IsDebug() ) printf(" Check last is %i \n",checklast);
4033      //      //
4034      if ( checkfirst == checklast ){      if ( checkfirst == checklast ){
# Line 3769  void PamelaDBOperations::HandleSuspiciou Line 4140  void PamelaDBOperations::HandleSuspiciou
4140            };            };
4141            //                  //      
4142            this->SetCommonGLRUN(firstTime,lastTime);            this->SetCommonGLRUN(firstTime,lastTime);
4143              this->SetPhysEndRunVariables();
4144            //            //
4145            if ( !IsRunAlreadyInserted() ){            if ( !IsRunAlreadyInserted() ){
4146              glrun->SetID(this->AssignRunID());              glrun->SetID(this->AssignRunID());
# Line 3808  void PamelaDBOperations::HandleSuspiciou Line 4180  void PamelaDBOperations::HandleSuspiciou
4180              if ( IsDebug() ) printf(" We have the runtrailer \n");              if ( IsDebug() ) printf(" We have the runtrailer \n");
4181              //                  //    
4182              this->SetCommonGLRUN(firstTime,lastTime);              this->SetCommonGLRUN(firstTime,lastTime);
4183                this->SetPhysEndRunVariables();
4184              //              //
4185              if ( !IsRunAlreadyInserted() ){              if ( !IsRunAlreadyInserted() ){
4186                glrun->SetID(this->AssignRunID());                glrun->SetID(this->AssignRunID());
# Line 4382  Int_t PamelaDBOperations::insertCALOPULS Line 4755  Int_t PamelaDBOperations::insertCALOPULS
4755   * Fill the GL_TRK_CALIB table   * Fill the GL_TRK_CALIB table
4756   */   */
4757  void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){  void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){
4758    //      
4759    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;  
4760      //      //
4761    } else {      glcal->ID         = 0;
4762        glcal->ID_ROOT_L0 = GetID_ROOT();
4763        glcal->EV_ROOT_CALIBTRK1 = t1;
4764        glcal->EV_ROOT_CALIBTRK2 = t2;
4765        glcal->FROM_TIME = fromtime;
4766        glcal->TO_TIME   = 0;
4767        glcal->OBT1      = obt1;
4768        glcal->OBT2      = obt2;
4769        glcal->PKT1      = pkt1;
4770        glcal->PKT2      = pkt2;
4771        glcal->BOOT_NUMBER = GetBOOTnumber();
4772        glcal->VALIDATION = valid;
4773      //      //
4774      // we have to insert a new calibration, check where to place it      HandleTRK_CALIB(glcal);
4775      //      //
4776      oss.str("");      delete glcal;
4777      oss << " SELECT ID,TO_TIME FROM GL_TRK_CALIB WHERE "  }
4778          << " FROM_TIME < "<< fromtime << " AND "  /**
4779          << " TO_TIME > "<< fromtime << ";";   * Fill the GL_TRK_CALIB table
4780     */
4781    void PamelaDBOperations::HandleTRK_CALIB(GL_TRK_CALIB *glcal){
4782    
4783        Bool_t pk1 = (glcal->OBT1>0&&glcal->PKT1>0);
4784        Bool_t pk2 = (glcal->OBT2>0&&glcal->PKT2>0);
4785        UInt_t boot_number = glcal->BOOT_NUMBER;
4786        UInt_t obt1 = glcal->OBT1;
4787        UInt_t obt2 = glcal->OBT2;
4788        UInt_t pkt1 = glcal->PKT1;
4789        UInt_t pkt2 = glcal->PKT2;
4790        UInt_t fromtime = glcal->FROM_TIME;
4791        UInt_t totime = 0;
4792        UInt_t idroot = glcal->ID_ROOT_L0;
4793        UInt_t t1 = glcal->EV_ROOT_CALIBTRK1;
4794        UInt_t t2 = glcal->EV_ROOT_CALIBTRK2;
4795        UInt_t valid = glcal->VALIDATION;
4796      //      //
4797      if ( IsDebug() ) printf(" Check where to place the trk calibration: query is \n %s \n",oss.str().c_str());      TSQLResult *result = 0;
4798      result = conn->Query(oss.str().c_str());      TSQLRow    *row    = 0;
4799      //      //
4800      if ( !result ) throw -4;      stringstream oss;
4801        oss.str("");
4802      //      //
     row = result->Next();  
4803      //      //
4804      if ( !row ){      if ( !pk1 && !pk2 ){
4805        //          if ( IsDebug() ) printf(" Cannot handle trk calibration with both packet missing!\n");
4806        // 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;  
       //  
4807      };      };
4808      //      //
4809      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 << "',";  
4810      //      //
4811      if ( !pk1 ){      oss.str("");
4812        oss << "NULL,";      oss << " SELECT ID FROM GL_TRK_CALIB WHERE "
4813            << " BOOT_NUMBER = "<< boot_number; //
4814        oss << " AND FROM_TIME="<<fromtime; /// NEWNEWNEW -- VA BENE ?!?!?!?!
4815        oss << " AND ( ( ";  
4816        if ( pk1 ){
4817            oss << " OBT1 = "<< obt1 << " AND "
4818                << " PKT1 = "<< pkt1
4819                << " ) OR ( ";
4820      } else {      } else {
4821        oss << "'"          oss << " PKT1 = "<< pkt2-1
4822            << t1 << "',";              << " ) OR ( ";  
4823      };      };      
4824      //      if ( pk2 ){
4825      if ( !pk2 ){          oss << " OBT2 = "<< obt2 << " AND "
4826        oss << "NULL,'";              << " PKT2 = "<< pkt2;
4827      } else {      } else {
4828        oss << "'"          oss << " PKT2 = "<< pkt1+1;
4829            << t2 << "','";      };      
4830      };      oss << " ) );";  
     //  
     oss << fromtime << "','"  
         << totime << "','"  
         << obt1 << "','"  
         << pkt1 << "','"  
         << obt2 << "','"  
         << pkt2 << "','"  
         << this->GetBOOTnumber() << "','"  
         << valid << "');";  
     //  
     if ( IsDebug() ) printf(" Insert the new trk calibration: query is \n %s \n",oss.str().c_str());  
4831      //      //
4832        if ( IsDebug() ) printf(" Check if the trk calibration has already been inserted: query is \n %s \n",oss.str().c_str());
4833      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
4834      //      //
4835      if ( !result ) throw -4;      if ( !result ) throw -4;
4836      //      //
4837    };      row = result->Next();
   //  
 };  
   
 /**  
  * Scan tracker calibrations packets, fill the GL_TRK_CALIB table  
  */  
 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++){  
     //  
     pret2 = t2;  
     tr1->GetEntry(t1);  
     //  
     ph1 = eh1->GetPscuHeader();  
     obt1 = ph1->GetOrbitalTime();    
     pkt1 = ph1->GetCounter();    
     fromtime = this->GetAbsTime(ph1->GetOrbitalTime());    
     //  
 //     valid = 1;  
 //     //  
 //     if ( caltrk1->unpackError != 0 && caltrk1->good0 == 0 ) valid = 0;// CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT1  
     //  
4838      //      //
4839      if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->PKT(pkt1) <= upperpkt && this->OBT(obt1) >= this->OBT(obtfirst) && this->OBT(obt1) <= upperobt ){      if ( row ){
       //    if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->OBT(obt1) >= this->OBT(obtfirst) ){  
       //  
       if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u \n",fromtime,obt1,pkt1);  
       //        
       valid = ValidateTrkCalib( caltrk1, eh1 );  
       if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;  
       //  
       // Do we have the second calibration packet?  
       //  
       while ( t2t1cal < t1+1 ){ // get the calibration packet2 that follows the packet1  
4840          //          //
4841          t2++;          if ( IsDebug() ) printf(" Trk calibration already inserted in the DB\n");
4842            if ( PEDANTIC ) throw -80;
4843          //          //
4844          pret2 = t2 - 1; // EMILIANO      } else {
4845          //          //
4846          if ( t2 < nevents2 ){          // we have to insert a new calibration, check where to place it
4847            tr2->GetEntry(t2);          //
4848            codt2 = eh2->GetCounter();          oss.str("");
4849            t2t1cal = codt2->Get(pctp->CalibTrk1);          oss << " SELECT ID,TO_TIME FROM GL_TRK_CALIB WHERE "
4850            //              << " FROM_TIME < "<< fromtime << " AND "
4851            ph2 = eh2->GetPscuHeader();              << " TO_TIME > "<< fromtime << ";";
4852            obt2 = ph2->GetOrbitalTime();            //
4853            pkt2 = ph2->GetCounter();            if ( IsDebug() ) printf(" Check where to place the trk calibration: query is \n %s \n",oss.str().c_str());
4854            //          result = conn->Query(oss.str().c_str());
4855            if ( IsDebug() ) printf(" This is a trk calibration2 at obt %u pkt %u t2 is %u , t2t1cal is %u \n",obt2,pkt2,t2,t2t1cal);                //
4856  //        if ( caltrk2->unpackError != 0 || caltrk2->good0 == 0 ) valid = 0; // CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT2          if ( !result ) throw -4;
4857            //                //
4858            row = result->Next();
4859            //
4860            if ( !row ){
4861                //
4862                // no calibrations in the db contain our calibration
4863                //
4864                if ( IsDebug() ) printf(" Calibration with fromtime lower than others to be inserted in the DB\n");
4865                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
4866                //
4867                oss.str("");
4868                oss << " SELECT FROM_TIME FROM GL_TRK_CALIB WHERE "
4869                    << " FROM_TIME > "<< fromtime << " ORDER BY FROM_TIME ASC LIMIT 1;";
4870                //
4871                if ( IsDebug() ) printf(" Check the upper limit for calibration: query is \n %s \n",oss.str().c_str());
4872                result = conn->Query(oss.str().c_str());
4873                //
4874                if ( !result ) throw -4;
4875                //
4876                row = result->Next();
4877                if ( !row ){
4878                    totime = numeric_limits<UInt_t>::max();
4879                } else {
4880                    totime = (UInt_t)atoll(row->GetField(0));
4881                };
4882                //
4883          } else {          } else {
4884            //              //
4885            // running out of vector without finding the corresponding calibration, sig              // determine upper and lower limits and make space for the new calibration
4886            //              //
4887            if ( IsDebug() ) printf(" t2 >= nevents2 \n");              totime = (UInt_t)atoll(row->GetField(1));
4888            pret2 = t2;              //
4889            obt2 = 0;              oss.str("");
4890            //      pkt2 = pkt1+2;              oss << " UPDATE GL_TRK_CALIB SET "  
4891            pkt2 = 0;                  << " TO_TIME = "<< fromtime << " WHERE "  // NOTICE: to_time is equal to from_time of the calibration before, so the interval is: [from_time,to_time[
4892            t2t1cal = t1+1;                  << " ID = "<< row->GetField(0) << ";";
4893                //
4894                if ( IsDebug() ) printf(" Make space for the new trk calibration: query is \n %s \n",oss.str().c_str());
4895                result = conn->Query(oss.str().c_str());
4896                //
4897                if ( !result ) throw -4;
4898                //
4899          };          };
         //      if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) && (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){  
   
         // 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(" running out of vector without finding the corresponding calibration, sig \n");  
 //        //  
 //        // running out of vector without finding the corresponding calibration, sig  
 //        //  
 //        pret2 = t2;  
 //        obt2 = 0;  
 //        //      pkt2 = pkt1+2;  
 //        pkt2 = 0;  
 //        t2t1cal = t1+1;  
 //      };  
   
   
4900          //          //
4901        };          oss.str("");
4902        //          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) "
4903        if ( IsDebug() ) printf(" Check if trk calibration2 exists \n");              << " VALUES (NULL,' "
4904        //              << idroot << "',";
       // 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");  
4905          //          //
4906          // running out of vector without finding the corresponding calibration, sig          if ( !pk1 ){
4907                oss << "NULL,";
4908            } else {
4909                oss << "'"
4910                    << t1 << "',";
4911            };
4912          //          //
4913          pret2 = t2;          if ( !pk2 ){
4914          obt2 = 0;              oss << "NULL,'";
4915          pkt2 = 0;          } else {
4916        };              oss << "'"
4917        //                  << t2 << "','";
4918        // The calibration is good          };
4919        //          //
4920        if ( this->PKT(pkt2) == this->PKT(pkt1)+1 ){          oss << fromtime << "','"
4921                << totime << "','"
4922                << obt1 << "','"
4923                << pkt1 << "','"
4924                << obt2 << "','"
4925                << pkt2 << "','"
4926                << boot_number << "','"
4927                << valid << "');";
4928            //
4929            if ( IsDebug() ) printf(" Insert the new trk calibration: query is \n %s \n",oss.str().c_str());
4930            //
4931            result = conn->Query(oss.str().c_str());
4932          //          //
4933          if ( IsDebug() ) printf(" Found trk calibration2 at obt %u pkt %u t2 is %u \n",obt2,pkt2,t2);          if ( !result ) throw -4;
         if ( IsDebug() ) printf(" The trk calibration2 at obt %u pkt %u t2 is %u is good \n",obt2,pkt2,t2);  
4934          //          //
4935          UInt_t valid2 = ValidateTrkCalib( caltrk2, eh2 );      };
4936          if ( IsDebug() ) cout << " pkt2 validation --> "<<valid2<<endl;      
4937          valid = valid & valid2;      oss.str("");
4938        oss << " SELECT ID FROM GL_TRK_CALIB ORDER BY ID DESC LIMIT 1 ;";  
4939        if ( IsDebug() ) cout << oss.str().c_str() << endl;
4940        result = conn->Query(oss.str().c_str());
4941        if ( !result ) throw -4;;
4942        row = result->Next();
4943        if(row)glcal->ID = (UInt_t)atoll(row->GetField(0));
4944        //
4945        delete result; // mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
4946        //
4947    };
4948    
4949    /**
4950     * Scan tracker calibrations packets, fill the GL_TRK_CALIB table
4951     */
4952    Int_t PamelaDBOperations::insertTRK_CALIB(){
4953        //
4954        CalibTrk1Event *caltrk1 = 0;
4955        CalibTrk2Event *caltrk2 = 0;
4956        TTree *tr1 = 0;
4957        TTree *tr2 = 0;
4958        EventHeader *eh1 = 0;
4959        PscuHeader *ph1 = 0;
4960        EventHeader *eh2 = 0;
4961        PscuHeader *ph2 = 0;
4962        //
4963        PacketType *pctp=0;
4964        EventCounter *codt2=0;
4965        //
4966        Int_t nevents1 = 0;
4967        Int_t nevents2 = 0;
4968        //
4969        fromtime = 0;
4970        //
4971        obt1 = 0;
4972        pkt1 = 0;
4973        obt2 = 0;
4974        pkt2 = 0;
4975        //
4976        tr1 = (TTree*)file->Get("CalibTrk1");
4977        if ( !tr1 || tr1->IsZombie() ) throw -22;
4978        tr2 = (TTree*)file->Get("CalibTrk2");
4979        if ( !tr2 || tr2->IsZombie() ) throw -23;
4980        //
4981        tr1->SetBranchAddress("CalibTrk1", &caltrk1);
4982        tr1->SetBranchAddress("Header", &eh1);
4983        nevents1 = tr1->GetEntries();
4984        tr2->SetBranchAddress("CalibTrk2", &caltrk2);
4985        tr2->SetBranchAddress("Header", &eh2);
4986        nevents2 = tr2->GetEntries();
4987        //
4988        if ( !nevents1 && !nevents2 ) return(1);
4989        //
4990        t2 = -1;
4991        Int_t pret2 = 0;
4992        Int_t t2t1cal = 0;
4993        //
4994        bool MISSING_pkt1 = true;
4995        bool MISSING_pkt2 = true;
4996        int  ncalib = 0;
4997        bool try_to_recover = false;
4998        //
4999        for (t1=0; t1 < nevents1; t1++){//loop over packet1
5000          //          //
5001          // Handle good calib          pret2 = t2;
5002            tr1->GetEntry(t1);
5003          //          //
5004          this->HandleTRK_CALIB(true,true);          ph1 = eh1->GetPscuHeader();
5005            obt1 = ph1->GetOrbitalTime();  
5006            pkt1 = ph1->GetCounter();  
5007            fromtime = GetAbsTime(ph1->GetOrbitalTime());  
5008          //          //
5009          // Check for missing calibtrk1          // chek if the packet number and obt are consistent with the other packets ???
5010          //          //
5011          if ( t2 != pret2+1 ){          if ( PKT(pkt1) >= PKT(pktfirst) && PKT(pkt1) <= upperpkt && OBT(obt1) >= OBT(obtfirst) && OBT(obt1) <= upperobt ){
5012            //              //    if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->OBT(obt1) >= this->OBT(obtfirst) ){
           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);  
           //  
           while ( t2 > pret2+1 ){  
             //  
             // handle missing calib1  
5013              //              //
5014              pret2++;              if ( IsDebug() ) printf("\n Trk calibration1 %u at time %u obt %u pkt %u \n",t1,fromtime,obt1,pkt1);
5015                //      
5016                valid = ValidateTrkCalib( caltrk1, eh1 );
5017                if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;
5018              //              //
5019              obt1 = 0;              // Do we have the second calibration packet?
             pkt1 = 0;  
5020              //              //
5021              tr2->GetEntry(pret2);              if ( IsDebug() ) cout << " Loop over calibration2 to search associated calibration: "<<endl;
5022              ph2 = eh2->GetPscuHeader();              while ( t2t1cal < t1+1 ){ // get the calibration packet2 that follows the packet1
5023              obt2 = ph2->GetOrbitalTime();                    //
5024              pkt2 = ph2->GetCounter();                    t2++;
5025                    //
5026                    pret2 = t2 - 1; // EMILIANO
5027                    //
5028                    if ( t2 < nevents2 ){
5029                        tr2->GetEntry(t2);
5030                        codt2 = eh2->GetCounter();
5031                        t2t1cal = codt2->Get(pctp->CalibTrk1);
5032                        //
5033                        ph2 = eh2->GetPscuHeader();
5034                        obt2 = ph2->GetOrbitalTime();  
5035                        pkt2 = ph2->GetCounter();  
5036                        //
5037                        if ( IsDebug() ) printf(" >> trk calibration2 at obt %u pkt %u t2 is %u , t2t1cal is %u \n",obt2,pkt2,t2,t2t1cal);    
5038                        //    if ( caltrk2->unpackError != 0 || caltrk2->good0 == 0 ) valid = 0; // CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT2
5039                        //    
5040                    } else {
5041                        //
5042                        // running out of vector without finding the corresponding calibration, sig
5043                        //
5044                        if ( IsDebug() ) printf(" t2 >= nevents2 \n");
5045                        pret2 = t2;
5046                        obt2 = 0;
5047                        //    pkt2 = pkt1+2;
5048                        pkt2 = 0;
5049                        t2t1cal = t1+1;
5050                    };
5051                    //      if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) && (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){
5052    
5053                    // EMILIANO
5054                    //      if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) || (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){
5055                    //        //    if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){
5056                    //        if ( IsDebug() ) printf(" running out of vector without finding the corresponding calibration, sig \n");
5057                    //        //
5058                    //        // running out of vector without finding the corresponding calibration, sig
5059                    //        //
5060                    //        pret2 = t2;
5061                    //        obt2 = 0;
5062                    //        //      pkt2 = pkt1+2;
5063                    //        pkt2 = 0;
5064                    //        t2t1cal = t1+1;
5065                    //      };
5066    
5067    
5068                    //
5069                };
5070              //              //
5071              fromtime = this->GetAbsTime(ph2->GetOrbitalTime());              if ( IsDebug() ) printf(" Check if trk calibration2 is the right one \n");
5072              //              //
5073              valid = 0;              // EMILIANO
5074              this->HandleTRK_CALIB(false,true);              if ( ( PKT(pkt2) < PKT(pktfirst) || PKT(pkt2) > upperpkt) || (OBT(obt2) < OBT(obtfirst) || OBT(obt2) > upperobt) ){
5075                    //      if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){
5076                    if ( IsDebug() ) printf(" *WARNING*  The calibration found is outside the interval, sig \n");
5077                    //
5078                    // running out of vector without finding the corresponding calibration, sig
5079                    //
5080                    pret2 = t2;
5081                    obt2 = 0;
5082                    pkt2 = 0;
5083                };
5084                if ( PKT(pkt2) == PKT(pkt1)+1 ){
5085                    if ( IsDebug() ) cout << " ...OK"<<endl;
5086                    // =======================
5087                    // The calibration is good
5088                    // =======================
5089                    //
5090    //      if ( IsDebug() ) printf(" Found trk calibration2 at obt %u pkt %u t2 is %u \n",obt2,pkt2,t2);
5091    //      if ( IsDebug() ) printf(" Trk calibration2 at obt %u pkt %u t2 is %u is good \n",obt2,pkt2,t2);
5092    //        if ( IsDebug() ) printf("\n Trk calibration2 at time %u obt %u pkt %u \n",fromtime,obt2,pkt2);
5093                    if ( IsDebug() ) printf(" Trk calibration2 %u at time %u obt %u pkt %u \n",t2,fromtime,obt2,pkt2);
5094                    //
5095                    UInt_t valid2 = ValidateTrkCalib( caltrk2, eh2 );
5096                    if ( IsDebug() ) cout << " pkt2 validation --> "<<valid2<<endl;
5097    //      valid = valid & valid2;
5098                    valid = valid & valid2; //QUESTO VA CAMBIATO
5099                    //
5100                    // Handle good calib
5101                    //
5102                    MISSING_pkt1 = false;
5103                    MISSING_pkt2 = false;
5104    //              this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5105                    //
5106                    // Check for missing calibtrk1
5107                    //
5108                    if ( t2 != pret2+1 ){
5109                        //
5110                        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);
5111                        //
5112                        while ( t2 > pret2+1 ){
5113                            //
5114                            // handle missing calib1
5115                            //
5116                            pret2++;
5117                            //
5118                            obt1 = 0;
5119                            pkt1 = 0;
5120                            //
5121                            tr2->GetEntry(pret2);
5122                            ph2 = eh2->GetPscuHeader();
5123                            obt2 = ph2->GetOrbitalTime();  
5124                            pkt2 = ph2->GetCounter();  
5125                            //
5126                            fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
5127                            //
5128                            valid = 0;
5129                            MISSING_pkt1 = true;
5130                            MISSING_pkt2 = false;
5131    //                      this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5132                            //
5133                        };
5134                        //
5135                    };
5136                    //
5137                } else if ( this->PKT(pkt2) > this->PKT(pkt1)+1 ){
5138                    //
5139                    // Check for missing calibtrk2
5140                    //
5141                    if ( IsDebug() ) printf(" Missing the trk calibration2! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);
5142                    t2 = pret2;
5143                    //
5144                    // handle missing calib2
5145                    //
5146                    obt2 = 0;
5147                    pkt2 = 0;
5148                    valid = 0;
5149                    MISSING_pkt1 = false;
5150                    MISSING_pkt2 = true;
5151    //              this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5152                    //
5153                };
5154              //              //
5155            };  
5156                if( !(MISSING_pkt1&MISSING_pkt2) ){
5157                  this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5158                  ncalib++;
5159                  if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
5160                }
5161    
5162    
5163            } else {
5164            //            //
5165                if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u OUTSIDE the considered time interval \n",fromtime,obt1,pkt1);
5166                //      if ( PEDANTIC ) throw -79;
5167                //
5168          };          };
5169            //    
5170    
5171        }; //end loop on pkt1
5172    
5173    
5174    
5175        //
5176        // we have one more calib pkt2 !
5177        //
5178        t2++;
5179        while ( t2 < nevents2 ){
5180          //          //
5181        } else if ( this->PKT(pkt2) > this->PKT(pkt1)+1 ){          // handle missing calib1
         //  
         // Check for missing calibtrk2  
5182          //          //
5183          if ( IsDebug() ) printf(" Missing the trk calibration2! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);          if ( IsDebug() ) printf(" t2 is %u nevents2 is %u \n",t2,nevents2);
5184          t2 = pret2;          obt1 = 0;
5185            pkt1 = 0;
5186          //          //
5187          // handle missing calib2          tr2->GetEntry(t2);
5188            ph2 = eh2->GetPscuHeader();
5189            obt2 = ph2->GetOrbitalTime();  
5190            pkt2 = ph2->GetCounter();  
5191          //          //
5192          obt2 = 0;          fromtime = this->GetAbsTime(ph2->GetOrbitalTime());
         pkt2 = 0;  
5193          valid = 0;          valid = 0;
5194          this->HandleTRK_CALIB(true,false);                //  if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->PKT(pkt1) <= upperpkt && this->OBT(obt1) >= this->OBT(obtfirst) && this->OBT(obt1) <= upperobt ){
5195            // EMILIANO
5196            if ( this->PKT(pkt2) >= this->PKT(pktfirst) && this->PKT(pkt2 <= upperpkt) && this->OBT(obt2) >= this->OBT(obtfirst) && this->OBT(obt2) <= upperobt ){
5197                //    if ( this->PKT(pkt2) > this->PKT(pktfirst) || this->OBT(obt2) > this->OBT(obtfirst) ){
5198                //
5199                if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);
5200                //
5201                MISSING_pkt1 = true;
5202                MISSING_pkt2 = false;
5203                this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2);
5204                ncalib++;
5205                if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
5206                //
5207            };
5208            //
5209            t2++;
5210          //          //
       };  
       //  
     } else {  
       //  
       if ( IsDebug() ) printf(" Trk calibration1 at time %u obt %u pkt %u OUTSIDE the considered time interval \n",fromtime,obt1,pkt1);  
       //      if ( PEDANTIC ) throw -79;  
       //  
     };  
     //      
   };  
   //  
   // we have one more calib pkt2 !  
   //  
   t2++;  
   while ( t2 < nevents2 ){  
     //  
     // handle missing calib1  
     //  
     if ( IsDebug() ) printf(" t2 is %u nevents2 is %u \n",t2,nevents2);  
     obt1 = 0;  
     pkt1 = 0;  
     //  
     tr2->GetEntry(t2);  
     ph2 = eh2->GetPscuHeader();  
     obt2 = ph2->GetOrbitalTime();    
     pkt2 = ph2->GetCounter();    
     //  
     fromtime = this->GetAbsTime(ph2->GetOrbitalTime());  
     valid = 0;  
 //  if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->PKT(pkt1) <= upperpkt && this->OBT(obt1) >= this->OBT(obtfirst) && this->OBT(obt1) <= upperobt ){  
  // 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(" Missing the trk calibration1! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);  
       //  
       this->HandleTRK_CALIB(false,true);  
       //  
5211      };      };
5212      //  
5213      t2++;  // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
5214      //  // -----------------------------------------------------------------
5215    };  // in case of corruption, check if the calibration can be recovered
5216    // from another chewbacca file
5217    // -----------------------------------------------------------------
5218    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
5219    
5220    //    cout <<" TRY TO RECOVER ?? "<<try_to_recover<<endl;
5221        
5222        if(chewbacca&&try_to_recover){
5223    
5224    
5225            if ( IsDebug() ) cout << endl << ">>>> TRY TO RECOVER TRACKER CALIBRATIONS <<<<"<<endl;
5226    
5227            TSQLResult *result = 0;
5228            TSQLRow    *row    = 0;
5229            //
5230            stringstream oss;
5231            oss.str("");
5232            //
5233    
5234            ////////////////////////////////////////////////////////////////////////
5235            // retrieve the name of the current file:
5236            ////////////////////////////////////////////////////////////////////////        
5237            oss.str("");
5238            oss << "SELECT NAME FROM GL_ROOT where ID=" << GetID_ROOT() <<";";
5239            if ( IsDebug() ) cout << oss.str().c_str() << endl;
5240    
5241            result = conn->Query(oss.str().c_str());
5242            if ( !result ) throw -4;;
5243            row = result->Next();
5244            TString thisfilename = (TString)row->GetField(0);
5245            if ( IsDebug() ) cout << "Current file ==> "<<thisfilename<<endl;      
5246    
5247            ////////////////////////////////////////////////////////////////////////        
5248            // read all the calibrations inserted
5249            ////////////////////////////////////////////////////////////////////////        
5250            oss.str("");
5251            oss << " SELECT ";
5252            oss << " ID,FROM_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,TO_TIME";
5253            oss << " FROM GL_TRK_CALIB ";
5254            oss << " ORDER BY ID DESC LIMIT "<<ncalib<<"; ";        
5255            if ( IsDebug() ) cout << oss.str().c_str() << endl;
5256    
5257            result = conn->Query(oss.str().c_str());
5258            if ( !result ) throw -4;;
5259            if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5260            
5261            // -----------------------------------
5262            // loop over calibrations ...
5263            // -----------------------------------
5264            UInt_t nn=0;
5265            do {
5266                row = result->Next();
5267                if(!row)break;
5268                
5269                UInt_t id       = (UInt_t)atoll(row->GetField(0));
5270                UInt_t fromtime = (UInt_t)atoll(row->GetField(1));
5271                UInt_t obt1     = (UInt_t)atoll(row->GetField(2));
5272                UInt_t pkt1     = (UInt_t)atoll(row->GetField(3));
5273                UInt_t obt2     = (UInt_t)atoll(row->GetField(4));
5274                UInt_t pkt2     = (UInt_t)atoll(row->GetField(5));
5275                UInt_t boot     = (UInt_t)atoll(row->GetField(6));
5276                UInt_t valid    = (UInt_t)atoll(row->GetField(7));
5277                bool MISSING_pkt1 = (row->GetFieldLength(8)==0);
5278                bool MISSING_pkt2 = (row->GetFieldLength(9)==0);
5279                UInt_t totime   = (UInt_t)atoll(row->GetField(10));
5280    
5281                // -------------------------------------
5282                // ...check if the entry is corrupted...
5283                // -------------------------------------
5284                cout <<"*** "<< MISSING_pkt1 << MISSING_pkt2 << valid <<endl;
5285                bool CORRUPTED = (MISSING_pkt1||MISSING_pkt2||!valid);
5286    
5287                if ( IsDebug() ) cout << "("<<nn<<")  ID = "<<id<<" from GL_TRK_CALIB  ==>  corrupted ? "<<CORRUPTED<<endl;
5288    
5289    //          if( !CORRUPTED  )continue; // nothing to do
5290    
5291                /////////////////////////////////////////////////////////  
5292                // if it is corrupted, ...look for ather chewbacca files
5293                // containing the same calibrations ...
5294                /////////////////////////////////////////////////////////
5295    
5296                bool this_MISSING_pkt1 = false;
5297                bool this_MISSING_pkt2 = false;
5298                int  this_t1=0;
5299                int  this_t2=0;;
5300                UInt_t this_valid = 0;
5301    
5302                TString path       = "";
5303                TString name       = "";
5304                TString raw        = "";
5305                UInt_t obt0        = 0;
5306                UInt_t timesync    = 0;
5307                UInt_t boot_number = 0;
5308                bool   FOUND       = false;
5309    
5310                if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
5311    
5312    //          for(int itable=0; itable<2; itable++){
5313                for(int itable=0; itable<1; itable++){
5314    
5315                    // ------------------------------------------------------
5316                    // loop over both ROOT_TABLE and ROOT_TABLE_BAD
5317                    // ------------------------------------------------------
5318    
5319                    TString table = "ROOT_TABLE";
5320                    if(itable==1)table = "ROOT_TABLE_BAD";
5321    
5322                    oss.str("");
5323                    oss << " SELECT ";
5324                    oss << " FOLDER_NAME,FILE_NAME,OBT_TIME_SYNC,LAST_TIME_SYNC_INFO,BOOT_NUMBER,INPUT_NAME ";
5325                    oss << " FROM "<<table;
5326                    oss << " WHERE 1 " << endl;
5327                    oss << " AND FILE_NAME != \""<< thisfilename<<"\"";
5328                    if( !MISSING_pkt1 ){
5329                        oss << " AND ";
5330                        oss << " PKT_NUMBER_INIT < "<<pkt1;
5331                        oss << " AND ";
5332                        oss << " PKT_NUMBER_FINAL > "<<pkt1;
5333                        oss << " AND ";
5334                        oss << " PKT_OBT_INIT < "<<obt1;
5335                        oss << " AND ";
5336                        oss << " PKT_OBT_FINAL > "<<obt1;
5337                    }else{
5338                        if(pkt2>1) pkt1 = pkt2-1;//serve dopo                  
5339                    }
5340                    if( !MISSING_pkt2 ){
5341                        oss << " AND ";
5342                        oss << " PKT_NUMBER_INIT < "<<pkt2;
5343                        oss << " AND ";
5344                        oss << " PKT_NUMBER_FINAL > "<<pkt2;
5345                        oss << " AND ";
5346                        oss << " PKT_OBT_INIT < "<<obt2;
5347                        oss << " AND ";
5348                        oss << " PKT_OBT_FINAL > "<<obt2;
5349                    }else{
5350                        if(pkt1>0) pkt2 = pkt1+1;//serve dopo
5351                    }
5352                    if( boot> 0 ){
5353                        oss << " AND ";
5354                        oss << " BOOT_NUMBER = "<<boot;
5355                    }else{
5356                    }
5357                    oss << " ORDER BY BAD_PKT_CALREAD ASC; ";
5358                
5359                    TSQLResult *result2 = 0;
5360                    TSQLRow    *row2    = 0;
5361    
5362                    if ( IsDebug() ) cout << oss.str().c_str() << endl;        
5363                    result2 = conn->Query(oss.str().c_str());
5364                    if ( !result2 ) throw -4;;
5365                    if ( IsDebug() ) cout <<"Rows: "<<result2->GetRowCount()<<endl;
5366    
5367                    // ------------------------------------------------------
5368                    // loop over files containing repetition (if any)
5369                    // ------------------------------------------------------
5370                    do {
5371                        row2 = result2->Next();
5372                        if(!row2)break;
5373                    
5374                        // ------------------------------------------------------
5375                        // ... a repetition is found ...
5376                        // ------------------------------------------------------
5377                        path       = (TString)row2->GetField(0);
5378                        name       = (TString)row2->GetField(1);
5379                        raw        = (TString)row2->GetField(5);
5380                        obt0        = (UInt_t)atoll(row2->GetField(2));
5381                        timesync    = (UInt_t)atoll(row2->GetField(3));
5382                        boot_number = (UInt_t)atoll(row2->GetField(4));
5383                    
5384                        if ( IsDebug() ) cout << "- - - - - - - - - - -" <<endl;
5385    //                  cout << path <<endl;
5386    //                  cout << "File    : " <<name <<endl;
5387    //                  cout << obt0 <<endl;
5388    //                  cout << timesync <<endl;
5389    //                  cout << "boot n. : "<<boot_number <<endl;
5390    //                  cout << raw <<endl;
5391    
5392                        // ------------------------------------------------------
5393                        // ... retrieve the calibration packets.
5394                        // ------------------------------------------------------
5395                        if ( IsDebug() ) printf(" file is %s/%s \n",((TString)gSystem->ExpandPathName(path.Data())).Data(),name.Data());
5396                        TFile *file = new TFile(((TString)gSystem->ExpandPathName(path.Data()))+"/"+name); // EM, path could be symbolic and we must expand it
5397                        if(!file)throw -100;
5398                        if(file->IsZombie())throw -100;
5399                        //
5400                        tr1 = (TTree*)file->Get("CalibTrk1");
5401                        if ( !tr1 || tr1->IsZombie() ) throw -22;
5402                        tr2 = (TTree*)file->Get("CalibTrk2");
5403                        if ( !tr2 || tr2->IsZombie() ) throw -23;
5404                        //
5405                        tr1->SetBranchAddress("CalibTrk1", &caltrk1);
5406                        tr1->SetBranchAddress("Header", &eh1);
5407                        nevents1 = tr1->GetEntries();
5408                        tr2->SetBranchAddress("CalibTrk2", &caltrk2);
5409                        tr2->SetBranchAddress("Header", &eh2);
5410                        nevents2 = tr2->GetEntries();
5411                        for(this_t1=0; this_t1<nevents1; this_t1++){
5412                            tr1->GetEntry(this_t1);
5413                            if(
5414                                (UInt_t)eh1->GetPscuHeader()->GetCounter() == pkt1 &&
5415                                true) break;
5416                            this_MISSING_pkt1 = true;
5417                        }
5418                        for(this_t2=0; this_t2<nevents2; this_t2++){
5419                            tr2->GetEntry(this_t2);
5420                            if(
5421                                (UInt_t)eh2->GetPscuHeader()->GetCounter() == pkt2 &&
5422                                true) break;
5423                            this_MISSING_pkt2 = true;
5424                        }
5425                        this_valid =
5426                            ValidateTrkCalib( caltrk1, eh1, file )
5427                            *
5428                            ValidateTrkCalib( caltrk2, eh2, file );
5429                                
5430                        // ---------------------------------------------------------------------
5431                        // accept the calibration if it is better than the previous:
5432                        //
5433                        // - if the new calibration is perfect (both valid packets)
5434                        // - if the new calibration has both the packets and the previous does not
5435                        // ---------------------------------------------------------------------
5436                        if(
5437                            ( !this_MISSING_pkt1&&!this_MISSING_pkt2&&this_valid )||
5438                            ( (MISSING_pkt1||MISSING_pkt2) && (!this_MISSING_pkt1&&!this_MISSING_pkt2) )||
5439                            false)FOUND=true;      
5440                
5441                        if(file)file->Close();
5442    
5443                        if(FOUND)break;
5444    
5445                    }while(1);//endl loop over root table entries
5446    
5447                    if(FOUND)break;
5448    
5449                }//end loop over tables
5450    
5451                if(FOUND){
5452    
5453                  if ( IsDebug() ) cout << " >>> REPETITION FOUND :-) <<<" <<endl;
5454    
5455                  ////////////////////////////////////////////
5456                  // insert a new entry in GL_TRK_CALIB and
5457                  // modify the time-tag of the previous one
5458                  ////////////////////////////////////////////
5459    
5460                  // ---------------------------------------------------------------------
5461                  // step 1: insert a new raw file in GL_RAW
5462                  // ---------------------------------------------------------------------
5463                  //
5464                  // check if the raw file already exist
5465                  //
5466                  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
5467                  //                oss.str("");
5468                  //                oss << "SELECT ID FROM GL_RAW where NAME=\"" << gSystem->BaseName(raw.Data()) <<"\";";
5469                  //                if ( IsDebug() ) cout << oss.str().c_str() << endl;
5470                    
5471                  //                result = conn->Query(oss.str().c_str());
5472                  //                if ( !result ) throw -4;;
5473                  //                if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5474                  //                if( result->GetRowCount() == 0){
5475                  //                    if ( IsDebug() ) cout << " << Insert new RAW file >> "<<endl;
5476                  //                    // - - - - - - - - - - -
5477                  //                    // insert new raw file
5478                  //                    // - - - - - - - - - - -
5479                  //                    GL_RAW glraw = GL_RAW();    
5480                  //                    glraw.PATH        = gSystem->DirName(raw.Data());
5481                  //                    glraw.NAME        = gSystem->BaseName(raw.Data());
5482                  //                    glraw.BOOT_NUMBER = boot_number;
5483                  //                    //
5484                  //                    insertPamelaRawFile( &glraw );
5485                  //                    //              
5486                  //                    id_raw = glraw.ID;              
5487                  //                }else{
5488                  //                    row = result->Next();
5489                  //                    id_raw = (UInt_t)atoll(row->GetField(0));
5490                  //                }
5491                  //                if ( IsDebug() ) cout << "ID_RAW = "<<id_raw<<endl;
5492    
5493                  // ---------------------------------------------------------------------
5494                  // step 1(bis): retrieve the timesync id associated to the file
5495                  // (NB, uso lo stesso associato al file iniziale)
5496                  // ---------------------------------------------------------------------
5497                  UInt_t idtimesync = 0;
5498                  oss.str("");
5499                  oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" limit 1;";
5500                  if ( debug ) printf(" %s \n",oss.str().c_str());
5501                  result = conn->Query(oss.str().c_str());
5502                  if ( !result ) throw -3;
5503                    row = result->Next();
5504                    if ( !row ) throw -3;
5505                    idtimesync = (UInt_t)atoll(row->GetField(0));
5506                    if ( IsDebug() ) cout << "ID_TIMESYNC = "<<idtimesync<<endl;
5507                    
5508                    delete result;// mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
5509                    // ---------------------------------------------------------------------
5510                    // step 2: insert a new root file in GL_ROOT
5511                    // ---------------------------------------------------------------------
5512                    //
5513                    // check if the root file already exist
5514                    //
5515                    UInt_t id_root = 0;
5516                    oss.str("");
5517                    oss << "SELECT ID FROM GL_ROOT where NAME=\"" << gSystem->BaseName(name.Data()) <<"\";";
5518                    if ( IsDebug() ) cout << oss.str().c_str() << endl;
5519                    
5520                    result = conn->Query(oss.str().c_str());
5521                    if ( !result ) throw -4;;
5522                    if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
5523                    if( result->GetRowCount() == 0){
5524                        if ( IsDebug() ) cout << " << Insert new ROOT file >> "<<endl;
5525                        // - - - - - - - - - - -
5526                        // insert new root file
5527                        // - - - - - - - - - - -
5528                        GL_ROOT glroot = GL_ROOT();            
5529                        glroot.ID_RAW      = id_raw;
5530                        glroot.ID_TIMESYNC = idtimesync;
5531                        //
5532                        // 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,
5533                        //             NOT STATIC NOT KEEPENV = $PAM_L0 must be used in the DB
5534                        //
5535                        if ( STATIC ){
5536                          glroot.PATH        = (TString)gSystem->ExpandPathName(path);
5537                        } else {
5538                          if ( KEEPENV ){
5539                            glroot.PATH      = path;
5540                          } else {
5541                            glroot.PATH      = "$PAM_L0";
5542                          };
5543                        };
5544                        //              glroot.PATH        = path;
5545                        glroot.NAME        = name;
5546                        //
5547                        insertPamelaRootFile( &glroot );
5548                        //              
5549                        id_root = glroot.ID;                    
5550                    }else{
5551                        row = result->Next();
5552                        if(row)id_root = (UInt_t)atoll(row->GetField(0));
5553                    }
5554                    if ( IsDebug() ) cout << "ID_ROOT = "<<id_root<<endl;
5555    
5556                    delete result;// mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
5557                    // ---------------------------------------------------------------------
5558                    // step 3: modify time-tag of corrupted GL_TRK_CALIB entry
5559                    // ---------------------------------------------------------------------
5560                    if ( IsDebug() ) cout << " << Modify time-tag of calibration ID="<<id<<" >> "<<endl;
5561                    oss.str("");
5562                    oss << " UPDATE GL_TRK_CALIB SET "  
5563                        << " TO_TIME=0 , FROM_TIME=0  WHERE "
5564                        << " ID = "<< id  << ";";
5565                    if ( IsDebug() ) cout << oss.str().c_str() << endl;
5566                    result = conn->Query(oss.str().c_str());
5567                    if ( !result ) throw -4;;
5568    
5569                    delete result; // mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
5570    
5571                    // ---------------------------------------------------------------------
5572                    // step 4: insert the new calibration:
5573                    // ---------------------------------------------------------------------
5574                    if ( IsDebug() ) cout << " << Insert new TRK calibration >> "<<endl;
5575                    //
5576                    GL_TRK_CALIB glcal = GL_TRK_CALIB();        
5577                    //
5578                    glcal.ID_ROOT_L0        = id_root;
5579                    glcal.EV_ROOT_CALIBTRK1 = this_t1;
5580                    glcal.EV_ROOT_CALIBTRK2 = this_t2;
5581                    glcal.FROM_TIME         = fromtime;
5582                    glcal.TO_TIME           = totime;
5583                    glcal.OBT1              = obt1;
5584                    glcal.OBT2              = obt2;
5585                    glcal.PKT1              = pkt1;
5586                    glcal.PKT2              = pkt1;
5587                    glcal.BOOT_NUMBER       = GetBOOTnumber();
5588                    glcal.VALIDATION        = this_valid;
5589                    //
5590                    HandleTRK_CALIB(&glcal);
5591                    if ( IsDebug() ) cout << "ID = "<<glcal.ID<<endl;
5592                    //
5593                    
5594                }
5595                if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
5596    
5597            }while(1);//end loop over calibrations
5598            
5599            
5600            if( result )delete result;
5601            if( row    )delete row;
5602            
5603            
5604    
5605            
5606    
5607    
5608        }
5609    
5610    
5611    //      // ------------------------------
5612    //      // try to recover the calibration
5613    //      // ------------------------------
5614    //      cout << "TRY TO RECOVER TRACKER CALIBRATION"<<endl;
5615    //      //
5616    //      ULong64_t time  = 0; //absolute time
5617    //      string    path[100]; //mettere un limite massimo
5618    //      int       nrows = 0;
5619    //      UInt_t    pkt   = 0;
5620    //      UInt_t    obt   = 0;
5621    //      char     *type  = "";
5622    //      EventHeader *eh   = new EventHeader();
5623    //      CalibTrk1Event *c = new CalibTrk1Event();
5624            
5625    //       //
5626    //       if(which_is_not_valid==1 || which_is_not_valid==3){
5627    //        //
5628    //        cout << "PKT1 --> missing or corrupted "<<endl;
5629    //        type = "CalibTrk1";
5630    //        pkt  = pkt1;
5631    //        obt  = obt1;
5632    //        time = this->GetAbsTime(obt1);
5633    //        if( pkt1 == 0 ){//missing
5634    //            time = this->GetAbsTime(obt2);
5635    //            pkt  = pkt2-1;          
5636    //        }
5637    //        //
5638    //       }else if (which_is_not_valid==2 || which_is_not_valid==3){
5639    //        //
5640    //        cout << "PKT2--> missing or corrupted "<<endl;
5641    //        type = "CalibTrk2 ";
5642    //        pkt  = pkt2;
5643    //        obt  = obt2;
5644    //        time = this->GetAbsTime(obt2);
5645    //        if( pkt2 == 0 ){//missing
5646    //            time = this->GetAbsTime(obt1);
5647    //            pkt  = pkt1+1;          
5648    //        }
5649    //        //
5650    //       }else{
5651    //        cout << "this should not happen!!! "<<endl;
5652    //        trow -666;
5653    //       }
5654          
5655    //       nrows = Query_ROOT_TABLE(time,conn,path);// get the list of file which might contain the packet
5656          
5657    
5658    //       for(int r=0; r<nrows; r++){ //loop over rows
5659    //        if(path)cout << r << " >>>> "<<(path+r)->c_str() << endl;
5660    //        /// verifica che il file non sia quello gia` aperto
5661    //       }
5662    
5663    //       ////////////////////////////////////////////////////////////////////////
5664    
5665    //       TSQLResult *result = 0;
5666    //       TSQLRow    *row    = 0;
5667    //       //
5668    //       stringstream oss;
5669    //       oss.str("");
5670    //       // ----------------------------------------
5671    //       // read the id of last calibration inserted
5672    //       // ----------------------------------------
5673    //       oss.str("");
5674    //       oss << " SELECT ";
5675    //       oss << " (ID,ID_ROOT_L0,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,FROM_TIME,TO_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION) ";
5676    //       oss << " ORDER BY ID DESC LIMIT 1; ";
5677          
5678    //       result = conn->Query(oss.str().c_str());
5679    //       row = result->Next();
5680    //       if( !row )throw -666;
5681    
5682    //       if( result )delete result;
5683    //       if( row    )delete row;
5684    
5685    //       UInt_t id = (UInt_t)atoll(row->GetField(0));
5686    
5687    //       // -------------------------------------
5688    //       // ...and modify it with new parameters
5689    //       // -------------------------------------
5690          
5691    
5692    //   }
5693    //    //
5694    return(0);    return(0);
5695  };  };
# Line 5061  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 5992  Int_t PamelaDBOperations::CleanGL_RUN_FR
5992                    << " RM_ACQ_SETTING_MODE=" << glrun->GetRM_ACQ_SETTING_MODE()<< " , "                      << " RM_ACQ_SETTING_MODE=" << glrun->GetRM_ACQ_SETTING_MODE()<< " , "  
5993                    << " TRK_CALIB_USED=" << glrun->GetTRK_CALIB_USED()<< " , "                      << " TRK_CALIB_USED=" << glrun->GetTRK_CALIB_USED()<< " , "  
5994                    << " CAL_DSP_MASK=" << glrun->GetCAL_DSP_MASK()<< " , "                      << " CAL_DSP_MASK=" << glrun->GetCAL_DSP_MASK()<< " , "  
5995                    << " LAST_TIMESYNC=" << glrun->GetLAST_TIMESYNC()<< " , "                      << " LAST_TIMESYNC=" << glrun->GetLAST_TIMESYNC()<< " , ";
5996                    << " OBT_TIMESYNC=" << glrun->GetOBT_TIMESYNC()                //
5997                    << " WHERE ID=" << myid[u] << ";";                if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
5998                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12() << " , ";
5999                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
6000                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC() << " , ";
6001                  //              
6002                  oss << " OBT_TIMESYNC=" << glrun->GetOBT_TIMESYNC();
6003                  oss << " WHERE ID=" << myid[u] << ";";
6004                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
6005              };              };
6006              //              //
# Line 5074  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6011  Int_t PamelaDBOperations::CleanGL_RUN_FR
6011              for (UInt_t u=1; u <= nid ; u++){              for (UInt_t u=1; u <= nid ; u++){
6012                oss.str("");                oss.str("");
6013                oss << "UPDATE GL_RUN_FRAGMENTS SET "                oss << "UPDATE GL_RUN_FRAGMENTS SET "
6014                    << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , "                    << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , ";
6015                    << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "                //
6016                    << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT()<< ";";                if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
6017                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , ";
6018                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
6019                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , ";
6020                  //              
6021                  oss << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "
6022                      << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT();
6023                  oss << " WHERE ID=" << myid[u] << ";"; // BUG!!! 090112
6024                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
6025              };                  };    
6026            };            };
# Line 5098  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6042  Int_t PamelaDBOperations::CleanGL_RUN_FR
6042                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
6043                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "
6044                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< " , "                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< " , "
6045                    << " PKT_COUNTER=" << glrun->GetPKT_COUNTER()<< " , "                    << " PKT_COUNTER=" << glrun->GetPKT_COUNTER()<< " , ";
6046                    << " PKT_READY_COUNTER=" << glrun->GetPKT_READY_COUNTER()                //
6047                  if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
6048                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
6049                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) {
6050                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
6051                  //              
6052                  oss << " PKT_READY_COUNTER=" << glrun->GetPKT_READY_COUNTER()
6053                    << " WHERE ID=" << myid[u] << ";";                    << " WHERE ID=" << myid[u] << ";";
6054                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
6055              };              };
# Line 5112  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6062  Int_t PamelaDBOperations::CleanGL_RUN_FR
6062                oss.str("");                oss.str("");
6063                oss << "UPDATE GL_RUN_FRAGMENTS SET "                oss << "UPDATE GL_RUN_FRAGMENTS SET "
6064                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "                    << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
6065                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "                    << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , ";
6066                    << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< ";";                //
6067                  if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
6068                    oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
6069                  if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ){
6070                    oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
6071                  //              
6072                  oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT();
6073                  oss << " WHERE ID=" << myid[u] << ";"; // BUG!!! 090112
6074                conn->Query(oss.str().c_str());                  conn->Query(oss.str().c_str());  
6075              };                  };    
6076            };            };
# Line 5272  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6229  Int_t PamelaDBOperations::CleanGL_RUN_FR
6229          glrun->SetID_RUN_FRAG(glrun->GetID());          glrun->SetID_RUN_FRAG(glrun->GetID());
6230          glrun->Fill_GL_RUN(conn);            glrun->Fill_GL_RUN(conn);  
6231          //          //
6232  //      oss.str("");          //      oss.str("");
6233  //      oss << " SELECT ID FROM GL_RUN WHERE "          //      oss << " SELECT ID FROM GL_RUN WHERE "
6234  //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "          //          << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
6235  //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "          //          << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
6236  //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "          //          << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
6237  //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "          //          << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
6238  //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";          //          << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
6239  //      //          //      //
6240  //      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());
6241  //      result2 = conn->Query(oss.str().c_str());          //      result2 = conn->Query(oss.str().c_str());
6242  //      //          //      //
6243  //      if ( !result2 ) throw -4;          //      if ( !result2 ) throw -4;
6244  //      //          //      //
6245  //      row2 = result2->Next();          //      row2 = result2->Next();
6246  //      //          //      //
6247  //      if ( !row2 ) throw -25;          //      if ( !row2 ) throw -25;
6248  //      //          //      //
6249  //      oss.str("");          //      oss.str("");
6250  //      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);
6251  //      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());
6252  //      result2 = conn->Query(oss.str().c_str());          //      result2 = conn->Query(oss.str().c_str());
6253  //      //          //      //
6254  //      if ( !result2 ) throw -4;          //      if ( !result2 ) throw -4;
6255          //          //
6256          moved++;          moved++;
6257          //          //
# Line 5306  Int_t PamelaDBOperations::CleanGL_RUN_FR Line 6263  Int_t PamelaDBOperations::CleanGL_RUN_FR
6263        //        //
6264        //        //
6265        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");        glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
6266  //      oss.str("");        //      oss.str("");
6267  //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);        //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);
6268  //       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());
6269  //       result2 = conn->Query(oss.str().c_str());        //       result2 = conn->Query(oss.str().c_str());
6270  //      //        //      //
6271  //      if ( !result2 ) throw -4;        //      if ( !result2 ) throw -4;
6272  //      //        //      //
6273        row = result->Next();        row = result->Next();
6274      };      };
6275    };    };
# Line 5366  Int_t PamelaDBOperations::ValidateRuns(T Line 6323  Int_t PamelaDBOperations::ValidateRuns(T
6323      // 2) get the OBT of the last validated run      // 2) get the OBT of the last validated run
6324      // --------------------------------------------------------------      // --------------------------------------------------------------
6325      oss.str("");      oss.str("");
6326      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
6327        oss << " SELECT * FROM GL_RUN  WHERE VALIDATION>0 AND RUNHEADER_TIME<="<< t_start
6328          <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";          <<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
6329      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());
6330      result = conn->Query(oss.str().c_str());      result = conn->Query(oss.str().c_str());
# Line 5457  Int_t PamelaDBOperations::ValidateRuns(T Line 6415  Int_t PamelaDBOperations::ValidateRuns(T
6415    GL_RUN* this_run = new GL_RUN();    GL_RUN* this_run = new GL_RUN();
6416    GL_RUN* next_run = new GL_RUN();    GL_RUN* next_run = new GL_RUN();
6417    Int_t   nseq_max = 1000;    Int_t   nseq_max = 1000;
6418  //  UInt_t* sequence = new UInt_t[100];    //  UInt_t* sequence = new UInt_t[100];
6419    vector<UInt_t> sequence(nseq_max);    vector<UInt_t> sequence(nseq_max);
6420    Int_t   nseq = 0;    Int_t   nseq = 0;
6421    Bool_t CHECK = false;    Bool_t CHECK = false;
# Line 5472  Int_t PamelaDBOperations::ValidateRuns(T Line 6430  Int_t PamelaDBOperations::ValidateRuns(T
6430    // ---------------------------------------------------------------------------------    // ---------------------------------------------------------------------------------
6431    while(1){    while(1){
6432                        
6433            row = result->Next();      row = result->Next();
6434            if( row == NULL ) break;      if( row == NULL ) break;
6435                        
6436            //------------      //------------
6437            //get run info      //get run info
6438            //------------      //------------
6439            this_run->Set_GL_RUN(row);      this_run->Set_GL_RUN(row);
6440                                        
6441            Bool_t this_BAD = false;      Bool_t this_BAD = false;
6442            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;
6443            else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;      else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;
6444            else{      else{
6445  //                printf("Missing or corrupted header!! \n");        //                  printf("Missing or corrupted header!! \n");
6446                    this_ONLINE = false;        this_ONLINE = false;
6447                    this_BAD = true;        this_BAD = true;
6448            };      };
6449    
6450            //-----------------------------------      //-----------------------------------
6451            //compare with previous(next in time)      //compare with previous(next in time)
6452            //-----------------------------------      //-----------------------------------
6453            CHECK = false;      CHECK = false;
6454            UInt_t interval=0;      UInt_t interval=0;
6455                        
6456            if( nrow != 0){      if( nrow != 0){
6457                    
6458                                        
6459                    t1 = this_run->GetRUNTRAILER_TIME();        t1 = this_run->GetRUNTRAILER_TIME();
6460                    t2 = next_run->GetRUNHEADER_TIME();        t2 = next_run->GetRUNHEADER_TIME();
6461                    interval = (t2-t1);        interval = (t2-t1);
6462                                        
6463                    if(this_ONLINE && next_ONLINE){                               // this: ON-LINE + next: ON-LINE        if(this_ONLINE && next_ONLINE){                           // this: ON-LINE + next: ON-LINE
6464                                                        
6465                            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
6466                                                        
6467                            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
6468                                                        
6469                            if( !CHECK && this_run->VALIDATION ){          if( !CHECK && this_run->VALIDATION ){
6470                                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);            //      for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
6471                                    nseq=0;            for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],this_run->VALIDATION);
6472                            }            nseq=0;
6473            }
6474                                        
6475                    }else if( !this_ONLINE && next_ONLINE) {              // this: DEFAULT + next:ON-LINE        }else if( !this_ONLINE && next_ONLINE) {          // this: DEFAULT + next:ON-LINE
6476                                                        
6477                            CHECK = true;          CHECK = true;
6478    
6479                    }else if( !next_ONLINE ){                                             // this:ANY + next:DEFAULT        }else if( !next_ONLINE ){                                         // this:ANY + next:DEFAULT
6480                                                        
6481                            assignVALIDATION(next_run->ID,true);          assignVALIDATION(next_run->ID,true);
6482                            nseq=0;          nseq=0;
6483                    }        }
6484            }      }
6485    
6486            //----------------------------      //----------------------------
6487            //check run sequence for calib      //check run sequence for calib
6488            //----------------------------      //----------------------------
6489            if( CHECK ){      if( CHECK ){
6490                    // check if calibration exists        // check if calibration exists
6491                    if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);        if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval);
6492                    Bool_t MISSING = MissingTRK_CALIB(t1,t2);        //      Bool_t MISSING = MissingTRK_CALIB(t1,t2);
6493                    for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],!MISSING);        UInt_t MISSING = MissingTRK_CALIB(t1,t2);
6494                    nseq=0;        UInt_t val = 0;
6495            };        if ( MISSING == 1 ) val = 0;
6496            //--------------        if ( MISSING == 0 ) val = 1;
6497            //store run info        if ( MISSING == 2 ) val = 2;
6498            //--------------        for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],val);
6499            *next_run   = *this_run;        nseq=0;
6500            next_ONLINE = this_ONLINE;      };
6501            if( !this_BAD ){      //--------------
6502                    if(nseq < nseq_max){      //store run info
6503                            sequence[nseq] = this_run->ID;      //--------------
6504                            nseq++;      *next_run   = *this_run;
6505                    }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);      next_ONLINE = this_ONLINE;
6506            };      if( !this_BAD ){
6507          if(nseq < nseq_max){
6508            sequence[nseq] = this_run->ID;
6509            nseq++;
6510          }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);
6511        };
6512                        
6513            if ( IsDebug() ) printf("%i Run %u \n",nrow,this_run->ID);      if ( IsDebug() ) printf("%i Run %u \n",nrow,this_run->ID);
6514            nrow++;      nrow++;
6515                        
6516    };    };
6517    delete this_run;    delete this_run;
# Line 5561  Int_t PamelaDBOperations::ValidateRuns(T Line 6525  Int_t PamelaDBOperations::ValidateRuns(T
6525   * @param t2 To absolute time   * @param t2 To absolute time
6526   * @return true if there might be a missing calibration   * @return true if there might be a missing calibration
6527   */   */
6528  Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){  //Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
6529    UInt_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
6530                    
6531          GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();    GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();
6532                    
6533          // get the closest VALIDATED calibration before the run start (t2)    // get the closest calibration before the run start (t2)
6534          if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true);      //>>> missing    //  if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true);        //>>> missing
6535      if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(1);       //>>> missing
6536                    
6537          if ( trkcalib->TO_TIME  < t2 ) return(true);                                    //>>> missing    //  if ( trkcalib->TO_TIME  < t2 ) return(true);                                      //>>> missing
6538      if ( trkcalib->TO_TIME  < t2 ) return(1);                                     //>>> missing
6539                    
6540          //==============================================================    //==============================================================
6541          // Check is done first on the basis of time between calibration,    // Check is done first on the basis of time between calibration,
6542          // which should be equal to the time between ascending-nodes.    // which should be equal to the time between ascending-nodes.
6543          //==============================================================    //==============================================================
6544          if ( t2 - trkcalib->FROM_TIME > 5700) {    if ( t2 - trkcalib->FROM_TIME > 5700) {
6545                  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);
6546          //==============================================================      //==============================================================
6547          // there might be a missing calibration, due to:      // there might be a missing calibration, due to:
6548          // - MM full      // - MM full
6549          // - corrupted packets      // - corrupted packets
6550          // - loss of data      // - loss of data
6551          // 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
6552          //==============================================================      //==============================================================
6553                  Bool_t DOWNLOAD = false;      Bool_t DOWNLOAD = false;
6554                  // check if the calib was skipped becouse of download .... DA FARE!!      // check if the calib was skipped becouse of download .... DA FARE!!
6555                  if(DOWNLOAD)return(false);      //    if(DOWNLOAD)return(false);
6556        if(DOWNLOAD)return(0);
6557                                    
6558                  return(true);                                   //>>> missing      //    return(true);                                         //>>> missing
6559        return(1);                                  //>>> missing
6560                                    
6561          };    };
6562                    
6563          //==============================================================    //==============================================================
6564          // 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,
6565          // it is enough to say that there are no missing calibrations    // it is enough to say that there are no missing calibrations
6566          //==============================================================    //==============================================================
6567          // the long time interval bewteen runs might be due to download    // the long time interval bewteen runs might be due to download
6568          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);
6569          return(false);    if ( trkcalib->VALIDATION ) return(0);
6570      if ( IsDebug() )printf("Calibration is not validated... :-/ ==> OK but with VALIDATION=2! \n");
6571      return(2);
6572                    
6573  };  };
6574  /**  /**
# Line 5606  Bool_t PamelaDBOperations::MissingTRK_CA Line 6577  Bool_t PamelaDBOperations::MissingTRK_CA
6577   * @param validation true/false   * @param validation true/false
6578   */   */
6579  Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){  Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){
6580          TSQLResult *result = 0;    return(this->assignVALIDATION(idrun,(UInt_t)validation));
6581          stringstream oss;  }
6582          oss.str("");  
6583          oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";  Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, UInt_t validation){
6584          //    TSQLResult *result = 0;
6585  //      if ( IsDebug() )    stringstream oss;
6586  //      printf(" Set VALIDATION = %i for run %i \n",validation,idrun);    oss.str("");
6587          if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());    oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";
6588          result = conn->Query(oss.str().c_str());    //
6589          if ( !result ) throw -4;    //    if ( IsDebug() )
6590          return(0);    //    printf(" Set VALIDATION = %i for run %i \n",validation,idrun);
6591      if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());
6592      result = conn->Query(oss.str().c_str());
6593      if ( !result ) throw -4;
6594      return(0);
6595  }  }
6596    
6597    
# Line 5802  Int_t PamelaDBOperations::removeFile(TSt Line 6777  Int_t PamelaDBOperations::removeFile(TSt
6777    stringstream myquery;    stringstream myquery;
6778    //      //  
6779    myquery.str("");    myquery.str("");
6780    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() <<"';";
6781    //    //
6782    pResult = conn->Query(myquery.str().c_str());    pResult = conn->Query(myquery.str().c_str());
6783    //    //
# Line 5818  Int_t PamelaDBOperations::removeFile(TSt Line 6793  Int_t PamelaDBOperations::removeFile(TSt
6793    //    //
6794    this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));    this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));
6795    this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));    this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));
6796      UInt_t idtsy=(UInt_t)atoll(Row->GetField(2));
6797    //    //
6798    this->ValidationOFF();    this->ValidationOFF();
6799    //    //
# Line 5825  Int_t PamelaDBOperations::removeFile(TSt Line 6801  Int_t PamelaDBOperations::removeFile(TSt
6801    //    //
6802    this->RemoveRUNS();    this->RemoveRUNS();
6803    //    //
6804    this->RemoveFILES();    this->RemoveFILES(idtsy);
6805    //    //
6806    this->SetID_ROOT(0);    this->SetID_ROOT(0);
6807    this->SetID_RAW(0);    this->SetID_RAW(0);
# Line 6045  void PamelaDBOperations::RemoveRUNS(){ Line 7021  void PamelaDBOperations::RemoveRUNS(){
7021   * Rearrange calibration tables   * Rearrange calibration tables
7022   *   *
7023   **/   **/
7024  void PamelaDBOperations::RemoveFILES(){  void PamelaDBOperations::RemoveFILES(UInt_t idtsy){
7025    stringstream myquery;    stringstream myquery;
7026    //    //
7027    myquery.str("");    myquery.str("");
# Line 6055  void PamelaDBOperations::RemoveFILES(){ Line 7031  void PamelaDBOperations::RemoveFILES(){
7031    //    //
7032    conn->Query(myquery.str().c_str());    conn->Query(myquery.str().c_str());
7033    //    //
7034      myquery.str("");
7035      myquery << " DELETE FROM GL_ROOT WHERE ID=" <<this->GetID_ROOT() <<";";
7036      //
7037      if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
7038      //
7039      conn->Query(myquery.str().c_str());  //
7040      //
7041      if ( !chewbacca ){
7042        myquery.str("");
7043        myquery << " DELETE FROM GL_TIMESYNC WHERE ID=" << idtsy <<";";
7044        //
7045        if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
7046        //
7047        conn->Query(myquery.str().c_str());
7048      };
7049      //
7050  };  };
7051    
7052  /**  /**
# Line 6259  void PamelaDBOperations::RemoveCALIBS(){ Line 7251  void PamelaDBOperations::RemoveCALIBS(){
7251   * Rearrange calibration tables   * Rearrange calibration tables
7252   *   *
7253   **/   **/
7254  UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh ){  UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh , TFile *file){
7255    
7256        if(!caltrk) return 0;
7257    
7258        if ( IsDebug() ) cout << "ValidateTrkCalib:"<<endl;
7259    
7260        UInt_t validate = 1;
7261      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};
7262      UInt_t timeaftercalib=120000; //2000;      UInt_t timeaftercalib=120000; //2000;
7263  //  ----------      TString classname = caltrk->GetName();
7264  //  Check CRCs  
7265  //  ----------  //  ----------------------------------
7266    //  Check CRCs and failed calibrations
7267    //  ----------------------------------
7268      for(Int_t ipkt=0; ipkt<6; ipkt++){      for(Int_t ipkt=0; ipkt<6; ipkt++){
7269          if( caltrk->crc_hcal[ipkt] )return 0; // :-(          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
7270          for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] )return 0; // :-(              if( caltrk->crc_hcal[ipkt] ){
7271    //              if(IsDebug())cout<<"(CRC Header)";
7272                    validate = 0;
7273                    if(IsDebug())cout <<endl<<" *** CRC *** (header DSPn "<<caltrk->DSPnumber[ipkt]<<")";
7274            
7275                }
7276                for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] ){
7277    //              if(IsDebug())cout<<"(CRC Pkt-"<<ilad<<")";
7278                    if(IsDebug())cout <<endl<<" *** CRC *** (data DSPn "<<caltrk->DSPnumber[ipkt]<<" ladder "<<ilad<<")";
7279                    validate = 0;
7280                }
7281                if( !(caltrk->ncalib_event[ipkt]==0 && caltrk->cal_flag[ipkt]==0) ){
7282                    if(IsDebug())cout <<endl<<" *** FAILURE ***     (data DSPn "<<caltrk->DSPnumber[ipkt]<<")";
7283                    validate = 0;
7284                }
7285            }else{
7286    //          validate=0;
7287                if(IsDebug())cout <<endl<<" *** DSPn *** ("<< caltrk->DSPnumber[ipkt] <<" @pkt "<<ipkt<<")";
7288            }
7289      }      }
7290    
7291  //  -----------------------  //  -----------------------
7292  //  Check missing packets:  //  Check missing packets:
7293  //  -----------------------  //  -----------------------
# Line 6295  UInt_t PamelaDBOperations::ValidateTrkCa Line 7313  UInt_t PamelaDBOperations::ValidateTrkCa
7313  //  Check if it is first or second calibration packet  //  Check if it is first or second calibration packet
7314  //  -------------------------------------------------  //  -------------------------------------------------
7315      UInt_t build=0;      UInt_t build=0;
     TString classname = caltrk->GetName();  
7316      UInt_t base=0;      UInt_t base=0;
7317      UInt_t mask=0;      UInt_t mask=0;
7318      if(classname.Contains("CalibTrk1Event")){      if(classname.Contains("CalibTrk1Event")){
# Line 6306  UInt_t PamelaDBOperations::ValidateTrkCa Line 7323  UInt_t PamelaDBOperations::ValidateTrkCa
7323          base=18;          base=18;
7324          mask=0xFC0000;          mask=0xFC0000;
7325      }      }
7326  //  -------------------------------------------------  //  ----------------------------------------------------
7327  //  Count number of packets and set build variable  //  Count number of valid packets and set build variable
7328  //  -------------------------------------------------  //  ----------------------------------------------------
7329        if(IsDebug())cout <<endl<< " DSP: ";
7330      Int_t  npkts=0;      Int_t  npkts=0;
7331      for(Int_t ipkt=0; ipkt<6; ipkt++){      for(Int_t ipkt=0; ipkt<6; ipkt++){
7332          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){          if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
7333                if(IsDebug())cout <<" "<<caltrk->DSPnumber[ipkt];
7334              npkts++;              npkts++;
7335              build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );              build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );
7336          }  //          cout << caltrk->DSPnumber[ipkt]
7337            };
7338      }      }
7339  //    if( npkts==6 )return 1; // :-)      if(IsDebug())cout << " ==> "<< hex << build << dec;
7340    //  ----------------------------------------------------
7341  //    cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime()<<endl;  //  If the number of valid packets is 6, ok exit...
7342    //  ----------------------------------------------------
7343  //  -----------------------------------------------      if( npkts==6 ){
7344  //  If missing packets: check the acq configuration          return validate; // exit
7345        }
7346    ////////////////////////////////////////////////////////
7347    //  ...otherwise there might be some missing packets
7348    //
7349    //  In this case check the acq configuration
7350  //  (some DSPs might be excluded from acquisition)  //  (some DSPs might be excluded from acquisition)
7351  //  -----------------------------------------------  ////////////////////////////////////////////////////////
7352    
7353        if(!eh || !file || (file&&file->IsZombie()) ){
7354            if ( IsDebug() )cout << " *** MISSING VIEW *** eh="<<eh<<" file="<<file<<" cannot validate"<<endl;
7355            return (0);
7356        }
7357        
7358  //  -----------------------------------------------  //  -----------------------------------------------
7359  //  retrieve the first run header after calib  //  retrieve the first run header after calib
7360  //  -----------------------------------------------  //  -----------------------------------------------
7361       PacketType *pctp;      
7362       EventCounter *cod;      PacketType *pctp;
7363       cod = eh->GetCounter();      EventCounter *cod;
7364       Int_t irun = cod->Get(pctp->RunHeader);      cod = eh->GetCounter();
7365       TTree *rh=(TTree*)file->Get("RunHeader");      Int_t irun = cod->Get(pctp->RunHeader);
7366       if ( !rh || rh->IsZombie() ) throw -17;      TTree *rh=(TTree*)file->Get("RunHeader");
7367       if( rh->GetEntries() == irun ){      if ( !rh || rh->IsZombie() ) throw -17;
7368            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (1)  -- cannot validate :-( "<<endl;      if( rh->GetEntries() <= irun ){
7369           return 0; // :-(          if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (1) -- cannot validate :-( "<<endl;
7370       }          return 0; // :-(
7371        }
7372       RunHeaderEvent *run  = 0;      RunHeaderEvent *run  = 0;
7373       EventHeader    *hrun = 0;      EventHeader    *hrun = 0;
7374       rh->SetBranchAddress("RunHeader", &run);      rh->SetBranchAddress("RunHeader", &run);
7375       rh->SetBranchAddress("Header", &hrun);      rh->SetBranchAddress("Header", &hrun);
7376       rh->GetEntry(irun);      rh->GetEntry(irun);    
7377  //     cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime() << " Run " << hrun->GetPscuHeader()->GetOrbitalTime() <<endl;      if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){
7378            if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (2) -- cannot validate :-( "<<endl;
7379       if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){          return 0; // :-(
7380            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (2) -- cannot validate :-( "<<endl;      }
7381           return 0; // :-(  
7382       }      UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());
7383            if( dtime > timeaftercalib ){
7384       if( !run->RM_ACQ_AFTER_CALIB ){          if ( IsDebug() ) cout << " *** MISSING-PKT *** run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;
7385            if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) RM_ACQ_AFTER_CALIB=0    -- cannot validate :-( "<<endl;          return 0; // :-(
7386           return 0; // :-(      }
7387       }  
7388        if ( IsDebug() ) cout <<endl<< " ACQ_BUILD_INFO ==> "<<hex<<(run->ACQ_BUILD_INFO & mask)<<dec;
7389       UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());  
7390       if( dtime > timeaftercalib ){      if( (run->ACQ_BUILD_INFO & mask) != build ){
7391           if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;          validate=0; // :-(
7392           return 0; // :-(          cout <<endl<< " *** MISSING-PKT *** packet mismatch: ACQ_BUILD_INFO="<<hex<<(run->ACQ_BUILD_INFO&mask)<<" != "<<build<<dec;
7393       }      };
7394        
7395        return validate;
7396    
      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; // :-)  
7397    
7398  }  }
7399    
# Line 6378  UInt_t PamelaDBOperations::ValidateTrkCa Line 7403  UInt_t PamelaDBOperations::ValidateTrkCa
7403   *   *
7404   **/   **/
7405  UInt_t PamelaDBOperations::Check(){  UInt_t PamelaDBOperations::Check(){
7406          return(this->Check(0,0));    return(this->Check(0,0));
7407  }  }
7408    
7409  UInt_t PamelaDBOperations::Check(UInt_t from, UInt_t to){  UInt_t PamelaDBOperations::Check(UInt_t from, UInt_t to){
7410    //    //
7411          if ( IsDebug() ) printf(" from %u to %u \n",from,to);    if ( IsDebug() ) printf(" from %u to %u \n",from,to);
7412    //    //
7413    UInt_t test = 0;    UInt_t test = 0;
7414    //    //
# Line 6424  UInt_t PamelaDBOperations::Check(UInt_t Line 7449  UInt_t PamelaDBOperations::Check(UInt_t
7449      //      //
7450      if ( from > 0 && nid <= from ) goto ss;      if ( from > 0 && nid <= from ) goto ss;
7451      if ( to > 0 && nid >= to ) goto ss;      if ( to > 0 && nid >= to ) goto ss;
7452  //      //
7453      if ( (UInt_t)atoll(row->GetField(4)) > 1 ){      if ( (UInt_t)atoll(row->GetField(4)) > 1 ){
7454        //        //
7455        //        //
# Line 6455  UInt_t PamelaDBOperations::Check(UInt_t Line 7480  UInt_t PamelaDBOperations::Check(UInt_t
7480              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)));  
7481              row3 = result3->Next();              row3 = result3->Next();
7482            };            };
7483  //      delete result3;            //    delete result3;
7484    
7485          };          };
7486          //          //
# Line 6476  UInt_t PamelaDBOperations::Check(UInt_t Line 7501  UInt_t PamelaDBOperations::Check(UInt_t
7501              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)));
7502              row3 = result3->Next();              row3 = result3->Next();
7503            };            };
7504  //      delete result3;            //    delete result3;
7505          };          };
7506          //          //
7507          oss.str("");          oss.str("");
# Line 6496  UInt_t PamelaDBOperations::Check(UInt_t Line 7521  UInt_t PamelaDBOperations::Check(UInt_t
7521              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)));
7522              row3 = result3->Next();              row3 = result3->Next();
7523            };            };
7524   //     delete result3;            //    delete result3;
7525    
7526          };          };
7527        };        };
# Line 6517  UInt_t PamelaDBOperations::Check(UInt_t Line 7542  UInt_t PamelaDBOperations::Check(UInt_t
7542            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)));
7543            row3 = result3->Next();            row3 = result3->Next();
7544          };          };
7545  //      delete result3;          //      delete result3;
7546        };        };
7547        //        //
7548      };      };
# Line 6543  UInt_t PamelaDBOperations::Check(UInt_t Line 7568  UInt_t PamelaDBOperations::Check(UInt_t
7568        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
7569        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7570        test = 1;        test = 1;
7571  //      delete result2;        //        delete result2;
7572      };      };
7573      //      //
7574      if ( (thisrtt < prevrht) && (thisrht != prevrht) ){      if ( (thisrtt < prevrht) && (thisrht != prevrht) ){
# Line 6565  UInt_t PamelaDBOperations::Check(UInt_t Line 7590  UInt_t PamelaDBOperations::Check(UInt_t
7590        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
7591        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7592        test = 1;        test = 1;
7593  //      delete result2;        //        delete result2;
7594      };      };
7595      //      //
7596      if ( (thisrht > thisrtt) && (thisrht != prevrht) ){      if ( (thisrht > thisrtt) && (thisrht != prevrht) ){
# Line 6587  UInt_t PamelaDBOperations::Check(UInt_t Line 7612  UInt_t PamelaDBOperations::Check(UInt_t
7612        thisf = (TString)row2->GetField(0);        thisf = (TString)row2->GetField(0);
7613        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());        if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
7614        test = 1;        test = 1;
7615  //      delete result2;        //        delete result2;
7616      };      };
7617  ss:    ss:
7618      //      //
7619      prevrht = thisrht;      prevrht = thisrht;
7620      prevrtt = thisrtt;      prevrtt = thisrtt;
7621      previd = thisid;      previd = thisid;
7622      prevl0id = thisl0id;      prevl0id = thisl0id;
7623      row = result->Next();      row = result->Next();
7624  //    if ( result2 ) delete result2;      //    if ( result2 ) delete result2;
7625  //    if ( result3 ) delete result3;      //    if ( result3 ) delete result3;
7626    };    };
7627    //    //
7628    return(test);    return(test);

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

  ViewVC Help
Powered by ViewVC 1.1.23