/* $Id: sinfo_rec_mflat.c,v 1.22 2008-02-05 08:13:05 amodigli Exp $
 *
 * This file is part of the SINFONI Pipeline
 * Copyright (C) 2002,2003 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
/*
 * $Author: amodigli $
 * $Date: 2008-02-05 08:13:05 $
 * $Revision: 1.22 $
 * $Name: not supported by cvs2svn $
 */

/****************************************************************
 *          Rec_Lampflats Frames Data Reduction                          *
 ****************************************************************/

#ifdef HAVE_CONFIG_H
#include <config.h>          /* allows the program compilation */
#endif

/*-----------------------------------------------------------------------------
                                Includes
 ----------------------------------------------------------------------------*/

/* std */
#include <strings.h>
#include <string.h>
#include <stdio.h>

/* cpl */
#include <cpl.h>    
#include <irplib_utils.h>
/* sinfoni */
#include <sinfo_pro_types.h>
#include <sinfo_utilities.h>
#include <sinfo_general_config.h>
#include <sinfo_product_config.h>
#include <sinfo_bp_config.h>
#include <sinfo_bp_norm_config.h>
#include <sinfo_lamp_flats_config.h>
#include <sinfo_bp_norm.h>
#include <sinfo_new_lamp_flats.h>
#include <sinfo_functions.h>
#include <sinfo_new_add_bp_map.h>
#include <sinfo_tpl_utils.h>
#include <sinfo_tpl_dfs.h>
#include <sinfo_msg.h>
#include <sinfo_error.h>
#include <sinfo_utils_wrappers.h>

/*-----------------------------------------------------------------------------
                            Functions prototypes
 ----------------------------------------------------------------------------*/
static int sinfo_rec_mflat_create(cpl_plugin *);
static int sinfo_rec_mflat_exec(cpl_plugin *);
static int sinfo_rec_mflat_destroy(cpl_plugin *);
static int sinfo_rec_mflat(cpl_parameterlist *, cpl_frameset *);


/*-----------------------------------------------------------------------------
                            Static variables
 ----------------------------------------------------------------------------*/

static char
sinfo_rec_mflat_description[] =
                "This recipe reduce normal raw flat fields.\n"
                "The input files are a set of flat fields with tag FLAT_LAMP\n"
                "optionally one may have in input also several bad pixel maps to be coadded.\n"
                "The main products are a master flat field (PRO.CATG=MASTER_FLAT_LAMP) image\n"
                "a bad pixel map (PRO.CATG=BP_MAP_NO), "
                "a master bad pixel map (PRO.CATG=MASTER_BP_MAP) resulting by the coaddition\n"
                "of all bad pixel maps.\n"
                "\n";



/*-----------------------------------------------------------------------------
                                Functions code
 ----------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/**
 * @defgroup sinfo_rec_mflat   Recipe to compute master flat
 */
/*---------------------------------------------------------------------------*/
/**@{*/
/*---------------------------------------------------------------------------*/
/**
  @brief    Build the list of available plugins, for this module. 
  @param    list    the plugin list
  @return   0 if everything is ok, -1 otherwise

  Create the recipe instance and make it available to the application using the 
  interface. This function is exported.
 */
/*---------------------------------------------------------------------------*/

int cpl_plugin_get_info(cpl_pluginlist *list)
{

    cpl_recipe *recipe = cpl_calloc(1, sizeof *recipe);
    cpl_plugin *plugin = &recipe->interface;


    cpl_plugin_init(plugin,
                    CPL_PLUGIN_API,
                    SINFONI_BINARY_VERSION,
                    CPL_PLUGIN_TYPE_RECIPE,
                    "sinfo_rec_mflat",
                    "Master flat determination",
                    sinfo_rec_mflat_description,
                    "Andrea Modigliani",
                    "Andrea.Modigliani@eso.org",
                    sinfo_get_license(),
                    sinfo_rec_mflat_create,
                    sinfo_rec_mflat_exec,
                    sinfo_rec_mflat_destroy);

    cpl_pluginlist_append(list, plugin);

    return 0;

}


/*---------------------------------------------------------------------------*/
/**
  @brief    Setup the recipe options    
  @param    plugin  the plugin
  @return   0 if everything is ok

  Defining the command-line/configuration parameters for the recipe.
 */
/*---------------------------------------------------------------------------*/

static int sinfo_rec_mflat_create(cpl_plugin *plugin)
{

    cpl_recipe      * recipe ;

    /* Check that the plugin is part of a valid recipe */
    if (cpl_plugin_get_type(plugin) == CPL_PLUGIN_TYPE_RECIPE) 
        recipe = (cpl_recipe *)plugin ;
    else return -1 ;

    /* Create the parameters list in the cpl_recipe object */
    recipe->parameters = cpl_parameterlist_new() ; 

    /*
     * Fill the parameter list.
     */
    sinfo_general_config_add(recipe->parameters);
    sinfo_product_config_add(recipe->parameters);
    sinfo_bp_norm_config_add(recipe->parameters);
    sinfo_lamp_flats_config_add(recipe->parameters);

    return 0;

}
/*---------------------------------------------------------------------------*/
/**
  @brief    Execute the plugin instance given by the interface
  @param    plugin  the plugin
  @return   0 if everything is ok
 */
/*---------------------------------------------------------------------------*/
static int sinfo_rec_mflat_exec(cpl_plugin *plugin)
{
    cpl_recipe  *   recipe ;
    cpl_errorstate initial_errorstate = cpl_errorstate_get();
    /* Get the recipe out of the plugin */
    if (cpl_plugin_get_type(plugin) == CPL_PLUGIN_TYPE_RECIPE) 
        recipe = (cpl_recipe *)plugin ;
    else return -1 ;
    cpl_error_reset();
    irplib_reset();

    if (!cpl_errorstate_is_equal(initial_errorstate)) {                      
        /* Dump the error history since recipe execution start.                
           At this point the recipe cannot recover from the error */           
        cpl_errorstate_dump(initial_errorstate, CPL_FALSE, NULL);              
    } 
    return sinfo_rec_mflat(recipe->parameters, recipe->frames);

}
/*---------------------------------------------------------------------------*/
/**
  @brief    Destroy what has been created by the 'create' function
  @param    plugin  the plugin
  @return   0 if everything is ok
 */
/*---------------------------------------------------------------------------*/
static int sinfo_rec_mflat_destroy(cpl_plugin *plugin)
{

    cpl_recipe *recipe = (cpl_recipe *) plugin;

    /* Get the recipe out of the plugin */
    if (cpl_plugin_get_type(plugin) == CPL_PLUGIN_TYPE_RECIPE)
        recipe = (cpl_recipe *)plugin ;
    else return -1 ;

    cpl_parameterlist_delete(recipe->parameters);
    return 0;

}

/*---------------------------------------------------------------------------*/
/**
  @brief    Interpret the command line options and execute the data processing
  @param    parlist     the parameters list
  @param    frameset   the frames list
  @return   0 if everything is ok
 */
/*---------------------------------------------------------------------------*/
/*
 * The actual recipe actually start here.
 */


static int
sinfo_rec_mflat(cpl_parameterlist *config, cpl_frameset *set)
{

    cpl_parameter* p;
    cpl_frameset* ref_set=NULL;
    int pdensity=0;
    int line_cor=0;

    check_nomsg(p=cpl_parameterlist_find(config,"sinfoni.product.density"));
    check_nomsg(pdensity=cpl_parameter_get_int(p));

    sinfo_msg("Welcome to SINFONI Pipeline release %d.%d.%d",
              SINFONI_MAJOR_VERSION,SINFONI_MINOR_VERSION,SINFONI_MICRO_VERSION);
    ck0(sinfo_dfs_set_groups(set),"Cannot indentify RAW and CALIB frames") ;

    check_nomsg(p=cpl_parameterlist_find(config, "sinfoni.general.lc_sw"));
    check_nomsg(line_cor=cpl_parameter_get_bool(p));
    if(line_cor==1) {
        check_nomsg(sinfo_ima_line_cor(config,set));
    }



    check_nomsg(ref_set=cpl_frameset_duplicate(set));
    sinfo_bp_config_add(config);
    check_nomsg(p = cpl_parameterlist_find(config,"sinfoni.bp.method"));
    check_nomsg(cpl_parameter_set_string(p,"Normal"));
    /*
       ---------------------------------------------------------
                MASTER_FLAT
       ---------------------------------------------------------
     */

    sinfo_msg("-------------------------------------------");
    sinfo_msg("MASTER FLAT DETERMINATION                  ");
    sinfo_msg("-------------------------------------------");

    ck0(sinfo_new_lamp_flats(cpl_func,config,set,ref_set),
        "MASTER FLAT DETERMINATION FAILED");
    sinfo_msg("MASTER FLAT DETERMINATION SUCCESS") ;

    sinfo_msg("-------------------------------------------");
    sinfo_msg("BP_MAP_NO BAD PIXEL MAP DETERMINATION      ");
    sinfo_msg("-------------------------------------------");
    /*
       ---------------------------------------------------------
                BP_SEARCH
       ---------------------------------------------------------
     */

    check_nomsg(p = cpl_parameterlist_find(config,"sinfoni.bp.method"));
    check_nomsg(cpl_parameter_set_string(p,"Normal"));
    ck0(sinfo_new_bp_search_normal(cpl_func,config,set,ref_set,PRO_BP_MAP_NO),
        "BP_MAP_NO BAD PIXEL MAP DETERMINATION FAILED") ;

    sinfo_msg("------------------------------------------");
    sinfo_msg("MASTER_BP_MAP BAD PIXEL MAP DETERMINATION ");
    sinfo_msg("------------------------------------------");
    ck0(sinfo_new_add_bp_map(cpl_func,config, set,ref_set),
        "MASTER_BP_MAP BAD PIXEL MAP FAILED") ;
    sinfo_msg("MASTER_BP_MAP BAD PIXEL MAP DETERMINATION SUCCESS");


    if(pdensity < 2) {
        check_nomsg(cpl_frameset_erase(set,PRO_BP_MAP_NO));
    }

    cleanup:

    sinfo_free_frameset(&ref_set);

    if (cpl_error_get_code() != CPL_ERROR_NONE) {
        return -1;
    } else {
        return 0;
    }

}

/**@}*/


