#include "DetectorEffiCorrectionRPMT.hh"
//////////////////////////////////////////////////////////
DetectorEffiCorrectionRPMT::DetectorEffiCorrectionRPMT(){
    formula=NULL;
    _MessageTag="DetectorEffiCorrectionRPMT::";
}
//////////////////////////////////////////////////////////
DetectorEffiCorrectionRPMT::DetectorEffiCorrectionRPMT(ElementContainerMatrix *ecm){
    formula=NULL;
    _MessageTag="DetectorEffiCorrectionRPMT::";
    SetTarget( ecm );
}
//////////////////////////////////////////////////////////
DetectorEffiCorrectionRPMT::~DetectorEffiCorrectionRPMT(){
}

//////////////////////////////////////////////////////////
bool DetectorEffiCorrectionRPMT::SetParamsFormula1( Double alpha, Double beta ){
    _params.clear();
    _params.push_back( alpha );
    _params.push_back( beta );
    formula = Formula1;
    return true;
}

//////////////////////////////////////////////////////////
bool DetectorEffiCorrectionRPMT::Formula1(ElementContainerMatrix* ecm, std::vector<Double> params ){
    if (ecm->PutPointer(0)->PutPointer(0)->CheckKey("Lamb")==0){
        return false;
    }
    if (params.size()!=2){
        return false;
    }

    for (UInt4 i=0; i<(ecm->PutSize()); i++){
        for (UInt4 j=0; j<(ecm->PutPointer(i)->PutSize()); j++){
            ElementContainer *ec = ecm->PutPointer(i)->PutPointer(j);

            std::string xkey = ec->PutXKey();
            std::string ykey = ec->PutYKey();
            std::string ekey = ec->PutEKey();

            std::vector<Double> *yy = ec->PutP(ykey);
            std::vector<Double> *ee = ec->PutP(ekey);
            std::vector<Double> *lam = ec->PutP("Lamb");

            Double lam_boundary = -1.0/params[0]*log(params[1]/(params[0]+params[1]));
            for (UInt4 k=0; k<(yy->size()); k++){
                Double nlam = 0.0;
                if ( (*lam)[k]<lam_boundary )
                    nlam = (1-exp(-1.0*params[0]*(*lam)[k]))*exp(-1.0*params[1]*(*lam)[k]);
                else
                    nlam = (1-exp(-1.0*params[0]*lam_boundary))*exp(-1.0*params[1]*lam_boundary);

                (*yy)[k] = (*yy)[k]/nlam;
                (*ee)[k] = (*ee)[k]/nlam;
            }
        }
    }
    return true;
}

//////////////////////////////////////////////////////////
bool DetectorEffiCorrectionRPMT::Execute(){
    ElementContainerMatrix* ecm = Put();
    if ( (ecm==NULL) || (formula==NULL) || (_params.empty()) ){
        return false;
    }

    return formula( ecm, _params );
}


