/* $Id: sinfo_rec_wavecal.c,v 1.31 2012-09-17 09:06:39 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: 2012-09-17 09:06:39 $
 * $Revision: 1.31 $
 * $Name: not supported by cvs2svn $
 */

/****************************************************************
 *          Wave_Cal Frames Data Reduction                          *
 ****************************************************************/

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

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

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


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

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

/* sinfoni */
#include <sinfo_pro_types.h>
#include <sinfo_general_config.h>
#include <sinfo_utilities.h>
#include <sinfo_product_config.h>
#include <sinfo_prepare_stacked_frames_config.h>
#include <sinfo_wavecal_config.h>
#include <sinfo_raw_types.h>
#include <sinfo_tpl_utils.h>
#include <sinfo_tpl_dfs.h>
#include <sinfo_hidden.h>
#include <sinfo_globals.h>
#include <sinfo_functions.h>
#include <sinfo_msg.h>
#include <sinfo_new_prepare_stacked_frames.h>
#include <sinfo_new_wave_cal_slit2.h>
#include <sinfo_error.h>
#include <sinfo_utils_wrappers.h>

#include <sinfo_key_names.h>

/*-----------------------------------------------------------------------------
                            Functions prototypes
 -----------------------------------------------------------------------------*/
static int sinfo_rec_wavecal_create(cpl_plugin *);
static int sinfo_rec_wavecal_exec(cpl_plugin *);
static int sinfo_rec_wavecal_destroy(cpl_plugin *);
static int sinfo_rec_wavecal(cpl_parameterlist *, cpl_frameset *);

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

static char sinfo_rec_wavecal_description1[] =
                "This recipe performs wavelength calibration.\n"
                "The input files are on/off arc lamp frames with tag WAVE_LAMP\n"
                "Master calibration frame input is:\n"
                "A corresponding (band) reference line table with tag REF_LINE_ARC\n"
                "A corresponding (band) distortion table with tag DISTORTION\n"
                "A corresponding (band,preoptic) master flat with tag MASTER_FLAT_LAMP\n"
                "A corresponding (band,preoptics) master bad "
                "pixel map with tag MASTER_BP_MAP\n";


static char sinfo_rec_wavecal_description2[] =
                "If wcal-estimate_ind=TRUE, a corresponding (band,preoptics) slitlet position\n"
                "guess table SLIT_POS_GUESS (for example a copy of the SLIT_POS product)\n"
                "If wcal-calib_indicator=FALSE, a corresponding (band,preoptics) parabolic \n"
                "fit coefficients table WAVE_COEF_SLIT\n"
                "If sinfoni.wavecal.slitpos_boostrap_switch=FALSE \n"
                "(wcal-calib-slitpos_bootstrap=0),\n"
                "a corresponding (band,preoptics) slitlets position table with tag SLIT_POS\n";



static char sinfo_rec_wavecal_description3[] =
                "The main products are:\n"
                "The master flat field corrected for distortions \n"
                "(PRO.CATG=MFLAT_STACKED_DIST)\n"
                "The arc lamp frames stacked (PRO.CATG=WAVE_LAMP_STACKED)\n"
                "The wavelength map (PRO.CATG=WAVE_MAP)\n"
                "The slitlet position table (PRO.CATG=SLIT_POS)\n"
                "A parabolic fit coefficients table (PRO.CATG=WAVE_COEF_SLIT)\n"
                "Parameters relative to arc lamp line fit: (PRO.CATG=WAVE_FIT_PARAMS)\n"
                "\n";


static char sinfo_rec_wavecal_description[1500];

/*-----------------------------------------------------------------------------
                                Functions code
 ----------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/**
 * @defgroup sinfo_rec_wavecal   Recipe to reduce arc lamp data
 */
/*---------------------------------------------------------------------------*/

/**@{*/
/*---------------------------------------------------------------------------*/
/**
  @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_wavecal_description,sinfo_rec_wavecal_description1);
    strcat(sinfo_rec_wavecal_description,sinfo_rec_wavecal_description2);
    strcat(sinfo_rec_wavecal_description,sinfo_rec_wavecal_description3);

    cpl_plugin_init(plugin,
                    CPL_PLUGIN_API,
                    SINFONI_BINARY_VERSION,
                    CPL_PLUGIN_TYPE_RECIPE,
                    "sinfo_rec_wavecal",
                    "Wavelength calibration and slitpos determination",
                    sinfo_rec_wavecal_description,
                    "Andrea Modigliani",
                    "Andrea.Modigliani@eso.org",
                    sinfo_get_license(),
                    sinfo_rec_wavecal_create,
                    sinfo_rec_wavecal_exec,
                    sinfo_rec_wavecal_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_wavecal_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.
     */

    /* Wavelength calibration  */
    sinfo_general_config_add(recipe->parameters);
    sinfo_product_config_add(recipe->parameters);
    sinfo_prepare_stacked_frames_config_add(recipe->parameters);
    sinfo_wavecal_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_wavecal_exec(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 ;

    return sinfo_rec_wavecal(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_wavecal_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_wavecal(cpl_parameterlist *config, cpl_frameset *set)
{

    int sw=0;
    fake* fk=NULL;
    cpl_parameter* p=NULL;
    cpl_frameset* wrk_set=NULL;
    cpl_frame* frame=NULL;
    int ind_index=0;
    cpl_frameset* ref_set=NULL;
    int pdensity=0;
    int line_cor=0;

    fk=sinfo_fake_new();

    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));


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

    /* hidden parameters */
    check_nomsg(p=cpl_parameterlist_find(config,
                    "sinfoni.wavecal.slitpos_boostrap"));
    check_nomsg(sw=cpl_parameter_get_bool(p));
    if( sw == 1 ) {
        check_nomsg(wrk_set=cpl_frameset_duplicate(set));

        check_nomsg(p=cpl_parameterlist_find(config,"sinfoni.stacked.ind_index"));
        check_nomsg(ind_index=cpl_parameter_get_bool(p));
        check_nomsg(cpl_parameter_set_bool(p,TRUE));

        sinfo_msg("---------------------------------------");
        sinfo_msg("%s FRAME DETERMINATION", PRO_WAVE_LAMP_STACKED);
        sinfo_msg("---------------------------------------");
        ck0(sinfo_new_prepare_stacked_frames(cpl_func,config, wrk_set, NULL,
                        PRO_WAVE_LAMP_STACKED,0,fk),
            "FAILED STACKING FRAME %s",PRO_WAVE_LAMP_STACKED);

        sinfo_msg("%s FRAME DETERMINATION SUCCESS", PRO_WAVE_LAMP_STACKED);

        ck0(sinfo_new_wave_cal_slit2(cpl_func,config, wrk_set,ref_set),
            "FIRST PART OF WAVELENGTH CALIBRATION FAILED") ;
        sinfo_msg("FIRST PART OF WAVELENGTH CALIBRATION") ;

        check_nomsg(frame = cpl_frameset_find(wrk_set,PRO_SLIT_POS_GUESS));
        check_nomsg(cpl_frameset_insert(set,cpl_frame_duplicate(frame)));
        check_nomsg(p=cpl_parameterlist_find(config,"sinfoni.stacked.ind_index"));
        if(ind_index == 1) {
            check_nomsg(cpl_parameter_set_bool(p,TRUE));
            check_nomsg(p=cpl_parameterlist_find(config,
                            "sinfoni.wavecal.slitpos_boostrap"));
            check_nomsg(cpl_parameter_set_bool(p,TRUE));
            sinfo_msg("Set ind_index to TRUE");
        } else {
            check_nomsg(cpl_parameter_set_bool(p,FALSE));
            check_nomsg(p=cpl_parameterlist_find(config,
                            "sinfoni.wavecal.slitpos_boostrap"));
            check_nomsg(cpl_parameter_set_bool(p,FALSE));
            sinfo_msg("Set ind_index to FALSE");
        }
        sinfo_free_frameset(&wrk_set);
    }


    sinfo_msg("---------------------------------------------");
    sinfo_msg("%s FRAME DETERMINATION", PRO_WAVE_LAMP_STACKED);
    sinfo_msg("---------------------------------------------");

    /*
     *  Modified code begins here...
     */
    {
        int nsky, ndark, nwave;






        nsky = cpl_frameset_count_tags (set, RAW_SKY_NODDING);
        nwave = cpl_frameset_count_tags (set, RAW_WAVE_LAMP);
        ndark = cpl_frameset_count_tags (set, PRO_MASTER_DARK);

        if ( (nwave == 0) & (nsky>0) ) {
            sinfo_msg ("No arc lamp frames found, using sky frames instead");
            if (ndark == 0)
                sinfo_msg ("Including Master dark is recommended when running wavecal on sky frames");

            int i = 0;
            int non=0;
            while (i < cpl_frameset_get_size(set)) {
                cpl_frame* fr = cpl_frameset_get_frame(set,i);
                const char* tag = cpl_frame_get_tag (fr);

                if (strcmp(tag, RAW_SKY_NODDING)==0)
                {
                    cpl_frame * frnew = 0;
                    char name[32];
                    const char* fname = cpl_frame_get_filename(fr);
                    sprintf (&name[0], "fakelamp_%d.fits", non++);
                    cpl_image* im = cpl_image_load(fname, CPL_TYPE_FLOAT, 0, 0);
                    cpl_propertylist* plist = cpl_propertylist_load(fname,0);

                    /* Both if these needs to be changed to make sure the sky frame is
				   interprated as ON-frame in sinfo_dfs.c

				   The selection of KEY_NAME_LAMP_XE is arbitrary, but one of
				   KEY_NAME_LAMP_* has to be set */
                    cpl_propertylist_set_bool (plist, KEY_NAME_LAMP_XE, 1);
                    cpl_propertylist_set_string (plist, KEY_NAME_DPR_TYPE, "WAVE,LAMP");

                    cpl_image_save (im, name, CPL_BPP_IEEE_FLOAT, plist, CPL_IO_DEFAULT);
                    cpl_image_delete (im);
                    cpl_propertylist_delete(plist);

                    /* Looks like it's not possible to modify the frame directly
				   without duplicating it first. */
                    frnew = cpl_frame_duplicate (fr);
                    cpl_frame_set_filename(frnew, name);
                    cpl_frame_set_tag (frnew, RAW_WAVE_LAMP);
                    cpl_frameset_erase_frame (set, fr);
                    cpl_frameset_insert (set, frnew);
                }
                else
                    i++;
            }
        }

        /*
         * Modified code ends here
         */
    }
    ck0(sinfo_new_prepare_stacked_frames(cpl_func,config, set, NULL,
                    PRO_WAVE_LAMP_STACKED,0,fk),
        "%s FRAME DETERMINATION FAILED",PRO_WAVE_LAMP_STACKED);
    sinfo_msg("%s FRAME DETERMINATION SUCCESS", PRO_WAVE_LAMP_STACKED);

    sinfo_msg("---------------------------------------------");
    sinfo_msg("WAVELENGTH CALIBRATION");
    sinfo_msg("---------------------------------------------");


    ck0(sinfo_new_wave_cal_slit2(cpl_func,config, set,ref_set),
        "FAILED WAVELENGTH CALIBRATION");
    sinfo_msg("SUCCESS WAVELENGTH CALIBRATION");

    sinfo_fake_delete(&fk);
    if(pdensity < 2) {
        check_nomsg(cpl_frameset_erase(set,PRO_STACK_MFLAT_DIST));
        check_nomsg(cpl_frameset_erase(set,PRO_WAVE_LAMP_STACKED));
    }

    cleanup:

    sinfo_free_frameset(&ref_set);
    sinfo_free_frameset(&wrk_set);
    sinfo_fake_delete(&fk);


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

}
/**@}*/
