/*
 * This file is part of the FORS Library
 * 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 "fors_preprocess.h"
#include "fiera_config.h"
#include "fors_detmodel.h"
#include "fors_ccd_config.h"
#include "fors_overscan.h"

/**
 * 
 */
fors_image *
fors_image_load_preprocess(const cpl_frame *frame,
                           const cpl_frame *bias_frame)
{
    cpl_errorstate      error_prevstate = cpl_errorstate_get();
    
    /* Load the image */
    fors_image * image_raw = fors_image_load(frame);
    if (!image_raw)
        return NULL;
    /* Read the CCD configuration */
    const char * filename = cpl_frame_get_filename(frame);
    cpl_propertylist * header = cpl_propertylist_load(filename, 0) ;
    fors::fiera_config ccd_config(header);
    if(!cpl_errorstate_is_equal(error_prevstate))
        return NULL;
    /* Update RON estimation from bias */
    cpl_propertylist * master_bias_header =
       cpl_propertylist_load(cpl_frame_get_filename(bias_frame), 0);
    fors::update_ccd_ron(ccd_config, master_bias_header);
    cpl_propertylist_delete(master_bias_header);
    if(!cpl_errorstate_is_equal(error_prevstate))
        return NULL;
    /* Create variances map */
    fors_image_variance_from_detmodel(image_raw, ccd_config);
    if(!cpl_errorstate_is_equal(error_prevstate))
        return NULL;

    /* Subtract overscan */
    fors_image * image_preproc = fors_subtract_prescan(image_raw, ccd_config);
    if(!cpl_errorstate_is_equal(error_prevstate))
        return NULL;

    /* Trimm pre/overscan */
    fors_trimm_preoverscan(image_preproc, ccd_config);
    fors_image_delete(&image_raw);
    if(!cpl_errorstate_is_equal(error_prevstate))
        return NULL;

    return image_preproc;
}


/**@}*/
