/* $Id: fors_align_sky_lss.c,v 1.9 2013-08-21 14:49:09 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-21 14:49:09 $
 * $Revision: 1.9 $
 * $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_align_sky_lss_create(cpl_plugin *);
static int fors_align_sky_lss_exec(cpl_plugin *);
static int fors_align_sky_lss_destroy(cpl_plugin *);
static int fors_align_sky_lss(cpl_parameterlist *, cpl_frameset *);

static char fors_align_sky_lss_description[] =
"This recipe is used to align the wavelength solution based on the arc\n"
"lamp exposure on a set of sky lines observed on a scientific exposure.\n"
"The input scientific frames are produced by the recipes fors_remove_bias\n"
"and fors_flatfield. An input catalog of sky lines can be specified, or\n"
"an internal one is used.\n"
"\n"
"This recipe should be applied to LSS or long-slit like data (MOS/MXU with\n"
"all slits at the same offset). For multi-slit MOS/MXU data use recipe\n"
"fors_align_sky instead. Please refer to the FORS PIpeline User's Manual\n"
"for more details.\n"
"\n"
"In the table below the MXU acronym can be alternatively read as MOS and\n"
"LSS, and SCI as STD.\n\n"
"Input files:\n\n"
"  DO category:               Type:       Explanation:         Required:\n"
"  SCIENCE_UNBIAS_MXU\n"
"  or SCIENCE_UNFLAT_MXU\n"
"  or STANDARD_UNBIAS_MXU\n"
"  or STANDARD_UNFLAT_MXU     Calib       Frame with sky lines    Y\n"
"  DISP_COEFF_MXU             Calib       Dispersion solution     Y\n"
"  SLIT_LOCATION_MXU          Calib       Slit location on CCD    Y\n"
"  MASTER_SKYLINECAT          Calib       Catalog of sky lines    .\n"
"  GRISM_TABLE                Calib       Grism table             .\n\n"
"Output files:\n\n"
"  DO category:               Data type:  Explanation:\n"
"  SKY_SHIFTS_LONG_SCI_MXU    FITS table  Observed sky lines offsets\n"
"  WAVELENGTH_MAP_SCI_MXU     FITS image  Wavelength mapped on CCD\n"
"  DISP_COEFF_SCI_MXU         FITS image  Upgraded dispersion solution\n\n";

#define fors_align_sky_lss_exit(message)          \
{                                             \
if ((const char *)message != NULL) cpl_msg_error(recipe, message);  \
cpl_image_delete(wavemap);                    \
cpl_image_delete(rainbow);                    \
cpl_image_delete(smapped);                    \
cpl_table_delete(grism_table);                \
cpl_table_delete(maskslits);                  \
cpl_table_delete(wavelengths);                \
cpl_table_delete(offsets);                    \
cpl_table_delete(slits);                      \
cpl_table_delete(idscoeff);                   \
cpl_vector_delete(lines);                     \
cpl_propertylist_delete(header);              \
cpl_msg_indent_less();                        \
return -1;                                    \
}

#define fors_align_sky_lss_exit_memcheck(message)   \
{                                               \
if ((const char *)message != NULL) cpl_msg_info(recipe, message);     \
printf("free wavemap (%p)\n", wavemap);         \
cpl_image_delete(wavemap);                      \
printf("free rainbow (%p)\n", rainbow);         \
cpl_image_delete(rainbow);                      \
printf("free smapped (%p)\n", smapped);         \
cpl_image_delete(smapped);                      \
printf("free grism_table (%p)\n", grism_table); \
cpl_table_delete(grism_table);                  \
printf("free maskslits (%p)\n", maskslits);     \
cpl_table_delete(maskslits);                    \
printf("free wavelengths (%p)\n", wavelengths); \
cpl_table_delete(wavelengths);                  \
printf("free offsets (%p)\n", offsets);         \
cpl_table_delete(offsets);                      \
printf("free idscoeff (%p)\n", idscoeff);       \
cpl_table_delete(idscoeff);                     \
printf("free slits (%p)\n", slits);             \
cpl_table_delete(slits);                        \
printf("free lines (%p)\n", lines);             \
cpl_vector_delete(lines);                       \
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_align_sky_lss",
                    "Upgrade wavelength solution using sky lines",
                    fors_align_sky_lss_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_align_sky_lss_create,
                    fors_align_sky_lss_exec,
                    fors_align_sky_lss_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_align_sky_lss_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_align_sky_lss.dispersion",
                                CPL_TYPE_DOUBLE,
                                "Expected spectral dispersion (Angstrom/pixel)",
                                "fors.fors_align_sky_lss",
                                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_align_sky_lss.startwavelength",
                                CPL_TYPE_DOUBLE,
                                "Start wavelength in spectral extraction",
                                "fors.fors_align_sky_lss",
                                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_align_sky_lss.endwavelength",
                                CPL_TYPE_DOUBLE,
                                "End wavelength in spectral extraction",
                                "fors.fors_align_sky_lss",
                                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);

    /*
     * Sky lines alignment
     */

    p = cpl_parameter_new_value("fors.fors_align_sky_lss.skyalign",
                                CPL_TYPE_INT,
                                "Polynomial order for sky lines alignment",
                                "fors.fors_align_sky_lss",
                                0);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "skyalign");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Line catalog table column containing the sky reference wavelengths
     */
    
    p = cpl_parameter_new_value("fors.fors_align_sky_lss.wcolumn",
                                CPL_TYPE_STRING,
                                "Name of sky line catalog table column "
                                "with wavelengths",
                                "fors.fors_align_sky_lss",
                                "WLEN");
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "wcolumn");
    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_align_sky_lss_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_align_sky_lss(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_align_sky_lss_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_align_sky_lss(cpl_parameterlist *parlist, 
                               cpl_frameset *frameset)
{

    const char *recipe = "fors_align_sky_lss";


    /*
     * Input parameters
     */

    double      dispersion;
    double      startwavelength;
    double      endwavelength;
    int         skyalign;
    const char *wcolumn;

    /*
     * CPL objects
     */

    cpl_image        *rainbow     = NULL;
    cpl_image        *wavemap     = NULL;
    cpl_image        *smapped     = NULL;
    cpl_image        *dummy       = NULL;
    cpl_table        *grism_table = NULL;
    cpl_table        *wavelengths = NULL;
    cpl_table        *slits       = NULL;
    cpl_table        *idscoeff    = NULL;
    cpl_table        *maskslits   = NULL;
    cpl_table        *offsets     = NULL;
    cpl_vector       *lines       = NULL;
    cpl_propertylist *header      = NULL;

    /*
     * Auxiliary variables
     */

    char        version[80];
    const char *slit_location_tag;
    const char *rectified_tag;
    const char *wavemap_tag;
    const char *shifts_tag;
    const char *disp_ali_tag;
    const char *disp_coeff_tag;
    int         nframes;
    int         rebin;
    int         nlines;
    int         nx;
    int         ccd_xsize, ccd_ysize;
    int         first_row, last_row;
    int         ylow, yhig;
    int         highres;
    int         treat_as_lss;
    int         i;
    double      reference;
    double     *line;
    int         mxu, mos, lss;
    int         rec_scib;
    int         rec_stdb;
    int         rec_scif;
    int         rec_stdf;
    int         nslits_out_det = 0;

    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_align_sky_lss_exit("Too many in input: GRISM_TABLE"); 

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

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

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

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

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

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

    skyalign = dfs_get_parameter_int(parlist,
                    "fors.fors_align_sky_lss.skyalign", NULL);

    if (skyalign < 0)
        fors_align_sky_lss_exit("Invalid polynomial degree");
    if (skyalign > 2)
        fors_align_sky_lss_exit("Max polynomial degree for sky alignment is 2");

    wcolumn = dfs_get_parameter_string(parlist,
                    "fors.fors_align_sky_lss.wcolumn", NULL);

    cpl_table_delete(grism_table); grism_table = NULL;

    if (cpl_error_get_code())
        fors_align_sky_lss_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, "SLIT_LOCATION_MXU");
    mos  = cpl_frameset_count_tags(frameset, "SLIT_LOCATION_MOS");
    lss  = cpl_frameset_count_tags(frameset, "SLIT_LOCATION_LSS");

    nframes = mos + mxu + lss;

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

    if (mxu) {
        rec_scib = cpl_frameset_count_tags(frameset, "SCIENCE_UNBIAS_MXU");
        rec_stdb = cpl_frameset_count_tags(frameset, "STANDARD_UNBIAS_MXU");
        rec_scif = cpl_frameset_count_tags(frameset, "SCIENCE_UNFLAT_MXU");
        rec_stdf = cpl_frameset_count_tags(frameset, "STANDARD_UNFLAT_MXU");
    }
    else if (mos) {
        rec_scib = cpl_frameset_count_tags(frameset, "SCIENCE_UNBIAS_MOS");
        rec_stdb = cpl_frameset_count_tags(frameset, "STANDARD_UNBIAS_MOS");
        rec_scif = cpl_frameset_count_tags(frameset, "SCIENCE_UNFLAT_MOS");
        rec_stdf = cpl_frameset_count_tags(frameset, "STANDARD_UNFLAT_MOS");
    }
    else {
        rec_scib = cpl_frameset_count_tags(frameset, "SCIENCE_UNBIAS_LSS");
        rec_stdb = cpl_frameset_count_tags(frameset, "STANDARD_UNBIAS_LSS");
        rec_scif = cpl_frameset_count_tags(frameset, "SCIENCE_UNFLAT_LSS");
        rec_stdf = cpl_frameset_count_tags(frameset, "STANDARD_UNFLAT_LSS");
    }

    nframes = rec_scib + rec_stdb + rec_scif + rec_stdf;

    if (nframes == 0) {
        fors_align_sky_lss_exit("Missing input scientific spectra");
    }
    if (nframes > 1) {
        cpl_msg_error(recipe, "Too many input scientific spectra (%d > 1)", 
                      nframes);
        fors_align_sky_lss_exit(NULL);
    }

    if (cpl_frameset_count_tags(frameset, "MASTER_SKYLINECAT") > 1)
        fors_align_sky_lss_exit("Too many in input: MASTER_SKYLINECAT");

    if (rec_scib) {
        if (mxu) {
            rectified_tag = "SCIENCE_UNBIAS_MXU";
            wavemap_tag   = "WAVELENGTH_MAP_SCI_MXU";
            shifts_tag    = "SKY_SHIFTS_LONG_SCI_MXU";
            disp_ali_tag  = "DISP_COEFF_SCI_MXU";
        }
        else if (mos) {
            rectified_tag = "SCIENCE_UNBIAS_MOS";
            wavemap_tag   = "WAVELENGTH_MAP_SCI_MOS";
            shifts_tag    = "SKY_SHIFTS_LONG_SCI_MOS";
            disp_ali_tag  = "DISP_COEFF_SCI_MOS";
        }
        else {
            rectified_tag = "SCIENCE_UNBIAS_LSS";
            wavemap_tag   = "WAVELENGTH_MAP_SCI_LSS";
            shifts_tag    = "SKY_SHIFTS_LONG_SCI_LSS";
            disp_ali_tag  = "DISP_COEFF_SCI_LSS";
        }
    }
    else if (rec_stdb) {
        if (mxu) {
            rectified_tag = "STANDARD_UNBIAS_MXU";
            wavemap_tag   = "WAVELENGTH_MAP_STD_MXU";
            shifts_tag    = "SKY_SHIFTS_LONG_STD_MXU";
            disp_ali_tag  = "DISP_COEFF_STD_MXU";
        }
        else if (mos) {
            rectified_tag = "STANDARD_UNBIAS_MOS";
            wavemap_tag   = "WAVELENGTH_MAP_STD_MOS";
            shifts_tag    = "SKY_SHIFTS_LONG_STD_MOS";
            disp_ali_tag  = "DISP_COEFF_STD_MOS";
        }
        else { 
            rectified_tag = "STANDARD_UNBIAS_LSS";
            wavemap_tag   = "WAVELENGTH_MAP_STD_LSS";
            shifts_tag    = "SKY_SHIFTS_LONG_STD_LSS";
            disp_ali_tag  = "DISP_COEFF_STD_LSS";
        }
    }
    else if (rec_scif) {
        if (mxu) {
            rectified_tag = "SCIENCE_UNFLAT_MXU";
            wavemap_tag   = "WAVELENGTH_MAP_SCI_MXU";
            shifts_tag    = "SKY_SHIFTS_LONG_SCI_MXU";
            disp_ali_tag  = "DISP_COEFF_SCI_MXU";
        }
        else if (mos) {   
            rectified_tag = "SCIENCE_UNFLAT_MOS";
            wavemap_tag   = "WAVELENGTH_MAP_SCI_MOS";
            shifts_tag    = "SKY_SHIFTS_LONG_SCI_MOS";
            disp_ali_tag  = "DISP_COEFF_SCI_MOS";
        }
        else {
            rectified_tag = "SCIENCE_UNFLAT_LSS";
            wavemap_tag   = "WAVELENGTH_MAP_SCI_LSS";
            shifts_tag    = "SKY_SHIFTS_LONG_SCI_LSS";
            disp_ali_tag  = "DISP_COEFF_SCI_LSS";
        }
    }
    else if (rec_stdf) {
        if (mxu) {
            rectified_tag = "STANDARD_UNFLAT_MXU";
            wavemap_tag   = "WAVELENGTH_MAP_STD_MXU";
            shifts_tag    = "SKY_SHIFTS_LONG_STD_MXU";
            disp_ali_tag  = "DISP_COEFF_STD_MXU";
        }
        else if (mos) {   
            rectified_tag = "STANDARD_UNFLAT_MOS";
            wavemap_tag   = "WAVELENGTH_MAP_STD_MOS";
            shifts_tag    = "SKY_SHIFTS_LONG_STD_MOS";
            disp_ali_tag  = "DISP_COEFF_STD_MOS";
        }
        else {
            rectified_tag = "STANDARD_UNFLAT_LSS";
            wavemap_tag   = "WAVELENGTH_MAP_STD_LSS";
            shifts_tag    = "SKY_SHIFTS_LONG_STD_LSS";
            disp_ali_tag  = "DISP_COEFF_STD_LSS";
        }
    }

    nframes = cpl_frameset_count_tags(frameset, rectified_tag);

    if (nframes == 0) {
        cpl_msg_error(recipe, "Missing input %s", rectified_tag);
        fors_align_sky_lss_exit(NULL);
    }
    if (nframes > 1) {
        cpl_msg_error(recipe, "Too many input %s (%d > 1)", rectified_tag,
                      nframes);
        fors_align_sky_lss_exit(NULL);
    }


    if (mxu) {
        disp_coeff_tag    = "DISP_COEFF_MXU";
        slit_location_tag = "SLIT_LOCATION_MXU";
    }
    else if (mos) {
        disp_coeff_tag    = "DISP_COEFF_MOS";
        slit_location_tag = "SLIT_LOCATION_MOS";
    }
    else {
        disp_coeff_tag    = "DISP_COEFF_LSS";
        slit_location_tag = "SLIT_LOCATION_LSS";
    }

    nframes = cpl_frameset_count_tags(frameset, disp_coeff_tag);

    if (nframes == 0) {
        cpl_msg_error(recipe, "Missing input %s", disp_coeff_tag);
        fors_align_sky_lss_exit(NULL);
    }
    if (nframes > 1) {
        cpl_msg_error(recipe, "Too many input %s (%d > 1)", disp_coeff_tag,
                      nframes);
        fors_align_sky_lss_exit(NULL);
    }


    header = dfs_load_header(frameset, rectified_tag, 0);

    if (header == NULL)
        fors_align_sky_lss_exit("Cannot load scientific frame header");

    if (mos || mxu) {
        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: if not, abort!
         */

        treat_as_lss = fors_mos_is_lss_like(maskslits, nslits_out_det);

        cpl_table_delete(maskslits); maskslits = NULL;

        if (!treat_as_lss)
            fors_align_sky_lss_exit("This is not an LSS observation. "
                                    "Please use recipe fors_align_sky");
    }

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

    smapped = dfs_load_image(frameset, rectified_tag, CPL_TYPE_FLOAT, 0, 0);
    if (smapped == NULL)
        fors_align_sky_lss_exit("Cannot load input scientific frame");

    slits = dfs_load_table(frameset, slit_location_tag, 1);
    if (slits == NULL)
        fors_align_sky_lss_exit("Cannot load slits 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;

    ccd_xsize = cpl_image_get_size_x(smapped);
    ccd_ysize = cpl_image_get_size_x(smapped);
    dummy = cpl_image_extract(smapped, 1, ylow, ccd_xsize, yhig);
    cpl_image_delete(smapped); smapped = dummy;
    nx = ccd_xsize;

    cpl_table_delete(slits); slits = NULL;

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

    wavelengths = dfs_load_table(frameset, "MASTER_SKYLINECAT", 1);

    if (wavelengths) {

        /*
         * Cast the wavelengths into a (double precision) CPL vector
         */

        nlines = cpl_table_get_nrow(wavelengths);

        if (nlines == 0)
            fors_align_sky_lss_exit("Empty input sky line catalog");

        if (cpl_table_has_column(wavelengths, wcolumn) != 1) {
            cpl_msg_error(recipe, "Missing column %s in input line "
                          "catalog table", wcolumn);
            fors_align_sky_lss_exit(NULL);
        }

        line = cpl_malloc(nlines * sizeof(double));

        for (i = 0; i < nlines; i++)
            line[i] = cpl_table_get(wavelengths, wcolumn, i, NULL);

        cpl_table_delete(wavelengths); wavelengths = NULL;

        lines = cpl_vector_wrap(nlines, line);
    }
    else {
        cpl_msg_info(recipe, "No sky line catalog found in input - fine!");
    }

    if (skyalign) {
        cpl_msg_info(recipe, "Align wavelength solution to reference "
        "skylines applying %d order residual fit...", skyalign);
    }
    else {
        cpl_msg_info(recipe, "Align wavelength solution to reference "
        "skylines applying median offset...");
    }

    if (dispersion > 1.0)
        highres = 0;
    else
        highres = 1;

    rainbow = mos_map_idscoeff(idscoeff, nx, reference, startwavelength,
                               endwavelength);

    offsets = mos_wavelength_align_lss(smapped, reference,
                                       startwavelength, endwavelength,
                                       idscoeff, lines, highres,
                                       skyalign, rainbow, 4);

    cpl_vector_delete(lines); lines = NULL;
    cpl_image_delete(smapped); smapped = NULL;

    if (offsets) {
        if (dfs_save_table(frameset, offsets, shifts_tag, NULL,
                           parlist, recipe, version))
            fors_align_sky_lss_exit(NULL);

        cpl_table_delete(offsets); offsets = NULL;
    }
    else
        fors_align_sky_lss_exit("Alignment of the wavelength solution "
                        "to reference sky lines could not be done!");

    if (dfs_save_table(frameset, idscoeff, disp_ali_tag, NULL,
                       parlist, recipe, version))
        fors_align_sky_lss_exit(NULL);

    cpl_table_delete(idscoeff); idscoeff = NULL;

    wavemap = cpl_image_new(ccd_xsize, ccd_ysize, CPL_TYPE_FLOAT);
    cpl_image_copy(wavemap, rainbow, 1, ylow);

    cpl_image_delete(rainbow); rainbow = NULL;

    if (dfs_save_image(frameset, wavemap, wavemap_tag,
                       header, parlist, recipe, version))
        fors_align_sky_lss_exit(NULL);

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

    return 0;
}
