/* $Id: fors_detect_spectra.c,v 1.11 2013-10-09 15:59:38 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-10-09 15:59:38 $
 * $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_detect_spectra_create(cpl_plugin *);
static int fors_detect_spectra_exec(cpl_plugin *);
static int fors_detect_spectra_destroy(cpl_plugin *);
static int fors_detect_spectra(cpl_parameterlist *, cpl_frameset *);

static char fors_detect_spectra_description[] =
"This recipe is used to detect and locate MOS/MXU slit spectra on the CCD,\n"
"applying a pattern-matching algorithm. The input spectral exposure must\n"
"contain spectra with the dispersion direction approximately horizontal,\n"
"with blue on the left and red on the right. Use recipe fors_wave_calib_lss\n"
"for LSS data, or for MOS/MXU data where all slits have the same offset.\n"
"\n"
"The rows of the input spectral exposure are processed separately, one\n"
"by one. First, the background continuum is removed. Second, a list of\n"
"positions of reference lines candidates is created. Only peaks above a\n"
"given threshold (specified by the parameter --peakdetection) are selected.\n"
"Third, the pattern-matching task selects from the found peaks the ones\n"
"corresponding to the reference lines, listed in the input line catalog,\n"
"associating them to the appropriate wavelengths. The ensuing polynomial\n"
"fit is used to locate the central wavelength of the applied grism along\n"
"each image row. The contributions from all rows form an image of the\n"
"location of all spectra, that can be used as a starting point for the\n"
"proper modeling of the optical and spectral distortions. For more details\n"
"on this reduction strategy please refer to the FORS Pipeline User's Manual.\n"
"\n"
"Note that specifying an input GRISM_TABLE will set some of the recipe\n"
"configuration parameters to default values valid for a particular grism.\n"
"Again, see the pipeline manual for more details.\n"
"\n"
"In the table below the MXU acronym can be alternatively read as MOS.\n\n"
"Input files:\n\n"
"  DO category:               Type:       Explanation:         Required:\n"
"  LAMP_UNBIAS_MXU            Calib       Bias subtracted arc     Y\n"
"  MASTER_LINECAT             Calib       Line catalog            Y\n"
"  GRISM_TABLE                Calib       Grism table             .\n\n"
"Output files:\n\n"
"  DO category:               Data type:  Explanation:\n"
"  SLIT_MAP_MXU               FITS image  Map of central wavelength on CCD\n"
"  SLIT_LOCATION_DETECT_MXU   FITS table  Slits positions on CCD\n"
"  SPECTRA_DETECTION_MXU      FITS image  Check of preliminary detection\n\n";

#define fors_detect_spectra_exit(message)     \
{                                             \
if (message) cpl_msg_error(recipe, message);  \
cpl_image_delete(spectra);                    \
cpl_image_delete(checkwave);                  \
cpl_image_delete(refimage);                   \
cpl_mask_delete(refmask);                     \
cpl_table_delete(grism_table);                \
cpl_table_delete(wavelengths);                \
cpl_table_delete(maskslits);                  \
cpl_table_delete(slits);                      \
cpl_vector_delete(lines);                     \
cpl_propertylist_delete(header);              \
cpl_msg_indent_less();                        \
return -1;                                    \
}

#define fors_detect_spectra_exit_memcheck(message) \
{                                               \
if (message) cpl_msg_info(recipe, message);     \
printf("free spectra (%p)\n", spectra);         \
cpl_image_delete(spectra);                      \
printf("free checkwave (%p)\n", checkwave);     \
cpl_image_delete(checkwave);                    \
printf("free refimage (%p)\n", refimage);       \
cpl_image_delete(refimage);                     \
printf("free refmask (%p)\n", refmask);         \
cpl_mask_delete(refmask);                       \
printf("free grism_table (%p)\n", grism_table); \
cpl_table_delete(grism_table);                  \
printf("free wavelengths (%p)\n", wavelengths); \
cpl_table_delete(wavelengths);                  \
printf("free maskslits (%p)\n", maskslits);     \
cpl_table_delete(maskslits);                    \
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_detect_spectra",
                    "Detect MOS/MXU spectra on CCD",
                    fors_detect_spectra_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_detect_spectra_create,
                    fors_detect_spectra_exec,
                    fors_detect_spectra_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_detect_spectra_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_detect_spectra.dispersion",
                                CPL_TYPE_DOUBLE,
                                "Expected spectral dispersion (Angstrom/pixel)",
                                "fors.fors_detect_spectra",
                                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);

    /*
     * Peak detection level
     */

    p = cpl_parameter_new_value("fors.fors_detect_spectra.peakdetection",
                                CPL_TYPE_DOUBLE,
                                "Initial peak detection threshold (ADU)",
                                "fors.fors_detect_spectra",
                                0.0);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "peakdetection");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Degree of wavelength calibration polynomial
     */

    p = cpl_parameter_new_value("fors.fors_detect_spectra.wdegree",
                                CPL_TYPE_INT,
                                "Degree of wavelength calibration polynomial",
                                "fors.fors_detect_spectra",
                                0);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "wdegree");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Reference lines search radius
     */

    p = cpl_parameter_new_value("fors.fors_detect_spectra.wradius",
                                CPL_TYPE_INT,
                                "Search radius if iterating pattern-matching "
                                "with first-guess method",
                                "fors.fors_detect_spectra",
                                4);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "wradius");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Rejection threshold in dispersion relation polynomial fitting
     */

    p = cpl_parameter_new_value("fors.fors_detect_spectra.wreject",
                                CPL_TYPE_DOUBLE,
                                "Rejection threshold in dispersion "
                                "relation fit (pixel)",
                                "fors.fors_detect_spectra",
                                0.7);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "wreject");
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_ENV);
    cpl_parameterlist_append(recipe->parameters, p);

    /*
     * Line catalog table column containing the reference wavelengths
     */

    p = cpl_parameter_new_value("fors.fors_detect_spectra.wcolumn",
                                CPL_TYPE_STRING,
                                "Name of line catalog table column "
                                "with wavelengths",
                                "fors.fors_detect_spectra",
                                "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);

    /*
     * Start wavelength for spectral extraction
     */

    p = cpl_parameter_new_value("fors.fors_detect_spectra.startwavelength",
                                CPL_TYPE_DOUBLE,
                                "Start wavelength in spectral extraction",
                                "fors.fors_detect_spectra",
                                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_detect_spectra.endwavelength",
                                CPL_TYPE_DOUBLE,
                                "End wavelength in spectral extraction",
                                "fors.fors_detect_spectra",
                                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);

    /*
     * Try slit identification
     */

    p = cpl_parameter_new_value("fors.fors_detect_spectra.slit_ident",
                                CPL_TYPE_BOOL,
                                "Attempt slit identification for MOS or MXU",
                                "fors.fors_detect_spectra",
                                TRUE);
    cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "slit_ident");
    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_detect_spectra_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_detect_spectra(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_detect_spectra_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_detect_spectra(cpl_parameterlist *parlist, 
                               cpl_frameset *frameset)
{

    const char *recipe = "fors_detect_spectra";


    /*
     * Input parameters
     */

    double      dispersion;
    double      peakdetection;
    int         wdegree;
    int         wradius;
    double      wreject;
    const char *wcolumn;
    double      startwavelength;
    double      endwavelength;
    int         slit_ident;

    /*
     * CPL objects
     */

    cpl_image        *spectra     = NULL;
    cpl_image        *checkwave   = NULL;
    cpl_image        *refimage    = NULL;
    cpl_mask         *refmask     = NULL;
    cpl_table        *grism_table = NULL;
    cpl_table        *wavelengths = NULL;
    cpl_table        *slits       = NULL;
    cpl_table        *positions   = NULL;
    cpl_table        *maskslits   = NULL;
    cpl_vector       *lines       = NULL;
    cpl_propertylist *header      = NULL;

    /*
     * Auxiliary variables
     */

    char        version[80];
    const char *arc_tag;
    const char *spectra_detection_tag;
    const char *slit_map_tag;
    const char *slit_location_tag;
    int         lamp_mxu;
    int         lamp_mos;
    int         lamp_lss;
    int         mos;
    int         treat_as_lss = 0;
    int         nslits;
    double      mxpos;
    int         narc;
    int         nlines;
    int         rebin;
    double     *line;
    int         nx, ny;
    double      reference;
    int         i;
    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_detect_spectra_exit("Too many in input: GRISM_TABLE"); 

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

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

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

    peakdetection = dfs_get_parameter_double(parlist,
                    "fors.fors_detect_spectra.peakdetection", grism_table);
    if (peakdetection <= 0.0)
        fors_detect_spectra_exit("Invalid peak detection level");

    wdegree = dfs_get_parameter_int(parlist,
                    "fors.fors_detect_spectra.wdegree", grism_table);

    if (wdegree < 1)
        fors_detect_spectra_exit("Invalid polynomial degree");

    if (wdegree > 5)
        fors_detect_spectra_exit("Max allowed polynomial degree is 5");

    wradius = dfs_get_parameter_int(parlist, 
                                    "fors.fors_detect_spectra.wradius", NULL);

    if (wradius < 0)
        fors_detect_spectra_exit("Invalid search radius");

    wreject = dfs_get_parameter_double(parlist, 
                                    "fors.fors_detect_spectra.wreject", NULL);

    if (wreject <= 0.0)
        fors_detect_spectra_exit("Invalid rejection threshold");

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

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

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

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

    slit_ident = dfs_get_parameter_bool(parlist,
                    "fors.fors_detect_spectra.slit_ident", NULL);

    cpl_table_delete(grism_table); grism_table = NULL;

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


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

    narc  = lamp_mxu = cpl_frameset_count_tags(frameset, "LAMP_UNBIAS_MXU");
    narc += lamp_mos = cpl_frameset_count_tags(frameset, "LAMP_UNBIAS_MOS");
    narc += lamp_lss = cpl_frameset_count_tags(frameset, "LAMP_UNBIAS_LSS");

    if (narc == 0) {
        fors_detect_spectra_exit("Missing input arc lamp frame");
    }
    if (narc > 1) {
        cpl_msg_error(recipe, "Too many input arc lamp frames (%d > 1)", narc);
        fors_detect_spectra_exit(NULL);
    }

    mos = 0;

    if (lamp_mxu) {
        arc_tag               = "LAMP_UNBIAS_MXU";
        spectra_detection_tag = "SPECTRA_DETECTION_MXU";
        slit_map_tag          = "SLIT_MAP_MXU";
        slit_location_tag     = "SLIT_LOCATION_DETECT_MXU";
    }
    else if (lamp_mos) {
        mos = 1;
        arc_tag               = "LAMP_UNBIAS_MOS";
        spectra_detection_tag = "SPECTRA_DETECTION_MOS";
        slit_map_tag          = "SLIT_MAP_MOS";
        slit_location_tag     = "SLIT_LOCATION_DETECT_MOS";
    }
    else if (lamp_lss) {
        fors_detect_spectra_exit("Use recipe fors_wave_calib_lss "
                                 "for LSS data reduction");
    }


    if (cpl_frameset_count_tags(frameset, "MASTER_LINECAT") == 0)
        fors_detect_spectra_exit("Missing required input: MASTER_LINECAT");

    if (cpl_frameset_count_tags(frameset, "MASTER_LINECAT") > 1)
        fors_detect_spectra_exit("Too many in input: MASTER_LINECAT");

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

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

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


    /*
     * Get the reference wavelength and the rebin factor along the
     * dispersion direction from the arc lamp exposure
     */

    header = dfs_load_header(frameset, arc_tag, 0);

    if (header == NULL)
        fors_detect_spectra_exit("Cannot load arc lamp header");

    instrume = (char *)cpl_propertylist_get_string(header, "INSTRUME");
    if (instrume == NULL)
        fors_detect_spectra_exit("Missing keyword INSTRUME in arc lamp 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_detect_spectra_exit("Missing keyword ESO INS GRIS1 WLEN "
                                 "in arc lamp 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 arc lamp frame header",
                      reference);
        fors_detect_spectra_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_detect_spectra_exit("Missing keyword ESO DET WIN1 BINX "
                                 "in arc lamp 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_info(recipe, "Produce mask slit position table...");

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

    cpl_propertylist_delete(header); header = NULL;


    /*
     * Check if all slits have the same X offset: in such case,
     * treat the observation as a long-slit one!
     */

    treat_as_lss = fors_mos_is_lss_like(maskslits, nslits_out_det);

    if (treat_as_lss) {
        cpl_msg_error(recipe, "All slits have the same offset: %.2f mm\n"
                      "The LSS data reduction strategy must be applied: "
                      "please use recipe fors_wave_calib_lss", mxpos);
        fors_detect_spectra_exit(NULL);
    }

    if (slit_ident == 0) {
        cpl_table_delete(maskslits); maskslits = NULL;
    }


    cpl_msg_indent_less();
    cpl_msg_info(recipe, "Load arc lamp exposure...");
    cpl_msg_indent_more();

    spectra = dfs_load_image(frameset, arc_tag, CPL_TYPE_FLOAT, 0, 0);

    if (spectra == NULL)
        fors_detect_spectra_exit("Cannot load arc lamp exposure");


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

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

    if (wavelengths == NULL)
        fors_detect_spectra_exit("Cannot load line catalog");


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

    nlines = cpl_table_get_nrow(wavelengths);

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

    if (cpl_table_has_column(wavelengths, wcolumn) != 1) {
        cpl_msg_error(recipe, "Missing column %s in input line catalog table",
                      wcolumn);
        fors_detect_spectra_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);


    cpl_msg_indent_less();
    cpl_msg_info(recipe, "Detecting spectra on CCD...");
    cpl_msg_indent_more();

    nx = cpl_image_get_size_x(spectra);
    ny = cpl_image_get_size_y(spectra);

    refmask = cpl_mask_new(nx, ny);

    if (mos_saturation_process(spectra))
	fors_detect_spectra_exit("Cannot process saturation");

    if (mos_subtract_background(spectra))
	fors_detect_spectra_exit("Cannot subtract the background");

    checkwave = mos_wavelength_calibration_raw(spectra, lines, dispersion,
                                               peakdetection, wradius,
                                               wdegree, wreject, reference,
                                               &startwavelength, &endwavelength,
                                               NULL, NULL, NULL, NULL, NULL,
                                               NULL, refmask, NULL);

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

    if (checkwave == NULL)
        fors_detect_spectra_exit("Wavelength calibration failure.");


    /*
     * Save check image to disk
     */

    header = cpl_propertylist_new();
    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, checkwave, spectra_detection_tag, header,
                       parlist, recipe, version))
        fors_detect_spectra_exit(NULL);

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


    cpl_msg_info(recipe, "Locate slits at reference wavelength on CCD...");
    slits = mos_locate_spectra(refmask);

    if (!slits) {
        cpl_msg_error(cpl_error_get_where(), "%s", cpl_error_get_message());
        fors_detect_spectra_exit("No slits could be detected!");
    }

    refimage = cpl_image_new_from_mask(refmask);
    cpl_mask_delete(refmask); refmask = NULL;

    header = dfs_load_header(frameset, arc_tag, 0);
    if (dfs_save_image(frameset, refimage, slit_map_tag, header,
                       parlist, recipe, version))
        fors_detect_spectra_exit(NULL);
    cpl_propertylist_delete(header); header = NULL;

    cpl_image_delete(refimage); refimage = NULL;

    if (slit_ident) {

        /*
         * Attempt slit identification: this recipe may continue even
         * in case of failed identification (i.e., the position table is
         * not produced, but an error is not set). In case of failure,
         * the spectra would be still extracted, even if they would not
         * be associated to slits on the mask.
         *
         * The reason for making the slit identification an user option
         * (via the parameter slit_ident) is to offer the possibility
         * to avoid identifications that are only apparently successful,
         * as it would happen in the case of an incorrect slit description
         * in the data header.
         */

        cpl_msg_indent_less();
        cpl_msg_info(recipe, "Attempt slit identification (optional)...");
        cpl_msg_indent_more();

        positions = mos_identify_slits(slits, maskslits, NULL);
        cpl_table_delete(maskslits); maskslits = NULL;

        if (positions) {
            cpl_table_delete(slits);
            slits = positions;

            /*
             * Eliminate slits which are _entirely_ outside the CCD
             */

            cpl_table_and_selected_double(slits,
                                          "ybottom", CPL_GREATER_THAN, ny-1);
            cpl_table_or_selected_double(slits,
                                          "ytop", CPL_LESS_THAN, 0);
            cpl_table_erase_selected(slits);

            nslits = cpl_table_get_nrow(slits);

            if (nslits == 0)
                fors_detect_spectra_exit("No slits found on the CCD");

            cpl_msg_info(recipe, "%d slits are entirely or partially "
                         "contained in CCD", nslits);

        }
        else {
            slit_ident = 0;
            cpl_msg_info(recipe, "Global distortion model cannot be computed");
            if (cpl_error_get_code() != CPL_ERROR_NONE) {
                fors_detect_spectra_exit(NULL);
            }
        }
    }

    if (dfs_save_table(frameset, slits, slit_location_tag, NULL,
                       parlist, recipe, version))
        fors_detect_spectra_exit(NULL);

    cpl_table_delete(slits); slits = NULL;

    return 0;
}
