/* $Id: sinfo_rec_jitter.c,v 1.35 2013-10-14 14:40:00 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: 2013-10-14 14:40:00 $
 * $Revision: 1.35 $
 * $Name: not supported by cvs2svn $
 */

/****************************************************************
 *           Object 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>
#include <math.h>
#include <libgen.h>


/* cpl */
#include <cpl.h>

/* irplib */
#include <irplib_utils.h>

/* sinfoni */
#include <sinfo_utilities.h>
#include <sinfo_pro_types.h>
#include <sinfo_general_config.h>
#include <sinfo_product_config.h>
#include <sinfo_prepare_stacked_frames_config.h>
#include <sinfo_objnod_config.h>
#include <sinfo_skycor_config.h>
#include <sinfo_psf_config.h>
#include <sinfo_standard_star_config.h>
#include <sinfo_new_prepare_stacked_frames.h>
#include <sinfo_new_cubes_coadd.h>
#include <sinfo_new_stdstar.h>
#include <sinfo_new_psf.h>
#include <sinfo_key_names.h>
#include <sinfo_raw_types.h>
#include <sinfo_functions.h>
#include <sinfo_tpl_utils.h>
#include <sinfo_tpl_dfs.h>
#include <sinfo_hidden.h>
#include <sinfo_globals.h>
#include <sinfo_msg.h>
#include <sinfo_rec_utils.h>
#include <sinfo_error.h>
#include <sinfo_utils_wrappers.h>

/*-----------------------------------------------------------------------------
                            Functions prototypes
 ----------------------------------------------------------------------------*/

static int sinfo_rec_jitter_create(cpl_plugin *) ;
static int sinfo_rec_jitter_exec(cpl_plugin *) ;
static int sinfo_rec_jitter_destroy(cpl_plugin *) ;
static int sinfo_rec_jitter(cpl_parameterlist *config, cpl_frameset *set);
/*-----------------------------------------------------------------------------
                            Static variables
 ----------------------------------------------------------------------------*/

static char sinfo_rec_jitter_description1[] =
                "This recipe performs science data reduction.\n"
                "The input files are:\n"
                "science object and sky frames with tags OBJECT_NODDING and SKY_NODDING or\n"
                "Telluric standard star frames and sky frames with tags STD and SKY_STD or\n"
                "PSF standard star and sky frames with tags \n"
                "PSF_CALIBRATOR and SKY_PSF_CALIBRATOR\n"
                "and Master calibration frames:\n";


static char sinfo_rec_jitter_description2[] =
                "A corresponding (band,preoptics) wavelength map image with tag WAVE_MAP\n"
                "A corresponding (band,preoptics) master flat field with tag MASTER_FLAT_LAMP\n"
                "A corresponding (band,preoptics) master bad pixel map with tag MASTER_BP_MAP\n"
                "A corresponding (band,preoptics) slitlets position frame with tag SLIT_POS\n"
                "A corresponding (band) distortion table with tag DISTORTION\n"
                "A corresponding (band) slitlet distance table with tag SLITLETS_DISTANCE\n";


static char sinfo_rec_jitter_description3[] =
                "The output is an image resulting from the IMA1 op IMA2 where op indicates\n"
                "A reference table with the position of the first "
                "column with tag FIRST_COLUMN\n"
                "Relevant outputs are:\n"
                "combined cubes (PRO.CATG=x_OBS x=STD,OBJ,PSF)\n"
                "reconstructed cube (PRO.CATG=COADD_x_OBS x=STD,OBJ,PSF)\n"
                "An average along Z of the reconstructed cube \n"
                "(PRO.CATG=MED_x_OBS x=STD,OBJ,PSF)\n"
                "The bad pixel map associated to the cube \n"
                "(PRO.CATG=BP_MAP_COADD_x_OBS x=STD,OBJ,PSF)\n"
                "\n";

static char sinfo_rec_jitter_description[1400];

/*-----------------------------------------------------------------------------
                                Functions code
 ----------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/**
 * @defgroup sinfo_rec_jitter Recipe to reduce science, PSF, telluric standards
 */
/*---------------------------------------------------------------------------*/
/**@{*/
/*---------------------------------------------------------------------------*/
/**
  @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;

    strcpy(sinfo_rec_jitter_description,sinfo_rec_jitter_description1);
    strcat(sinfo_rec_jitter_description,sinfo_rec_jitter_description2);
    strcat(sinfo_rec_jitter_description,sinfo_rec_jitter_description3);

    cpl_plugin_init(plugin,
                    CPL_PLUGIN_API,
                    SINFONI_BINARY_VERSION,
                    CPL_PLUGIN_TYPE_RECIPE,
                    "sinfo_rec_jitter",
                    "Object or STD star or PSF star data reduction",
                    sinfo_rec_jitter_description,
                    "Andrea Modigliani",
                    "Andrea.Mdigliani@eso.org",
                    sinfo_get_license(),
                    sinfo_rec_jitter_create,
                    sinfo_rec_jitter_exec,
                    sinfo_rec_jitter_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_jitter_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 ;
    cpl_error_reset();
    irplib_reset();

    /* 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_prepare_stacked_frames_config_add(recipe->parameters);
    sinfo_objnod_config_add(recipe->parameters);
    sinfo_skycor_config_add(recipe->parameters);
    sinfo_standard_star_config_add(recipe->parameters);
    sinfo_psf_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_jitter_exec(cpl_plugin *plugin)
{

    cpl_recipe *recipe = (cpl_recipe *) plugin;

    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 ;

    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_jitter(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_jitter_destroy(cpl_plugin *plugin)
{

    cpl_recipe  *   recipe ;

    /* 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_jitter(cpl_parameterlist *config, cpl_frameset *set)
{
    const char* pro_ctg_cube;
    cpl_parameter* p=NULL;
    int psf_sw=0;
    int std_sw=0;
    cpl_frameset* ref_set=NULL;
    int line_cor=0;

    sinfo_msg("Welcome to SINFONI Pipeline release %d.%d.%d",
              SINFONI_MAJOR_VERSION,SINFONI_MINOR_VERSION,SINFONI_MICRO_VERSION);

    if(sinfo_dfs_set_groups(set)) {
        sinfo_msg_error("Cannot indentify RAW and CALIB frames") ;
        return -1;
    }

    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));
    /* ===============================================================
     Defines several framesets each with a pair obj-sky,
     stack each pair, put the results in set
     =============================================================== */
    ck0(sinfo_cub_stk_frames(config,&set,cpl_func,&pro_ctg_cube),
        "Cannot stack RAW frames") ;

    /* ===============================================================
     SCI OBJNOD
     =============================================================== */
    sinfo_msg("------------------------------") ;
    sinfo_msg("COADDING CUBES");
    sinfo_msg("------------------------------") ;
    ck0(sinfo_new_cubes_coadd(cpl_func,config, set, pro_ctg_cube),
        "COADDING CUBES") ;

    sinfo_msg("------------------------------") ;
    sinfo_msg("COADDED CUBES");
    sinfo_msg("------------------------------") ;

    /* ===============================================================
     PSF
     =============================================================== */

    if((strcmp(pro_ctg_cube,PRO_COADD_PSF) == 0) ||
                    (strcmp(pro_ctg_cube,PRO_COADD_STD) == 0) ||
                    (strcmp(pro_ctg_cube,PRO_COADD_PUPIL) == 0) ) {


        p = cpl_parameterlist_find(config, "sinfoni.psf.switch");
        psf_sw = cpl_parameter_get_bool(p);
        sinfo_msg("switch=%d",psf_sw);
        if(psf_sw) {
            sinfo_msg("------------------------------") ;
            sinfo_msg("REDUCE PSF STD STAR FRAMES");
            sinfo_msg("------------------------------") ;
            if ( -1 == sinfo_new_psf(cpl_func,config,set,set) ) {
                sinfo_msg_error("REDUCING PSF STD STAR FRAMES") ;
                cpl_error_reset();
            } else {
                sinfo_msg("SUCCESS REDUCE PSF STD STAR FRAMES") ;
            }
        }

        p = cpl_parameterlist_find(config, "sinfoni.std_star.switch");
        std_sw = cpl_parameter_get_bool(p);
        sinfo_msg("switch=%d",std_sw);
        if(std_sw) {
            sinfo_msg("------------------------------") ;
            sinfo_msg("STD STAR DATA REDUCTION");
            sinfo_msg("------------------------------") ;
            if ( -1 == sinfo_new_stdstar(cpl_func,config, set,set ) ) {
                sinfo_msg_error("REDUCING STD STAR DATA") ;
                cpl_error_reset();
            } else {
                sinfo_msg("STD STAR DATA REDUCTION SUCCESS") ;
            }
        }
    }

    cleanup:
    sinfo_free_frameset(&ref_set);
    if (cpl_error_get_code() != CPL_ERROR_NONE) {
        sinfo_check_rec_status(0);
        return -1;
    } else {
        return 0;
    }


}

/**@}*/
