/* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set sw=2 sts=2 et cin: */
/* 
 * This file is part of the MUSE Instrument Pipeline
 * Copyright (C) 2005-2015 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 Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

/* This file was automatically generated */

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

/*----------------------------------------------------------------------------*
 *                              Includes                                      *
 *----------------------------------------------------------------------------*/
#include <string.h> /* strcmp(), strstr() */
#include <strings.h> /* strcasecmp() */
#include <cpl.h>

#include "muse_wavecal_z.h" /* in turn includes muse.h */

/*----------------------------------------------------------------------------*/
/**
  @defgroup recipe_muse_wavecal         Recipe muse_wavecal: Detect arc emission lines and determine the wavelength solution for each slice.
  @author Peter Weilbacher
  
        This recipe detects arc emission lines and fits a wavelength solution
        to each slice of the instrument.
        The wavelength calibration table contains polynomials defining the
        wavelength solution of the slices on the CCD.

        Processing trims the raw data and records the overscan statistics,
        subtracts the bias (taking account of the overscan, if --overscan is not
        "none") and converts them from adu to count. Optionally, the dark can be
        subtracted and the data can be divided by the flat-field, but this is
        not recommended. The data is then combined using input parameters,
        into separate images for each lamp.
        

        To compute the wavelength solution, arc lines are detected at the center
        of each slice (using threshold detection on a S/N image) and
        subsequently assigned wavelengths, using pattern matching to identify
        lines from the input line catalog. Each line is then traced to the edges
        of the slice, using Gaussian centering in each CCD column. The Gaussians
        not only yield center, but also centering error, and line properties
        (e.g. FWHM). Deviant fits are detected using polynomial fits to each arc
        line (using the xorder parameter) and rejected.
        
        These analysis and measuring steps are
        carried out separately on images exposed by the different arc lamps,
        reducing the amount of blending, that can otherwise influence line
        identification and Gaussian centering.
        The final two-dimensional fit uses all positions (of all lamps), their
        wavelengths, and the given polynomial orders to compute the final
        wavelength solution for each slice, iteratively rejecting outliers. This
        final fit can be either unweighted (fitweighting="uniform", for fastest
        processing) or weighted (other values of fitweighting, for higher
        accuracy).
      
 */
/*----------------------------------------------------------------------------*/
/**@{*/

/*----------------------------------------------------------------------------*
 *                         Static variables                                   *
 *----------------------------------------------------------------------------*/
static const char *muse_wavecal_help =
  "This recipe detects arc emission lines and fits a wavelength solution to each slice of the instrument. The wavelength calibration table contains polynomials defining the wavelength solution of the slices on the CCD. Processing trims the raw data and records the overscan statistics, subtracts the bias (taking account of the overscan, if --overscan is not \"none\") and converts them from adu to count. Optionally, the dark can be subtracted and the data can be divided by the flat-field, but this is not recommended. The data is then combined using input parameters, into separate images for each lamp. To compute the wavelength solution, arc lines are detected at the center of each slice (using threshold detection on a S/N image) and subsequently assigned wavelengths, using pattern matching to identify lines from the input line catalog. Each line is then traced to the edges of the slice, using Gaussian centering in each CCD column. The Gaussians not only yield center, but also centering error, and line properties (e.g. FWHM). Deviant fits are detected using polynomial fits to each arc line (using the xorder parameter) and rejected. These analysis and measuring steps are carried out separately on images exposed by the different arc lamps, reducing the amount of blending, that can otherwise influence line identification and Gaussian centering. The final two-dimensional fit uses all positions (of all lamps), their wavelengths, and the given polynomial orders to compute the final wavelength solution for each slice, iteratively rejecting outliers. This final fit can be either unweighted (fitweighting=\"uniform\", for fastest processing) or weighted (other values of fitweighting, for higher accuracy).";

static const char *muse_wavecal_help_esorex =
  "\n\nInput frames for raw frame tag \"ARC\":\n"
  "\n Frame tag            Type Req #Fr Description"
  "\n -------------------- ---- --- --- ------------"
  "\n ARC                  raw   Y      Raw arc lamp exposures"
  "\n MASTER_BIAS          calib Y    1 Master bias"
  "\n MASTER_DARK          calib .    1 Master dark"
  "\n MASTER_FLAT          calib .    1 Master flat"
  "\n TRACE_TABLE          calib Y    1 Trace table"
  "\n LINE_CATALOG         calib Y    1 Arc line catalog"
  "\n BADPIX_TABLE         calib .      Known bad pixels"
  "\n\nProduct frames for raw frame tag \"ARC\":\n"
  "\n Frame tag            Level    Description"
  "\n -------------------- -------- ------------"
  "\n WAVECAL_TABLE        final    Wavelength calibration table"
  "\n WAVECAL_RESIDUALS    final    Fit residuals of all arc lines (if --residuals=true)"
  "\n ARC_RED_LAMP         final    Reduced ARC image, per lamp (if --saveimages=true)";

/*----------------------------------------------------------------------------*/
/**
  @private
  @brief   Create the recipe config for this plugin.

  @remark The recipe config is used to check for the tags as well as to create
          the documentation of this plugin.
 */
/*----------------------------------------------------------------------------*/
static cpl_recipeconfig *
muse_wavecal_new_recipeconfig(void)
{
  cpl_recipeconfig *recipeconfig = cpl_recipeconfig_new();
      
  cpl_recipeconfig_set_tag(recipeconfig, "ARC", 1, -1);
  cpl_recipeconfig_set_input(recipeconfig, "ARC", "MASTER_BIAS", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "ARC", "MASTER_DARK", -1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "ARC", "MASTER_FLAT", -1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "ARC", "TRACE_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "ARC", "LINE_CATALOG", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "ARC", "BADPIX_TABLE", -1, -1);
  cpl_recipeconfig_set_output(recipeconfig, "ARC", "WAVECAL_TABLE");
  cpl_recipeconfig_set_output(recipeconfig, "ARC", "WAVECAL_RESIDUALS");
  cpl_recipeconfig_set_output(recipeconfig, "ARC", "ARC_RED_LAMP");
    
  return recipeconfig;
} /* muse_wavecal_new_recipeconfig() */

/*----------------------------------------------------------------------------*/
/**
  @private
  @brief   Return a new header that shall be filled on output.
  @param   aFrametag   tag of the output frame
  @param   aHeader     the prepared FITS header
  @return  CPL_ERROR_NONE on success another cpl_error_code on error

  @remark This function is also used to generate the recipe documentation.
 */
/*----------------------------------------------------------------------------*/
static cpl_error_code
muse_wavecal_prepare_header(const char *aFrametag, cpl_propertylist *aHeader)
{
  cpl_ensure_code(aFrametag, CPL_ERROR_NULL_INPUT);
  cpl_ensure_code(aHeader, CPL_ERROR_NULL_INPUT);
  if (!strcmp(aFrametag, "WAVECAL_TABLE")) {
    muse_processing_prepare_property(aHeader, "ESO QC WAVECAL SLICE[0-9]+ LINES NDET",
                                     CPL_TYPE_INT,
                                     "Number of detected arc lines in slice j");
    muse_processing_prepare_property(aHeader, "ESO QC WAVECAL SLICE[0-9]+ LINES NID",
                                     CPL_TYPE_INT,
                                     "Number of identified arc lines in slice j");
    muse_processing_prepare_property(aHeader, "ESO QC WAVECAL SLICE[0-9]+ LINES PEAK MEAN",
                                     CPL_TYPE_FLOAT,
                                     "[count] Mean peak count level above background of detected arc lines in slice j");
    muse_processing_prepare_property(aHeader, "ESO QC WAVECAL SLICE[0-9]+ LINES PEAK STDEV",
                                     CPL_TYPE_FLOAT,
                                     "[count] Standard deviation of peak count level above background of detected arc lines in slice j");
    muse_processing_prepare_property(aHeader, "ESO QC WAVECAL SLICE[0-9]+ LINES PEAK MIN",
                                     CPL_TYPE_FLOAT,
                                     "[count] Peak count level above background of the faintest line in slice j");
    muse_processing_prepare_property(aHeader, "ESO QC WAVECAL SLICE[0-9]+ LINES PEAK MAX",
                                     CPL_TYPE_FLOAT,
                                     "[count] Peak count level above background of the brightest line in slice j");
    muse_processing_prepare_property(aHeader, "ESO QC WAVECAL SLICE[0-9]+ LAMP[0-9] LINES PEAK MEAN",
                                     CPL_TYPE_FLOAT,
                                     "[count] Mean peak count level of lines of lamp l above background of detected arc lines in slice j.");
    muse_processing_prepare_property(aHeader, "ESO QC WAVECAL SLICE[0-9]+ LAMP[0-9] LINES PEAK STDEV",
                                     CPL_TYPE_FLOAT,
                                     "[count] Standard deviation of peak count level of lines of lamp l above background of detected arc lines in slice j.");
    muse_processing_prepare_property(aHeader, "ESO QC WAVECAL SLICE[0-9]+ LAMP[0-9] LINES PEAK MAX",
                                     CPL_TYPE_FLOAT,
                                     "[count] Peak count level above background of the brightest line of lamp l in slice j.");
    muse_processing_prepare_property(aHeader, "ESO QC WAVECAL SLICE[0-9]+ LINES FWHM MEAN",
                                     CPL_TYPE_FLOAT,
                                     "Mean FWHM of detected arc lines in slice j");
    muse_processing_prepare_property(aHeader, "ESO QC WAVECAL SLICE[0-9]+ LINES FWHM STDEV",
                                     CPL_TYPE_FLOAT,
                                     "Standard deviation of FWHM of detected arc lines in slice j");
    muse_processing_prepare_property(aHeader, "ESO QC WAVECAL SLICE[0-9]+ LINES FWHM MIN",
                                     CPL_TYPE_FLOAT,
                                     "Minimum FWHM of detected arc lines in slice j");
    muse_processing_prepare_property(aHeader, "ESO QC WAVECAL SLICE[0-9]+ LINES FWHM MAX",
                                     CPL_TYPE_FLOAT,
                                     "Maximum FWHM of detected arc lines in slice j");
    muse_processing_prepare_property(aHeader, "ESO QC WAVECAL SLICE[0-9]+ RESOL",
                                     CPL_TYPE_FLOAT,
                                     "Mean spectral resolution R determined in slice j");
    muse_processing_prepare_property(aHeader, "ESO QC WAVECAL SLICE[0-9]+ FIT NLINES",
                                     CPL_TYPE_INT,
                                     "Number of arc lines used in calibration solution fit in slice j");
    muse_processing_prepare_property(aHeader, "ESO QC WAVECAL SLICE[0-9]+ FIT RMS",
                                     CPL_TYPE_FLOAT,
                                     "[Angstrom] RMS of the wavelength calibration fit in slice j");
    muse_processing_prepare_property(aHeader, "ESO QC WAVECAL SLICE[0-9]+ DWLEN BOTTOM",
                                     CPL_TYPE_FLOAT,
                                     "[Angstrom] Difference in wavelength computed for the bottom left and bottom right corners of the slice on the CCD");
    muse_processing_prepare_property(aHeader, "ESO QC WAVECAL SLICE[0-9]+ DWLEN TOP",
                                     CPL_TYPE_FLOAT,
                                     "[Angstrom] Difference in wavelength computed for the top left and top right corners of the slice on the CCD");
    muse_processing_prepare_property(aHeader, "ESO QC WAVECAL SLICE[0-9]+ WLPOS",
                                     CPL_TYPE_FLOAT,
                                     "[pix] Position of wavelength given in WLEN in slice j");
    muse_processing_prepare_property(aHeader, "ESO QC WAVECAL SLICE[0-9]+ WLEN",
                                     CPL_TYPE_FLOAT,
                                     "[Angstrom] Wavelength associated to WLPOS in slice j");
    muse_processing_prepare_property(aHeader, "ESO QC WAVECAL NSATURATED LAMP[0-9]",
                                     CPL_TYPE_INT,
                                     "Number of saturated pixels in output data of lamp l");
  } else if (!strcmp(aFrametag, "WAVECAL_RESIDUALS")) {
  } else if (!strcmp(aFrametag, "ARC_RED_LAMP")) {
    muse_processing_prepare_property(aHeader, "ESO QC WAVECAL INPUT[0-9]+ NSATURATED",
                                     CPL_TYPE_INT,
                                     "Number of saturated pixels in raw arc i in input list");
    muse_processing_prepare_property(aHeader, "ESO QC WAVECAL NSATURATED",
                                     CPL_TYPE_INT,
                                     "Number of saturated pixels in output data");
  } else {
    cpl_msg_warning(__func__, "Frame tag %s is not defined", aFrametag);
    return CPL_ERROR_ILLEGAL_INPUT;
  }
  return CPL_ERROR_NONE;
} /* muse_wavecal_prepare_header() */

/*----------------------------------------------------------------------------*/
/**
  @private
  @brief   Return the level of an output frame.
  @param   aFrametag   tag of the output frame
  @return  the cpl_frame_level or CPL_FRAME_LEVEL_NONE on error

  @remark This function is also used to generate the recipe documentation.
 */
/*----------------------------------------------------------------------------*/
static cpl_frame_level
muse_wavecal_get_frame_level(const char *aFrametag)
{
  if (!aFrametag) {
    return CPL_FRAME_LEVEL_NONE;
  }
  if (!strcmp(aFrametag, "WAVECAL_TABLE")) {
    return CPL_FRAME_LEVEL_FINAL;
  }
  if (!strcmp(aFrametag, "WAVECAL_RESIDUALS")) {
    return CPL_FRAME_LEVEL_FINAL;
  }
  if (!strcmp(aFrametag, "ARC_RED_LAMP")) {
    return CPL_FRAME_LEVEL_FINAL;
  }
  return CPL_FRAME_LEVEL_NONE;
} /* muse_wavecal_get_frame_level() */

/*----------------------------------------------------------------------------*/
/**
  @private
  @brief   Return the mode of an output frame.
  @param   aFrametag   tag of the output frame
  @return  the muse_frame_mode

  @remark This function is also used to generate the recipe documentation.
 */
/*----------------------------------------------------------------------------*/
static muse_frame_mode
muse_wavecal_get_frame_mode(const char *aFrametag)
{
  if (!aFrametag) {
    return MUSE_FRAME_MODE_ALL;
  }
  if (!strcmp(aFrametag, "WAVECAL_TABLE")) {
    return MUSE_FRAME_MODE_MASTER;
  }
  if (!strcmp(aFrametag, "WAVECAL_RESIDUALS")) {
    return MUSE_FRAME_MODE_MASTER;
  }
  if (!strcmp(aFrametag, "ARC_RED_LAMP")) {
    return MUSE_FRAME_MODE_SUBSET;
  }
  return MUSE_FRAME_MODE_ALL;
} /* muse_wavecal_get_frame_mode() */

/*----------------------------------------------------------------------------*/
/**
  @private
  @brief   Setup the recipe options.
  @param   aPlugin   the plugin
  @return  0 if everything is ok, -1 if not called as part of a recipe.

  Define the command-line, configuration, and environment parameters for the
  recipe.
 */
/*----------------------------------------------------------------------------*/
static int
muse_wavecal_create(cpl_plugin *aPlugin)
{
  /* Check that the plugin is part of a valid recipe */
  cpl_recipe *recipe;
  if (cpl_plugin_get_type(aPlugin) == CPL_PLUGIN_TYPE_RECIPE) {
    recipe = (cpl_recipe *)aPlugin;
  } else {
    return -1;
  }

  /* register the extended processing information (new FITS header creation, *
   * getting of the frame level for a certain tag)                           */
  muse_processinginfo_register(recipe,
                               muse_wavecal_new_recipeconfig(),
                               muse_wavecal_prepare_header,
                               muse_wavecal_get_frame_level,
                               muse_wavecal_get_frame_mode);

  /* XXX initialize timing in messages                                       *
   *     since at least esorex is too stupid to turn it on, we have to do it */
  if (muse_cplframework() == MUSE_CPLFRAMEWORK_ESOREX) {
    cpl_msg_set_time_on();
  }

  /* Create the parameter list in the cpl_recipe object */
  recipe->parameters = cpl_parameterlist_new();
  /* Fill the parameters list */
  cpl_parameter *p;
      
  /* --nifu: IFU to handle. If set to 0, all IFUs are processed serially. If set to -1, all IFUs are processed in parallel. */
  p = cpl_parameter_new_range("muse.muse_wavecal.nifu",
                              CPL_TYPE_INT,
                             "IFU to handle. If set to 0, all IFUs are processed serially. If set to -1, all IFUs are processed in parallel.",
                              "muse.muse_wavecal",
                              (int)0,
                              (int)-1,
                              (int)24);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "nifu");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "nifu");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --overscan: If this is "none", stop when detecting discrepant overscan levels (see ovscsigma), for "offset" it assumes that the mean overscan level represents the real offset in the bias levels of the exposures involved, and adjusts the data accordingly; for "vpoly", a polynomial is fit to the vertical overscan and subtracted from the whole quadrant. */
  p = cpl_parameter_new_value("muse.muse_wavecal.overscan",
                              CPL_TYPE_STRING,
                             "If this is \"none\", stop when detecting discrepant overscan levels (see ovscsigma), for \"offset\" it assumes that the mean overscan level represents the real offset in the bias levels of the exposures involved, and adjusts the data accordingly; for \"vpoly\", a polynomial is fit to the vertical overscan and subtracted from the whole quadrant.",
                              "muse.muse_wavecal",
                              (const char *)"vpoly");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "overscan");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "overscan");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --ovscreject: This influences how values are rejected when computing overscan statistics. Either no rejection at all ("none"), rejection using the DCR algorithm ("dcr"), or rejection using an iterative constant fit ("fit"). */
  p = cpl_parameter_new_value("muse.muse_wavecal.ovscreject",
                              CPL_TYPE_STRING,
                             "This influences how values are rejected when computing overscan statistics. Either no rejection at all (\"none\"), rejection using the DCR algorithm (\"dcr\"), or rejection using an iterative constant fit (\"fit\").",
                              "muse.muse_wavecal",
                              (const char *)"dcr");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "ovscreject");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "ovscreject");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --ovscsigma: If the deviation of mean overscan levels between a raw input image and the reference image is higher than |ovscsigma x stdev|, stop the processing. If overscan="vpoly", this is used as sigma rejection level for the iterative polynomial fit (the level comparison is then done afterwards with |100 x stdev| to guard against incompatible settings). Has no effect for overscan="offset". */
  p = cpl_parameter_new_value("muse.muse_wavecal.ovscsigma",
                              CPL_TYPE_DOUBLE,
                             "If the deviation of mean overscan levels between a raw input image and the reference image is higher than |ovscsigma x stdev|, stop the processing. If overscan=\"vpoly\", this is used as sigma rejection level for the iterative polynomial fit (the level comparison is then done afterwards with |100 x stdev| to guard against incompatible settings). Has no effect for overscan=\"offset\".",
                              "muse.muse_wavecal",
                              (double)30.);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "ovscsigma");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "ovscsigma");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --ovscignore: The number of pixels of the overscan adjacent to the data section of the CCD that are ignored when computing statistics or fits. */
  p = cpl_parameter_new_value("muse.muse_wavecal.ovscignore",
                              CPL_TYPE_INT,
                             "The number of pixels of the overscan adjacent to the data section of the CCD that are ignored when computing statistics or fits.",
                              "muse.muse_wavecal",
                              (int)3);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "ovscignore");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "ovscignore");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --combine: Type of lampwise image combination to use. */
  p = cpl_parameter_new_enum("muse.muse_wavecal.combine",
                             CPL_TYPE_STRING,
                             "Type of lampwise image combination to use.",
                             "muse.muse_wavecal",
                             (const char *)"sigclip",
                             4,
                             (const char *)"average",
                             (const char *)"median",
                             (const char *)"minmax",
                             (const char *)"sigclip");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "combine");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "combine");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --lampwise: Identify and measure the arc emission lines on images separately for each lamp setup. */
  p = cpl_parameter_new_value("muse.muse_wavecal.lampwise",
                              CPL_TYPE_BOOL,
                             "Identify and measure the arc emission lines on images separately for each lamp setup.",
                              "muse.muse_wavecal",
                              (int)TRUE);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "lampwise");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "lampwise");
  if (!getenv("MUSE_EXPERT_USER")) {
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_CLI);
  }

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --sigma: Sigma level used to detect arc emission lines above the median background level in the S/N image of the central column of each slice */
  p = cpl_parameter_new_value("muse.muse_wavecal.sigma",
                              CPL_TYPE_DOUBLE,
                             "Sigma level used to detect arc emission lines above the median background level in the S/N image of the central column of each slice",
                              "muse.muse_wavecal",
                              (double)1.0);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "sigma");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "sigma");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --dres: The allowed range of resolutions for pattern matching (of detected arc lines to line list) in fractions relative to the expected value */
  p = cpl_parameter_new_value("muse.muse_wavecal.dres",
                              CPL_TYPE_DOUBLE,
                             "The allowed range of resolutions for pattern matching (of detected arc lines to line list) in fractions relative to the expected value",
                              "muse.muse_wavecal",
                              (double)0.05);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "dres");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "dres");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --tolerance: Tolerance for pattern matching (of detected arc lines to line list) */
  p = cpl_parameter_new_value("muse.muse_wavecal.tolerance",
                              CPL_TYPE_DOUBLE,
                             "Tolerance for pattern matching (of detected arc lines to line list)",
                              "muse.muse_wavecal",
                              (double)0.1);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "tolerance");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "tolerance");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --xorder: Order of the polynomial for the horizontal curvature within each slice */
  p = cpl_parameter_new_value("muse.muse_wavecal.xorder",
                              CPL_TYPE_INT,
                             "Order of the polynomial for the horizontal curvature within each slice",
                              "muse.muse_wavecal",
                              (int)2);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "xorder");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "xorder");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --yorder: Order of the polynomial used to fit the dispersion relation */
  p = cpl_parameter_new_value("muse.muse_wavecal.yorder",
                              CPL_TYPE_INT,
                             "Order of the polynomial used to fit the dispersion relation",
                              "muse.muse_wavecal",
                              (int)6);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "yorder");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "yorder");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --linesigma: Sigma level for iterative rejection of deviant fits for each arc line within each slice, a negative value means to use the default (2.5). */
  p = cpl_parameter_new_value("muse.muse_wavecal.linesigma",
                              CPL_TYPE_DOUBLE,
                             "Sigma level for iterative rejection of deviant fits for each arc line within each slice, a negative value means to use the default (2.5).",
                              "muse.muse_wavecal",
                              (double)-1.0);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "linesigma");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "linesigma");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --residuals: Create a table containing residuals of the fits to the data of all arc lines. This is useful to assess the quality of the wavelength solution in detail. */
  p = cpl_parameter_new_value("muse.muse_wavecal.residuals",
                              CPL_TYPE_BOOL,
                             "Create a table containing residuals of the fits to the data of all arc lines. This is useful to assess the quality of the wavelength solution in detail.",
                              "muse.muse_wavecal",
                              (int)FALSE);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "residuals");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "residuals");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --fitsigma: Sigma level for iterative rejection of deviant datapoints during the final polynomial wavelength solution within each slice, a negative value means to use the default (3.0). */
  p = cpl_parameter_new_value("muse.muse_wavecal.fitsigma",
                              CPL_TYPE_DOUBLE,
                             "Sigma level for iterative rejection of deviant datapoints during the final polynomial wavelength solution within each slice, a negative value means to use the default (3.0).",
                              "muse.muse_wavecal",
                              (double)-1.0);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "fitsigma");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "fitsigma");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --fitweighting: Type of weighting to use in the final polynomial wavelength solution fit, using centroiding error estimate and/or scatter of each single line as estimates of its accuracy. */
  p = cpl_parameter_new_enum("muse.muse_wavecal.fitweighting",
                             CPL_TYPE_STRING,
                             "Type of weighting to use in the final polynomial wavelength solution fit, using centroiding error estimate and/or scatter of each single line as estimates of its accuracy.",
                             "muse.muse_wavecal",
                             (const char *)"cerrscatter",
                             4,
                             (const char *)"uniform",
                             (const char *)"cerr",
                             (const char *)"scatter",
                             (const char *)"cerrscatter");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "fitweighting");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "fitweighting");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --saveimages: Save  */
  p = cpl_parameter_new_value("muse.muse_wavecal.saveimages",
                              CPL_TYPE_BOOL,
                             "Save",
                              "muse.muse_wavecal",
                              (int)FALSE);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "saveimages");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "saveimages");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --resample: Resample the input arc images onto 2D images for a visual check using tracing and wavelength calibration solutions. Note that the image produced will show small wiggles even when the calibration was successful! */
  p = cpl_parameter_new_value("muse.muse_wavecal.resample",
                              CPL_TYPE_BOOL,
                             "Resample the input arc images onto 2D images for a visual check using tracing and wavelength calibration solutions. Note that the image produced will show small wiggles even when the calibration was successful!",
                              "muse.muse_wavecal",
                              (int)FALSE);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "resample");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "resample");
  if (!getenv("MUSE_EXPERT_USER")) {
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_CLI);
  }

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --wavemap: Create a wavelength map of the input images */
  p = cpl_parameter_new_value("muse.muse_wavecal.wavemap",
                              CPL_TYPE_BOOL,
                             "Create a wavelength map of the input images",
                              "muse.muse_wavecal",
                              (int)FALSE);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "wavemap");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "wavemap");
  if (!getenv("MUSE_EXPERT_USER")) {
    cpl_parameter_disable(p, CPL_PARAMETER_MODE_CLI);
  }

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --merge: Merge output products from different IFUs into a common file. */
  p = cpl_parameter_new_value("muse.muse_wavecal.merge",
                              CPL_TYPE_BOOL,
                             "Merge output products from different IFUs into a common file.",
                              "muse.muse_wavecal",
                              (int)FALSE);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "merge");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "merge");

  cpl_parameterlist_append(recipe->parameters, p);
    
  return 0;
} /* muse_wavecal_create() */

/*----------------------------------------------------------------------------*/
/**
  @private
  @brief   Fill the recipe parameters into the parameter structure
  @param   aParams       the recipe-internal structure to fill
  @param   aParameters   the cpl_parameterlist with the parameters
  @return  0 if everything is ok, -1 if something went wrong.

  This is a convienience function that centrally fills all parameters into the
  according fields of the recipe internal structure.
 */
/*----------------------------------------------------------------------------*/
static int
muse_wavecal_params_fill(muse_wavecal_params_t *aParams, cpl_parameterlist *aParameters)
{
  cpl_ensure_code(aParams, CPL_ERROR_NULL_INPUT);
  cpl_ensure_code(aParameters, CPL_ERROR_NULL_INPUT);
  cpl_parameter *p;
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_wavecal.nifu");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->nifu = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_wavecal.overscan");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->overscan = cpl_parameter_get_string(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_wavecal.ovscreject");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->ovscreject = cpl_parameter_get_string(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_wavecal.ovscsigma");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->ovscsigma = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_wavecal.ovscignore");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->ovscignore = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_wavecal.combine");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->combine_s = cpl_parameter_get_string(p);
  aParams->combine =
    (!strcasecmp(aParams->combine_s, "average")) ? MUSE_WAVECAL_PARAM_COMBINE_AVERAGE :
    (!strcasecmp(aParams->combine_s, "median")) ? MUSE_WAVECAL_PARAM_COMBINE_MEDIAN :
    (!strcasecmp(aParams->combine_s, "minmax")) ? MUSE_WAVECAL_PARAM_COMBINE_MINMAX :
    (!strcasecmp(aParams->combine_s, "sigclip")) ? MUSE_WAVECAL_PARAM_COMBINE_SIGCLIP :
      MUSE_WAVECAL_PARAM_COMBINE_INVALID_VALUE;
  cpl_ensure_code(aParams->combine != MUSE_WAVECAL_PARAM_COMBINE_INVALID_VALUE,
                  CPL_ERROR_ILLEGAL_INPUT);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_wavecal.lampwise");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->lampwise = cpl_parameter_get_bool(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_wavecal.sigma");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->sigma = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_wavecal.dres");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->dres = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_wavecal.tolerance");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->tolerance = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_wavecal.xorder");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->xorder = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_wavecal.yorder");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->yorder = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_wavecal.linesigma");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->linesigma = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_wavecal.residuals");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->residuals = cpl_parameter_get_bool(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_wavecal.fitsigma");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->fitsigma = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_wavecal.fitweighting");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->fitweighting_s = cpl_parameter_get_string(p);
  aParams->fitweighting =
    (!strcasecmp(aParams->fitweighting_s, "uniform")) ? MUSE_WAVECAL_PARAM_FITWEIGHTING_UNIFORM :
    (!strcasecmp(aParams->fitweighting_s, "cerr")) ? MUSE_WAVECAL_PARAM_FITWEIGHTING_CERR :
    (!strcasecmp(aParams->fitweighting_s, "scatter")) ? MUSE_WAVECAL_PARAM_FITWEIGHTING_SCATTER :
    (!strcasecmp(aParams->fitweighting_s, "cerrscatter")) ? MUSE_WAVECAL_PARAM_FITWEIGHTING_CERRSCATTER :
      MUSE_WAVECAL_PARAM_FITWEIGHTING_INVALID_VALUE;
  cpl_ensure_code(aParams->fitweighting != MUSE_WAVECAL_PARAM_FITWEIGHTING_INVALID_VALUE,
                  CPL_ERROR_ILLEGAL_INPUT);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_wavecal.saveimages");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->saveimages = cpl_parameter_get_bool(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_wavecal.resample");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->resample = cpl_parameter_get_bool(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_wavecal.wavemap");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->wavemap = cpl_parameter_get_bool(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_wavecal.merge");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->merge = cpl_parameter_get_bool(p);
    
  return 0;
} /* muse_wavecal_params_fill() */

/*----------------------------------------------------------------------------*/
/**
  @private
  @brief    Execute the plugin instance given by the interface
  @param    aPlugin   the plugin
  @return   0 if everything is ok, -1 if not called as part of a recipe
 */
/*----------------------------------------------------------------------------*/
static int
muse_wavecal_exec(cpl_plugin *aPlugin)
{
  if (cpl_plugin_get_type(aPlugin) != CPL_PLUGIN_TYPE_RECIPE) {
    return -1;
  }
  muse_processing_recipeinfo(aPlugin);
  cpl_recipe *recipe = (cpl_recipe *)aPlugin;
  cpl_msg_set_threadid_on();

  cpl_frameset *usedframes = cpl_frameset_new(),
               *outframes = cpl_frameset_new();
  muse_wavecal_params_t params;
  muse_wavecal_params_fill(&params, recipe->parameters);

  cpl_errorstate prestate = cpl_errorstate_get();

  if (params.nifu < -1 || params.nifu > kMuseNumIFUs) {
    cpl_msg_error(__func__, "Please specify a valid IFU number (between 1 and "
                  "%d), 0 (to process all IFUs consecutively), or -1 (to "
                  "process all IFUs in parallel) using --nifu.", kMuseNumIFUs);
    return -1;
  } /* if invalid params.nifu */

  cpl_boolean donotmerge = CPL_FALSE; /* depending on nifu we may not merge */
  int rc = 0;
  if (params.nifu > 0) {
    muse_processing *proc = muse_processing_new("muse_wavecal",
                                                recipe);
    rc = muse_wavecal_compute(proc, &params);
    cpl_frameset_join(usedframes, proc->usedframes);
    cpl_frameset_join(outframes, proc->outframes);
    muse_processing_delete(proc);
    donotmerge = CPL_TRUE; /* after processing one IFU, merging cannot work */
  } else if (params.nifu < 0) { /* parallel processing */
    int *rcs = cpl_calloc(kMuseNumIFUs, sizeof(int));
    int nifu;
    #pragma omp parallel for default(none)                                     \
            shared(outframes, params, rcs, recipe, usedframes)
    for (nifu = 1; nifu <= kMuseNumIFUs; nifu++) {
      muse_processing *proc = muse_processing_new("muse_wavecal",
                                                  recipe);
      muse_wavecal_params_t *pars = cpl_malloc(sizeof(muse_wavecal_params_t));
      memcpy(pars, &params, sizeof(muse_wavecal_params_t));
      pars->nifu = nifu;
      int *rci = rcs + (nifu - 1);
      *rci = muse_wavecal_compute(proc, pars);
      if (rci && (int)cpl_error_get_code() == MUSE_ERROR_CHIP_NOT_LIVE) {
        *rci = 0;
      }
      cpl_free(pars);
      #pragma omp critical(muse_processing_used_frames)
      cpl_frameset_join(usedframes, proc->usedframes);
      #pragma omp critical(muse_processing_output_frames)
      cpl_frameset_join(outframes, proc->outframes);
      muse_processing_delete(proc);
    } /* for nifu */
    /* non-parallel loop to propagate the "worst" return code;       *
     * since we only ever return -1, any non-zero code is propagated */
    for (nifu = 1; nifu <= kMuseNumIFUs; nifu++) {
      if (rcs[nifu-1] != 0) {
        rc = rcs[nifu-1];
      } /* if */
    } /* for nifu */
    cpl_free(rcs);
  } else { /* serial processing */
    for (params.nifu = 1; params.nifu <= kMuseNumIFUs && !rc; params.nifu++) {
      muse_processing *proc = muse_processing_new("muse_wavecal",
                                                  recipe);
      rc = muse_wavecal_compute(proc, &params);
      if (rc && (int)cpl_error_get_code() == MUSE_ERROR_CHIP_NOT_LIVE) {
        rc = 0;
      }
      cpl_frameset_join(usedframes, proc->usedframes);
      cpl_frameset_join(outframes, proc->outframes);
      muse_processing_delete(proc);
    } /* for nifu */
  } /* else */
  UNUSED_ARGUMENT(donotmerge); /* maybe this is not going to be used below */

  if (!cpl_errorstate_is_equal(prestate)) {
    /* dump all errors from this recipe in chronological order */
    cpl_errorstate_dump(prestate, CPL_FALSE, muse_cplerrorstate_dump_some);
    /* reset message level to not get the same errors displayed again by esorex */
    cpl_msg_set_level(CPL_MSG_INFO);
  }
  /* clean up duplicates in framesets of used and output frames */
  muse_cplframeset_erase_duplicate(usedframes);
  muse_cplframeset_erase_duplicate(outframes);

  /* merge output products from the up to 24 IFUs */
  if (params.merge && !donotmerge) {
    muse_utils_frameset_merge_frames(outframes, CPL_TRUE);
  }

  /* to get esorex to see our classification (frame groups etc.), *
   * replace the original frameset with the list of used frames   *
   * before appending product output frames                       */
  /* keep the same pointer, so just erase all frames, not delete the frameset */
  muse_cplframeset_erase_all(recipe->frames);
  cpl_frameset_join(recipe->frames, usedframes);
  cpl_frameset_join(recipe->frames, outframes);
  cpl_frameset_delete(usedframes);
  cpl_frameset_delete(outframes);
  return rc;
} /* muse_wavecal_exec() */

/*----------------------------------------------------------------------------*/
/**
  @private
  @brief    Destroy what has been created by the 'create' function
  @param    aPlugin   the plugin
  @return   0 if everything is ok, -1 if not called as part of a recipe
 */
/*----------------------------------------------------------------------------*/
static int
muse_wavecal_destroy(cpl_plugin *aPlugin)
{
  /* Get the recipe from the plugin */
  cpl_recipe *recipe;
  if (cpl_plugin_get_type(aPlugin) == CPL_PLUGIN_TYPE_RECIPE) {
    recipe = (cpl_recipe *)aPlugin;
  } else {
    return -1;
  }

  /* Clean up */
  cpl_parameterlist_delete(recipe->parameters);
  muse_processinginfo_delete(recipe);
  return 0;
} /* muse_wavecal_destroy() */

/*----------------------------------------------------------------------------*/
/**
  @private
  @brief    Add this recipe to the list of available plugins.
  @param    aList   the plugin list
  @return   0 if everything is ok, -1 otherwise (but this cannot happen)

  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 *aList)
{
  cpl_recipe *recipe = cpl_calloc(1, sizeof *recipe);
  cpl_plugin *plugin = &recipe->interface;

  char *helptext;
  if (muse_cplframework() == MUSE_CPLFRAMEWORK_ESOREX) {
    helptext = cpl_sprintf("%s%s", muse_wavecal_help,
                           muse_wavecal_help_esorex);
  } else {
    helptext = cpl_sprintf("%s", muse_wavecal_help);
  }

  /* Initialize the CPL plugin stuff for this module */
  cpl_plugin_init(plugin, CPL_PLUGIN_API, MUSE_BINARY_VERSION,
                  CPL_PLUGIN_TYPE_RECIPE,
                  "muse_wavecal",
                  "Detect arc emission lines and determine the wavelength solution for each slice.",
                  helptext,
                  "Peter Weilbacher",
                  "usd-help@eso.org",
                  muse_get_license(),
                  muse_wavecal_create,
                  muse_wavecal_exec,
                  muse_wavecal_destroy);
  cpl_pluginlist_append(aList, plugin);
  cpl_free(helptext);

  return 0;
} /* cpl_plugin_get_info() */

/**@}*/