/* $Id: fors_resample.c,v 1.11 2013-08-14 16:11:42 cgarcia Exp $
 *
 * 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
 */

/*
 * $Author: cgarcia $
 * $Date: 2013-08-14 16:11:42 $
 * $Revision: 1.11 $
 * $Name: not supported by cvs2svn $
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <math.h>
#include <cpl.h>
#include <moses.h>
#include <fors_dfs.h>

static int fors_resample_create(cpl_plugin *);
static int fors_resample_exec(cpl_plugin *);
static int fors_resample_destroy(cpl_plugin *);
static int fors_resample(cpl_parameterlist *, cpl_frameset *);

static char fors_resample_description[] =
"This recipe is used to resample at constant wavelength step spatially\n"
"rectified spectra. The input frames are produced using either the recipe\n"
"fors_extract_slits in the case of MOS/MXU multi slit exposures, or the\n"
"recipes fors_remove_bias and fors_flatfield in the case of LSS or long-slit\n"
"like MOS/MXU data. Only in case of LSS or LSS-like data the SLIT_LOCATION\n"
"table is required in input. Please refer to the FORS Pipeline User's Manual\n"
"for more details.\n"
"\n"
"In the table below the MXU acronym can also be read as MOS and LSS, SCI\n"
"can be read as STD, and SCIENCE as STANDARD.\n\n"
"Input files:\n\n"
"  DO category:               Type:       Explanation:         Required:\n"
"  LAMP_UNBIAS_MXU\n"
"  or SCIENCE_UNBIAS_MXU\n"
"  or SCIENCE_UNFLAT_MXU\n"
"  or RECTIFIED_LAMP_MXU\n"
"  or RECTIFIED_ALL_SCI_MXU\n"
"  or RECTIFIED_SCI_MXU\n"
"  or RECTIFIED_SKY_SCI_MXU   Calib       Frame to resample       Y\n"
"  DISP_COEFF_MXU\n"
"  or DISP_COEFF_SCI_MXU      Calib       Dispersion coefficients Y\n"
"  SLIT_LOCATION_MXU          Calib       Slit location table     Y\n"
"  GRISM_TABLE                Calib       Grism table             .\n\n"
"Output files:\n\n"
"  DO category:               Data type:  Explanation:\n"
"  MAPPED_LAMP_MXU\n"
"  or MAPPED_ALL_SCI_MXU\n"
"  or MAPPED_SCI_MXU\n"
"  or MAPPED_SKY_SCI_MXU      FITS image  Resampled spectra\n\n";

#define fors_resample_exit(message)           \
{                                             \
if ((const char *)message != NULL) cpl_msg_error(recipe, message);  \
cpl_image_delete(spectra);                    \
cpl_image_delete(mapped);                     \
cpl_table_delete(grism_table);                \
cpl_table_delete(idscoeff);                   \
cpl_table_delete(slits);                      \
cpl_propertylist_delete(header);              \
cpl_msg_indent_less();                        \
return -1;                                    \
}

#define fors_resample_exit_memcheck(message)    \
{                                               \
if ((const char *)message != NULL) cpl_msg_info(recipe, message);     \
printf("free spectra (%p)\n", spectra);         \
cpl_image_delete(spectra);                      \
printf("free mapped (%p)\n", mapped);           \
cpl_image_delete(mapped);                       \
printf("free grism_table (%p)\n", grism_table); \
cpl_table_delete(grism_table);                  \
printf("free idscoeff (%p)\n", idscoeff);       \
cpl_table_delete(idscoeff);                     \
printf("free slits (%p)\n", slits);             \
cpl_table_delete(slits);                        \
printf("free header (%p)\n", header);           \
cpl_propertylist_delete(header);                \
cpl_msg_indent_less();                          \
return 0;                                       \
}


/**
 * @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,
                    FORS_BINARY_VERSION,
                    CPL_PLUGIN_TYPE_RECIPE,
                    "fors_resample",
                    "Resample input spectra at constant wavelength step",
                    fors_resample_description,
                    "Carlo Izzo",
                    PACKAGE_BUGREPORT,
    "This file is currently part of the FORS Instrument Pipeline\n"
    "Copyright (C) 2002-2010 European Southern Observatory\n\n"
    "This program is free software; you can redistribute it and/or modify\n"
    "it under the terms of the GNU General Public License as published by\n"
    "the Free Software Foundation; either version 2 of the License, or\n"
    "(at your option) any later version.\n\n"
    "This program is distributed in the hope that it will be useful,\n"
    "but WITHOUT ANY WARRANTY; without even the implied warranty of\n"
    "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n"
    "GNU General Public License for more details.\n\n"
    "You should have received a copy of the GNU General Public License\n"
    "along with this program; if not, write to the Free Software Foundation,\n"
    "Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n",
                    fors_resample_create,
                    fors_resample_exec,
                    fors_resample_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 fors_resample_create(cpl_plugin *plugin)
{
    cpl_recipe    *recipe;
    cpl_parameter *p;

    /* 
     * 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 (empty) parameters list in the cpl_recipe object 
     */

    recipe->parameters = cpl_parameterlist_new(); 

    /*
     * Dispersion
     */

    p = cpl_parameter_new_value("fors.fors_resample.dispersion",
                                CPL_TYPE_DOUBLE,
                                "Expected spectral dispersion (Angstrom/pixel)",
                                "fors.fors_resample",
                                0.0);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "dispersion");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Start wavelength for spectral extraction
     */

    p = cpl_parameter_new_value("fors.fors_resample.startwavelength",
                                CPL_TYPE_DOUBLE,
                                "Start wavelength in spectral extraction",
                                "fors.fors_resample",
                                0.0);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "startwavelength");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * End wavelength for spectral extraction
     */

    p = cpl_parameter_new_value("fors.fors_resample.endwavelength",
                                CPL_TYPE_DOUBLE,
                                "End wavelength in spectral extraction",
                                "fors.fors_resample",
                                0.0);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "endwavelength");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Flux conservation
     */
 
    p = cpl_parameter_new_value("fors.fors_resample.flux",
                                CPL_TYPE_BOOL,
                                "Apply flux conservation",
                                "fors.fors_resample",
                                TRUE);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "flux");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    return 0;
}


/**
 * @brief    Execute the plugin instance given by the interface
 *
 * @param    plugin  the plugin
 *
 * @return   0 if everything is ok
 */

static int fors_resample_exec(cpl_plugin *plugin)
{
    cpl_recipe *recipe;
    
    if (cpl_plugin_get_type(plugin) == CPL_PLUGIN_TYPE_RECIPE) 
        recipe = (cpl_recipe *)plugin;
    else 
        return -1;

    return fors_resample(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 fors_resample_destroy(cpl_plugin *plugin)
{
    cpl_recipe *recipe;
    
    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 set-of-frames
 *
 * @return   0 if everything is ok
 */

static int fors_resample(cpl_parameterlist *parlist, 
                               cpl_frameset *frameset)
{

    const char *recipe = "fors_resample";


    /*
     * Input parameters
     */

    double      dispersion;
    double      startwavelength;
    double      endwavelength;
    int         flux;

    /*
     * CPL objects
     */

    cpl_image        *spectra     = NULL;
    cpl_image        *mapped      = NULL;
    cpl_table        *grism_table = NULL;
    cpl_table        *maskslits   = NULL;
    cpl_table        *slits       = NULL;
    cpl_table        *idscoeff    = NULL;
    cpl_propertylist *header      = NULL;

    /*
     * Auxiliary variables
     */

    char        version[80];
    const char *disp_coeff_tag;
    const char *slit_location_tag;
    const char *rectified_tag;
    const char *mapped_tag;
    int         nframes;
    int         rebin;
    double      reference;
    int         treat_as_lss = 0;
    int         mxu, mos, lss;
    int         disp;
    int         dispsci;
    int         dispstd;
    int         sciall;
    int         stdall;
    int         scisky;
    int         stdsky;
    int         sci;
    int         std;
    int         lamp;

    char       *instrume = NULL;


    cpl_msg_set_indentation(2);

    /*
     * Get configuration parameters
     */

    cpl_msg_info(recipe, "Recipe %s configuration parameters:", recipe);
    cpl_msg_indent_more();
    
    if (cpl_frameset_count_tags(frameset, "GRISM_TABLE") > 1)
        fors_resample_exit("Too many in input: GRISM_TABLE"); 

    grism_table = dfs_load_table(frameset, "GRISM_TABLE", 1);

    dispersion = dfs_get_parameter_double(parlist,
                    "fors.fors_resample.dispersion", grism_table);

    if (dispersion <= 0.0)
        fors_resample_exit("Invalid spectral dispersion value");

    startwavelength = dfs_get_parameter_double(parlist,
                    "fors.fors_resample.startwavelength", grism_table);
    if (startwavelength > 1.0)
        if (startwavelength < 3000.0 || startwavelength > 13000.0)
            fors_resample_exit("Invalid wavelength");

    endwavelength = dfs_get_parameter_double(parlist,
                    "fors.fors_resample.endwavelength", grism_table);
    if (endwavelength > 1.0) {
        if (endwavelength < 3000.0 || endwavelength > 13000.0)
            fors_resample_exit("Invalid wavelength");
        if (startwavelength < 1.0)
            fors_resample_exit("Invalid wavelength interval");
    }

    if (startwavelength > 1.0)
        if (endwavelength - startwavelength <= 0.0)
            fors_resample_exit("Invalid wavelength interval");

    flux = dfs_get_parameter_bool(parlist, "fors.fors_resample.flux", NULL);

    cpl_table_delete(grism_table); grism_table = NULL;

    if (cpl_error_get_code())
        fors_resample_exit("Failure reading the configuration parameters");


    cpl_msg_indent_less();
    cpl_msg_info(recipe, "Check input set-of-frames:");
    cpl_msg_indent_more();

    mxu  = cpl_frameset_count_tags(frameset, "DISP_COEFF_MXU");
    mxu += cpl_frameset_count_tags(frameset, "DISP_COEFF_SCI_MXU");
    mxu += cpl_frameset_count_tags(frameset, "DISP_COEFF_STD_MXU");
    mos  = cpl_frameset_count_tags(frameset, "DISP_COEFF_MOS");
    mos += cpl_frameset_count_tags(frameset, "DISP_COEFF_SCI_MOS");
    mos += cpl_frameset_count_tags(frameset, "DISP_COEFF_STD_MOS");
    lss  = cpl_frameset_count_tags(frameset, "DISP_COEFF_LSS");
    lss += cpl_frameset_count_tags(frameset, "DISP_COEFF_SCI_LSS");
    lss += cpl_frameset_count_tags(frameset, "DISP_COEFF_STD_LSS");

    nframes = mos + mxu + lss;

    if (nframes == 0) {
        fors_resample_exit("Missing dispersion coefficients table");
    }
    if (nframes > 1) {
        cpl_msg_error(recipe, 
                      "Too many input dispersion coefficients tables (%d > 1)",
                      nframes);
        fors_resample_exit(NULL);
    }

    disp     = cpl_frameset_count_tags(frameset, "DISP_COEFF_MXU");
    disp    += cpl_frameset_count_tags(frameset, "DISP_COEFF_MOS");
    disp    += cpl_frameset_count_tags(frameset, "DISP_COEFF_LSS");
    dispsci  = cpl_frameset_count_tags(frameset, "DISP_COEFF_SCI_MXU");
    dispsci += cpl_frameset_count_tags(frameset, "DISP_COEFF_SCI_MOS");
    dispsci += cpl_frameset_count_tags(frameset, "DISP_COEFF_SCI_LSS");
    dispstd  = cpl_frameset_count_tags(frameset, "DISP_COEFF_STD_MXU");
    dispstd += cpl_frameset_count_tags(frameset, "DISP_COEFF_STD_MOS");
    dispstd += cpl_frameset_count_tags(frameset, "DISP_COEFF_STD_LSS");

    if (mxu) {
        slit_location_tag = "SLIT_LOCATION_MXU";
        if (disp)
            disp_coeff_tag = "DISP_COEFF_MXU";
        else if (dispsci)
            disp_coeff_tag = "DISP_COEFF_SCI_MXU";
        else
            disp_coeff_tag = "DISP_COEFF_STD_MXU";
    }
    else if (mos) {
        slit_location_tag = "SLIT_LOCATION_MOS";
        if (disp)
            disp_coeff_tag = "DISP_COEFF_MOS";
        else if (dispsci)
            disp_coeff_tag = "DISP_COEFF_SCI_MOS";
        else
            disp_coeff_tag = "DISP_COEFF_STD_MOS";
    }
    else {
        slit_location_tag = "SLIT_LOCATION_LSS";
        if (disp)
            disp_coeff_tag = "DISP_COEFF_LSS";
        else if (dispsci)
            disp_coeff_tag = "DISP_COEFF_SCI_LSS";
        else
            disp_coeff_tag = "DISP_COEFF_STD_LSS";
    }

    header = dfs_load_header(frameset, disp_coeff_tag, 0);

    if (header == NULL)
        fors_resample_exit("Cannot load dispersion coefficients table header");

    if (mos || mxu) {
        int nslits_out_det = 0;

        if (mos)
            maskslits = mos_load_slits_fors_mos(header, &nslits_out_det);
        else
            maskslits = mos_load_slits_fors_mxu(header);

        /*
         * Check if all slits have the same X offset.
         */

        treat_as_lss = fors_mos_is_lss_like(maskslits, nslits_out_det);

        cpl_table_delete(maskslits); maskslits = NULL;
    }

    cpl_propertylist_delete(header); header = NULL;

    if (mxu) {
        if (treat_as_lss) {
            sciall = cpl_frameset_count_tags(frameset, "SCIENCE_UNFLAT_MXU");
            stdall = cpl_frameset_count_tags(frameset, "STANDARD_UNFLAT_MXU");
            scisky = 0;
            stdsky = 0;
            sci    = cpl_frameset_count_tags(frameset, "SCIENCE_UNBIAS_MXU");
            std    = cpl_frameset_count_tags(frameset, "STANDARD_UNBIAS_MXU");
            lamp   = cpl_frameset_count_tags(frameset, "LAMP_UNBIAS_MXU");
        }
        else {
            sciall = cpl_frameset_count_tags(frameset, "RECTIFIED_ALL_SCI_MXU");
            stdall = cpl_frameset_count_tags(frameset, "RECTIFIED_ALL_STD_MXU");
            scisky = cpl_frameset_count_tags(frameset, "RECTIFIED_SKY_SCI_MXU");
            stdsky = cpl_frameset_count_tags(frameset, "RECTIFIED_SKY_STD_MXU");
            sci    = cpl_frameset_count_tags(frameset, "RECTIFIED_SCI_MXU");
            std    = cpl_frameset_count_tags(frameset, "RECTIFIED_STD_MXU");
            lamp   = cpl_frameset_count_tags(frameset, "RECTIFIED_LAMP_MXU");
        }
    }
    else if (mos) {
        if (treat_as_lss) {
            sciall = cpl_frameset_count_tags(frameset, "SCIENCE_UNFLAT_MOS");
            stdall = cpl_frameset_count_tags(frameset, "STANDARD_UNFLAT_MOS");
            scisky = 0;
            stdsky = 0;
            sci    = cpl_frameset_count_tags(frameset, "SCIENCE_UNBIAS_MOS");
            std    = cpl_frameset_count_tags(frameset, "STANDARD_UNBIAS_MOS");
            lamp   = cpl_frameset_count_tags(frameset, "LAMP_UNBIAS_MOS");
        }
        else {
            sciall = cpl_frameset_count_tags(frameset, "RECTIFIED_ALL_SCI_MOS");
            stdall = cpl_frameset_count_tags(frameset, "RECTIFIED_ALL_STD_MOS");
            scisky = cpl_frameset_count_tags(frameset, "RECTIFIED_SKY_SCI_MOS");
            stdsky = cpl_frameset_count_tags(frameset, "RECTIFIED_SKY_STD_MOS");
            sci    = cpl_frameset_count_tags(frameset, "RECTIFIED_SCI_MOS");
            std    = cpl_frameset_count_tags(frameset, "RECTIFIED_STD_MOS");
            lamp   = cpl_frameset_count_tags(frameset, "RECTIFIED_LAMP_MOS");
        }
    }
    else {
        sciall = cpl_frameset_count_tags(frameset, "SCIENCE_UNFLAT_LSS");
        stdall = cpl_frameset_count_tags(frameset, "STANDARD_UNFLAT_LSS");
        scisky = 0;
        stdsky = 0;
        sci    = cpl_frameset_count_tags(frameset, "SCIENCE_UNBIAS_LSS");
        std    = cpl_frameset_count_tags(frameset, "STANDARD_UNBIAS_LSS");
        lamp   = cpl_frameset_count_tags(frameset, "LAMP_UNBIAS_LSS");
    }

    nframes = sciall + stdall + scisky + stdsky + sci + std + lamp;

    if (nframes == 0)
        fors_resample_exit("Missing input spectral frame");

    if (nframes > 1) {
        cpl_msg_error(recipe, "Too many input spectral frames (%d > 1)", 
                      nframes);
        fors_resample_exit(NULL);
    }

    if (sciall) {
        if (mxu) {
            if (treat_as_lss) {
                rectified_tag = "SCIENCE_UNFLAT_MXU";
                mapped_tag    = "MAPPED_ALL_SCI_MXU";
            }
            else {
                rectified_tag = "RECTIFIED_ALL_SCI_MXU";
                mapped_tag    = "MAPPED_ALL_SCI_MXU";
            }
        }
        else if (mos) {
            if (treat_as_lss) {
                rectified_tag = "SCIENCE_UNFLAT_MOS";
                mapped_tag    = "MAPPED_ALL_SCI_MOS";
            }
            else {
                rectified_tag = "RECTIFIED_ALL_SCI_MOS";
                mapped_tag    = "MAPPED_ALL_SCI_MOS";
            }
        }
        else {
            rectified_tag = "SCIENCE_UNFLAT_LSS";
            mapped_tag    = "MAPPED_ALL_SCI_LSS";
        }
    }
    else if (stdall) {
        if (mxu) {
            if (treat_as_lss) {
                rectified_tag = "STANDARD_UNFLAT_MXU";
                mapped_tag    = "MAPPED_ALL_STD_MXU";
            }
            else {
                rectified_tag = "RECTIFIED_ALL_STD_MXU";
                mapped_tag    = "MAPPED_ALL_STD_MXU";
            }
        }
        else if (mos) {
            if (treat_as_lss) {
                rectified_tag = "STANDARD_UNFLAT_MOS";
                mapped_tag    = "MAPPED_ALL_STD_MOS";
            }
            else {
                rectified_tag = "RECTIFIED_ALL_STD_MOS";
                mapped_tag    = "MAPPED_ALL_STD_MOS";
            }
        }
        else {
            rectified_tag = "STANDARD_UNFLAT_LSS";
            mapped_tag    = "MAPPED_ALL_STD_LSS";
        }
    }
    else if (scisky) {
        if (mxu) {
            rectified_tag = "RECTIFIED_SKY_SCI_MXU";
            mapped_tag    = "MAPPED_SKY_SCI_MXU";
        }
        else {
            rectified_tag = "RECTIFIED_SKY_SCI_MOS";
            mapped_tag    = "MAPPED_SKY_SCI_MOS";
        }
    }
    else if (stdsky) {
        if (mxu) {
            rectified_tag = "RECTIFIED_SKY_STD_MXU";
            mapped_tag    = "MAPPED_SKY_STD_MXU";
        }
        else {
            rectified_tag = "RECTIFIED_SKY_STD_MOS";
            mapped_tag    = "MAPPED_SKY_STD_MOS";
        }
    }
    else if (sci) {
        if (mxu) {
            if (treat_as_lss) {
                rectified_tag = "SCIENCE_UNBIAS_MXU";
                mapped_tag    = "MAPPED_ALL_SCI_MXU";
            }
            else {
                rectified_tag = "RECTIFIED_SCI_MXU";
                mapped_tag    = "MAPPED_SCI_MXU";
            }
        }
        else if (mos) {
            if (treat_as_lss) {
                rectified_tag = "SCIENCE_UNBIAS_MOS";
                mapped_tag    = "MAPPED_ALL_SCI_MOS";
            }
            else {
                rectified_tag = "RECTIFIED_SCI_MOS";
                mapped_tag    = "MAPPED_SCI_MOS";
            }
        }
        else {
            rectified_tag = "SCIENCE_UNBIAS_LSS";
            mapped_tag    = "MAPPED_ALL_SCI_LSS";
        }
    }
    else if (std) {
        if (mxu) {
            if (treat_as_lss) {
                rectified_tag = "STANDARD_UNBIAS_MXU";
                mapped_tag    = "MAPPED_ALL_STD_MXU";
            }
            else {
                rectified_tag = "RECTIFIED_STD_MXU";
                mapped_tag    = "MAPPED_STD_MXU";
            }
        }
        else if (mos) {
            if (treat_as_lss) {
                rectified_tag = "STANDARD_UNBIAS_MOS";
                mapped_tag    = "MAPPED_ALL_STD_MOS";
            }
            else {
                rectified_tag = "RECTIFIED_STD_MOS";
                mapped_tag    = "MAPPED_STD_MOS";
            }
        }
        else {
            rectified_tag = "STANDARD_UNBIAS_LSS";
            mapped_tag    = "MAPPED_ALL_STD_LSS";
        }
    }
    else if (lamp) {
        if (mxu) {
            if (treat_as_lss) {
                rectified_tag = "LAMP_UNBIAS_MXU";
                mapped_tag    = "MAPPED_LAMP_MXU";
            }
            else {
                rectified_tag = "RECTIFIED_LAMP_MXU";
                mapped_tag    = "MAPPED_LAMP_MXU";
            }
        }
        else if (mos) {
            if (treat_as_lss) {
                rectified_tag = "LAMP_UNBIAS_MOS";
                mapped_tag    = "MAPPED_LAMP_MOS";
            }
            else {
                rectified_tag = "RECTIFIED_LAMP_MOS";
                mapped_tag    = "MAPPED_LAMP_MOS";
            }
        }
        else {
            rectified_tag = "LAMP_UNBIAS_LSS";
            mapped_tag    = "MAPPED_LAMP_LSS";
        }
    }

    header = dfs_load_header(frameset, rectified_tag, 0);

    if (header == NULL)
        fors_resample_exit("Cannot load spectral frame header");


    if (!dfs_equal_keyword(frameset, "ESO INS GRIS1 ID"))
        cpl_msg_warning(cpl_func,"Input frames are not from the same grism");

    if (!dfs_equal_keyword(frameset, "ESO INS FILT1 ID"))
        cpl_msg_warning(cpl_func,"Input frames are not from the same filter");

    if (!dfs_equal_keyword(frameset, "ESO DET CHIP1 ID"))
        cpl_msg_warning(cpl_func,"Input frames are not from the same chip");


    /*
     * Get the reference wavelength and the rebin factor along the
     * dispersion direction from the reference frame
     */

    instrume = (char *)cpl_propertylist_get_string(header, "INSTRUME");
    if (instrume == NULL)
        fors_resample_exit("Missing keyword INSTRUME in reference frame "
                            "header");

    if (instrume[4] == '1')
        snprintf(version, 80, "%s/%s", "fors1", VERSION);
    if (instrume[4] == '2')
        snprintf(version, 80, "%s/%s", "fors2", VERSION);

    reference = cpl_propertylist_get_double(header, "ESO INS GRIS1 WLEN");

    if (cpl_error_get_code() != CPL_ERROR_NONE)
        fors_resample_exit("Missing keyword ESO INS GRIS1 WLEN "
                            "in reference frame header");

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

    if (reference < 3000.0 || reference > 13000.0) {
        cpl_msg_error(recipe, "Invalid central wavelength %.2f read from "
                      "keyword ESO INS GRIS1 WLEN in reference frame header",
                      reference);
        fors_resample_exit(NULL);
    }

    cpl_msg_info(recipe, "The central wavelength is: %.2f", reference);

    rebin = cpl_propertylist_get_int(header, "ESO DET WIN1 BINX");

    if (cpl_error_get_code() != CPL_ERROR_NONE)
        fors_resample_exit("Missing keyword ESO DET WIN1 BINX "
                            "in reference frame header");

    if (rebin != 1) {
        dispersion *= rebin;
        cpl_msg_warning(recipe, "The rebin factor is %d, and therefore the "
                        "working dispersion used is %f A/pixel", rebin,
                        dispersion);
    }


    cpl_msg_indent_less();
    cpl_msg_info(recipe, "Load input frames...");
    cpl_msg_indent_more();

    spectra = dfs_load_image(frameset, rectified_tag, CPL_TYPE_FLOAT, 0, 0);
    if (spectra == NULL)
        fors_resample_exit("Cannot load input spectral frame");

    idscoeff = dfs_load_table(frameset, disp_coeff_tag, 1);
    if (idscoeff == NULL)
        fors_resample_exit("Cannot load dispersion solution table");

    if (lss || treat_as_lss) {
        int        first_row, last_row, ylow, yhig, nx;
        cpl_image *dummy;

        slits = dfs_load_table(frameset, slit_location_tag, 1);
        if (slits == NULL)
            fors_resample_exit("Cannot load slit location table");

        first_row = cpl_table_get_double(slits, "ybottom", 0, NULL);
        last_row = cpl_table_get_double(slits, "ytop", 0, NULL);

        ylow = first_row + 1;
        yhig = last_row + 1;

        nx = cpl_image_get_size_x(spectra);

        dummy = cpl_image_extract(spectra, 1, ylow, nx, yhig);
        cpl_image_delete(spectra); spectra = dummy;
    }

    cpl_msg_indent_less();
    cpl_msg_info(recipe, "Spectral resampling...");
    cpl_msg_indent_more();

    mapped = mos_wavelength_calibration(spectra, reference,
                                        startwavelength, endwavelength,
                                        dispersion, idscoeff, flux);

    cpl_table_delete(idscoeff); idscoeff = NULL;
    cpl_image_delete(spectra); spectra = NULL;

    cpl_propertylist_update_double(header, "CRPIX1", 1.0);
    cpl_propertylist_update_double(header, "CRPIX2", 1.0);
    cpl_propertylist_update_double(header, "CRVAL1",
                                   startwavelength + dispersion/2);
    cpl_propertylist_update_double(header, "CRVAL2", 1.0);
    /* cpl_propertylist_update_double(header, "CDELT1", dispersion);
    cpl_propertylist_update_double(header, "CDELT2", 1.0); */
    cpl_propertylist_update_double(header, "CD1_1", dispersion);
    cpl_propertylist_update_double(header, "CD1_2", 0.0);
    cpl_propertylist_update_double(header, "CD2_1", 0.0);
    cpl_propertylist_update_double(header, "CD2_2", 1.0);
    cpl_propertylist_update_string(header, "CTYPE1", "LINEAR");
    cpl_propertylist_update_string(header, "CTYPE2", "PIXEL");

    if (dfs_save_image(frameset, mapped, mapped_tag,
                       header, parlist, recipe, version))
        fors_resample_exit(NULL);

    cpl_image_delete(mapped); mapped = NULL;
    cpl_propertylist_delete(header); header = NULL;

    return 0;
}
