/**
 * \file GLTables.cpp
 * \author Elena Vannuccini
 * 
 * The file contains implementation of the methods to query the DB.
 */
//
#include <sstream>
#include <iostream>
#include <limits.h>
//
#include <TFile.h>
#include <TTree.h>
#include <TTimeStamp.h>
#include <EventHeader.h>
#include <PscuHeader.h>
//
#include <GLTables.h>
#include <sgp4.h>
//
ClassImp(Q2TH);
ClassImp(GL_TABLES);
ClassImp(GL_TRK_CALIB);
ClassImp(GL_RUN);
ClassImp(GL_ROOT);
ClassImp(GL_PARAM);
ClassImp(GL_S4_CALIB);
ClassImp(GL_CALO_CALIB);
ClassImp(GL_CALOPULSE_CALIB);
ClassImp(GL_TIMESYNC);
ClassImp(GL_TLE);
//
using namespace std;

Q2TH::Q2TH(TString host, TString user, TString psw){
  this->Open(host,user,psw);
};

void Q2TH::Open(TString host, TString user, TString psw){
  fh = gSystem->ExpandPathName(host.Data());
  fu = gSystem->ExpandPathName(user.Data());
  fp = gSystem->ExpandPathName(psw.Data());
  printf(" Connecting to DB %s \n",fh.Data());
  dbc = TSQLServer::Connect(fh.Data(),fu.Data(),fp.Data());
  if ( dbc && dbc->IsConnected() ){
    printf(" connected! \n");
  } else {
    printf(" ERROR! not connected... :( \n");
  };
};

TObject *Q2TH::Draw(TString query, Bool_t verbose, TString hname){
  //
  if ( !strcmp(query.Data(),"help") ){
    printf(" USAGE: \n");
    printf(" 1) start root and create Q2TH object with  \n");
    printf("    Q2TH *qt = new Q2TH()  \n");
    printf("    or \n");
    printf("    Q2TH *qt = new Q2TH(\"mysql://srvg-g2-01.ts.infn.it/pamelaProcessing9_TS\",\"pamelaprod_ro\",\"mypassword\")  \n");
    printf(" 2) query the DB with  \n");
    printf("    qt->Draw(\"select REAL_TIME_INIT,BAD_PKT_PERCENTAGE from ROOT_TABLE_MERGING;\");  \n");
    printf("    qt->Draw(\"select REAL_TIME_INIT,BAD_PKT_PERCENTAGE from ROOT_TABLE_MERGING;\",true); this will print numbers on screen \n");
    printf("    qt->Draw(\"select REAL_TIME_INIT from ROOT_TABLE_MERGING;\",true,\"myhisto\"); this will print numbers on screen and create histo \"myhisto\"\n");
    printf(" 3) to use your own THxD create it and then query the DB giving as argument the name of histo:   \n");
    printf("    TH2D *myhisto=new TH2D(\"myhisto\",\"myhisto\",5000,1140000000.,1240000000.,10000,0.,1.) \n");
    printf("    qt->Draw(\"select REAL_TIME_INIT,BAD_PKT_PERCENTAGE from ROOT_TABLE_MERGING;\",false,\"myhisto\")\n\n\n");

    return NULL;
  };
  //
  if (Row)
    delete Row;
  pResult = dbc->Query(query.Data());
  //
  Row = pResult->Next();      
  //
  Int_t dim = pResult->GetFieldCount();
  if ( dim < 1 || dim > 2 ){
    printf(" Dim == %i not supported yet \n",dim);
    return NULL;
  };  
  //
  TH1D *h1 = NULL;
  TH2D *h2 = NULL;
  Double_t f1 = 0.;
  Double_t minf1 = numeric_limits<Double_t>::max();
  Double_t maxf1 = numeric_limits<Double_t>::min();
  Double_t f2 = 0.;  
  Double_t minf2 = numeric_limits<Double_t>::max();
  Double_t maxf2 = numeric_limits<Double_t>::min();
  //
  while ( Row ){    
    f1 = (Double_t)atof(Row->GetField(0));
    if ( f1 > maxf1 ) maxf1 = f1;
    if ( f1 < minf1 ) minf1 = f1;
    if ( dim == 2 ){
      f2 = (Double_t)atof(Row->GetField(1));
      if ( f2 > maxf2 ) maxf2 = f2;
      if ( f2 < minf2 ) minf2 = f2;

    };
    if (Row)
      delete Row;
    Row = pResult->Next();
  };
  pResult->Delete();
  //
	
  //
  Int_t f1bin = 70;
  Int_t f2bin = 70;
  if ( dim == 1 ){
    f1bin = int((maxf1-minf1)/1000.);
    if ( f1bin < 70 ) f1bin = 70;
    if ( f1bin > 1000 ) f1bin = 1000;
	if ( !strcmp(hname.Data(),"q2th") ) hname += "1";
	//	h1 =  dynamic_cast<TH1D*>(gDirectory->FindObject(hname.Data()));
	h1 = (TH1D*)(gDirectory->FindObject(hname.Data()));
	if ( !strcmp(hname.Data(),"q2th1") ){
	 if ( h1 ) h1->Delete();
	};
	if ( !h1 ) h1 = new TH1D(hname.Data(),hname.Data(),f1bin,minf1*0.98,maxf1*1.02);
    //    h1->SetBit(TH1::kCanRebin);
    if ( verbose ) printf("\n\n Row     %s \n",pResult->GetFieldName(0));
  };
  if ( dim == 2 ){
    f2bin = int((maxf2-minf2)/1000.);
    if ( f2bin < 70 ) f2bin = 70;
    if ( f2bin > 1000 ) f2bin = 1000;
	if ( !strcmp(hname.Data(),"q2th") ) hname += "2";
	//	h2 =  dynamic_cast<TH2D*>(gDirectory->FindObject(hname.Data()));
	h2 =  (TH2D*)(gDirectory->FindObject(hname.Data()));
	if ( !strcmp(hname.Data(),"q2th2") ){
	 if ( h2 ) h2->Delete();
	};
	if ( !h2 ) h2 = new TH2D(hname.Data(),hname.Data(),f1bin,minf1*0.98,maxf1*1.02,f2bin,minf2*0.98,maxf2*1.02);
    //    h2->SetBit(TH2::kCanRebin);
    if ( verbose ) printf("\n\n Row     %s     %s \n",pResult->GetFieldName(0),pResult->GetFieldName(1));
  };
  //
  pResult = dbc->Query(query.Data());
  //
  if (Row)
    delete Row;
  Row = pResult->Next();      
  //
  Int_t r = 0;
  //
  while ( Row ){    
    f1 = (Double_t)atof(Row->GetField(0));
    if ( dim == 1 ){
      if ( verbose ) printf(" %i     %f \n",r,f1);
      h1->Fill(f1);
    } else {
      f2 = (Double_t)atof(Row->GetField(1));
      if ( verbose ) printf(" %i     %f     %f \n",r,f1,f2);
      h2->Fill(f1,f2);
    };
    r++;
    if (Row)
      delete Row;
    Row = pResult->Next();
  };
  //
  TCanvas *c = NULL;
  TString cname = Form("%sc",hname.Data());
  //  c =  dynamic_cast<TCanvas*>(gDirectory->FindObject(hname.Data()));
  c =  (TCanvas*)(gDirectory->FindObject(cname.Data()));
  if ( !c ) c = new TCanvas(Form("%sc",cname.Data()));
  c->Clear();
  c->cd();
  if ( dim == 1 ) h1->Draw();
  if ( dim == 2 ) h2->Draw();
  //
  if (Row)
    delete Row;
  pResult->Delete();
  if ( dim == 1 ) return h1;
  if ( dim == 2 ) return h2;
  //
  return NULL;
};

GL_TABLES::GL_TABLES(){
};

GL_TABLES::GL_TABLES(TString host, TString user, TString psw){
  fHost = new TString(host.Data());
  fUser = new TString(user.Data());
  fPsw = new TString(psw.Data());
  fSet = true;
  fNquery = 0;
  mh = host.Data();
  mu = user.Data();
  mp = psw.Data();
};


void GL_TABLES::Set(TString host, TString user, TString psw){
  fHost = new TString(host.Data());
  fUser = new TString(user.Data());
  fPsw = new TString(psw.Data());
  fSet = true;
  fNquery = 0;
  mh = host.Data();
  mu = user.Data();
  mp = psw.Data();
};

//Bool_t GL_TABLES::IsConnected(TSQLServer *&dbc){
Bool_t GL_TABLES::IsConnected(TSQLServer *dbc){
  //
  // 
  //
  if ( !fSet ){
    return true;
  };
  //
  //    printf(" host is %s \n",fHost->Data());
  //
  stringstream myquery;  
  myquery.str("");
  myquery << "show databases;";
  if ( dbc ){
    if ( dbc->IsConnected() ){
      delete dbc->Query(myquery.str().c_str());
      fNquery++;
      if ( !(dbc->GetErrorCode()) ){
	//	printf("ok\n");
	//
	//  if ( (dbc->GetErrorCode() != 2013 && dbc->GetErrorCode() != 2006) ){
	//    if ( !(dbc->GetErrorCode()) ){
	// is connected
	return true;
	//    };
      };
    };
  };
  //
  if ( true ) {
    //
    printf(" WARNING: Lost connection to DB! try to recover... \n");
    //
    TString host = fHost->Data();
    TString user = fUser->Data();
    TString psw = fPsw->Data();
    if ( dbc ){
      dbc->Close();
      delete dbc;
      dbc = 0;
    };
    dbc = TSQLServer::Connect(host.Data(),user.Data(),psw.Data());
    //
    myquery.str("");
    myquery << "show databases;";
    delete dbc->Query(myquery.str().c_str());
    fNquery++;
    //    if ( dbc->GetErrorCode() != 2013 && dbc->GetErrorCode() != 2006 ){
    if ( !(dbc->GetErrorCode()) ){
      //
      printf(" ...connection recovered, I can continue! \n");
      //
      myquery.str("");
      myquery << "SET time_zone='+0:00';";
      delete dbc->Query(myquery.str().c_str());
      fNquery++;
      myquery.str("");
      myquery << "SET sql_mode = 'NO_UNSIGNED_SUBTRACTION';";
      delete dbc->Query(myquery.str().c_str());
      fNquery++;
      myquery.str("");
      myquery << "SET wait_timeout=173000;";
      delete dbc->Query(myquery.str().c_str());
      fNquery++;
      return true;
    };
  };
  //
  printf(" GLTABLES: connection is gone away, query will fail\n");
  //
  return false;
  //
};

void GL_TABLES::ResetCounters(){
  fNquery = 0;
};

void GL_TABLES::AddQ(){
  if ( fSet ) fNquery++;
};

UInt_t GL_TABLES::GetNqueries(){
   UInt_t rn = 0;
   rn += (UInt_t&)fNquery;
   return(rn);
};

GL_RUN::GL_RUN() {
  ID                         = 0;
  ID_RUN_FRAG                = 0;
  ID_ROOT_L0                 = 0;
  ID_ROOT_L2                 = 0;
  RUNHEADER_TIME             = 0;
  RUNTRAILER_TIME            = 0;
  EV_FROM                    = 0; 
  EV_TO                      = 0; 
  TRK_CALIB_USED             = 0;
  EFF_WRK_SCHEDULE           = 0;
  PRH_VAR_TRG_MODE_A         = 0;
  PRH_VAR_TRG_MODE_B         = 0;
  ACQ_BUILD_INFO             = 0;
  ACQ_VAR_INFO               = 0;
  RUNHEADER_OBT              = 0;
  RUNTRAILER_OBT             = 0;
  RUNHEADER_PKT              = 0;
  RUNTRAILER_PKT             = 0;
  NEVENTS                    = 0;
  LAST_TIMESYNC              = 0;
  OBT_TIMESYNC               = 0;
  COMPILATIONTIMESTAMP       = 0;
  FAV_WRK_SCHEDULE           = 0;
  RM_ACQ_AFTER_CALIB         = 0;
  RM_ACQ_SETTING_MODE        = 0;
  PKT_COUNTER                = 0;
  PKT_READY_COUNTER          = 0;
  TRK_CALIB_USED             = 0;
  CAL_DSP_MASK               = 0;
  BOOT_NUMBER                = 0;
  PHYSENDRUN_MASK_S3S2S12    = 0;
  PHYSENDRUN_MASK_S11CRC     = 0;
  VALIDATION                 = 0;
}


void GL_RUN::Clear(Option_t *t) {
  ID                         = 0;
  ID_RUN_FRAG                = 0;
  ID_ROOT_L0                 = 0;
  ID_ROOT_L2                 = 0;
  RUNHEADER_TIME             = 0;
  RUNTRAILER_TIME            = 0;
  EV_FROM                    = 0; 
  EV_TO                      = 0; 
  TRK_CALIB_USED             = 0;
  EFF_WRK_SCHEDULE           = 0;
  PRH_VAR_TRG_MODE_A         = 0;
  PRH_VAR_TRG_MODE_B         = 0;
  ACQ_BUILD_INFO             = 0;
  ACQ_VAR_INFO               = 0;
  RUNHEADER_OBT              = 0;
  RUNTRAILER_OBT             = 0;
  RUNHEADER_PKT              = 0;
  RUNTRAILER_PKT             = 0;
  NEVENTS                    = 0;
  LAST_TIMESYNC              = 0;
  OBT_TIMESYNC               = 0;
  COMPILATIONTIMESTAMP       = 0;
  FAV_WRK_SCHEDULE           = 0;
  RM_ACQ_AFTER_CALIB         = 0;
  RM_ACQ_SETTING_MODE        = 0;
  PKT_COUNTER                = 0;
  PKT_READY_COUNTER          = 0;
  TRK_CALIB_USED             = 0;
  CAL_DSP_MASK               = 0;
  BOOT_NUMBER                = 0;
  PHYSENDRUN_MASK_S3S2S12    = 0;
  PHYSENDRUN_MASK_S11CRC     = 0;
  VALIDATION                 = 0;
}

GL_ROOT::GL_ROOT(){
  ID     = 0;
  ID_RAW = 0;
  ID_TIMESYNC = 0;
  PATH   = "";
  NAME   = "";
}

GL_RAW::GL_RAW(){
  ID     = 0;
  PATH   = "";
  NAME   = "";
  BOOT_NUMBER = 0;
}

GL_PARAM::GL_PARAM(){
  ID     = 0;
  PATH   = "";
  NAME   = "";
  DESCR  = "";
  FROM_TIME = 0;
  TO_TIME   = 0;
  TYPE = 0;
}


GL_TRK_CALIB::GL_TRK_CALIB(){
  ID               = 0;
  ID_ROOT_L0       = 0;
  EV_ROOT_CALIBTRK1 = 0;
  EV_ROOT_CALIBTRK2 = 0;
  FROM_TIME = 0;
  TO_TIME   = 0;
  OBT1 = 0;
  OBT2 = 0;
  PKT1 = 0;
  PKT2 = 0;
  BOOT_NUMBER                = 0;
  VALIDATION                 = 0;
}

GL_CALO_CALIB::GL_CALO_CALIB(){
  ID        = 0;
  ID_ROOT_L0  = 0;
  EV_ROOT = 0;
  FROM_TIME = 0;
  TO_TIME   = 0;
  SECTION   = 0;
  OBT = 0;
  PKT = 0;
  BOOT_NUMBER                = 0;
  VALIDATION                 = 0;
}

GL_CALOPULSE_CALIB::GL_CALOPULSE_CALIB(){
  ID        = 0;
  ID_ROOT_L0  = 0;
  EV_ROOT = 0;
  FROM_TIME = 0;
  TO_TIME   = 0;
  SECTION   = 0;
  PULSED_STRIP = 0;
  PULSE_AMPLITUDE = 0;
  OBT = 0;
  PKT = 0;
  BOOT_NUMBER                = 0;
  VALIDATION                 = 0;
}

GL_S4_CALIB::GL_S4_CALIB(){
  ID        = 0;
  ID_ROOT_L0 = 0;
  EV_ROOT = 0;
  FROM_TIME = 0;
  TO_TIME   = 0;
  OBT = 0;
  PKT = 0;
  BOOT_NUMBER                = 0;
}

GL_TIMESYNC::GL_TIMESYNC(){
  obtfirst = 0;
  pktfirst = 0;
  ID_RESURS_OFFSET  = 0;
  ID       = 0;
  ID_RAW   = 0;
  OBT0     = 0;
  TIMESYNC = 0;
  TYPE     = 0;
}

// ****************************************************

void GL_RUN::SetEV_FROM(UInt_t evfrom){
  EV_FROM = evfrom;
};

void GL_RUN::SetEV_TO(UInt_t evto){
  EV_TO = evto;
};

void GL_RUN::SetNEVENTS(UInt_t nev){
  NEVENTS = nev;
};

void GL_RUN::SetBOOTNUMBER(UInt_t boot){
  BOOT_NUMBER = boot;
};

void GL_RUN::SetRUNHEADER_TIME(UInt_t absth){
  RUNHEADER_TIME = absth;
};

void GL_RUN::SetRUNTRAILER_TIME(UInt_t abstt){
  RUNTRAILER_TIME = abstt;
};

void GL_RUN::SetRUNHEADER_PKT(UInt_t absth){
  RUNHEADER_PKT = absth;
};

void GL_RUN::SetRUNTRAILER_PKT(UInt_t abstt){
  RUNTRAILER_PKT = abstt;
};

void GL_RUN::SetRUNHEADER_OBT(UInt_t absth){
  RUNHEADER_OBT = absth;
};

void GL_RUN::SetRUNTRAILER_OBT(UInt_t abstt){
  RUNTRAILER_OBT = abstt;
};

void GL_RUN::SetID_ROOT_L2(UInt_t idl2){
  ID_ROOT_L2 = idl2;
};

void GL_RUN::SetID_ROOT_L0(UInt_t idroot){
  ID_ROOT_L0 = idroot;
};

void GL_RUN::SetID_RUN_FRAG(UInt_t idfrag){
  ID_RUN_FRAG = idfrag;
};

void GL_RUN::SetVALIDATION(UInt_t valid){
  VALIDATION = valid;
};

void GL_RUN::SetLAST_TIMESYNC(UInt_t ts){
  LAST_TIMESYNC = ts;
};

void GL_RUN::SetOBT_TIMESYNC(UInt_t ts){
  OBT_TIMESYNC = ts;
};

void GL_RUN:: SetPKT_COUNTER(UInt_t value){
  PKT_COUNTER = value;
};

void GL_RUN:: SetPKT_READY_COUNTER(UInt_t value){
  PKT_READY_COUNTER = value;
};

void GL_RUN:: SetCOMPILATIONTIMESTAMP(UInt_t value){
  COMPILATIONTIMESTAMP = value;
};

void GL_RUN:: SetPHYSENDRUN_MASK_S3S2S12(UInt_t value){
  PHYSENDRUN_MASK_S3S2S12 = value;
};

void GL_RUN:: SetPHYSENDRUN_MASK_S11CRC(UInt_t value){
  PHYSENDRUN_MASK_S11CRC = value;
};


void GL_RUN:: SetFAV_WRK_SCHEDULE(UInt_t value){
  FAV_WRK_SCHEDULE = value;
};

void GL_RUN:: SetEFF_WRK_SCHEDULE(UInt_t value){
  EFF_WRK_SCHEDULE = value;
};

void GL_RUN:: SetPRH_VAR_TRG_MODE_A(UInt_t value){
  PRH_VAR_TRG_MODE_A = value;
};

void GL_RUN:: SetPRH_VAR_TRG_MODE_B(UInt_t value){
  PRH_VAR_TRG_MODE_B = value;
};

void GL_RUN:: SetACQ_BUILD_INFO(UInt_t value){
  ACQ_BUILD_INFO = value;
};

void GL_RUN:: SetACQ_VAR_INFO(UInt_t value){
  ACQ_VAR_INFO = value;
};

void GL_RUN:: SetRM_ACQ_AFTER_CALIB(UInt_t value){
  RM_ACQ_AFTER_CALIB = value;
};

void GL_RUN:: SetRM_ACQ_SETTING_MODE(UInt_t value){
  RM_ACQ_SETTING_MODE = value;
};

void GL_RUN:: SetTRK_CALIB_USED(UInt_t value){
  TRK_CALIB_USED = value;
};

void GL_RUN:: SetCAL_DSP_MASK(UInt_t value){
  CAL_DSP_MASK = value;
};

void GL_RUN:: SetID(UInt_t value){
  ID = value;
};

void GL_RUN::Set_GL_RUNT(RunTrailerEvent *runt, PscuHeader *pht){
  PKT_COUNTER                = runt->PKT_COUNTER;
  PKT_READY_COUNTER          = runt->PKT_ReadyCounter;
  RUNTRAILER_OBT             = pht->GetOrbitalTime(); 
  RUNTRAILER_PKT             = pht->GetCounter();
};

void GL_RUN::Set_GL_RUNH(RunHeaderEvent *runh, PscuHeader *phh){
  TRK_CALIB_USED             = runh->TRK_CALIB_USED;
  PRH_VAR_TRG_MODE_A         = runh->PRH_VAR_TRIGGER_MODE_A;
  PRH_VAR_TRG_MODE_B         = runh->PRH_VAR_TRIGGER_MODE_B;
  ACQ_BUILD_INFO             = runh->ACQ_BUILD_INFO;
  ACQ_VAR_INFO               = runh->ACQ_VAR_INFO;
  RUNHEADER_OBT              = phh->GetOrbitalTime(); 
  RUNHEADER_PKT              = phh->GetCounter(); 
  LAST_TIMESYNC              = runh->LAST_TIME_SYNC_INFO;
  OBT_TIMESYNC               = runh->OBT_TIME_SYNC; 
  COMPILATIONTIMESTAMP       = runh->COMPILATIONTIMESTAMP;
  FAV_WRK_SCHEDULE           = runh->FAVOURITE_WORKING_SCHEDULE;
  EFF_WRK_SCHEDULE           = runh->EFFECTIVE_WORKING_SCHEDULE;
  RM_ACQ_AFTER_CALIB         = runh->RM_ACQ_AFTER_CALIB;
  RM_ACQ_SETTING_MODE        = runh->RM_ACQ_SETTING_MODE;
  TRK_CALIB_USED             = runh->TRK_CALIB_USED;
  CAL_DSP_MASK               = runh->CAL_DSP_MASK;
};

void GL_RUN::Set_GL_RUNT0(){
  PKT_COUNTER                = 0;
  PKT_READY_COUNTER          = 0;
  RUNTRAILER_OBT             = 0;
  RUNTRAILER_PKT             = 0;
};

void GL_RUN::Set_GL_RUNH0(){
  TRK_CALIB_USED             = 0;
  PRH_VAR_TRG_MODE_A         = 0;
  PRH_VAR_TRG_MODE_B         = 0;
  ACQ_BUILD_INFO             = 0;
  ACQ_VAR_INFO               = 0;
  RUNHEADER_OBT              = 0;
  RUNHEADER_PKT              = 0;
  LAST_TIMESYNC              = 0;
  OBT_TIMESYNC               = 0;
  COMPILATIONTIMESTAMP       = 0;
  FAV_WRK_SCHEDULE           = 0;
  EFF_WRK_SCHEDULE           = 0;
  RM_ACQ_AFTER_CALIB         = 0;
  RM_ACQ_SETTING_MODE        = 0;
  TRK_CALIB_USED             = 0;
  CAL_DSP_MASK              = 0;
};

void GL_RUN::Set_GL_RUN(TSQLRow *Row){
	for( Int_t t = 0; t < 32; t++){ 
		if (t== 0) ID                = (UInt_t)atoll(Row->GetField(t));
		if (t== 1) ID_RUN_FRAG       = (UInt_t)atoll(Row->GetField(t));
		if (t== 2) ID_ROOT_L0        = (UInt_t)atoll(Row->GetField(t));
		if (t== 3) ID_ROOT_L2        = (UInt_t)atoll(Row->GetField(t));
		if (t== 4) RUNHEADER_TIME    = (UInt_t)atoll(Row->GetField(t)); 
		if (t== 5) RUNTRAILER_TIME   = (UInt_t)atoll(Row->GetField(t)); 
		if (t== 6) RUNHEADER_OBT     = (UInt_t)atoll(Row->GetField(t));
		if (t== 7) RUNTRAILER_OBT    = (UInt_t)atoll(Row->GetField(t));
		if (t== 8) RUNHEADER_PKT     = (UInt_t)atoll(Row->GetField(t));
		if (t== 9) RUNTRAILER_PKT    = (UInt_t)atoll(Row->GetField(t));
		if (t==10) BOOT_NUMBER       = (UInt_t)atoll(Row->GetField(t));
		if (t==11) EV_FROM           = (UInt_t)atoll(Row->GetField(t));
		if (t==12) EV_TO             = (UInt_t)atoll(Row->GetField(t));
		if (t==13) NEVENTS           = (UInt_t)atoll(Row->GetField(t));
		if (t==14) PKT_COUNTER       = (UInt_t)atoll(Row->GetField(t));
		if (t==15) PKT_READY_COUNTER = (UInt_t)atoll(Row->GetField(t));
		if (t==16) COMPILATIONTIMESTAMP = (UInt_t)atoll(Row->GetField(t));
		if (t==17) FAV_WRK_SCHEDULE  = (UInt_t)atoll(Row->GetField(t));
		if (t==18) EFF_WRK_SCHEDULE  = (UInt_t)atoll(Row->GetField(t));
		if (t==19) PRH_VAR_TRG_MODE_A= (UInt_t)atoll(Row->GetField(t));
		if (t==20) PRH_VAR_TRG_MODE_B= (UInt_t)atoll(Row->GetField(t));
		if (t==21) ACQ_BUILD_INFO    = (UInt_t)atoll(Row->GetField(t));
		if (t==22) ACQ_VAR_INFO      = (UInt_t)atoll(Row->GetField(t));
		if (t==23) RM_ACQ_AFTER_CALIB= (UInt_t)atoll(Row->GetField(t));
		if (t==24) RM_ACQ_SETTING_MODE = (UInt_t)atoll(Row->GetField(t));
		if (t==25) TRK_CALIB_USED    = (UInt_t)atoll(Row->GetField(t));
		if (t==26) CAL_DSP_MASK      = (UInt_t)atoll(Row->GetField(t));
		if (t==27) LAST_TIMESYNC     = (UInt_t)atoll(Row->GetField(t));
		if (t==28) OBT_TIMESYNC      = (UInt_t)atoll(Row->GetField(t));
		if (t==29) PHYSENDRUN_MASK_S3S2S12 = (UInt_t)atoll(Row->GetField(t));
		if (t==30) PHYSENDRUN_MASK_S11CRC = (UInt_t)atoll(Row->GetField(t));
		if (t==31) VALIDATION        = (UInt_t)atoll(Row->GetField(t));
	};

}

/**
 * This method delete the run from the "FromTable" table and store it in the GL_RUN_TRASH table
 * If IDRUN is 0 "this->ID" run is used.
 *
 **/
Int_t GL_RUN::DeleteRun(TSQLServer *dbc,UInt_t IDRUN,TString FromTable){
  // MySQL variables
  TSQLResult *pResult;
  TSQLRow *Row = NULL;
  stringstream myquery;
  //
  if ( !IDRUN ) IDRUN = ID;
  if ( !IDRUN ) return 1;
  // ----------------
  myquery.str("");
  myquery << " INSERT INTO GL_RUN_TRASH (";  
  myquery << "ID";
  myquery << ",ID_RUN_FRAG";
  myquery << ",ID_ROOT_L0";
  myquery << ",ID_ROOT_L2";
  myquery << ",RUNHEADER_TIME";
  myquery << ",RUNTRAILER_TIME";
  myquery << ",RUNHEADER_OBT";
  myquery << ",RUNTRAILER_OBT";
  myquery << ",RUNHEADER_PKT";
  myquery << ",RUNTRAILER_PKT";
  myquery << ",BOOT_NUMBER";
  myquery << ",EV_FROM";
  myquery << ",EV_TO";
  myquery << ",NEVENTS";
  myquery << ",PKT_COUNTER";
  myquery << ",PKT_READY_COUNTER";
  myquery << ",COMPILATIONTIMESTAMP";
  myquery << ",FAV_WRK_SCHEDULE";
  myquery << ",EFF_WRK_SCHEDULE";
  myquery << ",PRH_VAR_TRG_MODE_A";
  myquery << ",PRH_VAR_TRG_MODE_B";
  myquery << ",ACQ_BUILD_INFO";
  myquery << ",ACQ_VAR_INFO";
  myquery << ",RM_ACQ_AFTER_CALIB";
  myquery << ",RM_ACQ_SETTING_MODE";
  myquery << ",TRK_CALIB_USED";
  myquery << ",CAL_DSP_MASK";
  myquery << ",LAST_TIMESYNC";
  myquery << ",OBT_TIMESYNC";
  myquery << ",PHYSENDRUN_MASK_S3S2S12";
  myquery << ",PHYSENDRUN_MASK_S11CRC";
  myquery << ",VALIDATION";
  myquery << ",INSERT_TIME";
  myquery << ") SELECT * FROM ";
  myquery << FromTable.Data();
  myquery << " WHERE ID=";
  myquery << (UInt_t)IDRUN << ";";
  //
  //  printf("1myquery is %s \n",myquery.str().c_str());
  //
  if ( !this->GetGLTABLES()->IsConnected(dbc) ) return -57;  
  this->GetGLTABLES()->AddQ();
  delete dbc->Query(myquery.str().c_str());
  //
  // retrieve this ID_TRASH
  //
  myquery.str("");
  myquery << " SELECT ID_TRASH,ID_ROOT_L0,ID_ROOT_L2 FROM GL_RUN_TRASH ORDER BY ID_TRASH DESC LIMIT 1";  
  if ( !this->GetGLTABLES()->IsConnected(dbc) ) return -57;  
  this->GetGLTABLES()->AddQ();
  pResult = dbc->Query(myquery.str().c_str());
  //
  UInt_t idtrash = 0;
  UInt_t idl0 = 0;
  UInt_t idl2 = 0;
  //
  if (Row)
    delete Row;
  Row = pResult->Next();      
  if( Row != NULL ){
    idtrash = (UInt_t)atoll(Row->GetField(0));
    idl0 = (UInt_t)atoll(Row->GetField(1));
    idl2 = (UInt_t)atoll(Row->GetField(2));    
  };
  //
  TString fileL0 = "";
  TString fileL2 = "";
  myquery.str("");
  myquery << " SELECT NAME FROM GL_ROOT WHERE ID=";
  myquery <<  idl0 << ";";
  //
  //  printf("2myquery is %s \n",myquery.str().c_str());
  //
  if ( !this->GetGLTABLES()->IsConnected(dbc) ){
    if (pResult)
      delete pResult;
    if (Row)
      delete Row;
    return -57;
  }
  this->GetGLTABLES()->AddQ();
  pResult = dbc->Query(myquery.str().c_str());
  //
  if (Row)
    delete Row;
  Row = pResult->Next();      
  if( Row != NULL ){
    fileL0 = (TString)Row->GetField(0);
  };
  //
  //
  //
  myquery.str("");
  myquery << " SELECT NAME FROM GL_ROOT WHERE ID=";
  myquery << idl2 << ";";
  //
  //  printf("3myquery is %s \n",myquery.str().c_str());
  //
  if ( !this->GetGLTABLES()->IsConnected(dbc) ){
    if (pResult)
      delete pResult;
    if (Row)
      delete Row;
    return -57;
  }
  this->GetGLTABLES()->AddQ();
  pResult = dbc->Query(myquery.str().c_str());
  //
  if (Row)
    delete Row;
  Row = pResult->Next();      
  if( Row != NULL ){
    fileL2 = (TString)Row->GetField(0);
  }
  delete pResult;
  pResult = NULL;
  if (Row){
    delete Row;
    Row = NULL; // This variable is not used below
  }
  //
  //
  //
  myquery.str("");
  myquery << " UPDATE GL_RUN_TRASH SET FILENAMEL0='";
  myquery <<  fileL0.Data() << "' where ID_TRASH=";
  myquery << idtrash << ";";
  //
  //  printf("4myquery is %s \n",myquery.str().c_str());
  //
  if ( !this->GetGLTABLES()->IsConnected(dbc) ) return -57;  
  this->GetGLTABLES()->AddQ();
  delete dbc->Query(myquery.str().c_str());
  //
  myquery.str("");
  myquery << " UPDATE GL_RUN_TRASH SET FILENAMEL2='";
  myquery <<  fileL2.Data() << "' where ID_TRASH=";
  myquery << idtrash << ";";
  //
  //  printf("4myquery is %s \n",myquery.str().c_str());
  //
  if ( !this->GetGLTABLES()->IsConnected(dbc) ) return -57;  
  this->GetGLTABLES()->AddQ();
  delete dbc->Query(myquery.str().c_str());
  //
  myquery.str("");
  myquery << " UPDATE GL_RUN_TRASH SET BELONGED_TO='";
  myquery <<  FromTable.Data() << "' where ID_TRASH=";
  myquery << idtrash << ";";
  //
  //  printf("4myquery is %s \n",myquery.str().c_str());
  //
  //
  if ( !this->GetGLTABLES()->IsConnected(dbc) ) return -57;  
  this->GetGLTABLES()->AddQ();
  delete dbc->Query(myquery.str().c_str());
  //
  myquery.str("");
  myquery << " DELETE FROM ";
  myquery <<  FromTable.Data() << " where ID=";
  myquery << IDRUN << ";";
  //
  //  printf("5myquery is %s \n",myquery.str().c_str());
  //
  //
  if ( !this->GetGLTABLES()->IsConnected(dbc) ) return -57;  
  this->GetGLTABLES()->AddQ();
  delete dbc->Query(myquery.str().c_str());
  //
  return 0;
};



/**
 * This method restore a run from the GL_RUN_TRASH table.
 * If ID is 0 "this->ID" is used; if "ToTable" is empty BELONG_TO field of GL_RUN_TRASH is used.
 *
 **/
Int_t GL_RUN::RestoreRun(TSQLServer *dbc,UInt_t IDRUN,TString ToTable){
  // insert into GL_RUN_FRAGMENTS select * FROM GL_RUN where ID=11;
  //insert into GL_RUN_TRASH VALUES (ID , ID_RUN_FRAG , ID_ROOT_L0 , ID_ROOT_L2 , RUNHEADER_TIME , RUNTRAILER_TIME , RUNHEADER_OBT , RUNTRAILER_OBT , RUNHEADER_PKT , RUNTRAILER_PKT , BOOT_NUMBER , EV_FROM , EV_TO  , NEVENTS , PKT_COUNTER , PKT_READY_COUNTER , COMPILATIONTIMESTAMP , FAV_WRK_SCHEDULE , EFF_WRK_SCHEDULE , PRH_VAR_TRG_MODE_A , PRH_VAR_TRG_MODE_B , ACQ_BUILD_INFO , ACQ_VAR_INFO , RM_ACQ_AFTER_CALIB , RM_ACQ_SETTING_MODE, TRK_CALIB_USED,CAL_DSP_MASK, LAST_TIMESYNC, OBT_TIMESYNC, VALIDATION, INSERT_TIME) select * FROM GL_RUN where ID=11;
  // MySQL variables
  TSQLResult *pResult = NULL;
  TSQLRow *Row = NULL;
  stringstream myquery;
  //
  if ( !IDRUN ) IDRUN = ID;
  if ( !IDRUN ) return 1;
  //
  if ( !strcmp(ToTable.Data(),"") ){
    //    
    myquery.str("");
    myquery << " SELECT BELONGED_TO FROM GL_RUN_TRASH WHERE ID=";
    myquery << (UInt_t)IDRUN << ";";
    //
    printf(" qui? myquery is %s \n",myquery.str().c_str());
    //
    if ( !this->GetGLTABLES()->IsConnected(dbc) ) return -57;  
    this->GetGLTABLES()->AddQ();
    pResult = dbc->Query(myquery.str().c_str());
    //
    Row = pResult->Next();      
    if( Row != NULL ){
     ToTable = (TString)Row->GetField(0);
    } else {
      delete pResult;
      return 1;
    };
  };

  if (pResult)
    delete pResult;
  if (Row)
    delete Row;
  // ----------------
  myquery.str("");
  myquery << " INSERT INTO ";
  myquery << ToTable.Data();
  myquery << " (";  
  myquery << "ID";
  myquery << ",ID_RUN_FRAG";
  myquery << ",ID_ROOT_L0";
  myquery << ",ID_ROOT_L2";
  myquery << ",RUNHEADER_TIME";
  myquery << ",RUNTRAILER_TIME";
  myquery << ",RUNHEADER_OBT";
  myquery << ",RUNTRAILER_OBT";
  myquery << ",RUNHEADER_PKT";
  myquery << ",RUNTRAILER_PKT";
  myquery << ",BOOT_NUMBER";
  myquery << ",EV_FROM";
  myquery << ",EV_TO";
  myquery << ",NEVENTS";
  myquery << ",PKT_COUNTER";
  myquery << ",PKT_READY_COUNTER";
  myquery << ",COMPILATIONTIMESTAMP";
  myquery << ",FAV_WRK_SCHEDULE";
  myquery << ",EFF_WRK_SCHEDULE";
  myquery << ",PRH_VAR_TRG_MODE_A";
  myquery << ",PRH_VAR_TRG_MODE_B";
  myquery << ",ACQ_BUILD_INFO";
  myquery << ",ACQ_VAR_INFO";
  myquery << ",RM_ACQ_AFTER_CALIB";
  myquery << ",RM_ACQ_SETTING_MODE";
  myquery << ",TRK_CALIB_USED";
  myquery << ",CAL_DSP_MASK";
  myquery << ",LAST_TIMESYNC";
  myquery << ",OBT_TIMESYNC";
  myquery << ",PHYSENDRUN_MASK_S3S2S12";
  myquery << ",PHYSENDRUN_MASK_S11CRC";
  myquery << ",VALIDATION";
  myquery << ",INSERT_TIME";
  myquery << ") SELECT ";
  myquery << "ID";
  myquery << ",ID_RUN_FRAG";
  myquery << ",ID_ROOT_L0";
  myquery << ",ID_ROOT_L2";
  myquery << ",RUNHEADER_TIME";
  myquery << ",RUNTRAILER_TIME";
  myquery << ",RUNHEADER_OBT";
  myquery << ",RUNTRAILER_OBT";
  myquery << ",RUNHEADER_PKT";
  myquery << ",RUNTRAILER_PKT";
  myquery << ",BOOT_NUMBER";
  myquery << ",EV_FROM";
  myquery << ",EV_TO";
  myquery << ",NEVENTS";
  myquery << ",PKT_COUNTER";
  myquery << ",PKT_READY_COUNTER";
  myquery << ",COMPILATIONTIMESTAMP";
  myquery << ",FAV_WRK_SCHEDULE";
  myquery << ",EFF_WRK_SCHEDULE";
  myquery << ",PRH_VAR_TRG_MODE_A";
  myquery << ",PRH_VAR_TRG_MODE_B";
  myquery << ",ACQ_BUILD_INFO";
  myquery << ",ACQ_VAR_INFO";
  myquery << ",RM_ACQ_AFTER_CALIB";
  myquery << ",RM_ACQ_SETTING_MODE";
  myquery << ",TRK_CALIB_USED";
  myquery << ",CAL_DSP_MASK";
  myquery << ",LAST_TIMESYNC";
  myquery << ",OBT_TIMESYNC";
  myquery << ",PHYSENDRUN_MASK_S3S2S12";
  myquery << ",PHYSENDRUN_MASK_S11CRC";
  myquery << ",VALIDATION";
  myquery << ",INSERT_TIME";
  myquery << " FROM GL_RUN_TRASH ";
  myquery << " WHERE BELONGED_TO='GL_RUN_FRAGMENTS' AND ID=";
  myquery << (UInt_t)IDRUN << ";";
  //
  //  printf("5myquery is %s \n",myquery.str().c_str());
  //
  if ( !this->GetGLTABLES()->IsConnected(dbc) ) return -57;  
  this->GetGLTABLES()->AddQ();
  delete dbc->Query(myquery.str().c_str());
  //
  //
  myquery.str("");
  myquery << " DELETE FROM GL_RUN_TRASH where BELONGED_TO='GL_RUN_FRAGMENTS' AND ID=";
  myquery << IDRUN << ";";
  //
  if ( !this->GetGLTABLES()->IsConnected(dbc) ) return -57;  
  this->GetGLTABLES()->AddQ();
  delete dbc->Query(myquery.str().c_str());
  //
  return 0;
};

/**
 * Function to fill the GL_RUN  table of the DB.
 *
 * \param  
 *
 */
Int_t GL_RUN::Fill_GL_RUN(TSQLServer *dbc){
  // MySQL variables
  stringstream myquery;
  // ----------------
  myquery.str("");
  myquery << " INSERT INTO GL_RUN (";  
  myquery << "ID";
  myquery << ",ID_RUN_FRAG";
  myquery << ",ID_ROOT_L0";
  myquery << ",ID_ROOT_L2";
  myquery << ",RUNHEADER_TIME";
  myquery << ",RUNTRAILER_TIME";
  myquery << ",RUNHEADER_OBT";
  myquery << ",RUNTRAILER_OBT";
  myquery << ",RUNHEADER_PKT";
  myquery << ",RUNTRAILER_PKT";
  myquery << ",EV_FROM";
  myquery << ",EV_TO";
  myquery << ",NEVENTS";
  myquery << ",LAST_TIMESYNC";
  myquery << ",OBT_TIMESYNC";
  myquery << ",COMPILATIONTIMESTAMP";
  myquery << ",FAV_WRK_SCHEDULE";
  myquery << ",EFF_WRK_SCHEDULE";
  myquery << ",PRH_VAR_TRG_MODE_A";
  myquery << ",PRH_VAR_TRG_MODE_B";
  myquery << ",ACQ_BUILD_INFO";
  myquery << ",ACQ_VAR_INFO";
  myquery << ",RM_ACQ_AFTER_CALIB";
  myquery << ",RM_ACQ_SETTING_MODE";
  myquery << ",PKT_COUNTER";
  myquery << ",PKT_READY_COUNTER";
  myquery << ",TRK_CALIB_USED";
  myquery << ",CAL_DSP_MASK";
  myquery << ",BOOT_NUMBER";
  myquery << ",PHYSENDRUN_MASK_S3S2S12";
  myquery << ",PHYSENDRUN_MASK_S11CRC";
  myquery << ",VALIDATION";
  myquery << ") VALUES ('";

  myquery << (UInt_t)ID << "','";
  myquery << (UInt_t)ID_RUN_FRAG << "','";
  myquery << (UInt_t)ID_ROOT_L0 << "','";
  myquery << (UInt_t)ID_ROOT_L2 << "','";
  myquery << (UInt_t)RUNHEADER_TIME << "','";
  myquery << (UInt_t)RUNTRAILER_TIME << "','";
  myquery << (UInt_t)RUNHEADER_OBT << "','";
  myquery << (UInt_t)RUNTRAILER_OBT << "','";
  myquery << (UInt_t)RUNHEADER_PKT << "','";
  myquery << (UInt_t)RUNTRAILER_PKT << "','";
  myquery << (UInt_t)EV_FROM << "','";
  myquery << (UInt_t)EV_TO << "','";
  myquery << (UInt_t)NEVENTS << "','";
  myquery << (UInt_t)LAST_TIMESYNC << "','";
  myquery << (UInt_t)OBT_TIMESYNC << "','";
  myquery << (UInt_t)COMPILATIONTIMESTAMP << "','";
  myquery << (UInt_t)FAV_WRK_SCHEDULE << "','";
  myquery << (UInt_t)EFF_WRK_SCHEDULE << "','";
  myquery << (UInt_t)PRH_VAR_TRG_MODE_A << "','";
  myquery << (UInt_t)PRH_VAR_TRG_MODE_B << "','";
  myquery << (UInt_t)ACQ_BUILD_INFO << "','";
  myquery << (UInt_t)ACQ_VAR_INFO << "','";
  myquery << (UInt_t)RM_ACQ_AFTER_CALIB << "','";
  myquery << (UInt_t)RM_ACQ_SETTING_MODE << "','";
  myquery << (UInt_t)PKT_COUNTER << "','";
  myquery << (UInt_t)PKT_READY_COUNTER << "','";
  myquery << (UInt_t)TRK_CALIB_USED << "','";
  myquery << (UInt_t)CAL_DSP_MASK << "','";
  myquery << (UInt_t)BOOT_NUMBER << "','";
  myquery << (UInt_t)PHYSENDRUN_MASK_S3S2S12 << "','";
  myquery << (UInt_t)PHYSENDRUN_MASK_S11CRC << "','";
  myquery << (UInt_t)VALIDATION << "');";
  //
  //  printf("myquery is %s \n",myquery.str().c_str());
  //
  if ( !this->GetGLTABLES()->IsConnected(dbc) ) return -57;  
  this->GetGLTABLES()->AddQ();
  delete dbc->Query(myquery.str().c_str());
  //
  return 0;

};// ****************************************************

/**
 * Function to fill the GL_RUN  table of the DB.
 *
 * \param  
 *
 */
Int_t GL_RUN::Fill_GL_RUN_FRAGMENTS(TSQLServer *dbc){
  // MySQL variables
  stringstream myquery;
  // ----------------
  myquery.str("");
  myquery << " INSERT INTO GL_RUN_FRAGMENTS (";  
  myquery << "ID";
  myquery << ",ID_ROOT_L0";
  myquery << ",RUNHEADER_TIME";
  myquery << ",RUNTRAILER_TIME";
  myquery << ",RUNHEADER_OBT";
  myquery << ",RUNTRAILER_OBT";
  myquery << ",RUNHEADER_PKT";
  myquery << ",RUNTRAILER_PKT";
  myquery << ",EV_FROM";
  myquery << ",EV_TO";
  myquery << ",NEVENTS";
  myquery << ",LAST_TIMESYNC";
  myquery << ",OBT_TIMESYNC";
  myquery << ",COMPILATIONTIMESTAMP";
  myquery << ",FAV_WRK_SCHEDULE";
  myquery << ",EFF_WRK_SCHEDULE";
  myquery << ",PRH_VAR_TRG_MODE_A";
  myquery << ",PRH_VAR_TRG_MODE_B";
  myquery << ",ACQ_BUILD_INFO";
  myquery << ",ACQ_VAR_INFO";
  myquery << ",RM_ACQ_AFTER_CALIB";
  myquery << ",RM_ACQ_SETTING_MODE";
  myquery << ",PKT_COUNTER";
  myquery << ",PKT_READY_COUNTER";
  myquery << ",TRK_CALIB_USED";
  myquery << ",CAL_DSP_MASK";
  myquery << ",BOOT_NUMBER";
  myquery << ",PHYSENDRUN_MASK_S3S2S12";
  myquery << ",PHYSENDRUN_MASK_S11CRC";
  myquery << ") VALUES ('";
  myquery << (UInt_t)ID << "','";
  myquery << (UInt_t)ID_ROOT_L0 << "','";
  myquery << (UInt_t)RUNHEADER_TIME << "','";
  myquery << (UInt_t)RUNTRAILER_TIME << "','";
  myquery << (UInt_t)RUNHEADER_OBT << "','";
  myquery << (UInt_t)RUNTRAILER_OBT << "','";
  myquery << (UInt_t)RUNHEADER_PKT << "','";
  myquery << (UInt_t)RUNTRAILER_PKT << "','";
  myquery << (UInt_t)EV_FROM << "','";
  myquery << (UInt_t)EV_TO << "','";
  myquery << (UInt_t)NEVENTS << "','";
  myquery << (UInt_t)LAST_TIMESYNC << "','";
  myquery << (UInt_t)OBT_TIMESYNC << "','";
  myquery << (UInt_t)COMPILATIONTIMESTAMP << "','";
  myquery << (UInt_t)FAV_WRK_SCHEDULE << "','";
  myquery << (UInt_t)EFF_WRK_SCHEDULE << "','";
  myquery << (UInt_t)PRH_VAR_TRG_MODE_A << "','";
  myquery << (UInt_t)PRH_VAR_TRG_MODE_B << "','";
  myquery << (UInt_t)ACQ_BUILD_INFO << "','";
  myquery << (UInt_t)ACQ_VAR_INFO << "','";
  myquery << (UInt_t)RM_ACQ_AFTER_CALIB << "','";
  myquery << (UInt_t)RM_ACQ_SETTING_MODE << "','";
  myquery << (UInt_t)PKT_COUNTER << "','";
  myquery << (UInt_t)PKT_READY_COUNTER << "','";
  myquery << (UInt_t)TRK_CALIB_USED << "','";
  myquery << (UInt_t)CAL_DSP_MASK << "','";
  myquery << (UInt_t)BOOT_NUMBER << "','";
  myquery << (UInt_t)PHYSENDRUN_MASK_S3S2S12 << "','";
  myquery << (UInt_t)PHYSENDRUN_MASK_S11CRC << "');";
  //
  // printf("myquery is %s \n",myquery.str().c_str());
  //
  if ( !this->GetGLTABLES()->IsConnected(dbc) ) return -57;  
  this->GetGLTABLES()->AddQ();
  delete dbc->Query(myquery.str().c_str());
  //
  return 0;

};// ****************************************************


/**
 * Function to query the GL_RUN  table of the DB.
 *
 * \param  RUN id
 * \return struct of type GL_RUN _data, which stores the query result
 *
 */
Int_t GL_RUN::Query_GL_RUN(UInt_t run, TSQLServer *dbc){
  // MySQL variables
  TSQLResult *pResult;
  TSQLRow *Row = NULL;
  int r;
  stringstream myquery;
  // ----------------
  myquery.str("");
  myquery << " select ";
  myquery << "ID";
  myquery << ",ID_RUN_FRAG";
  myquery << ",ID_ROOT_L0";
  myquery << ",ID_ROOT_L2";
  myquery << ",RUNHEADER_TIME";
  myquery << ",RUNTRAILER_TIME";
  myquery << ",RUNHEADER_OBT";
  myquery << ",RUNTRAILER_OBT";
  myquery << ",RUNHEADER_PKT";
  myquery << ",RUNTRAILER_PKT";
  myquery << ",EV_FROM";
  myquery << ",EV_TO";
  myquery << ",NEVENTS";
  myquery << ",LAST_TIMESYNC";
  myquery << ",OBT_TIMESYNC";
  myquery << ",COMPILATIONTIMESTAMP";
  myquery << ",FAV_WRK_SCHEDULE";
  myquery << ",EFF_WRK_SCHEDULE";
  myquery << ",PRH_VAR_TRG_MODE_A";
  myquery << ",PRH_VAR_TRG_MODE_B";
  myquery << ",ACQ_BUILD_INFO";
  myquery << ",ACQ_VAR_INFO";
  myquery << ",RM_ACQ_AFTER_CALIB";
  myquery << ",RM_ACQ_SETTING_MODE";
  myquery << ",PKT_COUNTER";
  myquery << ",PKT_READY_COUNTER";
  myquery << ",TRK_CALIB_USED";
  myquery << ",CAL_DSP_MASK";
  myquery << ",BOOT_NUMBER";
  myquery << ",PHYSENDRUN_MASK_S3S2S12";
  myquery << ",PHYSENDRUN_MASK_S11CRC";
  myquery << ",VALIDATION";
  myquery << " from GL_RUN where ID=" << run << ";";
  //
  //  printf(" myquery is %s \n",myquery.str().c_str());
  if ( !this->IsConnected(dbc) ) return -57;  
  this->AddQ();
  pResult = dbc->Query(myquery.str().c_str());
  //
  //  printf(" getrowcount %i \n",pResult->GetRowCount());
  //
  if( !pResult->GetRowCount() ){
    delete pResult;
    if (Row)
      delete Row;
    return(-50);
  }
  //
  for( r=0; r < 1000; r++){
	  if (Row)
	    delete Row;
      Row = pResult->Next();      
      if( Row == NULL ) break;
//	  Set_GL_RUN(Row);
      for( int t = 0; t < pResult->GetFieldCount(); t++){ 
	if (t== 0) ID                = (UInt_t)atoll(Row->GetField(t));
	if (t== 1) ID_RUN_FRAG       = (UInt_t)atoll(Row->GetField(t));
	if (t== 2) ID_ROOT_L0        = (UInt_t)atoll(Row->GetField(t));
	if (t== 3) ID_ROOT_L2        = (UInt_t)atoll(Row->GetField(t));
	if (t== 4) RUNHEADER_TIME    = (UInt_t)atoll(Row->GetField(t)); 
	if (t== 5) RUNTRAILER_TIME   = (UInt_t)atoll(Row->GetField(t)); 
	if (t== 6) RUNHEADER_OBT     = (UInt_t)atoll(Row->GetField(t));
	if (t== 7) RUNTRAILER_OBT    = (UInt_t)atoll(Row->GetField(t));
	if (t== 8) RUNHEADER_PKT     = (UInt_t)atoll(Row->GetField(t));
	if (t== 9) RUNTRAILER_PKT    = (UInt_t)atoll(Row->GetField(t));
	if (t==10) EV_FROM           = (UInt_t)atoll(Row->GetField(t));
	if (t==11) EV_TO             = (UInt_t)atoll(Row->GetField(t));
	if (t==12) NEVENTS           = (UInt_t)atoll(Row->GetField(t));
	if (t==13) LAST_TIMESYNC     = (UInt_t)atoll(Row->GetField(t));
	if (t==14) OBT_TIMESYNC      = (UInt_t)atoll(Row->GetField(t));
	if (t==15) COMPILATIONTIMESTAMP = (UInt_t)atoll(Row->GetField(t));
	if (t==16) FAV_WRK_SCHEDULE  = (UInt_t)atoll(Row->GetField(t));
	if (t==17) EFF_WRK_SCHEDULE  = (UInt_t)atoll(Row->GetField(t));
	if (t==18) PRH_VAR_TRG_MODE_A= (UInt_t)atoll(Row->GetField(t));
	if (t==19) PRH_VAR_TRG_MODE_B= (UInt_t)atoll(Row->GetField(t));
	if (t==20) ACQ_BUILD_INFO    = (UInt_t)atoll(Row->GetField(t));
	if (t==21) ACQ_VAR_INFO      = (UInt_t)atoll(Row->GetField(t));
	if (t==22) RM_ACQ_AFTER_CALIB= (UInt_t)atoll(Row->GetField(t));
	if (t==23) RM_ACQ_SETTING_MODE = (UInt_t)atoll(Row->GetField(t));
	if (t==24) PKT_COUNTER       = (UInt_t)atoll(Row->GetField(t));
	if (t==25) PKT_READY_COUNTER = (UInt_t)atoll(Row->GetField(t));
	if (t==26) TRK_CALIB_USED    = (UInt_t)atoll(Row->GetField(t));
	if (t==27) CAL_DSP_MASK      = (UInt_t)atoll(Row->GetField(t));
	if (t==28) BOOT_NUMBER       = (UInt_t)atoll(Row->GetField(t));
	if (t==29) PHYSENDRUN_MASK_S3S2S12 = (UInt_t)atoll(Row->GetField(t));
	if (t==30) PHYSENDRUN_MASK_S11CRC = (UInt_t)atoll(Row->GetField(t));
	if (t==31) VALIDATION        = (UInt_t)atoll(Row->GetField(t));
      };
  }

  if (Row)
    delete Row;
  delete pResult;
  return(0);
};

/**
 * Function to query the GL_RUN  table of the DB.
 *
 * \param  where = condition string
 * \return struct of type GL_RUN _data, which stores the query result
 *
 */
Int_t GL_RUN::Query_GL_RUN_FRAGMENTS(TString where, TSQLServer *dbc){
  // MySQL variables
  TSQLResult *pResult;
  TSQLRow *Row = NULL;
  int t;
  int r;
  stringstream myquery;
  // ----------------
  myquery.str("");
  myquery << " select ";
  myquery << "ID";
  myquery << ",ID_RUN_FRAG";
  myquery << ",ID_ROOT_L0";
  myquery << ",ID_ROOT_L2";
  myquery << ",RUNHEADER_TIME";
  myquery << ",RUNTRAILER_TIME";
  myquery << ",RUNHEADER_OBT";
  myquery << ",RUNTRAILER_OBT";
  myquery << ",RUNHEADER_PKT";
  myquery << ",RUNTRAILER_PKT";
  myquery << ",EV_FROM";
  myquery << ",EV_TO";
  myquery << ",NEVENTS";
  myquery << ",LAST_TIMESYNC";
  myquery << ",OBT_TIMESYNC";
  myquery << ",COMPILATIONTIMESTAMP";
  myquery << ",FAV_WRK_SCHEDULE";
  myquery << ",EFF_WRK_SCHEDULE";
  myquery << ",PRH_VAR_TRG_MODE_A";
  myquery << ",PRH_VAR_TRG_MODE_B";
  myquery << ",ACQ_BUILD_INFO";
  myquery << ",ACQ_VAR_INFO";
  myquery << ",RM_ACQ_AFTER_CALIB";
  myquery << ",RM_ACQ_SETTING_MODE";
  myquery << ",PKT_COUNTER";
  myquery << ",PKT_READY_COUNTER";
  myquery << ",TRK_CALIB_USED";
  myquery << ",CAL_DSP_MASK";
  myquery << ",BOOT_NUMBER";
  myquery << ",PHYSENDRUN_MASK_S3S2S12";
  myquery << ",PHYSENDRUN_MASK_S11CRC";
  myquery << ",VALIDATION";
  myquery << " from GL_RUN_FRAGMENTS where " << where.Data() << ";";
  //
  //  printf(" query is %s \n",myquery.str().c_str());
  //
  if ( !this->GetGLTABLES()->IsConnected(dbc) ) return -57;  
  this->GetGLTABLES()->AddQ();
  pResult = dbc->Query(myquery.str().c_str());
  if(!pResult->GetRowCount()){
    delete pResult;
    if (Row)
      delete Row;
    return(-50);
  }
  for( r=0; r < 1000; r++){ 
	if (Row)
	  delete Row;
    Row = pResult->Next();      
    if( Row == NULL ) break;
    for( t = 0; t < pResult->GetFieldCount(); t++){ 
      if (t== 0) ID                = (UInt_t)atoll(Row->GetField(t));
      if (t== 1) ID_RUN_FRAG       = (UInt_t)atoll(Row->GetField(t));
      if (t== 2) ID_ROOT_L0        = (UInt_t)atoll(Row->GetField(t));
      if (t== 3) ID_ROOT_L2        = (UInt_t)atoll(Row->GetField(t));
      if (t== 4) RUNHEADER_TIME    = (UInt_t)atoll(Row->GetField(t)); 
      if (t== 5) RUNTRAILER_TIME   = (UInt_t)atoll(Row->GetField(t)); 
      if (t== 6) RUNHEADER_OBT     = (UInt_t)atoll(Row->GetField(t));
      if (t== 7) RUNTRAILER_OBT    = (UInt_t)atoll(Row->GetField(t));
      if (t== 8) RUNHEADER_PKT     = (UInt_t)atoll(Row->GetField(t));
      if (t== 9) RUNTRAILER_PKT    = (UInt_t)atoll(Row->GetField(t));
      if (t==10) EV_FROM           = (UInt_t)atoll(Row->GetField(t));
      if (t==11) EV_TO             = (UInt_t)atoll(Row->GetField(t));
      if (t==12) NEVENTS           = (UInt_t)atoll(Row->GetField(t));
      if (t==13) LAST_TIMESYNC     = (UInt_t)atoll(Row->GetField(t));
      if (t==14) OBT_TIMESYNC      = (UInt_t)atoll(Row->GetField(t));
      if (t==15) COMPILATIONTIMESTAMP = (UInt_t)atoll(Row->GetField(t));
      if (t==16) FAV_WRK_SCHEDULE  = (UInt_t)atoll(Row->GetField(t));
      if (t==17) EFF_WRK_SCHEDULE  = (UInt_t)atoll(Row->GetField(t));
      if (t==18) PRH_VAR_TRG_MODE_A= (UInt_t)atoll(Row->GetField(t));
      if (t==19) PRH_VAR_TRG_MODE_B= (UInt_t)atoll(Row->GetField(t));
      if (t==20) ACQ_BUILD_INFO    = (UInt_t)atoll(Row->GetField(t));
      if (t==21) ACQ_VAR_INFO      = (UInt_t)atoll(Row->GetField(t));
      if (t==22) RM_ACQ_AFTER_CALIB= (UInt_t)atoll(Row->GetField(t));
      if (t==23) RM_ACQ_SETTING_MODE = (UInt_t)atoll(Row->GetField(t));
      if (t==24) PKT_COUNTER       = (UInt_t)atoll(Row->GetField(t));
      if (t==25) PKT_READY_COUNTER = (UInt_t)atoll(Row->GetField(t));
      if (t==26) TRK_CALIB_USED    = (UInt_t)atoll(Row->GetField(t));
      if (t==27) CAL_DSP_MASK      = (UInt_t)atoll(Row->GetField(t));
      if (t==28) BOOT_NUMBER       = (UInt_t)atoll(Row->GetField(t));
      if (t==29) PHYSENDRUN_MASK_S3S2S12 = (UInt_t)atoll(Row->GetField(t));
      if (t==30) PHYSENDRUN_MASK_S11CRC = (UInt_t)atoll(Row->GetField(t));
      if (t==31) VALIDATION        = (UInt_t)atoll(Row->GetField(t));
    };
  }

  if (Row)
    delete Row;
  delete pResult;
  return(0);
};// ****************************************************

/**
 * Function to query the GL_ROOT table of the DB.
 *
 * \param  entry ID
 * \return struct of type GL_ROOT_data, which stores the query result
 */
Int_t GL_ROOT::Query_GL_ROOT(UInt_t id, TSQLServer *dbc){
  // MySQL variables
  TSQLResult *pResult;
  TSQLRow *Row = NULL;
  int t;
  int r;
  stringstream myquery;
  // ----------------
  myquery.str("");
  myquery << "select ";
  myquery << " ID"; 
  myquery << ",ID_RAW"; 
  myquery << ",ID_TIMESYNC"; 
  myquery << ",PATH"; 
  myquery << ",NAME"; 
  myquery << " from GL_ROOT where ID=" << id << ";";    
  //
  if ( !this->GetGLTABLES()->IsConnected(dbc) ) return -57;  
  this->GetGLTABLES()->AddQ();
  pResult = dbc->Query(myquery.str().c_str());
  if(!pResult->GetRowCount()){
    delete pResult;
    if (Row)
      delete Row;
    return (-51);
  }
  for( r=0; r < 1000; r++){ 
	  if (Row)
	    delete Row;
      Row = pResult->Next();      
      if( Row == NULL ) break;
      for( t = 0; t < pResult->GetFieldCount(); t++){ 
	  if(t==0) ID     = (UInt_t)atoll(Row->GetField(t));
	  if(t==1) ID_RAW = (UInt_t)atoll(Row->GetField(t));
	  if(t==2) ID_TIMESYNC = (UInt_t)atoll(Row->GetField(t));
	  if(t==3){
        PATH   = TString(Row->GetField(t)) + '/';
        gSystem->ExpandPathName(PATH);
      }
	  if(t==4) NAME   = Row->GetField(t);
      }
  }
  if (Row)
    delete Row;
  delete pResult;   
  return 0;
};
// ****************************************************
/**
 * Function to query the GL_TRK_CALIB table of the DB.
 *
 * \param  run starting time
 * \param  dbc DB server
 * \return struct of type GL_TRK_CALIB_data, which stores the query result
 */
Int_t GL_TRK_CALIB::Query_GL_TRK_CALIB(UInt_t time, TSQLServer *dbc){
  // MySQL variables
  TSQLResult *pResult;
  TSQLRow *Row = NULL;
  int t;
  int r;
  stringstream myquery;
  // ----------------
  myquery.str("");
  myquery << "select ID,ID_ROOT_L0,EV_ROOT_CALIBTRK1,EV_ROOT_CALIBTRK2,FROM_TIME,TO_TIME,OBT1,OBT2,PKT1,PKT2,BOOT_NUMBER,VALIDATION from GL_TRK_CALIB where FROM_TIME <= "<< time;
//  myquery << " AND VALIDATION=1 ORDER BY FROM_TIME DESC LIMIT 1;";      // RIVEDERE LA VALIDAZIONE!!!
  myquery << " and EV_ROOT_CALIBTRK1>=0 and EV_ROOT_CALIBTRK2>=0 "; // EM! SE MANCA UN PACCHETTO DEI DUE IL PROCESSAMENTO CRASHA... DA RIVEDERE LA VALIDAZIONE      
  myquery << " ORDER BY FROM_TIME DESC LIMIT 1;";      
  //  myquery << " ORDER BY FROM_TIME DESC LIMIT 1;";      
  if ( !this->GetGLTABLES()->IsConnected(dbc) ) return -57;  
  this->GetGLTABLES()->AddQ();
  pResult = dbc->Query(myquery.str().c_str()); 
  if(!pResult->GetRowCount()){
    delete pResult;
    return (-53);
  }
  for( r=0; r < 1000; r++){ 
	  if (Row)
	    delete Row;
      Row = pResult->Next();     
      if( Row == NULL ) break;
      for( t = 0; t < pResult->GetFieldCount(); t++){ 
	  stringstream row;
	  row.str("");
	  row << "0" << Row->GetField(t); // add leading 0 since we have two fields that could be "null" and we want to avoid crashes due to atoll
	  if (t==0) ID                = (UInt_t)atoll(Row->GetField(t));
	  if (t==1) ID_ROOT_L0        = (UInt_t)atoll(Row->GetField(t));
	  if (t==2) EV_ROOT_CALIBTRK1 = (UInt_t)atoll(row.str().c_str());
	  if (t==3) EV_ROOT_CALIBTRK2 = (UInt_t)atoll(row.str().c_str());
	  if (t==4) FROM_TIME         = (UInt_t)atoll(Row->GetField(t));
	  if (t==5) TO_TIME           = (UInt_t)atoll(Row->GetField(t));
	  //
	  if (t==6) OBT1              = (UInt_t)atoll(Row->GetField(t));
	  if (t==7) OBT2              = (UInt_t)atoll(Row->GetField(t));
	  if (t==8) PKT1              = (UInt_t)atoll(Row->GetField(t));
	  if (t==9) PKT2              = (UInt_t)atoll(Row->GetField(t));
	  if (t==10) BOOT_NUMBER      = (UInt_t)atoll(Row->GetField(t));
	  if (t==11) VALIDATION       = (UInt_t)atoll(Row->GetField(t));
	  };
  }
  if (Row)
    delete Row;
  delete pResult;
  //
//  if ( TO_TIME < time ) return(51);
  //
  if ( (!OBT1 && !PKT1 ) || (!OBT2 && !PKT2) ) return(52); // ONE CALIBRATION PACKET IS MISSING!
  //
  return 0;
};

// ****************************************************
/**
 * Function to query the GL_CALO_CALIB table of the DB.
 *
 * \param  run starting time
 * \return struct of type GL_CALO_CALIB_data, which stores the query result
 */
Int_t GL_CALO_CALIB::Query_GL_CALO_CALIB(UInt_t time, UInt_t &uptime,  UInt_t section, TSQLServer *dbc){
  // MySQL variables
  TSQLResult *pResult;
  TSQLRow *Row = NULL;
  int t;
  stringstream myquery;
  uptime = 0;
  //
  // select the correct calibration
  //
  myquery.str("");
  myquery << "select ID_ROOT_L0, FROM_TIME, TO_TIME, EV_ROOT,VALIDATION from GL_CALO_CALIB where SECTION=" << section;
  myquery << " and FROM_TIME <= " << time;
  myquery << " and TO_TIME > " << time;
  myquery << " ;";
  //myquery << " and VALIDATION=1;";
  //
  if ( !this->GetGLTABLES()->IsConnected(dbc) ) return -57;  
  this->GetGLTABLES()->AddQ();
  pResult = dbc->Query(myquery.str().c_str());
  // printf(" mysquery is %s\n",myquery.str().c_str());
  //
  if (Row)
    delete Row;
  if( !pResult->GetRowCount() ){
    delete pResult;
    return(-54);
  }
  Row = pResult->Next();
  if( Row == NULL ){
    delete pResult;
    return (-54);
  }
  //
  uptime = (UInt_t)atoll(Row->GetField(2));
  //
  UInt_t myfromtime = (UInt_t)atoll(Row->GetField(1));
  UInt_t mytotime = (UInt_t)atoll(Row->GetField(2));
  //
  // if it is corrupted validation is 0 and we have no results from the query...
  //
  if( atoi(Row->GetField(4)) == 0 ){ // if validation = 0
    //
    // in this case take relax the conditions and take the valid calibration that preceed the correct one
    //
    myquery.str("");
    myquery << "select ID_ROOT_L0, FROM_TIME, TO_TIME, EV_ROOT,VALIDATION from GL_CALO_CALIB where SECTION=" << section;
    myquery << " and FROM_TIME <= " << time;
    myquery << " and VALIDATION=1 ORDER BY FROM_TIME DESC LIMIT 1;";
    if ( !this->GetGLTABLES()->IsConnected(dbc) ){
      if(pResult)
        delete pResult;
      if(Row)
        delete Row;
      return -57;
    }
    this->GetGLTABLES()->AddQ();
    pResult = dbc->Query(myquery.str().c_str());
    //    printf(" mysquery is %s\n",myquery.str().c_str());
    //
    // if no results yet quit with error
    //
    if( !pResult->GetRowCount() ){
      delete pResult;
      if(Row)
        delete Row;
      return (-54);
    }
    //
    if (Row)
      delete Row;
    Row = pResult->Next();
    //
    myfromtime = (UInt_t)atoll(Row->GetField(1));
    //
  };
  //
  // if the selected calibration is too old (more than 5 orbits old) try to take the closest not corrupted one
  //
  if ( (time-myfromtime)>28500 && myfromtime > 0 ){
    //
    myquery.str("");
    myquery << "select ID_ROOT_L0, FROM_TIME, TO_TIME, EV_ROOT from GL_CALO_CALIB where SECTION=" << section;
    myquery << " and VALIDATION=1 ORDER BY ABS(" << time << "-FROM_TIME) asc limit 1;";
    if ( !this->GetGLTABLES()->IsConnected(dbc) ){
      if(pResult)
        delete pResult;
      if(Row)
        delete Row;
      return -57;
    }
    this->GetGLTABLES()->AddQ();
    pResult = dbc->Query(myquery.str().c_str());
    //    printf(" mysquery is %s\n",myquery.str().c_str());
    //
    // if no results yet quit with error
    //
    if( !pResult->GetRowCount() ){
      if (Row)
        delete Row;
      delete pResult;
      return (-54);
    }
    //
    if (Row)
      delete Row;
    Row = pResult->Next();
    //
  };
  //
  // store infos and exit
  //
  if( Row == NULL ){
    delete pResult;
    return (-54);
  }
  for( t = 0; t < pResult->GetFieldCount(); t++){
    if (t==0) ID_ROOT_L0  = (UInt_t)atoll(Row->GetField(t));
    if (t==1) FROM_TIME = myfromtime;
    if (t==2) TO_TIME   = mytotime;	      
    if (t==3) EV_ROOT = (UInt_t)atoll(Row->GetField(t));
  }
  if (Row)
    delete Row;
  delete pResult;
  return 0;
};


// ****************************************************
/**
 * Function to query the GL_CALOPULSE_CALIB table of the DB.
 *
 * \param  run starting time
 * \return struct of type GL_CALOPULSE_CALIB_data, which stores the query result
 */
Int_t GL_CALOPULSE_CALIB::Query_GL_CALOPULSE_CALIB(UInt_t time, UInt_t section, UInt_t pampli, TSQLServer *dbc){
  // MySQL variables
  TSQLResult *pResult;
  TSQLRow *Row = NULL;
  int t;
  stringstream myquery;
  //
  // select the correct calibration i.e. the closest to our time 
  //
  myquery.str("");
  myquery << "select ID_ROOT_L0, FROM_TIME, TO_TIME, EV_ROOT from GL_CALOPULSE_CALIB where SECTION=" << section;
  myquery << " and PULSE_AMPLITUDE=" << pampli;
  myquery << " and VALIDATION=1 and (PULSED_STRIP IS NULL OR PULSED_STRIP<100) ORDER BY ABS(" << time << "-FROM_TIME) asc limit 1;";
  //  printf(" myq is %s \n",myquery.str().c_str());
  //
  if ( !this->GetGLTABLES()->IsConnected(dbc) ) return -57;  
  this->GetGLTABLES()->AddQ();
  pResult = dbc->Query(myquery.str().c_str());
  //
  if( !pResult ) return(-54);
  //
  if (Row)
    delete Row;
  Row = pResult->Next();
  //
  if( !Row ){
    delete pResult;
    return (-54);
  }
  //
  // store infos and exit
  //
  for( t = 0; t < pResult->GetFieldCount(); t++){
    //    printf(" field %i is %s \n",t,Row->GetField(t));
    if (t==0) ID_ROOT_L0  = (UInt_t)atoll(Row->GetField(t));
    if (t==1) FROM_TIME = (UInt_t)atoll(Row->GetField(t));
    if (t==2) TO_TIME   = (UInt_t)atoll(Row->GetField(t));	      
    if (t==3) EV_ROOT = (UInt_t)atoll(Row->GetField(t));
  }
  if (Row)
    delete Row;
  pResult->Delete();
  return 0;
};


// ****************************************************
/**
 * Function to query the GL_S4_CALIB table of the DB.
 *
 * \param  run starting time
 * \return struct of type GL_S4_CALIB_data, which stores the query result
 */
Int_t GL_S4_CALIB::Query_GL_S4_CALIB(UInt_t time, TSQLServer *dbc){
  // MySQL variables
  TSQLResult *pResult;
  TSQLRow *Row = NULL;
  int t;
  int r;
  stringstream myquery;
  // ----------------
  myquery.str("");
  myquery << "select ID,ID_ROOT_L0,EV_ROOT,FROM_TIME,TO_TIME from GL_S4_CALIB where FROM_TIME <= "<< time;
  myquery << " ORDER BY FROM_TIME DESC LIMIT 1;";      
  //  myquery << " ORDER BY FROM_TIME DESC LIMIT 1;";      
  if ( !this->GetGLTABLES()->IsConnected(dbc) ) return -57;  
  this->GetGLTABLES()->AddQ();
  pResult = dbc->Query(myquery.str().c_str()); 
  if(!pResult->GetRowCount()){
    delete pResult;
    return (-55);//throw -55;
  }
  for( r=0; r < 1000; r++){ 
	  if (Row)
	    delete Row;
      Row = pResult->Next();     
      if( Row == NULL ) break;
      for( t = 0; t < pResult->GetFieldCount(); t++){ 
	if (t==0) ID               = (UInt_t)atoll(Row->GetField(t));
	if (t==1) ID_ROOT_L0  = (UInt_t)atoll(Row->GetField(t));
	if (t==2) EV_ROOT    = (UInt_t)atoll(Row->GetField(t));
	if (t==3) FROM_TIME = (UInt_t)atoll(Row->GetField(t));
	if (t==4) TO_TIME   = (UInt_t)atoll(Row->GetField(t));
      };
  }
  if (Row)
    delete Row;
  delete pResult;     
  //
  if(TO_TIME < time)return(51);
  //
  return 0;
};
// ****************************************************
/**
 * Function to query the GL_PARAM table of the DB.
 *
 * \param  run starting time
 * \param  parameter description (DESCR)
 * \return struct of type GL_ROOT_data, which stores the query result
 */
Int_t GL_PARAM::Query_GL_PARAM(UInt_t time, UInt_t type, TSQLServer *dbc){
  //    Bool_t debug = 1;
  // MySQL variables
  TSQLResult *pResult;
  TSQLRow *Row = NULL;
  int t;
  int r;
  stringstream myquery;
  // ----------------    
  myquery.str("");
  myquery << " select ";
  myquery << " ID, PATH, NAME, DESCR, FROM_TIME,TO_TIME, TYPE ";
  myquery << " from GL_PARAM ";
  myquery << " where TYPE = '"<<type<<"' ";
  myquery << " and FROM_TIME <= " << time; 
  myquery << " ORDER BY TO_TIME DESC LIMIT 1;";  
  //
  if ( !this->GetGLTABLES()->IsConnected(dbc) ) return -57;  
  this->GetGLTABLES()->AddQ();
  pResult = dbc->Query(myquery.str().c_str()); 
  if(!pResult->GetRowCount()){
    delete pResult;
    return (-52);
  }
  for( r=0; r < 1000; r++){ 
	  if (Row)
	    delete Row;
      Row = pResult->Next();     
      if( Row == NULL ) break;
      for( t = 0; t < pResult->GetFieldCount(); t++){ 
        if (t==0) ID        = (UInt_t)atoll(Row->GetField(t));
        if (t==1) {
          PATH = TString(Row->GetField(t)) + "/";// put in fpath the path to that file
          gSystem->ExpandPathName(PATH);
        }
        if (t==2) NAME      = Row->GetField(t);
        if (t==3) DESCR     = Row->GetField(t);
        if (t==4) FROM_TIME = (UInt_t)atoll(Row->GetField(t));
        if (t==5) TO_TIME   = (UInt_t)atoll(Row->GetField(t));
        if (t==6) TYPE     = (UInt_t)atoll(Row->GetField(t));
      };
  }
  if (Row)
    delete Row;
  delete pResult; 
  //
  if(TO_TIME==0) TO_TIME = numeric_limits<UInt_t>::max();
  //
  if(TO_TIME < time) return(51);
  //        
  return 0;   
};


/**
 * Fills a struct cGLRun with values from a GLRun object (to put data into a F77 common).
 */

void GL_RUN::GetLevel2Struct(cGLRun *l2) const{
    l2->id                 = ID;
    l2->id_reg_run         = ID_ROOT_L0;
    l2->id_reg_run_l2      = ID_ROOT_L2;
    l2->runheader_time     = RUNHEADER_TIME;
    l2->runtrailer_time    = RUNTRAILER_TIME;
    l2->ev_from   = EV_FROM; 
    l2->trk_calib_used     = TRK_CALIB_USED;
    l2->eff_wrk_schedule   = EFF_WRK_SCHEDULE;
    l2->prh_var_trg_mode_a = PRH_VAR_TRG_MODE_A;
    l2->prh_var_trg_mode_b = PRH_VAR_TRG_MODE_B;
    l2->acq_build_info     = ACQ_BUILD_INFO;
    l2->acq_var_info       = ACQ_VAR_INFO;
};

GL_TIMESYNC::GL_TIMESYNC(UInt_t id, TString type, TSQLServer *dbc){
  // MySQL variables
  TFile *file = 0;
  UInt_t idtsy = 0;
  //
  TSQLResult *pResult;
  TSQLRow *Row = NULL;
  stringstream myquery;
  stringstream rname;
  //  pcksList packetsNames;
  //  pcksList::iterator Iter;
  //  getPacketsNames(packetsNames);
  rname.str("");
  // ----------------
  myquery.str("");
  myquery << "select ";
  myquery << "PATH"; 
  myquery << ",NAME,ID_TIMESYNC"; 
  myquery << " from GL_ROOT where ";
  myquery << type.Data();
  myquery << "=" << id << ";";    
  //
  if ( !this->GetGLTABLES()->IsConnected(dbc) ) return;  
  this->GetGLTABLES()->AddQ();
  pResult = dbc->Query(myquery.str().c_str());
  if( pResult->GetRowCount() ){
	if (Row)
	  delete Row;
    Row = pResult->Next();      
    if( Row ){
      stringstream fname;
      fname.str("");
      TString auxStr(Row->GetField(0));
      gSystem->ExpandPathName(auxStr);
      fname << auxStr << "/" << Row->GetField(1);
      rname << Row->GetField(1);
      file = new TFile(fname.str().c_str(),"READ");
      idtsy = (UInt_t)atoll(Row->GetField(2));
    };
  };
  //
  if ( file && file->IsOpen() ){
    TTree *T=(TTree*)file->Get("Physics");
    pamela::EventHeader *eh = 0;
    pamela::PscuHeader *ph = 0;
    T->SetBranchAddress("Header", &eh);
    //
    T->GetEntry(0);
    ph = eh->GetPscuHeader();
    pktfirst = ph->GetCounter();
    if ( eh ){
      delete eh;
      eh = 0;
    }
    //    obtfirst = ph->GetOrbitalTime();  
    //
  };
  //
  // look for Resurs offset
  //
  T0 = 0;
  //
  stringstream oss;
  //
  TString name=rname.str().c_str();
  //  UInt_t dworbit = 0;
  //  Int_t nlength = name.Length();
  delete pResult;
  if (Row){
    delete Row;
    Row = NULL;
  }
  //
  // New code, we have one more column on GL_TIMESYNC so we can trust that one for the Resurs offset
  //
  oss.str("");
  oss << "SELECT OBT0,TIMESYNC,TYPE,ID_RESURS_OFFSET from GL_TIMESYNC where ID=" << idtsy <<";";
  if ( !this->GetGLTABLES()->IsConnected(dbc) ) return;  
  this->GetGLTABLES()->AddQ();
  pResult = dbc->Query(oss.str().c_str());
  Bool_t fndit = false;
  if ( pResult ){
	if (Row)
	  delete Row;
    Row = pResult->Next();
    if ( Row ){
      //
      OBT0 = (UInt_t)atoll(Row->GetField(0));
      obtfirst = OBT0;
      TIMESYNC = (UInt_t)atoll(Row->GetField(1));
      TYPE = (UInt_t)atoll(Row->GetField(2));      
      //
      oss.str("");
      oss << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE) FROM GL_RESURS_OFFSET WHERE ID=" 
	  << Row->GetField(3) << ";";
      if ( !this->GetGLTABLES()->IsConnected(dbc) ){
        delete pResult;
        delete Row;
        return;
      }
      this->GetGLTABLES()->AddQ();
      delete pResult;
      pResult = dbc->Query(oss.str().c_str());
      if (pResult){
    	if (Row)
    	  delete Row;
	    Row = pResult->Next();
	    if ( Row ){
	      //	    printf(" GREAT! the DB structure is the new one! \n");
	    fndit = true;
            //	    dworbit = 1;
	    };
      };
    };
  };
  if ( !fndit ){
    //
    printf(" ERROR OLD DB! \n");
    printf(" ERROR FROM GLTables! cannot determine Resurs offset \n");
    //
  };
  //
  TTimeStamp tu = TTimeStamp((UInt_t)atoi(Row->GetField(0)),(UInt_t)atoi(Row->GetField(1)),(UInt_t)atoi(Row->GetField(2)),(UInt_t)atoi(Row->GetField(3)),(UInt_t)atoi(Row->GetField(4)),(UInt_t)atoi(Row->GetField(5)),0,true,0);
  T0 = (UInt_t)tu.GetSec();
  //
  toffset = (UInt_t)TIMESYNC - (UInt_t)(this->DBobt(OBT0)/1000) + T0;
  //
  //  printf(" T0 %u toffset is %u \n",T0,toffset);
  //
  if ( file ) file->Close();
  if (Row)
    delete Row;
  delete pResult;       
};

GL_TIMESYNC::GL_TIMESYNC(UInt_t id, TString type, TSQLServer *dbc, Bool_t usel0file){
  // MySQL variables
  TFile *file = 0;
  UInt_t idtsy = 0;
  //
  TSQLResult *pResult;
  TSQLRow *Row = NULL;
  stringstream myquery;
  stringstream rname;
  //  pcksList packetsNames;
  //  pcksList::iterator Iter;
  //  getPacketsNames(packetsNames);
  rname.str("");
  // ----------------
  myquery.str("");
  myquery << "select ";
  myquery << "PATH"; 
  myquery << ",NAME,ID_TIMESYNC"; 
  myquery << " from GL_ROOT where ";
  myquery << type.Data();
  myquery << "=" << id << ";";    
  //
  if ( !this->GetGLTABLES()->IsConnected(dbc) ) return;  
  this->GetGLTABLES()->AddQ();
  pResult = dbc->Query(myquery.str().c_str());
  if( pResult->GetRowCount() ){
	if (Row)
	  delete Row;
    Row = pResult->Next();      
    if( Row ){
      stringstream fname;
      fname.str("");
      TString auxString(Row->GetField(0));
      gSystem->ExpandPathName(auxString);
      fname << auxString << "/" << Row->GetField(1);
      rname << Row->GetField(1);
      if ( usel0file ) file = new TFile(fname.str().c_str(),"READ");
      idtsy = (UInt_t)atoll(Row->GetField(2));
    };
  };
  //
  if ( usel0file && file && file->IsOpen() ){
    TTree *T=(TTree*)file->Get("Physics");
    pamela::EventHeader *eh = 0;
    pamela::PscuHeader *ph = 0;
    T->SetBranchAddress("Header", &eh);
    //
    T->GetEntry(0);
    ph = eh->GetPscuHeader();
    pktfirst = ph->GetCounter();
    if ( eh ){
      delete eh;
      eh = 0;
    }
    //    obtfirst = ph->GetOrbitalTime();  
    //
  };
  if ( !usel0file ) pktfirst = 0;
  //
  // look for Resurs offset
  //
  T0 = 0;
  //
  stringstream oss;
  //
  TString name=rname.str().c_str();
  //  UInt_t dworbit = 0;
  //  Int_t nlength = name.Length();
  delete pResult;
  if (Row){
    delete Row;
    Row = NULL;
  }
  //
  // New code, we have one more column on GL_TIMESYNC so we can trust that one for the Resurs offset
  //
  oss.str("");
  oss << "SELECT OBT0,TIMESYNC,TYPE,ID_RESURS_OFFSET from GL_TIMESYNC where ID=" << idtsy <<";";
  if ( !this->GetGLTABLES()->IsConnected(dbc) ) return;  
  this->GetGLTABLES()->AddQ();
  pResult = dbc->Query(oss.str().c_str());
  Bool_t fndit = false;
  if ( pResult ){
	if (Row)
	  delete Row;
    Row = pResult->Next();
    if ( Row ){
      //
      OBT0 = (UInt_t)atoll(Row->GetField(0));
      obtfirst = OBT0;
      TIMESYNC = (UInt_t)atoll(Row->GetField(1));
      TYPE = (UInt_t)atoll(Row->GetField(2));      
      //
      oss.str("");
      oss << "SELECT YEAR(OFFSET_DATE),MONTH(OFFSET_DATE),DAY(OFFSET_DATE),HOUR(OFFSET_DATE),MINUTE(OFFSET_DATE),SECOND(OFFSET_DATE) FROM GL_RESURS_OFFSET WHERE ID=" 
	  << Row->GetField(3) << ";";
      if ( !this->GetGLTABLES()->IsConnected(dbc) ){
        delete pResult;
        delete Row;
        return;
      }
      this->GetGLTABLES()->AddQ();
      delete pResult;
      pResult = dbc->Query(oss.str().c_str());
      if (pResult){
    	if (Row)
    	  delete Row;
    	Row = pResult->Next();
	    if (Row){
	      //	    printf(" GREAT! the DB structure is the new one! \n");
	    fndit = true;
            //	    dworbit = 1;
	    };
      };
    };
  };
  if ( !fndit ){
    //
    printf(" ERROR OLD DB! \n");
    printf(" ERROR FROM GLTables! cannot determine Resurs offset \n");
    //
  };
  //
  TTimeStamp tu = TTimeStamp((UInt_t)atoi(Row->GetField(0)),(UInt_t)atoi(Row->GetField(1)),(UInt_t)atoi(Row->GetField(2)),(UInt_t)atoi(Row->GetField(3)),(UInt_t)atoi(Row->GetField(4)),(UInt_t)atoi(Row->GetField(5)),0,true,0);
  T0 = (UInt_t)tu.GetSec();
  //
  toffset = (UInt_t)TIMESYNC - (UInt_t)(this->DBobt(OBT0)/1000) + T0;
  //
  //  printf(" T0 %u toffset is %u \n",T0,toffset);
  //
  if ( file ) file->Close();
  if (Row)
    delete Row;
  delete pResult;       
};

/**
 * 
 * Returns the DB absolute time needed to associate calibrations to data
 * 
 */
UInt_t GL_TIMESYNC::DBabsTime(UInt_t OBT){  
  //
  //  printf(" OBT %u DBobt %llu toffset %u dbabstime %u\n",OBT,this->DBobt(OBT),toffset,((UInt_t)(this->DBobt(OBT)/1000)+toffset));
  return(((UInt_t)(this->DBobt(OBT)/1000)+toffset));
  //
};

/**
 * 
 * Returns the Resurs time given the OBT needed to process inclination and orbital infos
 * 
 */
UInt_t GL_TIMESYNC::ResursTime(UInt_t OBT){  
  //
  return(((UInt_t)((Int_t)(this->DBobt(OBT)-this->DBobt(OBT0)/1000))+TIMESYNC));
  //
};


/**
 * Return the correct packet number if we went back to zero
 */
Long64_t GL_TIMESYNC::DBpkt(UInt_t pkt_num){  
  //
  if ( pkt_num < (pktfirst/2) && pktfirst > (16777214/2)  ){
    return((Long64_t)pkt_num+16777215LL);
  };
  //
  if ( pkt_num > pktfirst*2 && pkt_num > (16777214/2) ){
    return((Long64_t)pkt_num-16777215LL);
  };
  //
  return((Long64_t)pkt_num);
  //
};

/**
 * Return the correct On Board Time if we went back to zero
 */
Long64_t GL_TIMESYNC::DBobt(UInt_t obt){  
  //
  if ( obt < ((Long64_t)obtfirst/2) && obtfirst > (numeric_limits<UInt_t>::max()/2) ){
    return((Long64_t)obt+(Long64_t)numeric_limits<UInt_t>::max());
  };
  //
  if ( obt > ((Long64_t)obtfirst*2) && obt > (numeric_limits<UInt_t>::max()/2) ){
    return((Long64_t)obt-(Long64_t)numeric_limits<UInt_t>::max());
  };
  //
  return((Long64_t)obt);
};



// ULong64_t GL_TIMESYNC::DBobt(UInt_t obt){  
//   //
//   if ( obt < (obtfirst/2) && obtfirst > (numeric_limits<UInt_t>::max()/2) ) return((ULong64_t)(obt+numeric_limits<UInt_t>::max()));
//   //
//   if ( obt > (obtfirst*2) && obt > (numeric_limits<UInt_t>::max()/2) ){
//     if ( (obt-numeric_limits<UInt_t>::max()) < 0  ){
//       return((ULong64_t)(numeric_limits<UInt_t>::max()-obt));
//     } else {
//       return((ULong64_t)(obt-numeric_limits<UInt_t>::max()));
//     };
//   };
//   //
//   return((ULong64_t)obt);
//   //
// };

// UInt_t GL_TIMESYNC::DBpkt(UInt_t pkt_num){  
//   //
//   if ( pkt_num < (pktfirst/2) && pktfirst > (16777214/2)  ) return((pkt_num+16777215));
//   //
//   if ( pkt_num > pktfirst*2 && pkt_num > (16777214/2) ){
//     if ( (pkt_num-16777215) < 0 ){
//       return((16777215-pkt_num));
//     } else {
//       return((pkt_num-16777215));
//     };
//   };
//   //
//   return(pkt_num);
//   //
// };

/*
 *
 * Convert the time in the DB from UInt_t to a string
 * 
 * @param dbt time in the DB
 * @param tzone Time Zone, can be UTC,GMT,CET,CEST,MSD default is MSK
 *
 */
TString GL_TIMESYNC::ConvertTime(TString &tzone, UInt_t dbt){
  //
  Int_t offset = 0;
  TString rtime;
  Bool_t found = false;
  //
  if ( !strcmp(tzone.Data(),"MSK") || !strcmp(tzone.Data(),"MWT") ){
    //
    offset = 60*60*3; // UTC (Coordinated Universal Time) + 3hs = Moscow Winter Time 
    found = true;
    //
  };
  //
  if ( !strcmp(tzone.Data(),"CET") ){
    //
    offset = 60*60*1; // CET (Central European Time) = UTC + 1 hs 
    found = true;
    //
  };
  //
  if ( !strcmp(tzone.Data(),"CEST") ){
    //
    offset = 60*60*2; // CEST (Central European Summer Time) = UTC + 2 h
    found = true;
    //
  };
  //
  if ( !strcmp(tzone.Data(),"MSD") || !strcmp(tzone.Data(),"MST")){
    //
    offset = 60*60*4; // MSD (Moscow Summer Time) = UTC + 4 h
    found = true;
    //
  };
  //
  if ( !found && strcmp(tzone.Data(),"UTC") && strcmp(tzone.Data(),"GMT") && strcmp(tzone.Data(),"") ){
    printf("\n Unknown time zone %s using UTC \n",tzone.Data());
    tzone = "UTC";
  };
  //
  dbt += offset;
  //
  TTimeStamp *time = new TTimeStamp((time_t)dbt,0);
  //
  rtime = time->AsString("s");
  //
  delete time;
  //
  return(rtime);
}

/*
 *
 * Convert the time from TZONE to UTC
 * 
 * @param dbt time in the DB
 * @param tzone Time Zone, can be UTC,GMT,CET,CEST,MSD default is MSK
 *
 */
TString GL_TIMESYNC::UnConvertTime(TString &tzone, UInt_t dbt){
  //
  Int_t offset = 0;
  TString rtime;
  //
  Bool_t found = false;
  //
  if ( !strcmp(tzone.Data(),"MSK") || !strcmp(tzone.Data(),"MWT") ){
    //
    offset = -60*60*3; // UTC (Coordinated Universal Time) = Moscow Winter Time - 3hs
    found = true;
    //
  };
  //
  if ( !strcmp(tzone.Data(),"CET") ){
    //
    offset = -60*60*1; // CET (Central European Time) - 1 hs = UTC  
    found = true;
    //
  };
  //
  if ( !strcmp(tzone.Data(),"CEST") ){
    //
    offset = -60*60*2; // CEST (Central European Summer Time) - 2 h = UTC
    found = true;
    //
  };
  //
  if ( !strcmp(tzone.Data(),"MSD") || !strcmp(tzone.Data(),"MST") ){
    //
    offset = -60*60*4; // MSD (Moscow Summer Time) - 4 h = UTC
    found = true;
    //
  };
  //
  if ( !found && strcmp(tzone.Data(),"UTC") && strcmp(tzone.Data(),"GMT") && strcmp(tzone.Data(),"") ){
    //
    offset = 0;
    printf("\n Unknown time zone %s using UTC \n",tzone.Data());
    tzone = "UTC";
  };
  //
  dbt += offset;
  TTimeStamp *time = new TTimeStamp((time_t)dbt,0);
  //
  rtime = time->AsString("s");
  //
  return(rtime);
}


//
// Build a query and call DoQuery.
//
// date it's an SQL datetime date and dbc is the connection to be
// used.  It will query for the tle with the nearest but previous date
// and the immediatly next one.
//
Int_t GL_TLE::Query(TString date, TSQLServer *dbc){
  stringstream myquery;
  myquery.str("");

  myquery << "(SELECT ID, TLE1, TLE2, TLE3, UNIX_TIMESTAMP(FROM_TIME) FROM GL_TLE "
	  << "WHERE FROM_TIME <= '" << date.Data()
	  << "' ORDER BY FROM_TIME DESC LIMIT 1) "
	  << "UNION "
	  << "(SELECT ID, TLE1, TLE2, TLE3, UNIX_TIMESTAMP(FROM_TIME) FROM GL_TLE "
	  << "WHERE FROM_TIME > '" << date.Data()
	  << "' ORDER BY FROM_TIME ASC LIMIT 1)";

  return DoQuery(myquery.str().c_str(), dbc);
}


//
// Build a query and call DoQuery.
//
// time is the UTC date in unix time (UTC) and dbc is the connection
// to be used.  It will query for the tle with the nearest but
// previous date and the immediatly next one.
//
// Returns the value returned by DoQuery().
//
Int_t GL_TLE::Query(UInt_t time, TSQLServer *dbc){
  stringstream myquery;
  myquery.str("");

  myquery << "(SELECT ID, TLE1, TLE2, TLE3, UNIX_TIMESTAMP(FROM_TIME) FROM GL_TLE "
	  << "WHERE FROM_TIME <= FROM_UNIXTIME('" << time
	  << "') ORDER BY FROM_TIME DESC LIMIT 1) "
	  << "UNION "
	  << "(SELECT ID, TLE1, TLE2, TLE3, UNIX_TIMESTAMP(FROM_TIME) FROM GL_TLE "
	  << "WHERE FROM_TIME > FROM_UNIXTIME('" << time
	  << "') ORDER BY FROM_TIME ASC LIMIT 1)";

  return DoQuery(myquery.str().c_str(), dbc);
}


//
// Do the query myquery on the connectio dbc.  Initialize tle,
// tleFromTime and tleToTime.
//
// We should have two rows (unless the table is old).  From the last
// one we only take tleToTime.
//
// Returns 0 for success, 1 for failure.
//
Int_t GL_TLE::DoQuery(TString myquery, TSQLServer *dbc){
  TSQLResult *result;
  TSQLRow *row = NULL;

  // Set the right time_zone (otherwise horrible things will occur! :)
  if ( !this->GetGLTABLES()->IsConnected(dbc) ) return -57;  
  delete dbc->Query("SET time_zone = '+0:00';");
  delete dbc->Query("SET sql_mode = 'NO_UNSIGNED_SUBTRACTION';");

  // Do the query
  this->GetGLTABLES()->AddQ();
  result = dbc->Query(myquery.Data());
  if(! result->GetRowCount() ) {
    cerr << "GL_TLE: query failed: " << myquery.Data() << endl;
    delete result;
    return 1;
  }

  // Get results
  row = result->Next(); // first tle row
  tle = GiveTle(row);

  tleFromTime = strtol(row->GetField(4), NULL, 10);
  if (row)
    delete row;
  row = result->Next(); // second tle row
  if(row)
    tleToTime = strtol(row->GetField(4), NULL, 10);
  else {
    cerr << "GL_TLE: Warning: using last avaible TLE. Please update GL_TLE table!\n";
    tleToTime = UINT_MAX;
  }

  if (row)
    delete row;
  delete result;

  return 0;
}


//
// Build a cTle object from the GL_TLE row.
//
cTle* GL_TLE::GiveTle(TSQLRow *row) {
  cTle *thistle = NULL;
  string tle1, tle2, tle3;

  // Build cTle object
  tle1 = row->GetField(1);
  tle2 = row->GetField(2);
  tle3 = row->GetField(3);

  thistle = new cTle(tle1, tle2, tle3);

  return thistle;
}
