--- chewbacca/YodaProfiler/src/PamelaDBOperations.cpp	2008/10/31 11:21:44	1.4
+++ chewbacca/YodaProfiler/src/PamelaDBOperations.cpp	2013/04/10 08:54:28	1.35
@@ -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,77 @@
       };
       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-"<< chlastts <<")<50000 AND ABS(REAL_TIME_INIT-"<< row2->GetField(10) <<")<50000 group by BOOT_NUMBER order by BOOT_NUMBER asc;"; // even more relaxed conditions... 091214 [9REDtest3: error -29]
+	      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 +254,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 +462,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 +514,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")+'/');
+    };
   };
 };
 
@@ -649,8 +732,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();
@@ -658,7 +742,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;
@@ -682,8 +766,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();
@@ -777,6 +863,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);
@@ -785,6 +873,7 @@
   };
   //
   if ( chewbacca && nevent < 1 ) {
+    if ( IsDebug() ) printf(" chewbacca and no events in the file \n");
     pktfirst = chpktmin;
     upperpkt = PKT(chpktmax);
     pktlast = chpktmax;
@@ -810,7 +899,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)); 
@@ -1125,7 +1215,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("");
@@ -1330,7 +1428,7 @@
   //
   //  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 ( 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());
   };
@@ -1449,6 +1547,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);
@@ -1464,30 +1570,6 @@
 // PUBLIC FUNCTIONS
 //
 
-// /**
-//  * Insert a new row into GL_RAW table.
-//  */
-// Int_t PamelaDBOperations::insertPamelaRawFile(){
-//   //
-//   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);
-// }
 /**
  * Insert a new row into GL_RAW table.
  */
@@ -1501,7 +1583,8 @@
     
     glraw.PATH = GetRawPath();
     glraw.NAME = GetRawFile();
-    glraw.BOOT_NUMBER = 0;//???
+    //    glraw.BOOT_NUMBER = 0;//???
+    glraw.BOOT_NUMBER = this->GetBOOTnumber();
     
     if( insertPamelaRawFile(&glraw) )return(1);
     //
@@ -1515,7 +1598,7 @@
  */
 Int_t PamelaDBOperations::insertPamelaRawFile(GL_RAW *glraw){
   //
-    if(!glraw)return(1);//??
+    if(!glraw)return(1);//?? ok I think
     //
     stringstream oss;
     //
@@ -1578,6 +1661,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;
@@ -1599,7 +1683,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;
@@ -1646,9 +1730,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.;
     //
     //
@@ -1656,9 +1740,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");
@@ -1852,104 +1936,6 @@
   return(signal);
 }
 
-// /**
-//  * 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(){
-//   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;
-//     //
-//     row = result->Next();
-//     //
-//     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 ";
-//     } 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));
-//       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));
-//   };
-//   //
-//   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() << "')";
-//   };
-//   //
-//   if ( debug ) printf(" query is %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() <<"';";
-//   };
-//   //
-//   if ( debug ) printf(" query is %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());
-//   //
-//   delete result;
-//   //
-//   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.
@@ -1959,7 +1945,7 @@
     stringstream oss;
     TSQLResult *result = 0;
     TSQLRow    *row    = 0;
-  //
+    //
     // ----------------------
     // determine the timesync
     // ----------------------
@@ -2031,7 +2017,15 @@
     
     glroot.ID_RAW = GetID_RAW();
     glroot.ID_TIMESYNC = idtimesync;
-    glroot.PATH = GetRootPath();
+    if ( STATIC ){
+      glroot.PATH = GetRootPath(); 
+    } else {
+      if ( KEEPENV ){
+	glroot.PATH = gSystem->DirName(filerootname.Data());
+      } else {
+	glroot.PATH = "$PAM_L0";
+      };
+    };
     glroot.NAME = GetRootFile();
 
     if ( insertPamelaRootFile(&glroot) )return 1;
@@ -2046,22 +2040,14 @@
  * 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 ('"
-	<< glroot->ID_RAW << "', '" << glroot->ID_TIMESYNC << "', '" << glroot->PATH << "', '" << glroot->NAME << "')";
-  } else {
-    oss << "INSERT INTO GL_ROOT (ID_RAW, ID_TIMESYNC,PATH, NAME) VALUES ('"
-	<< glroot->ID_RAW << "', '" << glroot->ID_TIMESYNC << "', '$PAM_L0', '" << glroot->NAME << "')";
-  };
+  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("%s \n",oss.str().c_str());
   if (conn->Query(oss.str().c_str()) == 0) throw -4;
@@ -2070,11 +2056,7 @@
   //
   oss.str("");
   //  oss << "SELECT ID FROM GL_ROOT WHERE ID_RAW=" << this->GetID_RAW() << ";";
-  if ( STATIC ){
-    oss << "SELECT ID FROM GL_ROOT WHERE PATH='" << glroot->PATH << "' and NAME='"<< glroot->NAME <<"';";
-  } else {
-    oss << "SELECT ID FROM GL_ROOT WHERE PATH='$PAM_L0' and NAME='"<< glroot->NAME <<"';";
-  };
+  oss << "SELECT ID FROM GL_ROOT WHERE PATH='" << glroot->PATH << "' and NAME='"<< glroot->NAME <<"';";
   //
   if ( debug ) printf("%s \n",oss.str().c_str());
   result = conn->Query(oss.str().c_str());
@@ -2288,8 +2270,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)
@@ -2326,6 +2310,7 @@
     //
   } else {
     //
+    if ( IsDebug() ) printf(" We have runtrailers \n"); 
     Int_t conptt = -1;
     for (Int_t ptt=0; ptt<rtev; ptt++){
       //
@@ -2342,7 +2327,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));
 	//
@@ -2381,7 +2366,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 ){
@@ -2420,6 +2405,7 @@
 	      //
 	      this->HandleRunFragments(true,true,chminentry,(evbefh)); 
 	      //
+	      // what about pth=ptht-1
 	    };
 	  };
 	  //
@@ -2442,7 +2428,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();
@@ -2482,9 +2468,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();
@@ -2508,10 +2498,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);
@@ -2742,10 +2734,14 @@
     //
     // 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;
+    if ( firstev != (lastev+1) ){ // could be a problem sometimes (?)
+      if ( rhfirstev != firstev && !mishead ) mishead = true;
+      if ( rtlastev != lastev && !mistrail ) mistrail = true;
+    }; 
     //
+    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);
     //
     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());
@@ -2787,9 +2783,14 @@
       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 ( 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;
@@ -2840,7 +2841,7 @@
 	//
 	found = false; // default value
 	//
-	if ( IsDebug() ) printf(" Found a possible candidate, checking if it is the good one... \n");
+	if ( IsDebug() ) printf(" A 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:
 	//
@@ -2856,6 +2857,7 @@
 	    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 {
 	    //
@@ -2921,6 +2923,7 @@
 	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
 	//
@@ -2951,6 +2954,8 @@
 	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->SetNEVENTS(lastev-firstev+1);
 	//
@@ -3043,7 +3048,7 @@
 	//
 	found = false; // default value
 	//
-	if ( IsDebug() ) printf(" Found a possible candidate, checking if it is the good one... \n");
+	if ( IsDebug() ) printf(" B 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:
 	//
@@ -3143,7 +3148,7 @@
 	  apkt = PKT(ph->GetCounter());
 	  aobt = OBT(ph->GetOrbitalTime());	
 	  lastev--;
-	  if ( PEDANTIC ) throw -72;
+	  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);
 	//
@@ -3211,7 +3216,7 @@
       // 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 "
+      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 ("
@@ -3234,8 +3239,313 @@
       row = result->Next();
       //
       if ( row ){
-	if ( IsDebug() ) printf(" The run is already present in the GL_RUN table \n");
-	if ( PEDANTIC ) throw -70;
+	//
+	// 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]
+	// 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!
+	//
+	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());
@@ -3272,7 +3582,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...
-    };
+      };
     //
   };
   //
@@ -3288,7 +3598,7 @@
   //  
   EventCounter *code=0;
   //
-  UInt_t nevent = 0;
+  //  UInt_t nevent = 0;
   UInt_t checkfirst = 0;
   UInt_t checklast = 0;
   UInt_t firstentry = 0;
@@ -3310,12 +3620,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);
     //
@@ -3345,7 +3656,7 @@
       //
     } 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
       //
@@ -3355,6 +3666,8 @@
       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++){
 	//
@@ -3363,9 +3676,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 ){
 	  //
@@ -3449,18 +3768,6 @@
 	    //	    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;
 
 
@@ -3575,7 +3882,7 @@
 		//
 		found = false; // default value
 		//
-		if ( IsDebug() ) printf(" Found a possible candidate, checking if it is the good one... \n");
+		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:
 		//
@@ -3780,37 +4087,6 @@
 	    }; // EEE
 
 
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
           } else {
 	    if ( !IsRunAlreadyInserted() ){
 	      glrun->SetID(this->AssignRunID());
@@ -3825,6 +4101,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; 
@@ -3857,7 +4141,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;
@@ -3882,7 +4166,7 @@
   EventHeader *eh = 0;
   PscuHeader *ph = 0;
   T->SetBranchAddress("Header", &eh);
-  nevent = T->GetEntries();
+  //  nevent = T->GetEntries();
   //
   codt = eht->GetCounter();
   codh = ehh->GetCounter();
@@ -4116,6 +4400,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;
@@ -4133,6 +4418,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();  
@@ -4300,6 +4601,8 @@
   tr->SetBranchAddress("Header", &eh);
   nevents = tr->GetEntries();
   //
+  Float_t totpul = 0.;
+  //
   if ( nevents > 0 ){
     //
     for (UInt_t i=0; i < nevents; i++){
@@ -4309,6 +4612,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();  
@@ -4466,6 +4785,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();  
@@ -4641,152 +4976,6 @@
   return(0);
 };
 
-// /**
-//  * 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;
-//     //
-//   } 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 << "','"
-// 	<< this->GetBOOTnumber() << "','"
-// 	<< 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;
-//     //
-//   };
-//   //
-// };
 /**
  * Fill the GL_TRK_CALIB table
  */
@@ -4977,7 +5166,8 @@
     if ( !result ) throw -4;;
     row = result->Next();
     if(row)glcal->ID = (UInt_t)atoll(row->GetField(0));
-
+    //
+    delete result; // mmm... "Error in <TMySQLResult::Next>: result set closed" solved? 090112 [8RED error messages]
     //
 };
 
@@ -5187,20 +5377,22 @@
 		//
 	    };
 	    //
+
+	    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;
 	    //
 	};
 	//    
 
-	if( !(MISSING_pkt1&MISSING_pkt2) ){
-	    this->HandleTRK_CALIB(!MISSING_pkt1,!MISSING_pkt2); 
-	    ncalib++;
-	    if( MISSING_pkt1||MISSING_pkt2||!valid )try_to_recover=true;
-	}
-
     }; //end loop on pkt1
 
 
@@ -5257,7 +5449,8 @@
 
 	if ( IsDebug() ) cout << endl << ">>>> TRY TO RECOVER TRACKER CALIBRATIONS <<<<"<<endl;
 
-	TSQLResult *result = 0;
+	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;
 	//
 	stringstream oss;
@@ -5287,7 +5480,7 @@
 	oss << " ORDER BY ID DESC LIMIT "<<ncalib<<"; ";	
 	if ( IsDebug() ) cout << oss.str().c_str() << endl;
 
-	result = conn->Query(oss.str().c_str());
+	rresult = conn->Query(oss.str().c_str());
 	if ( !result ) throw -4;;
 	if ( IsDebug() ) cout <<"Rows: "<<result->GetRowCount()<<endl;
 	
@@ -5296,7 +5489,7 @@
 	// -----------------------------------
 	UInt_t nn=0;
 	do {
-	    row = result->Next();
+            row = rresult->Next();
 	    if(!row)break;
 	    
 	    UInt_t id       = (UInt_t)atoll(row->GetField(0));
@@ -5335,9 +5528,9 @@
 	    TString path       = "";
 	    TString name       = "";
 	    TString raw        = "";
-	    UInt_t obt0        = 0;
-	    UInt_t timesync    = 0;
-	    UInt_t boot_number = 0;
+            //	    UInt_t obt0        = 0;
+            //	    UInt_t timesync    = 0;
+            //	    UInt_t boot_number = 0;
 	    bool   FOUND       = false;
 
 	    if ( IsDebug() ) cout << "------------------------------------------------------------" <<endl;
@@ -5410,22 +5603,23 @@
 		    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));
+                    //		    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 << "File    : " <<name <<endl;
 //		    cout << obt0 <<endl;
 //		    cout << timesync <<endl;
-		    cout << "boot n. : "<<boot_number <<endl;
+//		    cout << "boot n. : "<<boot_number <<endl;
 //		    cout << raw <<endl;
 
 		    // ------------------------------------------------------
 		    // ... retrieve the calibration packets.
 		    // ------------------------------------------------------
-		    TFile *file = new TFile(path+"/"+name);
+		    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;
 		    //
@@ -5475,73 +5669,75 @@
 		    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
-		////////////////////////////////////////////
+	      if ( IsDebug() ) cout << " >>> REPETITION FOUND :-) <<<" <<endl;
 
-		// ---------------------------------------------------------------------
-		// step 1: insert a new raw file in GL_RAW
-		// ---------------------------------------------------------------------
-		//
-		// check if the raw file already exist
-		//
-		UInt_t id_raw = 0;
-		oss.str("");
-		oss << "SELECT ID FROM GL_RAW where NAME=\"" << gSystem->BaseName(raw.Data()) <<"\";";
-		if ( IsDebug() ) cout << oss.str().c_str() << 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<<" limit 1;";
-		if ( debug ) printf(" %s \n",oss.str().c_str());
-		result = conn->Query(oss.str().c_str());
-		if ( !result ) throw -3;
+	      // 		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<<" limit 1;";
+	      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 raw file already exist
+		// check if the root file already exist
 		//
 		UInt_t id_root = 0;
 		oss.str("");
@@ -5559,7 +5755,20 @@
 		    GL_ROOT glroot = GL_ROOT();		    
 		    glroot.ID_RAW      = id_raw;
 		    glroot.ID_TIMESYNC = idtimesync;
-		    glroot.PATH        = path;
+		    //
+		    // 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 );
@@ -5571,6 +5780,7 @@
 		}
 		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
 		// ---------------------------------------------------------------------
@@ -5583,6 +5793,8 @@
 		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:
 		// ---------------------------------------------------------------------
@@ -5612,7 +5824,7 @@
 	}while(1);//end loop over calibrations
 	
 	
-	if( result )delete result;
+	if( rresult )delete rresult; // 10RED bug
 	if( row    )delete row;
 	
 	
@@ -5913,7 +6125,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());
     //
@@ -6034,7 +6246,8 @@
 		oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; 
 	      //	      
 	      oss << " RUNHEADER_OBT=" << glrun->GetRUNHEADER_OBT()<< " , "
-		  << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT()<< ";";
+		  << " RUNHEADER_PKT=" << glrun->GetRUNHEADER_PKT();
+	      oss << " WHERE ID=" << myid[u] << ";"; // BUG!!! 090112
 	      conn->Query(oss.str().c_str());	
 	    };	  
 	  };
@@ -6083,7 +6296,8 @@
 	      if ( glrun->GetPHYSENDRUN_MASK_S11CRC() ){
 		oss << " PHYSENDRUN_MASK_S11CRC=" << glrun->GetPHYSENDRUN_MASK_S11CRC()<< " , "; };
 	      //	      
-	      oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT()<< ";";
+	      oss << " RUNTRAILER_PKT=" << glrun->GetRUNTRAILER_PKT();
+	      oss << " WHERE ID=" << myid[u] << ";"; // BUG!!! 090112
 	      conn->Query(oss.str().c_str());	
 	    };	  
 	  };
@@ -6134,7 +6348,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();
 	      };
@@ -6211,7 +6425,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 ("
@@ -6269,8 +6483,199 @@
 	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));      
       //
@@ -6336,7 +6741,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());
@@ -6479,7 +6885,8 @@
 	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);
+	  //	  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;
 	}
 		  
@@ -6500,8 +6907,13 @@
     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);
+      //      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;
     };
     //--------------
@@ -6531,14 +6943,17 @@
  * @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();
 	
   // 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(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,
@@ -6555,9 +6970,11 @@
     //==============================================================
     Bool_t DOWNLOAD = false;
     // check if the calib was skipped becouse of download .... DA FARE!! 
-    if(DOWNLOAD)return(false);
+    //    if(DOWNLOAD)return(false);
+    if(DOWNLOAD)return(0);
 		
-    return(true); 					//>>> missing
+    //    return(true); 					//>>> missing
+    return(1); 					//>>> missing
 		
   };
 	
@@ -6567,7 +6984,9 @@
   //==============================================================
   // 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 ( trkcalib->VALIDATION ) return(0);
+  if ( IsDebug() )printf("Calibration is not validated... :-/ ==> OK but with VALIDATION=2! \n");
+  return(2);
 	
 };
 /**
@@ -6576,6 +6995,10 @@
  * @param validation true/false
  */
 Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, Bool_t validation){
+  return(this->assignVALIDATION(idrun,(UInt_t)validation));
+}
+
+Int_t PamelaDBOperations::assignVALIDATION(UInt_t idrun, UInt_t validation){
   TSQLResult *result = 0;
   stringstream oss;
   oss.str("");
@@ -6772,7 +7195,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());
   //
@@ -6788,6 +7211,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();
   //
@@ -6795,7 +7219,7 @@
   //
   this->RemoveRUNS();
   //
-  this->RemoveFILES();
+  this->RemoveFILES(idtsy);
   //
   this->SetID_ROOT(0);
   this->SetID_RAW(0);
@@ -7015,7 +7439,7 @@
  * Rearrange calibration tables
  *
  **/
-void PamelaDBOperations::RemoveFILES(){
+void PamelaDBOperations::RemoveFILES(UInt_t idtsy){
   stringstream myquery;
   //
   myquery.str("");
@@ -7025,6 +7449,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());
+  };
+  //
 };
 
 /**
@@ -7374,120 +7814,6 @@
 
 
 }
-// UInt_t PamelaDBOperations::ValidateTrkCalib( CalibTrk1Event* caltrk, EventHeader *eh ){
-
-//     if(!caltrk || !eh) return 0;
-
-//   Int_t vorder[]={5,5,3,3,4,4,2,2,1,1,0,0};
-//   UInt_t timeaftercalib=120000; //2000;
-//   //  ----------
-//   //  Check CRCs 
-//   //  ----------
-//   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; // :-(
-//   }
-//   //  -----------------------
-//   //  Check missing packets:
-//   //  -----------------------
-//   //    Readout order:
-//   //    ------------------
-//   //    DSP   packet board
-//   //    ------------------
-//   //    12    0      1
-//   //    10    1      1
-//   //     8    2      1
-//   //     4    3      1
-//   //     6    4      1
-//   //     2    5      1
-//   //    ------------------
-//   //    11    0      2
-//   //     9    1      2
-//   //     7    2      2
-//   //     3    3      2
-//   //     5    4      2
-//   //     1    5      2
-//   //    ------------------
-//   //  -------------------------------------------------
-//   //  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")){
-//     base=12;
-//     mask=0x03F000; 
-//   }
-//   if(classname.Contains("CalibTrk2Event")){
-//     base=18;
-//     mask=0xFC0000; 
-//   }
-//   //  -------------------------------------------------
-//   //  Count number of packets and set build variable
-//   //  -------------------------------------------------
-//   Int_t  npkts=0;
-//   for(Int_t ipkt=0; ipkt<6; ipkt++){
-//     if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
-//       npkts++;
-//       build = build | ( 1<<(base+vorder[caltrk->DSPnumber[ipkt]-1]) );
-//     } 
-//   }
-//   //    if( npkts==6 )return 1; // :-)
-
-//   //    cout << classname << " "<<eh->GetPscuHeader()->GetOrbitalTime()<<endl;
-
-//   //  -----------------------------------------------
-//   //  If missing packets: check the acq configuration
-//   //  (some DSPs might be excluded from acquisition)
-//   //  -----------------------------------------------
-
-//   //  -----------------------------------------------
-//   //  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; // :-)
-
-// }
 
 /**
  *