/* -*- 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_standard_z.h" /* in turn includes muse.h */

/*----------------------------------------------------------------------------*/
/**
  @defgroup recipe_muse_standard         Recipe muse_standard: Create a flux response curve from a standard star exposure.
  @author Peter Weilbacher
  
        Merge pixel tables from all IFUs and correct for differential
        atmospheric refraction.

        To derive the flux response curve, integrate the flux of all objects
        detected within the field of view using the given profile. Select one
        object as the standard star (either the brightest or the one nearest
        one, depending on --select) and compare its measured fluxes to
        tabulated fluxes to derive the sensitivity over wavelength. Postprocess
        this sensitivity curve to mark wavelength ranges affected by telluric
        absorption. Interpolate over the telluric regions and derive a telluric
        correction spectrum for them. The final response cuve is then linearly
        extrapolated to the largest possible MUSE wavelength range and smoothed
        (with the method given by --smooth). The derivation of the telluric
        correction spectrum assumes that the star has a smooth spectrum within
        the telluric regions.

        If there are more than one exposure given in the input data, the
        derivation of the flux response and telluric corrections are done
        separately for each exposure. For each exposure, an image containing
        the extracted stellar spectra and the datacube used for
        flux integration are saved, together with collapsed images for each given
        filter.
      
 */
/*----------------------------------------------------------------------------*/
/**@{*/

/*----------------------------------------------------------------------------*
 *                         Static variables                                   *
 *----------------------------------------------------------------------------*/
static const char *muse_standard_help =
  "Merge pixel tables from all IFUs and correct for differential atmospheric refraction. To derive the flux response curve, integrate the flux of all objects detected within the field of view using the given profile. Select one object as the standard star (either the brightest or the one nearest one, depending on --select) and compare its measured fluxes to tabulated fluxes to derive the sensitivity over wavelength. Postprocess this sensitivity curve to mark wavelength ranges affected by telluric absorption. Interpolate over the telluric regions and derive a telluric correction spectrum for them. The final response cuve is then linearly extrapolated to the largest possible MUSE wavelength range and smoothed (with the method given by --smooth). The derivation of the telluric correction spectrum assumes that the star has a smooth spectrum within the telluric regions. If there are more than one exposure given in the input data, the derivation of the flux response and telluric corrections are done separately for each exposure. For each exposure, an image containing the extracted stellar spectra and the datacube used for flux integration are saved, together with collapsed images for each given filter.";

static const char *muse_standard_help_esorex =
  "\n\nInput frames for raw frame tag \"PIXTABLE_STD\":\n"
  "\n Frame tag            Type Req #Fr Description"
  "\n -------------------- ---- --- --- ------------"
  "\n PIXTABLE_STD         raw   Y      Pixel table of a standard star field"
  "\n EXTINCT_TABLE        calib Y    1 Atmospheric extinction table"
  "\n STD_FLUX_TABLE       calib Y      Flux reference table for standard stars"
  "\n TELLURIC_REGIONS     calib .    1 Definition of telluric regions"
  "\n FILTER_LIST          calib .    1 File to be used to create field-of-view images."
  "\n\nProduct frames for raw frame tag \"PIXTABLE_STD\":\n"
  "\n Frame tag            Level    Description"
  "\n -------------------- -------- ------------"
  "\n DATACUBE_STD         final    Reduced standard star field exposure"
  "\n STD_FLUXES           final    The integrated flux per wavelength of all detected sources"
  "\n STD_RESPONSE         final    Response curve as derived from standard star(s)"
  "\n STD_TELLURIC         final    Telluric absorption as derived from standard star(s)";

/*----------------------------------------------------------------------------*/
/**
  @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_standard_new_recipeconfig(void)
{
  cpl_recipeconfig *recipeconfig = cpl_recipeconfig_new();
      
  cpl_recipeconfig_set_tag(recipeconfig, "PIXTABLE_STD", 1, -1);
  cpl_recipeconfig_set_input(recipeconfig, "PIXTABLE_STD", "EXTINCT_TABLE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "PIXTABLE_STD", "STD_FLUX_TABLE", 1, -1);
  cpl_recipeconfig_set_input(recipeconfig, "PIXTABLE_STD", "TELLURIC_REGIONS", -1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "PIXTABLE_STD", "FILTER_LIST", -1, 1);
  cpl_recipeconfig_set_output(recipeconfig, "PIXTABLE_STD", "DATACUBE_STD");
  cpl_recipeconfig_set_output(recipeconfig, "PIXTABLE_STD", "STD_FLUXES");
  cpl_recipeconfig_set_output(recipeconfig, "PIXTABLE_STD", "STD_RESPONSE");
  cpl_recipeconfig_set_output(recipeconfig, "PIXTABLE_STD", "STD_TELLURIC");
    
  return recipeconfig;
} /* muse_standard_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_standard_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, "DATACUBE_STD")) {
    muse_processing_prepare_property(aHeader, "ESO QC STANDARD NDET",
                                     CPL_TYPE_INT,
                                     "Number of detected sources in output cube.");
    muse_processing_prepare_property(aHeader, "ESO QC STANDARD LAMBDA",
                                     CPL_TYPE_FLOAT,
                                     "[Angstrom] Wavelength of plane in combined cube that was used for object detection.");
    muse_processing_prepare_property(aHeader, "ESO QC STANDARD POS[0-9]+ X",
                                     CPL_TYPE_FLOAT,
                                     "[pix] Position of source k in x-direction in output cube. If the FWHM measurement fails, this value will be -1.");
    muse_processing_prepare_property(aHeader, "ESO QC STANDARD POS[0-9]+ Y",
                                     CPL_TYPE_FLOAT,
                                     "[pix] Position of source k in y-direction in output cube. If the FWHM measurement fails, this value will be -1.");
    muse_processing_prepare_property(aHeader, "ESO QC STANDARD FWHM[0-9]+ X",
                                     CPL_TYPE_FLOAT,
                                     "[arcsec] FWHM of source k in x-direction in output cube. If the FWHM measurement fails, this value will be -1.");
    muse_processing_prepare_property(aHeader, "ESO QC STANDARD FWHM[0-9]+ Y",
                                     CPL_TYPE_FLOAT,
                                     "[arcsec] FWHM of source k in y-direction in output cube. If the FWHM measurement fails, this value will be -1.");
    muse_processing_prepare_property(aHeader, "ESO QC STANDARD FWHM NVALID",
                                     CPL_TYPE_INT,
                                     "Number of detected sources with valid FWHM in output cube.");
    muse_processing_prepare_property(aHeader, "ESO QC STANDARD FWHM MEDIAN",
                                     CPL_TYPE_FLOAT,
                                     "[arcsec] Median FWHM of all sources with valid FWHM measurement (in x- and y-direction) in output cube. If less than three sources with valid FWHM are detected, this value is zero.");
    muse_processing_prepare_property(aHeader, "ESO QC STANDARD FWHM MAD",
                                     CPL_TYPE_FLOAT,
                                     "[arcsec] Median absolute deviation of the FWHM of all sources with valid FWHM measurement (in x- and y-direction) in output cube. If less than three sources with valid FWHM are detected, this value is zero.");
  } else if (!strcmp(aFrametag, "STD_FLUXES")) {
  } else if (!strcmp(aFrametag, "STD_RESPONSE")) {
    muse_processing_prepare_property(aHeader, "ESO QC STANDARD STARNAME",
                                     CPL_TYPE_STRING,
                                     "Name of the standard star used for the throughput / zeropoint calculation.");
    muse_processing_prepare_property(aHeader, "ESO QC STANDARD THRU5000",
                                     CPL_TYPE_FLOAT,
                                     "Throughput computed at 5000 +/- 100 Angstrom.");
    muse_processing_prepare_property(aHeader, "ESO QC STANDARD THRU7000",
                                     CPL_TYPE_FLOAT,
                                     "Throughput computed at 7000 +/- 100 Angstrom.");
    muse_processing_prepare_property(aHeader, "ESO QC STANDARD THRU8000",
                                     CPL_TYPE_FLOAT,
                                     "Throughput computed at 8000 +/- 100 Angstrom.");
    muse_processing_prepare_property(aHeader, "ESO QC STANDARD THRU9000",
                                     CPL_TYPE_FLOAT,
                                     "Throughput computed at 9000 +/- 100 Angstrom.");
    muse_processing_prepare_property(aHeader, "ESO QC STANDARD ZP V",
                                     CPL_TYPE_FLOAT,
                                     "[mag] Zeropoint in Johnson V filter. zp = -2.5 log10(fobs_V / fref_V), where fobs_V was integrated over the filter curve and converted to f_lambda using the known effective VLT area. (optional) Only computed if FILTER_LIST and corresponding --filter is given.");
    muse_processing_prepare_property(aHeader, "ESO QC STANDARD ZP R",
                                     CPL_TYPE_FLOAT,
                                     "[mag] Zeropoint in Cousins R filter. zp = -2.5 log10(fobs_R / fref_R), where fobs_R was integrated over the filter curve and converted to f_lambda using the known effective VLT area. (optional) Only computed if FILTER_LIST and corresponding --filter is given.");
    muse_processing_prepare_property(aHeader, "ESO QC STANDARD ZP I",
                                     CPL_TYPE_FLOAT,
                                     "[mag] Zeropoint in Cousins I filter. zp = -2.5 log10(fobs_I / fref_I), where fobs_I was integrated over the filter curve and converted to f_lambda using the known effective VLT area. (optional) Only computed if FILTER_LIST and corresponding --filter is given.");
  } else if (!strcmp(aFrametag, "STD_TELLURIC")) {
  } else {
    cpl_msg_warning(__func__, "Frame tag %s is not defined", aFrametag);
    return CPL_ERROR_ILLEGAL_INPUT;
  }
  return CPL_ERROR_NONE;
} /* muse_standard_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_standard_get_frame_level(const char *aFrametag)
{
  if (!aFrametag) {
    return CPL_FRAME_LEVEL_NONE;
  }
  if (!strcmp(aFrametag, "DATACUBE_STD")) {
    return CPL_FRAME_LEVEL_FINAL;
  }
  if (!strcmp(aFrametag, "STD_FLUXES")) {
    return CPL_FRAME_LEVEL_FINAL;
  }
  if (!strcmp(aFrametag, "STD_RESPONSE")) {
    return CPL_FRAME_LEVEL_FINAL;
  }
  if (!strcmp(aFrametag, "STD_TELLURIC")) {
    return CPL_FRAME_LEVEL_FINAL;
  }
  return CPL_FRAME_LEVEL_NONE;
} /* muse_standard_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_standard_get_frame_mode(const char *aFrametag)
{
  if (!aFrametag) {
    return MUSE_FRAME_MODE_ALL;
  }
  if (!strcmp(aFrametag, "DATACUBE_STD")) {
    return MUSE_FRAME_MODE_DATEOBS;
  }
  if (!strcmp(aFrametag, "STD_FLUXES")) {
    return MUSE_FRAME_MODE_DATEOBS;
  }
  if (!strcmp(aFrametag, "STD_RESPONSE")) {
    return MUSE_FRAME_MODE_DATEOBS;
  }
  if (!strcmp(aFrametag, "STD_TELLURIC")) {
    return MUSE_FRAME_MODE_DATEOBS;
  }
  return MUSE_FRAME_MODE_ALL;
} /* muse_standard_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_standard_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_standard_new_recipeconfig(),
                               muse_standard_prepare_header,
                               muse_standard_get_frame_level,
                               muse_standard_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;
      
  /* --profile: Type of flux integration to use. "gaussian" and "moffat" use 2D profile fitting, circle and square are non-optimal flux integrators. */
  p = cpl_parameter_new_enum("muse.muse_standard.profile",
                             CPL_TYPE_STRING,
                             "Type of flux integration to use. \"gaussian\" and \"moffat\" use 2D profile fitting, circle and square are non-optimal flux integrators.",
                             "muse.muse_standard",
                             (const char *)"moffat",
                             4,
                             (const char *)"gaussian",
                             (const char *)"moffat",
                             (const char *)"circle",
                             (const char *)"square");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "profile");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "profile");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --select: How to select the star for flux integration, "flux" uses the brightest star in the field, "distance" uses the detection nearest to the approximate coordinates of the reference source. */
  p = cpl_parameter_new_enum("muse.muse_standard.select",
                             CPL_TYPE_STRING,
                             "How to select the star for flux integration, \"flux\" uses the brightest star in the field, \"distance\" uses the detection nearest to the approximate coordinates of the reference source.",
                             "muse.muse_standard",
                             (const char *)"distance",
                             2,
                             (const char *)"flux",
                             (const char *)"distance");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "select");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "select");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --smooth: How to smooth the response curve before writing it to disk.  "none" does not do any kind of smoothing (such a response curve is only useful, if smoothed externally; "median" does a median-filter of 15 Angstrom half-width; "ppoly" fits piecewise cubic polynomials (each one across 2x150 Angstrom width) postprocessed by a sliding average filter of 15 Angstrom half-width. */
  p = cpl_parameter_new_enum("muse.muse_standard.smooth",
                             CPL_TYPE_STRING,
                             "How to smooth the response curve before writing it to disk. \"none\" does not do any kind of smoothing (such a response curve is only useful, if smoothed externally; \"median\" does a median-filter of 15 Angstrom half-width; \"ppoly\" fits piecewise cubic polynomials (each one across 2x150 Angstrom width) postprocessed by a sliding average filter of 15 Angstrom half-width.",
                             "muse.muse_standard",
                             (const char *)"ppoly",
                             3,
                             (const char *)"none",
                             (const char *)"median",
                             (const char *)"ppoly");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "smooth");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "smooth");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --lambdamin: Cut off the data below this wavelength after loading the pixel table(s). */
  p = cpl_parameter_new_value("muse.muse_standard.lambdamin",
                              CPL_TYPE_DOUBLE,
                             "Cut off the data below this wavelength after loading the pixel table(s).",
                              "muse.muse_standard",
                              (double)4000.);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "lambdamin");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "lambdamin");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --lambdamax: Cut off the data above this wavelength after loading the pixel table(s). */
  p = cpl_parameter_new_value("muse.muse_standard.lambdamax",
                              CPL_TYPE_DOUBLE,
                             "Cut off the data above this wavelength after loading the pixel table(s).",
                              "muse.muse_standard",
                              (double)10000.);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "lambdamax");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "lambdamax");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --lambdaref: Reference wavelength used for correction of differential atmospheric refraction. The R-band (peak wavelength ~7000 Angstrom) that is usually used for guiding, is close to the central wavelength of MUSE, so a value of 7000.0 Angstrom should be used if nothing else is known. A value less than zero switches DAR correction off. */
  p = cpl_parameter_new_value("muse.muse_standard.lambdaref",
                              CPL_TYPE_DOUBLE,
                             "Reference wavelength used for correction of differential atmospheric refraction. The R-band (peak wavelength ~7000 Angstrom) that is usually used for guiding, is close to the central wavelength of MUSE, so a value of 7000.0 Angstrom should be used if nothing else is known. A value less than zero switches DAR correction off.",
                              "muse.muse_standard",
                              (double)7000.);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "lambdaref");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "lambdaref");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --darcheck: Carry out a check of the theoretical DAR correction using source centroiding. If "correct" it will also apply an empirical correction. */
  p = cpl_parameter_new_enum("muse.muse_standard.darcheck",
                             CPL_TYPE_STRING,
                             "Carry out a check of the theoretical DAR correction using source centroiding. If \"correct\" it will also apply an empirical correction.",
                             "muse.muse_standard",
                             (const char *)"none",
                             3,
                             (const char *)"none",
                             (const char *)"check",
                             (const char *)"correct");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "darcheck");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "darcheck");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --filter: The filter name(s) to be used for the output field-of-view image. Each name has to correspond to an EXTNAME in an extension of the FILTER_LIST file. If an unsupported filter name is given, creation of the respective image is omitted. If multiple filter names are given, they have to be comma separated. If the zeropoint QC parameters are wanted, make sure to add "Johnson_V,Cousins_R,Cousins_I". */
  p = cpl_parameter_new_value("muse.muse_standard.filter",
                              CPL_TYPE_STRING,
                             "The filter name(s) to be used for the output field-of-view image. Each name has to correspond to an EXTNAME in an extension of the FILTER_LIST file. If an unsupported filter name is given, creation of the respective image is omitted. If multiple filter names are given, they have to be comma separated. If the zeropoint QC parameters are wanted, make sure to add \"Johnson_V,Cousins_R,Cousins_I\".",
                              "muse.muse_standard",
                              (const char *)"white");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "filter");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "filter");

  cpl_parameterlist_append(recipe->parameters, p);
    
  return 0;
} /* muse_standard_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_standard_params_fill(muse_standard_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_standard.profile");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->profile_s = cpl_parameter_get_string(p);
  aParams->profile =
    (!strcasecmp(aParams->profile_s, "gaussian")) ? MUSE_STANDARD_PARAM_PROFILE_GAUSSIAN :
    (!strcasecmp(aParams->profile_s, "moffat")) ? MUSE_STANDARD_PARAM_PROFILE_MOFFAT :
    (!strcasecmp(aParams->profile_s, "circle")) ? MUSE_STANDARD_PARAM_PROFILE_CIRCLE :
    (!strcasecmp(aParams->profile_s, "square")) ? MUSE_STANDARD_PARAM_PROFILE_SQUARE :
      MUSE_STANDARD_PARAM_PROFILE_INVALID_VALUE;
  cpl_ensure_code(aParams->profile != MUSE_STANDARD_PARAM_PROFILE_INVALID_VALUE,
                  CPL_ERROR_ILLEGAL_INPUT);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_standard.select");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->select_s = cpl_parameter_get_string(p);
  aParams->select =
    (!strcasecmp(aParams->select_s, "flux")) ? MUSE_STANDARD_PARAM_SELECT_FLUX :
    (!strcasecmp(aParams->select_s, "distance")) ? MUSE_STANDARD_PARAM_SELECT_DISTANCE :
      MUSE_STANDARD_PARAM_SELECT_INVALID_VALUE;
  cpl_ensure_code(aParams->select != MUSE_STANDARD_PARAM_SELECT_INVALID_VALUE,
                  CPL_ERROR_ILLEGAL_INPUT);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_standard.smooth");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->smooth_s = cpl_parameter_get_string(p);
  aParams->smooth =
    (!strcasecmp(aParams->smooth_s, "none")) ? MUSE_STANDARD_PARAM_SMOOTH_NONE :
    (!strcasecmp(aParams->smooth_s, "median")) ? MUSE_STANDARD_PARAM_SMOOTH_MEDIAN :
    (!strcasecmp(aParams->smooth_s, "ppoly")) ? MUSE_STANDARD_PARAM_SMOOTH_PPOLY :
      MUSE_STANDARD_PARAM_SMOOTH_INVALID_VALUE;
  cpl_ensure_code(aParams->smooth != MUSE_STANDARD_PARAM_SMOOTH_INVALID_VALUE,
                  CPL_ERROR_ILLEGAL_INPUT);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_standard.lambdamin");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->lambdamin = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_standard.lambdamax");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->lambdamax = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_standard.lambdaref");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->lambdaref = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_standard.darcheck");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->darcheck_s = cpl_parameter_get_string(p);
  aParams->darcheck =
    (!strcasecmp(aParams->darcheck_s, "none")) ? MUSE_STANDARD_PARAM_DARCHECK_NONE :
    (!strcasecmp(aParams->darcheck_s, "check")) ? MUSE_STANDARD_PARAM_DARCHECK_CHECK :
    (!strcasecmp(aParams->darcheck_s, "correct")) ? MUSE_STANDARD_PARAM_DARCHECK_CORRECT :
      MUSE_STANDARD_PARAM_DARCHECK_INVALID_VALUE;
  cpl_ensure_code(aParams->darcheck != MUSE_STANDARD_PARAM_DARCHECK_INVALID_VALUE,
                  CPL_ERROR_ILLEGAL_INPUT);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_standard.filter");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->filter = cpl_parameter_get_string(p);
    
  return 0;
} /* muse_standard_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_standard_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_standard_params_t params;
  muse_standard_params_fill(&params, recipe->parameters);

  cpl_errorstate prestate = cpl_errorstate_get();

  muse_processing *proc = muse_processing_new("muse_standard",
                                              recipe);
  int rc = muse_standard_compute(proc, &params);
  cpl_frameset_join(usedframes, proc->usedframes);
  cpl_frameset_join(outframes, proc->outframes);
  muse_processing_delete(proc);
  
  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);

  /* 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_standard_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_standard_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_standard_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_standard_help,
                           muse_standard_help_esorex);
  } else {
    helptext = cpl_sprintf("%s", muse_standard_help);
  }

  /* Initialize the CPL plugin stuff for this module */
  cpl_plugin_init(plugin, CPL_PLUGIN_API, MUSE_BINARY_VERSION,
                  CPL_PLUGIN_TYPE_RECIPE,
                  "muse_standard",
                  "Create a flux response curve from a standard star exposure.",
                  helptext,
                  "Peter Weilbacher",
                  "usd-help@eso.org",
                  muse_get_license(),
                  muse_standard_create,
                  muse_standard_exec,
                  muse_standard_destroy);
  cpl_pluginlist_append(aList, plugin);
  cpl_free(helptext);

  return 0;
} /* cpl_plugin_get_info() */

/**@}*/