#include "SASCalcDetectorEffi.hh"
//////////////////////////////////////////////////////////
SASCalcDetectorEffi::
SASCalcDetectorEffi()
{
}
//////////////////////////////////////////////////////////
SASCalcDetectorEffi::
~SASCalcDetectorEffi()
{
}
//////////////////////////////////////////////////////////
bool SASCalcDetectorEffi::loadData(std::string _filepath)
{
    FILE* file;
    size_t result;
    char tmpBuf[C_SAS_TMP_BUF_SIZE];
    std::printf("Load Start.\n");
    file = fopen(_filepath.c_str(), "rb");
    int i;

    if (NULL==file) {
        std::printf("File is not found.\n");
        return false;
    }

    // Read Header Infomation
    for (i=0;i<11;i++) {
        memset(tmpBuf,'\0',C_SAS_TMP_BUF_SIZE);
        result = fread(tmpBuf, sizeof(char), C_SAS_TMP_BUF_SIZE,file);
        if (result != C_SAS_TMP_BUF_SIZE) {
            std::printf("File contents has an error.\n");
            std::printf("%02d:%s",i,tmpBuf);
        } else {
            std::printf("%02d:%s",i,tmpBuf);
        }
    }

    result = fread(dwLoadBox, sizeof(double), sizeof(dwLoadBox)/sizeof(double), file);
    if (result != sizeof(dwLoadBox)/sizeof(double)) {
        std::printf("File contents has an error.\n");
    }


    fclose(file);
    std::printf("Load End.\n");

    return true;

}
//////////////////////////////////////////////////////////
double SASCalcDetectorEffi::PutApproximateVal(double lambda,double sec)
{
    double dwLambdaPos;
    double dwSecPos;
    double dwLambdaFloor;
    double dwSecFloor;

    double dwA;
    double dwB;

    int nLambdaIdx;
    int nSecIdx;
    double ret;

    dwLambdaPos = (lambda - C_SAS_DW_LAMBDA_MIN) / C_SAS_DW_LAMBDA_GAP;
    dwSecPos = (sec - C_SAS_DW_SEC_MIN) / C_SAS_DW_SEC_GAP;

    dwLambdaFloor = floor(dwLambdaPos);
    dwSecFloor = floor(dwSecPos);

    nLambdaIdx = (int)dwLambdaFloor;
    nSecIdx = (int)dwSecFloor;

    dwA = dwLambdaPos - dwLambdaFloor;
    dwB = dwSecPos - dwSecFloor;

    assert((0 <= dwA) && (dwA <= 1.0f));
    assert((0 <= dwB) && (dwB <= 1.0f));

    ret = (1.0 - dwA) * (1.0 - dwB) * dwLoadBox[nLambdaIdx][nSecIdx]
        + (1.0 - dwA) * dwB * dwLoadBox[nLambdaIdx][nSecIdx + 1]
        + dwA * (1.0 - dwB) * dwLoadBox[nLambdaIdx + 1][nSecIdx]
        + dwA * dwB * dwLoadBox[nLambdaIdx + 1][nSecIdx + 1];

    return ret;
}



