/*
 * This file is part of the FORS Data Reduction Pipeline
 * Copyright (C) 2002-2010 European Southern Observatory
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <cmath>
#include <stdexcept>
#include "cpl.h"
#include "fors_grism.h"


std::unique_ptr<mosca::grism_config> fors_grism_config_from_frame
(cpl_frame * grism_frame, const double wave_ref,
        const double start_wave, const double stop_wave)
{
    cpl_table * table = 
            cpl_table_load(cpl_frame_get_filename(grism_frame), 1, 1);
    
    std::unique_ptr<mosca::grism_config> grism_cfg =
            fors_grism_config_from_table(table, wave_ref,
                    start_wave, stop_wave);
    
    cpl_table_delete(table);
    
    return grism_cfg;
}


std::unique_ptr<mosca::grism_config> fors_grism_config_from_table
(const cpl_table * table, const double wave_ref,
        const double start_wave, const double stop_wave){

    std::unique_ptr<mosca::grism_config> grism_cfg;

    if (!cpl_table_has_column(table, "dispersion") ||
            !cpl_table_has_column(table, "startwavelength") ||
            !cpl_table_has_column(table, "endwavelength") )
             throw std::invalid_argument("Table doesn't not contain "
                     "a grism configuration");


        if (cpl_table_get_column_type(table, "dispersion") != CPL_TYPE_DOUBLE ||
            cpl_table_get_column_type(table, "startwavelength") != CPL_TYPE_DOUBLE ||
            cpl_table_get_column_type(table, "endwavelength") != CPL_TYPE_DOUBLE)
            throw std::invalid_argument("Unexpected type for GRISM_TABLE. "
                    "Expected double");

        const double nominal_dispersion =
                cpl_table_get_double(table,  "dispersion", 0, NULL);
        const double startwavelength = std::isnan(start_wave) ?
                cpl_table_get_double(table,  "startwavelength", 0, NULL) : start_wave;
        const double endwavelength = std::isnan(stop_wave) ?
                cpl_table_get_double(table,  "endwavelength", 0, NULL) : stop_wave;

        grism_cfg.reset
         (new mosca::grism_config(nominal_dispersion,
                                  startwavelength, endwavelength, wave_ref));

        return grism_cfg;
}
