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

/*----------------------------------------------------------------------------*/
/**
  @defgroup recipe_muse_astrometry         Recipe muse_astrometry: Compute an astrometric solution.
  @author Peter Weilbacher
  
        Merge pixel tables from all IFUs, apply correction for differential
        atmospheric refraction (when necessary), optionally apply flux
        calibration and telluric correction (if the necessary input data was
        given), and resample the data from all exposures into a datacube. Use
        the cube to detect objects which are then matched to their reference
        positions from which a two-dimensional WCS solution is computed.

        There are two pattern matching algorithm implemented, which can be
        selected by chosing a positive or zero value of faccuracy.

        In the first method (with a positive value of faccuracy), start using
        the search radius, and iteratively decrease it, until no duplicate
        detections are identified any more.  Similarly, iterate the data
        accuracy (decrease it downwards from the mean positioning error) until
        matches are found.  Remove the remaining unidentified objects.

        The second method (when faccuracy is set to zero), iterates through all
        quadruples in both the detected objects and the catalogue, calculates
        the transformation and checks whether more than 80% of the detections
        match a catalog entry within the radius.

        The main output is the ASTROMETRY_WCS file which is a bare FITS header
        containing the world coordinate solution.
        The secondary product is DATACUBE_ASTROMETRY, it is not needed for
        further processing but can be used for verification and debugging. It
        contains the reconstructed cube and two images created from it in
        further FITS extensions: a white-light image and the special image
        created from the central planes of the cube used to detect and centroid
        the stars (as well as its variance).
      
 */
/*----------------------------------------------------------------------------*/
/**@{*/

/*----------------------------------------------------------------------------*
 *                         Static variables                                   *
 *----------------------------------------------------------------------------*/
static const char *muse_astrometry_help =
  "Merge pixel tables from all IFUs, apply correction for differential atmospheric refraction (when necessary), optionally apply flux calibration and telluric correction (if the necessary input data was given), and resample the data from all exposures into a datacube. Use the cube to detect objects which are then matched to their reference positions from which a two-dimensional WCS solution is computed. There are two pattern matching algorithm implemented, which can be selected by chosing a positive or zero value of faccuracy. In the first method (with a positive value of faccuracy), start using the search radius, and iteratively decrease it, until no duplicate detections are identified any more. Similarly, iterate the data accuracy (decrease it downwards from the mean positioning error) until matches are found. Remove the remaining unidentified objects. The second method (when faccuracy is set to zero), iterates through all quadruples in both the detected objects and the catalogue, calculates the transformation and checks whether more than 80% of the detections match a catalog entry within the radius. The main output is the ASTROMETRY_WCS file which is a bare FITS header containing the world coordinate solution. The secondary product is DATACUBE_ASTROMETRY, it is not needed for further processing but can be used for verification and debugging. It contains the reconstructed cube and two images created from it in further FITS extensions: a white-light image and the special image created from the central planes of the cube used to detect and centroid the stars (as well as its variance).";

static const char *muse_astrometry_help_esorex =
  "\n\nInput frames for raw frame tag \"PIXTABLE_ASTROMETRY\":\n"
  "\n Frame tag            Type Req #Fr Description"
  "\n -------------------- ---- --- --- ------------"
  "\n PIXTABLE_ASTROMETRY  raw   Y      Pixel table of an astrometric field"
  "\n ASTROMETRY_REFERENCE calib Y    1 Reference table of known objects for astrometry"
  "\n EXTINCT_TABLE        calib .    1 Atmospheric extinction table"
  "\n STD_RESPONSE         calib .    1 Response curve as derived from standard star(s)"
  "\n STD_TELLURIC         calib .    1 Telluric absorption as derived from standard star(s)"
  "\n\nProduct frames for raw frame tag \"PIXTABLE_ASTROMETRY\":\n"
  "\n Frame tag            Level    Description"
  "\n -------------------- -------- ------------"
  "\n DATACUBE_ASTROMETRY  final    Reduced astrometry field exposure"
  "\n ASTROMETRY_WCS       final    Astrometric solution";

/*----------------------------------------------------------------------------*/
/**
  @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_astrometry_new_recipeconfig(void)
{
  cpl_recipeconfig *recipeconfig = cpl_recipeconfig_new();
      
  cpl_recipeconfig_set_tag(recipeconfig, "PIXTABLE_ASTROMETRY", 1, -1);
  cpl_recipeconfig_set_input(recipeconfig, "PIXTABLE_ASTROMETRY", "ASTROMETRY_REFERENCE", 1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "PIXTABLE_ASTROMETRY", "EXTINCT_TABLE", -1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "PIXTABLE_ASTROMETRY", "STD_RESPONSE", -1, 1);
  cpl_recipeconfig_set_input(recipeconfig, "PIXTABLE_ASTROMETRY", "STD_TELLURIC", -1, 1);
  cpl_recipeconfig_set_output(recipeconfig, "PIXTABLE_ASTROMETRY", "DATACUBE_ASTROMETRY");
  cpl_recipeconfig_set_output(recipeconfig, "PIXTABLE_ASTROMETRY", "ASTROMETRY_WCS");
    
  return recipeconfig;
} /* muse_astrometry_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_astrometry_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_ASTROMETRY")) {
    muse_processing_prepare_property(aHeader, "ESO QC ASTRO NDET",
                                     CPL_TYPE_INT,
                                     "Number of detected sources in output cube.");
    muse_processing_prepare_property(aHeader, "ESO QC ASTRO LAMBDA",
                                     CPL_TYPE_FLOAT,
                                     "[Angstrom] Wavelength of plane in combined cube that was used for object detection.");
    muse_processing_prepare_property(aHeader, "ESO QC ASTRO 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 ASTRO 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 ASTRO 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 ASTRO 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 ASTRO FWHM NVALID",
                                     CPL_TYPE_INT,
                                     "Number of detected sources with valid FWHM in output cube.");
    muse_processing_prepare_property(aHeader, "ESO QC ASTRO 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 ASTRO 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, "ASTROMETRY_WCS")) {
    muse_processing_prepare_property(aHeader, "ESO QC ASTRO NSTARS",
                                     CPL_TYPE_INT,
                                     "Number of stars identified for the astrometric solution");
    muse_processing_prepare_property(aHeader, "ESO QC ASTRO SCALE X",
                                     CPL_TYPE_FLOAT,
                                     "[arcsec] Computed scale in x-direction");
    muse_processing_prepare_property(aHeader, "ESO QC ASTRO SCALE Y",
                                     CPL_TYPE_FLOAT,
                                     "[arcsec] Computed scale in y-direction");
    muse_processing_prepare_property(aHeader, "ESO QC ASTRO ANGLE X",
                                     CPL_TYPE_FLOAT,
                                     "[deg] Computed angle in x-direction");
    muse_processing_prepare_property(aHeader, "ESO QC ASTRO ANGLE Y",
                                     CPL_TYPE_FLOAT,
                                     "[deg] Computed angle in y-direction");
    muse_processing_prepare_property(aHeader, "ESO QC ASTRO MEDRES X",
                                     CPL_TYPE_FLOAT,
                                     "[arcsec] Median residuals of astrometric fit in x-direction");
    muse_processing_prepare_property(aHeader, "ESO QC ASTRO MEDRES Y",
                                     CPL_TYPE_FLOAT,
                                     "[arcsec] Median residuals of astrometric fit in y-direction");
  } else {
    cpl_msg_warning(__func__, "Frame tag %s is not defined", aFrametag);
    return CPL_ERROR_ILLEGAL_INPUT;
  }
  return CPL_ERROR_NONE;
} /* muse_astrometry_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_astrometry_get_frame_level(const char *aFrametag)
{
  if (!aFrametag) {
    return CPL_FRAME_LEVEL_NONE;
  }
  if (!strcmp(aFrametag, "DATACUBE_ASTROMETRY")) {
    return CPL_FRAME_LEVEL_FINAL;
  }
  if (!strcmp(aFrametag, "ASTROMETRY_WCS")) {
    return CPL_FRAME_LEVEL_FINAL;
  }
  return CPL_FRAME_LEVEL_NONE;
} /* muse_astrometry_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_astrometry_get_frame_mode(const char *aFrametag)
{
  if (!aFrametag) {
    return MUSE_FRAME_MODE_ALL;
  }
  if (!strcmp(aFrametag, "DATACUBE_ASTROMETRY")) {
    return MUSE_FRAME_MODE_DATEOBS;
  }
  if (!strcmp(aFrametag, "ASTROMETRY_WCS")) {
    return MUSE_FRAME_MODE_DATEOBS;
  }
  return MUSE_FRAME_MODE_ALL;
} /* muse_astrometry_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_astrometry_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_astrometry_new_recipeconfig(),
                               muse_astrometry_prepare_header,
                               muse_astrometry_get_frame_level,
                               muse_astrometry_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;
      
  /* --centroid: Centroiding method to use for objects in the field of view. "gaussian" and "moffat" use 2D fits to derive the centroid, "box" is a simple centroid in a square box. */
  p = cpl_parameter_new_enum("muse.muse_astrometry.centroid",
                             CPL_TYPE_STRING,
                             "Centroiding method to use for objects in the field of view. \"gaussian\" and \"moffat\" use 2D fits to derive the centroid, \"box\" is a simple centroid in a square box.",
                             "muse.muse_astrometry",
                             (const char *)"moffat",
                             3,
                             (const char *)"gaussian",
                             (const char *)"moffat",
                             (const char *)"box");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "centroid");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "centroid");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --detsigma: Source detection sigma level to use. If this is negative, values between its absolute and 1.0 are tested with a stepsize of 0.1, to find an optimal solution. */
  p = cpl_parameter_new_value("muse.muse_astrometry.detsigma",
                              CPL_TYPE_DOUBLE,
                             "Source detection sigma level to use. If this is negative, values between its absolute and 1.0 are tested with a stepsize of 0.1, to find an optimal solution.",
                              "muse.muse_astrometry",
                              (double)1.5);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "detsigma");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "detsigma");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --radius: Initial radius in pixels for pattern matching identification in the astrometric field. */
  p = cpl_parameter_new_value("muse.muse_astrometry.radius",
                              CPL_TYPE_DOUBLE,
                             "Initial radius in pixels for pattern matching identification in the astrometric field.",
                              "muse.muse_astrometry",
                              (double)3.);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "radius");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "radius");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --faccuracy: Factor of initial accuracy relative to mean positional accuracy of the measured positions to use for pattern matching. If this is set to zero, use the quadruples based method. */
  p = cpl_parameter_new_value("muse.muse_astrometry.faccuracy",
                              CPL_TYPE_DOUBLE,
                             "Factor of initial accuracy relative to mean positional accuracy of the measured positions to use for pattern matching. If this is set to zero, use the quadruples based method.",
                              "muse.muse_astrometry",
                              (double)0.);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "faccuracy");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "faccuracy");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --niter: Number of iterations of the astrometric fit. */
  p = cpl_parameter_new_value("muse.muse_astrometry.niter",
                              CPL_TYPE_INT,
                             "Number of iterations of the astrometric fit.",
                              "muse.muse_astrometry",
                              (int)2);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "niter");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "niter");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --rejsigma: Rejection sigma level of the astrometric fit. */
  p = cpl_parameter_new_value("muse.muse_astrometry.rejsigma",
                              CPL_TYPE_DOUBLE,
                             "Rejection sigma level of the astrometric fit.",
                              "muse.muse_astrometry",
                              (double)3.);
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "rejsigma");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "rejsigma");

  cpl_parameterlist_append(recipe->parameters, p);
      
  /* --rotcenter: Center of rotation of the instrument, given as two comma-separated floating point values in pixels. */
  p = cpl_parameter_new_value("muse.muse_astrometry.rotcenter",
                              CPL_TYPE_STRING,
                             "Center of rotation of the instrument, given as two comma-separated floating point values in pixels.",
                              "muse.muse_astrometry",
                              (const char *)"-0.01,-1.20");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CFG, "rotcenter");
  cpl_parameter_set_alias(p, CPL_PARAMETER_MODE_CLI, "rotcenter");

  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_astrometry.lambdamin",
                              CPL_TYPE_DOUBLE,
                             "Cut off the data below this wavelength after loading the pixel table(s).",
                              "muse.muse_astrometry",
                              (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_astrometry.lambdamax",
                              CPL_TYPE_DOUBLE,
                             "Cut off the data above this wavelength after loading the pixel table(s).",
                              "muse.muse_astrometry",
                              (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_astrometry.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_astrometry",
                              (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_astrometry.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_astrometry",
                             (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);
    
  return 0;
} /* muse_astrometry_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_astrometry_params_fill(muse_astrometry_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_astrometry.centroid");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->centroid_s = cpl_parameter_get_string(p);
  aParams->centroid =
    (!strcasecmp(aParams->centroid_s, "gaussian")) ? MUSE_ASTROMETRY_PARAM_CENTROID_GAUSSIAN :
    (!strcasecmp(aParams->centroid_s, "moffat")) ? MUSE_ASTROMETRY_PARAM_CENTROID_MOFFAT :
    (!strcasecmp(aParams->centroid_s, "box")) ? MUSE_ASTROMETRY_PARAM_CENTROID_BOX :
      MUSE_ASTROMETRY_PARAM_CENTROID_INVALID_VALUE;
  cpl_ensure_code(aParams->centroid != MUSE_ASTROMETRY_PARAM_CENTROID_INVALID_VALUE,
                  CPL_ERROR_ILLEGAL_INPUT);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_astrometry.detsigma");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->detsigma = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_astrometry.radius");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->radius = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_astrometry.faccuracy");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->faccuracy = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_astrometry.niter");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->niter = cpl_parameter_get_int(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_astrometry.rejsigma");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->rejsigma = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_astrometry.rotcenter");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->rotcenter = cpl_parameter_get_string(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_astrometry.lambdamin");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->lambdamin = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_astrometry.lambdamax");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->lambdamax = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_astrometry.lambdaref");
  cpl_ensure_code(p, CPL_ERROR_DATA_NOT_FOUND);
  aParams->lambdaref = cpl_parameter_get_double(p);
      
  p = cpl_parameterlist_find(aParameters, "muse.muse_astrometry.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_ASTROMETRY_PARAM_DARCHECK_NONE :
    (!strcasecmp(aParams->darcheck_s, "check")) ? MUSE_ASTROMETRY_PARAM_DARCHECK_CHECK :
    (!strcasecmp(aParams->darcheck_s, "correct")) ? MUSE_ASTROMETRY_PARAM_DARCHECK_CORRECT :
      MUSE_ASTROMETRY_PARAM_DARCHECK_INVALID_VALUE;
  cpl_ensure_code(aParams->darcheck != MUSE_ASTROMETRY_PARAM_DARCHECK_INVALID_VALUE,
                  CPL_ERROR_ILLEGAL_INPUT);
    
  return 0;
} /* muse_astrometry_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_astrometry_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_astrometry_params_t params;
  muse_astrometry_params_fill(&params, recipe->parameters);

  cpl_errorstate prestate = cpl_errorstate_get();

  muse_processing *proc = muse_processing_new("muse_astrometry",
                                              recipe);
  int rc = muse_astrometry_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_astrometry_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_astrometry_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_astrometry_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_astrometry_help,
                           muse_astrometry_help_esorex);
  } else {
    helptext = cpl_sprintf("%s", muse_astrometry_help);
  }

  /* Initialize the CPL plugin stuff for this module */
  cpl_plugin_init(plugin, CPL_PLUGIN_API, MUSE_BINARY_VERSION,
                  CPL_PLUGIN_TYPE_RECIPE,
                  "muse_astrometry",
                  "Compute an astrometric solution.",
                  helptext,
                  "Peter Weilbacher",
                  "usd-help@eso.org",
                  muse_get_license(),
                  muse_astrometry_create,
                  muse_astrometry_exec,
                  muse_astrometry_destroy);
  cpl_pluginlist_append(aList, plugin);
  cpl_free(helptext);

  return 0;
} /* cpl_plugin_get_info() */

/**@}*/