/*
 * 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 <stdexcept>
#include "cpl.h"
#include "fors_grism.h"

std::auto_ptr<mosca::grism_config> fors_grism_config_from_frame
(cpl_frame * grism_frame, double wave_ref)
{
    std::auto_ptr<mosca::grism_config> grism_cfg;
    
    cpl_table * table = 
            cpl_table_load(cpl_frame_get_filename(grism_frame), 1, 1);
    
    
    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");

    double nominal_dispersion = 
            cpl_table_get_double(table,  "dispersion", 0, NULL);
    double startwavelength = 
            cpl_table_get_double(table,  "startwavelength", 0, NULL);
    double endwavelength = 
            cpl_table_get_double(table,  "endwavelength", 0, NULL);

//    cpl_propertylist * header = 
//            cpl_propertylist_load(cpl_frame_get_filename(grism_frame), 1);
//    cpl_propertylist_dump(header, stdout);
    
//    if(!cpl_propertylist_has(header, "ESO INS GRIS1 WLEN"))
//        throw std::invalid_argument("Missing keyword ESO INS GRIS1 WLEN "
//                                    "in grism confguration");

//    double wave_ref = cpl_propertylist_get_double(header, "ESO INS GRIS1 WLEN");

//    if (wave_ref < 3000.0)   /* Perhaps in nanometers... */
//        wave_ref *= 10;

    grism_cfg.reset
     (new mosca::grism_config(nominal_dispersion,
                              startwavelength, endwavelength, wave_ref));
    
    cpl_table_delete(table);
    //cpl_propertylist_delete(header);
    
    return grism_cfg;
}
