--- chewbacca/YodaProfiler/src/PamelaDBOperations.cpp	2008/09/23 07:20:33	1.1
+++ chewbacca/YodaProfiler/src/PamelaDBOperations.cpp	2014/10/14 13:19:32	1.40
@@ -58,8 +58,9 @@
  * @param debug        debug flag.
  * @param tlefilename  ascii file with TLE 3 line elements.
  */
-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){
   //
+  RELAXED = false;
   chewbacca = false;
   chminentry = 0;
   chID = 0;
@@ -76,6 +77,8 @@
     //
   };
   //
+  KEEPENV = false;
+  if ( keepenv ) KEEPENV=true;
   STATIC=false;
   if ( staticp ) STATIC=true;
   //
@@ -85,12 +88,12 @@
   //
   glrun = new GL_RUN();
   //
-  if ( !chewbacca ){
-    if ( !boot ) SetNOBOOT(false);
-    SetTsync(tsync,gpamela);
-    SetBOOTnumber(boot,gpamela);
-    SetObt0(obt0);
-  };
+  //   if ( !chewbacca ){
+  //     if ( !boot ) SetNOBOOT(false);
+  //     SetTsync(tsync,gpamela);
+  //     SetBOOTnumber(boot,gpamela);
+  //     SetObt0(obt0);
+  //   };
   //
   SetTLEPath(tlefilename);
   //
@@ -99,6 +102,7 @@
   if (INSERT_RAW) SetRawName(filerawname);
   //
   INSERT_ROOT = !filerootname.IsNull();
+  if ( INSERT_ROOT ) this->SetRootName(filerootname);
   this->SetOrbitNo(dwinput);
   //
   this->SetID_RAW(0);
@@ -122,6 +126,12 @@
 //
 // SETTERS 
 //
+void PamelaDBOperations::NotChewbacca(UInt_t boot, UInt_t tsync, UInt_t obt0, Bool_t gpamela){
+  if ( !boot ) SetNOBOOT(false);
+  SetTsync(tsync,gpamela);
+  SetBOOTnumber(boot,gpamela);
+  SetObt0(obt0);
+};
 
 void PamelaDBOperations::OpenL0File(TString filerootname){
   if( INSERT_ROOT ){
@@ -132,13 +142,15 @@
       stringstream qu;
       TSQLResult *result = 0;
       TSQLResult *result2 = 0;
+      TSQLResult *result3 = 0;
       TSQLRow    *row    = 0;    
       TSQLRow    *row2    = 0;    
+      TSQLRow    *row3    = 0;    
       TString chpath;
       TString chfile;
       UInt_t ridn = 0;
       qu.str("");
-      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 << ";"; 
       if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
       result = conn->Query(qu.str().c_str());
       if ( result ){
@@ -149,6 +161,8 @@
 	  chpktmax = (UInt_t)atoll(row->GetField(2));
 	  chobtmin = (UInt_t)atoll(row->GetField(3));
 	  chobtmax = (UInt_t)atoll(row->GetField(4));
+	  chiby = (TString)(row->GetField(5));
+	  chrtinit = (UInt_t)atoll(row->GetField(6));
 	} else {
 	  throw -84;
 	};
@@ -157,19 +171,96 @@
       };
       delete result;
       qu.str("");
-      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 << ";"; 
       if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
       result2 = conn->Query(qu.str().c_str());
       if ( result2 ){
 	row2 = result2->Next();
 	if ( row2 ){
-	  chpath = (TString)gSystem->ExpandPathName(row2->GetField(0))+'/';
+	  if ( KEEPENV ){
+	    chpath = (TString)(row2->GetField(0))+'/';
+	  } else {
+	    chpath = (TString)gSystem->ExpandPathName(row2->GetField(0))+'/';
+	  };
 	  chfile = (TString)(row2->GetField(1));
 	  chobtts = (UInt_t)atoll(row2->GetField(2));
 	  chlastts = (UInt_t)atoll(row2->GetField(3));
 	  chresursts = (UInt_t)atoll(row2->GetField(4));
 	  chboot = (UInt_t)atoll(row2->GetField(5));
 	  //
+	  if ( !chboot ){
+	    if ( debug ) printf(" mmm... no BOOT number determined by chewbacca, try to find it looking at DB \n");
+	    //
+	    // new feature: check in ROOT_TABLE (timewise) the previous and the next BOOT number != 0 , if it is the same we know this one!
+	    // if it is different roll back to the old behaviour
+	    // 
+	    qu.str("");
+	    qu << "SELECT BOOT_NUMBER from ROOT_TABLE where BOOT_NUMBER!=0 AND REAL_TIME_INIT>"<< row2->GetField(10) <<" order by REAL_TIME_INIT asc limit 1;"; 
+	    if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
+	    UInt_t chbootA = 0;
+	    UInt_t chbootB = 1;
+	    result3 = conn->Query(qu.str().c_str());
+	    if ( result3 ){
+	      row3 = result3->Next();
+	      if ( row3 ){
+		chbootA = (UInt_t)atoll(row3->GetField(0));
+		if ( debug ) printf(" Found boot_number A = %u \n",chbootA);
+	      };
+	    };
+	    delete result3;
+	    qu.str("");
+	    qu << "SELECT BOOT_NUMBER from ROOT_TABLE where BOOT_NUMBER!=0 AND REAL_TIME_INIT<"<< row2->GetField(10) <<" order by REAL_TIME_INIT desc limit 1;"; 
+	    if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
+	    result3 = conn->Query(qu.str().c_str());
+	    if ( result3 ){
+	      row3 = result3->Next();
+	      if ( row3 ){
+		chbootB = (UInt_t)atoll(row3->GetField(0));
+		if ( debug ) printf(" Found boot_number B = %u \n",chbootB);
+	      };
+	    };
+	    if ( chbootA == chbootB ){
+	      chboot = chbootA;
+	      if ( debug ) printf(" Found boot_number! it is %u \n",chboot);
+	    } else {	    
+	      qu.str("");
+	      //	    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;"; 
+	      //	    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]
+	      qu << "SELECT BOOT_NUMBER from ROOT_TABLE where BOOT_NUMBER!=0 AND ABS(LAST_TIME_SYNC_INFO-"<< (float)chlastts <<")<50000 AND ABS(REAL_TIME_INIT-"<< atof(row2->GetField(10)) <<")<50000 group by BOOT_NUMBER order by BOOT_NUMBER asc;"; // even more relaxed conditions... 091214 [9REDtest3: error -29] // 10RED MYSQL operators BUG:
+              /*
+
+mysql> select CAST(1322000646 AS UNSIGNED INTEGER)-1322017203.;
++--------------------------------------------------+
+| CAST(1322000646 AS UNSIGNED INTEGER)-1322017203. |
++--------------------------------------------------+
+|                                           -16557 | 
++--------------------------------------------------+
+1 row in set (0.06 sec)
+
+mysql> select CAST(1322000646 AS UNSIGNED INTEGER)-1322017203;
++-------------------------------------------------+
+| CAST(1322000646 AS UNSIGNED INTEGER)-1322017203 |
++-------------------------------------------------+
+|                            18446744073709535059 | 
++-------------------------------------------------+
+1 row in set (0.02 sec)
+
+              */
+	      if ( debug ) printf(" chewbacca: query is %s \n",qu.str().c_str());
+	      result3 = conn->Query(qu.str().c_str());
+	      if ( result3 ){
+		row3 = result3->Next();
+		if ( row3 && result3->GetRowCount() == 1 ){
+		  chboot = (UInt_t)atoll(row3->GetField(0));
+		  if ( debug ) printf(" Found boot_number = %u \n",chboot);
+		} else {
+		  if ( debug ) printf(" AGH CANNOT DETERMINE THE BOOT NUMBER... \n");
+		  throw -29;
+		};
+	      };
+	    };
+	  };
+	  //
 	  chpktinit = (UInt_t)atoll(row2->GetField(6));
 	  chpktfinal = (UInt_t)atoll(row2->GetField(7));
 	  chobtinit = (UInt_t)atoll(row2->GetField(8));
@@ -182,13 +273,15 @@
 	throw -85;
       };
       filerootname = chpath + chfile;// + ".root";
-      if ( debug ) printf(" chewbacca: filename is %s \n",filerootname.Data());
     };
     this->SetRootName(filerootname);
-    file = TFile::Open(this->GetRootName().Data());
-  } else {
-    this->SetRootName("");
   };
+  if ( debug ) printf(" Filename is %s \n",filerootname.Data());
+  file = TFile::Open(this->GetRootName().Data());
+  //  } else {
+  //    this->SetRootName("");
+  //    this->SetRootName(filerootname);
+  //  };
 }
 
 //
@@ -388,23 +481,28 @@
     return;
   };
   //
-  TString name = this->GetRootFile();
-  Int_t nlength = name.Length();
-  if ( nlength < 5 ) return;
-  TString dwo = 0;
-  for (Int_t i = 0; i<5; i++){
-    dwo.Append(name[i],1);
-  };
-  if ( dwo.IsDigit() ){
-    dworbit = (UInt_t)dwo.Atoi();
-  } else {
-    dwo="";
-    for (Int_t i = 8; i<13; i++){
+  if ( !chewbacca ){
+    TString name = this->GetRootFile();
+    Int_t nlength = name.Length();
+    if ( nlength < 5 ){
+      if ( IsDebug() ) printf(" Agh problems determining the orbit number! name = %s \n",name.Data());
+      return;
+    };
+    TString dwo = "";
+    for (Int_t i = 0; i<5; i++){
       dwo.Append(name[i],1);
-    };     
-    if ( dwo.IsDigit() ) dworbit = (UInt_t)dwo.Atoi();
+    };
+    if ( dwo.IsDigit() ){
+      dworbit = (UInt_t)dwo.Atoi();
+    } else {
+      dwo="";
+      for (Int_t i = 8; i<13; i++){
+	dwo.Append(name[i],1);
+      };     
+      if ( dwo.IsDigit() ) dworbit = (UInt_t)dwo.Atoi();
+    };
+    if ( IsDebug() ) printf(" Downlink orbit is %i (dwo = %s) \n",dworbit,dwo.Data());
   };
-  if ( IsDebug() ) printf(" Downlink orbit is %i (dwo = %s) \n",dworbit,dwo.Data());
   return;
 };
 
@@ -435,9 +533,13 @@
 
 TString PamelaDBOperations::GetRootPath(){
   if ( STATIC ){
-    return((TString)gSystem->DirName(filerootname.Data())+'/');
-  } else {
-    return((TString)gSystem->ExpandPathName("$PAM_L0")+'/');
+    return((TString)gSystem->DirName(this->GetRootName().Data())+'/');
+  } else {    
+    if ( KEEPENV ){
+      return((TString)gSystem->ExpandPathName(gSystem->DirName(filerootname.Data()))+'/');
+    } else {
+      return((TString)gSystem->ExpandPathName("$PAM_L0")+'/');
+    };
   };
 };
 
@@ -490,6 +592,52 @@
 };
 
 /**
+ * 
+ * Set the variables which belogns to physendrun tree
+ * 
+ */
+void PamelaDBOperations::SetPhysEndRunVariables(){ 
+  //
+  //
+  //
+  TTree *T = 0;
+  T = (TTree*)file->Get("PhysEndRun");
+  if ( !T || T->IsZombie() ) throw -90;
+  //
+  PhysEndRunEvent *pher= 0;
+  EventHeader *eh = 0;
+  T->SetBranchAddress("PhysEndRun", &pher); 
+  T->SetBranchAddress("Header", &eh);
+  //
+  UInt_t phobt = 0;
+  UInt_t phpkt = 0;
+  //
+  glrun->SetPHYSENDRUN_MASK_S3S2S12(0);
+  glrun->SetPHYSENDRUN_MASK_S11CRC(0); 
+  //
+  for (Int_t p=0; p<T->GetEntries(); p++){
+    //
+    T->GetEntry(p);
+    //
+    phobt = (UInt_t)eh->GetPscuHeader()->GetOrbitalTime();
+    phpkt = (UInt_t)eh->GetPscuHeader()->GetCounter();
+    //
+    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())  ){
+      if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() || glrun->GetPHYSENDRUN_MASK_S11CRC() ){
+	if ( IsDebug() ) printf(" WARNING while looping in physendrun: found two PhysEndRun packet for the same RUN! \n");
+	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);
+	if ( PEDANTIC && IsDebug() ) printf(" ERROR while looping in physendrun: found two PhysEndRun packet for the same RUN!\n ");
+	if ( PEDANTIC ) throw -91;
+      } else {
+	glrun->SetPHYSENDRUN_MASK_S3S2S12((UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S3S2S12);
+	glrun->SetPHYSENDRUN_MASK_S11CRC((UInt_t)pher->TB_ENDRUN.TB_PMT_MASK_S11CRC);
+      };
+    };
+  };
+  //
+};
+
+/**
  * Patch, look for upper limits to avoid processing retransmitted data
  */
 Int_t PamelaDBOperations::SetUpperLimits(){
@@ -603,8 +751,9 @@
     UInt_t tjump = 50000;
     //UInt_t tjump = 100;
     while ( tjump > 0 ){
-      pktlast = numeric_limits<UInt_t>::max();
-      while ( pktlast > chpktmax && (Int_t)(nevent-1-it) >= 0 ){
+      //      pktlast = numeric_limits<UInt_t>::max();
+      pktlast = chpktmax + 1;
+      while ( PKT(pktlast) > PKT(chpktmax) && (Int_t)(nevent-1-it) >= 0 ){
 	if ( (Int_t)(nevent-1-it) >= 0 ){
 	  T->GetEntry(nevent-1-it);
 	  ph = eh->GetPscuHeader();
@@ -612,7 +761,7 @@
 	} else {
 	  pktlast = chpktmax + 1;
 	};
-	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));
 	it += tjump;
       };
       if ( tjump > 1 ) it -= 2*tjump;
@@ -636,8 +785,10 @@
     tjump = 50000;
     //tjump = 100;
     while ( tjump > 0 ){
-      pktlast = 0;
-      while ( pktlast < chpktmin && it < (Int_t)nevent ){
+      //      pktlast = 0;
+      pktlast = chpktmin - 1;
+      if ( debug ) printf("LLlook for down %i %i %llu %llu \n",it,pktlast,PKT(pktlast),PKT(chpktmin));
+      while ( PKT(pktlast) < PKT(chpktmin) && it < (Int_t)nevent ){
 	if ( it < (Int_t)nevent ){ 
 	  T->GetEntry(it);
 	  ph = eh->GetPscuHeader();
@@ -731,6 +882,8 @@
     ph = eh->GetPscuHeader();
     pktlast = ph->GetCounter();
     nevent = upperentry - chminentry;
+    if ( ((Int_t)upperentry - (Int_t)chminentry) < 0 ) nevent = 0; // nevent is UInt_t! 090112 [8RED: error -88]
+    if ( IsDebug() ) printf(" Setting nevent to %u - upperentry %i chminentry %i \n",nevent,upperentry,chminentry);
     //
   } else {
     upperpkt = PKT(pktlast);
@@ -739,12 +892,13 @@
   };
   //
   if ( chewbacca && nevent < 1 ) {
-	pktfirst = chpktmin;
-	upperpkt = PKT(chpktmax);
-	pktlast = chpktmax;
-	obtfirst = chobtmin;
-	obtlast = chobtmax;
-	upperobt = OBT(chobtmax);
+    if ( IsDebug() ) printf(" chewbacca and no events in the file \n");
+    pktfirst = chpktmin;
+    upperpkt = PKT(chpktmax);
+    pktlast = chpktmax;
+    obtfirst = chobtmin;
+    obtlast = chobtmax;
+    upperobt = OBT(chobtmax);
   };
   //
   if ( IsDebug() ) printf(" First entries are: OBT %u pkt_num %u entry %i\n",obtfirst,pktfirst,chminentry); 
@@ -752,9 +906,9 @@
   if ( IsDebug() ) printf(" Last entries are: OBT %lld pkt_num %lld entry %i\n",upperobt,upperpkt,upperentry); 
   //
   if ( (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)); 
-	if ( PEDANTIC ) throw -88;
-	return(32);
+    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 ( PEDANTIC ) throw -88;
+    return(32);
   };
   //
   if ( !nevent ) return(64);
@@ -764,7 +918,8 @@
   //  if ( nevent < jump ) jump = int(nevent/10);
   //  if ( !jump ) jump = 1;
   //
-  if ( (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) || (labs(PKT(pktlast)-PKT(pktfirst))<deltapkt && labs(OBT(obtlast)-OBT(obtfirst))<deltaobt) && nevent > deltapkt ){
+
+  if ( ((PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) || (labs(PKT(pktlast)-PKT(pktfirst))<deltapkt && labs(OBT(obtlast)-OBT(obtfirst))<deltaobt)) && nevent > deltapkt ){
     //
     if ( IsDebug() ) printf(" starting jump %i \n",jump);
     //    if ( IsDebug() ) printf(" (PKT(pktlast) < PKT(pktfirst) && OBT(obtlast) > OBT(obtfirst)) %llu < %llu && %llu > %llu \n     OR \n     (PKT(pktlast) > PKT(pktfirst) && OBT(obtlast) < OBT(obtfirst)) %llu > %llu && %llu < %llu \n",PKT(pktlast),PKT(pktfirst),OBT(obtlast),OBT(obtfirst),PKT(pktlast),PKT(pktfirst),OBT(obtlast),OBT(obtfirst)); 
@@ -1040,7 +1195,7 @@
 	upperpkt = pkth;
 	upperobt = obth;
 	rhev = lasthead+1;
-    } else {
+      } else {
 	rhev = lasthead;
       };
       if ( IsDebug() ) printf(" rhev after %i ph %lld upperp %lld oh %lld uppero %lld \n",rhev,pkth,upperpkt,obth,upperobt);
@@ -1079,7 +1234,15 @@
   stringstream   oss;
   //  
   oss.str("");
-  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.
+    if ( !strcmp(tag.Data(),"NONE") ){
+      oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< chiby.Data() <<"');";
+    } else {
+      oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< tag.Data() <<"');";
+    };
+  } else {
+    oss << "INSERT INTO _RUNID_GEN VALUES (NULL,'"<< tag.Data() <<"');";
+  };
   result = conn->Query(oss.str().c_str());
   if ( !result ) throw -10;
   oss.str("");
@@ -1210,6 +1373,7 @@
   oss.str("");
   oss << "SET wait_timeout=173000;";
   conn->Query(oss.str().c_str()); 
+  delete conn->Query("SET sql_mode = 'NO_UNSIGNED_SUBTRACTION';");
   //
 }
 
@@ -1227,7 +1391,7 @@
   stringstream oss;
   //  
   oss.str("");
-  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;";
   TSQLResult *result = 0;
   result = conn->Query(oss.str().c_str()); 
   if ( !result ) throw -10;
@@ -1260,19 +1424,19 @@
  */
 Long64_t PamelaDBOperations::PKT(UInt_t pkt_num){  
   //
-//  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));
   //
   if ( pkt_num < (ppktfirst/2) && ppktfirst > (16777214/2)  ){
-//    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);
     return((Long64_t)pkt_num+16777215LL);
   };
   //
   if ( pkt_num > ((Long64_t)ppktfirst*2) && pkt_num > (16777214/2) ){
-//    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);
     return((Long64_t)pkt_num-16777215LL);
   };
   //
-//  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)pkt_num);
+  //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)pkt_num);
   return((Long64_t)pkt_num);
   //
 };
@@ -1282,20 +1446,20 @@
  */
 Long64_t PamelaDBOperations::OBT(UInt_t obt){  
   //
-//  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));
   //
-  if ( obt < (pobtfirst/2) && pobtfirst > (numeric_limits<UInt_t>::max()/2) ){
-//    if ( IsDebug() ) printf(" rise up obt %lld \n",(Long64_t)obt+(Long64_t)numeric_limits<UInt_t>::max());
+  if ( obt < ((Long64_t)pobtfirst/2) && pobtfirst > (numeric_limits<UInt_t>::max()/2) ){
+    //    if ( IsDebug() ) printf(" rise up obt %lld \n",(Long64_t)obt+(Long64_t)numeric_limits<UInt_t>::max());
     return((Long64_t)obt+(Long64_t)numeric_limits<UInt_t>::max());
   };
   //
   if ( obt > ((Long64_t)pobtfirst*2) && obt > (numeric_limits<UInt_t>::max()/2) ){
-//    if ( IsDebug() ) printf(" pobtfirst*2 %lld \n",((Long64_t)pobtfirst*2));
-//    if ( IsDebug() ) printf(" rise down pktnum %lld \n", (Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());
+    //    if ( IsDebug() ) printf(" pobtfirst*2 %lld \n",((Long64_t)pobtfirst*2));
+    //    if ( IsDebug() ) printf(" rise down pktnum %lld \n", (Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());
     return((Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());
   };
   //
-//  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)obt);
+  //  if ( IsDebug() ) printf(" as it is %lld \n",(Long64_t)obt);
   return((Long64_t)obt);
 };
 
@@ -1331,9 +1495,13 @@
   UInt_t lastPkt = 0;
   UInt_t rhtime = 0;
   UInt_t rttime = 0;
+  //
+  if ( IsDebug() ) printf(" A firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
+  //
   if ( !mishead ){
     codh = ehh->GetCounter();
-    if ( lastev+1 == firstev || (lastev == firstev && lastev != -1) ){      
+    if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){      
+      if ( IsDebug() ) printf(" B firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
       firstev = 1;
       lastev = 0;
     } else {
@@ -1346,7 +1514,8 @@
   };
   if ( !mistrail ){
     codt = eht->GetCounter();
-    if ( lastev+1 == firstev || (lastev == firstev && lastev != -1)){      
+    if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1)){      
+      if ( IsDebug() ) printf(" C firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
       lastev = 0;
       firstev = lastev+1;
     } else {
@@ -1363,7 +1532,7 @@
   if ( mishead ) {
     glrun->Set_GL_RUNH0();
     //
-    if ( lastev+1 == firstev || (lastev == firstev && lastev != -1) ){      
+    if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){      
       firstObt = lastObt;
       firstPkt = lastPkt;
       rhtime = rttime;
@@ -1382,7 +1551,7 @@
   if ( mistrail ){
     glrun->Set_GL_RUNT0();
     //
-    if ( lastev+1 == firstev || (lastev == firstev && lastev != -1) ){      
+    if ( (lastev+1 == firstev && lastev != -1) || (lastev == firstev && lastev != -1) ){      
       lastObt = firstObt;
       lastPkt = firstPkt;
       rttime = rhtime;
@@ -1398,6 +1567,14 @@
     glrun->SetRUNTRAILER_PKT(lastPkt);
     //    
   };
+  //
+  // ad hoc solution for INF EV_TO [8RED] 090113
+  //
+  if ( !firstev && lastev == -1 ){
+    if ( IsDebug() ) printf(" EE firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
+    firstev = 1;
+    lastev = 0;
+  };
   glrun->SetEV_FROM((UInt_t)firstev);
   glrun->SetEV_TO((UInt_t)lastev);
   glrun->SetNEVENTS((UInt_t)lastev-(UInt_t)firstev+1);
@@ -1405,6 +1582,7 @@
   if ( IsDebug() ) printf(" firstev %i lastev %i nevents %i \n",firstev,lastev,lastev-firstev+1);
   //
   this->SetCommonGLRUN(rhtime,rttime);
+  this->SetPhysEndRunVariables();
   //
 };
 
@@ -1416,25 +1594,61 @@
  * Insert a new row into GL_RAW table.
  */
 Int_t PamelaDBOperations::insertPamelaRawFile(){
+
+    //
+    Bool_t idr =  this->SetID_RAW();
+    if ( idr ) return(1);
+
+    GL_RAW glraw = GL_RAW();
+    
+    glraw.PATH = GetRawPath();
+    glraw.NAME = GetRawFile();
+    //    glraw.BOOT_NUMBER = 0;//???
+    glraw.BOOT_NUMBER = this->GetBOOTnumber();
+    
+    if( insertPamelaRawFile(&glraw) )return(1);
+    //
+    idr =  this->SetID_RAW();
+    if ( !idr ) throw -11;
+    
+    return(0);
+}
+/**
+ * Insert a new row into GL_RAW table.
+ */
+Int_t PamelaDBOperations::insertPamelaRawFile(GL_RAW *glraw){
   //
-  stringstream oss;
-  //
-  Bool_t idr =  this->SetID_RAW();
-  if ( idr ) return(1);
-  //
-  oss.str("");
-  if ( STATIC ){
-    oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"
-	<< this->GetRawPath().Data() << "', '" << this->GetRawFile().Data() << "')";
-  } else {
-    oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('$PAM_RAW', '" << this->GetRawFile().Data() << "')";
-  };
-  if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
-  //
-  idr =  this->SetID_RAW();
-  if ( !idr ) throw -11;
-  //
-  return(0);
+    if(!glraw)return(1);//?? ok I think
+    //
+    stringstream oss;
+    //
+    oss.str("");
+    if ( STATIC ){
+	oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('"
+	    << glraw->PATH << "', '" << glraw->NAME << "')";
+    } else {
+	oss << "INSERT INTO GL_RAW (PATH, NAME) VALUES ('$PAM_RAW', '" << glraw->NAME << "')";
+    };
+    if ( debug ) cout <<oss.str().c_str() <<endl;
+    if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
+    //
+    oss.str("");
+    oss << "SELECT ID FROM GL_RAW WHERE NAME=\""<<glraw->NAME<<"\";";
+    if ( debug ) cout << oss.str().c_str()<<endl;
+    if ( conn->Query(oss.str().c_str()) == 0 ) throw -4;
+    //
+    TSQLResult *result = 0;
+    TSQLRow    *row    = 0;
+    result = conn->Query(oss.str().c_str());
+    if ( result == NULL ) throw -4;
+    row = result->Next();
+    if ( !row ) return(1);
+    glraw->ID = (UInt_t)atoll(row->GetField(0));
+    if ( debug ) printf(" The ID of the RAW file is %u \n",glraw->ID);
+    delete result;
+    delete row;
+    //
+    return(0);
 }
 
 
@@ -1445,7 +1659,8 @@
 Int_t PamelaDBOperations::insertPamelaGL_TIMESYNC(){
   //
   Int_t signal = 0;
-  UInt_t idresof = 0;
+  //  UInt_t idresof = 0;
+  idresof = 0;
   stringstream   oss;
   TSQLResult *result = 0;
   TSQLRow *row = 0;
@@ -1467,6 +1682,7 @@
     result = conn->Query(oss.str().c_str());
     if ( !result ) throw -10;
     row = result->Next();
+    if ( !row ) throw -92;
     idresof = (UInt_t)atoll(row->GetField(0));
     existsts = true;
     goto eout;
@@ -1488,7 +1704,7 @@
     if ( !row ){
       oss.str("");
       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< " 
-	  << dworbit << " order by FROM_ORBIT desc limit 1;";
+	  << dworbit << " AND SPECIAL_FILE='' order by FROM_ORBIT desc limit 1;";
       if ( IsDebug() ) printf(" %s \n",oss.str().c_str());
       result = conn->Query(oss.str().c_str());
       if ( !result ) throw -10;
@@ -1535,9 +1751,9 @@
     TYPE = 0;
     TSYNC = 0;
     //
-    Double_t minimum = 0.;
-    Double_t maximum = 0.;
-    Double_t minimum2 = 0.;
+    //    Double_t minimum = 0.;
+    // Double_t maximum = 0.;
+    //Double_t minimum2 = 0.;
     Double_t maximum2 = 0.;
     //
     //
@@ -1545,9 +1761,9 @@
     pamela::McmdRecord *mcrc = 0;
     TArrayC *mcmddata = 0;
     //
-    minimum = numeric_limits<Double_t>::max();
-    maximum = numeric_limits<Double_t>::min();
-    minimum2 = numeric_limits<Double_t>::max();
+    //    minimum = numeric_limits<Double_t>::max();
+    //    maximum = numeric_limits<Double_t>::min();
+    //    minimum2 = numeric_limits<Double_t>::max();
     maximum2 = numeric_limits<Double_t>::min();
     //
     T = (TTree*)file->Get("Mcmd");
@@ -1746,94 +1962,132 @@
  * The raw file indicates in the parameters should be already been stored in the database.
  */
 Int_t PamelaDBOperations::insertPamelaRootFile(){
-  stringstream oss;
-  TSQLResult *result = 0;
-  TSQLRow    *row    = 0;
-  UInt_t idtimesync = 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;
+
+    stringstream oss;
+    TSQLResult *result = 0;
+    TSQLRow    *row    = 0;
     //
-    row = result->Next();
+    // ----------------------
+    // determine the timesync
+    // ----------------------
+    UInt_t idtimesync = 0;
     //
-    if ( !row ) throw -3;
-    idtimesync = (UInt_t)atoll(row->GetField(0));
-  } else {
-    oss.str("");
-    if ( STATIC ){
-      oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
-	  << " LEFT JOIN GL_ROOT "
-	  << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
-	  << " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "
-	  << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
+    if ( chewbacca ){
+	oss.str("");
+	oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" and ID_RESURS_OFFSET="<< idresof <<" limit 1;"; // 10RED BUG!!!! without 'and ID_RESURS_OFFSET="<< idresof ' this query is not enough to ensure finding the correct line in GL_TIMSYNC...
+	if ( debug ) printf(" %s \n",oss.str().c_str());
+	result = conn->Query(oss.str().c_str());
+	//
+	if ( !result ) throw -3;
+	//
+	row = result->Next();
+	//
+	if ( !row ) throw -3;
+	idtimesync = (UInt_t)atoll(row->GetField(0));
     } else {
-      oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
-	  << " LEFT JOIN GL_ROOT "
-	  << " ON GL_RAW.ID = GL_ROOT.ID_RAW "
-	  << " WHERE GL_RAW.PATH = '$PAM_RAW' AND "
-	  << " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
+	oss.str("");
+	if ( STATIC ){
+	    oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
+		<< " LEFT JOIN GL_ROOT "
+		<< " ON GL_RAW.ID = GL_ROOT.ID_RAW "
+		<< " WHERE GL_RAW.PATH = '" << this->GetRawPath().Data() << "' AND "
+		<< " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
+	} else {
+	    oss << " SELECT COUNT(GL_ROOT.ID_RAW),GL_RAW.ID,GL_ROOT.ID FROM GL_RAW "
+		<< " LEFT JOIN GL_ROOT "
+		<< " ON GL_RAW.ID = GL_ROOT.ID_RAW "
+		<< " WHERE GL_RAW.PATH = '$PAM_RAW' AND "
+		<< " GL_RAW.NAME = '" << this->GetRawFile().Data() << "' GROUP BY GL_RAW.ID ";
+	};
+	result = conn->Query(oss.str().c_str());
+	//
+	if ( !result ) throw -12;
+	//
+	row = result->Next();
+	//
+	if ( !row ) throw -10;
+	if ( row != NULL && (UInt_t)atoll(row->GetField(0))>0 ){
+	    idroot = (UInt_t)atoll(row->GetField(2));
+	    delete row;
+	    delete result;
+	    return(1);
+	};
+	//
+	// determine which timesync has to be used
+	//
+	oss.str("");
+	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;";
+	result = conn->Query(oss.str().c_str());
+	//
+	if ( !result ) throw -3;
+	//
+	row = result->Next();
+	//
+	if ( !row ) throw -3;
+	idtimesync = (UInt_t)atoll(row->GetField(0));
     };
-    result = conn->Query(oss.str().c_str());
-    //
-    if ( !result ) throw -12;
-    //
-    row = result->Next();
-    //
-    if ( !row ) throw -10;
-    if ( row != NULL && (UInt_t)atoll(row->GetField(0))>0 ){
-      idroot = (UInt_t)atoll(row->GetField(2));
-      return(1);
+    
+    delete row;
+    delete result;
+
+    // ----------------------
+    // insert root file
+    // ----------------------
+
+    GL_ROOT glroot = GL_ROOT();
+    
+    glroot.ID_RAW = GetID_RAW();
+    glroot.ID_TIMESYNC = idtimesync;
+    if ( STATIC ){
+      glroot.PATH = GetRootPath(); 
+    } else {
+      if ( KEEPENV ){
+	glroot.PATH = gSystem->DirName(filerootname.Data());
+      } else {
+	glroot.PATH = "$PAM_L0";
+      };
     };
-    //
-    // determine which timesync has to be used
-    //
-    oss.str("");
-    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;";
-    result = conn->Query(oss.str().c_str());
-    //
-    if ( !result ) throw -3;
-    //
-    row = result->Next();
-    //
-    if ( !row ) throw -3;
-    idtimesync = (UInt_t)atoll(row->GetField(0));
-  };
+    glroot.NAME = GetRootFile();
+
+    if ( insertPamelaRootFile(&glroot) )return 1;
+
+    SetID_ROOT(glroot.ID);
+    
+
+    return (0);
+}
+/**
+ * Insert all the new rows into GL_ROOT. 
+ * The raw file indicates in the parameters should be already been stored in the database.
+ */
+Int_t PamelaDBOperations::insertPamelaRootFile(GL_ROOT *glroot){
+  stringstream oss;
+  TSQLResult *result = 0;
+  TSQLRow    *row    = 0;
+  //
   //
   oss.str("");
-  if ( STATIC ){
-    oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
-	<< 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() << "')";
-  };
+  oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
+      << glroot->ID_RAW << "', '" << glroot->ID_TIMESYNC << "', '" << glroot->PATH << "', '" << glroot->NAME << "')";
   //
-  if ( debug ) printf(" query is %s \n",oss.str().c_str());
+  if ( debug ) printf("%s \n",oss.str().c_str());
   if (conn->Query(oss.str().c_str()) == 0) throw -4;
   //
   delete result;
   //
   oss.str("");
   //  oss << "SELECT ID FROM GL_ROOT WHERE ID_RAW=" << this->GetID_RAW() << ";";
-  if ( STATIC ){
-    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() <<"';";
-  };
+  oss << "SELECT ID FROM GL_ROOT WHERE PATH='" << glroot->PATH << "' and NAME='"<< glroot->NAME <<"';";
   //
-  if ( debug ) printf(" query is %s \n",oss.str().c_str());
+  if ( debug ) printf("%s \n",oss.str().c_str());
   result = conn->Query(oss.str().c_str());
   if ( !result ) throw -12;
   row = result->Next();
   if ( !row ) throw -3;
-  this->SetID_ROOT((UInt_t)atoll(row->GetField(0)));
-  if ( debug ) printf(" The ID of the ROOT file is %u \n",this->GetID_ROOT());
+
+  glroot->ID = (UInt_t)atoll(row->GetField(0));
+
+  if ( debug ) printf(" The ID of the ROOT file is %u \n",glroot->ID);
   //
   delete result;
   //
@@ -1929,16 +2183,16 @@
     UInt_t lowerts = tsync-(obt0/1000)-5;
     if ( chewbacca ){
       oss.str("");
-      oss << "select BOOT_NUMBER from ROOT_TABLE where LAST_TIME_SYNC_INFO-(OBT_TIME_SYNC)<"
+      oss << "select BOOT_NUMBER from ROOT_TABLE where CAST((LAST_TIME_SYNC_INFO-(OBT_TIME_SYNC)) AS SIGNED INT)<" // 10RED MYSQL OPERATORS BUG
 	  << upperts 
-	  << " AND LAST_TIME_SYNC_INFO-(OBT_TIME_SYNC)>"
+	  << " AND CAST((LAST_TIME_SYNC_INFO-(OBT_TIME_SYNC)) AS SIGNED INT)>" // 10RED MYSQL OPERATORS BUG
 	  << lowerts
 	  << " AND BOOT_NUMBER>1;";
     } else {
       oss.str("");
-      oss << "select GL_RAW.BOOT_NUMBER from GL_TIMESYNC LEFT JOIN GL_RAW ON GL_RAW.ID = GL_TIMESYNC.ID_RAW where TIMESYNC-(OBT0/1000)<"
+      oss << "select GL_RAW.BOOT_NUMBER from GL_TIMESYNC LEFT JOIN GL_RAW ON GL_RAW.ID = GL_TIMESYNC.ID_RAW where CAST((TIMESYNC-(OBT0/1000)) AS SIGNED INT)<" // 10RED MYSQL OPERATORS BUG
 	  << upperts 
-	  << " AND TIMESYNC-(OBT0/1000)>"
+	  << " AND CAST((TIMESYNC-(OBT0/1000)) AS SIGNED INT)>" // 10RED MYSQL OPERATORS BUG
 	  << lowerts
 	  << " AND GL_RAW.BOOT_NUMBER>0 GROUP BY GL_TIMESYNC.OBT0;";
     };
@@ -2037,8 +2291,10 @@
   //
   // no runtrailers in the file!
   //
-  if ( !rtev ){
-    if ( !rhev ){
+  if ( IsDebug() ) printf(" Start rtev %i rhev %i nrtev %i nrhev %i \n",rtev,rhev,nrtev,nrhev); 
+  if ( !rtev || (chewbacca && !nrtev) ){
+    if ( IsDebug() ) printf(" No runtrailers \n"); 
+    if ( !rhev || (chewbacca && !nrhev) ){
       if ( IsDebug() ) printf(" No runheaders nor runtrailers!! \n"); 
       if ( !(upperentry-chminentry) ){
 	if ( IsDebug() ) printf(" No physics events nor runs in the file \n"); // di nuovo potrebbe esserci un runtrailer senza eventi (riempimento MM)
@@ -2061,10 +2317,10 @@
 	  cod = ehh->GetCounter();
 	  tcod = (UInt_t)cod->Get(pctp->Physics);
 	  evbefh = TMath::Max(chminentry,tcod);
-//	  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
 	  if ( (UInt_t)evbefh == upperentry || !upperentry ) evbefh = upperentry + 1;
-//
-	if ( debug ) printf(" evbefh %i upperentry %u \n",evbefh,upperentry);
+	  //
+	  if ( debug ) printf(" evbefh %i upperentry %u \n",evbefh,upperentry);
 	  //
 	  this->HandleRunFragments(false,true,evbefh,upperentry); 
 	  //
@@ -2075,6 +2331,7 @@
     //
   } else {
     //
+    if ( IsDebug() ) printf(" We have runtrailers \n"); 
     Int_t conptt = -1;
     for (Int_t ptt=0; ptt<rtev; ptt++){
       //
@@ -2091,7 +2348,7 @@
 	ptht = cod->Get(pctp->RunHeader) - 1;
 	//      evbeft = cod->Get(pctp->Physics);
 	tcod = (UInt_t)cod->Get(pctp->Physics);
-	if ( !tcod ) tcod = 1;
+	if ( !tcod ) tcod = 1;    // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
 	evbeft = TMath::Min(upperentry,(tcod-1));
 	if ( debug ) printf(" Loop in runtrailers, evbeft is %u upperentry %u cod->getetc %u \n",evbeft,upperentry,cod->Get(pctp->Physics));
 	//
@@ -2130,7 +2387,7 @@
 	  obth = phh->GetOrbitalTime();
 	  cod = ehh->GetCounter();
 	  tcod = (UInt_t)cod->Get(pctp->Physics);
-	  if ( !tcod ) tcod = 1;
+	  if ( !tcod ) tcod = 1; // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
 	  evbefh = TMath::Max(chminentry,(tcod-1));
 	  // 
 	  if ( PKT(pkth) >= PKT(pktfirst) && PKT(pkth) <= upperpkt ){
@@ -2169,6 +2426,7 @@
 	      //
 	      this->HandleRunFragments(true,true,chminentry,(evbefh)); 
 	      //
+	      // what about pth=ptht-1
 	    };
 	  };
 	  //
@@ -2191,7 +2449,7 @@
 	      cod = ehh->GetCounter();
 	      //	    evbeft = cod->Get(pctp->Physics);
 	      tcod = (UInt_t)cod->Get(pctp->Physics);
-	      if ( !tcod ) tcod = 1;
+	      if ( !tcod ) tcod = 1; // IS A BUG SINCE RUNS WITH ZERO EVENTS WILL LOOK LIKE RUNS WITH ONE EVENT
 	      evbeft = TMath::Min(upperentry,(tcod-1));
 	      rh->GetEntry(pth);
 	      phh = ehh->GetPscuHeader();
@@ -2231,9 +2489,13 @@
 	//	if ( ptt+1 == rtev){  
 	if ( conptt+1 == nrtev ){  
 	  //	if ( conptt+1 == (nrtev+nrtbef )){  
+	  if ( IsDebug() ) printf(" >>>>>>>>>>> %i %u %i %u \n",ptht,rhev,nrtev,conptt); 
 	  ptht++;
-	  if ( ptht < rhev ){
+	  if ( ptht < rhev ){ 
 	    rh->GetEntry(ptht);
+	    //pth++;
+	    //if ( pth < rhev ){
+	    //rh->GetEntry(pth);
 	    phh = ehh->GetPscuHeader();
 	    pkth = phh->GetCounter();
 	    obth = phh->GetOrbitalTime();
@@ -2257,10 +2519,12 @@
 	    if ( (UInt_t)evbeft < upperentry-1 && upperentry>0 ){
 	      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 ( (ptt-1) < 0 ) throw -15; // should never arrive here!
-	      rt->GetEntry(ptt-1);
+	      //	      if ( (ptt-1) < 0 ) throw -15; // should never arrive here!
+	      if ( (rtev-1) < 0 || ptt < 0 ) throw -15; // should never arrive here!
+	      //	      rt->GetEntry(ptt-1);
+	      rt->GetEntry(rtev-1);
 	      cod = eht->GetCounter();
-	      tcod = (UInt_t)cod->Get(pctp->Physics);
+	      tcod = (UInt_t)cod->Get(pctp->Physics)+1;
 	      evbefh = TMath::Max(chminentry,tcod);
 	      //	    evbefh = cod->Get(pctp->Physics);
 	      rt->GetEntry(ptt);
@@ -2367,10 +2631,10 @@
       //
       if ( IsDebug() ) printf(" The new run has more events than the old one \n");
       glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
-//       oss.str("");
-//       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
-//       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
-//       conn->Query(oss.str().c_str());
+      //       oss.str("");
+      //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
+      //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
+      //       conn->Query(oss.str().c_str());
       if ( signal ) signal = false;
       goto gonext;      
       //
@@ -2385,10 +2649,10 @@
       if ( IsDebug() ) printf(" The new run has the same number of events and the runheader the old one miss the runheader \n");
       //
       glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
-//       oss.str("");
-//       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
-//       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
-//       conn->Query(oss.str().c_str());
+      //       oss.str("");
+      //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
+      //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
+      //       conn->Query(oss.str().c_str());
       //
       if ( signal ) signal = false;
       goto gonext;
@@ -2403,10 +2667,10 @@
       if ( IsDebug() ) printf(" The new run has the same number of events, the runheader and the runtrailer the old one miss the runtrailer \n");
       //
       glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
-//       oss.str("");
-//       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
-//       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
-//       conn->Query(oss.str().c_str());
+      //       oss.str("");
+      //       oss << "DELETE FROM GL_RUN WHERE ID=" << row->GetField(0) <<";";
+      //       if ( IsDebug() ) printf(" delete the run entry: query is \n %s \n",oss.str().c_str());      
+      //       conn->Query(oss.str().c_str());
       if ( signal ) signal = false;
       //
     };
@@ -2488,526 +2752,852 @@
     if ( IsDebug() ) printf("The run is not consistent, it contains non-physics packets! The run has been handled \n");
     //
   } 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 ){
     //
-    // 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
     //
-    if ( IsDebug() ) printf(" The run is new \n");
-    if ( IsDebug() ) printf(" -> fill the GL_RUNFRAGMENTS table \n");
+    if ( firstev != (lastev+1) ){ // could be a problem sometimes (?)
+      if ( rhfirstev != firstev && !mishead ) mishead = true;
+      if ( rtlastev != lastev && !mistrail ) mistrail = true;
+    }; 
     //
-    glrun->SetID(this->AssignRunID());
-    glrun->SetID_RUN_FRAG(0);
-    glrun->Fill_GL_RUN_FRAGMENTS(conn);
+    if ( IsDebug() ) printf(" bhere firstev is %i lastev is %i \n",firstev,lastev);
+    this->FillClass(mishead,mistrail,firstev,lastev);
+    if ( IsDebug() ) printf(" chere firstev is %i lastev is %i \n",firstev,lastev);
     //
-  } else {
-    if ( IsDebug() ) printf(" The run is already present in the fragment table \n");
-    if ( PEDANTIC ) throw -69;
-    return;
-  };
-  //
-  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
+    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,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!!
+    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(" 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());
     result = conn->Query(oss.str().c_str());
     //
     if ( !result ) throw -4;
     //
     row = result->Next();
     //
-    if ( !row && NoFrag() ){
+    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, relaxed %u \n",RELAXED);
+      if ( !RELAXED ){
+	if ( PEDANTIC ) throw -69;
+	return;
+      } else {
+	glrun->SetID((UInt_t)atoll(row->GetField(0)));
+	glrun->SetID_RUN_FRAG(0);
+      };
+    };
+    //
+    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
       //
       oss.str("");
-      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 "
 	  << " 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!!
+	  << " 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());
+      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;
       //
-      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 ( !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 ( !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)));
+      if ( !row ){
+	if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
+	found = false;
+      } else {
+	//
+	found = false; // default value
+	//
+	if ( IsDebug() ) printf(" A Found a possible candidate, checking if it is the good one... \n");
 	//
-	chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;   
+	// if we have both runheader and runtrailer we can check with pkt_counter:
 	//
-	if ( labs(chkpkt-pktt)<2 ){ 
+	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)));
 	  //
-	  if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt); 
+	  chkpkt = pkth + (ULong64_t)glrun->GetPKT_COUNTER() + 1ULL + 1ULL;   
 	  //
-	  found = true;
+	  if ( labs(chkpkt-pktt)<2 ){ 
+	    //
+	    if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt); 
+	    //
+	    found = true;
+	    if ( IsDebug() ) printf(" where firstev is %i lastev is %i \n",firstev,lastev);
+	    //
+	  } else {
+	    //
+	    if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt); 	    
+	    //
+	    found = false;
+	    //
+	  };
+	};
+	if ( !found && chewbacca ) goto justcheck;
+	if ( !found ){
 	  //
-	} 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
 	  //
-	  if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt); 	    
+	  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);
 	  //
-	  found = false;
+	  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 && chewbacca ) goto justcheck;
-      if ( !found ){
+      //
+      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 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 ){
+	  glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
+	  glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
+	};
 	//
-	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);
+	GL_RUN *glrun1 = new GL_RUN();
 	//
-	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 {
+	//      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
+	if ( IsDebug() ) printf(" there firstev is %i lastev is %i \n",firstev,lastev);
+	//
+	// 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());
+	//
+	if ( IsDebug() ) printf(" here firstev is %i lastev is %i \n",firstev,lastev);
+	//
+	glrun->SetEV_FROM(firstev);
+	glrun->SetEV_TO(lastev); // EM 10 RED ghost run bug
+	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 ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
+	if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
+	//
+	if ( !IsRunAlreadyInserted() ){
+	  //
+	  //	glrun->SetID(this->AssignRunID());
+	  glrun->SetID_RUN_FRAG(glrun1->GetID());
+	  glrun->Fill_GL_RUN(conn);
 	  //
-	  if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3); 
+	  // set id number
 	  //
-	  found = false;
+	  glrun1->SetID_RUN_FRAG(glrun->GetID());
+	  glrun1->Fill_GL_RUN(conn);
 	  //
 	};
-      };
-    };
-    //
-    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() ){
+	// delete old entry in fragment table
+	//
+	glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
+	glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
 	//
-	//	glrun->SetID(this->AssignRunID());
-	glrun->SetID_RUN_FRAG(glrun1->GetID());
-	glrun->Fill_GL_RUN(conn);
+	delete glrun1;
 	//
-	// set id number
 	//
-	glrun1->SetID_RUN_FRAG(glrun->GetID());
-	glrun1->Fill_GL_RUN(conn);
+	return;
 	//
       };
-      // delete old entry in fragment table
-      //
-      glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
-      glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
-      //
-      delete glrun1;
-      //
-      //
-      return;
       //
     };
     //
-  };
-  //
-  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() ){
+    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 WHERE "
+      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 
-	  << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
+	  << " ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
       //
-      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());
       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 ( !row && NoFrag() ){
+	//
+	oss.str("");
+	oss << " SELECT ID,PKT_COUNTER,RUNHEADER_TIME,RUNHEADER_OBT,RUNTRAILER_PKT,RUNHEADER_PKT FROM GL_RUN WHERE "
+	    << " BOOT_NUMBER=" << this->GetBOOTnumber() << " AND "
+	    << " RUNTRAILER_TIME >= " << (UInt_t)glrun->GetRUNTRAILER_TIME() << " AND "
+	    << " ID != " << glrun->ID 
+	    << " AND ID=ID_RUN_FRAG ORDER BY RUNTRAILER_TIME ASC LIMIT 1;";
+	//
+	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 ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){
-	ULong64_t chkpkt = 0;  
-	ULong64_t pktt = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
-	ULong64_t pkth = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
+      if ( !row ){
+	if ( IsDebug() ) printf(" the corresponding piece has NOT been found \n");
+	found = false;
+      } else {
+	//
+	found = false; // default value
 	//
-	chkpkt = pkth + (ULong64_t)((UInt_t)atoll(row->GetField(1))) + 1ULL + 1ULL;   
+	if ( IsDebug() ) printf(" B Found a possible candidate, checking if it is the good one... \n");
 	//
-	if ( labs(chkpkt-pktt)<2 ){ 
+	// if we have both runheader and runtrailer we can check with pkt_counter:
+	//
+	if ( !mishead && (UInt_t)atoll(row->GetField(1)) != 0 ){
+	  ULong64_t chkpkt = 0;  
+	  ULong64_t pktt = (ULong64_t)PKT((UInt_t)atoll(row->GetField(4)));
+	  ULong64_t pkth = (ULong64_t)PKT(glrun->GetRUNHEADER_PKT());
 	  //
-	  if ( IsDebug() ) printf(" FOUND!!! check %llu pktt %llu \n",chkpkt,pktt); 
+	  chkpkt = pkth + (ULong64_t)((UInt_t)atoll(row->GetField(1))) + 1ULL + 1ULL;   
 	  //
-	  found = true;
+	  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 justcheck;
+	if ( !found ){
 	  //
-	} 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
 	  //
-	  if ( IsDebug() ) printf(" The check with pkt counter failed: check %llu pktt %llu \n",chkpkt,pktt); 	    
+	  ULong64_t chkpkt1 = 0;
+	  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);
 	  //
-	  found = false;
+	  ULong64_t chkpkt2 = 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);
+	  //
+	  ULong64_t chkpkt3 = 0;
+	  ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNTRAILER_TIME());
+	  ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
+	  chkpkt3 = labs(orunh3-dbrunt3);
 	  //
+	  if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
+	    //
+	    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 && chewbacca ) goto justcheck;
-      if ( !found ){
+      //
+      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 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 ){
+	  glrun->RestoreRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
+	  glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN");
+	};
 	//
-	ULong64_t chkpkt1 = 0;
-	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);
+	GL_RUN *glrun1 = new GL_RUN();
 	//
-	ULong64_t chkpkt2 = 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);
+	//      UInt_t idfrag = (UInt_t)atoll(row->GetField(0));
 	//
-	ULong64_t chkpkt3 = 0;
-	ULong64_t orunh3 = (ULong64_t)(glrun->GetRUNTRAILER_TIME());
-	ULong64_t dbrunt3 = (ULong64_t)((UInt_t)atoll(row->GetField(2)));
-	chkpkt3 = labs(orunh3-dbrunt3);
+	oss.str("");
+	oss << " ID="<<row->GetField(0)<<";";
 	//
-	if ( (chkpkt1 < 200 || chkpkt2 < 20000) && chkpkt3 < 20 ){
-	  //
-	  if ( IsDebug() ) printf(" FOUND!!! check1 %llu<200 cechk2 %llu<20000 check3 %llu<20 \n",chkpkt1,chkpkt2,chkpkt3); 
-	  //
-	  found = true;
-	  //
-	} else {
+	glrun1->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn); // here we have runtrailer infos
+	//
+	// merge infos
+	//
+	UInt_t apkt = PKT(glrun->GetRUNTRAILER_PKT());
+	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 && !RELAXED) throw -72;
+	};
+	if ( IsDebug() ) printf(" Check overlapping events done: %u %u %llu %llu lastev is %i\n",apkt,bpkt,aobt,bobt,lastev);
+	//
+	glrun->SetEV_FROM(firstev); // EM 10RED ghost run bug
+	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());  
+	//
+	if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ) glrun1->SetPHYSENDRUN_MASK_S3S2S12(glrun->GetPHYSENDRUN_MASK_S3S2S12());
+	if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) glrun1->SetPHYSENDRUN_MASK_S11CRC(glrun->GetPHYSENDRUN_MASK_S11CRC());
+	//
+	if ( !IsRunAlreadyInserted() ){
+	  //
+	  //	glrun->SetID(this->AssignRunID());
+	  //
+	  glrun->SetID_RUN_FRAG(glrun1->GetID());
+	  glrun->Fill_GL_RUN(conn);
 	  //
-	  if ( IsDebug() ) printf(" Check failed: check1 %llu<200? cechk2 %llu<20000? check3 %llu<20? \n",chkpkt1,chkpkt2,chkpkt3); 
+	  // set id number
 	  //
-	  found = false;
+	  glrun1->SetID_RUN_FRAG(glrun->GetID());
+	  glrun1->Fill_GL_RUN(conn);
 	  //
 	};
+	//
+	// delete old entries in fragment table
+	//
+	glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
+	glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
+	//
+	delete glrun1;
+	//
+	return;
+	//
       };
+      //
     };
     //
-    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");
-      };
+  justcheck:
+    //
+    if ( !found ){      
       //
-      GL_RUN *glrun1 = new GL_RUN();
+      if ( IsDebug() ) printf(" not found, check if we have already processed the file \n "); 
       //
-      //      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?
       //
       oss.str("");
-      oss << " ID="<<row->GetField(0)<<";";
+      oss << " SELECT ID,ID_ROOT_L0 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() << ") ));";
       //
-      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());
+      result = conn->Query(oss.str().c_str());
       //
-      // merge infos
+      if ( !result ) throw -4;
       //
-      UInt_t apkt = PKT(glrun->GetRUNTRAILER_PKT());
-      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());  
+      row = result->Next();
       //
-      if ( !IsRunAlreadyInserted() ){
-	//
-	//	glrun->SetID(this->AssignRunID());
+      if ( row ){
 	//
-	glrun->SetID_RUN_FRAG(glrun1->GetID());
-	glrun->Fill_GL_RUN(conn);
+	// 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 
+	// "small gap" piece... we recognize this since: we have two entries from this query, the pkt number is consistent with our pkt number.
 	//
-	// set id number
+	// 090112 [8RED (-70): RUN ALREADY INSERTED]
+	// 093012 [8RED (-70): RUN ALREADY INSERTED] try to be more general... the run has not been instered yet if the runheader-trailer PKT interval is not covered by already inserted runs, NOTICE: we must look in the GL_RUN_TRASH table!
 	//
-	glrun1->SetID_RUN_FRAG(glrun->GetID());
-	glrun1->Fill_GL_RUN(conn);
+	Bool_t OK = false;
+	UInt_t IDRL2A = 0;
+	UInt_t IDRL2B = 0;
+	if ( chewbacca ){
+	  if ( result->GetRowCount() >= 2 ){
+	    //
+	    if ( IsDebug() ) printf(" RH---| gap |---RT case, number of pieces in the GL_RUN table: %i \n",result->GetRowCount());
+	    OK = true;
+	    IDRL2A = (UInt_t)atoll(row->GetField(0));
+	    //
+	    while ( row ){
+	      //
+	      TSQLResult *trresult = 0;
+	      TSQLRow    *trrow    = 0;
+	      //
+	      stringstream tross;
+	      tross.str("");
+	      //
+	      tross << " SELECT RUNHEADER_PKT, RUNTRAILER_PKT FROM GL_RUN_TRASH where ID=" << row->GetField(0) << ";";
+	      if ( IsDebug() ) printf(" check in the gl_run_trash table for pkt intervals: query is \n %s \n",tross.str().c_str());
+	      trresult = conn->Query(tross.str().c_str());
+	      if ( !trresult ) throw -4;
+	      trrow = trresult->Next();
+	      if ( !trrow || trresult->GetRowCount() != 1 ){
+		OK = false;
+		if ( IsDebug() ) printf(" OPS! no such run (or multiple runs!) in GL_RUN_TRASH table, something wrong is going on! \n");
+		break;
+	      };
+	      //
+	      UInt_t pktH =  (UInt_t)atoll(row->GetField(0));
+	      UInt_t pktT =  (UInt_t)atoll(row->GetField(1));
+	      delete trresult;
+	      if (
+		  (PKT(pktH) >= PKT(glrun->GetRUNHEADER_PKT()) && PKT(pktH) <= PKT(glrun->GetRUNTRAILER_PKT())) ||
+		  (PKT(pktT) >= PKT(glrun->GetRUNHEADER_PKT()) && PKT(pktT) <= PKT(glrun->GetRUNTRAILER_PKT())) ||
+		  (PKT(pktH) <= PKT(glrun->GetRUNTRAILER_PKT()) && PKT(pktT) >= PKT(glrun->GetRUNTRAILER_PKT())) ){	       
+		OK = false;
+		if ( IsDebug() ) printf(" The run is overlapping with already inserted ones!! \n");
+		break;		
+	      };
+	      //PKT(glrun->GetRUNHEADER_PKT())  PKT(glrun->GetRUNTRAILER_PKT())
+	      row = result->Next();
+	    };
+	    
+	    //	  if ( result->GetRowCount() == 2 ) {
+	    // 	    IDRL2A = (UInt_t)atoll(row->GetField(0));
+	    // 	    UInt_t IDRL0A = (UInt_t)atoll(row->GetField(1));
+	    // 	    row = result->Next();
+	    // 	    IDRL2B = (UInt_t)atoll(row->GetField(0));
+	    // 	    UInt_t IDRL0B = (UInt_t)atoll(row->GetField(1));
+	    // 	    if ( IsDebug() ) printf(" IDRL0A %u B %u IDRL2A %u B %u \n",IDRL0A,IDRL0B,IDRL2A,IDRL2B);
+	    // 	    //	    if ( IDRL0A == IDRL0B ){ //091230 why this condition???? RH could be in a file and RT in another one...
+	    // 	    if ( true ){
+	    // 	      TSQLResult *result2 = 0;
+	    // 	      TSQLRow    *row2    = 0;
+	    // 	      oss.str("");
+	    // 	      oss << "select PKT_NUMBER_FINAL from ROOT_TABLE_MERGING where REAL_TIME_INIT<" << chrtinit << " order by REAL_TIME_INIT desc limit 1;";
+	    // 	      if ( IsDebug() ) printf(" Check if we are in the case RH---| small gap |---RT: query is \n %s \n",oss.str().c_str());
+	    // 	      result2 = conn->Query(oss.str().c_str());
+	    // 	      //
+	    // 	      if ( !result2 ) throw -4;
+	    // 	      //
+	    // 	      row2 = result2->Next();
+	    // 	      //
+	    // 	      if ( row2 ){
+	    // 		UInt_t PKA = (UInt_t)atoll(row2->GetField(0));
+	    // 		delete result2;
+	    // 		oss.str("");
+	    // 		oss << "select PKT_NUMBER_INIT from ROOT_TABLE_MERGING where REAL_TIME_INIT>" << chrtinit << " order by REAL_TIME_INIT asc limit 1;";
+	    // 		if ( IsDebug() ) printf(" Check if we are in the case RH---| small gap |---RT: query is \n %s \n",oss.str().c_str());
+	    // 		result2 = conn->Query(oss.str().c_str());
+	    // 		//
+	    // 		if ( !result2 ) throw -4;
+	    // 		//
+	    // 		row2 = result2->Next();
+	    // 		//
+	    // 		if ( row2 ){
+	    // 		  UInt_t PKB = (UInt_t)atoll(row2->GetField(0));
+	    // 		  //
+	    // 		  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);
+	    // 		  if ( PKT(PKA)+1LL == PKT(glrun->GetRUNHEADER_PKT()) && PKT(PKB) == PKT(glrun->GetRUNTRAILER_PKT())+1LL ){
+	    // 		    if ( IsDebug() ) printf(" Ok, we are in the case: RH---| small gap |---RT \n");
+	    // 		    OK = true;
+	    // 		  };
+	    // 		};
+	    // 	      };		  
+	    // 	    };
+	    // 	  };	  
+	  };
+	};
+	if ( OK ){
+	  //
+	  // this is the case in which we must insert a piece of run between two fragments in the GL_RUN table // we arrive here ONLY with internal pieces of runs, never runheader or runtrailer by definition	  
+	  //
+	  // 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 )
+	  //
+	  if ( IsDebug() ) printf(" Ok, we are in the case: RH---| small gap |---RT \n");
+	  //
+	  GL_RUN *glA = new GL_RUN();
+	  glA->Query_GL_RUN(IDRL2A,conn);
+	  //
+	  glrun->SetRUNHEADER_TIME(glA->GetRUNHEADER_TIME());
+	  glrun->SetRUNHEADER_OBT(glA->GetRUNHEADER_OBT());
+	  glrun->SetRUNHEADER_PKT(glA->GetRUNHEADER_PKT());
+	  //
+	  glrun->SetRUNTRAILER_TIME(glA->GetRUNTRAILER_TIME());
+	  glrun->SetRUNTRAILER_OBT(glA->GetRUNTRAILER_OBT());
+	  glrun->SetRUNTRAILER_PKT(glA->GetRUNTRAILER_PKT());
+	  //
+	  if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glA->GetPHYSENDRUN_MASK_S3S2S12());
+	  if ( glA->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glA->GetPHYSENDRUN_MASK_S11CRC());
+	  //	      
+	  if ( glA->GetACQ_BUILD_INFO() != 0 ){
+	    //
+	    // the first piece contains a good runheader we can update all the other runs with correct infos!
+	    //
+	    glrun->SetCOMPILATIONTIMESTAMP(glA->GetCOMPILATIONTIMESTAMP());
+	    glrun->SetFAV_WRK_SCHEDULE(glA->GetFAV_WRK_SCHEDULE());
+	    glrun->SetEFF_WRK_SCHEDULE(glA->GetEFF_WRK_SCHEDULE());
+	    glrun->SetPRH_VAR_TRG_MODE_A(glA->GetPRH_VAR_TRG_MODE_A());
+	    glrun->SetPRH_VAR_TRG_MODE_B(glA->GetPRH_VAR_TRG_MODE_B());
+	    glrun->SetACQ_BUILD_INFO(glA->GetACQ_BUILD_INFO());
+	    glrun->SetACQ_VAR_INFO(glA->GetACQ_VAR_INFO());
+	    glrun->SetRM_ACQ_AFTER_CALIB(glA->GetRM_ACQ_AFTER_CALIB());
+	    glrun->SetRM_ACQ_SETTING_MODE(glA->GetRM_ACQ_SETTING_MODE());
+	    glrun->SetTRK_CALIB_USED(glA->GetTRK_CALIB_USED());
+	    glrun->SetCAL_DSP_MASK(glA->GetCAL_DSP_MASK());
+	    glrun->SetLAST_TIMESYNC(glA->GetLAST_TIMESYNC());
+	    glrun->SetOBT_TIMESYNC(glA->GetOBT_TIMESYNC());
+	    //
+	  };
+	  //
+	  if ( glA->GetPKT_READY_COUNTER() != 0 ){
+	    //
+	    // the first piece contains a good runtrailer we can update all the other runs with correct infos!
+	    //
+	    glrun->SetPKT_COUNTER(glA->GetPKT_COUNTER());
+	    glrun->SetPKT_READY_COUNTER(glA->GetPKT_READY_COUNTER());
+	  };
+	  //
+	  // update runheader ROOT_ID_FRAG
+	  //
+	  oss.str("");
+	  oss << "UPDATE GL_RUN SET ID_RUN_FRAG = " << glrun->GetID() << " where ID = " << IDRL2A << ";";
+	  if ( IsDebug() ) printf(" update gl_run to have cross indexing: %s\n",oss.str().c_str());
+	  conn->Query(oss.str().c_str());
+	  //
+	  oss.str("");
+	  oss << "SELECT ID FROM GL_RUN WHERE ID_RUN_FRAG = " << IDRL2A << ";";
+	  if ( IsDebug() ) printf(" update gl_run to have cross indexing: %s\n",oss.str().c_str());
+	  TSQLResult *tsresult = 0;
+	  TSQLRow    *tsrow    = 0;
+	  tsresult=conn->Query(oss.str().c_str());
+	  if ( !tsresult ) throw -4;
+	  tsrow = tsresult->Next();
+	  if ( !tsrow || tsresult->GetRowCount() != 1 ) throw -4;
+	  IDRL2B = (UInt_t)atoll(tsrow->GetField(0));
+	  glrun->SetID_RUN_FRAG(IDRL2B);
+	  //
+	  // fill the new run in GL_RUN
+	  //
+	  glrun->Fill_GL_RUN(conn);	
+	  //
+	  glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
+	  delete glA;
+	  //
+	} else {
+// 	  //
+// 	  // this is the case in which we must insert a piece of run between two fragments in the GL_RUN table
+// 	  //
+// 	  // 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 )
+// 	  //
+// 	  GL_RUN *glA = new GL_RUN();
+// 	  glA->Query_GL_RUN(IDRL2A,conn);
+// 	  //
+// 	  if ( glA->GetACQ_BUILD_INFO() != 0 ){
+// 	    //
+// 	    // the first piece contains a good runheader we can update all the other runs with correct infos!
+// 	    //
+// 	    oss.str("");
+// 	    oss << "UPDATE GL_RUN_FRAGMENTS SET "
+// 		<< " RUNHEADER_TIME=" << glA->GetRUNHEADER_TIME()<< " , "
+// 		<< " RUNHEADER_OBT=" << glA->GetRUNHEADER_OBT()<< " , "
+// 		<< " RUNHEADER_PKT=" << glA->GetRUNHEADER_PKT()<< " , "
+// 		<< " COMPILATIONTIMESTAMP=" << glA->GetCOMPILATIONTIMESTAMP()<< " , "
+// 		<< " FAV_WRK_SCHEDULE=" << glA->GetFAV_WRK_SCHEDULE()<< " , "
+// 		<< " EFF_WRK_SCHEDULE=" << glA->GetEFF_WRK_SCHEDULE()<< " , "
+// 		<< " PRH_VAR_TRG_MODE_A=" << glA->GetPRH_VAR_TRG_MODE_A()<< " , "
+// 		<< " PRH_VAR_TRG_MODE_B=" << glA->GetPRH_VAR_TRG_MODE_B()<< " , "
+// 		<< " ACQ_BUILD_INFO=" << glA->GetACQ_BUILD_INFO()<< " , "
+// 		<< " ACQ_VAR_INFO=" << glA->GetACQ_VAR_INFO()<< " , "
+// 		<< " RM_ACQ_AFTER_CALIB=" << glA->GetRM_ACQ_AFTER_CALIB()<< " , "  
+// 		<< " RM_ACQ_SETTING_MODE=" << glA->GetRM_ACQ_SETTING_MODE()<< " , "  
+// 		<< " TRK_CALIB_USED=" << glA->GetTRK_CALIB_USED()<< " , "  
+// 		<< " CAL_DSP_MASK=" << glA->GetCAL_DSP_MASK()<< " , "  
+// 		<< " LAST_TIMESYNC=" << glA->GetLAST_TIMESYNC()<< " , ";
+// 	    //
+// 	    if ( glA->GetPHYSENDRUN_MASK_S3S2S12() )
+// 	      oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12() << " , "; 
+// 	    if ( glA->GetPHYSENDRUN_MASK_S11CRC() )
+// 	      oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC() << " , ";
+// 	    //	      
+// 	    oss << " OBT_TIMESYNC=" << glA->GetOBT_TIMESYNC();
+// 	    oss << " WHERE ID=" << glrun->GetID() << ";";
+// 	    if ( IsDebug() ) printf(" update with correct infos: %s\n",oss.str().c_str());
+// 	    conn->Query(oss.str().c_str());	
+// 	    //
+// 	  } else {
+// 	    //
+// 	    // sig no runheader, let set anyway what is possible...
+// 	    //
+// 	    oss.str("");
+// 	    oss << "UPDATE GL_RUN_FRAGMENTS SET "
+// 		<< " RUNHEADER_TIME=" << glA->GetRUNHEADER_TIME()<< " , ";
+// 	    //
+// 	    if ( glA->GetPHYSENDRUN_MASK_S3S2S12() )
+// 	      oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , ";
+// 	    if ( glA->GetPHYSENDRUN_MASK_S11CRC() )
+// 	      oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; 
+// 	    //	      
+// 	    oss << " RUNHEADER_OBT=" << glA->GetRUNHEADER_OBT()<< " , "
+// 		<< " RUNHEADER_PKT=" << glA->GetRUNHEADER_PKT();
+// 	    oss << " WHERE ID=" << glrun->GetID() << ";";
+// 	    if ( IsDebug() ) printf(" update with correct infos2: %s\n",oss.str().c_str());
+// 	    conn->Query(oss.str().c_str());	
+// 	  };
+// 	  //
+// 	  // update runheader ROOT_ID_FRAG
+// 	  //
+// 	  oss.str("");
+// 	  oss << "UPDATE GL_RUN SET ID_RUN_FRAG = " << glrun->GetID() << " where ID = " << IDRL2A << ";";
+// 	  if ( IsDebug() ) printf(" update gl_run to have cross indexing: %s\n",oss.str().c_str());
+// 	  conn->Query(oss.str().c_str());
+// 	  //
+// 	  // now let's look for runtrailer if any in the last run
+// 	  //
+// 	  glA->Query_GL_RUN(IDRL2B,conn);
+// 	  //
+// 	  if ( glA->GetPKT_READY_COUNTER() != 0 ){
+// 	    //
+// 	    // the first piece contains a good runtrailer we can update all the other runs with correct infos!
+// 	    //
+// 	    oss.str("");
+// 	    oss << "UPDATE GL_RUN_FRAGMENTS SET "
+// 		<< " RUNTRAILER_TIME=" << glA->GetRUNTRAILER_TIME()<< " , "
+// 		<< " RUNTRAILER_OBT=" << glA->GetRUNTRAILER_OBT()<< " , "
+// 		<< " RUNTRAILER_PKT=" << glA->GetRUNTRAILER_PKT()<< " , "
+// 		<< " PKT_COUNTER=" << glA->GetPKT_COUNTER()<< " , ";
+// 	    //
+// 	    if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ){
+// 	      oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
+// 	    if ( glA->GetPHYSENDRUN_MASK_S11CRC() ) {
+// 	      oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
+// 	    //	      
+// 	    oss << " PKT_READY_COUNTER=" << glA->GetPKT_READY_COUNTER()
+// 		<< " WHERE ID=" << glrun->GetID() << ";";
+// 	    if ( IsDebug() ) printf(" update with correct trailer infos: %s\n",oss.str().c_str());
+// 	    conn->Query(oss.str().c_str());	
+// 	    //
+// 	  } else {
+// 	    //
+// 	    // sig no runtrailer, let set anyway what is possible...
+// 	    //
+// 	    oss.str("");
+// 	    oss << "UPDATE GL_RUN_FRAGMENTS SET "
+// 		<< " RUNTRAILER_TIME=" << glA->GetRUNTRAILER_TIME()<< " , "
+// 		<< " RUNTRAILER_OBT=" << glA->GetRUNTRAILER_OBT()<< " , ";
+// 	      //
+// 	    if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ){
+// 	      oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
+// 	    if ( glA->GetPHYSENDRUN_MASK_S11CRC() ){
+// 	      oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
+// 	    //	      
+// 	    oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()
+// 		<< " WHERE ID=" << glrun->GetID() << ";";
+// 	    if ( IsDebug() ) printf(" update with correct trailer infos2: %s\n",oss.str().c_str());
+// 	    conn->Query(oss.str().c_str());	
+// 	  };
+// 	  //
+// 	  UInt_t myi = glrun->GetID();
+// 	  oss.str("");
+// 	  oss << " ID= "<< myi;
+// 	  //
+// 	  glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);   
+// 	  //
+// 	  // fill the new run in GL_RUN
+// 	  //
+// 	  glrun->SetID_RUN_FRAG(IDRL2B);
+// 	  glrun->Fill_GL_RUN(conn);	
+// 	  glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
+// 	  delete glA;
+// 	  //
+// 	} else {
+	  //
+	  // is just a repetition
+	  //
+	  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");
+	};     
       };
-      //
-      // delete old entries in fragment table
-      //
-      glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
-      glrun1->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
-      //
-      delete glrun1;
-      //
-      return;
-      //
     };
-    //
-  };
+  }; // EEE
   //
- justcheck:
+  return;
+};
+
+
+/**
+ * Handle run without header or trailer
+ **/
+void PamelaDBOperations::HandleMissingHoT(Bool_t mishead, Bool_t mistrail, UInt_t firstev, UInt_t lastev){  
   //
-  if ( !found ){      
+  //
+  // is the piece of run good (no other packets inside)?
+  //
+  if ( !this->IsRunConsistent(mishead,mistrail,firstev,lastev)){
+    // 
+    // if not, handle other pieces and continue with the first one
     //
-    if ( IsDebug() ) printf(" not found, check if we have already processed the file \n "); 
+    if ( IsDebug() ) printf("The run is not consistent, it contains non-physics packets! The run has been handled \n");
     //
-    // 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
-  //
-  return;
-};
-
-
-/**
- * Handle run without header or trailer
- **/
-void PamelaDBOperations::HandleMissingHoT(Bool_t mishead, Bool_t mistrail, UInt_t firstev, UInt_t lastev){  
-  //
-  //
-  // is the piece of run good (no other packets inside)?
-  //
-  if ( !this->IsRunConsistent(mishead,mistrail,firstev,lastev)){
-    // 
-    // if not, handle other pieces and continue with the first one
-    //
-    if ( IsDebug() ) printf("The run is not consistent, it contains non-physics packets! The run has been handled \n");
-    //
-  } else {
+  } else {
     //
     this->FillClass(mishead,mistrail,firstev,lastev);
     //
@@ -3015,7 +3605,7 @@
       glrun->SetID(this->AssignRunID());
       glrun->SetID_RUN_FRAG(0);
       glrun->Fill_GL_RUN(conn);    // it'ok we arrive here only inside a file hence in the middle of the runs...
-    };
+      };
     //
   };
   //
@@ -3031,7 +3621,7 @@
   //  
   EventCounter *code=0;
   //
-  UInt_t nevent = 0;
+  //  UInt_t nevent = 0;
   UInt_t checkfirst = 0;
   UInt_t checklast = 0;
   UInt_t firstentry = 0;
@@ -3053,12 +3643,13 @@
   EventHeader *eh = 0;
   PscuHeader *ph = 0;
   T->SetBranchAddress("Header", &eh);
-  nevent = T->GetEntries();
+  //  nevent = T->GetEntries();
   //
   //
   if ( firstev == lastev+1 || lastev == firstev ) { // no events inside the run!
     //if ( firstev <= lastev+1 ) { // no events inside the run!
     if ( IsDebug() ) printf(" Checking but no events in the run! \n");
+    firstev = lastev+1; // this is necessary for files with no Physics entries, should have no influence on other files
     // return true is correct
     return(true);
     //
@@ -3068,16 +3659,16 @@
     code = eh->GetCounter();
     checkfirst = 0;
     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
-       if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
-     };
+      if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
+    };
     if ( IsDebug() ) printf(" Check first is %i firstev is %i\n",checkfirst,firstev);
     //
     T->GetEntry(lastev);
     code = eh->GetCounter();
     checklast = 0;
     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
-       if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
-     };
+      if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
+    };
     if ( IsDebug() ) printf(" Check last is %i lastev is %i\n",checklast,lastev);
     //
     if ( checkfirst == checklast ){ 
@@ -3088,16 +3679,18 @@
       //
     } else {
       //
-      if ( IsDebug() ) printf(" There are no-phyics packets inside the run!\n");
+      if ( IsDebug() ) printf(" There are no-physics packets inside the run!\n");
       //
       // HERE WE MUST HANDLE THAT RUNS AND GO BACK
       //
-//      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");
       //
       Bool_t emptyruns = false;
       UInt_t check = 0;
       UInt_t lastevtemp = lastev;
       UInt_t firstevno = firstev;
+      UInt_t rhchko=0;
+      UInt_t rhchk=0;
       //
       for (UInt_t i=firstev; i<=lastev; i++){
 	//
@@ -3106,9 +3699,15 @@
 	//
 	check = 0;
 	//
+
+	// if we have a runheader set lastev then exit
+	//
 	for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
 	  if ( strcmp(*Iter,"Physics") ) check += code->Get(GetPacketType(*Iter));
 	};
+	// check here if we have a runheader
+	rhchko = rhchk;	  
+	rhchk = code->Get(GetPacketType("RunHeader"));	  
 	//
 	if ( checkfirst < check || i == lastev ){
 	  //
@@ -3184,378 +3783,340 @@
 	  };
 	  //	  
 	  this->SetCommonGLRUN(firstTime,lastTime);
+	  this->SetPhysEndRunVariables();
 	  //
 	  if ( chminentry == firstentry  ){ // EEE
             if ( IsDebug() ) printf(" Inside isrunconsistent found a fragment of run at the beginning of the file, put it in the fragment table \n");
-//
-//	    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
-//
-
-
-
-
-
-
-
-
-
-
-
-
-
-  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
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+	    //
+	    //	    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
+	    //
 
+	    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(" C 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->SetEV_TO(lastev); // 10 RED ghost run bug
+		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 ( glrun1->GetPHYSENDRUN_MASK_S3S2S12() ) glrun->SetPHYSENDRUN_MASK_S3S2S12(glrun1->GetPHYSENDRUN_MASK_S3S2S12());
+		if ( glrun1->GetPHYSENDRUN_MASK_S11CRC() ) glrun->SetPHYSENDRUN_MASK_S11CRC(glrun1->GetPHYSENDRUN_MASK_S11CRC());
+		//
+		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
 
 
           } else {
-	  if ( !IsRunAlreadyInserted() ){
-	    glrun->SetID(this->AssignRunID());
-	    glrun->SetID_RUN_FRAG(0);
-	    glrun->Fill_GL_RUN(conn);
-	  };
+	    if ( !IsRunAlreadyInserted() ){
+	      glrun->SetID(this->AssignRunID());
+	      glrun->SetID_RUN_FRAG(0);
+	      glrun->Fill_GL_RUN(conn);
+	    };
           }; // EEE
 	  //
 	  firstevno = lastentry + 1;
@@ -3564,6 +4125,14 @@
 	  //
 	};
 	//
+	if ( i > firstev ){
+	  if ( rhchko != rhchk ){
+	    if ( IsDebug() ) printf("oh oh... we have a runheader! stop here and handle later the remaining piece\n");
+	    lastev = i;
+	    return(false);
+	  };
+	};
+	//
 	if ( check == checklast && i != lastev ){
 	  lastevtemp = i - 1;
 	  i = lastev - 1; 
@@ -3596,7 +4165,7 @@
   EventCounter *code=0;
   UInt_t firstev = 0;
   UInt_t lastev = 0;
-  UInt_t nevent = 0;
+  //  UInt_t nevent = 0;
   UInt_t checkfirst = 0;
   UInt_t checklast = 0;
   UInt_t firstentry = 0;
@@ -3621,7 +4190,7 @@
   EventHeader *eh = 0;
   PscuHeader *ph = 0;
   T->SetBranchAddress("Header", &eh);
-  nevent = T->GetEntries();
+  //  nevent = T->GetEntries();
   //
   codt = eht->GetCounter();
   codh = ehh->GetCounter();
@@ -3647,17 +4216,17 @@
     code = eh->GetCounter();
     checkfirst = 0;
     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
-       if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
-       if ( !strcmp(*Iter,"RunHeader") ) nrunh1++;
-     };
+      if ( strcmp(*Iter,"Physics") ) checkfirst += code->Get(GetPacketType(*Iter));
+      if ( !strcmp(*Iter,"RunHeader") ) nrunh1++;
+    };
     if ( IsDebug() ) printf(" Check first is %i \n",checkfirst);
     //
     T->GetEntry(lastev);
     code = eh->GetCounter();
     checklast = 0;
     for(Iter = packetsNames.begin(); Iter != packetsNames.end(); Iter++){
-       if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
-     };
+      if ( strcmp(*Iter,"Physics") ) checklast += code->Get(GetPacketType(*Iter));
+    };
     if ( IsDebug() ) printf(" Check last is %i \n",checklast);
     //
     if ( checkfirst == checklast ){ 
@@ -3769,6 +4338,7 @@
 	  };
 	  //	  
 	  this->SetCommonGLRUN(firstTime,lastTime);
+	  this->SetPhysEndRunVariables();
 	  //
 	  if ( !IsRunAlreadyInserted() ){
 	    glrun->SetID(this->AssignRunID());
@@ -3808,6 +4378,7 @@
 	    if ( IsDebug() ) printf(" We have the runtrailer \n");
 	    //	  
 	    this->SetCommonGLRUN(firstTime,lastTime);
+	    this->SetPhysEndRunVariables();
 	    //
 	    if ( !IsRunAlreadyInserted() ){
 	      glrun->SetID(this->AssignRunID());
@@ -3853,6 +4424,7 @@
   UInt_t totime = 0;
   UInt_t obt = 0;
   UInt_t pkt = 0;
+  Float_t totped = 0.;
   //
   tr = (TTree*)file->Get("CalibCalPed");
   if ( !tr || tr->IsZombie() ) throw -21;
@@ -3870,6 +4442,22 @@
       if ( calibCalPed->cstwerr[section] ){
 	valid = 1;
 	if ( calibCalPed->cperror[section] ) valid = 0;
+	//
+	// check pedestal values for one plane, if all zeros calibration is not valid (calorimeter power problems) [8th data reduction bug, fixed on 25/11/2009 by E.M.]
+	//
+	totped = 0.;
+	Int_t ns = 0;
+	if ( section == 2 ) ns = 3; 
+	if ( section == 3 ) ns = 1; 
+	if ( section == 1 ) ns = 2; 
+	for (UInt_t ss=0; ss<96; ss++){
+	  totped += fabs(calibCalPed->calped[ns][0][ss]);
+	}
+	if ( totped < 1. ){
+	  if ( IsDebug() ) printf(" Section %i totped %f -  No calibration data! Calorimeter power problems? \n",section,totped);
+	  valid = 0;
+	};
+	//
 	ph = eh->GetPscuHeader();
 	obt = ph->GetOrbitalTime();  
 	pkt = ph->GetCounter();  
@@ -4037,6 +4625,8 @@
   tr->SetBranchAddress("Header", &eh);
   nevents = tr->GetEntries();
   //
+  Float_t totpul = 0.;
+  //
   if ( nevents > 0 ){
     //
     for (UInt_t i=0; i < nevents; i++){
@@ -4046,6 +4636,22 @@
 	if ( cp1->pstwerr[section] && cp1->unpackError == 0 ){
 	  valid = 1;
 	  if ( cp1->pperror[section] ) valid = 0;
+	  //
+	  // check pulse values for one plane, if all zeros calibration is not valid (calorimeter power problems) [8th data reduction bug, fixed on 25/11/2009 by E.M.]
+	  //
+	  totpul = 0.;
+	  Int_t ns = 0;
+	  if ( section == 2 ) ns = 3; 
+	  if ( section == 3 ) ns = 1; 
+	  if ( section == 1 ) ns = 2; 
+	  for (UInt_t ss=0; ss<96; ss++){
+	    totpul += cp1->calpuls[ns][0][ss];
+	  }
+	  if ( totpul >= 3145632. ){
+	    if ( IsDebug() ) printf(" PULSE1 Section %i totpul %f -  No calibration data! Calorimeter power problems? \n",section,totpul);
+	    valid = 0;
+	  };
+	  //
 	  ph = eh->GetPscuHeader();
 	  obt = ph->GetOrbitalTime();  
 	  pkt = ph->GetCounter();  
@@ -4203,6 +4809,22 @@
 	if ( cp2->pstwerr[section] && cp2->unpackError == 0 ){
 	  valid = 1;
 	  if ( cp2->pperror[section] ) valid = 0;
+	  //
+	  // check pulse values for one plane, if all zeros calibration is not valid (calorimeter power problems) [8th data reduction bug, fixed on 25/11/2009 by E.M.]
+	  //
+	  totpul = 0.;
+	  Int_t ns = 0;
+	  if ( section == 2 ) ns = 3; 
+	  if ( section == 3 ) ns = 1; 
+	  if ( section == 1 ) ns = 2; 
+	  for (UInt_t ss=0; ss<96; ss++){
+	    totpul += cp2->calpuls[ns][0][ss];
+	  }
+	  if ( totpul >= 3145632. ){
+	    if ( IsDebug() ) printf(" PULSE2 Section %i totpul %f -  No calibration data! Calorimeter power problems? \n",section,totpul);
+	    valid = 0;
+	  };
+	  //
 	  ph = eh->GetPscuHeader();
 	  obt = ph->GetOrbitalTime();  
 	  pkt = ph->GetCounter();  
@@ -4382,383 +5004,943 @@
  * Fill the GL_TRK_CALIB table
  */
 void PamelaDBOperations::HandleTRK_CALIB(Bool_t pk1, Bool_t pk2){
-  //
-  TSQLResult *result = 0;
-  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;
+    
+    GL_TRK_CALIB *glcal = new GL_TRK_CALIB();
     //
-  } else {
+    glcal->ID         = 0;
+    glcal->ID_ROOT_L0 = GetID_ROOT();
+    glcal->EV_ROOT_CALIBTRK1 = t1;
+    glcal->EV_ROOT_CALIBTRK2 = t2;
+    glcal->FROM_TIME = fromtime;
+    glcal->TO_TIME   = 0;
+    glcal->OBT1      = obt1;
+    glcal->OBT2      = obt2;
+    glcal->PKT1      = pkt1;
+    glcal->PKT2      = pkt2;
+    glcal->BOOT_NUMBER = GetBOOTnumber();
+    glcal->VALIDATION = valid;
     //
-    // we have to insert a new calibration, check where to place it
+    HandleTRK_CALIB(glcal);
     //
-    oss.str("");
-    oss << " SELECT ID,TO_TIME FROM GL_TRK_CALIB WHERE "
-	<< " FROM_TIME < "<< fromtime << " AND "
-	<< " TO_TIME > "<< fromtime << ";";
+    delete glcal;
+}
+/**
+ * Fill the GL_TRK_CALIB table
+ */
+void PamelaDBOperations::HandleTRK_CALIB(GL_TRK_CALIB *glcal){
+
+    Bool_t pk1 = (glcal->OBT1>0&&glcal->PKT1>0);
+    Bool_t pk2 = (glcal->OBT2>0&&glcal->PKT2>0);
+    UInt_t boot_number = glcal->BOOT_NUMBER;
+    UInt_t obt1 = glcal->OBT1;
+    UInt_t obt2 = glcal->OBT2;
+    UInt_t pkt1 = glcal->PKT1;
+    UInt_t pkt2 = glcal->PKT2;
+    UInt_t fromtime = glcal->FROM_TIME;
+    UInt_t totime = 0;
+    UInt_t idroot = glcal->ID_ROOT_L0;
+    UInt_t t1 = glcal->EV_ROOT_CALIBTRK1;
+    UInt_t t2 = glcal->EV_ROOT_CALIBTRK2;
+    UInt_t valid = glcal->VALIDATION;
     //
-    if ( IsDebug() ) printf(" Check where to place the trk calibration: query is \n %s \n",oss.str().c_str());
-    result = conn->Query(oss.str().c_str());
+    TSQLResult *result = 0;
+    TSQLRow    *row    = 0;
     //
-    if ( !result ) throw -4;
+    stringstream oss;
+    oss.str("");
     //
-    row = result->Next();
     //
-    if ( !row ){
-      //
-      // no calibrations in the db contain our calibration
-      //
-      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;
-      //
+    if ( !pk1 && !pk2 ){
+	if ( IsDebug() ) printf(" Cannot handle trk calibration with both packet missing!\n");
+	return;
     };
     //
-    oss.str("");
-    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 << "',";
+    // check if the calibration has already been inserted
     //
-    if ( !pk1 ){
-      oss << "NULL,";
+    oss.str("");
+    oss << " SELECT ID FROM GL_TRK_CALIB WHERE "
+	<< " BOOT_NUMBER = "<< boot_number; // 
+    oss << " AND FROM_TIME="<<fromtime; /// NEWNEWNEW -- VA BENE ?!?!?!?!
+    oss << " AND ( ( ";   
+    if ( pk1 ){
+	oss << " OBT1 = "<< obt1 << " AND "
+	    << " PKT1 = "<< pkt1
+	    << " ) OR ( ";
     } else {
-      oss << "'"
-	  << t1 << "',";
-    };
-    //
-    if ( !pk2 ){
-      oss << "NULL,'";
+	oss << " PKT1 = "<< pkt2-1
+	    << " ) OR ( ";   
+    };      
+    if ( pk2 ){
+	oss << " OBT2 = "<< obt2 << " AND "
+	    << " PKT2 = "<< pkt2;
     } else {
-      oss << "'"
-	  << t2 << "','";
-    };
+	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());
     //
-    oss << fromtime << "','"
-	<< totime << "','"
-	<< obt1 << "','"
-	<< pkt1 << "','"
-	<< obt2 << "','"
-	<< pkt2 << "','"
-	<< this->GetBOOTnumber() << "','"
-	<< valid << "');";
+    if ( !result ) throw -4;
     //
-    if ( IsDebug() ) printf(" Insert the new trk calibration: query is \n %s \n",oss.str().c_str());
+    row = result->Next();
     //
+    if ( row ){
+	//
+	if ( IsDebug() ) printf(" Trk calibration already inserted in the DB\n");
+	if ( PEDANTIC ) throw -80;
+	//
+    } else {
+	//
+	// we have to insert a new calibration, check where to place it
+	//
+	oss.str("");
+	oss << " SELECT ID,TO_TIME FROM GL_TRK_CALIB WHERE "
+	    << " FROM_TIME < "<< fromtime << " AND "
+	    << " TO_TIME > "<< fromtime << ";";
+	//
+	if ( IsDebug() ) printf(" Check where to place the trk 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 ){
+	    //
+	    // no calibrations in the db contain our calibration
+	    //
+	    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;
+	    //
+	};
+	//
+	oss.str("");
+	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 << "',";
+	//
+	if ( !pk1 ){
+	    oss << "NULL,";
+	} else {
+	    oss << "'"
+		<< t1 << "',";
+	};
+	//
+	if ( !pk2 ){
+	    oss << "NULL,'";
+	} else {
+	    oss << "'"
+		<< t2 << "','";
+	};
+	//
+	oss << fromtime << "','"
+	    << totime << "','"
+	    << obt1 << "','"
+	    << pkt1 << "','"
+	    << obt2 << "','"
+	    << pkt2 << "','"
+	    << boot_number << "','"
+	    << valid << "');";
+	//
+	if ( IsDebug() ) printf(" Insert the new trk calibration: query is \n %s \n",oss.str().c_str());
+	//
+	result = conn->Query(oss.str().c_str());
+	//
+	if ( !result ) throw -4;
+	//
+    };
+    
+    oss.str("");
+    oss << " SELECT ID FROM GL_TRK_CALIB ORDER BY ID DESC LIMIT 1 ;";	
+    if ( IsDebug() ) cout << oss.str().c_str() << endl;
     result = conn->Query(oss.str().c_str());
+    if ( !result ) throw -4;;
+    row = result->Next();
+    if(row)glcal->ID = (UInt_t)atoll(row->GetField(0));
     //
-    if ( !result ) throw -4;
+    delete result; // mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
     //
-  };
-  //
 };
 
 /**
  * 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);
+    CalibTrk1Event *caltrk1 = 0;
+    CalibTrk2Event *caltrk2 = 0;
+    TTree *tr1 = 0;
+    TTree *tr2 = 0;
+    EventHeader *eh1 = 0;
+    PscuHeader *ph1 = 0;
+    EventHeader *eh2 = 0;
+    PscuHeader *ph2 = 0;
     //
-    ph1 = eh1->GetPscuHeader();
-    obt1 = ph1->GetOrbitalTime();  
-    pkt1 = ph1->GetCounter();  
-    fromtime = this->GetAbsTime(ph1->GetOrbitalTime());  
+    PacketType *pctp=0;
+    EventCounter *codt2=0;
     //
-//     valid = 1;
-//     //
-//     if ( caltrk1->unpackError != 0 && caltrk1->good0 == 0 ) valid = 0;// CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT1
+    Int_t nevents1 = 0;
+    Int_t nevents2 = 0;
     //
+    fromtime = 0;
     //
-    if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->PKT(pkt1) <= upperpkt && this->OBT(obt1) >= this->OBT(obtfirst) && this->OBT(obt1) <= upperobt ){
-      //    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
+    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;
+    //
+    bool MISSING_pkt1 = true;
+    bool MISSING_pkt2 = true;
+    int  ncalib = 0;
+    bool try_to_recover = false;
+    //
+    for (t1=0; t1 < nevents1; t1++){//loop over packet1
 	//
-	t2++;
+	pret2 = t2;
+	tr1->GetEntry(t1);
 	//
-	pret2 = t2 - 1; // EMILIANO
+	ph1 = eh1->GetPscuHeader();
+	obt1 = ph1->GetOrbitalTime();  
+	pkt1 = ph1->GetCounter();  
+	fromtime = GetAbsTime(ph1->GetOrbitalTime());  
 	//
-	if ( t2 < nevents2 ){
-	  tr2->GetEntry(t2);
-	  codt2 = eh2->GetCounter();
-	  t2t1cal = codt2->Get(pctp->CalibTrk1);
-	  //
-	  ph2 = eh2->GetPscuHeader();
-	  obt2 = ph2->GetOrbitalTime();  
-	  pkt2 = ph2->GetCounter();  
-	  //
-	  if ( IsDebug() ) printf(" This is a trk calibration2 at obt %u pkt %u t2 is %u , t2t1cal is %u \n",obt2,pkt2,t2,t2t1cal);	  
-//	  if ( caltrk2->unpackError != 0 || caltrk2->good0 == 0 ) valid = 0; // CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT2
-	  //	  
-	} else {
-	  //
-	  // running out of vector without finding the corresponding calibration, sig
-	  //
-	  if ( IsDebug() ) printf(" t2 >= nevents2 \n");
-	  pret2 = t2;
-	  obt2 = 0;
-	  //	  pkt2 = pkt1+2;
-	  pkt2 = 0;
-	  t2t1cal = t1+1;
-	};
-	//	if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) && (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){
+	// chek if the packet number and obt are consistent with the other packets ???
+	//
+	if ( PKT(pkt1) >= PKT(pktfirst) && PKT(pkt1) <= upperpkt && OBT(obt1) >= OBT(obtfirst) && OBT(obt1) <= upperobt ){
+	    //    if ( this->PKT(pkt1) >= this->PKT(pktfirst) && this->OBT(obt1) >= this->OBT(obtfirst) ){
+	    //
+	    if ( IsDebug() ) printf("\n Trk calibration1 %u at time %u obt %u pkt %u \n",t1,fromtime,obt1,pkt1);
+	    //      
+	    valid = ValidateTrkCalib( caltrk1, eh1 );
+	    if ( IsDebug() ) cout << " pkt1 validation --> "<<valid<<endl;
+	    //
+	    // Do we have the second calibration packet?
+	    //
+	    if ( IsDebug() ) cout << " Loop over calibration2 to search associated calibration: "<<endl;
+	    while ( t2t1cal < t1+1 ){ // get the calibration packet2 that follows the packet1
+		//
+		t2++;
+		//
+		pret2 = t2 - 1; // EMILIANO
+		//
+		if ( t2 < nevents2 ){
+		    tr2->GetEntry(t2);
+		    codt2 = eh2->GetCounter();
+		    t2t1cal = codt2->Get(pctp->CalibTrk1);
+		    //
+		    ph2 = eh2->GetPscuHeader();
+		    obt2 = ph2->GetOrbitalTime();  
+		    pkt2 = ph2->GetCounter();  
+		    //
+		    if ( IsDebug() ) printf(" >> trk calibration2 at obt %u pkt %u t2 is %u , t2t1cal is %u \n",obt2,pkt2,t2,t2t1cal);	  
+		    //	  if ( caltrk2->unpackError != 0 || caltrk2->good0 == 0 ) valid = 0; // CONDITIONS ON THE GOODNESS OF THE CALIBRATION PKT2
+		    //	  
+		} else {
+		    //
+		    // running out of vector without finding the corresponding calibration, sig
+		    //
+		    if ( IsDebug() ) printf(" t2 >= nevents2 \n");
+		    pret2 = t2;
+		    obt2 = 0;
+		    //	  pkt2 = pkt1+2;
+		    pkt2 = 0;
+		    t2t1cal = t1+1;
+		};
+		//	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;
-// 	};
+		// 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;
+		// 	};
 
 
+		//
+	    };
+	    //
+	    if ( IsDebug() ) printf(" Check if trk calibration2 is the right one \n");
+	    //
+	    // EMILIANO
+	    if ( ( PKT(pkt2) < PKT(pktfirst) || PKT(pkt2) > upperpkt) || (OBT(obt2) < OBT(obtfirst) || OBT(obt2) > upperobt) ){
+		//	if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){
+		if ( IsDebug() ) printf(" *WARNING*  The calibration found is outside the interval, sig \n");
+		//
+		// running out of vector without finding the corresponding calibration, sig
+		//
+		pret2 = t2;
+		obt2 = 0;
+		pkt2 = 0;
+	    };
+	    if ( PKT(pkt2) == PKT(pkt1)+1 ){
+		if ( IsDebug() ) cout << " ...OK"<<endl;
+		// =======================
+		// The calibration is good
+		// =======================
+		//
+//	if ( IsDebug() ) printf(" Found trk calibration2 at obt %u pkt %u t2 is %u \n",obt2,pkt2,t2);
+//	if ( IsDebug() ) printf(" Trk calibration2 at obt %u pkt %u t2 is %u is good \n",obt2,pkt2,t2);
+//        if ( IsDebug() ) printf("\n Trk calibration2 at time %u obt %u pkt %u \n",fromtime,obt2,pkt2);
+		if ( IsDebug() ) printf(" Trk calibration2 %u at time %u obt %u pkt %u \n",t2,fromtime,obt2,pkt2);
+		//
+		UInt_t valid2 = ValidateTrkCalib( caltrk2, eh2 );
+		if ( IsDebug() ) cout << " pkt2 validation --> "<<valid2<<endl;
+//	valid = valid & valid2;
+		valid = valid & valid2; //QUESTO VA CAMBIATO
+		//
+		// Handle good calib
+		//
+		MISSING_pkt1 = false;
+		MISSING_pkt2 = false;
+// 		this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2); 
+		//
+		// Check for missing calibtrk1
+		//
+		if ( t2 != pret2+1 ){
+		    //
+		    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
+			//
+			pret2++;
+			//
+			obt1 = 0;
+			pkt1 = 0;
+			//
+			tr2->GetEntry(pret2);
+			ph2 = eh2->GetPscuHeader();
+			obt2 = ph2->GetOrbitalTime();  
+			pkt2 = ph2->GetCounter();  
+			//
+			fromtime = this->GetAbsTime(ph2->GetOrbitalTime()); 
+			//
+			valid = 0;
+			MISSING_pkt1 = true;
+			MISSING_pkt2 = false;
+// 			this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2); 
+			//
+		    };
+		    //
+		};
+		//
+	    } else if ( this->PKT(pkt2) > this->PKT(pkt1)+1 ){
+		//
+		// Check for missing calibtrk2
+		//
+		if ( IsDebug() ) printf(" Missing the trk calibration2! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);
+		t2 = pret2;
+		//
+		// handle missing calib2
+		//
+		obt2 = 0;
+		pkt2 = 0;
+		valid = 0;
+		MISSING_pkt1 = false;
+		MISSING_pkt2 = true;
+// 		this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2); 
+		//
+	    };
+	    //
+
+	    if( !(MISSING_pkt1&MISSING_pkt2) ){
+	      this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2); 
+	      ncalib++;
+	      if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
+	    }
+
+
+	} 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;
+	    //
+	};
+	//    
+
+    }; //end loop on pkt1
+
+
+
+    //
+    // we have one more calib pkt2 !
+    //
+    t2++;
+    while ( t2 < nevents2 ){
 	//
-      };
-      //
-      if ( IsDebug() ) printf(" Check if trk calibration2 exists \n");
-      //
-      // EMILIANO
-      if ( (this->PKT(pkt2) < this->PKT(pktfirst) || this->PKT(pkt2) > upperpkt) || (this->OBT(obt2) < this->OBT(obtfirst) || this->OBT(obt2) > upperobt) ){
-	//	if ( this->PKT(pkt2) < this->PKT(pktfirst) && this->OBT(obt2) < this->OBT(obtfirst) ){
-	if ( IsDebug() ) printf(" The calibration found is outside the interval, sig \n");
-	//
-	// running out of vector without finding the corresponding calibration, sig
-	//
-	pret2 = t2;
-	obt2 = 0;
-	pkt2 = 0;
-      };
-      //
-      // The calibration is good
-      //
-      if ( this->PKT(pkt2) == this->PKT(pkt1)+1 ){
-	//
-	if ( IsDebug() ) printf(" Found trk calibration2 at obt %u pkt %u t2 is %u \n",obt2,pkt2,t2);
-	if ( IsDebug() ) printf(" The trk calibration2 at obt %u pkt %u t2 is %u is good \n",obt2,pkt2,t2);
-	//
-	UInt_t valid2 = ValidateTrkCalib( caltrk2, eh2 );
-	if ( IsDebug() ) cout << " pkt2 validation --> "<<valid2<<endl;
-	valid = valid & valid2;
-	//
-	// Handle good calib
+	// handle missing calib1
 	//
-	this->HandleTRK_CALIB(true,true);
+	if ( IsDebug() ) printf(" t2 is %u nevents2 is %u \n",t2,nevents2);
+	obt1 = 0;
+	pkt1 = 0;
 	//
-	// Check for missing calibtrk1
+	tr2->GetEntry(t2);
+	ph2 = eh2->GetPscuHeader();
+	obt2 = ph2->GetOrbitalTime();  
+	pkt2 = ph2->GetCounter();  
 	//
-	if ( t2 != pret2+1 ){
-	  //
-	  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
-	    //
-	    pret2++;
-	    //
-	    obt1 = 0;
-	    pkt1 = 0;
-	    //
-	    tr2->GetEntry(pret2);
-	    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) ){
 	    //
-	    fromtime = this->GetAbsTime(ph2->GetOrbitalTime()); 
+	    if ( IsDebug() ) printf(" Missing the trk calibration1! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);
 	    //
-	    valid = 0;
-	    this->HandleTRK_CALIB(false,true);
+	    MISSING_pkt1 = true;
+	    MISSING_pkt2 = false;
+	    this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2); 
+	    ncalib++;
+	    if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
 	    //
-	  };
-	  //
 	};
 	//
-      } else if ( this->PKT(pkt2) > this->PKT(pkt1)+1 ){
-	//
-	// Check for missing calibtrk2
-	//
-	if ( IsDebug() ) printf(" Missing the trk calibration2! Next one at obt %u pkt %u t2 is %u\n",obt2,pkt2,t2);
-	t2 = pret2;
+	t2++;
 	//
-	// handle missing calib2
+    };
+
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
+// -----------------------------------------------------------------
+// in case of corruption, check if the calibration can be recovered 
+// from another chewbacca file
+// -----------------------------------------------------------------
+// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
+
+//    cout <<" TRY TO RECOVER ?? "<<try_to_recover<<endl;
+    
+    if(chewbacca&&try_to_recover){
+
+
+	if ( IsDebug() ) cout << endl << ">>>> TRY TO RECOVER TRACKER CALIBRATIONS <<<<"<<endl;
+
+	TSQLResult *rresult = 0; // 10RED bug, result is re-used inside result looop...
+	TSQLResult *result = 0; // 10RED bug, result is re-used inside result looop...
+	TSQLRow    *row    = 0;
 	//
-	obt2 = 0;
-	pkt2 = 0;
-	valid = 0;
-	this->HandleTRK_CALIB(true,false);       
+	stringstream oss;
+	oss.str("");
 	//
-      };
-      //
-    } 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);
-      //
-    };
-    //
-    t2++;
-    //
-  };
+
+	////////////////////////////////////////////////////////////////////////
+	// retrieve the name of the current file:
+	////////////////////////////////////////////////////////////////////////	
+	oss.str("");
+	oss << "SELECT NAME FROM GL_ROOT where ID=" << GetID_ROOT() <<";";
+	if ( IsDebug() ) cout << oss.str().c_str() << endl;
+
+	result = conn->Query(oss.str().c_str());
+	if ( !result ) throw -4;;
+	row = result->Next();
+	TString thisfilename = (TString)row->GetField(0);
+	if ( IsDebug() ) cout << "Current file ==> "<<thisfilename<<endl;	
+
+	////////////////////////////////////////////////////////////////////////	
+	// read all the calibrations inserted
+	////////////////////////////////////////////////////////////////////////	
+	oss.str("");
+	oss << " SELECT ";
+	oss << " ID,FROM_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,TO_TIME";
+	oss << " FROM GL_TRK_CALIB ";
+	oss << " ORDER BY ID DESC LIMIT "<<ncalib<<"; ";	
+	if ( IsDebug() ) cout << oss.str().c_str() << endl;
+
+	rresult = conn->Query(oss.str().c_str());
+	if ( !result ) throw -4;;
+	if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
+	
+	// -----------------------------------
+	// loop over calibrations ...
+	// -----------------------------------
+	UInt_t nn=0;
+	do {
+            row = rresult->Next();
+	    if(!row)break;
+	    
+	    UInt_t id       = (UInt_t)atoll(row->GetField(0));
+	    UInt_t fromtime = (UInt_t)atoll(row->GetField(1));
+	    UInt_t obt1     = (UInt_t)atoll(row->GetField(2));
+	    UInt_t pkt1     = (UInt_t)atoll(row->GetField(3));
+	    UInt_t obt2     = (UInt_t)atoll(row->GetField(4));
+	    UInt_t pkt2     = (UInt_t)atoll(row->GetField(5));
+	    UInt_t boot     = (UInt_t)atoll(row->GetField(6));
+	    UInt_t valid    = (UInt_t)atoll(row->GetField(7));
+	    bool MISSING_pkt1 = (row->GetFieldLength(8)==0);
+	    bool MISSING_pkt2 = (row->GetFieldLength(9)==0);
+	    UInt_t totime   = (UInt_t)atoll(row->GetField(10));
+
+	    // -------------------------------------
+	    // ...check if the entry is corrupted...
+	    // -------------------------------------
+	    cout <<"*** "<< MISSING_pkt1 << MISSING_pkt2 << valid <<endl;
+	    bool CORRUPTED = (MISSING_pkt1||MISSING_pkt2||!valid);
+
+	    if ( IsDebug() ) cout << "("<<nn<<")  ID = "<<id<<" from GL_TRK_CALIB  ==>  corrupted ? "<<CORRUPTED<<endl;
+
+//	    if( !CORRUPTED  )continue; // nothing to do
+
+	    /////////////////////////////////////////////////////////	
+	    // if it is corrupted, ...look for ather chewbacca files 
+	    // containing the same calibrations ...
+	    /////////////////////////////////////////////////////////
+
+	    bool this_MISSING_pkt1 = false;
+	    bool this_MISSING_pkt2 = false;
+	    int  this_t1=0;
+	    int  this_t2=0;;
+	    UInt_t this_valid = 0;
+
+	    TString path       = "";
+	    TString name       = "";
+	    TString raw        = "";
+            //	    UInt_t obt0        = 0;
+            //	    UInt_t timesync    = 0;
+            //	    UInt_t boot_number = 0;
+	    bool   FOUND       = false;
+
+	    if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
+
+//	    for(int itable=0; itable<2; itable++){
+	    for(int itable=0; itable<1; itable++){
+
+		// ------------------------------------------------------
+		// loop over both ROOT_TABLE and ROOT_TABLE_BAD 
+		// ------------------------------------------------------
+
+		TString table = "ROOT_TABLE";
+		if(itable==1)table = "ROOT_TABLE_BAD";
+
+		oss.str("");
+		oss << " SELECT ";
+		oss << " FOLDER_NAME,FILE_NAME,OBT_TIME_SYNC,LAST_TIME_SYNC_INFO,BOOT_NUMBER,INPUT_NAME ";
+		oss << " FROM "<<table;
+		oss << " WHERE 1 " << endl;
+		oss << " AND FILE_NAME != \""<< thisfilename<<"\"";
+		if( !MISSING_pkt1 ){
+		    oss << " AND ";
+		    oss << " PKT_NUMBER_INIT < "<<pkt1;
+		    oss << " AND ";
+		    oss << " PKT_NUMBER_FINAL > "<<pkt1;
+		    oss << " AND ";
+		    oss << " PKT_OBT_INIT < "<<obt1;
+		    oss << " AND ";
+		    oss << " PKT_OBT_FINAL > "<<obt1;
+		}else{
+		    if(pkt2>1) pkt1 = pkt2-1;//serve dopo		    
+		}
+		if( !MISSING_pkt2 ){
+		    oss << " AND ";
+		    oss << " PKT_NUMBER_INIT < "<<pkt2;
+		    oss << " AND ";
+		    oss << " PKT_NUMBER_FINAL > "<<pkt2;
+		    oss << " AND ";
+		    oss << " PKT_OBT_INIT < "<<obt2;
+		    oss << " AND ";
+		    oss << " PKT_OBT_FINAL > "<<obt2;
+		}else{
+		    if(pkt1>0) pkt2 = pkt1+1;//serve dopo
+		}
+		if( boot> 0 ){
+		    oss << " AND ";
+		    oss << " BOOT_NUMBER = "<<boot;
+		}else{
+		}
+		oss << " ORDER BY BAD_PKT_CALREAD ASC; ";
+	    
+		TSQLResult *result2 = 0;
+		TSQLRow    *row2    = 0;
+
+		if ( IsDebug() ) cout << oss.str().c_str() << endl;	    
+		result2 = conn->Query(oss.str().c_str());
+		if ( !result2 ) throw -4;;
+		if ( IsDebug() ) cout <<"Rows: "<<result2->GetRowCount()<<endl;
+
+		// ------------------------------------------------------
+		// loop over files containing repetition (if any)
+		// ------------------------------------------------------
+		do {
+		    row2 = result2->Next();
+		    if(!row2)break;
+		
+		    // ------------------------------------------------------
+		    // ... a repetition is found ...
+		    // ------------------------------------------------------
+		    path       = (TString)row2->GetField(0);
+		    name       = (TString)row2->GetField(1);
+		    raw        = (TString)row2->GetField(5);
+                    //		    obt0        = (UInt_t)atoll(row2->GetField(2));
+                    //		    timesync    = (UInt_t)atoll(row2->GetField(3));
+                    //		    boot_number = (UInt_t)atoll(row2->GetField(4));
+		
+		    if ( IsDebug() ) cout << "- - - - - - - - - - -" <<endl;
+//		    cout << path <<endl;
+//		    cout << "File    : " <<name <<endl;
+//		    cout << obt0 <<endl;
+//		    cout << timesync <<endl;
+//		    cout << "boot n. : "<<boot_number <<endl;
+//		    cout << raw <<endl;
+
+		    // ------------------------------------------------------
+		    // ... retrieve the calibration packets.
+		    // ------------------------------------------------------
+		    if ( IsDebug() ) printf(" file is %s/%s \n",((TString)gSystem->ExpandPathName(path.Data())).Data(),name.Data());
+		    TFile *file = new TFile(((TString)gSystem->ExpandPathName(path.Data()))+"/"+name); // EM, path could be symbolic and we must expand it
+		    if(!file)throw -100;
+		    if(file->IsZombie())throw -100;
+		    //
+		    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();
+		    for(this_t1=0; this_t1<nevents1; this_t1++){
+			tr1->GetEntry(this_t1);
+			if( 
+			    (UInt_t)eh1->GetPscuHeader()->GetCounter() == pkt1 &&
+			    true) break;
+			this_MISSING_pkt1 = true;
+		    }
+		    for(this_t2=0; this_t2<nevents2; this_t2++){
+			tr2->GetEntry(this_t2);
+			if( 
+			    (UInt_t)eh2->GetPscuHeader()->GetCounter() == pkt2 &&
+			    true) break;
+			this_MISSING_pkt2 = true;
+		    }
+		    this_valid = 
+			ValidateTrkCalib( caltrk1, eh1, file )
+			*
+			ValidateTrkCalib( caltrk2, eh2, file );
+			    
+		    // ---------------------------------------------------------------------
+		    // accept the calibration if it is better than the previous:
+		    //
+		    // - if the new calibration is perfect (both valid packets)
+		    // - if the new calibration has both the packets and the previous does not
+		    // ---------------------------------------------------------------------
+		    if( 
+			( !this_MISSING_pkt1&&!this_MISSING_pkt2&&this_valid )||
+			( (MISSING_pkt1||MISSING_pkt2) && (!this_MISSING_pkt1&&!this_MISSING_pkt2) )||
+			false)FOUND=true;	
+	    
+		    if(file)file->Close();
+
+		    if(FOUND)break;
+
+		}while(1);//endl loop over root table entries
+                
+                delete result2; // 10RED potential memory leak
+		if(FOUND)break;
+
+	    }//end loop over tables 
+
+	    if(FOUND){
+
+	      if ( IsDebug() ) cout << " >>> REPETITION FOUND :-) <<<" <<endl;
+
+	      ////////////////////////////////////////////
+	      // insert a new entry in GL_TRK_CALIB and 
+	      // modify the time-tag of the previous one
+	      ////////////////////////////////////////////
+
+	      // ---------------------------------------------------------------------
+	      // step 1: insert a new raw file in GL_RAW
+	      // ---------------------------------------------------------------------
+	      //
+	      // check if the raw file already exist
+	      //
+	      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
+	      // 		oss.str("");
+	      // 		oss << "SELECT ID FROM GL_RAW where NAME=\"" << gSystem->BaseName(raw.Data()) <<"\";";
+	      // 		if ( IsDebug() ) cout << oss.str().c_str() << endl;
+		
+	      // 		result = conn->Query(oss.str().c_str());
+	      // 		if ( !result ) throw -4;;
+	      // 		if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
+	      // 		if( result->GetRowCount() == 0){
+	      // 		    if ( IsDebug() ) cout << " << Insert new RAW file >> "<<endl;
+	      // 		    // - - - - - - - - - - -
+	      // 		    // insert new raw file
+	      // 		    // - - - - - - - - - - - 
+	      // 		    GL_RAW glraw = GL_RAW();    
+	      // 		    glraw.PATH        = gSystem->DirName(raw.Data());
+	      // 		    glraw.NAME        = gSystem->BaseName(raw.Data());
+	      // 		    glraw.BOOT_NUMBER = boot_number;
+	      // 		    //
+	      // 		    insertPamelaRawFile( &glraw );
+	      // 		    //		    
+	      // 		    id_raw = glraw.ID;		    
+	      // 		}else{
+	      // 		    row = result->Next();
+	      // 		    id_raw = (UInt_t)atoll(row->GetField(0));
+	      // 		}
+	      // 		if ( IsDebug() ) cout << "ID_RAW = "<<id_raw<<endl;
+
+	      // ---------------------------------------------------------------------
+	      // step 1(bis): retrieve the timesync id associated to the file
+	      // (NB, uso lo stesso associato al file iniziale)
+	      // ---------------------------------------------------------------------
+	      UInt_t idtimesync = 0;
+	      oss.str("");
+              oss << " SELECT ID FROM GL_TIMESYNC where TIMESYNC="<<chlastts<<" AND OBT0="<<chobtts*1000<<" and ID_RESURS_OFFSET="<< idresof <<" limit 1;"; // 10RED BUG!!!! without 'and ID_RESURS_OFFSET="<< idresof ' this query is not enough to ensure finding the correct line in GL_TIMSYNC...
+	      if ( debug ) printf(" %s \n",oss.str().c_str());
+	      result = conn->Query(oss.str().c_str());
+	      if ( !result ) throw -3;
+		row = result->Next();
+		if ( !row ) throw -3;
+		idtimesync = (UInt_t)atoll(row->GetField(0));
+		if ( IsDebug() ) cout << "ID_TIMESYNC = "<<idtimesync<<endl;
+		
+		delete result;// mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
+		// ---------------------------------------------------------------------
+		// step 2: insert a new root file in GL_ROOT
+		// ---------------------------------------------------------------------
+		//
+		// check if the root file already exist
+		//
+		UInt_t id_root = 0;
+		oss.str("");
+		oss << "SELECT ID FROM GL_ROOT where NAME=\"" << gSystem->BaseName(name.Data()) <<"\";";
+		if ( IsDebug() ) cout << oss.str().c_str() << endl;
+		
+		result = conn->Query(oss.str().c_str());
+		if ( !result ) throw -4;;
+		if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
+		if( result->GetRowCount() == 0){
+		    if ( IsDebug() ) cout << " << Insert new ROOT file >> "<<endl;
+		    // - - - - - - - - - - -
+		    // insert new root file
+		    // - - - - - - - - - - - 
+		    GL_ROOT glroot = GL_ROOT();		    
+		    glroot.ID_RAW      = id_raw;
+		    glroot.ID_TIMESYNC = idtimesync;
+		    //
+		    // 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, 
+		    //             NOT STATIC NOT KEEPENV = $PAM_L0 must be used in the DB
+		    //
+		    if ( STATIC ){
+		      glroot.PATH        = (TString)gSystem->ExpandPathName(path);
+		    } else {
+		      if ( KEEPENV ){
+			glroot.PATH      = path;
+		      } else {
+			glroot.PATH      = "$PAM_L0";
+		      };
+		    };
+		    //		    glroot.PATH        = path; 
+		    glroot.NAME        = name;
+		    //
+		    insertPamelaRootFile( &glroot );
+		    //		    
+		    id_root = glroot.ID;		    
+		}else{
+		    row = result->Next();
+		    if(row)id_root = (UInt_t)atoll(row->GetField(0));
+		}
+		if ( IsDebug() ) cout << "ID_ROOT = "<<id_root<<endl;
+
+		delete result;// mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
+		// ---------------------------------------------------------------------
+		// step 3: modify time-tag of corrupted GL_TRK_CALIB entry
+		// ---------------------------------------------------------------------
+		if ( IsDebug() ) cout << " << Modify time-tag of calibration ID="<<id<<" >> "<<endl;
+		oss.str("");
+		oss << " UPDATE GL_TRK_CALIB SET "   
+		    << " TO_TIME=0 , FROM_TIME=0  WHERE " 
+		    << " ID = "<< id  << ";";
+		if ( IsDebug() ) cout << oss.str().c_str() << endl;
+		result = conn->Query(oss.str().c_str());
+		if ( !result ) throw -4;;
+
+		delete result; // mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
+
+		// ---------------------------------------------------------------------
+		// step 4: insert the new calibration:
+		// ---------------------------------------------------------------------
+		if ( IsDebug() ) cout << " << Insert new TRK calibration >> "<<endl;
+		//
+		GL_TRK_CALIB glcal = GL_TRK_CALIB();	    
+		//
+		glcal.ID_ROOT_L0        = id_root;
+		glcal.EV_ROOT_CALIBTRK1 = this_t1;
+		glcal.EV_ROOT_CALIBTRK2 = this_t2;
+		glcal.FROM_TIME         = fromtime;
+		glcal.TO_TIME           = totime;
+		glcal.OBT1              = obt1;
+		glcal.OBT2              = obt2;
+		glcal.PKT1              = pkt1;
+		glcal.PKT2              = pkt1;
+		glcal.BOOT_NUMBER       = GetBOOTnumber();
+		glcal.VALIDATION        = this_valid;
+		//
+		HandleTRK_CALIB(&glcal);
+		if ( IsDebug() ) cout << "ID = "<<glcal.ID<<endl;
+		//
+		
+	    }
+	    if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
+
+	}while(1);//end loop over calibrations
+	
+	
+	if( rresult )delete rresult; // 10RED bug
+	if( row    )delete row;
+	
+	
+
+	
+
+
+    }
+
+
+// 	// ------------------------------
+// 	// try to recover the calibration
+// 	// ------------------------------
+// 	cout << "TRY TO RECOVER TRACKER CALIBRATION"<<endl;
+// 	//
+// 	ULong64_t time  = 0; //absolute time
+// 	string    path[100]; //mettere un limite massimo
+// 	int       nrows = 0;
+// 	UInt_t    pkt   = 0;
+// 	UInt_t    obt   = 0;
+// 	char     *type  = "";
+// 	EventHeader *eh   = new EventHeader();
+// 	CalibTrk1Event *c = new CalibTrk1Event();
+	
+//       //
+//       if(which_is_not_valid==1 || which_is_not_valid==3){
+// 	  //
+// 	  cout << "PKT1 --> missing or corrupted "<<endl;
+// 	  type = "CalibTrk1";
+// 	  pkt  = pkt1;
+// 	  obt  = obt1;
+// 	  time = this->GetAbsTime(obt1);
+// 	  if( pkt1 == 0 ){//missing
+// 	      time = this->GetAbsTime(obt2); 
+// 	      pkt  = pkt2-1;	      
+// 	  }
+// 	  //
+//       }else if (which_is_not_valid==2 || which_is_not_valid==3){
+// 	  //
+// 	  cout << "PKT2--> missing or corrupted "<<endl;
+// 	  type = "CalibTrk2 ";
+// 	  pkt  = pkt2;
+// 	  obt  = obt2;
+// 	  time = this->GetAbsTime(obt2);
+// 	  if( pkt2 == 0 ){//missing
+// 	      time = this->GetAbsTime(obt1); 
+// 	      pkt  = pkt1+1;	      
+// 	  }
+// 	  //
+//       }else{
+// 	  cout << "this should not happen!!! "<<endl;
+// 	  trow -666;
+//       }
+      
+//       nrows = Query_ROOT_TABLE(time,conn,path);// get the list of file which might contain the packet
+      
+
+//       for(int r=0; r<nrows; r++){ //loop over rows
+// 	  if(path)cout << r << " >>>> "<<(path+r)->c_str() << endl;
+// 	  /// verifica che il file non sia quello gia` aperto
+//       }
+
+//       ////////////////////////////////////////////////////////////////////////
+
+//       TSQLResult *result = 0;
+//       TSQLRow    *row    = 0;
+//       //
+//       stringstream oss;
+//       oss.str("");
+//       // ----------------------------------------
+//       // read the id of last calibration inserted
+//       // ----------------------------------------
+//       oss.str("");
+//       oss << " SELECT ";
+//       oss << " (ID,ID_ROOT_L0,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,FROM_TIME,TO_TIME,OBT1,PKT1,OBT2,PKT2,BOOT_NUMBER,VALIDATION) ";
+//       oss << " ORDER BY ID DESC LIMIT 1; ";
+      
+//       result = conn->Query(oss.str().c_str());
+//       row = result->Next();
+//       if( !row )throw -666;
+
+//       if( result )delete result;
+//       if( row    )delete row;
+
+//       UInt_t id = (UInt_t)atoll(row->GetField(0));
+
+//       // -------------------------------------
+//       // ...and modify it with new parameters
+//       // -------------------------------------
+      
+
+//   }
   //
   return(0);
 };
@@ -4967,7 +6149,7 @@
     memset(myid,0,500*sizeof(UInt_t));
     //
     oss.str("");
-    oss << "SELECT ID,RUNTRAILER_TIME,RUNTRAILER_PKT,BOOT_NUMBER FROM GL_RUN_FRAGMENTS WHERE INSERT_TIME <= '" << clean_time->AsSQLString() << "'order BY RUNHEADER_TIME asc;";
+    oss << "SELECT ID,RUNTRAILER_TIME,RUNTRAILER_PKT,BOOT_NUMBER FROM GL_RUN_FRAGMENTS WHERE INSERT_TIME <= '" << clean_time->AsSQLString() << "' order BY RUNHEADER_TIME asc;";
     if ( IsDebug() ) printf(" Select from GL_RUN_FRAGMENTS runs older than %s : query is \n %s \n",clean_time->AsSQLString(),oss.str().c_str());
     nresult = conn->Query(oss.str().c_str());
     //
@@ -4998,7 +6180,7 @@
 	  while ( anr ){
 	    //
 	    oss.str("");
-	    oss << "SELECT ID,RUNTRAILER_TIME,RUNTRAILER_PKT,BOOT_NUMBER FROM GL_RUN_FRAGMENTS WHERE BOOT_NUMBER=" << mbo << " AND RUNHEADER_PKT=" << mrhp <<  "+1 AND ABS(RUNHEADER_TIME-"<< mrht <<")<=1 AND INSERT_TIME <= '" << clean_time->AsSQLString() << "' order BY RUNHEADER_TIME asc;";
+	    oss << "SELECT ID,RUNTRAILER_TIME,RUNTRAILER_PKT,BOOT_NUMBER FROM GL_RUN_FRAGMENTS WHERE BOOT_NUMBER=" << mbo << " AND RUNHEADER_PKT=" << mrhp <<  "+1 AND ABS(RUNHEADER_TIME-"<< (float)mrht <<")<=1 AND INSERT_TIME <= '" << clean_time->AsSQLString() << "' order BY RUNHEADER_TIME asc;"; // 10RED MYSQL OPERATOR BUG
 	    if ( IsDebug() ) printf(" In the loop searching for fragmented runs : query is \n %s \n",oss.str().c_str());
 	    //
 	    nresult1 = conn->Query(oss.str().c_str());
@@ -5061,9 +6243,15 @@
 		  << " RM_ACQ_SETTING_MODE=" << glrun->GetRM_ACQ_SETTING_MODE()<< " , "  
 		  << " TRK_CALIB_USED=" << glrun->GetTRK_CALIB_USED()<< " , "  
 		  << " CAL_DSP_MASK=" << glrun->GetCAL_DSP_MASK()<< " , "  
-		  << " LAST_TIMESYNC=" << glrun->GetLAST_TIMESYNC()<< " , "  
-		  << " OBT_TIMESYNC=" << glrun->GetOBT_TIMESYNC() 
-		  << " WHERE ID=" << myid[u] << ";";
+		  << " LAST_TIMESYNC=" << glrun->GetLAST_TIMESYNC()<< " , ";
+	      //
+	      if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
+		oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12() << " , "; 
+	      if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
+		oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC() << " , ";
+	      //	      
+	      oss << " OBT_TIMESYNC=" << glrun->GetOBT_TIMESYNC();
+	      oss << " WHERE ID=" << myid[u] << ";";
 	      conn->Query(oss.str().c_str());	
 	    };
 	    //
@@ -5074,9 +6262,16 @@
 	    for (UInt_t u=1; u <= nid ; u++){
 	      oss.str("");
 	      oss << "UPDATE GL_RUN_FRAGMENTS SET "
-		  << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , "
-		  << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "
-		  << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT()<< ";";
+		  << " RUNHEADER_TIME=" << glrun->GetRUNHEADER_TIME()<< " , ";
+	      //
+	      if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() )
+		oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , ";
+	      if ( glrun->GetPHYSENDRUN_MASK_S11CRC() )
+		oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; 
+	      //	      
+	      oss << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "
+		  << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT();
+	      oss << " WHERE ID=" << myid[u] << ";"; // BUG!!! 090112
 	      conn->Query(oss.str().c_str());	
 	    };	  
 	  };
@@ -5098,8 +6293,14 @@
 		  << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
 		  << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "
 		  << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< " , "
-		  << " PKT_COUNTER=" << glrun->GetPKT_COUNTER()<< " , "
-		  << " PKT_READY_COUNTER=" << glrun->GetPKT_READY_COUNTER()
+		  << " PKT_COUNTER=" << glrun->GetPKT_COUNTER()<< " , ";
+	      //
+	      if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
+		oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
+	      if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ) {
+		oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
+	      //	      
+	      oss << " PKT_READY_COUNTER=" << glrun->GetPKT_READY_COUNTER()
 		  << " WHERE ID=" << myid[u] << ";";
 	      conn->Query(oss.str().c_str());	
 	    };
@@ -5112,8 +6313,15 @@
 	      oss.str("");
 	      oss << "UPDATE GL_RUN_FRAGMENTS SET "
 		  << " RUNTRAILER_TIME=" << glrun->GetRUNTRAILER_TIME()<< " , "
-		  << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , "
-		  << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< ";";
+		  << " RUNTRAILER_OBT=" << glrun->GetRUNTRAILER_OBT()<< " , ";
+	      //
+	      if ( glrun->GetPHYSENDRUN_MASK_S3S2S12() ){
+		oss << " PHYSENDRUN_MASK_S3S2S12=" << glrun->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
+	      if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ){
+		oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
+	      //	      
+	      oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT();
+	      oss << " WHERE ID=" << myid[u] << ";"; // BUG!!! 090112
 	      conn->Query(oss.str().c_str());	
 	    };	  
 	  };
@@ -5164,7 +6372,7 @@
 	      row2 = result2->Next();
 	      //
 	      if ( row2 ){
-		if ( IsDebug() ) printf(" The already exist in the GL_RUN table! \n");
+		if ( IsDebug() ) printf(" The run already exists in the GL_RUN table! \n");
 		if ( PEDANTIC ) throw -83;
 		row2->Close();
 	      };
@@ -5241,7 +6449,7 @@
       glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);   
       //
       oss.str("");
-      oss << " SELECT ID,NEVENTS,TRK_CALIB_USED,PKT_COUNTER FROM GL_RUN WHERE "
+      oss << " SELECT ID,NEVENTS,TRK_CALIB_USED,PKT_COUNTER,ID_ROOT_L0 FROM GL_RUN WHERE "
 	  << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND ("
 	  << " (RUNHEADER_TIME>=" << (UInt_t)(glrun->GetRUNHEADER_TIME()-10) << " AND "
 	  << " RUNTRAILER_TIME<=" << (UInt_t)(glrun->GetRUNTRAILER_TIME()+10) << " AND ("
@@ -5272,47 +6480,238 @@
 	glrun->SetID_RUN_FRAG(glrun->GetID());
 	glrun->Fill_GL_RUN(conn);   
 	//
-// 	oss.str("");
-// 	oss << " SELECT ID FROM GL_RUN WHERE "
-// 	    << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
-// 	    << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
-// 	    << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
-// 	    << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
-// 	    << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
-// 	//
-// 	if ( IsDebug() ) printf(" Look for the ID of the inserted run: query is \n %s \n",oss.str().c_str());
-// 	result2 = conn->Query(oss.str().c_str());
-// 	//
-// 	if ( !result2 ) throw -4;
-// 	//
-// 	row2 = result2->Next();
-// 	//
-// 	if ( !row2 ) throw -25;
-// 	//
-// 	oss.str("");
-// 	oss << " UPDATE GL_RUN SET ID_RUN_FRAG = " << row2->GetField(0) << " WHERE ID = " << row2->GetField(0);
-// 	if ( IsDebug() ) printf(" Update the ID_RUN_FRAG of the inserted run: query is \n %s \n",oss.str().c_str());
-// 	result2 = conn->Query(oss.str().c_str());
-// 	//
-// 	if ( !result2 ) throw -4;
+	// 	oss.str("");
+	// 	oss << " SELECT ID FROM GL_RUN WHERE "
+	// 	    << " BOOT_NUMBER=" << glrun->GetBOOT_NUMBER() << " AND "
+	// 	    << " RUNHEADER_PKT=" << (UInt_t)glrun->GetRUNHEADER_PKT() << " AND "
+	// 	    << " RUNTRAILER_PKT=" << (UInt_t)glrun->GetRUNTRAILER_PKT() << " AND "
+	// 	    << " RUNHEADER_OBT=" << (UInt_t)glrun->GetRUNHEADER_OBT() << " AND "
+	// 	    << " RUNTRAILER_OBT=" << (UInt_t)glrun->GetRUNTRAILER_OBT() << "; ";
+	// 	//
+	// 	if ( IsDebug() ) printf(" Look for the ID of the inserted run: query is \n %s \n",oss.str().c_str());
+	// 	result2 = conn->Query(oss.str().c_str());
+	// 	//
+	// 	if ( !result2 ) throw -4;
+	// 	//
+	// 	row2 = result2->Next();
+	// 	//
+	// 	if ( !row2 ) throw -25;
+	// 	//
+	// 	oss.str("");
+	// 	oss << " UPDATE GL_RUN SET ID_RUN_FRAG = " << row2->GetField(0) << " WHERE ID = " << row2->GetField(0);
+	// 	if ( IsDebug() ) printf(" Update the ID_RUN_FRAG of the inserted run: query is \n %s \n",oss.str().c_str());
+	// 	result2 = conn->Query(oss.str().c_str());
+	// 	//
+	// 	if ( !result2 ) throw -4;
 	//
 	moved++;
 	//
       } else {
-	if ( IsDebug() ) printf(" The already exist in the GL_RUN table! \n");
-	if ( PEDANTIC ) throw -83;
+
+	// questa parte mah mah mah... da controllare
+
+	//
+	// 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 
+	// "small gap" piece... we recognize this since: we have two entries from this query, the pkt number is consistent with our pkt number.
+	//
+	// 090112 [8RED (-70): RUN ALREADY INSERTED]
+	//
+	Bool_t OK = false;
+	UInt_t IDRL2A = 0;
+	UInt_t IDRL2B = 0;
+	  if ( result2->GetRowCount() == 2 ){
+	    IDRL2A = (UInt_t)atoll(row2->GetField(0));
+	    UInt_t IDRL0A = (UInt_t)atoll(row2->GetField(4));
+	    row2 = result2->Next();
+	    IDRL2B = (UInt_t)atoll(row2->GetField(0));
+	    UInt_t IDRL0B = (UInt_t)atoll(row2->GetField(4));
+	    if ( IsDebug() ) printf(" IDRL0A %u B %u IDRL2A %u B %u \n",IDRL0A,IDRL0B,IDRL2A,IDRL2B);
+	    //	    if ( IDRL0A == IDRL0B ){
+// 	      TSQLResult *result2a = 0;
+// 	      TSQLRow    *row2a    = 0;
+// 	      oss.str("");
+// 	      oss << "select PKT_NUMBER_FINAL from ROOT_TABLE_MERGING where REAL_TIME_INIT<" << chrtinit << " order by REAL_TIME_INIT desc limit 1;";
+// 	      if ( IsDebug() ) printf(" Check if we are in the case RH---| small gap |---RT: query is \n %s \n",oss.str().c_str());
+// 	      result2a = conn->Query(oss.str().c_str());
+// 	      //
+// 	      if ( !result2a ) throw -4;
+// 	      //
+// 	      row2a = result2a->Next();
+// 	      //
+// 	      if ( row2a ){
+// 		UInt_t PKA = (UInt_t)atoll(row2a->GetField(0));
+// 		delete result2a;
+// 		oss.str("");
+// 		oss << "select PKT_NUMBER_INIT from ROOT_TABLE_MERGING where REAL_TIME_INIT>" << chrtinit << " order by REAL_TIME_INIT asc limit 1;";
+// 		if ( IsDebug() ) printf(" Check if we are in the case RH---| small gap |---RT: query is \n %s \n",oss.str().c_str());
+// 		result2a = conn->Query(oss.str().c_str());
+// 		//
+// 		if ( !result2a ) throw -4;
+// 		//
+// 		row2a = result2a->Next();
+// 		//
+// 		if ( row2a ){
+// 		  UInt_t PKB = (UInt_t)atoll(row2a->GetField(0));
+// 		  //
+// 		  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);
+// 		  if ( PKT(PKA)+1LL == PKT(glrun->GetRUNHEADER_PKT()) && PKT(PKB) == PKT(glrun->GetRUNTRAILER_PKT())+1LL ){
+// 		    if ( IsDebug() ) printf(" Ok, we are in the case: RH---| small gap |---RT \n");
+		    OK = true;
+		    //		  };
+		    //		};
+		    //	      };		  
+		    //	  };
+	  };	  
+	if ( OK ){
+	  //
+	  // this is the case in which we must insert a piece of run between two fragments in the GL_RUN table
+	  //
+	  // 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 )
+	  //
+	  GL_RUN *glA = new GL_RUN();
+	  glA->Query_GL_RUN(IDRL2A,conn);
+	  //
+	  if ( glA->GetACQ_BUILD_INFO() != 0 ){
+	    //
+	    // the first piece contains a good runheader we can update all the other runs with correct infos!
+	    //
+	    oss.str("");
+	    oss << "UPDATE GL_RUN_FRAGMENTS SET "
+		<< " RUNHEADER_TIME=" << glA->GetRUNHEADER_TIME()<< " , "
+		<< " RUNHEADER_OBT=" << glA->GetRUNHEADER_OBT()<< " , "
+		<< " RUNHEADER_PKT=" << glA->GetRUNHEADER_PKT()<< " , "
+		<< " COMPILATIONTIMESTAMP=" << glA->GetCOMPILATIONTIMESTAMP()<< " , "
+		<< " FAV_WRK_SCHEDULE=" << glA->GetFAV_WRK_SCHEDULE()<< " , "
+		<< " EFF_WRK_SCHEDULE=" << glA->GetEFF_WRK_SCHEDULE()<< " , "
+		<< " PRH_VAR_TRG_MODE_A=" << glA->GetPRH_VAR_TRG_MODE_A()<< " , "
+		<< " PRH_VAR_TRG_MODE_B=" << glA->GetPRH_VAR_TRG_MODE_B()<< " , "
+		<< " ACQ_BUILD_INFO=" << glA->GetACQ_BUILD_INFO()<< " , "
+		<< " ACQ_VAR_INFO=" << glA->GetACQ_VAR_INFO()<< " , "
+		<< " RM_ACQ_AFTER_CALIB=" << glA->GetRM_ACQ_AFTER_CALIB()<< " , "  
+		<< " RM_ACQ_SETTING_MODE=" << glA->GetRM_ACQ_SETTING_MODE()<< " , "  
+		<< " TRK_CALIB_USED=" << glA->GetTRK_CALIB_USED()<< " , "  
+		<< " CAL_DSP_MASK=" << glA->GetCAL_DSP_MASK()<< " , "  
+		<< " LAST_TIMESYNC=" << glA->GetLAST_TIMESYNC()<< " , ";
+	    //
+	    if ( glA->GetPHYSENDRUN_MASK_S3S2S12() )
+	      oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12() << " , "; 
+	    if ( glA->GetPHYSENDRUN_MASK_S11CRC() )
+	      oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC() << " , ";
+	    //	      
+	    oss << " OBT_TIMESYNC=" << glA->GetOBT_TIMESYNC();
+	    oss << " WHERE ID=" << glrun->GetID() << ";";
+	    if ( IsDebug() ) printf(" update with correct infos: %s\n",oss.str().c_str());
+	    conn->Query(oss.str().c_str());	
+	    //
+	  } else {
+	    //
+	    // sig no runheader, let set anyway what is possible...
+	    //
+	    oss.str("");
+	    oss << "UPDATE GL_RUN_FRAGMENTS SET "
+		<< " RUNHEADER_TIME=" << glA->GetRUNHEADER_TIME()<< " , ";
+	    //
+	    if ( glA->GetPHYSENDRUN_MASK_S3S2S12() )
+	      oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , ";
+	    if ( glA->GetPHYSENDRUN_MASK_S11CRC() )
+	      oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; 
+	    //	      
+	    oss << " RUNHEADER_OBT=" << glA->GetRUNHEADER_OBT()<< " , "
+		<< " RUNHEADER_PKT=" << glA->GetRUNHEADER_PKT();
+	    oss << " WHERE ID=" << glrun->GetID() << ";";
+	    if ( IsDebug() ) printf(" update with correct infos2: %s\n",oss.str().c_str());
+	    conn->Query(oss.str().c_str());	
+	  };
+	  //
+	  // update runheader ROOT_ID_FRAG
+	  //
+	  oss.str("");
+	  oss << "UPDATE GL_RUN SET ID_RUN_FRAG = " << glrun->GetID() << " where ID = " << IDRL2A << ";";
+	  if ( IsDebug() ) printf(" update gl_run to have cross indexing: %s\n",oss.str().c_str());
+	  conn->Query(oss.str().c_str());
+	  //
+	  // now let's look for runtrailer if any in the last run
+	  //
+	  glA->Query_GL_RUN(IDRL2B,conn);
+	  //
+	  if ( glA->GetPKT_READY_COUNTER() != 0 ){
+	    //
+	    // the first piece contains a good runtrailer we can update all the other runs with correct infos!
+	    //
+	    oss.str("");
+	    oss << "UPDATE GL_RUN_FRAGMENTS SET "
+		<< " RUNTRAILER_TIME=" << glA->GetRUNTRAILER_TIME()<< " , "
+		<< " RUNTRAILER_OBT=" << glA->GetRUNTRAILER_OBT()<< " , "
+		<< " RUNTRAILER_PKT=" << glA->GetRUNTRAILER_PKT()<< " , "
+		<< " PKT_COUNTER=" << glA->GetPKT_COUNTER()<< " , ";
+	    //
+	    if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ){
+	      oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
+	    if ( glA->GetPHYSENDRUN_MASK_S11CRC() ) {
+	      oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
+	    //	      
+	    oss << " PKT_READY_COUNTER=" << glA->GetPKT_READY_COUNTER()
+		<< " WHERE ID=" << glrun->GetID() << ";";
+	    if ( IsDebug() ) printf(" update with correct trailer infos: %s\n",oss.str().c_str());
+	    conn->Query(oss.str().c_str());	
+	    //
+	  } else {
+	    //
+	    // sig no runtrailer, let set anyway what is possible...
+	    //
+	    oss.str("");
+	    oss << "UPDATE GL_RUN_FRAGMENTS SET "
+		<< " RUNTRAILER_TIME=" << glA->GetRUNTRAILER_TIME()<< " , "
+		<< " RUNTRAILER_OBT=" << glA->GetRUNTRAILER_OBT()<< " , ";
+	      //
+	    if ( glA->GetPHYSENDRUN_MASK_S3S2S12() ){
+	      oss << " PHYSENDRUN_MASK_S3S2S12=" << glA->GetPHYSENDRUN_MASK_S3S2S12()<< " , "; };
+	    if ( glA->GetPHYSENDRUN_MASK_S11CRC() ){
+	      oss << " PHYSENDRUN_MASK_S11CRC=" << glA->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
+	    //	      
+	    oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()
+		<< " WHERE ID=" << glrun->GetID() << ";";
+	    if ( IsDebug() ) printf(" update with correct trailer infos2: %s\n",oss.str().c_str());
+	    conn->Query(oss.str().c_str());	
+	  };
+	  //
+	  UInt_t myi = glrun->GetID();
+	  oss.str("");
+	  oss << " ID= "<< myi;
+	  //
+	  glrun->Query_GL_RUN_FRAGMENTS(oss.str().c_str(),conn);   
+	  //
+	  // fill the new run in GL_RUN
+	  //
+	  glrun->SetID_RUN_FRAG(IDRL2B);
+	  glrun->Fill_GL_RUN(conn);	
+	  glrun->DeleteRun(conn,0,"GL_RUN_FRAGMENTS");
+	  delete glA;
+	  moved++;
+	  //
+	} else {
+	  //
+	  // is just a repetition
+	  //
+	  if ( IsDebug() ) printf(" The run %u is already present in the GL_RUN table...\n",glrun->GetID());	
+	  //	  printf(" CCCCCCCCICCCCCCCCCCCCIOOOOOOOOOO si muove Ciccio! %u \n",glrun->GetID());
+	  //	  if ( PEDANTIC && glrun->GetID() != 61563 ) throw -83; 
+	  if ( PEDANTIC ) throw -83; 
+	};
+	//	if ( IsDebug() ) printf(" The run already exists in the GL_RUN table! ...\n");
+	//	if ( PEDANTIC ) throw -83;
       };
       if ( IsDebug() ) printf(" Delete run %s from the GL_RUN_FRAGMENTS table \n",row->GetField(0));      
       //
       //
       glrun->DeleteRun(conn,(UInt_t)atoll(row->GetField(0)),"GL_RUN_FRAGMENTS");
-//      oss.str("");
-//       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);
-//       if ( IsDebug() ) printf(" Clean the GL_RUN_FRAGMENTS table: query is \n %s \n",oss.str().c_str());
-//       result2 = conn->Query(oss.str().c_str());
-//      //
-//      if ( !result2 ) throw -4;
-//      //
+      //      oss.str("");
+      //       oss << " DELETE from GL_RUN_FRAGMENTS where ID = " << row->GetField(0);
+      //       if ( IsDebug() ) printf(" Clean the GL_RUN_FRAGMENTS table: query is \n %s \n",oss.str().c_str());
+      //       result2 = conn->Query(oss.str().c_str());
+      //      //
+      //      if ( !result2 ) throw -4;
+      //      //
       row = result->Next();
     };
   };
@@ -5366,7 +6765,8 @@
     // 2) get the OBT of the last validated run
     // --------------------------------------------------------------
     oss.str("");
-    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
+    oss << " SELECT * FROM GL_RUN  WHERE VALIDATION>0 AND RUNHEADER_TIME<="<< t_start
 	<<" ORDER BY RUNHEADER_TIME DESC LIMIT 1;";
     if ( IsDebug() ) printf(" Get stop validation-time: query is \n %s \n",oss.str().c_str());
     result = conn->Query(oss.str().c_str());
@@ -5457,7 +6857,7 @@
   GL_RUN* this_run = new GL_RUN();
   GL_RUN* next_run = new GL_RUN();
   Int_t   nseq_max = 1000;
-//  UInt_t* sequence = new UInt_t[100];
+  //  UInt_t* sequence = new UInt_t[100];
   vector<UInt_t> sequence(nseq_max);
   Int_t   nseq = 0;
   Bool_t CHECK = false;
@@ -5472,82 +6872,88 @@
   // ---------------------------------------------------------------------------------
   while(1){
 	  
-	  row = result->Next();
-	  if( row == NULL ) break;
+    row = result->Next();
+    if( row == NULL ) break;
 	  
-	  //------------
-	  //get run info
-	  //------------
-	  this_run->Set_GL_RUN(row);
+    //------------
+    //get run info
+    //------------
+    this_run->Set_GL_RUN(row);
 	  	  
-	  Bool_t this_BAD = false;
-	  if(this_run->GetTRK_CALIB_USED() == 1 || this_run->GetTRK_CALIB_USED() == 2) this_ONLINE = true;
-	  else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;
-	  else{
-//		  printf("Missing or corrupted header!! \n");
-		  this_ONLINE = false;
-		  this_BAD = true;
-	  };
+    Bool_t this_BAD = false;
+    if(this_run->GetTRK_CALIB_USED() == 1 || this_run->GetTRK_CALIB_USED() == 2) this_ONLINE = true;
+    else if (this_run->GetTRK_CALIB_USED() == 104)                          this_ONLINE = false;
+    else{
+      //		  printf("Missing or corrupted header!! \n");
+      this_ONLINE = false;
+      this_BAD = true;
+    };
 
-	  //-----------------------------------
-	  //compare with previous(next in time)
-	  //-----------------------------------
-	  CHECK = false;
-	  UInt_t interval=0;
+    //-----------------------------------
+    //compare with previous(next in time)
+    //-----------------------------------
+    CHECK = false;
+    UInt_t interval=0;
 	  
-	  if( nrow != 0){
+    if( nrow != 0){
 	
 		  
-		  t1 = this_run->GetRUNTRAILER_TIME();
-		  t2 = next_run->GetRUNHEADER_TIME();
-		  interval = (t2-t1);
+      t1 = this_run->GetRUNTRAILER_TIME();
+      t2 = next_run->GetRUNHEADER_TIME();
+      interval = (t2-t1);
 		  
-		  if(this_ONLINE && next_ONLINE){ 				// this: ON-LINE + next: ON-LINE
+      if(this_ONLINE && next_ONLINE){ 				// this: ON-LINE + next: ON-LINE
 			  
-			  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
 			  
-			  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
 			  
-			  if( !CHECK && this_run->VALIDATION ){
-				  for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
-				  nseq=0;
-			  }
+	if( !CHECK && this_run->VALIDATION ){
+	  //	  for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],true);
+	  for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],this_run->VALIDATION);
+	  nseq=0;
+	}
 		  
-		  }else if( !this_ONLINE && next_ONLINE) { 		// this: DEFAULT + next:ON-LINE
+      }else if( !this_ONLINE && next_ONLINE) { 		// this: DEFAULT + next:ON-LINE
 			  
-			  CHECK = true;
+	CHECK = true;
 
-		  }else if( !next_ONLINE ){						// this:ANY + next:DEFAULT 
+      }else if( !next_ONLINE ){						// this:ANY + next:DEFAULT 
 			  
-			  assignVALIDATION(next_run->ID,true);
-			  nseq=0;
-		  }
-	  }
+	assignVALIDATION(next_run->ID,true);
+	nseq=0;
+      }
+    }
 
-	  //----------------------------
-	  //check run sequence for calib
-	  //----------------------------
-	  if( CHECK ){
-		  // check if calibration exists
-		  if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval); 
-		  Bool_t MISSING = MissingTRK_CALIB(t1,t2);
-		  for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],!MISSING);
-		  nseq=0;
-	  };
-	  //--------------
-	  //store run info
-	  //--------------
-	  *next_run   = *this_run;
-	  next_ONLINE = this_ONLINE;
-	  if( !this_BAD ){ 
-		  if(nseq < nseq_max){
-			  sequence[nseq] = this_run->ID; 
-			  nseq++;
-		  }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);
-	  };
+    //----------------------------
+    //check run sequence for calib
+    //----------------------------
+    if( CHECK ){
+      // check if calibration exists
+      if ( IsDebug() )printf("DT %i ===> CHECK Missing calibration\n",interval); 
+      //      Bool_t MISSING = MissingTRK_CALIB(t1,t2);
+      UInt_t MISSING = MissingTRK_CALIB(t1,t2);
+      UInt_t val = 0;
+      if ( MISSING == 1 ) val = 0;
+      if ( MISSING == 0 ) val = 1;
+      if ( MISSING == 2 ) val = 2;
+      for (Int_t irun = 0; irun < nseq; irun++)assignVALIDATION(sequence[irun],val);
+      nseq=0;
+    };
+    //--------------
+    //store run info
+    //--------------
+    *next_run   = *this_run;
+    next_ONLINE = this_ONLINE;
+    if( !this_BAD ){ 
+      if(nseq < nseq_max){
+	sequence[nseq] = this_run->ID; 
+	nseq++;
+      }else printf("ValidateRuns ***WARNING*** : run sequence exceed assumed size (%i) \n",nseq_max);
+    };
 	  
-	  if ( IsDebug() ) printf("%i Run %u \n",nrow,this_run->ID);
-	  nrow++;
+    if ( IsDebug() ) printf("%i Run %u \n",nrow,this_run->ID);
+    nrow++;
 	  
   };
   delete this_run;
@@ -5561,43 +6967,50 @@
  * @param t2 To absolute time
  * @return true if there might be a missing calibration
  */
-Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
+//Bool_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
+UInt_t PamelaDBOperations::MissingTRK_CALIB(UInt_t t1,UInt_t t2){
 	
-	GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();
+  GL_TRK_CALIB* trkcalib = new GL_TRK_CALIB();
 	
-	// get the closest VALIDATED calibration before the run start (t2)
-	if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true); 	//>>> missing
+  // get the closest calibration before the run start (t2)
+  //  if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(true); 	//>>> missing
+  if ( trkcalib->Query_GL_TRK_CALIB(t2, conn) )return(1); 	//>>> missing
 	
-	if ( trkcalib->TO_TIME  < t2 ) return(true); 					//>>> missing
+  //  if ( trkcalib->TO_TIME  < t2 ) return(true); 					//>>> missing
+  if ( trkcalib->TO_TIME  < t2 ) return(1); 					//>>> missing
 	
-	//==============================================================
-	// Check is done first on the basis of time between calibration,
-	// which should be equal to the time between ascending-nodes.
-	//==============================================================
-	if ( t2 - trkcalib->FROM_TIME > 5700) {
-		if ( IsDebug() )printf("Long time between calib and run start %u :-( ==> there might be a missing calib \n",t2 - trkcalib->FROM_TIME);
-	//==============================================================
-	// there might be a missing calibration, due to:
-	// - MM full
-	// - corrupted packets
-	// - loss of data
-	// There is an exception in case a download was done during ascending node
-	//==============================================================
-		Bool_t DOWNLOAD = false;
-		// check if the calib was skipped becouse of download .... DA FARE!! 
-		if(DOWNLOAD)return(false);
+  //==============================================================
+  // Check is done first on the basis of time between calibration,
+  // which should be equal to the time between ascending-nodes.
+  //==============================================================
+  if ( t2 - trkcalib->FROM_TIME > 5700) {
+    if ( IsDebug() )printf("Long time between calib and run start %u :-( ==> there might be a missing calib \n",t2 - trkcalib->FROM_TIME);
+    //==============================================================
+    // there might be a missing calibration, due to:
+    // - MM full
+    // - corrupted packets
+    // - loss of data
+    // There is an exception in case a download was done during ascending node
+    //==============================================================
+    Bool_t DOWNLOAD = false;
+    // check if the calib was skipped becouse of download .... DA FARE!! 
+    //    if(DOWNLOAD)return(false);
+    if(DOWNLOAD)return(0);
 		
-		return(true); 					//>>> missing
+    //    return(true); 					//>>> missing
+    return(1); 					//>>> missing
 		
-	};
+  };
 	
-	//==============================================================
-	// If the last calibration is close to the run less than this time, 
-	// it is enough to say that there are no missing calibrations
-	//==============================================================
-	// the long time interval bewteen runs might be due to download
-	if ( IsDebug() )printf("Short time between calib and run start %u :-) ==> OK! \n",t2 - trkcalib->FROM_TIME);
-	return(false);
+  //==============================================================
+  // If the last calibration is close to the run less than this time, 
+  // it is enough to say that there are no missing calibrations
+  //==============================================================
+  // the long time interval bewteen runs might be due to download
+  if ( IsDebug() )printf("Short time between calib and run start %u :-) ==> OK! \n",t2 - trkcalib->FROM_TIME);
+  if ( trkcalib->VALIDATION ) return(0);
+  if ( IsDebug() )printf("Calibration is not validated... :-/ ==> OK but with VALIDATION=2! \n");
+  return(2);
 	
 };
 /**
@@ -5606,17 +7019,21 @@
  * @param validation true/false
  */
 Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){
-	TSQLResult *result = 0;
-	stringstream oss;
-	oss.str("");
-	oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";
-	//
-//	if ( IsDebug() ) 
-//	printf(" Set VALIDATION = %i for run %i \n",validation,idrun);
-	if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());
-	result = conn->Query(oss.str().c_str());
-	if ( !result ) throw -4;
-	return(0);
+  return(this->assignVALIDATION(idrun,(UInt_t)validation));
+}
+
+Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, UInt_t validation){
+  TSQLResult *result = 0;
+  stringstream oss;
+  oss.str("");
+  oss << " UPDATE GL_RUN SET VALIDATION="<< (UInt_t)validation <<" WHERE ID= " << idrun << ";";
+  //
+  //	if ( IsDebug() ) 
+  //	printf(" Set VALIDATION = %i for run %i \n",validation,idrun);
+  if ( IsDebug() )printf(" Query: %s \n",oss.str().c_str());
+  result = conn->Query(oss.str().c_str());
+  if ( !result ) throw -4;
+  return(0);
 }
 
 
@@ -5802,7 +7219,7 @@
   stringstream myquery;
   //  
   myquery.str("");
-  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() <<"';";
   //
   pResult = conn->Query(myquery.str().c_str());
   //
@@ -5818,6 +7235,7 @@
   //
   this->SetID_ROOT((UInt_t)atoll(Row->GetField(0)));
   this->SetID_RAW((UInt_t)atoll(Row->GetField(1)));
+  UInt_t idtsy=(UInt_t)atoll(Row->GetField(2));
   //
   this->ValidationOFF();
   //
@@ -5825,7 +7243,7 @@
   //
   this->RemoveRUNS();
   //
-  this->RemoveFILES();
+  this->RemoveFILES(idtsy);
   //
   this->SetID_ROOT(0);
   this->SetID_RAW(0);
@@ -6045,7 +7463,7 @@
  * Rearrange calibration tables
  *
  **/
-void PamelaDBOperations::RemoveFILES(){
+void PamelaDBOperations::RemoveFILES(UInt_t idtsy){
   stringstream myquery;
   //
   myquery.str("");
@@ -6055,6 +7473,22 @@
   //
   conn->Query(myquery.str().c_str());
   //
+  myquery.str("");
+  myquery << " DELETE FROM GL_ROOT WHERE ID=" <<this->GetID_ROOT() <<";";
+  //
+  if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
+  //
+  conn->Query(myquery.str().c_str());  //
+  //
+  if ( !chewbacca ){
+    myquery.str("");
+    myquery << " DELETE FROM GL_TIMESYNC WHERE ID=" << idtsy <<";";
+    //
+    if ( IsDebug() ) printf("  query is \n %s \n",myquery.str().c_str());
+    //
+    conn->Query(myquery.str().c_str());
+  };
+  //
 };
 
 /**
@@ -6259,17 +7693,43 @@
  * Rearrange calibration tables
  *
  **/
-UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh ){
+UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh , TFile *file){
 
+    if(!caltrk) return 0;
+
+    if ( IsDebug() ) cout << "ValidateTrkCalib:"<<endl;
+
+    UInt_t validate = 1;
     Int_t vorder[]={5,5,3,3,4,4,2,2,1,1,0,0};
     UInt_t timeaftercalib=120000; //2000;
-//  ----------
-//  Check CRCs 
-//  ----------
+    TString classname = caltrk->GetName();
+
+//  ----------------------------------
+//  Check CRCs and failed calibrations
+//  ----------------------------------
     for(Int_t ipkt=0; ipkt<6; ipkt++){
-	if( caltrk->crc_hcal[ipkt] )return 0; // :-(
-	for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] )return 0; // :-(
+	if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
+	    if( caltrk->crc_hcal[ipkt] ){
+//		if(IsDebug())cout<<"(CRC Header)";
+		validate = 0;
+		if(IsDebug())cout <<endl<<" *** CRC *** (header DSPn "<<caltrk->DSPnumber[ipkt]<<")";
+	
+	    }
+	    for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] ){
+//		if(IsDebug())cout<<"(CRC Pkt-"<<ilad<<")";
+		if(IsDebug())cout <<endl<<" *** CRC *** (data DSPn "<<caltrk->DSPnumber[ipkt]<<" ladder "<<ilad<<")";
+		validate = 0;
+	    }
+	    if( !(caltrk->ncalib_event[ipkt]==0 && caltrk->cal_flag[ipkt]==0) ){
+		if(IsDebug())cout <<endl<<" *** FAILURE *** 	(data DSPn "<<caltrk->DSPnumber[ipkt]<<")";
+		validate = 0;
+	    }
+	}else{
+// 	    validate=0;
+ 	    if(IsDebug())cout <<endl<<" *** DSPn *** ("<< caltrk->DSPnumber[ipkt] <<" @pkt "<<ipkt<<")";
+	}
     }
+
 //  -----------------------
 //  Check missing packets:
 //  -----------------------
@@ -6295,7 +7755,6 @@
 //  Check if it is first or second calibration packet
 //  -------------------------------------------------
     UInt_t build=0;
-    TString classname = caltrk->GetName();
     UInt_t base=0;
     UInt_t mask=0;
     if(classname.Contains("CalibTrk1Event")){
@@ -6306,69 +7765,77 @@
 	base=18;
 	mask=0xFC0000; 
     }
-//  -------------------------------------------------
-//  Count number of packets and set build variable
-//  -------------------------------------------------
+//  ----------------------------------------------------
+//  Count number of valid packets and set build variable
+//  ----------------------------------------------------
+    if(IsDebug())cout <<endl<< " DSP: ";
     Int_t  npkts=0;
     for(Int_t ipkt=0; ipkt<6; ipkt++){
 	if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
+	    if(IsDebug())cout <<" "<<caltrk->DSPnumber[ipkt];
 	    npkts++;
 	    build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );
-	} 
+// 	    cout << caltrk->DSPnumber[ipkt]
+	};
     }
-//    if( npkts==6 )return 1; // :-)
-
-//    cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime()<<endl;
-
-//  -----------------------------------------------
-//  If missing packets: check the acq configuration
+    if(IsDebug())cout << " ==> "<< hex << build << dec;
+//  ----------------------------------------------------
+//  If the number of valid packets is 6, ok exit...
+//  ----------------------------------------------------
+    if( npkts==6 ){
+	return validate; // exit
+    }
+////////////////////////////////////////////////////////
+//  ...otherwise there might be some missing packets
+//
+//  In this case check the acq configuration
 //  (some DSPs might be excluded from acquisition)
-//  -----------------------------------------------
+////////////////////////////////////////////////////////
 
+    if(!eh || !file || (file&&file->IsZombie()) ){
+	if ( IsDebug() )cout << " *** MISSING VIEW *** eh="<<eh<<" file="<<file<<" cannot validate"<<endl;
+	return (0);
+    }
+    
 //  -----------------------------------------------
 //  retrieve the first run header after calib
 //  -----------------------------------------------
-     PacketType *pctp;
-     EventCounter *cod;
-     cod = eh->GetCounter();
-     Int_t irun = cod->Get(pctp->RunHeader);
-     TTree *rh=(TTree*)file->Get("RunHeader");
-     if ( !rh || rh->IsZombie() ) throw -17;
-     if( rh->GetEntries() == irun ){ 
-	  if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (1)  -- cannot validate :-( "<<endl;
-	 return 0; // :-(
-     }
-
-     RunHeaderEvent *run  = 0;
-     EventHeader    *hrun = 0;
-     rh->SetBranchAddress("RunHeader", &run);
-     rh->SetBranchAddress("Header", &hrun);
-     rh->GetEntry(irun);
-//     cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime() << " Run " << hrun->GetPscuHeader()->GetOrbitalTime() <<endl;
-
-     if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){
-	  if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) no runs after calib (2) -- cannot validate :-( "<<endl;
-	 return 0; // :-(
-     }
-     
-     if( !run->RM_ACQ_AFTER_CALIB ){ 
-	  if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) RM_ACQ_AFTER_CALIB=0    -- cannot validate :-( "<<endl;
-	 return 0; // :-(
-     }
-
-     UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());
-     if( dtime > timeaftercalib ){
-	 if ( IsDebug() ) cout << "ValidateTrkCalib: (MISSING VIEW) run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;
-	 return 0; // :-(
-     }
-     
-
-
-     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; // :-)
+    
+    PacketType *pctp;
+    EventCounter *cod;
+    cod = eh->GetCounter();
+    Int_t irun = cod->Get(pctp->RunHeader);
+    TTree *rh=(TTree*)file->Get("RunHeader");
+    if ( !rh || rh->IsZombie() ) throw -17;
+    if( rh->GetEntries() <= irun ){ 
+	if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (1) -- cannot validate :-( "<<endl;
+	return 0; // :-(
+    }
+    RunHeaderEvent *run  = 0;
+    EventHeader    *hrun = 0;
+    rh->SetBranchAddress("RunHeader", &run);
+    rh->SetBranchAddress("Header", &hrun);
+    rh->GetEntry(irun);    
+    if( OBT(hrun->GetPscuHeader()->GetOrbitalTime()) < OBT(eh->GetPscuHeader()->GetOrbitalTime())){
+	if ( IsDebug() ) cout << " *** MISSING-PKT *** no runs after calib (2) -- cannot validate :-( "<<endl;
+	return 0; // :-(
+    }
+
+    UInt_t dtime = OBT(hrun->GetPscuHeader()->GetOrbitalTime()) - OBT(eh->GetPscuHeader()->GetOrbitalTime());
+    if( dtime > timeaftercalib ){
+	if ( IsDebug() ) cout << " *** MISSING-PKT *** run after calib too far ( "<<dtime<<"ms ) -- cannot validate :-( "<<endl;
+	return 0; // :-(
+    }
+
+    if ( IsDebug() ) cout <<endl<< " ACQ_BUILD_INFO ==> "<<hex<<(run->ACQ_BUILD_INFO & mask)<<dec;
+
+    if( (run->ACQ_BUILD_INFO & mask) != build ){
+	validate=0; // :-(
+	cout <<endl<< " *** MISSING-PKT *** packet mismatch: ACQ_BUILD_INFO="<<hex<<(run->ACQ_BUILD_INFO&mask)<<" != "<<build<<dec;
+    };
+
+    return validate;
+
 
 }
 
@@ -6378,12 +7845,12 @@
  *
  **/
 UInt_t PamelaDBOperations::Check(){
-	return(this->Check(0,0));
+  return(this->Check(0,0));
 }
 
 UInt_t PamelaDBOperations::Check(UInt_t from, UInt_t to){
   //
-	if ( IsDebug() ) printf(" from %u to %u \n",from,to);
+  if ( IsDebug() ) printf(" from %u to %u \n",from,to);
   //
   UInt_t test = 0;
   //
@@ -6424,7 +7891,7 @@
     //
     if ( from > 0 && nid <= from ) goto ss;
     if ( to > 0 && nid >= to ) goto ss;
-//
+    //
     if ( (UInt_t)atoll(row->GetField(4)) > 1 ){
       //
       //
@@ -6455,7 +7922,7 @@
 	    printf(" CHECK n.4 RUNs %u and %u HAVE SAME RUNHEADER \n",thisid,(UInt_t)atoll(row3->GetField(0)));	  
 	    row3 = result3->Next();
 	  };
-//	delete result3;
+	  //	delete result3;
 
 	};
 	//
@@ -6476,7 +7943,7 @@
 	    printf(" CHECK n.5 RUNs %u and %u HAVE SAME RUNTRAILER \n",thisid,(UInt_t)atoll(row3->GetField(0)));
 	    row3 = result3->Next();
 	  };
-//	delete result3;
+	  //	delete result3;
 	};
 	//
 	oss.str("");
@@ -6496,7 +7963,7 @@
 	    printf(" CHECK n.7 RUNs %u and %u HAVE SAME RUNTRAILER AND RUNHEADER (ARE THE SAME?) \n",thisid,(UInt_t)atoll(row3->GetField(0)));
 	    row3 = result3->Next();
 	  };
- //	delete result3;
+	  //	delete result3;
 
 	};
       };
@@ -6517,7 +7984,7 @@
 	  printf(" CHECK n.6 RUN %u CONTAINS RUN %u  \n",thisid,(UInt_t)atoll(row3->GetField(0)));
 	  row3 = result3->Next();
 	};
-//	delete result3;
+	//	delete result3;
       };
       //
     };
@@ -6543,7 +8010,7 @@
       thisf = (TString)row2->GetField(0);
       if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
       test = 1;
-//	delete result2;
+      //	delete result2;
     };
     //
     if ( (thisrtt < prevrht) && (thisrht != prevrht) ){
@@ -6565,7 +8032,7 @@
       thisf = (TString)row2->GetField(0);
       if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
       test = 1;
-//	delete result2;
+      //	delete result2;
     };
     //
     if ( (thisrht > thisrtt) && (thisrht != prevrht) ){
@@ -6587,17 +8054,17 @@
       thisf = (TString)row2->GetField(0);
       if ( IsDebug() ) printf(" ==> files %s and %s \n",prevf.Data(),thisf.Data());
       test = 1;
-//	delete result2;
+      //	delete result2;
     };
-ss:
+  ss:
     //
     prevrht = thisrht;
     prevrtt = thisrtt;
     previd = thisid;
     prevl0id = thisl0id;
     row = result->Next();
-//    if ( result2 ) delete result2;
-//    if ( result3 ) delete result3;
+    //    if ( result2 ) delete result2;
+    //    if ( result3 ) delete result3;
   };
   //
   return(test);