
/**
 * \file TrkParams.cpp
 * \author Elena Vannuccini
 */

#include <TrkParams.h>
#include <iostream>
#include <iomanip>
using namespace std;


Bool_t TrkParams::simuflag = kFALSE;
// -------------------------
// CALIBRATION (PED,SIG,BAD)
// -------------------------
GL_TRK_CALIB TrkParams::calib      = GL_TRK_CALIB();
TString      TrkParams::calibpatht = "";
TString      TrkParams::calibpathf = "";
Bool_t       TrkParams::calib104   = 0;
Bool_t       TrkParams::calibload  = false;
TrkCalib*    TrkParams::calib1 = 0;
TrkCalib*    TrkParams::calib2 = 0;
// -------------------------
// PARAMETERS loaded from DB
// -------------------------
UInt_t       TrkParams::trkparamtype[] = {1,2,3,4,5,6,7};
GL_PARAM     TrkParams::gl[]           = {GL_PARAM(),GL_PARAM(),GL_PARAM(),GL_PARAM(),GL_PARAM(),GL_PARAM(),GL_PARAM()};
TString      TrkParams::glpath[]       = {"","","","","","",""};
Bool_t       TrkParams::glload[]       = {false,false,false,false,false,false,false}; 
// ----------------
// other parameters
// ----------------
cDbg   TrkParams::init__dbg_mode       = {0,0,0};
//int    TrkParams::init__pfa            = 14;//COG4
int    TrkParams::init__pfa            = 5;//ETAL
int    TrkParams::init__mini_trackmode = 0;
int    TrkParams::init__mini_istepmin  = 5; //3;
double TrkParams::init__mini_fact      = 1.e4; //100.;
float  TrkParams::init__pfa_e234ax[]   = {0.,10.,10.,15.,15.,90.};
float  TrkParams::init__pfa_e234ay[]   = {0.,20.,90.,90.,90.,90.};
double TrkParams::init__deltab_0       = 0.;
double TrkParams::init__deltab_1       = 0.;
double TrkParams::init__dlt            = 1.e-5;
// ------------------------------------------
// nominal z-coordinates to define acceptance
// ------------------------------------------
int   TrkParams::nGF   = NGF;
float TrkParams::zGF[] = {+53.74,+53.04,+23.94,+23.44,+22.29,+21.83,+13.39,+4.49,-4.41,-13.31,-21.83,-22.22,-23.49,-24.34};
float TrkParams::xGF_min[] = {-20.40,-20.40,-9.00,-9.00,-8.07,-8.07,-8.07,-8.07,-8.07,-8.07,-8.07,-8.07,-9.00,-9.00};
float TrkParams::xGF_max[] = {+20.40,+20.40,+9.00,+9.00,+8.07,+8.07,+8.07,+8.07,+8.07,+8.07,+8.07,+8.07,+9.00,+9.00};
// float TrkParams::yGF_min[] = {-16.50,-16.50,-7.50,-7.50,-7.25,-6.57,-7.25,-7.25,-7.25,-7.25,-6.57,-6.75,-7.50,-7.50};
// float TrkParams::yGF_max[] = {+16.50,+16.50,+7.50,+7.50,+6.75,+6.57,+6.75,+6.75,+6.75,+6.75,+6.57,+7.25,+7.50,+7.50};
// per i piani interni alla cavita`, gli estremi sono dati dalla cavita` stessa
float TrkParams::yGF_min[] = {-16.50,-16.50,-7.50,-7.50,-7.25,-6.57,-6.57,-6.57,-6.57,-6.57,-6.57,-6.75,-7.50,-7.50};
float TrkParams::yGF_max[] = {+16.50,+16.50,+7.50,+7.50,+6.75,+6.57,+6.57,+6.57,+6.57,+6.57,+6.57,+7.25,+7.50,+7.50};
TString TrkParams::GF_element[] = {"S11","S12","S21","S22","T1","CUF","T2","T3","T4","T5","CLF","T6","S31","S32"};

TrkParams::TrkParams(){

    cout<<"TrkParams::TrkParams()"<<endl;

}
float aint(float f){
    int   ret  = (int)f;
    float ret1 = 0;
    ret1=(float)ret;
    return ret1;	
}

float anint(float f){
    int   ret  = (int)(f+0.5);
    float ret1 = 0;
    ret1=(float)ret;
    return ret1;	
}

void TrkParams::SetSimuFlag(Bool_t flag){
  simuflag = flag;
}

Bool_t TrkParams::GetSimuFlag(){
  return simuflag;
}


/**
 * Static method to open a DB connection. 
 * HOST, USER and PASSWORD are taken from enviroment variables $PAM_DBHOST, 
 * $PAM_DBUSER and $PAM_DBPSW
 * NB! The method create a new connection, which has to be closed by the user.
 */
TSQLServer* TrkParams::SetDBConnection(){

    TString host = "mysql://localhost/pamelaprod";
    TString user = "anonymous";
    TString psw = "";
    const char *pamdbhost=gSystem->Getenv("PAM_DBHOST");
    const char *pamdbuser=gSystem->Getenv("PAM_DBUSER");
    const char *pamdbpsw=gSystem->Getenv("PAM_DBPSW");
    if ( !pamdbhost ) pamdbhost = "";
    if ( !pamdbuser ) pamdbuser = "";
    if ( !pamdbpsw ) pamdbpsw = "";
    if ( strcmp(pamdbhost,"") ) host = pamdbhost;
    if ( strcmp(pamdbuser,"") ) user = pamdbuser;
    if ( strcmp(pamdbpsw,"") ) psw = pamdbpsw;
    if(TrkParams::DebugMode()){
	cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl; 
	cout<<"TrkParams::SetDBConnection() >> Connecting to DB"<<endl;
	cout<<"HOST "<<host<<endl;
	cout<<"USER "<<user<<endl;
	cout<<"PSW  "<<psw<<endl;
    }
    TSQLServer *dbc = TSQLServer::Connect(host.Data(),user.Data(),psw.Data());
    if( !dbc )return NULL;
    if( !dbc->IsConnected() )return NULL;    
    stringstream myquery;  // EMILIANO
    myquery.str("");  // EMILIANO
    myquery << "SET time_zone='+0:00';";  // EMILIANO
    delete dbc->Query(myquery.str().c_str());  // EMILIANO
    delete dbc->Query("SET sql_mode = 'NO_UNSIGNED_SUBTRACTION';");//EM
    if(TrkParams::DebugMode()){
	cout << " ...done"<<endl;
	cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl; 
    }
    
    return dbc;
}
/**
 * \brief Static method to set the calibration to be loaded. 

 * It retrieves the calibration associated to a given run, from 
 * a given DB. It fills the F77 common.
 * @param glrun Pointer to a GL_RUN row 
 * @param dbc   Pointer to a DB connection 
 */
Bool_t TrkParams::SetCalib( GL_RUN *glrun, TSQLServer* dbc ){

//    cout << "glrun-> RUNHEADER_TIME "<<glrun->RUNHEADER_TIME <<endl;

    if( !CalibIsLoaded()                          || 
	(glrun->TRK_CALIB_USED==104 && !calib104) ||
	(glrun->TRK_CALIB_USED!=104 && calib104)  ||
	glrun->RUNHEADER_TIME < calib.FROM_TIME   ||
	glrun->RUNHEADER_TIME > calib.TO_TIME     ||
	false ){


	GL_TRK_CALIB q2;
	GL_ROOT q3;
	GL_PARAM q4;


	bool LOCAL_CONNECTION = false;
	if( !dbc || (dbc && !dbc->IsConnected()) ){

//	    if(TrkParams::WarningMode())cout <<" Missing DB connection -- check PAMELA environment variables "<<endl; 
	    dbc = TrkParams::SetDBConnection();
 	    if(dbc && dbc->IsConnected())LOCAL_CONNECTION = true;

	}

	
	if(TrkParams::VerboseMode()){
	    cout << "--------------------------------------"<<endl;
	    cout << "UPDATING calibration -- run-header time "<< glrun->RUNHEADER_TIME <<endl;
	}
	if( q2.Query_GL_TRK_CALIB(glrun->RUNHEADER_TIME,dbc) ){
	    cout << " Bool_t TrkParams::SetCalib( GL_RUN* , TSQLServer* ) -- ERROR -- failed query to GL_TRK_CALIB "<<endl;
	    return false;
	}
	if( q2.EV_ROOT_CALIBTRK1 != q2.EV_ROOT_CALIBTRK2 ) 
	    printf(" WARNING!! ---> EV_ROOT_CALIBTRK1=%d it's different from EV_ROOT_CALIBTRK2=%d \n\n",q2.EV_ROOT_CALIBTRK1,q2.EV_ROOT_CALIBTRK2);	
	if( q3.Query_GL_ROOT(q2.ID_ROOT_L0,dbc) ){
	    cout << " Bool_t TrkParams::SetCalib( GL_RUN* , TSQLServer* ) -- ERROR -- failed query to GL_ROOT "<<endl;
	    return false;
	}

	if(TrkParams::VerboseMode())cout << "selected DB entry "<<q2.ID<<" from_time "<<q2.FROM_TIME<<" to time "<<q2.TO_TIME<<" --> VALIDATION "<<q2.VALIDATION<<endl;
	calib      = q2;
	calibpathf = q3.PATH + q3.NAME;
	calib104   = (glrun->TRK_CALIB_USED==104);
	calibload  = kFALSE;
	if(calib104){
	    if (q4.Query_GL_PARAM(glrun->RUNHEADER_TIME,7,dbc) )return false; 
	    calibpatht = q4.PATH + q4.NAME;
	}
	
	if(LOCAL_CONNECTION&&dbc){
	    dbc->Close();
	    delete dbc;
	    if(TrkParams::DebugMode()){
		cout << " DB connection closed."<<endl;
	    }	    
	}

//    return TrkParams::LoadCalib();
	return true;
    }

    return false;
};

/**
 * Method to "validate" tracker calibration. Implemented for test purpose. Effective implementation
 * in YodaProfiler.
 */
UInt_t TrkParams::ValidateTrkCalib( CalibTrk1Event* caltrk){

    UInt_t validate = 1;
    Int_t vorder[]={5,5,3,3,4,4,2,2,1,1,0,0};
//    UInt_t timeaftercalib=120000; //2000;
    TString classname = caltrk->GetName();
//  ----------
//  Check CRCs 
//  ----------
    if(TrkParams::VerboseMode())cout << " DSP: ";
    for(Int_t ipkt=0; ipkt<6; ipkt++){
	if(TrkParams::VerboseMode())cout <<" "<<caltrk->DSPnumber[ipkt];
	if(caltrk->DSPnumber[ipkt]>0 && caltrk->DSPnumber[ipkt]<=12){
	    if( caltrk->crc_hcal[ipkt] ){
		if(TrkParams::WarningMode())cout<<"(CRC Header)";
//		if(TrkParams::WarningMode())cout << "ValidateTrkCalib: "<<classname<<" --WARNING-- CRC error in calibration header: pkt "<<ipkt<<endl;    
//		return 0; // :-(
		validate = 0;
	    }
	    for(Int_t ilad=0; ilad<3; ilad++)if( caltrk->crc_cal[ipkt][ilad] ){
		if(TrkParams::WarningMode())cout<<"(CRC Pkt-"<<ilad<<")";
//		if(TrkParams::WarningMode())cout << "ValidateTrkCalib: "<<classname<<" --WARNING-- CRC error in calibration packet: pkt "<<ipkt<<endl;    
//		return 0; // :-(
		validate = 0;
	    }
	}
    }
    if(TrkParams::VerboseMode())cout << endl;;
//  -----------------------
//  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;
    UInt_t base=0;
    //    UInt_t mask=0;// EM GCC 4.7
    if(classname.Contains("CalibTrk1Event")){
	base=12;
        //	mask=0x03F000; // EM GCC 4.7
    }
    if(classname.Contains("CalibTrk2Event")){
	base=18;
        //	mask=0xFC0000;  // EM GCC 4.7
    }
//  -------------------------------------------------
//  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; // :-)
    else {
	if(TrkParams::WarningMode())cout << "ValidateTrkCalib: "<<classname<<" --WARNING-- there might be some missing packets :-(  ( "<<npkts<<" instead of 6 ) --> "<<endl;    
	validate = 0;
    }
//    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; // :-)

//    cout << validate << endl;
    return validate;

}
/**
 * Method to fill the tracker calibration-parameter struct from on-line calibrations
 */
void TrkParams::FillACalibFrom(TFile* f0, Int_t ev_reg1, Int_t ev_reg2){

    cTrkCalib *ca = &pedsigbad_;
    ca->Reset();

    TTree *tr1 = (TTree*)f0->Get("CalibTrk1");  
    TTree *tr2 = (TTree*)f0->Get("CalibTrk2"); 

    if(!calib1)calib1 = new TrkCalib(); 
    if(!calib2)calib2 = new TrkCalib(); 
//     calibx->Set(calibdata1);
//     caliby->Set(calibdata2);

//     CalibTrk1Event *calibdata1 = 0;
//     CalibTrk2Event *calibdata2 = 0;
//     tr1->SetBranchAddress("CalibTrk1",&calibdata1);
//     tr2->SetBranchAddress("CalibTrk2",&calibdata2);
    tr1->SetBranchAddress("CalibTrk1",calib1->GetPointerTo());
    tr2->SetBranchAddress("CalibTrk2",calib2->GetPointerTo());
    if ( tr1->GetEntry(ev_reg1) <= 0 ) throw -36;//EM
    if ( tr2->GetEntry(ev_reg2) <= 0 ) throw -36;//EM 
    Int_t dspn1(0),dspn2(0);
 

    // --- TEST TEST TEST TEST --- //
//    TrkParams::ValidateTrkCalib(calib1->Get());
//    TrkParams::ValidateTrkCalib((CalibTrk1Event*)calib2->Get());

    UInt_t test1 = TrkParams::ValidateTrkCalib((CalibTrk1Event*)(calib1->Get()));
    UInt_t test2 = TrkParams::ValidateTrkCalib((CalibTrk1Event*)(calib2->Get()));
    if( !test1 || !test2 ){
//	if(TrkParams::calib.VALIDATION==1)cout << "--> modify DB info "<<endl;
	TrkParams::calib.VALIDATION = 0;
    }
//    if(TrkParams::calib.VALIDATION==0)cout << " ** WARNING ** Calibration not validated "<<endl;

    for(Int_t i=0;i<6;i++){


	dspn1=calib1->Get()->DSPnumber[i]-1;
	dspn2=calib2->Get()->DSPnumber[i]-1;
//	cout<<"dspn1= "<<dspn1<<"   dspn2= "<<dspn2<<endl;	
	for(Int_t ii=0;ii<3072;ii++){
	    Int_t j=(ii/128);
	    Int_t jj=ii-j*128; 
	    if(dspn1>=0 && dspn1<12){
		ca->pedestal[jj][j][dspn1]=calib1->Get()->DSPped_par[i][ii];
		ca->pedestal_t[jj][j][dspn1]=aint(calib1->Get()->DSPped_par[i][ii]);
		ca->sigma[jj][j][dspn1]=calib1->Get()->DSPsig_par[i][ii];
		ca->sigma_t[jj][j][dspn1]=anint(calib1->Get()->DSPsig_par[i][ii]);
		if(calib1->Get()->DSPbad_par[i][ii]==0) 
		    ca->bad[jj][j][dspn1]=1;
		else if(calib1->Get()->DSPbad_par[i][ii]==1)
		    ca->bad[jj][j][dspn1]=0;
		//	      cout<<"sigma trk1= "<<sigma[jj][j][dspn1]<<endl;
		//        cout<<"sigma_t trk1= "<<sigma_t[jj][j][dspn1]<<endl;
	    }

	    if(dspn2>=0 && dspn2<12){
		ca->pedestal[jj][j][dspn2]=calib2->Get()->DSPped_par[i][ii];
		ca->pedestal_t[jj][j][dspn2]=aint(calib2->Get()->DSPped_par[i][ii]);
		ca->sigma[jj][j][dspn2]=calib2->Get()->DSPsig_par[i][ii];
		ca->sigma_t[jj][j][dspn2]=anint(calib2->Get()->DSPsig_par[i][ii]);
		if(calib2->Get()->DSPbad_par[i][ii]==0)
		    ca->bad[jj][j][dspn2]=1;
		else if(calib2->Get()->DSPbad_par[i][ii]==1)
		    ca->bad[jj][j][dspn2]=0;
		//        cout<<"sigma trk2= "<<sigma[jj][j][dspn2]<<endl;
		//        cout<<"sigma_t trk2= "<<sigma_t[jj][j][dspn2]<<endl;
	    }
	};
    };
	
    tr1->Delete();
    tr2->Delete();
};
/**
 * Method to fill the tracker calibration-parameter struct from on-line calibrations
 */
// void TrkParams::FillFCalibFrom(TFile* f0, Int_t ev_reg1, Int_t ev_reg2){

//     cTrkCalib *ca = &pedsigbad_;
// //    ca->Reset();

//     TTree *tr1 = (TTree*)f0->Get("CalibTrk1");  
//     TTree *tr2 = (TTree*)f0->Get("CalibTrk2"); 

//     CalibTrk1Event *calibdata1 = 0;
//     CalibTrk2Event *calibdata2 = 0;
//     tr1->SetBranchAddress("CalibTrk1",&calibdata1);
//     tr2->SetBranchAddress("CalibTrk2",&calibdata2);
//     tr1->GetEntry(ev_reg1);
//     tr2->GetEntry(ev_reg2); 
//     Int_t dspn1(0),dspn2(0);

//     // --- TEST TEST TEST TEST --- //
// //     TrkParams::ValidateTrkCalib(calibdata1);
// //     TrkParams::ValidateTrkCalib((CalibTrk1Event*)calibdata2);
//     UInt_t test1 = TrkParams::ValidateTrkCalib(calibdata1);
//     UInt_t test2 = TrkParams::ValidateTrkCalib((CalibTrk1Event*)calibdata2);
//     if( !test1 || !test2 ){
// 	if(TrkParams::calib.VALIDATION==1)cout << "--> modify DB info "<<endl;
// 	TrkParams::calib.VALIDATION = 0;
//     }
//     if(TrkParams::calib.VALIDATION==0)cout << " ** WARNING ** Calibration not validated "<<endl;
	
//     for(Int_t i=0;i<6;i++){
// 	dspn1=calibdata1->DSPnumber[i]-1;
// 	dspn2=calibdata2->DSPnumber[i]-1;
// 	/*     cout<<"dspn1= "<<dspn1<<"   dspn2= "<<dspn2<<endl; */
// 	for(Int_t ii=0;ii<3072;ii++){
// 	    Int_t j=(ii/128);
// 	    Int_t jj=ii-j*128; 
// 	    if(dspn1>=0 && dspn1<12){
// 		ca->pedestal[jj][j][dspn1]=calibdata1->DSPped_par[i][ii];
// 		ca->sigma[jj][j][dspn1]=calibdata1->DSPsig_par[i][ii];
// 		if(calibdata1->DSPbad_par[i][ii]==0)
// 		    ca->bad[jj][j][dspn1]=1;
// 		else if(calibdata1->DSPbad_par[i][ii]==1)
// 		    ca->bad[jj][j][dspn1]=0;
// 		//	      cout<<"sigma trk1= "<<sigma[jj][j][dspn1]<<endl;
// 		//        cout<<"sigma_t trk1= "<<sigma_t[jj][j][dspn1]<<endl;
// 	    }
// 	    if(dspn2>=0 && dspn2<12){
// 		ca->pedestal[jj][j][dspn2]=calibdata2->DSPped_par[i][ii];
// 		ca->sigma[jj][j][dspn2]=calibdata2->DSPsig_par[i][ii];
// 		if(calibdata2->DSPbad_par[i][ii]==0)
// 		    ca->bad[jj][j][dspn2]=1;
// 		else if(calibdata2->DSPbad_par[i][ii]==1)
// 		    ca->bad[jj][j][dspn2]=0;
// 		//        cout<<"sigma trk2= "<<sigma[jj][j][dspn2]<<endl;
// 		//        cout<<"sigma_t trk2= "<<sigma_t[jj][j][dspn2]<<endl;
// 	    }
// 	};
//     };
	
//     tr1->Delete();
//     tr2->Delete();
// };
/**
 * Method to fill the tracker calibration-parameter struct from on-line calibrations
 */
// void TrkParams::FillTCalibFrom(TFile* f0, Int_t ev_reg1, Int_t ev_reg2){

//     cTrkCalib *ca = &pedsigbad_;
// //    ca->Reset();

//     TTree *tr1 = (TTree*)f0->Get("CalibTrk1");  
//     TTree *tr2 = (TTree*)f0->Get("CalibTrk2"); 

//     CalibTrk1Event *calibdata1 = 0;
//     CalibTrk2Event *calibdata2 = 0;
//     tr1->SetBranchAddress("CalibTrk1",&calibdata1);
//     tr2->SetBranchAddress("CalibTrk2",&calibdata2);
//     tr1->GetEntry(ev_reg1);
//     tr2->GetEntry(ev_reg2); 
//     Int_t dspn1(0),dspn2(0);
	
//     // --- TEST TEST TEST TEST --- //
// //     TrkParams::ValidateTrkCalib(calibdata1);
// //     TrkParams::ValidateTrkCalib((CalibTrk1Event*)calibdata2);
//     UInt_t test1 = TrkParams::ValidateTrkCalib(calibdata1);
//     UInt_t test2 = TrkParams::ValidateTrkCalib((CalibTrk1Event*)calibdata2);
//     if( !test1 || !test2 ){
// 	if(TrkParams::calib.VALIDATION==1)cout << "--> modify DB info "<<endl;
// 	TrkParams::calib.VALIDATION = 0;
//     }
//     if(TrkParams::calib.VALIDATION==0)cout << " ** WARNING ** Calibration not validated "<<endl;

//     for(Int_t i=0;i<6;i++){
// 	dspn1=calibdata1->DSPnumber[i]-1;
// 	dspn2=calibdata2->DSPnumber[i]-1;
// 	/*     cout<<"dspn1= "<<dspn1<<"   dspn2= "<<dspn2<<endl; */
// 	for(Int_t ii=0;ii<3072;ii++){
// 	    Int_t j=(ii/128);
// 	    Int_t jj=ii-j*128; 
// 	    if(dspn1>=0 && dspn1<12){
// 		ca->pedestal_t[jj][j][dspn1]=aint(calibdata1->DSPped_par[i][ii]);
// 		ca->sigma_t[jj][j][dspn1]=anint(calibdata1->DSPsig_par[i][ii]);
// 	    }
// 	    if(dspn2>=0 && dspn2<12){
// 		ca->pedestal_t[jj][j][dspn2]=aint(calibdata2->DSPped_par[i][ii]);
// 		ca->sigma_t[jj][j][dspn2]=anint(calibdata2->DSPsig_par[i][ii]);
// 	    }	
// 	};
//     };
	
//     tr1->Delete();
//     tr2->Delete();
// };
/**
 * Method to fill the tracker calibration-parameter struct from default calibration
 */
void TrkParams::FillTCalibFrom(TString path){
    
    path_.FillWith(path);
    fillpedsigfromdefault_();
    if(path_.error) throw -216;

};
/**
 * Method to fill the tracker VA1-mask struct from calibration
 */
void TrkParams::FillMask(TFile* f0, Int_t ev_reg1, Int_t ev_reg2){
    
    cTrkMask *ma = &mask_;
    ma->Reset();

    TrkCalib *calib = new TrkCalib();

    for(Int_t i=0; i<2; i++){
	TTree *tr=0; 
	if(i==0){
	    //-------------------------
	    //read calibration packet 1
	    //-------------------------
	    tr = (TTree*)f0->Get("CalibTrk1");  
	    tr->SetBranchAddress("CalibTrk1",calib->GetPointerTo());
	    if ( tr->GetEntry(ev_reg1) <= 0 ) throw -36;//EM
	}
	if(i==1){
	    //-------------------------
	    //read calibration packet 2
	    //-------------------------
	    tr = (TTree*)f0->Get("CalibTrk2"); 
	    tr->SetBranchAddress("CalibTrk2",calib->GetPointerTo());
	    if ( tr->GetEntry(ev_reg2) <= 0 ) throw -36; 
	}
	for(Int_t ipkt=0; ipkt<NPLANE; ipkt++){
	    Int_t view   = calib->GetView(ipkt);
	    if( (view-1)>= 0 && (view-1)<12 ){
		for(Int_t ivk=0; ivk<NVK; ivk++){
		    Float_t sigm = calib->GetMean("SIG-BAD",ipkt,ivk+1);
		    Float_t sigmin = 0.;
		    if(view%2)sigmin = 6.5;
		    else      sigmin = 2.5;
		    Int_t mask = 1;
		    if( sigm<sigmin )mask = 0;		    
		    ma->mask_vk_run[ivk][view-1] = mask;		    
		}	
	    }
	}
	if(tr)tr->Delete();
    }

    if(TrkParams::VerboseMode()){
	for(Int_t iv=0; iv<NVIEW; iv++){
	    cout<<"view "<<setw(3)<<iv<<": ";
	    for(Int_t ivk=0; ivk<NVK; ivk++)cout<<ma->mask_vk_run[ivk][iv];
	    cout << endl;
	}
    }

    if(calib)calib->Delete();

};

// Bool_t TrkParams::CalibIsLoaded(UInt_t time){

//     if( !calibload ) return false;

// };


/**
 * \brief Static method to load calibration. 
 * Calibration is loaded ONLY IF TrkParams::CalibLoaded()==kTRUE, which appens after the method TrkParams::SetCalib(***) is called.
 */
Bool_t TrkParams::LoadCalib( ){

    if( TrkParams::CalibIsLoaded() )return false;

    // =============================================================
    // retrieve calibration file needed to reduce data 
    // =============================================================
    // if run OBT is > last calibration "expiration date"
    //  - search for new calibration packet
    //  - load calibration parameters (full + truncated)    
    if(TrkParams::VerboseMode()){
	cout << "--------------------------------------"<<endl;
	cout << "Retrieve calibration (PED-SIG-BAD) ..."<<endl;
	cout << " Full pedestals for cluster finding:";
	cout << " >> loading from LEVEL0 file: "<< calibpathf << endl;
    }
    FileStat_t t;
    if( gSystem->GetPathInfo(calibpathf.Data(),t) )return false;
   
    bool alreadyopened = false;
    TFile *f0_c=0;
    f0_c = (TFile*)gROOT->GetListOfFiles()->FindObject(calibpathf);
    if(f0_c)alreadyopened=true;
    else f0_c = new TFile(calibpathf);
    if ( !f0_c ) return false;

    if(TrkParams::VerboseMode()){
	cout << " calibration entry "<< calib.EV_ROOT_CALIBTRK1 << " " << calib.EV_ROOT_CALIBTRK2; 
	cout << " (from time "<< calib.FROM_TIME <<" to time "<< calib.TO_TIME <<")"<<endl;
	cout << " - full+truncated parameters "<<endl; 
    }
    TrkParams::FillACalibFrom(f0_c,calib.EV_ROOT_CALIBTRK1,calib.EV_ROOT_CALIBTRK2);
    if(TrkParams::VerboseMode())cout << " - VK-mask (RUN-by-RUN)"<<endl; 
    TrkParams::FillMask(f0_c,calib.EV_ROOT_CALIBTRK1,calib.EV_ROOT_CALIBTRK2);

    // =============================================================
    // retrieve calibration file needed to uncompress data
    // =============================================================
    // if the run was compressed using default calib
    // load truncated pedestals from default
    // otherwise reload them from on-line calibration
    if(TrkParams::VerboseMode())cout << " Truncated pedestals for uncompression:";
    if( calib104 ){

 	if(TrkParams::VerboseMode())cout << " >> loading default calibration: "<< calibpatht << endl; 
	TrkParams::FillTCalibFrom(calibpatht);
	    
    }else{

//	if ( !f0_c ) return false;
	if(TrkParams::VerboseMode())cout << ">> already loaded " << endl;
//	TrkParams::FillTCalibFrom(f0_c,calib.EV_ROOT_CALIBTRK1,calib.EV_ROOT_CALIBTRK2);
    };
    if(!alreadyopened)f0_c->Close();
    if(TrkParams::VerboseMode())cout << "--------------------------------------"<<endl;
    
    calibload = kTRUE;
    return true;
};

Int_t TrkParams::GetIndex( UInt_t type ){
    Int_t index = -1;
    for (Int_t i=0; i< NTYPES; i++)if( type == trkparamtype[i] )index=i;
    return index;
};

/**
 * Set tracker parameters proper for a run querying the DB.
 * @param glrun Input run info 
 * @param dbc   Database 
 * @param type  Parameter type
 * @return FALSE if parameter set fails.
 * If glrun==NULL the first parameter entry from GL_PARAM table is set. 
 * If dbc==NULL, try to open a connection taking DB-connection
 * parameters from PAMELA environment variables.
 */
Bool_t TrkParams::Set( GL_RUN* glrun , TSQLServer* dbc , UInt_t type, UInt_t abstime){


    UInt_t index = TrkParams::GetIndex( type );
    if(index < 0)return false;

    if(TrkParams::VerboseMode())
      cout <<"Calling Bool_t TrkParams::Set(GL_RUN* "<<glrun<<" ,TSQLServer* "<<dbc<<" ,UInt_t "<<type<<" ,UInt_t " <<abstime << " ) >> (**WARNING** check that this is all ok!! )"<<endl;

    UInt_t runheadtime=1;
    UInt_t runid=0;
//    UInt_t runheadtime = numeric_limits<UInt_t>::max();
    if(glrun){
	runheadtime = glrun->RUNHEADER_TIME;
	runid       = glrun->ID;
    }else 
      cout <<"Bool_t TrkParams::Set(GL_RUN* "<<glrun<<" ,TSQLServer* "<<dbc<<" ,UInt_t "<<type<<" ,UInt_t " <<abstime << " ) >> GL_RUN==NULL -- taking first entry (**WARNING** check that this is ok!! )"<<endl;


    if( !abstime || !simuflag ) abstime = runheadtime;// EM: if simu?

    if(TrkParams::VerboseMode())
      cout << "TrkParams::IsLoaded(type)=" << TrkParams::IsLoaded(type) << " abstime=" << abstime << " runheadtime=" << runheadtime << " gl[index].FROM_TIME=" << gl[index].FROM_TIME << " gl[index].TO_TIME=" << gl[index].TO_TIME << endl;

    if( !TrkParams::IsLoaded(type) ||
	abstime < gl[index].FROM_TIME   ||
	abstime > gl[index].TO_TIME     ||	
        false ){
      
      if(TrkParams::VerboseMode())
	cout << "<< set TrkParams type "<<type<<" from DB << RUN "<<runid<<endl;
      
      bool LOCAL_CONNECTION = false;
      if( !dbc || (dbc && !dbc->IsConnected()) ){
	
	//	    if(TrkParams::WarningMode())cout <<" Missing DB connection -- check PAMELA environment variables "<<endl; 
	dbc = TrkParams::SetDBConnection();
	if(dbc && dbc->IsConnected())LOCAL_CONNECTION = true;
	
      }
      
      GL_PARAM q4;
      //	if( q4.Query_GL_PARAM(runheadtime,type,dbc) )return false;       
      if( q4.Query_GL_PARAM(abstime,type,dbc) )return false;     //VALERIO  
      if(LOCAL_CONNECTION){
	dbc->Close();
	delete dbc;
	if(TrkParams::DebugMode()){
	  cout << " DB connection closed."<<endl;
	}	    
      }
      gl[index]     = q4;
      glpath[index] = q4.PATH+q4.NAME;
      glload[index] = false;
      
      //return true;
      
    }
    return true;
    
};
/**
 * Set tracker parameters proper for the run, from input.
 * @param path  Path to parameters directory
 * @param type  Parameter type
 * @return FALSE if parameter set fails.
 */
Bool_t TrkParams::Set( TString path , UInt_t type){

    UInt_t index = TrkParams::GetIndex( type );
    if(index < 0)return false;

    gl[index].TYPE= type;
    glpath[index] = path;
    if(TrkParams::VerboseMode())
	cout << "<< set TrkParams type "<<type<<" from path << "<<path<<endl;
    glload[index] = false;

//    return TrkParams::Load(type);
    return true;

};

/**
 * Set and load tracker parameters.
 * @param type  Parameter type
 * If no path as been yet specified, it set a default path.
 * @return FALSE if parameter set fails.
 */
Bool_t TrkParams::Set(UInt_t type){


    return Set(0,0,type);


};
/**
 * Set tracker parameters.
 * If no path as been yet specified, try to read from DB 
 * otherwise it set a default path.
 * @return FALSE if parameter set fails.
 */

Bool_t  TrkParams::Set( ){


    for(Int_t i=0; i<NTYPES; i++)if ( !TrkParams::Set(trkparamtype[i])) return false;

    return true;
}

/**
 * Load tracker parameter, if not already loaded.
 * @param type Parameter type
 * ( Any call to TrkParams::Set(...) forces reloading )
 */
Bool_t TrkParams::Load(UInt_t type){
    
    Int_t index = TrkParams::GetIndex( type );
    if( index<0 )return false;
    if( glload[index] )return false;
    if( glpath[index].IsNull() )TrkParams::Set(type);

    switch( type ){
    //------------------------------------------
    case 1:	
	if(TrkParams::VerboseMode())cout <<type<<" -- Loading magnetic field "<<glpath[index]<<endl;
	strcpy(path_.path,glpath[index].Data());
	path_.pathlen = glpath[index].Length();
	path_.error   = 0;
	readb_();
	if(path_.error) return false;
	glload[index]=true;
	break;
    //------------------------------------------
    case 2:	
	if(TrkParams::VerboseMode())cout <<type<<" -- Loading ADC-to-MIP conversion parameters "<<glpath[index]<<endl;
	strcpy(path_.path,glpath[index].Data());
	path_.pathlen = glpath[index].Length();
	path_.error   = 0;
	readmipparam_();
	if(path_.error) return false;
	glload[index]=true;
	break;
    //------------------------------------------
    case 3:	
	if(TrkParams::VerboseMode())cout <<type<<" -- Loading charge-correlation parameters "<<glpath[index]<<endl;
	strcpy(path_.path,glpath[index].Data());
	path_.pathlen = glpath[index].Length();
	path_.error   = 0;
	readchargeparam_();
	if(path_.error) return false;
	glload[index]=true;
	break;
    //------------------------------------------
    case 4:	
	if(TrkParams::VerboseMode())cout <<type<<" -- Loading p.f.a. parameters "<<glpath[index]<<endl;
	strcpy(path_.path,glpath[index].Data());
	path_.pathlen = glpath[index].Length();
	path_.error   = 0;
	readetaparam_();
	if(path_.error) return false;
	glload[index]=true;
	break;
    //------------------------------------------
    case 5:	
	if(TrkParams::VerboseMode())cout <<type<<" -- Loading alignment parameters "<<glpath[index]<<endl;
	strcpy(path_.path,glpath[index].Data());
	path_.pathlen = glpath[index].Length();
	path_.error   = 0;
	readalignparam_();
	if(path_.error) return false;
	glload[index]=true;
	break;
    //------------------------------------------
    case 6:	
	if(TrkParams::VerboseMode())cout <<type<<" -- Loading VK-mask parameters "<<glpath[index]<<endl;
	strcpy(path_.path,glpath[index].Data());
	path_.pathlen = glpath[index].Length();
	path_.error   = 0;
	readvkmask_();
	if(path_.error) return false;
	glload[index]=true;
	break;
    //------------------------------------------
    case 7:	
	if(TrkParams::VerboseMode())cout <<type<<" -- Loading default calibration "<<glpath[index]<<endl;
	strcpy(path_.path,glpath[index].Data());
	path_.pathlen = glpath[index].Length();
	path_.error   = 0;
//	fillpedsigfromdefault_();
	if(TrkParams::VerboseMode())cout << ">> not implemented <<"<<endl;
	if(path_.error) return false;
	glload[index]=true;
	break;
    default:
	if(TrkParams::VerboseMode())cout << " Bool_t TrkParams::Load(UInt_t type) -- type "<< type << "not yet implemented"<<endl;
	return false;
    };

    return true;
}

Bool_t TrkParams::Load( ){
	Bool_t result = true;
    for(Int_t i=0 ; i<NTYPES; i++)
      if(!glload[i] && trkparamtype[i]>0 )
        if( !TrkParams::Load(trkparamtype[i]) )
          result = false;
    return result;
};
Bool_t TrkParams::IsLoaded( ){
    for(Int_t i=0 ; i<NTYPES; i++)if(!glload[i] && trkparamtype[i]>0 )return false;
    return true;
};

/**
 * Get ADC-to-MIP conversion parameters
 * @param nl ladder number (0-2)
 * @param nv view number (0-11)
 */
float TrkParams::GetMIP(int nl, int nv){
    TrkParams::Load(2);
    if( !TrkParams::IsLoaded(2) )return 0.;
    return adc2mip_.mip[nl][nv];
}

/**
 * Get BY (kGauss)
 * @param v (x,y,z) coordinates in cm
 */
float TrkParams::GetBX(float* v){
    TrkParams::Load(1);
    if( !TrkParams::IsLoaded(1) )return 0.;
    float b[3];
    gufld_(v,b);
    return b[0]/10.;
}
/**
 * Get BY (kGauss)
 * @param v (x,y,z) coordinates in cm
 */
float TrkParams::GetBY(float* v){
    TrkParams::Load(1);
    if( !TrkParams::IsLoaded(1) )return 0.;
    float b[3];
    gufld_(v,b);
    return b[1]/10.;
}
/**
 * Get BY (kGauss)
 * @param v (x,y,z) coordinates in cm
 */
float TrkParams::GetBZ(float* v){
    TrkParams::Load(1);
    if( !TrkParams::IsLoaded(1) )return 0.;
    float b[3];
    gufld_(v,b);
    return b[2]/10.;
}


/**
 * \brief Set tracking mode (0=standard. 1=???)
 */
void TrkParams::SetTrackingMode(int trackmode) {
    init__mini_trackmode = trackmode;
    SetTrackingMode(); //fill F77 common
};
/**
 * \brief Set fit-precision factor (typical value fact=100.)
 */
void TrkParams::SetPrecisionFactor(double fact){
    init__mini_fact      = fact;
    SetPrecisionFactor(); //fill F77 common
};
/**
 * \brief Set minimum number of step in track fitting 
 */
void TrkParams::SetStepMin(int istepmin){
    init__mini_istepmin  = istepmin;
    SetStepMin(); //fill F77 common
};
/**
 * \brief Set deltaB parameters (id=0,1) 
 */
void TrkParams::SetDeltaB(int id,double db){
    if(id!=0 && id!=1)cout << "void TrkParams::SetDeltaB(int id,double db) -- wrong input parameters: "<<id<<" "<<db<<endl;
    if(id==0)init__deltab_0 = db;
    if(id==1)init__deltab_1 = db;
    SetDeltaB(); //fill F77 common
};
/**
 * \brief Set DLT-grkuta precision factor (default 1.e-4)
 */
void TrkParams::SetDLT(double fact){
    init__dlt               = fact;
    SetDLT(); //fill F77 common
};

/**
 * \brief Fill F77 commons with PFA settings
 */
void TrkParams::SetPFA(){
    sw_.pfaid = init__pfa;    
    for(int i=0; i<6; i++){
	pfa_.e234ax[i] = init__pfa_e234ax[i];
	pfa_.e234ay[i] = init__pfa_e234ay[i];
    }
};
/**
 * \brief Set p.f.a.
 *
 * Implemented algorythms:
 * 0  ETA 
 * 1  ---
 * 2  ETA2
 * 3  ETA3
 * 4  ETA4
 * 5  ETAL ==> ETA+LANDI
 * 10 COG
 * 11 COG1
 * 12 COG2
 * 13 COG3
 * 14 COG4
 */
void TrkParams::SetPFA(int pfaid){
    init__pfa  = pfaid;
    SetPFA(); //fill F77 common
};
/**
 * \brief Set p.f.a. angular intervals
 *
 * This methods allows to set amgular intervals to apply ETA2,ETA3 or ETA4 
 * algorythm, in case ETA or ETAL is set (see TrkParams::SetPFA(int pfaid)).
 * @param v Pointer to a vector of 12 components, which represent the 
 * angular limits for ETA2,ETA3 and ETA4, for x and y views, respectivelly.
 * 
 */
void TrkParams::SetPFA(float *v){
    for(int i=0; i<6; i++){
	init__pfa_e234ax[i]  = v[i];
	init__pfa_e234ay[i]  = v[i+6];
    }
    SetPFA(); //fill F77 common
};


/**
 * \brief Get spatial resolution.
 *
 * Method to retrieve the spatial resolution associated with the 
 * adopted p.f.a.
 * @param view Tracker view (1-12)
 * @param angle Track projected angle
 *
 * In order to change p.f.a. use the SetPFA(int pfaid) method, eg.:
 *
 *  TrkParams::SetPFA(0)  // ETA
 * 
 */
float TrkParams::GetResolution(int view, float angle){
    float res = 1000;
    if     ( init__pfa == 0 )res = riseta_(&view,&angle);
    else if( init__pfa == 5 )res = riseta_(&view,&angle);
    else cout << "float TrkParams::GetResolution(int view, float angle) -- PFA "<<init__pfa<<" not yet implemented"<<endl; 
    return res;
}

/**
 * Returns the number of angular bins for p.f.a. parameters
 */
int TrkParams::GetPFA_NbinsAngle(){
    TrkParams::Load(4);
    if( !TrkParams::IsLoaded(4) ){
	cout << "int TrkParams::GetPFA_NbinsAngle() --- ERROR --- p.f.a. parameters  not loaded"<<endl;
	return 0;
    }
    return pfa_.nangbin;
};
/**
 * Returns the number of eta bins for p.f.a. parameters
 */
int TrkParams::GetPFA_NbinsETA(){
    TrkParams::Load(4);
    if( !TrkParams::IsLoaded(4) ){
	cout << "int TrkParams::GetPFA_NbinsETA() --- ERROR --- p.f.a. parameters  not loaded"<<endl;
	return 0;
    }
    return pfa_.netaval;
};

/**
 * Returns the pointer to a vector ( of size TrkParams::GetPFA_NbinsETA() ),
 * with eta-correction values for each eta bin. 
 * Bin extremes are given by float* TrkParams::GetPFA_ETAabs(pfa,int).
 *
 * @param pfa "ETA2","ETA3" or "ETA4"
 * @param nview View number (0-11)
 * @param nladder Ladder number (0-2)
 * @param nang Angular bin (@see int TrkParams::GetPFA_NbinsAngle()).
 * 
 * NB! the vector must be deallocated! 
 * delete [] vname;
 */
float* TrkParams::GetPFA_ETAcorr(TString pfa, int nview, int nladder, int nang){

    TrkParams::Load(4);
    if( !TrkParams::IsLoaded(4) ){
	cout << "float* TrkParams::GetPFA_ETAcorr(TString pfa, int nview, int nladder, int nang) --- ERROR --- p.f.a. parameters  not loaded"<<endl;
	return 0;
    }
   
    int nbins = GetPFA_NbinsETA();
    if(!nbins)return 0;

    if( nview   <   0 ||
	nview   >= 12 ||
	nladder <   0 ||
	nladder >=  3 ||
	nang    <   0 ||
	nang    >=  GetPFA_NbinsAngle() ||
	false)return 0;

     float *fcorr = new float [nbins];
//    float fcorr[nbins];

    if(!pfa.CompareTo("ETA2",TString::kIgnoreCase)){
	for(int ib=0; ib<nbins; ib++){
	    fcorr[ib] = pfa_.feta2[nang][nladder][nview][ib];
//	    cout << pfa_.eta2[nang][ib] << " - " <<  pfa_.feta2[nang][nladder][nview][ib]<<endl;;
	}
    }else if (!pfa.CompareTo("ETA3",TString::kIgnoreCase)){
	for(int ib=0; ib<nbins; ib++)fcorr[ib] = pfa_.feta3[nang][nladder][nview][ib];
    }else if (!pfa.CompareTo("ETA4",TString::kIgnoreCase)){
	for(int ib=0; ib<nbins; ib++)fcorr[ib] = pfa_.feta4[nang][nladder][nview][ib];
    }else{
	cout << "float* TrkParams::GetPFA_ETAcorr("<<pfa<<",...) ---  pfa parameters not implemented "<<endl;
	return 0;
    }    

    return fcorr;

};

/**
 * Returns the pointer to a vector with eta-bin extremes (@see float* TrkParams::GetPFA_ETAcorr(TString,int,int,int)).
 *
 * @param pfa "ETA2","ETA3" or "ETA4"
 * @param nang Angular bin (@see int TrkParams::GetPFA_NbinsAngle()).
 * 
 * NB the vector must be deallocated 
 * delete [] vname;
 */
float* TrkParams::GetPFA_ETAabs(TString pfa, int nang){
   
    TrkParams::Load(4);
    if( !TrkParams::IsLoaded(4) ){
	cout << "float* TrkParams::GetPFA_ETAabs(TString pfa, int nang) --- ERROR --- p.f.a. parameters  not loaded"<<endl;
	return 0;
    }

    int nbins = GetPFA_NbinsETA();
    if(!nbins)return 0;

    float *fcorr = new float [nbins];
//    float fcorr[nbins];
    if( nang    <   0 ||
	nang    >=  GetPFA_NbinsAngle() ||
	false)return 0;

    if(!pfa.CompareTo("ETA2",TString::kIgnoreCase)){
	for(int ib=0; ib<nbins; ib++)fcorr[ib] = pfa_.eta2[nang][ib];
    }else if (!pfa.CompareTo("ETA3",TString::kIgnoreCase)){
	for(int ib=0; ib<nbins; ib++)fcorr[ib] = pfa_.eta3[nang][ib];
    }else if (!pfa.CompareTo("ETA4",TString::kIgnoreCase)){
	for(int ib=0; ib<nbins; ib++)fcorr[ib] = pfa_.eta4[nang][ib];
    }else{
	cout << "float* TrkParams::GetPFA_ETAabs("<<pfa<<",...) ---  pfa parameters not implemented "<<endl;
	return 0;
    }    

    return fcorr;

};
/**
 * Returns the "Landi-correction".
 *
 * @param nview View number (0-11)
 * @param nladder Ladder number (0-2)
 * @param nang Angular bin (@see int TrkParams::GetPFA_NbinsAngle()).
 */
float TrkParams::GetPFA_ETAlandi(int nview, int nladder, int nang){

//     TrkParams::Load(4);
//     if( !TrkParams::IsLoaded(4) ){
// 	cout << "float* TrkParams::GetPFA_ETAlandi(int nview, int nladder, int nang) --- ERROR --- p.f.a. parameters  not loaded"<<endl;
// 	return 0;
//     }
    int nbins = GetPFA_NbinsAngle();
    if(!nbins)return 0;

    if( nview   <   0 ||
	nview   >= 12 ||
	nladder <   0 ||
	nladder >=  3 ||
	nang    <   0 ||
	nang    >=  nbins ||
	false)return 0;
   

    return pfa_.fcorr[nang][nladder][nview];

};

/**
 * Returns the index (0, n.bin-1) of the angular bin for pfa parameters
 * @param angle Effective angle (deg)
 */
int TrkParams::GetPFA_AngleBin(float angle){
    
    int nangbin = TrkParams::GetPFA_NbinsAngle();
    int istart = (int)(nangbin/2);
    int idbin = -1;
//    cout << angle <<" ??" << endl;
    if( angle > pfa_.angR[istart] ){
	idbin = nangbin-1;
	for(int id=istart+1; id<nangbin; id++ ){
//	    cout << id << endl;
	    if( pfa_.angR[id] >= angle ){
		idbin = id;
		break;
	    }
	}
    }else{
	idbin = 0;
	for(int id=istart; id>=0; id-- ){
//	    cout << id << endl;
	    if( pfa_.angL[id] < angle ){
		idbin = id;
		break;
	    }
	}

    }
//    cout << ">>> "<<idbin<<" "<<pfa_.angL[idbin]<<" "<<pfa_.angR[idbin]<<endl;
    return idbin;
}



ClassImp(TrkParams);
